From 1d46a3465433380089f56ebf8f9cc26267eb58d7 Mon Sep 17 00:00:00 2001 From: ben-fornefeld Date: Tue, 6 Jan 2026 15:34:24 +0100 Subject: [PATCH 01/39] wip: sdk reference generation workflow --- .github/workflows/sdk-reference-sync.yml | 130 +++++ .gitignore | 2 + docs.json | 77 ++- package.json | 18 + pnpm-lock.yaml | 461 ++++++++++++++++++ requirements.txt | 4 + scripts/configs/typedoc-theme.js | 63 +++ scripts/configs/typedoc.json | 35 ++ scripts/generate-mcp-servers.sh | 0 scripts/generate-sdk-nav.js | 197 ++++++++ scripts/generate-sdk-reference.sh | 133 +++++ scripts/merge-sdk-nav.js | 74 +++ scripts/sdk-generators/cli.sh | 97 ++++ .../sdk-generators/code-interpreter-js-sdk.sh | 129 +++++ .../code-interpreter-python-sdk.sh | 110 +++++ scripts/sdk-generators/desktop-js-sdk.sh | 130 +++++ scripts/sdk-generators/desktop-python-sdk.sh | 110 +++++ scripts/sdk-generators/js-sdk.sh | 123 +++++ scripts/sdk-generators/python-sdk.sh | 114 +++++ 19 files changed, 2003 insertions(+), 4 deletions(-) create mode 100644 .github/workflows/sdk-reference-sync.yml create mode 100644 package.json create mode 100644 pnpm-lock.yaml create mode 100644 requirements.txt create mode 100644 scripts/configs/typedoc-theme.js create mode 100644 scripts/configs/typedoc.json mode change 100644 => 100755 scripts/generate-mcp-servers.sh create mode 100644 scripts/generate-sdk-nav.js create mode 100755 scripts/generate-sdk-reference.sh create mode 100644 scripts/merge-sdk-nav.js create mode 100755 scripts/sdk-generators/cli.sh create mode 100755 scripts/sdk-generators/code-interpreter-js-sdk.sh create mode 100755 scripts/sdk-generators/code-interpreter-python-sdk.sh create mode 100755 scripts/sdk-generators/desktop-js-sdk.sh create mode 100755 scripts/sdk-generators/desktop-python-sdk.sh create mode 100755 scripts/sdk-generators/js-sdk.sh create mode 100755 scripts/sdk-generators/python-sdk.sh diff --git a/.github/workflows/sdk-reference-sync.yml b/.github/workflows/sdk-reference-sync.yml new file mode 100644 index 0000000..45d5d01 --- /dev/null +++ b/.github/workflows/sdk-reference-sync.yml @@ -0,0 +1,130 @@ +name: Sync SDK Reference Documentation + +on: + # manual trigger with inputs + workflow_dispatch: + inputs: + sdk: + description: 'SDK to generate (js-sdk, python-sdk, cli, code-interpreter-js-sdk, code-interpreter-python-sdk, desktop-js-sdk, desktop-python-sdk, all)' + required: true + default: 'all' + type: choice + options: + - all + - js-sdk + - python-sdk + - cli + - code-interpreter-js-sdk + - code-interpreter-python-sdk + - desktop-js-sdk + - desktop-python-sdk + version: + description: 'Version to generate (e.g., v2.9.0 or latest)' + required: true + default: 'latest' + type: string + + # triggered from e2b-dev/e2b repo on release + repository_dispatch: + types: [sdk-release] + +jobs: + generate: + runs-on: ubuntu-latest + permissions: + contents: write + + steps: + - name: Checkout docs repo + uses: actions/checkout@v4 + with: + fetch-depth: 0 + + - name: Setup Node.js + uses: actions/setup-node@v4 + with: + node-version: '20' + + - name: Install pnpm + uses: pnpm/action-setup@v4 + with: + version: 9 + + - name: Setup Python + uses: actions/setup-python@v5 + with: + python-version: '3.11' + + - name: Install Node dependencies + run: pnpm install + + - name: Install Python dependencies + run: pip install -r requirements.txt + + - name: Install Poetry + run: pip install poetry + + - name: Determine SDK and Version + id: params + run: | + # handle workflow_dispatch + if [[ "${{ github.event_name }}" == "workflow_dispatch" ]]; then + SDK="${{ github.event.inputs.sdk }}" + VERSION="${{ github.event.inputs.version }}" + # handle repository_dispatch from e2b repo + elif [[ "${{ github.event_name }}" == "repository_dispatch" ]]; then + SDK="${{ github.event.client_payload.sdk }}" + VERSION="${{ github.event.client_payload.version }}" + fi + + # fallback to defaults if empty + echo "sdk=${SDK:-all}" >> $GITHUB_OUTPUT + echo "version=${VERSION:-latest}" >> $GITHUB_OUTPUT + + - name: Generate SDK Reference + run: | + chmod +x scripts/generate-sdk-reference.sh + chmod +x scripts/sdk-generators/*.sh + ./scripts/generate-sdk-reference.sh \ + --sdk "${{ steps.params.outputs.sdk }}" \ + --version "${{ steps.params.outputs.version }}" + + - name: Verify generated files + run: | + echo "Generated SDK reference files:" + find docs/sdk-reference -type f -name "*.mdx" 2>/dev/null | head -20 || echo "No MDX files found" + echo "" + echo "Navigation JSON:" + cat sdk_navigation.json 2>/dev/null | head -50 || echo "No navigation file found" + + - name: Commit and push changes + run: | + git config user.name "github-actions[bot]" + git config user.email "github-actions[bot]@users.noreply.github.com" + + # stage changes + git add docs/sdk-reference/ + git add sdk_navigation.json + git add docs.json + + # commit if there are changes + if git diff --staged --quiet; then + echo "No changes to commit" + else + git commit -m "[skip ci] Update SDK reference: ${{ steps.params.outputs.sdk }} ${{ steps.params.outputs.version }}" + git push + fi + + - name: Summary + run: | + echo "## SDK Reference Generation Complete" >> $GITHUB_STEP_SUMMARY + echo "" >> $GITHUB_STEP_SUMMARY + echo "- **SDK**: ${{ steps.params.outputs.sdk }}" >> $GITHUB_STEP_SUMMARY + echo "- **Version**: ${{ steps.params.outputs.version }}" >> $GITHUB_STEP_SUMMARY + echo "" >> $GITHUB_STEP_SUMMARY + echo "### Generated Files" >> $GITHUB_STEP_SUMMARY + echo '```' >> $GITHUB_STEP_SUMMARY + find docs/sdk-reference -type f -name "*.mdx" | wc -l | xargs echo "Total MDX files:" + find docs/sdk-reference -type f -name "*.mdx" >> $GITHUB_STEP_SUMMARY || true + echo '```' >> $GITHUB_STEP_SUMMARY + diff --git a/.gitignore b/.gitignore index 090a1f0..3b21614 100644 --- a/.gitignore +++ b/.gitignore @@ -1,2 +1,4 @@ .idea .DS_Store + +node_modules \ No newline at end of file diff --git a/docs.json b/docs.json index f1410c9..17f8f36 100644 --- a/docs.json +++ b/docs.json @@ -168,18 +168,24 @@ }, { "group": "Deployment", - "pages": ["docs/byoc"] + "pages": [ + "docs/byoc" + ] }, { "group": "Migration", - "pages": ["docs/migration/v2"] + "pages": [ + "docs/migration/v2" + ] }, { "group": "Troubleshooting", "pages": [ { "group": "SDKs", - "pages": ["docs/troubleshooting/sdks/workers-edge-runtime"] + "pages": [ + "docs/troubleshooting/sdks/workers-edge-runtime" + ] }, { "group": "Templates", @@ -195,7 +201,70 @@ { "anchor": "SDK Reference", "icon": "brackets-curly", - "href": "https://e2b.dev/docs/sdk-reference" + "dropdowns": [ + { + "dropdown": "CLI", + "icon": "terminal", + "versions": [ + { + "version": "v2.2.0@latest", + "groups": [ + { + "group": "CLI v2.2.0", + "pages": [ + "docs/sdk-reference/cli/v2.2.0/auth", + "docs/sdk-reference/cli/v2.2.0/sandbox", + "docs/sdk-reference/cli/v2.2.0/template" + ] + } + ] + } + ] + }, + { + "dropdown": "JavaScript SDK", + "icon": "square-js", + "versions": [ + { + "version": "v2.9.0@latest", + "groups": [ + { + "group": "JavaScript SDK v2.9.0", + "pages": [ + "docs/sdk-reference/js-sdk/v2.9.0/commands", + "docs/sdk-reference/js-sdk/v2.9.0/errors", + "docs/sdk-reference/js-sdk/v2.9.0/filesystem", + "docs/sdk-reference/js-sdk/v2.9.0/sandbox", + "docs/sdk-reference/js-sdk/v2.9.0/template" + ] + } + ] + } + ] + }, + { + "dropdown": "Python SDK", + "icon": "python", + "versions": [ + { + "version": "v2.9.0@latest", + "groups": [ + { + "group": "Python SDK v2.9.0", + "pages": [ + "docs/sdk-reference/python-sdk/v2.9.0/exceptions", + "docs/sdk-reference/python-sdk/v2.9.0/sandbox_async", + "docs/sdk-reference/python-sdk/v2.9.0/sandbox_sync", + "docs/sdk-reference/python-sdk/v2.9.0/template", + "docs/sdk-reference/python-sdk/v2.9.0/template_async", + "docs/sdk-reference/python-sdk/v2.9.0/template_sync" + ] + } + ] + } + ] + } + ] } ], "global": {} diff --git a/package.json b/package.json new file mode 100644 index 0000000..ac01fff --- /dev/null +++ b/package.json @@ -0,0 +1,18 @@ +{ + "name": "e2b-docs", + "version": "1.0.0", + "private": true, + "description": "E2B Documentation - SDK Reference Generator", + "scripts": { + "generate-sdk-ref": "bash scripts/generate-sdk-reference.sh", + "generate-sdk-nav": "node scripts/generate-sdk-nav.js", + "merge-sdk-nav": "node scripts/merge-sdk-nav.js", + "generate-all": "pnpm run generate-sdk-ref -- --all" + }, + "devDependencies": { + "typedoc": "0.26.8", + "typedoc-plugin-markdown": "4.2.7", + "semver": "^7.7.2" + } +} + diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml new file mode 100644 index 0000000..2715af0 --- /dev/null +++ b/pnpm-lock.yaml @@ -0,0 +1,461 @@ +lockfileVersion: '9.0' + +settings: + autoInstallPeers: true + excludeLinksFromLockfile: false + +importers: + + .: + devDependencies: + semver: + specifier: ^7.7.2 + version: 7.7.3 + typedoc: + specifier: 0.26.8 + version: 0.26.8(typescript@5.6.3) + typedoc-plugin-markdown: + specifier: 4.2.7 + version: 4.2.7(typedoc@0.26.8(typescript@5.6.3)) + +packages: + + '@shikijs/core@1.29.2': + resolution: {integrity: sha512-vju0lY9r27jJfOY4Z7+Rt/nIOjzJpZ3y+nYpqtUZInVoXQ/TJZcfGnNOGnKjFdVZb8qexiCuSlZRKcGfhhTTZQ==} + + '@shikijs/engine-javascript@1.29.2': + resolution: {integrity: sha512-iNEZv4IrLYPv64Q6k7EPpOCE/nuvGiKl7zxdq0WFuRPF5PAE9PRo2JGq/d8crLusM59BRemJ4eOqrFrC4wiQ+A==} + + '@shikijs/engine-oniguruma@1.29.2': + resolution: {integrity: sha512-7iiOx3SG8+g1MnlzZVDYiaeHe7Ez2Kf2HrJzdmGwkRisT7r4rak0e655AcM/tF9JG/kg5fMNYlLLKglbN7gBqA==} + + '@shikijs/langs@1.29.2': + resolution: {integrity: sha512-FIBA7N3LZ+223U7cJDUYd5shmciFQlYkFXlkKVaHsCPgfVLiO+e12FmQE6Tf9vuyEsFe3dIl8qGWKXgEHL9wmQ==} + + '@shikijs/themes@1.29.2': + resolution: {integrity: sha512-i9TNZlsq4uoyqSbluIcZkmPL9Bfi3djVxRnofUHwvx/h6SRW3cwgBC5SML7vsDcWyukY0eCzVN980rqP6qNl9g==} + + '@shikijs/types@1.29.2': + resolution: {integrity: sha512-VJjK0eIijTZf0QSTODEXCqinjBn0joAHQ+aPSBzrv4O2d/QSbsMw+ZeSRx03kV34Hy7NzUvV/7NqfYGRLrASmw==} + + '@shikijs/vscode-textmate@10.0.2': + resolution: {integrity: sha512-83yeghZ2xxin3Nj8z1NMd/NCuca+gsYXswywDy5bHvwlWL8tpTQmzGeUuHd9FC3E/SBEMvzJRwWEOz5gGes9Qg==} + + '@types/hast@3.0.4': + resolution: {integrity: sha512-WPs+bbQw5aCj+x6laNGWLH3wviHtoCv/P3+otBhbOhJgG8qtpdAMlTCxLtsTWA7LH1Oh/bFCHsBn0TPS5m30EQ==} + + '@types/mdast@4.0.4': + resolution: {integrity: sha512-kGaNbPh1k7AFzgpud/gMdvIm5xuECykRR+JnWKQno9TAXVa6WIVCGTPvYGekIDL4uwCZQSYbUxNBSb1aUo79oA==} + + '@types/unist@3.0.3': + resolution: {integrity: sha512-ko/gIFJRv177XgZsZcBwnqJN5x/Gien8qNOn0D5bQU/zAzVf9Zt3BlcUiLqhV9y4ARk0GbT3tnUiPNgnTXzc/Q==} + + '@ungap/structured-clone@1.3.0': + resolution: {integrity: sha512-WmoN8qaIAo7WTYWbAZuG8PYEhn5fkz7dZrqTBZ7dtt//lL2Gwms1IcnQ5yHqjDfX8Ft5j4YzDM23f87zBfDe9g==} + + argparse@2.0.1: + resolution: {integrity: sha512-8+9WqebbFzpX9OR+Wa6O29asIogeRMzcGtAINdpMHHyAg10f05aSFVBbcEqGf/PXw1EjAZ+q2/bEBg3DvurK3Q==} + + balanced-match@1.0.2: + resolution: {integrity: sha512-3oSeUO0TMV67hN1AmbXsK4yaqU7tjiHlbxRDZOpH0KW9+CeX4bRAaX0Anxt0tx2MrpRpWwQaPwIlISEJhYU5Pw==} + + brace-expansion@2.0.2: + resolution: {integrity: sha512-Jt0vHyM+jmUBqojB7E1NIYadt0vI0Qxjxd2TErW94wDz+E2LAm5vKMXXwg6ZZBTHPuUlDgQHKXvjGBdfcF1ZDQ==} + + ccount@2.0.1: + resolution: {integrity: sha512-eyrF0jiFpY+3drT6383f1qhkbGsLSifNAjA61IUjZjmLCWjItY6LB9ft9YhoDgwfmclB2zhu51Lc7+95b8NRAg==} + + character-entities-html4@2.1.0: + resolution: {integrity: sha512-1v7fgQRj6hnSwFpq1Eu0ynr/CDEw0rXo2B61qXrLNdHZmPKgb7fqS1a2JwF0rISo9q77jDI8VMEHoApn8qDoZA==} + + character-entities-legacy@3.0.0: + resolution: {integrity: sha512-RpPp0asT/6ufRm//AJVwpViZbGM/MkjQFxJccQRHmISF/22NBtsHqAWmL+/pmkPWoIUJdWyeVleTl1wydHATVQ==} + + comma-separated-tokens@2.0.3: + resolution: {integrity: sha512-Fu4hJdvzeylCfQPp9SGWidpzrMs7tTrlu6Vb8XGaRGck8QSNZJJp538Wrb60Lax4fPwR64ViY468OIUTbRlGZg==} + + dequal@2.0.3: + resolution: {integrity: sha512-0je+qPKHEMohvfRTCEo3CrPG6cAzAYgmzKyxRiYSSDkS6eGJdyVJm7WaYA5ECaAD9wLB2T4EEeymA5aFVcYXCA==} + engines: {node: '>=6'} + + devlop@1.1.0: + resolution: {integrity: sha512-RWmIqhcFf1lRYBvNmr7qTNuyCt/7/ns2jbpp1+PalgE/rDQcBT0fioSMUpJ93irlUhC5hrg4cYqe6U+0ImW0rA==} + + emoji-regex-xs@1.0.0: + resolution: {integrity: sha512-LRlerrMYoIDrT6jgpeZ2YYl/L8EulRTt5hQcYjy5AInh7HWXKimpqx68aknBFpGL2+/IcogTcaydJEgaTmOpDg==} + + entities@4.5.0: + resolution: {integrity: sha512-V0hjH4dGPh9Ao5p0MoRY6BVqtwCjhz6vI5LT8AJ55H+4g9/4vbHx1I54fS0XuclLhDHArPQCiMjDxjaL8fPxhw==} + engines: {node: '>=0.12'} + + hast-util-to-html@9.0.5: + resolution: {integrity: sha512-OguPdidb+fbHQSU4Q4ZiLKnzWo8Wwsf5bZfbvu7//a9oTYoqD/fWpe96NuHkoS9h0ccGOTe0C4NGXdtS0iObOw==} + + hast-util-whitespace@3.0.0: + resolution: {integrity: sha512-88JUN06ipLwsnv+dVn+OIYOvAuvBMy/Qoi6O7mQHxdPXpjy+Cd6xRkWwux7DKO+4sYILtLBRIKgsdpS2gQc7qw==} + + html-void-elements@3.0.0: + resolution: {integrity: sha512-bEqo66MRXsUGxWHV5IP0PUiAWwoEjba4VCzg0LjFJBpchPaTfyfCKTG6bc5F8ucKec3q5y6qOdGyYTSBEvhCrg==} + + linkify-it@5.0.0: + resolution: {integrity: sha512-5aHCbzQRADcdP+ATqnDuhhJ/MRIqDkZX5pyjFHRRysS8vZ5AbqGEoFIb6pYHPZ+L/OC2Lc+xT8uHVVR5CAK/wQ==} + + lunr@2.3.9: + resolution: {integrity: sha512-zTU3DaZaF3Rt9rhN3uBMGQD3dD2/vFQqnvZCDv4dl5iOzq2IZQqTxu90r4E5J+nP70J3ilqVCrbho2eWaeW8Ow==} + + markdown-it@14.1.0: + resolution: {integrity: sha512-a54IwgWPaeBCAAsv13YgmALOF1elABB08FxO9i+r4VFk5Vl4pKokRPeX8u5TCgSsPi6ec1otfLjdOpVcgbpshg==} + hasBin: true + + mdast-util-to-hast@13.2.1: + resolution: {integrity: sha512-cctsq2wp5vTsLIcaymblUriiTcZd0CwWtCbLvrOzYCDZoWyMNV8sZ7krj09FSnsiJi3WVsHLM4k6Dq/yaPyCXA==} + + mdurl@2.0.0: + resolution: {integrity: sha512-Lf+9+2r+Tdp5wXDXC4PcIBjTDtq4UKjCPMQhKIuzpJNW0b96kVqSwW0bT7FhRSfmAiFYgP+SCRvdrDozfh0U5w==} + + micromark-util-character@2.1.1: + resolution: {integrity: sha512-wv8tdUTJ3thSFFFJKtpYKOYiGP2+v96Hvk4Tu8KpCAsTMs6yi+nVmGh1syvSCsaxz45J6Jbw+9DD6g97+NV67Q==} + + micromark-util-encode@2.0.1: + resolution: {integrity: sha512-c3cVx2y4KqUnwopcO9b/SCdo2O67LwJJ/UyqGfbigahfegL9myoEFoDYZgkT7f36T0bLrM9hZTAaAyH+PCAXjw==} + + micromark-util-sanitize-uri@2.0.1: + resolution: {integrity: sha512-9N9IomZ/YuGGZZmQec1MbgxtlgougxTodVwDzzEouPKo3qFWvymFHWcnDi2vzV1ff6kas9ucW+o3yzJK9YB1AQ==} + + micromark-util-symbol@2.0.1: + resolution: {integrity: sha512-vs5t8Apaud9N28kgCrRUdEed4UJ+wWNvicHLPxCa9ENlYuAY31M0ETy5y1vA33YoNPDFTghEbnh6efaE8h4x0Q==} + + micromark-util-types@2.0.2: + resolution: {integrity: sha512-Yw0ECSpJoViF1qTU4DC6NwtC4aWGt1EkzaQB8KPPyCRR8z9TWeV0HbEFGTO+ZY1wB22zmxnJqhPyTpOVCpeHTA==} + + minimatch@9.0.5: + resolution: {integrity: sha512-G6T0ZX48xgozx7587koeX9Ys2NYy6Gmv//P89sEte9V9whIapMNF4idKxnW2QtCcLiTWlb/wfCabAtAFWhhBow==} + engines: {node: '>=16 || 14 >=14.17'} + + oniguruma-to-es@2.3.0: + resolution: {integrity: sha512-bwALDxriqfKGfUufKGGepCzu9x7nJQuoRoAFp4AnwehhC2crqrDIAP/uN2qdlsAvSMpeRC3+Yzhqc7hLmle5+g==} + + property-information@7.1.0: + resolution: {integrity: sha512-TwEZ+X+yCJmYfL7TPUOcvBZ4QfoT5YenQiJuX//0th53DE6w0xxLEtfK3iyryQFddXuvkIk51EEgrJQ0WJkOmQ==} + + punycode.js@2.3.1: + resolution: {integrity: sha512-uxFIHU0YlHYhDQtV4R9J6a52SLx28BCjT+4ieh7IGbgwVJWO+km431c4yRlREUAsAmt/uMjQUyQHNEPf0M39CA==} + engines: {node: '>=6'} + + regex-recursion@5.1.1: + resolution: {integrity: sha512-ae7SBCbzVNrIjgSbh7wMznPcQel1DNlDtzensnFxpiNpXt1U2ju/bHugH422r+4LAVS1FpW1YCwilmnNsjum9w==} + + regex-utilities@2.3.0: + resolution: {integrity: sha512-8VhliFJAWRaUiVvREIiW2NXXTmHs4vMNnSzuJVhscgmGav3g9VDxLrQndI3dZZVVdp0ZO/5v0xmX516/7M9cng==} + + regex@5.1.1: + resolution: {integrity: sha512-dN5I359AVGPnwzJm2jN1k0W9LPZ+ePvoOeVMMfqIMFz53sSwXkxaJoxr50ptnsC771lK95BnTrVSZxq0b9yCGw==} + + semver@7.7.3: + resolution: {integrity: sha512-SdsKMrI9TdgjdweUSR9MweHA4EJ8YxHn8DFaDisvhVlUOe4BF1tLD7GAj0lIqWVl+dPb/rExr0Btby5loQm20Q==} + engines: {node: '>=10'} + hasBin: true + + shiki@1.29.2: + resolution: {integrity: sha512-njXuliz/cP+67jU2hukkxCNuH1yUi4QfdZZY+sMr5PPrIyXSu5iTb/qYC4BiWWB0vZ+7TbdvYUCeL23zpwCfbg==} + + space-separated-tokens@2.0.2: + resolution: {integrity: sha512-PEGlAwrG8yXGXRjW32fGbg66JAlOAwbObuqVoJpv/mRgoWDQfgH1wDPvtzWyUSNAXBGSk8h755YDbbcEy3SH2Q==} + + stringify-entities@4.0.4: + resolution: {integrity: sha512-IwfBptatlO+QCJUo19AqvrPNqlVMpW9YEL2LIVY+Rpv2qsjCGxaDLNRgeGsQWJhfItebuJhsGSLjaBbNSQ+ieg==} + + trim-lines@3.0.1: + resolution: {integrity: sha512-kRj8B+YHZCc9kQYdWfJB2/oUl9rA99qbowYYBtr4ui4mZyAQ2JpvVBd/6U2YloATfqBhBTSMhTpgBHtU0Mf3Rg==} + + typedoc-plugin-markdown@4.2.7: + resolution: {integrity: sha512-bLsQdweSm48P9j6kGqQ3/4GCH5zu2EnURSkkxqirNc+uVFE9YK825ogDw+WbNkRHIV6eZK/1U43gT7YfglyYOg==} + engines: {node: '>= 18'} + peerDependencies: + typedoc: 0.26.x + + typedoc@0.26.8: + resolution: {integrity: sha512-QBF0BMbnNeUc6U7pRHY7Jb8pjhmiNWZNQT8LU6uk9qP9t3goP9bJptdlNqMC0wBB2w9sQrxjZt835bpRSSq1LA==} + engines: {node: '>= 18'} + hasBin: true + peerDependencies: + typescript: 4.6.x || 4.7.x || 4.8.x || 4.9.x || 5.0.x || 5.1.x || 5.2.x || 5.3.x || 5.4.x || 5.5.x || 5.6.x + + typescript@5.6.3: + resolution: {integrity: sha512-hjcS1mhfuyi4WW8IWtjP7brDrG2cuDZukyrYrSauoXGNgx0S7zceP07adYkJycEr56BOUTNPzbInooiN3fn1qw==} + engines: {node: '>=14.17'} + hasBin: true + + uc.micro@2.1.0: + resolution: {integrity: sha512-ARDJmphmdvUk6Glw7y9DQ2bFkKBHwQHLi2lsaH6PPmz/Ka9sFOBsBluozhDltWmnv9u/cF6Rt87znRTPV+yp/A==} + + unist-util-is@6.0.1: + resolution: {integrity: sha512-LsiILbtBETkDz8I9p1dQ0uyRUWuaQzd/cuEeS1hoRSyW5E5XGmTzlwY1OrNzzakGowI9Dr/I8HVaw4hTtnxy8g==} + + unist-util-position@5.0.0: + resolution: {integrity: sha512-fucsC7HjXvkB5R3kTCO7kUjRdrS0BJt3M/FPxmHMBOm8JQi2BsHAHFsy27E0EolP8rp0NzXsJ+jNPyDWvOJZPA==} + + unist-util-stringify-position@4.0.0: + resolution: {integrity: sha512-0ASV06AAoKCDkS2+xw5RXJywruurpbC4JZSm7nr7MOt1ojAzvyyaO+UxZf18j8FCF6kmzCZKcAgN/yu2gm2XgQ==} + + unist-util-visit-parents@6.0.2: + resolution: {integrity: sha512-goh1s1TBrqSqukSc8wrjwWhL0hiJxgA8m4kFxGlQ+8FYQ3C/m11FcTs4YYem7V664AhHVvgoQLk890Ssdsr2IQ==} + + unist-util-visit@5.0.0: + resolution: {integrity: sha512-MR04uvD+07cwl/yhVuVWAtw+3GOR/knlL55Nd/wAdblk27GCVt3lqpTivy/tkJcZoNPzTwS1Y+KMojlLDhoTzg==} + + vfile-message@4.0.3: + resolution: {integrity: sha512-QTHzsGd1EhbZs4AsQ20JX1rC3cOlt/IWJruk893DfLRr57lcnOeMaWG4K0JrRta4mIJZKth2Au3mM3u03/JWKw==} + + vfile@6.0.3: + resolution: {integrity: sha512-KzIbH/9tXat2u30jf+smMwFCsno4wHVdNmzFyL+T/L3UGqqk6JKfVqOFOZEpZSHADH1k40ab6NUIXZq422ov3Q==} + + yaml@2.8.2: + resolution: {integrity: sha512-mplynKqc1C2hTVYxd0PU2xQAc22TI1vShAYGksCCfxbn/dFwnHTNi1bvYsBTkhdUNtGIf5xNOg938rrSSYvS9A==} + engines: {node: '>= 14.6'} + hasBin: true + + zwitch@2.0.4: + resolution: {integrity: sha512-bXE4cR/kVZhKZX/RjPEflHaKVhUVl85noU3v6b8apfQEc1x4A+zBxjZ4lN8LqGd6WZ3dl98pY4o717VFmoPp+A==} + +snapshots: + + '@shikijs/core@1.29.2': + dependencies: + '@shikijs/engine-javascript': 1.29.2 + '@shikijs/engine-oniguruma': 1.29.2 + '@shikijs/types': 1.29.2 + '@shikijs/vscode-textmate': 10.0.2 + '@types/hast': 3.0.4 + hast-util-to-html: 9.0.5 + + '@shikijs/engine-javascript@1.29.2': + dependencies: + '@shikijs/types': 1.29.2 + '@shikijs/vscode-textmate': 10.0.2 + oniguruma-to-es: 2.3.0 + + '@shikijs/engine-oniguruma@1.29.2': + dependencies: + '@shikijs/types': 1.29.2 + '@shikijs/vscode-textmate': 10.0.2 + + '@shikijs/langs@1.29.2': + dependencies: + '@shikijs/types': 1.29.2 + + '@shikijs/themes@1.29.2': + dependencies: + '@shikijs/types': 1.29.2 + + '@shikijs/types@1.29.2': + dependencies: + '@shikijs/vscode-textmate': 10.0.2 + '@types/hast': 3.0.4 + + '@shikijs/vscode-textmate@10.0.2': {} + + '@types/hast@3.0.4': + dependencies: + '@types/unist': 3.0.3 + + '@types/mdast@4.0.4': + dependencies: + '@types/unist': 3.0.3 + + '@types/unist@3.0.3': {} + + '@ungap/structured-clone@1.3.0': {} + + argparse@2.0.1: {} + + balanced-match@1.0.2: {} + + brace-expansion@2.0.2: + dependencies: + balanced-match: 1.0.2 + + ccount@2.0.1: {} + + character-entities-html4@2.1.0: {} + + character-entities-legacy@3.0.0: {} + + comma-separated-tokens@2.0.3: {} + + dequal@2.0.3: {} + + devlop@1.1.0: + dependencies: + dequal: 2.0.3 + + emoji-regex-xs@1.0.0: {} + + entities@4.5.0: {} + + hast-util-to-html@9.0.5: + dependencies: + '@types/hast': 3.0.4 + '@types/unist': 3.0.3 + ccount: 2.0.1 + comma-separated-tokens: 2.0.3 + hast-util-whitespace: 3.0.0 + html-void-elements: 3.0.0 + mdast-util-to-hast: 13.2.1 + property-information: 7.1.0 + space-separated-tokens: 2.0.2 + stringify-entities: 4.0.4 + zwitch: 2.0.4 + + hast-util-whitespace@3.0.0: + dependencies: + '@types/hast': 3.0.4 + + html-void-elements@3.0.0: {} + + linkify-it@5.0.0: + dependencies: + uc.micro: 2.1.0 + + lunr@2.3.9: {} + + markdown-it@14.1.0: + dependencies: + argparse: 2.0.1 + entities: 4.5.0 + linkify-it: 5.0.0 + mdurl: 2.0.0 + punycode.js: 2.3.1 + uc.micro: 2.1.0 + + mdast-util-to-hast@13.2.1: + dependencies: + '@types/hast': 3.0.4 + '@types/mdast': 4.0.4 + '@ungap/structured-clone': 1.3.0 + devlop: 1.1.0 + micromark-util-sanitize-uri: 2.0.1 + trim-lines: 3.0.1 + unist-util-position: 5.0.0 + unist-util-visit: 5.0.0 + vfile: 6.0.3 + + mdurl@2.0.0: {} + + micromark-util-character@2.1.1: + dependencies: + micromark-util-symbol: 2.0.1 + micromark-util-types: 2.0.2 + + micromark-util-encode@2.0.1: {} + + micromark-util-sanitize-uri@2.0.1: + dependencies: + micromark-util-character: 2.1.1 + micromark-util-encode: 2.0.1 + micromark-util-symbol: 2.0.1 + + micromark-util-symbol@2.0.1: {} + + micromark-util-types@2.0.2: {} + + minimatch@9.0.5: + dependencies: + brace-expansion: 2.0.2 + + oniguruma-to-es@2.3.0: + dependencies: + emoji-regex-xs: 1.0.0 + regex: 5.1.1 + regex-recursion: 5.1.1 + + property-information@7.1.0: {} + + punycode.js@2.3.1: {} + + regex-recursion@5.1.1: + dependencies: + regex: 5.1.1 + regex-utilities: 2.3.0 + + regex-utilities@2.3.0: {} + + regex@5.1.1: + dependencies: + regex-utilities: 2.3.0 + + semver@7.7.3: {} + + shiki@1.29.2: + dependencies: + '@shikijs/core': 1.29.2 + '@shikijs/engine-javascript': 1.29.2 + '@shikijs/engine-oniguruma': 1.29.2 + '@shikijs/langs': 1.29.2 + '@shikijs/themes': 1.29.2 + '@shikijs/types': 1.29.2 + '@shikijs/vscode-textmate': 10.0.2 + '@types/hast': 3.0.4 + + space-separated-tokens@2.0.2: {} + + stringify-entities@4.0.4: + dependencies: + character-entities-html4: 2.1.0 + character-entities-legacy: 3.0.0 + + trim-lines@3.0.1: {} + + typedoc-plugin-markdown@4.2.7(typedoc@0.26.8(typescript@5.6.3)): + dependencies: + typedoc: 0.26.8(typescript@5.6.3) + + typedoc@0.26.8(typescript@5.6.3): + dependencies: + lunr: 2.3.9 + markdown-it: 14.1.0 + minimatch: 9.0.5 + shiki: 1.29.2 + typescript: 5.6.3 + yaml: 2.8.2 + + typescript@5.6.3: {} + + uc.micro@2.1.0: {} + + unist-util-is@6.0.1: + dependencies: + '@types/unist': 3.0.3 + + unist-util-position@5.0.0: + dependencies: + '@types/unist': 3.0.3 + + unist-util-stringify-position@4.0.0: + dependencies: + '@types/unist': 3.0.3 + + unist-util-visit-parents@6.0.2: + dependencies: + '@types/unist': 3.0.3 + unist-util-is: 6.0.1 + + unist-util-visit@5.0.0: + dependencies: + '@types/unist': 3.0.3 + unist-util-is: 6.0.1 + unist-util-visit-parents: 6.0.2 + + vfile-message@4.0.3: + dependencies: + '@types/unist': 3.0.3 + unist-util-stringify-position: 4.0.0 + + vfile@6.0.3: + dependencies: + '@types/unist': 3.0.3 + vfile-message: 4.0.3 + + yaml@2.8.2: {} + + zwitch@2.0.4: {} diff --git a/requirements.txt b/requirements.txt new file mode 100644 index 0000000..e83d282 --- /dev/null +++ b/requirements.txt @@ -0,0 +1,4 @@ +# Python dependencies for SDK reference generation +pydoc-markdown>=4.8.2 +poetry>=1.8.0 + diff --git a/scripts/configs/typedoc-theme.js b/scripts/configs/typedoc-theme.js new file mode 100644 index 0000000..c434d84 --- /dev/null +++ b/scripts/configs/typedoc-theme.js @@ -0,0 +1,63 @@ +/** + * Custom TypeDoc markdown theme for E2B SDK reference docs. + * Cleans up generated markdown for Mintlify compatibility. + */ +const { MarkdownPageEvent } = require('typedoc-plugin-markdown') + +function load(app) { + // listen to the render event + app.renderer.on(MarkdownPageEvent.END, (page) => { + // process markdown content + page.contents = removeMarkdownLinks( + removeFirstNLines( + convertH5toH3(removeLinesWithConditions(page.contents)), + 6 + ) + ) + }) +} + +// makes methods in the sdk reference look more prominent +function convertH5toH3(text) { + return text.replace(/^##### (.*)$/gm, '### $1') +} + +// removes markdown-style links, keeps link text +function removeMarkdownLinks(text) { + return text.replace(/\[([^\]]+)\]\(([^)]+)\)/g, '$1') +} + +function removeFirstNLines(text, n) { + return text.split('\n').slice(n).join('\n') +} + +// removes "Extends", "Overrides", "Inherited from" sections +function removeLinesWithConditions(text) { + const lines = text.split('\n') + const filteredLines = [] + + for (let i = 0; i < lines.length; i++) { + if ( + lines[i].startsWith('#### Extends') || + lines[i].startsWith('###### Overrides') || + lines[i].startsWith('###### Inherited from') + ) { + // skip this line and the next three + i += 3 + continue + } + + if (lines[i].startsWith('##### new')) { + // avoid promoting constructors + i += 1 + continue + } + + filteredLines.push(convertH5toH3(lines[i])) + } + + return filteredLines.join('\n') +} + +module.exports = { load } + diff --git a/scripts/configs/typedoc.json b/scripts/configs/typedoc.json new file mode 100644 index 0000000..29c1a4b --- /dev/null +++ b/scripts/configs/typedoc.json @@ -0,0 +1,35 @@ +{ + "out": "sdk_ref", + "plugin": ["typedoc-plugin-markdown"], + "exclude": ["**/*.spec.ts"], + "entryPoints": [ + "src/sandbox/index.ts", + "src/sandbox/filesystem/index.ts", + "src/sandbox/process/index.ts", + "src/sandbox/commands/index.ts", + "src/errors.ts", + "src/template/index.ts", + "src/template/readycmd.ts", + "src/template/logger.ts" + ], + "excludeExternals": true, + "excludeInternal": true, + "excludePrivate": true, + "excludeProtected": true, + "navigation": { + "includeGroups": false, + "includeCategories": false + }, + "outputFileStrategy": "modules", + "readme": "none", + "disableSources": true, + "classPropertiesFormat": "table", + "typeDeclarationFormat": "table", + "enumMembersFormat": "table", + "parametersFormat": "table", + "expandParameters": true, + "useCodeBlocks": true, + "hidePageTitle": true, + "hideBreadcrumbs": true +} + diff --git a/scripts/generate-mcp-servers.sh b/scripts/generate-mcp-servers.sh old mode 100644 new mode 100755 diff --git a/scripts/generate-sdk-nav.js b/scripts/generate-sdk-nav.js new file mode 100644 index 0000000..3142cba --- /dev/null +++ b/scripts/generate-sdk-nav.js @@ -0,0 +1,197 @@ +#!/usr/bin/env node + +/** + * SDK Navigation Generator + * Scans the docs/sdk-reference directory and generates Mintlify-compatible navigation JSON. + */ + +const fs = require('fs'); +const path = require('path'); + +// try to use semver for sorting, fall back to basic string comparison +let semver; +try { + semver = require('semver'); +} catch { + semver = null; +} + +const SCRIPT_DIR = __dirname; +const DOCS_DIR = path.join(SCRIPT_DIR, '..'); +const SDK_REF_DIR = path.join(DOCS_DIR, 'docs', 'sdk-reference'); +const OUTPUT_FILE = path.join(DOCS_DIR, 'sdk_navigation.json'); + +// SDK configuration - maps directory names to display names and icons +const SDK_CONFIGS = { + 'cli': { + name: 'CLI', + icon: 'terminal', + order: 1 + }, + 'js-sdk': { + name: 'JavaScript SDK', + icon: 'square-js', + order: 2 + }, + 'python-sdk': { + name: 'Python SDK', + icon: 'python', + order: 3 + }, + 'code-interpreter-js-sdk': { + name: 'Code Interpreter JavaScript SDK', + icon: 'square-js', + order: 4 + }, + 'code-interpreter-python-sdk': { + name: 'Code Interpreter Python SDK', + icon: 'python', + order: 5 + }, + 'desktop-js-sdk': { + name: 'Desktop JavaScript SDK', + icon: 'square-js', + order: 6 + }, + 'desktop-python-sdk': { + name: 'Desktop Python SDK', + icon: 'python', + order: 7 + }, +}; + +/** + * Get all version directories for an SDK + */ +function getVersions(sdkDir) { + try { + const entries = fs.readdirSync(sdkDir, { withFileTypes: true }); + const versions = entries + .filter(e => e.isDirectory() && e.name.startsWith('v')) + .map(e => e.name); + + // sort versions (latest first) + if (semver) { + return versions.sort((a, b) => { + const cleanA = a.replace(/^v/, ''); + const cleanB = b.replace(/^v/, ''); + try { + return semver.rcompare(cleanA, cleanB); + } catch { + return b.localeCompare(a); + } + }); + } + + // fallback: basic string sort (won't handle semver correctly) + return versions.sort().reverse(); + } catch { + return []; + } +} + +/** + * Get all MDX modules in a version directory + */ +function getModules(versionDir) { + try { + const entries = fs.readdirSync(versionDir, { withFileTypes: true }); + return entries + .filter(e => e.isFile() && e.name.endsWith('.mdx')) + .map(e => e.name.replace('.mdx', '')) + .sort(); + } catch { + return []; + } +} + +/** + * Generate navigation structure for all SDKs + */ +function generateNavigation() { + const navigation = []; + + // check if sdk-reference directory exists + if (!fs.existsSync(SDK_REF_DIR)) { + console.log('⚠️ SDK reference directory not found:', SDK_REF_DIR); + return navigation; + } + + // process each SDK + for (const [sdkKey, config] of Object.entries(SDK_CONFIGS)) { + const sdkDir = path.join(SDK_REF_DIR, sdkKey); + + if (!fs.existsSync(sdkDir)) { + console.log(` Skipping ${sdkKey} (not found)`); + continue; + } + + const versions = getVersions(sdkDir); + if (versions.length === 0) { + console.log(` Skipping ${sdkKey} (no versions)`); + continue; + } + + console.log(` Found ${sdkKey}: ${versions.length} versions`); + + const dropdown = { + dropdown: config.name, + icon: config.icon, + versions: versions.map((version, index) => { + const versionDir = path.join(sdkDir, version); + const modules = getModules(versionDir); + + return { + // mark first version as @latest + version: index === 0 ? `${version}@latest` : version, + groups: [ + { + group: `${config.name} ${version}`, + pages: modules.map(module => + `docs/sdk-reference/${sdkKey}/${version}/${module}` + ) + } + ] + }; + }) + }; + + // store with order for sorting + navigation.push({ ...dropdown, _order: config.order }); + } + + // sort by order and remove _order field + return navigation + .sort((a, b) => a._order - b._order) + .map(({ _order, ...rest }) => rest); +} + +/** + * Main entry point + */ +function main() { + console.log('📝 Generating SDK navigation...'); + console.log(` Source: ${SDK_REF_DIR}`); + console.log(` Output: ${OUTPUT_FILE}`); + console.log(''); + + const navigation = generateNavigation(); + + // write output file + fs.writeFileSync(OUTPUT_FILE, JSON.stringify(navigation, null, 2)); + + console.log(''); + console.log(`✅ Generated ${OUTPUT_FILE}`); + console.log(` Found ${navigation.length} SDKs`); + + // summary + for (const sdk of navigation) { + const totalPages = sdk.versions.reduce((sum, v) => + sum + v.groups.reduce((s, g) => s + g.pages.length, 0), 0 + ); + console.log(` - ${sdk.dropdown}: ${sdk.versions.length} versions, ${totalPages} pages`); + } +} + +main(); + diff --git a/scripts/generate-sdk-reference.sh b/scripts/generate-sdk-reference.sh new file mode 100755 index 0000000..d28de58 --- /dev/null +++ b/scripts/generate-sdk-reference.sh @@ -0,0 +1,133 @@ +#!/usr/bin/env bash + +set -euo pipefail + +# SDK Reference Documentation Generator +# Usage: ./generate-sdk-reference.sh [--sdk ] [--version ] +# ./generate-sdk-reference.sh --all +# +# Examples: +# ./generate-sdk-reference.sh --sdk js-sdk --version v2.9.0 +# ./generate-sdk-reference.sh --sdk python-sdk --version v2.9.0 +# ./generate-sdk-reference.sh --all --version latest + +SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" +DOCS_DIR="$(cd "$SCRIPT_DIR/.." && pwd)" + +# defaults +SDK_TYPE="all" +VERSION="latest" + +# parse arguments +while [[ $# -gt 0 ]]; do + case $1 in + --sdk) + # only set if value is non-empty and not another flag + if [[ -n "${2:-}" && ! "$2" =~ ^-- ]]; then + SDK_TYPE="$2" + shift 2 + else + shift + fi + ;; + --version) + # only set if value is non-empty and not another flag + if [[ -n "${2:-}" && ! "$2" =~ ^-- ]]; then + VERSION="$2" + shift 2 + else + shift + fi + ;; + --all) + SDK_TYPE="all" + shift + ;; + *) + echo "Unknown option: $1" + exit 1 + ;; + esac +done + +# create temp directory for cloning repos +TEMP_DIR=$(mktemp -d) +trap "rm -rf $TEMP_DIR" EXIT + +echo "🚀 SDK Reference Generator" +echo " SDK: $SDK_TYPE" +echo " Version: $VERSION" +echo " Temp dir: $TEMP_DIR" +echo "" + +# helper to run individual SDK generators +run_generator() { + local sdk="$1" + local version="$2" + local generator="$SCRIPT_DIR/sdk-generators/${sdk}.sh" + + if [[ -f "$generator" ]]; then + echo "📦 Generating $sdk..." + chmod +x "$generator" + "$generator" "$version" "$TEMP_DIR" "$DOCS_DIR" + else + echo "⚠️ Generator not found: $generator" + fi +} + +case "$SDK_TYPE" in + js-sdk) + run_generator "js-sdk" "$VERSION" + ;; + python-sdk) + run_generator "python-sdk" "$VERSION" + ;; + cli) + run_generator "cli" "$VERSION" + ;; + code-interpreter-js-sdk) + run_generator "code-interpreter-js-sdk" "$VERSION" + ;; + code-interpreter-python-sdk) + run_generator "code-interpreter-python-sdk" "$VERSION" + ;; + desktop-js-sdk) + run_generator "desktop-js-sdk" "$VERSION" + ;; + desktop-python-sdk) + run_generator "desktop-python-sdk" "$VERSION" + ;; + all) + # generate all SDKs from main e2b repo + run_generator "js-sdk" "$VERSION" + run_generator "python-sdk" "$VERSION" + run_generator "cli" "$VERSION" + + # generate SDKs from external repos + run_generator "code-interpreter-js-sdk" "$VERSION" + run_generator "code-interpreter-python-sdk" "$VERSION" + run_generator "desktop-js-sdk" "$VERSION" + run_generator "desktop-python-sdk" "$VERSION" + ;; + *) + echo "❌ Unknown SDK type: $SDK_TYPE" + echo " Valid options: js-sdk, python-sdk, cli, code-interpreter-js-sdk," + echo " code-interpreter-python-sdk, desktop-js-sdk," + echo " desktop-python-sdk, all" + exit 1 + ;; +esac + +# generate navigation JSON after all SDKs are generated +echo "" +echo "📝 Generating navigation JSON..." +node "$SCRIPT_DIR/generate-sdk-nav.js" + +# merge navigation into docs.json +echo "" +echo "🔄 Merging navigation into docs.json..." +node "$SCRIPT_DIR/merge-sdk-nav.js" + +echo "" +echo "✅ SDK reference generation complete" + diff --git a/scripts/merge-sdk-nav.js b/scripts/merge-sdk-nav.js new file mode 100644 index 0000000..87bc05c --- /dev/null +++ b/scripts/merge-sdk-nav.js @@ -0,0 +1,74 @@ +#!/usr/bin/env node + +/** + * Merge SDK Navigation into docs.json + * + * This script merges the generated sdk_navigation.json into the docs.json + * Mintlify configuration. It finds the "SDK Reference" anchor and replaces + * its dropdowns with the generated navigation. + */ + +const fs = require('fs'); +const path = require('path'); + +const DOCS_DIR = path.join(__dirname, '..'); +const DOCS_JSON_PATH = path.join(DOCS_DIR, 'docs.json'); +const SDK_NAV_PATH = path.join(DOCS_DIR, 'sdk_navigation.json'); + +function main() { + console.log('🔄 Merging SDK navigation into docs.json...'); + + // read files + if (!fs.existsSync(SDK_NAV_PATH)) { + console.log('⚠️ sdk_navigation.json not found, skipping merge'); + return; + } + + const docsJson = JSON.parse(fs.readFileSync(DOCS_JSON_PATH, 'utf-8')); + const sdkNav = JSON.parse(fs.readFileSync(SDK_NAV_PATH, 'utf-8')); + + // find SDK Reference anchor + const anchors = docsJson.navigation?.anchors; + if (!anchors) { + console.error('❌ No anchors found in docs.json'); + process.exit(1); + } + + const sdkRefIndex = anchors.findIndex(a => a.anchor === 'SDK Reference'); + if (sdkRefIndex === -1) { + console.error('❌ SDK Reference anchor not found in docs.json'); + process.exit(1); + } + + // filter out empty dropdowns and update + const validDropdowns = sdkNav.filter(d => d.versions && d.versions.length > 0); + + if (validDropdowns.length === 0) { + console.log('⚠️ No SDK versions found, keeping existing docs.json'); + return; + } + + // update SDK Reference anchor with generated navigation + anchors[sdkRefIndex] = { + anchor: 'SDK Reference', + icon: 'brackets-curly', + dropdowns: validDropdowns + }; + + // write updated docs.json + fs.writeFileSync(DOCS_JSON_PATH, JSON.stringify(docsJson, null, 2) + '\n'); + + console.log(`✅ Updated docs.json with ${validDropdowns.length} SDK dropdowns`); + + // summary + for (const dropdown of validDropdowns) { + const totalVersions = dropdown.versions.length; + const totalPages = dropdown.versions.reduce((sum, v) => + sum + v.groups.reduce((s, g) => s + g.pages.length, 0), 0 + ); + console.log(` - ${dropdown.dropdown}: ${totalVersions} versions, ${totalPages} pages`); + } +} + +main(); + diff --git a/scripts/sdk-generators/cli.sh b/scripts/sdk-generators/cli.sh new file mode 100755 index 0000000..248253b --- /dev/null +++ b/scripts/sdk-generators/cli.sh @@ -0,0 +1,97 @@ +#!/usr/bin/env bash + +set -euo pipefail + +# CLI Reference Generator +# Usage: ./cli.sh + +VERSION="$1" +TEMP_DIR="$2" +DOCS_DIR="$3" + +echo " → CLI version: $VERSION" + +# determine the git tag to clone +if [[ "$VERSION" == "latest" ]]; then + # get latest CLI tag from e2b repo (format: @e2b/cli@X.Y.Z) + VERSION=$(git ls-remote --tags --refs https://github.com/e2b-dev/e2b.git | \ + grep 'refs/tags/@e2b/cli@' | \ + sed 's/.*refs\/tags\/@e2b\/cli@/v/' | \ + sort -V | tail -1) || true + + if [[ -z "$VERSION" ]]; then + echo " ❌ No CLI tags found" + exit 1 + fi + echo " → Resolved latest to: $VERSION" +fi + +# convert version to git tag format (v2.2.0 -> @e2b/cli@2.2.0) +GIT_TAG="@e2b/cli@${VERSION#v}" + +# clone e2b repo at specific version +REPO_DIR="$TEMP_DIR/e2b-cli" +if [[ ! -d "$REPO_DIR" ]]; then + echo " → Cloning e2b repo at $GIT_TAG..." + git clone --depth 1 --branch "$GIT_TAG" \ + https://github.com/e2b-dev/e2b.git \ + "$REPO_DIR" 2>/dev/null || { + echo " ⚠️ Tag $GIT_TAG not found, trying branch main..." + git clone --depth 1 \ + https://github.com/e2b-dev/e2b.git \ + "$REPO_DIR" + } +fi + +CLI_DIR="$REPO_DIR/packages/cli" +if [[ ! -d "$CLI_DIR" ]]; then + echo " ❌ Directory not found: $CLI_DIR" + echo " → Checking repo structure..." + ls -la "$REPO_DIR" || true + exit 1 +fi + +cd "$CLI_DIR" + +# install dependencies (use pnpm if available, fallback to npm) +echo " → Installing dependencies..." +if command -v pnpm &> /dev/null; then + pnpm install --ignore-scripts 2>&1 || { + echo " ⚠️ pnpm install failed, trying npm..." + npm install --legacy-peer-deps 2>&1 + } +else + npm install --legacy-peer-deps 2>&1 +fi + +# build and generate +echo " → Building CLI..." +npx tsup + +echo " → Generating documentation..." +mkdir -p sdk_ref +NODE_ENV=development node dist/index.js -cmd2md + +# process output - files should already be flat (auth.md, sandbox.md, etc.) +cd sdk_ref + +# rename .md to .mdx +for file in *.md; do + if [[ -f "$file" ]]; then + mv "$file" "${file%.md}.mdx" + fi +done + +# copy to docs repo +TARGET_DIR="$DOCS_DIR/docs/sdk-reference/cli/$VERSION" +mkdir -p "$TARGET_DIR" + +echo " → Copying files to $TARGET_DIR" +cp *.mdx "$TARGET_DIR/" 2>/dev/null || echo " ⚠️ No MDX files to copy" + +# list generated files +echo " → Generated files:" +ls -la "$TARGET_DIR" 2>/dev/null || echo " ⚠️ No files generated" + +echo " ✅ CLI $VERSION complete" + diff --git a/scripts/sdk-generators/code-interpreter-js-sdk.sh b/scripts/sdk-generators/code-interpreter-js-sdk.sh new file mode 100755 index 0000000..ad27ef8 --- /dev/null +++ b/scripts/sdk-generators/code-interpreter-js-sdk.sh @@ -0,0 +1,129 @@ +#!/usr/bin/env bash + +set -euo pipefail + +# Code Interpreter JavaScript SDK Reference Generator +# Usage: ./code-interpreter-js-sdk.sh + +VERSION="$1" +TEMP_DIR="$2" +DOCS_DIR="$3" + +SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" +CONFIGS_DIR="$SCRIPT_DIR/../configs" + +echo " → Code Interpreter JS SDK version: $VERSION" + +# determine the git tag to clone +if [[ "$VERSION" == "latest" ]]; then + # get latest tag from code-interpreter repo (format: @e2b/code-interpreter@X.Y.Z) + VERSION=$(git ls-remote --tags --refs https://github.com/e2b-dev/code-interpreter.git | \ + grep 'refs/tags/@e2b/code-interpreter@' | \ + sed 's/.*refs\/tags\/@e2b\/code-interpreter@/v/' | \ + sort -V | tail -1) || true + + if [[ -z "$VERSION" ]]; then + echo " ⚠️ No JS SDK tags found, skipping..." + exit 0 + fi + echo " → Resolved latest to: $VERSION" +fi + +# convert version to git tag format +GIT_TAG="@e2b/code-interpreter@${VERSION#v}" + +# clone code-interpreter repo at specific version +REPO_DIR="$TEMP_DIR/code-interpreter" +if [[ ! -d "$REPO_DIR" ]]; then + echo " → Cloning code-interpreter repo at $GIT_TAG..." + git clone --depth 1 --branch "$GIT_TAG" \ + https://github.com/e2b-dev/code-interpreter.git \ + "$REPO_DIR" 2>/dev/null || { + echo " ⚠️ Tag $GIT_TAG not found, trying branch main..." + git clone --depth 1 \ + https://github.com/e2b-dev/code-interpreter.git \ + "$REPO_DIR" + } +fi + +# find JS SDK directory - try common locations +JS_DIR="" +for dir in "$REPO_DIR/js" "$REPO_DIR/packages/js-sdk" "$REPO_DIR/packages/sdk" "$REPO_DIR/js-sdk"; do + if [[ -d "$dir" ]]; then + JS_DIR="$dir" + break + fi +done + +if [[ -z "$JS_DIR" ]]; then + echo " ⚠️ No JS SDK directory found in code-interpreter repo, skipping..." + echo " → Repo structure:" + ls -la "$REPO_DIR" 2>/dev/null || true + exit 0 +fi + +cd "$JS_DIR" + +# install dependencies +echo " → Installing dependencies..." +if command -v pnpm &> /dev/null; then + pnpm install --ignore-scripts 2>&1 || npm install --legacy-peer-deps 2>&1 +else + npm install --legacy-peer-deps 2>&1 +fi + +# check if there's a typedoc config, otherwise use our default +if [[ -f "typedoc.json" ]]; then + echo " → Running TypeDoc with repo config..." + npx typedoc --plugin typedoc-plugin-markdown \ + --plugin "$CONFIGS_DIR/typedoc-theme.js" +else + echo " → Running TypeDoc with default config..." + cp "$CONFIGS_DIR/typedoc.json" ./typedoc.docs.json + npx typedoc --options ./typedoc.docs.json \ + --plugin typedoc-plugin-markdown \ + --plugin "$CONFIGS_DIR/typedoc-theme.js" +fi + +# process generated files - flatten structure for Mintlify +cd sdk_ref + +# remove README if exists +rm -f README.md + +# flatten nested structure +find . -mindepth 2 -type f -name "*.md" | while read -r file; do + dir=$(dirname "$file") + filename=$(basename "$file") + + if [[ "$filename" == "page.md" || "$filename" == "index.md" ]]; then + module=$(basename "$dir") + mv "$file" "./${module}.md" 2>/dev/null || true + else + mv "$file" "./" 2>/dev/null || true + fi +done + +# remove empty directories +find . -type d -empty -delete 2>/dev/null || true + +# rename .md to .mdx +for file in *.md; do + if [[ -f "$file" ]]; then + mv "$file" "${file%.md}.mdx" + fi +done + +# copy to docs repo +TARGET_DIR="$DOCS_DIR/docs/sdk-reference/code-interpreter-js-sdk/$VERSION" +mkdir -p "$TARGET_DIR" + +echo " → Copying files to $TARGET_DIR" +cp *.mdx "$TARGET_DIR/" 2>/dev/null || echo " ⚠️ No MDX files to copy" + +# list generated files +echo " → Generated files:" +ls -la "$TARGET_DIR" 2>/dev/null || echo " ⚠️ No files generated" + +echo " ✅ Code Interpreter JS SDK $VERSION complete" + diff --git a/scripts/sdk-generators/code-interpreter-python-sdk.sh b/scripts/sdk-generators/code-interpreter-python-sdk.sh new file mode 100755 index 0000000..9149045 --- /dev/null +++ b/scripts/sdk-generators/code-interpreter-python-sdk.sh @@ -0,0 +1,110 @@ +#!/usr/bin/env bash + +set -euo pipefail + +# Code Interpreter Python SDK Reference Generator +# Usage: ./code-interpreter-python-sdk.sh + +VERSION="$1" +TEMP_DIR="$2" +DOCS_DIR="$3" + +echo " → Code Interpreter Python SDK version: $VERSION" + +# determine the git tag to clone +if [[ "$VERSION" == "latest" ]]; then + # get latest tag from code-interpreter repo (format: e2b-code-interpreter@X.Y.Z) + VERSION=$(git ls-remote --tags --refs https://github.com/e2b-dev/code-interpreter.git | \ + grep 'refs/tags/e2b-code-interpreter@' | \ + sed 's/.*refs\/tags\/e2b-code-interpreter@/v/' | \ + sort -V | tail -1) || true + + if [[ -z "$VERSION" ]]; then + echo " ⚠️ No Python SDK tags found, skipping..." + exit 0 + fi + echo " → Resolved latest to: $VERSION" +fi + +# convert version to git tag format +GIT_TAG="e2b-code-interpreter@${VERSION#v}" + +# clone code-interpreter repo at specific version +REPO_DIR="$TEMP_DIR/code-interpreter-python" +if [[ ! -d "$REPO_DIR" ]]; then + echo " → Cloning code-interpreter repo at $GIT_TAG..." + git clone --depth 1 --branch "$GIT_TAG" \ + https://github.com/e2b-dev/code-interpreter.git \ + "$REPO_DIR" 2>/dev/null || { + echo " ⚠️ Tag $GIT_TAG not found, trying branch main..." + git clone --depth 1 \ + https://github.com/e2b-dev/code-interpreter.git \ + "$REPO_DIR" + } +fi + +# find Python SDK directory - try common locations +PY_DIR="" +for dir in "$REPO_DIR/python" "$REPO_DIR/packages/python-sdk" "$REPO_DIR/packages/python" "$REPO_DIR/python-sdk"; do + if [[ -d "$dir" ]]; then + PY_DIR="$dir" + break + fi +done + +if [[ -z "$PY_DIR" ]]; then + echo " ⚠️ No Python SDK directory found in code-interpreter repo, skipping..." + echo " → Repo structure:" + ls -la "$REPO_DIR" 2>/dev/null || true + ls -la "$REPO_DIR/packages" 2>/dev/null || true + exit 0 +fi + +cd "$PY_DIR" + +# install dependencies +echo " → Installing dependencies with poetry..." +poetry install --quiet 2>/dev/null || pip install pydoc-markdown + +# packages to generate docs for +packages=("e2b_code_interpreter") + +# create output directory +mkdir -p sdk_ref + +# function to process generated markdown +process_mdx() { + local file=$1 + sed -i'' -e '/]*>.*<\/a>/d' "${file}" 2>/dev/null || true + sed -i'' -e '/^# /d' "${file}" 2>/dev/null || true + sed -i'' -e '/^## / s/ Objects$//' "${file}" 2>/dev/null || true + sed -i'' -e 's/^####/###/' "${file}" 2>/dev/null || true +} + +echo " → Generating documentation..." + +for package in "${packages[@]}"; do + echo " → Processing ${package}..." + + poetry run pydoc-markdown -p "${package}" > "sdk_ref/sandbox.mdx" 2>/dev/null || { + echo " ⚠️ Failed to generate docs for ${package}" + continue + } + + process_mdx "sdk_ref/sandbox.mdx" +done + +# copy to docs repo +TARGET_DIR="$DOCS_DIR/docs/sdk-reference/code-interpreter-python-sdk/$VERSION" +mkdir -p "$TARGET_DIR" + +echo " → Copying files to $TARGET_DIR" +cd sdk_ref +cp *.mdx "$TARGET_DIR/" 2>/dev/null || echo " ⚠️ No MDX files to copy" + +# list generated files +echo " → Generated files:" +ls -la "$TARGET_DIR" 2>/dev/null || echo " ⚠️ No files generated" + +echo " ✅ Code Interpreter Python SDK $VERSION complete" + diff --git a/scripts/sdk-generators/desktop-js-sdk.sh b/scripts/sdk-generators/desktop-js-sdk.sh new file mode 100755 index 0000000..60d14ee --- /dev/null +++ b/scripts/sdk-generators/desktop-js-sdk.sh @@ -0,0 +1,130 @@ +#!/usr/bin/env bash + +set -euo pipefail + +# Desktop JavaScript SDK Reference Generator +# Usage: ./desktop-js-sdk.sh + +VERSION="$1" +TEMP_DIR="$2" +DOCS_DIR="$3" + +SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" +CONFIGS_DIR="$SCRIPT_DIR/../configs" + +echo " → Desktop JS SDK version: $VERSION" + +# determine the git tag to clone +if [[ "$VERSION" == "latest" ]]; then + # get latest tag from desktop repo (format: @e2b/desktop@X.Y.Z) + VERSION=$(git ls-remote --tags --refs https://github.com/e2b-dev/desktop.git | \ + grep 'refs/tags/@e2b/desktop@' | \ + sed 's/.*refs\/tags\/@e2b\/desktop@/v/' | \ + sort -V | tail -1) || true + + if [[ -z "$VERSION" ]]; then + echo " ⚠️ No JS SDK tags found, skipping..." + exit 0 + fi + echo " → Resolved latest to: $VERSION" +fi + +# convert version to git tag format +GIT_TAG="@e2b/desktop@${VERSION#v}" + +# clone desktop repo at specific version +REPO_DIR="$TEMP_DIR/desktop" +if [[ ! -d "$REPO_DIR" ]]; then + echo " → Cloning desktop repo at $GIT_TAG..." + git clone --depth 1 --branch "$GIT_TAG" \ + https://github.com/e2b-dev/desktop.git \ + "$REPO_DIR" 2>/dev/null || { + echo " ⚠️ Tag $GIT_TAG not found, trying branch main..." + git clone --depth 1 \ + https://github.com/e2b-dev/desktop.git \ + "$REPO_DIR" + } +fi + +# find JS SDK directory - try common locations +JS_DIR="" +for dir in "$REPO_DIR/js" "$REPO_DIR/packages/js-sdk" "$REPO_DIR/packages/sdk" "$REPO_DIR/js-sdk"; do + if [[ -d "$dir" ]]; then + JS_DIR="$dir" + break + fi +done + +if [[ -z "$JS_DIR" ]]; then + echo " ⚠️ No JS SDK directory found in desktop repo, skipping..." + echo " → Repo structure:" + ls -la "$REPO_DIR" 2>/dev/null || true + ls -la "$REPO_DIR/packages" 2>/dev/null || true + exit 0 +fi + +cd "$JS_DIR" + +# install dependencies +echo " → Installing dependencies..." +if command -v pnpm &> /dev/null; then + pnpm install --ignore-scripts 2>&1 || npm install --legacy-peer-deps 2>&1 +else + npm install --legacy-peer-deps 2>&1 +fi + +# check if there's a typedoc config, otherwise use our default +if [[ -f "typedoc.json" ]]; then + echo " → Running TypeDoc with repo config..." + npx typedoc --plugin typedoc-plugin-markdown \ + --plugin "$CONFIGS_DIR/typedoc-theme.js" +else + echo " → Running TypeDoc with default config..." + cp "$CONFIGS_DIR/typedoc.json" ./typedoc.docs.json + npx typedoc --options ./typedoc.docs.json \ + --plugin typedoc-plugin-markdown \ + --plugin "$CONFIGS_DIR/typedoc-theme.js" +fi + +# process generated files - flatten structure for Mintlify +cd sdk_ref + +# remove README if exists +rm -f README.md + +# flatten nested structure +find . -mindepth 2 -type f -name "*.md" | while read -r file; do + dir=$(dirname "$file") + filename=$(basename "$file") + + if [[ "$filename" == "page.md" || "$filename" == "index.md" ]]; then + module=$(basename "$dir") + mv "$file" "./${module}.md" 2>/dev/null || true + else + mv "$file" "./" 2>/dev/null || true + fi +done + +# remove empty directories +find . -type d -empty -delete 2>/dev/null || true + +# rename .md to .mdx +for file in *.md; do + if [[ -f "$file" ]]; then + mv "$file" "${file%.md}.mdx" + fi +done + +# copy to docs repo +TARGET_DIR="$DOCS_DIR/docs/sdk-reference/desktop-js-sdk/$VERSION" +mkdir -p "$TARGET_DIR" + +echo " → Copying files to $TARGET_DIR" +cp *.mdx "$TARGET_DIR/" 2>/dev/null || echo " ⚠️ No MDX files to copy" + +# list generated files +echo " → Generated files:" +ls -la "$TARGET_DIR" 2>/dev/null || echo " ⚠️ No files generated" + +echo " ✅ Desktop JS SDK $VERSION complete" + diff --git a/scripts/sdk-generators/desktop-python-sdk.sh b/scripts/sdk-generators/desktop-python-sdk.sh new file mode 100755 index 0000000..d91c8e1 --- /dev/null +++ b/scripts/sdk-generators/desktop-python-sdk.sh @@ -0,0 +1,110 @@ +#!/usr/bin/env bash + +set -euo pipefail + +# Desktop Python SDK Reference Generator +# Usage: ./desktop-python-sdk.sh + +VERSION="$1" +TEMP_DIR="$2" +DOCS_DIR="$3" + +echo " → Desktop Python SDK version: $VERSION" + +# determine the git tag to clone +if [[ "$VERSION" == "latest" ]]; then + # get latest tag from desktop repo (format: e2b-desktop@X.Y.Z) + VERSION=$(git ls-remote --tags --refs https://github.com/e2b-dev/desktop.git | \ + grep 'refs/tags/e2b-desktop@' | \ + sed 's/.*refs\/tags\/e2b-desktop@/v/' | \ + sort -V | tail -1) || true + + if [[ -z "$VERSION" ]]; then + echo " ⚠️ No Python SDK tags found, skipping..." + exit 0 + fi + echo " → Resolved latest to: $VERSION" +fi + +# convert version to git tag format +GIT_TAG="e2b-desktop@${VERSION#v}" + +# clone desktop repo at specific version +REPO_DIR="$TEMP_DIR/desktop-python" +if [[ ! -d "$REPO_DIR" ]]; then + echo " → Cloning desktop repo at $GIT_TAG..." + git clone --depth 1 --branch "$GIT_TAG" \ + https://github.com/e2b-dev/desktop.git \ + "$REPO_DIR" 2>/dev/null || { + echo " ⚠️ Tag $GIT_TAG not found, trying branch main..." + git clone --depth 1 \ + https://github.com/e2b-dev/desktop.git \ + "$REPO_DIR" + } +fi + +# find Python SDK directory - try common locations +PY_DIR="" +for dir in "$REPO_DIR/python" "$REPO_DIR/packages/python-sdk" "$REPO_DIR/packages/python" "$REPO_DIR/python-sdk"; do + if [[ -d "$dir" ]]; then + PY_DIR="$dir" + break + fi +done + +if [[ -z "$PY_DIR" ]]; then + echo " ⚠️ No Python SDK directory found in desktop repo, skipping..." + echo " → Repo structure:" + ls -la "$REPO_DIR" 2>/dev/null || true + ls -la "$REPO_DIR/packages" 2>/dev/null || true + exit 0 +fi + +cd "$PY_DIR" + +# install dependencies +echo " → Installing dependencies with poetry..." +poetry install --quiet 2>/dev/null || pip install pydoc-markdown + +# packages to generate docs for +packages=("e2b_desktop") + +# create output directory +mkdir -p sdk_ref + +# function to process generated markdown +process_mdx() { + local file=$1 + sed -i'' -e '/]*>.*<\/a>/d' "${file}" 2>/dev/null || true + sed -i'' -e '/^# /d' "${file}" 2>/dev/null || true + sed -i'' -e '/^## / s/ Objects$//' "${file}" 2>/dev/null || true + sed -i'' -e 's/^####/###/' "${file}" 2>/dev/null || true +} + +echo " → Generating documentation..." + +for package in "${packages[@]}"; do + echo " → Processing ${package}..." + + poetry run pydoc-markdown -p "${package}" > "sdk_ref/sandbox.mdx" 2>/dev/null || { + echo " ⚠️ Failed to generate docs for ${package}" + continue + } + + process_mdx "sdk_ref/sandbox.mdx" +done + +# copy to docs repo +TARGET_DIR="$DOCS_DIR/docs/sdk-reference/desktop-python-sdk/$VERSION" +mkdir -p "$TARGET_DIR" + +echo " → Copying files to $TARGET_DIR" +cd sdk_ref +cp *.mdx "$TARGET_DIR/" 2>/dev/null || echo " ⚠️ No MDX files to copy" + +# list generated files +echo " → Generated files:" +ls -la "$TARGET_DIR" 2>/dev/null || echo " ⚠️ No files generated" + +echo " ✅ Desktop Python SDK $VERSION complete" + diff --git a/scripts/sdk-generators/js-sdk.sh b/scripts/sdk-generators/js-sdk.sh new file mode 100755 index 0000000..a60ae40 --- /dev/null +++ b/scripts/sdk-generators/js-sdk.sh @@ -0,0 +1,123 @@ +#!/usr/bin/env bash + +set -euo pipefail + +# JavaScript SDK Reference Generator +# Usage: ./js-sdk.sh + +VERSION="$1" +TEMP_DIR="$2" +DOCS_DIR="$3" + +SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" +CONFIGS_DIR="$SCRIPT_DIR/../configs" + +echo " → JS SDK version: $VERSION" + +# determine the git tag to clone +if [[ "$VERSION" == "latest" ]]; then + # get latest tag from e2b repo (format: e2b@X.Y.Z) + VERSION=$(git ls-remote --tags --refs https://github.com/e2b-dev/e2b.git | \ + grep 'refs/tags/e2b@' | \ + sed 's/.*refs\/tags\/e2b@/v/' | \ + sort -V | tail -1) || true + + if [[ -z "$VERSION" ]]; then + echo " ❌ No JS SDK tags found" + exit 1 + fi + echo " → Resolved latest to: $VERSION" +fi + +# convert version to git tag format (v2.9.0 -> e2b@2.9.0) +GIT_TAG="e2b@${VERSION#v}" + +# clone e2b repo at specific version +REPO_DIR="$TEMP_DIR/e2b-js-sdk" +if [[ ! -d "$REPO_DIR" ]]; then + echo " → Cloning e2b repo at $GIT_TAG..." + git clone --depth 1 --branch "$GIT_TAG" \ + https://github.com/e2b-dev/e2b.git \ + "$REPO_DIR" 2>/dev/null || { + echo " ⚠️ Tag $GIT_TAG not found, trying branch main..." + git clone --depth 1 \ + https://github.com/e2b-dev/e2b.git \ + "$REPO_DIR" + } +fi + +JS_SDK_DIR="$REPO_DIR/packages/js-sdk" +if [[ ! -d "$JS_SDK_DIR" ]]; then + echo " ❌ Directory not found: $JS_SDK_DIR" + echo " → Checking repo structure..." + ls -la "$REPO_DIR" || true + exit 1 +fi + +cd "$JS_SDK_DIR" + +# install dependencies (use pnpm if available, fallback to npm) +echo " → Installing dependencies..." +if command -v pnpm &> /dev/null; then + pnpm install --ignore-scripts 2>&1 || { + echo " ⚠️ pnpm install failed, trying npm..." + npm install --legacy-peer-deps 2>&1 + } +else + npm install --legacy-peer-deps 2>&1 +fi + +# copy typedoc config to temp location +cp "$CONFIGS_DIR/typedoc.json" ./typedoc.docs.json + +# generate using TypeDoc +echo " → Running TypeDoc..." +npx typedoc --options ./typedoc.docs.json \ + --plugin typedoc-plugin-markdown \ + --plugin "$CONFIGS_DIR/typedoc-theme.js" + +# process generated files - flatten structure for Mintlify +cd sdk_ref + +# remove README if exists +rm -f README.md + +# flatten nested structure: move all files to root level +find . -mindepth 2 -type f -name "*.md" | while read -r file; do + # get the parent directory name as module name + dir=$(dirname "$file") + filename=$(basename "$file") + + if [[ "$filename" == "page.md" || "$filename" == "index.md" ]]; then + # use directory name as file name + module=$(basename "$dir") + mv "$file" "./${module}.md" 2>/dev/null || true + else + # move file to root + mv "$file" "./" 2>/dev/null || true + fi +done + +# remove empty directories +find . -type d -empty -delete 2>/dev/null || true + +# rename .md to .mdx +for file in *.md; do + if [[ -f "$file" ]]; then + mv "$file" "${file%.md}.mdx" + fi +done + +# copy to docs repo +TARGET_DIR="$DOCS_DIR/docs/sdk-reference/js-sdk/$VERSION" +mkdir -p "$TARGET_DIR" + +echo " → Copying files to $TARGET_DIR" +cp *.mdx "$TARGET_DIR/" 2>/dev/null || echo " ⚠️ No MDX files to copy" + +# list generated files +echo " → Generated files:" +ls -la "$TARGET_DIR" 2>/dev/null || echo " ⚠️ No files generated" + +echo " ✅ JS SDK $VERSION complete" + diff --git a/scripts/sdk-generators/python-sdk.sh b/scripts/sdk-generators/python-sdk.sh new file mode 100755 index 0000000..fd24069 --- /dev/null +++ b/scripts/sdk-generators/python-sdk.sh @@ -0,0 +1,114 @@ +#!/usr/bin/env bash + +set -euo pipefail + +# Python SDK Reference Generator +# Usage: ./python-sdk.sh + +VERSION="$1" +TEMP_DIR="$2" +DOCS_DIR="$3" + +echo " → Python SDK version: $VERSION" + +# determine the git tag to clone +if [[ "$VERSION" == "latest" ]]; then + # get latest tag from e2b repo (format: e2b@X.Y.Z) + VERSION=$(git ls-remote --tags --refs https://github.com/e2b-dev/e2b.git | \ + grep 'refs/tags/e2b@' | \ + sed 's/.*refs\/tags\/e2b@/v/' | \ + sort -V | tail -1) || true + + if [[ -z "$VERSION" ]]; then + echo " ❌ No Python SDK tags found" + exit 1 + fi + echo " → Resolved latest to: $VERSION" +fi + +# convert version to git tag format (v2.9.0 -> e2b@2.9.0) +GIT_TAG="e2b@${VERSION#v}" + +# clone e2b repo at specific version +REPO_DIR="$TEMP_DIR/e2b-python-sdk" +if [[ ! -d "$REPO_DIR" ]]; then + echo " → Cloning e2b repo at $GIT_TAG..." + git clone --depth 1 --branch "$GIT_TAG" \ + https://github.com/e2b-dev/e2b.git \ + "$REPO_DIR" 2>/dev/null || { + echo " ⚠️ Tag $GIT_TAG not found, trying branch main..." + git clone --depth 1 \ + https://github.com/e2b-dev/e2b.git \ + "$REPO_DIR" + } +fi + +cd "$REPO_DIR/packages/python-sdk" + +# install poetry and dependencies +echo " → Installing dependencies with poetry..." +poetry install --quiet 2>/dev/null || pip install pydoc-markdown + +# packages to generate docs for +packages=("sandbox_sync" "sandbox_async" "exceptions" "template" "template_sync" "template_async") +template_submodules=("logger" "readycmd") + +# create output directory +mkdir -p sdk_ref + +# function to process generated markdown +process_mdx() { + local file=$1 + # remove package path display + sed -i'' -e '/]*>.*<\/a>/d' "${file}" 2>/dev/null || true + # remove empty hyperlinks + sed -i'' -e '/^# /d' "${file}" 2>/dev/null || true + # remove " Objects" from lines starting with "##" + sed -i'' -e '/^## / s/ Objects$//' "${file}" 2>/dev/null || true + # replace lines starting with "####" with "###" + sed -i'' -e 's/^####/###/' "${file}" 2>/dev/null || true +} + +echo " → Generating documentation for packages..." + +for package in "${packages[@]}"; do + echo " → Processing e2b.${package}..." + + # generate raw SDK reference markdown file + poetry run pydoc-markdown -p "e2b.${package}" > "sdk_ref/${package}.mdx" 2>/dev/null || { + echo " ⚠️ Failed to generate docs for ${package}" + continue + } + + # process the generated markdown + process_mdx "sdk_ref/${package}.mdx" +done + +# generate documentation for template submodules +for submodule in "${template_submodules[@]}"; do + echo " → Processing e2b.template.${submodule}..." + + # generate raw SDK reference markdown file + poetry run pydoc-markdown -p "e2b.template.${submodule}" > "sdk_ref/${submodule}.mdx" 2>/dev/null || { + echo " ⚠️ Failed to generate docs for template.${submodule}" + continue + } + + # process the generated markdown + process_mdx "sdk_ref/${submodule}.mdx" +done + +# copy to docs repo +TARGET_DIR="$DOCS_DIR/docs/sdk-reference/python-sdk/$VERSION" +mkdir -p "$TARGET_DIR" + +echo " → Copying files to $TARGET_DIR" +cd sdk_ref +cp *.mdx "$TARGET_DIR/" 2>/dev/null || echo " ⚠️ No MDX files to copy" + +# list generated files +echo " → Generated files:" +ls -la "$TARGET_DIR" 2>/dev/null || echo " ⚠️ No files generated" + +echo " ✅ Python SDK $VERSION complete" + From 254049f5848c2c24a1a19666ea51126e7d69644f Mon Sep 17 00:00:00 2001 From: ben-fornefeld Date: Tue, 6 Jan 2026 15:46:36 +0100 Subject: [PATCH 02/39] Refactor SDK reference generation workflow - Updated the SDK generation workflow to load SDK configurations from `sdks.json`, improving maintainability. - Removed individual SDK generator scripts for CLI, Code Interpreter (JS and Python), and Desktop SDKs, consolidating functionality into a single generator script. - Enhanced the `generate-sdk-reference.sh` script to dynamically handle SDK types and versions. - Cleaned up the workflow YAML file for better readability and consistency in string formatting. --- .github/workflows/sdk-reference-sync.yml | 25 +-- scripts/generate-sdk-nav.js | 67 +++---- scripts/generate-sdk-reference.sh | 79 +++----- scripts/generate-sdk.sh | 143 +++++++++++++++ scripts/generators/cli.sh | 49 +++++ scripts/generators/pydoc.sh | 59 ++++++ scripts/generators/typedoc.sh | 33 ++++ scripts/lib/common.sh | 170 ++++++++++++++++++ scripts/sdk-generators/cli.sh | 97 ---------- .../sdk-generators/code-interpreter-js-sdk.sh | 129 ------------- .../code-interpreter-python-sdk.sh | 110 ------------ scripts/sdk-generators/desktop-js-sdk.sh | 130 -------------- scripts/sdk-generators/desktop-python-sdk.sh | 110 ------------ scripts/sdk-generators/js-sdk.sh | 123 ------------- scripts/sdk-generators/python-sdk.sh | 114 ------------ scripts/sdks.json | 95 ++++++++++ 16 files changed, 612 insertions(+), 921 deletions(-) create mode 100755 scripts/generate-sdk.sh create mode 100755 scripts/generators/cli.sh create mode 100755 scripts/generators/pydoc.sh create mode 100755 scripts/generators/typedoc.sh create mode 100755 scripts/lib/common.sh delete mode 100755 scripts/sdk-generators/cli.sh delete mode 100755 scripts/sdk-generators/code-interpreter-js-sdk.sh delete mode 100755 scripts/sdk-generators/code-interpreter-python-sdk.sh delete mode 100755 scripts/sdk-generators/desktop-js-sdk.sh delete mode 100755 scripts/sdk-generators/desktop-python-sdk.sh delete mode 100755 scripts/sdk-generators/js-sdk.sh delete mode 100755 scripts/sdk-generators/python-sdk.sh create mode 100644 scripts/sdks.json diff --git a/.github/workflows/sdk-reference-sync.yml b/.github/workflows/sdk-reference-sync.yml index 45d5d01..6b992d0 100644 --- a/.github/workflows/sdk-reference-sync.yml +++ b/.github/workflows/sdk-reference-sync.yml @@ -5,9 +5,9 @@ on: workflow_dispatch: inputs: sdk: - description: 'SDK to generate (js-sdk, python-sdk, cli, code-interpreter-js-sdk, code-interpreter-python-sdk, desktop-js-sdk, desktop-python-sdk, all)' + description: "SDK to generate (js-sdk, python-sdk, cli, code-interpreter-js-sdk, code-interpreter-python-sdk, desktop-js-sdk, desktop-python-sdk, all)" required: true - default: 'all' + default: "all" type: choice options: - all @@ -19,9 +19,9 @@ on: - desktop-js-sdk - desktop-python-sdk version: - description: 'Version to generate (e.g., v2.9.0 or latest)' + description: "Version to generate (e.g., v2.9.0 or latest)" required: true - default: 'latest' + default: "latest" type: string # triggered from e2b-dev/e2b repo on release @@ -33,7 +33,7 @@ jobs: runs-on: ubuntu-latest permissions: contents: write - + steps: - name: Checkout docs repo uses: actions/checkout@v4 @@ -43,7 +43,7 @@ jobs: - name: Setup Node.js uses: actions/setup-node@v4 with: - node-version: '20' + node-version: "20" - name: Install pnpm uses: pnpm/action-setup@v4 @@ -53,7 +53,7 @@ jobs: - name: Setup Python uses: actions/setup-python@v5 with: - python-version: '3.11' + python-version: "3.11" - name: Install Node dependencies run: pnpm install @@ -76,7 +76,7 @@ jobs: SDK="${{ github.event.client_payload.sdk }}" VERSION="${{ github.event.client_payload.version }}" fi - + # fallback to defaults if empty echo "sdk=${SDK:-all}" >> $GITHUB_OUTPUT echo "version=${VERSION:-latest}" >> $GITHUB_OUTPUT @@ -84,7 +84,9 @@ jobs: - name: Generate SDK Reference run: | chmod +x scripts/generate-sdk-reference.sh - chmod +x scripts/sdk-generators/*.sh + chmod +x scripts/generate-sdk.sh + chmod +x scripts/lib/*.sh + chmod +x scripts/generators/*.sh ./scripts/generate-sdk-reference.sh \ --sdk "${{ steps.params.outputs.sdk }}" \ --version "${{ steps.params.outputs.version }}" @@ -101,12 +103,12 @@ jobs: run: | git config user.name "github-actions[bot]" git config user.email "github-actions[bot]@users.noreply.github.com" - + # stage changes git add docs/sdk-reference/ git add sdk_navigation.json git add docs.json - + # commit if there are changes if git diff --staged --quiet; then echo "No changes to commit" @@ -127,4 +129,3 @@ jobs: find docs/sdk-reference -type f -name "*.mdx" | wc -l | xargs echo "Total MDX files:" find docs/sdk-reference -type f -name "*.mdx" >> $GITHUB_STEP_SUMMARY || true echo '```' >> $GITHUB_STEP_SUMMARY - diff --git a/scripts/generate-sdk-nav.js b/scripts/generate-sdk-nav.js index 3142cba..7299cfe 100644 --- a/scripts/generate-sdk-nav.js +++ b/scripts/generate-sdk-nav.js @@ -3,6 +3,8 @@ /** * SDK Navigation Generator * Scans the docs/sdk-reference directory and generates Mintlify-compatible navigation JSON. + * + * Reads SDK configuration from sdks.json for display names, icons, and ordering. */ const fs = require('fs'); @@ -19,46 +21,30 @@ try { const SCRIPT_DIR = __dirname; const DOCS_DIR = path.join(SCRIPT_DIR, '..'); const SDK_REF_DIR = path.join(DOCS_DIR, 'docs', 'sdk-reference'); +const CONFIG_FILE = path.join(SCRIPT_DIR, 'sdks.json'); const OUTPUT_FILE = path.join(DOCS_DIR, 'sdk_navigation.json'); -// SDK configuration - maps directory names to display names and icons -const SDK_CONFIGS = { - 'cli': { - name: 'CLI', - icon: 'terminal', - order: 1 - }, - 'js-sdk': { - name: 'JavaScript SDK', - icon: 'square-js', - order: 2 - }, - 'python-sdk': { - name: 'Python SDK', - icon: 'python', - order: 3 - }, - 'code-interpreter-js-sdk': { - name: 'Code Interpreter JavaScript SDK', - icon: 'square-js', - order: 4 - }, - 'code-interpreter-python-sdk': { - name: 'Code Interpreter Python SDK', - icon: 'python', - order: 5 - }, - 'desktop-js-sdk': { - name: 'Desktop JavaScript SDK', - icon: 'square-js', - order: 6 - }, - 'desktop-python-sdk': { - name: 'Desktop Python SDK', - icon: 'python', - order: 7 - }, -}; +/** + * Load SDK configuration from sdks.json + */ +function loadSdkConfigs() { + try { + const config = require(CONFIG_FILE); + return Object.fromEntries( + Object.entries(config.sdks).map(([key, sdk]) => [ + key, + { + name: sdk.displayName, + icon: sdk.icon, + order: sdk.order + } + ]) + ); + } catch (err) { + console.error('Failed to load sdks.json:', err.message); + process.exit(1); + } +} /** * Get all version directories for an SDK @@ -109,6 +95,7 @@ function getModules(versionDir) { * Generate navigation structure for all SDKs */ function generateNavigation() { + const SDK_CONFIGS = loadSdkConfigs(); const navigation = []; // check if sdk-reference directory exists @@ -117,7 +104,7 @@ function generateNavigation() { return navigation; } - // process each SDK + // process each SDK from config for (const [sdkKey, config] of Object.entries(SDK_CONFIGS)) { const sdkDir = path.join(SDK_REF_DIR, sdkKey); @@ -171,6 +158,7 @@ function generateNavigation() { */ function main() { console.log('📝 Generating SDK navigation...'); + console.log(` Config: ${CONFIG_FILE}`); console.log(` Source: ${SDK_REF_DIR}`); console.log(` Output: ${OUTPUT_FILE}`); console.log(''); @@ -194,4 +182,3 @@ function main() { } main(); - diff --git a/scripts/generate-sdk-reference.sh b/scripts/generate-sdk-reference.sh index d28de58..9037e58 100755 --- a/scripts/generate-sdk-reference.sh +++ b/scripts/generate-sdk-reference.sh @@ -1,5 +1,4 @@ #!/usr/bin/env bash - set -euo pipefail # SDK Reference Documentation Generator @@ -13,6 +12,7 @@ set -euo pipefail SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" DOCS_DIR="$(cd "$SCRIPT_DIR/.." && pwd)" +CONFIG_FILE="$SCRIPT_DIR/sdks.json" # defaults SDK_TYPE="all" @@ -22,7 +22,6 @@ VERSION="latest" while [[ $# -gt 0 ]]; do case $1 in --sdk) - # only set if value is non-empty and not another flag if [[ -n "${2:-}" && ! "$2" =~ ^-- ]]; then SDK_TYPE="$2" shift 2 @@ -31,7 +30,6 @@ while [[ $# -gt 0 ]]; do fi ;; --version) - # only set if value is non-empty and not another flag if [[ -n "${2:-}" && ! "$2" =~ ^-- ]]; then VERSION="$2" shift 2 @@ -60,65 +58,35 @@ echo " Version: $VERSION" echo " Temp dir: $TEMP_DIR" echo "" -# helper to run individual SDK generators +# get list of SDKs from config +get_sdk_list() { + node -e "console.log(Object.keys(require('$CONFIG_FILE').sdks).join(' '))" +} + +# generate SDK documentation run_generator() { local sdk="$1" local version="$2" - local generator="$SCRIPT_DIR/sdk-generators/${sdk}.sh" - if [[ -f "$generator" ]]; then - echo "📦 Generating $sdk..." - chmod +x "$generator" - "$generator" "$version" "$TEMP_DIR" "$DOCS_DIR" - else - echo "⚠️ Generator not found: $generator" - fi + echo "📦 Generating $sdk..." + chmod +x "$SCRIPT_DIR/generate-sdk.sh" + "$SCRIPT_DIR/generate-sdk.sh" "$sdk" "$version" "$TEMP_DIR" "$DOCS_DIR" || { + echo " ⚠️ Generator failed for $sdk" + return 0 # continue with other SDKs + } } -case "$SDK_TYPE" in - js-sdk) - run_generator "js-sdk" "$VERSION" - ;; - python-sdk) - run_generator "python-sdk" "$VERSION" - ;; - cli) - run_generator "cli" "$VERSION" - ;; - code-interpreter-js-sdk) - run_generator "code-interpreter-js-sdk" "$VERSION" - ;; - code-interpreter-python-sdk) - run_generator "code-interpreter-python-sdk" "$VERSION" - ;; - desktop-js-sdk) - run_generator "desktop-js-sdk" "$VERSION" - ;; - desktop-python-sdk) - run_generator "desktop-python-sdk" "$VERSION" - ;; - all) - # generate all SDKs from main e2b repo - run_generator "js-sdk" "$VERSION" - run_generator "python-sdk" "$VERSION" - run_generator "cli" "$VERSION" - - # generate SDKs from external repos - run_generator "code-interpreter-js-sdk" "$VERSION" - run_generator "code-interpreter-python-sdk" "$VERSION" - run_generator "desktop-js-sdk" "$VERSION" - run_generator "desktop-python-sdk" "$VERSION" - ;; - *) - echo "❌ Unknown SDK type: $SDK_TYPE" - echo " Valid options: js-sdk, python-sdk, cli, code-interpreter-js-sdk," - echo " code-interpreter-python-sdk, desktop-js-sdk," - echo " desktop-python-sdk, all" - exit 1 - ;; -esac +# run generators +if [[ "$SDK_TYPE" == "all" ]]; then + SDK_LIST=$(get_sdk_list) + for sdk in $SDK_LIST; do + run_generator "$sdk" "$VERSION" + done +else + run_generator "$SDK_TYPE" "$VERSION" +fi -# generate navigation JSON after all SDKs are generated +# generate navigation JSON echo "" echo "📝 Generating navigation JSON..." node "$SCRIPT_DIR/generate-sdk-nav.js" @@ -130,4 +98,3 @@ node "$SCRIPT_DIR/merge-sdk-nav.js" echo "" echo "✅ SDK reference generation complete" - diff --git a/scripts/generate-sdk.sh b/scripts/generate-sdk.sh new file mode 100755 index 0000000..5e0dc0b --- /dev/null +++ b/scripts/generate-sdk.sh @@ -0,0 +1,143 @@ +#!/usr/bin/env bash +set -euo pipefail + +# Universal SDK Generator +# Usage: ./generate-sdk.sh +# +# This script replaces all individual SDK generator scripts by reading +# configuration from sdks.json and using shared utility functions. + +SDK_KEY="$1" +VERSION="$2" +TEMP_DIR="$3" +DOCS_DIR="$4" + +SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" +CONFIG_FILE="$SCRIPT_DIR/sdks.json" +CONFIGS_DIR="$SCRIPT_DIR/configs" + +# source shared utilities +source "$SCRIPT_DIR/lib/common.sh" + +# helper to read config values using node +get_config() { + local path="$1" + node -e "const c = require('$CONFIG_FILE').sdks['$SDK_KEY']; console.log(c && c.$path !== undefined ? c.$path : '')" +} + +get_config_array() { + local path="$1" + node -e "const c = require('$CONFIG_FILE').sdks['$SDK_KEY']; const v = c && c.$path; if(Array.isArray(v)) console.log(v.join(' '));" +} + +# read SDK configuration +DISPLAY_NAME=$(get_config "displayName") +REPO=$(get_config "repo") +TAG_PATTERN=$(get_config "tagPattern") +TAG_FORMAT=$(get_config "tagFormat") +GENERATOR=$(get_config "generator") +REQUIRED=$(get_config "required") +SDK_PATH=$(get_config "sdkPath") +SDK_PATHS=$(get_config_array "sdkPaths") +PACKAGES=$(get_config_array "packages") + +# validate configuration +if [[ -z "$DISPLAY_NAME" ]]; then + echo " ❌ SDK '$SDK_KEY' not found in configuration" + exit 1 +fi + +echo " → $DISPLAY_NAME version: $VERSION" + +# resolve version +RESOLVED_VERSION=$(resolve_version "$REPO" "$TAG_PATTERN" "$VERSION") || true + +if [[ -z "$RESOLVED_VERSION" ]]; then + if [[ "$REQUIRED" == "true" ]]; then + echo " ❌ No tags found for $DISPLAY_NAME" + exit 1 + else + echo " ⚠️ No tags found, skipping..." + exit 0 + fi +fi +echo " → Resolved to: $RESOLVED_VERSION" + +# build git tag from format +GIT_TAG=$(echo "$TAG_FORMAT" | sed "s/{version}/${RESOLVED_VERSION#v}/") + +# clone repo +REPO_DIR="$TEMP_DIR/${SDK_KEY}" +clone_repo "$REPO" "$GIT_TAG" "$REPO_DIR" + +# find SDK directory +SDK_DIR="" +if [[ -n "$SDK_PATH" ]]; then + # single path specified + SDK_DIR="$REPO_DIR/$SDK_PATH" + if [[ ! -d "$SDK_DIR" ]]; then + echo " ❌ SDK directory not found: $SDK_DIR" + if [[ "$REQUIRED" == "true" ]]; then + exit 1 + else + exit 0 + fi + fi +elif [[ -n "$SDK_PATHS" ]]; then + # multiple paths to try + SDK_DIR=$(find_sdk_directory "$REPO_DIR" $SDK_PATHS) || true + if [[ -z "$SDK_DIR" ]]; then + echo " ⚠️ SDK directory not found in any of: $SDK_PATHS" + echo " → Repo structure:" + ls -la "$REPO_DIR" 2>/dev/null || true + ls -la "$REPO_DIR/packages" 2>/dev/null || true + if [[ "$REQUIRED" == "true" ]]; then + exit 1 + else + exit 0 + fi + fi +else + # default to repo root + SDK_DIR="$REPO_DIR" +fi + +# install dependencies +install_dependencies "$SDK_DIR" "$GENERATOR" + +# source and run the appropriate generator +source "$SCRIPT_DIR/generators/${GENERATOR}.sh" + +case "$GENERATOR" in + typedoc) + generate_typedoc "$SDK_DIR" "$CONFIGS_DIR" + ;; + pydoc) + # build submodules string if exists + SUBMODULES="" + if [[ "$SDK_KEY" == "python-sdk" ]]; then + SUBMODULES="e2b.template.logger e2b.template.readycmd" + fi + generate_pydoc "$SDK_DIR" "$PACKAGES" "$SUBMODULES" + ;; + cli) + generate_cli_docs "$SDK_DIR" + ;; + *) + echo " ❌ Unknown generator: $GENERATOR" + exit 1 + ;; +esac + +# flatten markdown structure (for TypeDoc output) +if [[ -d "$SDK_DIR/sdk_ref" ]]; then + flatten_markdown "$SDK_DIR/sdk_ref" + + # copy to docs repo + copy_to_docs "$SDK_DIR/sdk_ref" \ + "$DOCS_DIR/docs/sdk-reference/$SDK_KEY/$RESOLVED_VERSION" \ + "$DISPLAY_NAME" "$RESOLVED_VERSION" +else + echo " ⚠️ No sdk_ref directory found" +fi + diff --git a/scripts/generators/cli.sh b/scripts/generators/cli.sh new file mode 100755 index 0000000..12fbb12 --- /dev/null +++ b/scripts/generators/cli.sh @@ -0,0 +1,49 @@ +#!/usr/bin/env bash + +# CLI documentation generator +# Builds CLI and generates documentation using commands2md utility + +generate_cli_docs() { + local sdk_dir="$1" + + cd "$sdk_dir" + + # build CLI first + echo " → Building CLI..." + if command -v pnpm &> /dev/null; then + pnpm run build 2>&1 || npx tsup 2>&1 || { + echo " ❌ CLI build failed" + return 1 + } + else + npm run build 2>&1 || npx tsup 2>&1 || { + echo " ❌ CLI build failed" + return 1 + } + fi + + # generate documentation using the CLI's commands2md utility + echo " → Generating documentation..." + mkdir -p sdk_ref + + # the CLI has a special script for generating docs + if [[ -f "scripts/commands2md.js" ]]; then + node scripts/commands2md.js sdk_ref 2>/dev/null || { + # fallback: try running the built CLI + node dist/index.js docs --output sdk_ref 2>/dev/null || true + } + else + # try common doc generation commands + node dist/index.js docs --output sdk_ref 2>/dev/null || \ + node dist/index.js generate-docs --output sdk_ref 2>/dev/null || true + fi + + # rename .md to .mdx + cd sdk_ref + for file in *.md; do + [[ -f "$file" ]] && mv "$file" "${file%.md}.mdx" + done + + return 0 +} + diff --git a/scripts/generators/pydoc.sh b/scripts/generators/pydoc.sh new file mode 100755 index 0000000..0ac2dce --- /dev/null +++ b/scripts/generators/pydoc.sh @@ -0,0 +1,59 @@ +#!/usr/bin/env bash + +# pydoc-markdown generator for Python SDKs +# Generates markdown documentation using pydoc-markdown + +# process generated mdx files (cleanup formatting) +process_mdx() { + local file="$1" + # remove package path display links + sed -i'' -e '/]*>.*<\/a>/d' "${file}" 2>/dev/null || true + # remove h1 headers + sed -i'' -e '/^# /d' "${file}" 2>/dev/null || true + # remove " Objects" suffix from h2 headers + sed -i'' -e '/^## / s/ Objects$//' "${file}" 2>/dev/null || true + # convert h4 to h3 + sed -i'' -e 's/^####/###/' "${file}" 2>/dev/null || true +} + +generate_pydoc() { + local sdk_dir="$1" + local packages="$2" + local submodules="$3" + + cd "$sdk_dir" + mkdir -p sdk_ref + + echo " → Generating documentation for packages..." + + # generate for each main package + for pkg in $packages; do + local output_name="${pkg##*.}" # get last part after dot + echo " → Processing ${pkg}..." + + if poetry run pydoc-markdown -p "$pkg" > "sdk_ref/${output_name}.mdx" 2>/dev/null; then + process_mdx "sdk_ref/${output_name}.mdx" + else + echo " ⚠️ Failed to generate docs for ${pkg}" + rm -f "sdk_ref/${output_name}.mdx" + fi + done + + # generate for submodules if provided + if [[ -n "$submodules" ]]; then + for submod in $submodules; do + local output_name="${submod##*.}" + echo " → Processing ${submod}..." + + if poetry run pydoc-markdown -p "$submod" > "sdk_ref/${output_name}.mdx" 2>/dev/null; then + process_mdx "sdk_ref/${output_name}.mdx" + else + echo " ⚠️ Failed to generate docs for ${submod}" + rm -f "sdk_ref/${output_name}.mdx" + fi + done + fi + + return 0 +} + diff --git a/scripts/generators/typedoc.sh b/scripts/generators/typedoc.sh new file mode 100755 index 0000000..8782630 --- /dev/null +++ b/scripts/generators/typedoc.sh @@ -0,0 +1,33 @@ +#!/usr/bin/env bash + +# TypeDoc generator for JavaScript SDKs +# Generates markdown documentation using TypeDoc with custom theme + +generate_typedoc() { + local sdk_dir="$1" + local configs_dir="$2" + + cd "$sdk_dir" + + # check if repo has its own typedoc config + if [[ -f "typedoc.json" ]]; then + echo " → Running TypeDoc with repo config..." + npx typedoc --plugin typedoc-plugin-markdown \ + --plugin "$configs_dir/typedoc-theme.js" || { + echo " ❌ TypeDoc generation failed" + return 1 + } + else + echo " → Running TypeDoc with default config..." + cp "$configs_dir/typedoc.json" ./typedoc.docs.json + npx typedoc --options ./typedoc.docs.json \ + --plugin typedoc-plugin-markdown \ + --plugin "$configs_dir/typedoc-theme.js" || { + echo " ❌ TypeDoc generation failed" + return 1 + } + fi + + return 0 +} + diff --git a/scripts/lib/common.sh b/scripts/lib/common.sh new file mode 100755 index 0000000..2983a44 --- /dev/null +++ b/scripts/lib/common.sh @@ -0,0 +1,170 @@ +#!/usr/bin/env bash + +# Shared utility functions for SDK documentation generation + +# resolve latest version for a repo and tag pattern +# args: repo, tag_pattern, version +# returns: resolved version (e.g., "v2.9.0") or empty string on failure +resolve_version() { + local repo="$1" + local tag_pattern="$2" + local version="$3" + + if [[ "$version" != "latest" ]]; then + echo "$version" + return 0 + fi + + # escape special characters in tag pattern for grep + local escaped_pattern=$(echo "$tag_pattern" | sed 's/[[\.*^$()+?{|]/\\&/g') + + local resolved + resolved=$(git ls-remote --tags --refs "$repo" 2>/dev/null | \ + grep "refs/tags/${escaped_pattern}" | \ + sed "s/.*refs\/tags\/${tag_pattern}/v/" | \ + sort -V | tail -1) || true + + if [[ -z "$resolved" ]]; then + return 1 + fi + + echo "$resolved" +} + +# clone repo at specific tag with fallback to main branch +# args: repo, git_tag, target_dir +clone_repo() { + local repo="$1" + local git_tag="$2" + local target_dir="$3" + + if [[ -d "$target_dir" ]]; then + return 0 + fi + + echo " → Cloning repo at $git_tag..." + git clone --depth 1 --branch "$git_tag" "$repo" "$target_dir" 2>/dev/null || { + echo " ⚠️ Tag $git_tag not found, trying branch main..." + git clone --depth 1 "$repo" "$target_dir" + } +} + +# find SDK directory from list of possible paths +# args: base_dir, path1, path2, ... +# returns: full path to SDK directory or empty string +find_sdk_directory() { + local base_dir="$1" + shift + + for path in "$@"; do + local full_path="${base_dir}/${path}" + if [[ -d "$full_path" ]]; then + echo "$full_path" + return 0 + fi + done + + return 1 +} + +# install dependencies based on generator type +# args: sdk_dir, generator +install_dependencies() { + local sdk_dir="$1" + local generator="$2" + + cd "$sdk_dir" + + echo " → Installing dependencies..." + case "$generator" in + typedoc) + if command -v pnpm &> /dev/null; then + pnpm install --ignore-scripts 2>&1 || { + echo " ⚠️ pnpm failed, trying npm..." + npm install --legacy-peer-deps 2>&1 + } + else + npm install --legacy-peer-deps 2>&1 + fi + ;; + pydoc) + poetry install --quiet 2>/dev/null || pip install pydoc-markdown + ;; + cli) + if command -v pnpm &> /dev/null; then + pnpm install 2>&1 || npm install 2>&1 + else + npm install 2>&1 + fi + ;; + esac +} + +# flatten markdown files structure for Mintlify +# args: sdk_ref_dir +flatten_markdown() { + local sdk_ref_dir="$1" + + cd "$sdk_ref_dir" + rm -f README.md + + # flatten nested structure: move all md files to root level + find . -mindepth 2 -type f -name "*.md" 2>/dev/null | while read -r file; do + local dir=$(dirname "$file") + local filename=$(basename "$file") + + if [[ "$filename" == "page.md" || "$filename" == "index.md" ]]; then + local module=$(basename "$dir") + mv "$file" "./${module}.md" 2>/dev/null || true + else + mv "$file" "./" 2>/dev/null || true + fi + done + + # remove empty directories + find . -type d -empty -delete 2>/dev/null || true + + # rename .md to .mdx + for file in *.md; do + [[ -f "$file" ]] && mv "$file" "${file%.md}.mdx" + done +} + +# copy generated docs to target directory with reporting +# args: src_dir, target_dir, sdk_name, version +copy_to_docs() { + local src_dir="$1" + local target_dir="$2" + local sdk_name="$3" + local version="$4" + + mkdir -p "$target_dir" + + echo " → Copying files to $target_dir" + if cp "$src_dir"/*.mdx "$target_dir/" 2>/dev/null; then + echo " → Generated files:" + ls -la "$target_dir" + echo " ✅ $sdk_name $version complete" + return 0 + else + echo " ⚠️ No MDX files to copy" + return 1 + fi +} + +# read a value from JSON config using node +# args: json_file, jq_path (e.g., ".sdks.js-sdk.displayName") +json_get() { + local json_file="$1" + local path="$2" + node -e "console.log(require('$json_file')$path || '')" +} + +# read array from JSON config using node +# args: json_file, jq_path (e.g., ".sdks.js-sdk.packages") +json_get_array() { + local json_file="$1" + local path="$2" + node -e "const v = require('$json_file')$path; if(Array.isArray(v)) console.log(v.join(' '));" +} + diff --git a/scripts/sdk-generators/cli.sh b/scripts/sdk-generators/cli.sh deleted file mode 100755 index 248253b..0000000 --- a/scripts/sdk-generators/cli.sh +++ /dev/null @@ -1,97 +0,0 @@ -#!/usr/bin/env bash - -set -euo pipefail - -# CLI Reference Generator -# Usage: ./cli.sh - -VERSION="$1" -TEMP_DIR="$2" -DOCS_DIR="$3" - -echo " → CLI version: $VERSION" - -# determine the git tag to clone -if [[ "$VERSION" == "latest" ]]; then - # get latest CLI tag from e2b repo (format: @e2b/cli@X.Y.Z) - VERSION=$(git ls-remote --tags --refs https://github.com/e2b-dev/e2b.git | \ - grep 'refs/tags/@e2b/cli@' | \ - sed 's/.*refs\/tags\/@e2b\/cli@/v/' | \ - sort -V | tail -1) || true - - if [[ -z "$VERSION" ]]; then - echo " ❌ No CLI tags found" - exit 1 - fi - echo " → Resolved latest to: $VERSION" -fi - -# convert version to git tag format (v2.2.0 -> @e2b/cli@2.2.0) -GIT_TAG="@e2b/cli@${VERSION#v}" - -# clone e2b repo at specific version -REPO_DIR="$TEMP_DIR/e2b-cli" -if [[ ! -d "$REPO_DIR" ]]; then - echo " → Cloning e2b repo at $GIT_TAG..." - git clone --depth 1 --branch "$GIT_TAG" \ - https://github.com/e2b-dev/e2b.git \ - "$REPO_DIR" 2>/dev/null || { - echo " ⚠️ Tag $GIT_TAG not found, trying branch main..." - git clone --depth 1 \ - https://github.com/e2b-dev/e2b.git \ - "$REPO_DIR" - } -fi - -CLI_DIR="$REPO_DIR/packages/cli" -if [[ ! -d "$CLI_DIR" ]]; then - echo " ❌ Directory not found: $CLI_DIR" - echo " → Checking repo structure..." - ls -la "$REPO_DIR" || true - exit 1 -fi - -cd "$CLI_DIR" - -# install dependencies (use pnpm if available, fallback to npm) -echo " → Installing dependencies..." -if command -v pnpm &> /dev/null; then - pnpm install --ignore-scripts 2>&1 || { - echo " ⚠️ pnpm install failed, trying npm..." - npm install --legacy-peer-deps 2>&1 - } -else - npm install --legacy-peer-deps 2>&1 -fi - -# build and generate -echo " → Building CLI..." -npx tsup - -echo " → Generating documentation..." -mkdir -p sdk_ref -NODE_ENV=development node dist/index.js -cmd2md - -# process output - files should already be flat (auth.md, sandbox.md, etc.) -cd sdk_ref - -# rename .md to .mdx -for file in *.md; do - if [[ -f "$file" ]]; then - mv "$file" "${file%.md}.mdx" - fi -done - -# copy to docs repo -TARGET_DIR="$DOCS_DIR/docs/sdk-reference/cli/$VERSION" -mkdir -p "$TARGET_DIR" - -echo " → Copying files to $TARGET_DIR" -cp *.mdx "$TARGET_DIR/" 2>/dev/null || echo " ⚠️ No MDX files to copy" - -# list generated files -echo " → Generated files:" -ls -la "$TARGET_DIR" 2>/dev/null || echo " ⚠️ No files generated" - -echo " ✅ CLI $VERSION complete" - diff --git a/scripts/sdk-generators/code-interpreter-js-sdk.sh b/scripts/sdk-generators/code-interpreter-js-sdk.sh deleted file mode 100755 index ad27ef8..0000000 --- a/scripts/sdk-generators/code-interpreter-js-sdk.sh +++ /dev/null @@ -1,129 +0,0 @@ -#!/usr/bin/env bash - -set -euo pipefail - -# Code Interpreter JavaScript SDK Reference Generator -# Usage: ./code-interpreter-js-sdk.sh - -VERSION="$1" -TEMP_DIR="$2" -DOCS_DIR="$3" - -SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" -CONFIGS_DIR="$SCRIPT_DIR/../configs" - -echo " → Code Interpreter JS SDK version: $VERSION" - -# determine the git tag to clone -if [[ "$VERSION" == "latest" ]]; then - # get latest tag from code-interpreter repo (format: @e2b/code-interpreter@X.Y.Z) - VERSION=$(git ls-remote --tags --refs https://github.com/e2b-dev/code-interpreter.git | \ - grep 'refs/tags/@e2b/code-interpreter@' | \ - sed 's/.*refs\/tags\/@e2b\/code-interpreter@/v/' | \ - sort -V | tail -1) || true - - if [[ -z "$VERSION" ]]; then - echo " ⚠️ No JS SDK tags found, skipping..." - exit 0 - fi - echo " → Resolved latest to: $VERSION" -fi - -# convert version to git tag format -GIT_TAG="@e2b/code-interpreter@${VERSION#v}" - -# clone code-interpreter repo at specific version -REPO_DIR="$TEMP_DIR/code-interpreter" -if [[ ! -d "$REPO_DIR" ]]; then - echo " → Cloning code-interpreter repo at $GIT_TAG..." - git clone --depth 1 --branch "$GIT_TAG" \ - https://github.com/e2b-dev/code-interpreter.git \ - "$REPO_DIR" 2>/dev/null || { - echo " ⚠️ Tag $GIT_TAG not found, trying branch main..." - git clone --depth 1 \ - https://github.com/e2b-dev/code-interpreter.git \ - "$REPO_DIR" - } -fi - -# find JS SDK directory - try common locations -JS_DIR="" -for dir in "$REPO_DIR/js" "$REPO_DIR/packages/js-sdk" "$REPO_DIR/packages/sdk" "$REPO_DIR/js-sdk"; do - if [[ -d "$dir" ]]; then - JS_DIR="$dir" - break - fi -done - -if [[ -z "$JS_DIR" ]]; then - echo " ⚠️ No JS SDK directory found in code-interpreter repo, skipping..." - echo " → Repo structure:" - ls -la "$REPO_DIR" 2>/dev/null || true - exit 0 -fi - -cd "$JS_DIR" - -# install dependencies -echo " → Installing dependencies..." -if command -v pnpm &> /dev/null; then - pnpm install --ignore-scripts 2>&1 || npm install --legacy-peer-deps 2>&1 -else - npm install --legacy-peer-deps 2>&1 -fi - -# check if there's a typedoc config, otherwise use our default -if [[ -f "typedoc.json" ]]; then - echo " → Running TypeDoc with repo config..." - npx typedoc --plugin typedoc-plugin-markdown \ - --plugin "$CONFIGS_DIR/typedoc-theme.js" -else - echo " → Running TypeDoc with default config..." - cp "$CONFIGS_DIR/typedoc.json" ./typedoc.docs.json - npx typedoc --options ./typedoc.docs.json \ - --plugin typedoc-plugin-markdown \ - --plugin "$CONFIGS_DIR/typedoc-theme.js" -fi - -# process generated files - flatten structure for Mintlify -cd sdk_ref - -# remove README if exists -rm -f README.md - -# flatten nested structure -find . -mindepth 2 -type f -name "*.md" | while read -r file; do - dir=$(dirname "$file") - filename=$(basename "$file") - - if [[ "$filename" == "page.md" || "$filename" == "index.md" ]]; then - module=$(basename "$dir") - mv "$file" "./${module}.md" 2>/dev/null || true - else - mv "$file" "./" 2>/dev/null || true - fi -done - -# remove empty directories -find . -type d -empty -delete 2>/dev/null || true - -# rename .md to .mdx -for file in *.md; do - if [[ -f "$file" ]]; then - mv "$file" "${file%.md}.mdx" - fi -done - -# copy to docs repo -TARGET_DIR="$DOCS_DIR/docs/sdk-reference/code-interpreter-js-sdk/$VERSION" -mkdir -p "$TARGET_DIR" - -echo " → Copying files to $TARGET_DIR" -cp *.mdx "$TARGET_DIR/" 2>/dev/null || echo " ⚠️ No MDX files to copy" - -# list generated files -echo " → Generated files:" -ls -la "$TARGET_DIR" 2>/dev/null || echo " ⚠️ No files generated" - -echo " ✅ Code Interpreter JS SDK $VERSION complete" - diff --git a/scripts/sdk-generators/code-interpreter-python-sdk.sh b/scripts/sdk-generators/code-interpreter-python-sdk.sh deleted file mode 100755 index 9149045..0000000 --- a/scripts/sdk-generators/code-interpreter-python-sdk.sh +++ /dev/null @@ -1,110 +0,0 @@ -#!/usr/bin/env bash - -set -euo pipefail - -# Code Interpreter Python SDK Reference Generator -# Usage: ./code-interpreter-python-sdk.sh - -VERSION="$1" -TEMP_DIR="$2" -DOCS_DIR="$3" - -echo " → Code Interpreter Python SDK version: $VERSION" - -# determine the git tag to clone -if [[ "$VERSION" == "latest" ]]; then - # get latest tag from code-interpreter repo (format: e2b-code-interpreter@X.Y.Z) - VERSION=$(git ls-remote --tags --refs https://github.com/e2b-dev/code-interpreter.git | \ - grep 'refs/tags/e2b-code-interpreter@' | \ - sed 's/.*refs\/tags\/e2b-code-interpreter@/v/' | \ - sort -V | tail -1) || true - - if [[ -z "$VERSION" ]]; then - echo " ⚠️ No Python SDK tags found, skipping..." - exit 0 - fi - echo " → Resolved latest to: $VERSION" -fi - -# convert version to git tag format -GIT_TAG="e2b-code-interpreter@${VERSION#v}" - -# clone code-interpreter repo at specific version -REPO_DIR="$TEMP_DIR/code-interpreter-python" -if [[ ! -d "$REPO_DIR" ]]; then - echo " → Cloning code-interpreter repo at $GIT_TAG..." - git clone --depth 1 --branch "$GIT_TAG" \ - https://github.com/e2b-dev/code-interpreter.git \ - "$REPO_DIR" 2>/dev/null || { - echo " ⚠️ Tag $GIT_TAG not found, trying branch main..." - git clone --depth 1 \ - https://github.com/e2b-dev/code-interpreter.git \ - "$REPO_DIR" - } -fi - -# find Python SDK directory - try common locations -PY_DIR="" -for dir in "$REPO_DIR/python" "$REPO_DIR/packages/python-sdk" "$REPO_DIR/packages/python" "$REPO_DIR/python-sdk"; do - if [[ -d "$dir" ]]; then - PY_DIR="$dir" - break - fi -done - -if [[ -z "$PY_DIR" ]]; then - echo " ⚠️ No Python SDK directory found in code-interpreter repo, skipping..." - echo " → Repo structure:" - ls -la "$REPO_DIR" 2>/dev/null || true - ls -la "$REPO_DIR/packages" 2>/dev/null || true - exit 0 -fi - -cd "$PY_DIR" - -# install dependencies -echo " → Installing dependencies with poetry..." -poetry install --quiet 2>/dev/null || pip install pydoc-markdown - -# packages to generate docs for -packages=("e2b_code_interpreter") - -# create output directory -mkdir -p sdk_ref - -# function to process generated markdown -process_mdx() { - local file=$1 - sed -i'' -e '/]*>.*<\/a>/d' "${file}" 2>/dev/null || true - sed -i'' -e '/^# /d' "${file}" 2>/dev/null || true - sed -i'' -e '/^## / s/ Objects$//' "${file}" 2>/dev/null || true - sed -i'' -e 's/^####/###/' "${file}" 2>/dev/null || true -} - -echo " → Generating documentation..." - -for package in "${packages[@]}"; do - echo " → Processing ${package}..." - - poetry run pydoc-markdown -p "${package}" > "sdk_ref/sandbox.mdx" 2>/dev/null || { - echo " ⚠️ Failed to generate docs for ${package}" - continue - } - - process_mdx "sdk_ref/sandbox.mdx" -done - -# copy to docs repo -TARGET_DIR="$DOCS_DIR/docs/sdk-reference/code-interpreter-python-sdk/$VERSION" -mkdir -p "$TARGET_DIR" - -echo " → Copying files to $TARGET_DIR" -cd sdk_ref -cp *.mdx "$TARGET_DIR/" 2>/dev/null || echo " ⚠️ No MDX files to copy" - -# list generated files -echo " → Generated files:" -ls -la "$TARGET_DIR" 2>/dev/null || echo " ⚠️ No files generated" - -echo " ✅ Code Interpreter Python SDK $VERSION complete" - diff --git a/scripts/sdk-generators/desktop-js-sdk.sh b/scripts/sdk-generators/desktop-js-sdk.sh deleted file mode 100755 index 60d14ee..0000000 --- a/scripts/sdk-generators/desktop-js-sdk.sh +++ /dev/null @@ -1,130 +0,0 @@ -#!/usr/bin/env bash - -set -euo pipefail - -# Desktop JavaScript SDK Reference Generator -# Usage: ./desktop-js-sdk.sh - -VERSION="$1" -TEMP_DIR="$2" -DOCS_DIR="$3" - -SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" -CONFIGS_DIR="$SCRIPT_DIR/../configs" - -echo " → Desktop JS SDK version: $VERSION" - -# determine the git tag to clone -if [[ "$VERSION" == "latest" ]]; then - # get latest tag from desktop repo (format: @e2b/desktop@X.Y.Z) - VERSION=$(git ls-remote --tags --refs https://github.com/e2b-dev/desktop.git | \ - grep 'refs/tags/@e2b/desktop@' | \ - sed 's/.*refs\/tags\/@e2b\/desktop@/v/' | \ - sort -V | tail -1) || true - - if [[ -z "$VERSION" ]]; then - echo " ⚠️ No JS SDK tags found, skipping..." - exit 0 - fi - echo " → Resolved latest to: $VERSION" -fi - -# convert version to git tag format -GIT_TAG="@e2b/desktop@${VERSION#v}" - -# clone desktop repo at specific version -REPO_DIR="$TEMP_DIR/desktop" -if [[ ! -d "$REPO_DIR" ]]; then - echo " → Cloning desktop repo at $GIT_TAG..." - git clone --depth 1 --branch "$GIT_TAG" \ - https://github.com/e2b-dev/desktop.git \ - "$REPO_DIR" 2>/dev/null || { - echo " ⚠️ Tag $GIT_TAG not found, trying branch main..." - git clone --depth 1 \ - https://github.com/e2b-dev/desktop.git \ - "$REPO_DIR" - } -fi - -# find JS SDK directory - try common locations -JS_DIR="" -for dir in "$REPO_DIR/js" "$REPO_DIR/packages/js-sdk" "$REPO_DIR/packages/sdk" "$REPO_DIR/js-sdk"; do - if [[ -d "$dir" ]]; then - JS_DIR="$dir" - break - fi -done - -if [[ -z "$JS_DIR" ]]; then - echo " ⚠️ No JS SDK directory found in desktop repo, skipping..." - echo " → Repo structure:" - ls -la "$REPO_DIR" 2>/dev/null || true - ls -la "$REPO_DIR/packages" 2>/dev/null || true - exit 0 -fi - -cd "$JS_DIR" - -# install dependencies -echo " → Installing dependencies..." -if command -v pnpm &> /dev/null; then - pnpm install --ignore-scripts 2>&1 || npm install --legacy-peer-deps 2>&1 -else - npm install --legacy-peer-deps 2>&1 -fi - -# check if there's a typedoc config, otherwise use our default -if [[ -f "typedoc.json" ]]; then - echo " → Running TypeDoc with repo config..." - npx typedoc --plugin typedoc-plugin-markdown \ - --plugin "$CONFIGS_DIR/typedoc-theme.js" -else - echo " → Running TypeDoc with default config..." - cp "$CONFIGS_DIR/typedoc.json" ./typedoc.docs.json - npx typedoc --options ./typedoc.docs.json \ - --plugin typedoc-plugin-markdown \ - --plugin "$CONFIGS_DIR/typedoc-theme.js" -fi - -# process generated files - flatten structure for Mintlify -cd sdk_ref - -# remove README if exists -rm -f README.md - -# flatten nested structure -find . -mindepth 2 -type f -name "*.md" | while read -r file; do - dir=$(dirname "$file") - filename=$(basename "$file") - - if [[ "$filename" == "page.md" || "$filename" == "index.md" ]]; then - module=$(basename "$dir") - mv "$file" "./${module}.md" 2>/dev/null || true - else - mv "$file" "./" 2>/dev/null || true - fi -done - -# remove empty directories -find . -type d -empty -delete 2>/dev/null || true - -# rename .md to .mdx -for file in *.md; do - if [[ -f "$file" ]]; then - mv "$file" "${file%.md}.mdx" - fi -done - -# copy to docs repo -TARGET_DIR="$DOCS_DIR/docs/sdk-reference/desktop-js-sdk/$VERSION" -mkdir -p "$TARGET_DIR" - -echo " → Copying files to $TARGET_DIR" -cp *.mdx "$TARGET_DIR/" 2>/dev/null || echo " ⚠️ No MDX files to copy" - -# list generated files -echo " → Generated files:" -ls -la "$TARGET_DIR" 2>/dev/null || echo " ⚠️ No files generated" - -echo " ✅ Desktop JS SDK $VERSION complete" - diff --git a/scripts/sdk-generators/desktop-python-sdk.sh b/scripts/sdk-generators/desktop-python-sdk.sh deleted file mode 100755 index d91c8e1..0000000 --- a/scripts/sdk-generators/desktop-python-sdk.sh +++ /dev/null @@ -1,110 +0,0 @@ -#!/usr/bin/env bash - -set -euo pipefail - -# Desktop Python SDK Reference Generator -# Usage: ./desktop-python-sdk.sh - -VERSION="$1" -TEMP_DIR="$2" -DOCS_DIR="$3" - -echo " → Desktop Python SDK version: $VERSION" - -# determine the git tag to clone -if [[ "$VERSION" == "latest" ]]; then - # get latest tag from desktop repo (format: e2b-desktop@X.Y.Z) - VERSION=$(git ls-remote --tags --refs https://github.com/e2b-dev/desktop.git | \ - grep 'refs/tags/e2b-desktop@' | \ - sed 's/.*refs\/tags\/e2b-desktop@/v/' | \ - sort -V | tail -1) || true - - if [[ -z "$VERSION" ]]; then - echo " ⚠️ No Python SDK tags found, skipping..." - exit 0 - fi - echo " → Resolved latest to: $VERSION" -fi - -# convert version to git tag format -GIT_TAG="e2b-desktop@${VERSION#v}" - -# clone desktop repo at specific version -REPO_DIR="$TEMP_DIR/desktop-python" -if [[ ! -d "$REPO_DIR" ]]; then - echo " → Cloning desktop repo at $GIT_TAG..." - git clone --depth 1 --branch "$GIT_TAG" \ - https://github.com/e2b-dev/desktop.git \ - "$REPO_DIR" 2>/dev/null || { - echo " ⚠️ Tag $GIT_TAG not found, trying branch main..." - git clone --depth 1 \ - https://github.com/e2b-dev/desktop.git \ - "$REPO_DIR" - } -fi - -# find Python SDK directory - try common locations -PY_DIR="" -for dir in "$REPO_DIR/python" "$REPO_DIR/packages/python-sdk" "$REPO_DIR/packages/python" "$REPO_DIR/python-sdk"; do - if [[ -d "$dir" ]]; then - PY_DIR="$dir" - break - fi -done - -if [[ -z "$PY_DIR" ]]; then - echo " ⚠️ No Python SDK directory found in desktop repo, skipping..." - echo " → Repo structure:" - ls -la "$REPO_DIR" 2>/dev/null || true - ls -la "$REPO_DIR/packages" 2>/dev/null || true - exit 0 -fi - -cd "$PY_DIR" - -# install dependencies -echo " → Installing dependencies with poetry..." -poetry install --quiet 2>/dev/null || pip install pydoc-markdown - -# packages to generate docs for -packages=("e2b_desktop") - -# create output directory -mkdir -p sdk_ref - -# function to process generated markdown -process_mdx() { - local file=$1 - sed -i'' -e '/]*>.*<\/a>/d' "${file}" 2>/dev/null || true - sed -i'' -e '/^# /d' "${file}" 2>/dev/null || true - sed -i'' -e '/^## / s/ Objects$//' "${file}" 2>/dev/null || true - sed -i'' -e 's/^####/###/' "${file}" 2>/dev/null || true -} - -echo " → Generating documentation..." - -for package in "${packages[@]}"; do - echo " → Processing ${package}..." - - poetry run pydoc-markdown -p "${package}" > "sdk_ref/sandbox.mdx" 2>/dev/null || { - echo " ⚠️ Failed to generate docs for ${package}" - continue - } - - process_mdx "sdk_ref/sandbox.mdx" -done - -# copy to docs repo -TARGET_DIR="$DOCS_DIR/docs/sdk-reference/desktop-python-sdk/$VERSION" -mkdir -p "$TARGET_DIR" - -echo " → Copying files to $TARGET_DIR" -cd sdk_ref -cp *.mdx "$TARGET_DIR/" 2>/dev/null || echo " ⚠️ No MDX files to copy" - -# list generated files -echo " → Generated files:" -ls -la "$TARGET_DIR" 2>/dev/null || echo " ⚠️ No files generated" - -echo " ✅ Desktop Python SDK $VERSION complete" - diff --git a/scripts/sdk-generators/js-sdk.sh b/scripts/sdk-generators/js-sdk.sh deleted file mode 100755 index a60ae40..0000000 --- a/scripts/sdk-generators/js-sdk.sh +++ /dev/null @@ -1,123 +0,0 @@ -#!/usr/bin/env bash - -set -euo pipefail - -# JavaScript SDK Reference Generator -# Usage: ./js-sdk.sh - -VERSION="$1" -TEMP_DIR="$2" -DOCS_DIR="$3" - -SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" -CONFIGS_DIR="$SCRIPT_DIR/../configs" - -echo " → JS SDK version: $VERSION" - -# determine the git tag to clone -if [[ "$VERSION" == "latest" ]]; then - # get latest tag from e2b repo (format: e2b@X.Y.Z) - VERSION=$(git ls-remote --tags --refs https://github.com/e2b-dev/e2b.git | \ - grep 'refs/tags/e2b@' | \ - sed 's/.*refs\/tags\/e2b@/v/' | \ - sort -V | tail -1) || true - - if [[ -z "$VERSION" ]]; then - echo " ❌ No JS SDK tags found" - exit 1 - fi - echo " → Resolved latest to: $VERSION" -fi - -# convert version to git tag format (v2.9.0 -> e2b@2.9.0) -GIT_TAG="e2b@${VERSION#v}" - -# clone e2b repo at specific version -REPO_DIR="$TEMP_DIR/e2b-js-sdk" -if [[ ! -d "$REPO_DIR" ]]; then - echo " → Cloning e2b repo at $GIT_TAG..." - git clone --depth 1 --branch "$GIT_TAG" \ - https://github.com/e2b-dev/e2b.git \ - "$REPO_DIR" 2>/dev/null || { - echo " ⚠️ Tag $GIT_TAG not found, trying branch main..." - git clone --depth 1 \ - https://github.com/e2b-dev/e2b.git \ - "$REPO_DIR" - } -fi - -JS_SDK_DIR="$REPO_DIR/packages/js-sdk" -if [[ ! -d "$JS_SDK_DIR" ]]; then - echo " ❌ Directory not found: $JS_SDK_DIR" - echo " → Checking repo structure..." - ls -la "$REPO_DIR" || true - exit 1 -fi - -cd "$JS_SDK_DIR" - -# install dependencies (use pnpm if available, fallback to npm) -echo " → Installing dependencies..." -if command -v pnpm &> /dev/null; then - pnpm install --ignore-scripts 2>&1 || { - echo " ⚠️ pnpm install failed, trying npm..." - npm install --legacy-peer-deps 2>&1 - } -else - npm install --legacy-peer-deps 2>&1 -fi - -# copy typedoc config to temp location -cp "$CONFIGS_DIR/typedoc.json" ./typedoc.docs.json - -# generate using TypeDoc -echo " → Running TypeDoc..." -npx typedoc --options ./typedoc.docs.json \ - --plugin typedoc-plugin-markdown \ - --plugin "$CONFIGS_DIR/typedoc-theme.js" - -# process generated files - flatten structure for Mintlify -cd sdk_ref - -# remove README if exists -rm -f README.md - -# flatten nested structure: move all files to root level -find . -mindepth 2 -type f -name "*.md" | while read -r file; do - # get the parent directory name as module name - dir=$(dirname "$file") - filename=$(basename "$file") - - if [[ "$filename" == "page.md" || "$filename" == "index.md" ]]; then - # use directory name as file name - module=$(basename "$dir") - mv "$file" "./${module}.md" 2>/dev/null || true - else - # move file to root - mv "$file" "./" 2>/dev/null || true - fi -done - -# remove empty directories -find . -type d -empty -delete 2>/dev/null || true - -# rename .md to .mdx -for file in *.md; do - if [[ -f "$file" ]]; then - mv "$file" "${file%.md}.mdx" - fi -done - -# copy to docs repo -TARGET_DIR="$DOCS_DIR/docs/sdk-reference/js-sdk/$VERSION" -mkdir -p "$TARGET_DIR" - -echo " → Copying files to $TARGET_DIR" -cp *.mdx "$TARGET_DIR/" 2>/dev/null || echo " ⚠️ No MDX files to copy" - -# list generated files -echo " → Generated files:" -ls -la "$TARGET_DIR" 2>/dev/null || echo " ⚠️ No files generated" - -echo " ✅ JS SDK $VERSION complete" - diff --git a/scripts/sdk-generators/python-sdk.sh b/scripts/sdk-generators/python-sdk.sh deleted file mode 100755 index fd24069..0000000 --- a/scripts/sdk-generators/python-sdk.sh +++ /dev/null @@ -1,114 +0,0 @@ -#!/usr/bin/env bash - -set -euo pipefail - -# Python SDK Reference Generator -# Usage: ./python-sdk.sh - -VERSION="$1" -TEMP_DIR="$2" -DOCS_DIR="$3" - -echo " → Python SDK version: $VERSION" - -# determine the git tag to clone -if [[ "$VERSION" == "latest" ]]; then - # get latest tag from e2b repo (format: e2b@X.Y.Z) - VERSION=$(git ls-remote --tags --refs https://github.com/e2b-dev/e2b.git | \ - grep 'refs/tags/e2b@' | \ - sed 's/.*refs\/tags\/e2b@/v/' | \ - sort -V | tail -1) || true - - if [[ -z "$VERSION" ]]; then - echo " ❌ No Python SDK tags found" - exit 1 - fi - echo " → Resolved latest to: $VERSION" -fi - -# convert version to git tag format (v2.9.0 -> e2b@2.9.0) -GIT_TAG="e2b@${VERSION#v}" - -# clone e2b repo at specific version -REPO_DIR="$TEMP_DIR/e2b-python-sdk" -if [[ ! -d "$REPO_DIR" ]]; then - echo " → Cloning e2b repo at $GIT_TAG..." - git clone --depth 1 --branch "$GIT_TAG" \ - https://github.com/e2b-dev/e2b.git \ - "$REPO_DIR" 2>/dev/null || { - echo " ⚠️ Tag $GIT_TAG not found, trying branch main..." - git clone --depth 1 \ - https://github.com/e2b-dev/e2b.git \ - "$REPO_DIR" - } -fi - -cd "$REPO_DIR/packages/python-sdk" - -# install poetry and dependencies -echo " → Installing dependencies with poetry..." -poetry install --quiet 2>/dev/null || pip install pydoc-markdown - -# packages to generate docs for -packages=("sandbox_sync" "sandbox_async" "exceptions" "template" "template_sync" "template_async") -template_submodules=("logger" "readycmd") - -# create output directory -mkdir -p sdk_ref - -# function to process generated markdown -process_mdx() { - local file=$1 - # remove package path display - sed -i'' -e '/]*>.*<\/a>/d' "${file}" 2>/dev/null || true - # remove empty hyperlinks - sed -i'' -e '/^# /d' "${file}" 2>/dev/null || true - # remove " Objects" from lines starting with "##" - sed -i'' -e '/^## / s/ Objects$//' "${file}" 2>/dev/null || true - # replace lines starting with "####" with "###" - sed -i'' -e 's/^####/###/' "${file}" 2>/dev/null || true -} - -echo " → Generating documentation for packages..." - -for package in "${packages[@]}"; do - echo " → Processing e2b.${package}..." - - # generate raw SDK reference markdown file - poetry run pydoc-markdown -p "e2b.${package}" > "sdk_ref/${package}.mdx" 2>/dev/null || { - echo " ⚠️ Failed to generate docs for ${package}" - continue - } - - # process the generated markdown - process_mdx "sdk_ref/${package}.mdx" -done - -# generate documentation for template submodules -for submodule in "${template_submodules[@]}"; do - echo " → Processing e2b.template.${submodule}..." - - # generate raw SDK reference markdown file - poetry run pydoc-markdown -p "e2b.template.${submodule}" > "sdk_ref/${submodule}.mdx" 2>/dev/null || { - echo " ⚠️ Failed to generate docs for template.${submodule}" - continue - } - - # process the generated markdown - process_mdx "sdk_ref/${submodule}.mdx" -done - -# copy to docs repo -TARGET_DIR="$DOCS_DIR/docs/sdk-reference/python-sdk/$VERSION" -mkdir -p "$TARGET_DIR" - -echo " → Copying files to $TARGET_DIR" -cd sdk_ref -cp *.mdx "$TARGET_DIR/" 2>/dev/null || echo " ⚠️ No MDX files to copy" - -# list generated files -echo " → Generated files:" -ls -la "$TARGET_DIR" 2>/dev/null || echo " ⚠️ No files generated" - -echo " ✅ Python SDK $VERSION complete" - diff --git a/scripts/sdks.json b/scripts/sdks.json new file mode 100644 index 0000000..bf8e638 --- /dev/null +++ b/scripts/sdks.json @@ -0,0 +1,95 @@ +{ + "sdks": { + "cli": { + "displayName": "CLI", + "icon": "terminal", + "order": 1, + "repo": "https://github.com/e2b-dev/e2b.git", + "tagPattern": "@e2b/cli@", + "tagFormat": "@e2b/cli@{version}", + "sdkPath": "packages/cli", + "generator": "cli", + "required": true + }, + "js-sdk": { + "displayName": "JavaScript SDK", + "icon": "square-js", + "order": 2, + "repo": "https://github.com/e2b-dev/e2b.git", + "tagPattern": "e2b@", + "tagFormat": "e2b@{version}", + "sdkPath": "packages/js-sdk", + "generator": "typedoc", + "required": true + }, + "python-sdk": { + "displayName": "Python SDK", + "icon": "python", + "order": 3, + "repo": "https://github.com/e2b-dev/e2b.git", + "tagPattern": "e2b@", + "tagFormat": "e2b@{version}", + "sdkPath": "packages/python-sdk", + "generator": "pydoc", + "required": true, + "packages": [ + "e2b.sandbox_sync", + "e2b.sandbox_async", + "e2b.exceptions", + "e2b.template", + "e2b.template_sync", + "e2b.template_async" + ], + "submodules": { + "e2b.template": ["logger", "readycmd"] + } + }, + "code-interpreter-js-sdk": { + "displayName": "Code Interpreter JavaScript SDK", + "icon": "square-js", + "order": 4, + "repo": "https://github.com/e2b-dev/code-interpreter.git", + "tagPattern": "@e2b/code-interpreter@", + "tagFormat": "@e2b/code-interpreter@{version}", + "sdkPaths": ["js", "packages/js-sdk", "packages/sdk", "js-sdk"], + "generator": "typedoc", + "required": false + }, + "code-interpreter-python-sdk": { + "displayName": "Code Interpreter Python SDK", + "icon": "python", + "order": 5, + "repo": "https://github.com/e2b-dev/code-interpreter.git", + "tagPattern": "e2b-code-interpreter@", + "tagFormat": "e2b-code-interpreter@{version}", + "sdkPaths": ["python", "packages/python-sdk", "packages/python", "python-sdk"], + "generator": "pydoc", + "required": false, + "packages": ["e2b_code_interpreter"] + }, + "desktop-js-sdk": { + "displayName": "Desktop JavaScript SDK", + "icon": "square-js", + "order": 6, + "repo": "https://github.com/e2b-dev/desktop.git", + "tagPattern": "@e2b/desktop@", + "tagFormat": "@e2b/desktop@{version}", + "sdkPaths": ["js", "packages/js-sdk", "packages/sdk", "js-sdk"], + "generator": "typedoc", + "required": false + }, + "desktop-python-sdk": { + "displayName": "Desktop Python SDK", + "icon": "python", + "order": 7, + "repo": "https://github.com/e2b-dev/desktop.git", + "tagPattern": "e2b-desktop@", + "tagFormat": "e2b-desktop@{version}", + "sdkPaths": ["python", "packages/python-sdk", "packages/python", "python-sdk"], + "generator": "pydoc", + "required": false, + "packages": ["e2b_desktop"] + } + } +} + From f75a36ff3a3fffe241221e9617ebafa91cabf5a8 Mon Sep 17 00:00:00 2001 From: ben-fornefeld Date: Wed, 7 Jan 2026 13:15:06 +0100 Subject: [PATCH 03/39] Enhance SDK navigation and styling - Updated `.gitignore` to include `sdk_navigation.json` for generated SDK navigation. - Added new styles for version switcher in `style.css`, improving UI for SDK and version selection. - Modified `generate-sdk-nav.js` to group SDKs by family, enhancing navigation structure. - Updated SDK configurations in `sdks.json` to include family and language attributes for better organization. - Improved CLI and Python documentation generation scripts for consistency and added frontmatter to markdown files. --- .gitignore | 5 +- scripts/generate-sdk-nav.js | 140 ++++++++++++++++++++++++++++-------- scripts/generators/cli.sh | 22 +++--- scripts/generators/pydoc.sh | 10 +-- scripts/lib/common.sh | 40 +++++++++-- scripts/merge-sdk-nav.js | 13 ++-- scripts/sdks.json | 40 +++++++---- style.css | 32 +++++++++ 8 files changed, 233 insertions(+), 69 deletions(-) diff --git a/.gitignore b/.gitignore index 3b21614..ac322bc 100644 --- a/.gitignore +++ b/.gitignore @@ -1,4 +1,7 @@ .idea .DS_Store -node_modules \ No newline at end of file +node_modules + +# Generated SDK navigation (intermediate file) +sdk_navigation.json \ No newline at end of file diff --git a/scripts/generate-sdk-nav.js b/scripts/generate-sdk-nav.js index 7299cfe..692df39 100644 --- a/scripts/generate-sdk-nav.js +++ b/scripts/generate-sdk-nav.js @@ -36,7 +36,10 @@ function loadSdkConfigs() { { name: sdk.displayName, icon: sdk.icon, - order: sdk.order + order: sdk.order, + family: sdk.family, + language: sdk.language, + standalone: sdk.standalone } ]) ); @@ -52,8 +55,14 @@ function loadSdkConfigs() { function getVersions(sdkDir) { try { const entries = fs.readdirSync(sdkDir, { withFileTypes: true }); + + // accept both "v2.9.0" and "2.9.0" formats const versions = entries - .filter(e => e.isDirectory() && e.name.startsWith('v')) + .filter(e => { + if (!e.isDirectory()) return false; + // match version patterns: v1.2.3 or 1.2.3 + return /^v?\d+\.\d+\.\d+/.test(e.name); + }) .map(e => e.name); // sort versions (latest first) @@ -93,6 +102,7 @@ function getModules(versionDir) { /** * Generate navigation structure for all SDKs + * Groups SDKs by family (e.g., sdk, code-interpreter, desktop) */ function generateNavigation() { const SDK_CONFIGS = loadSdkConfigs(); @@ -104,47 +114,93 @@ function generateNavigation() { return navigation; } - // process each SDK from config + // group SDKs by family + const families = {}; for (const [sdkKey, config] of Object.entries(SDK_CONFIGS)) { - const sdkDir = path.join(SDK_REF_DIR, sdkKey); + const family = config.family || sdkKey; + if (!families[family]) { + families[family] = { + name: getFamilyDisplayName(family), + icon: getFirstIcon(family, config.icon), + order: Math.min(...[config.order]), // use lowest order in family + standalone: config.standalone || false, + languages: [] + }; + } + // update order to be the minimum across all SDKs in family + families[family].order = Math.min(families[family].order, config.order); + families[family].languages.push({ key: sdkKey, config }); + } + + // process each family + for (const [familyKey, family] of Object.entries(families)) { + // get versions from first language (they should all match) + const firstLang = family.languages[0]; + const firstSdkDir = path.join(SDK_REF_DIR, firstLang.key); - if (!fs.existsSync(sdkDir)) { - console.log(` Skipping ${sdkKey} (not found)`); + if (!fs.existsSync(firstSdkDir)) { + console.log(` Skipping ${familyKey} (not found)`); continue; } - const versions = getVersions(sdkDir); + const versions = getVersions(firstSdkDir); if (versions.length === 0) { - console.log(` Skipping ${sdkKey} (no versions)`); + console.log(` Skipping ${familyKey} (no versions)`); continue; } - console.log(` Found ${sdkKey}: ${versions.length} versions`); + console.log(` Found ${familyKey}: ${versions.length} versions, ${family.languages.length} languages`); + // create dropdown for this family const dropdown = { - dropdown: config.name, - icon: config.icon, + dropdown: family.name, + icon: family.icon, versions: versions.map((version, index) => { - const versionDir = path.join(sdkDir, version); - const modules = getModules(versionDir); + const displayVersion = version.startsWith('v') ? version : `v${version}`; + + // standalone SDKs (like CLI) - pages directly under version + if (family.standalone) { + const versionDir = path.join(firstSdkDir, version); + const modules = getModules(versionDir); + + return { + version: displayVersion, + default: index === 0, + pages: modules.map(module => + `docs/sdk-reference/${firstLang.key}/${version}/${module}` + ) + }; + } + + // multi-language SDKs - groups for each language + const groups = family.languages.map(lang => { + const sdkDir = path.join(SDK_REF_DIR, lang.key); + const versionDir = path.join(sdkDir, version); + + if (!fs.existsSync(versionDir)) { + return null; + } + + const modules = getModules(versionDir); + + return { + group: lang.config.language || lang.config.name, + icon: lang.config.icon, // add icon for the language + pages: modules.map(module => + `docs/sdk-reference/${lang.key}/${version}/${module}` + ) + }; + }).filter(Boolean); return { - // mark first version as @latest - version: index === 0 ? `${version}@latest` : version, - groups: [ - { - group: `${config.name} ${version}`, - pages: modules.map(module => - `docs/sdk-reference/${sdkKey}/${version}/${module}` - ) - } - ] + version: displayVersion, + default: index === 0, + groups }; }) }; - // store with order for sorting - navigation.push({ ...dropdown, _order: config.order }); + navigation.push({ ...dropdown, _order: family.order }); } // sort by order and remove _order field @@ -153,6 +209,29 @@ function generateNavigation() { .map(({ _order, ...rest }) => rest); } +/** + * Get display name for SDK family + */ +function getFamilyDisplayName(family) { + const names = { + 'cli': 'CLI', + 'sdk': 'SDK', + 'code-interpreter': 'Code Interpreter SDK', + 'desktop': 'Desktop SDK' + }; + return names[family] || family; +} + +/** + * Get icon for SDK family (prefer brackets-curly for multi-language SDKs) + */ +function getFirstIcon(family, defaultIcon) { + if (family === 'sdk' || family === 'code-interpreter' || family === 'desktop') { + return 'brackets-curly'; + } + return defaultIcon; +} + /** * Main entry point */ @@ -174,9 +253,14 @@ function main() { // summary for (const sdk of navigation) { - const totalPages = sdk.versions.reduce((sum, v) => - sum + v.groups.reduce((s, g) => s + g.pages.length, 0), 0 - ); + const totalPages = sdk.versions.reduce((sum, v) => { + if (v.pages) { + return sum + v.pages.length; + } else if (v.groups) { + return sum + v.groups.reduce((s, g) => s + g.pages.length, 0); + } + return sum; + }, 0); console.log(` - ${sdk.dropdown}: ${sdk.versions.length} versions, ${totalPages} pages`); } } diff --git a/scripts/generators/cli.sh b/scripts/generators/cli.sh index 12fbb12..4ee997e 100755 --- a/scripts/generators/cli.sh +++ b/scripts/generators/cli.sh @@ -26,23 +26,19 @@ generate_cli_docs() { echo " → Generating documentation..." mkdir -p sdk_ref - # the CLI has a special script for generating docs - if [[ -f "scripts/commands2md.js" ]]; then - node scripts/commands2md.js sdk_ref 2>/dev/null || { - # fallback: try running the built CLI - node dist/index.js docs --output sdk_ref 2>/dev/null || true - } - else - # try common doc generation commands - node dist/index.js docs --output sdk_ref 2>/dev/null || \ - node dist/index.js generate-docs --output sdk_ref 2>/dev/null || true - fi + # the CLI uses -cmd2md flag to generate markdown docs + NODE_ENV=development node dist/index.js -cmd2md 2>&1 || { + echo " ⚠️ CLI doc generation failed" + return 1 + } - # rename .md to .mdx + # rename .md to .mdx (if any .md files exist) cd sdk_ref + shopt -s nullglob for file in *.md; do - [[ -f "$file" ]] && mv "$file" "${file%.md}.mdx" + mv "$file" "${file%.md}.mdx" done + shopt -u nullglob return 0 } diff --git a/scripts/generators/pydoc.sh b/scripts/generators/pydoc.sh index 0ac2dce..e7a51e0 100755 --- a/scripts/generators/pydoc.sh +++ b/scripts/generators/pydoc.sh @@ -6,14 +6,16 @@ # process generated mdx files (cleanup formatting) process_mdx() { local file="$1" + local tmp_file="${file}.tmp" + # remove package path display links - sed -i'' -e '/]*>.*<\/a>/d' "${file}" 2>/dev/null || true + sed '/]*>.*<\/a>/d' "${file}" > "${tmp_file}" && mv "${tmp_file}" "${file}" # remove h1 headers - sed -i'' -e '/^# /d' "${file}" 2>/dev/null || true + sed '/^# /d' "${file}" > "${tmp_file}" && mv "${tmp_file}" "${file}" # remove " Objects" suffix from h2 headers - sed -i'' -e '/^## / s/ Objects$//' "${file}" 2>/dev/null || true + sed '/^## / s/ Objects$//' "${file}" > "${tmp_file}" && mv "${tmp_file}" "${file}" # convert h4 to h3 - sed -i'' -e 's/^####/###/' "${file}" 2>/dev/null || true + sed 's/^####/###/' "${file}" > "${tmp_file}" && mv "${tmp_file}" "${file}" } generate_pydoc() { diff --git a/scripts/lib/common.sh b/scripts/lib/common.sh index 2983a44..9bfe66b 100755 --- a/scripts/lib/common.sh +++ b/scripts/lib/common.sh @@ -15,13 +15,13 @@ resolve_version() { return 0 fi - # escape special characters in tag pattern for grep - local escaped_pattern=$(echo "$tag_pattern" | sed 's/[[\.*^$()+?{|]/\\&/g') + # escape special characters in tag pattern for sed (needs different escaping than grep) + local sed_escaped_pattern=$(echo "$tag_pattern" | sed 's/[\/&@]/\\&/g') local resolved resolved=$(git ls-remote --tags --refs "$repo" 2>/dev/null | \ - grep "refs/tags/${escaped_pattern}" | \ - sed "s/.*refs\/tags\/${tag_pattern}/v/" | \ + grep "refs/tags/${tag_pattern}" | \ + sed "s|.*refs/tags/${sed_escaped_pattern}|v|" | \ sort -V | tail -1) || true if [[ -z "$resolved" ]]; then @@ -124,9 +124,37 @@ flatten_markdown() { # remove empty directories find . -type d -empty -delete 2>/dev/null || true - # rename .md to .mdx + # rename .md to .mdx and add frontmatter (if any .md files exist) + shopt -s nullglob for file in *.md; do - [[ -f "$file" ]] && mv "$file" "${file%.md}.mdx" + local mdx_file="${file%.md}.mdx" + # add frontmatter to disable TOC for SDK reference pages + { + echo "---" + echo "sidebarTitle: \"$(basename "$file" .md)\"" + echo "toc: false" + echo "---" + echo "" + cat "$file" + } > "$mdx_file" + rm "$file" + done + shopt -u nullglob + + # add frontmatter to existing .mdx files (from pydoc generator) + for file in *.mdx; do + if ! head -n1 "$file" | grep -q "^---$"; then + local tmp_file="${file}.tmp" + { + echo "---" + echo "sidebarTitle: \"$(basename "$file" .mdx)\"" + echo "toc: false" + echo "---" + echo "" + cat "$file" + } > "$tmp_file" + mv "$tmp_file" "$file" + fi done } diff --git a/scripts/merge-sdk-nav.js b/scripts/merge-sdk-nav.js index 87bc05c..18a1dd3 100644 --- a/scripts/merge-sdk-nav.js +++ b/scripts/merge-sdk-nav.js @@ -5,7 +5,7 @@ * * This script merges the generated sdk_navigation.json into the docs.json * Mintlify configuration. It finds the "SDK Reference" anchor and replaces - * its dropdowns with the generated navigation. + * its dropdowns with the generated navigation, enabling SDK and version selection. */ const fs = require('fs'); @@ -63,9 +63,14 @@ function main() { // summary for (const dropdown of validDropdowns) { const totalVersions = dropdown.versions.length; - const totalPages = dropdown.versions.reduce((sum, v) => - sum + v.groups.reduce((s, g) => s + g.pages.length, 0), 0 - ); + const totalPages = dropdown.versions.reduce((sum, v) => { + if (v.pages) { + return sum + v.pages.length; + } else if (v.groups) { + return sum + v.groups.reduce((s, g) => s + g.pages.length, 0); + } + return sum; + }, 0); console.log(` - ${dropdown.dropdown}: ${totalVersions} versions, ${totalPages} pages`); } } diff --git a/scripts/sdks.json b/scripts/sdks.json index bf8e638..6c82756 100644 --- a/scripts/sdks.json +++ b/scripts/sdks.json @@ -3,7 +3,9 @@ "cli": { "displayName": "CLI", "icon": "terminal", - "order": 1, + "order": 4, + "family": "cli", + "standalone": true, "repo": "https://github.com/e2b-dev/e2b.git", "tagPattern": "@e2b/cli@", "tagFormat": "@e2b/cli@{version}", @@ -12,9 +14,11 @@ "required": true }, "js-sdk": { - "displayName": "JavaScript SDK", + "displayName": "JavaScript", "icon": "square-js", - "order": 2, + "order": 1, + "family": "sdk", + "language": "JavaScript", "repo": "https://github.com/e2b-dev/e2b.git", "tagPattern": "e2b@", "tagFormat": "e2b@{version}", @@ -23,9 +27,11 @@ "required": true }, "python-sdk": { - "displayName": "Python SDK", + "displayName": "Python", "icon": "python", - "order": 3, + "order": 1, + "family": "sdk", + "language": "Python", "repo": "https://github.com/e2b-dev/e2b.git", "tagPattern": "e2b@", "tagFormat": "e2b@{version}", @@ -45,9 +51,11 @@ } }, "code-interpreter-js-sdk": { - "displayName": "Code Interpreter JavaScript SDK", + "displayName": "JavaScript", "icon": "square-js", - "order": 4, + "order": 2, + "family": "code-interpreter", + "language": "JavaScript", "repo": "https://github.com/e2b-dev/code-interpreter.git", "tagPattern": "@e2b/code-interpreter@", "tagFormat": "@e2b/code-interpreter@{version}", @@ -56,9 +64,11 @@ "required": false }, "code-interpreter-python-sdk": { - "displayName": "Code Interpreter Python SDK", + "displayName": "Python", "icon": "python", - "order": 5, + "order": 2, + "family": "code-interpreter", + "language": "Python", "repo": "https://github.com/e2b-dev/code-interpreter.git", "tagPattern": "e2b-code-interpreter@", "tagFormat": "e2b-code-interpreter@{version}", @@ -68,9 +78,11 @@ "packages": ["e2b_code_interpreter"] }, "desktop-js-sdk": { - "displayName": "Desktop JavaScript SDK", + "displayName": "JavaScript", "icon": "square-js", - "order": 6, + "order": 3, + "family": "desktop", + "language": "JavaScript", "repo": "https://github.com/e2b-dev/desktop.git", "tagPattern": "@e2b/desktop@", "tagFormat": "@e2b/desktop@{version}", @@ -79,9 +91,11 @@ "required": false }, "desktop-python-sdk": { - "displayName": "Desktop Python SDK", + "displayName": "Python", "icon": "python", - "order": 7, + "order": 3, + "family": "desktop", + "language": "Python", "repo": "https://github.com/e2b-dev/desktop.git", "tagPattern": "e2b-desktop@", "tagFormat": "e2b-desktop@{version}", diff --git a/style.css b/style.css index 490a779..63bba09 100644 --- a/style.css +++ b/style.css @@ -61,3 +61,35 @@ code { .dark\:text-sky-200:is(.dark *) { color: rgb(255, 183, 102) !important; } + +/* Version switcher styles - subtle highlight */ +#sidebar ul:last-child li button, +#sidebar ul:last-child li select { + background-color: rgba(255, 136, 0, 0.1) !important; /* 10% orange tint */ + color: #ff8800 !important; /* Orange text */ + border: 1px solid rgba(255, 136, 0, 0.3) !important; /* 30% orange border */ + border-radius: 6px !important; + padding: 0.5rem 1rem !important; + font-weight: 500 !important; + transition: all 0.2s ease !important; +} + +#sidebar ul:last-child li button:hover, +#sidebar ul:last-child li select:hover { + background-color: rgba(255, 136, 0, 0.15) !important; /* Slightly darker on hover */ + border-color: rgba(255, 136, 0, 0.5) !important; +} + +/* Dark mode version switcher */ +.dark #sidebar ul:last-child li button, +.dark #sidebar ul:last-child li select { + background-color: rgba(255, 136, 0, 0.15) !important; /* Slightly more visible in dark */ + color: #ffaa44 !important; /* Lighter orange for contrast */ + border-color: rgba(255, 136, 0, 0.4) !important; +} + +.dark #sidebar ul:last-child li button:hover, +.dark #sidebar ul:last-child li select:hover { + background-color: rgba(255, 136, 0, 0.25) !important; + border-color: rgba(255, 136, 0, 0.6) !important; +} From 192768707ba570e6edb1abb00c57a3610bd7e388 Mon Sep 17 00:00:00 2001 From: ben-fornefeld Date: Wed, 7 Jan 2026 13:53:25 +0100 Subject: [PATCH 04/39] cleanup --- .github/workflows/sdk-reference-sync.yml | 6 - scripts/generate-sdk-nav.js | 149 +++-------------------- scripts/generate-sdk-reference.sh | 19 +-- scripts/generate-sdk.sh | 28 +---- scripts/generators/cli.sh | 7 -- scripts/generators/pydoc.sh | 12 +- scripts/generators/typedoc.sh | 4 - scripts/lib/common.sh | 42 +------ scripts/merge-sdk-nav.js | 23 +--- scripts/sdks.json | 36 ++---- 10 files changed, 33 insertions(+), 293 deletions(-) diff --git a/.github/workflows/sdk-reference-sync.yml b/.github/workflows/sdk-reference-sync.yml index 6b992d0..d1055a8 100644 --- a/.github/workflows/sdk-reference-sync.yml +++ b/.github/workflows/sdk-reference-sync.yml @@ -67,17 +67,14 @@ jobs: - name: Determine SDK and Version id: params run: | - # handle workflow_dispatch if [[ "${{ github.event_name }}" == "workflow_dispatch" ]]; then SDK="${{ github.event.inputs.sdk }}" VERSION="${{ github.event.inputs.version }}" - # handle repository_dispatch from e2b repo elif [[ "${{ github.event_name }}" == "repository_dispatch" ]]; then SDK="${{ github.event.client_payload.sdk }}" VERSION="${{ github.event.client_payload.version }}" fi - # fallback to defaults if empty echo "sdk=${SDK:-all}" >> $GITHUB_OUTPUT echo "version=${VERSION:-latest}" >> $GITHUB_OUTPUT @@ -104,12 +101,9 @@ jobs: git config user.name "github-actions[bot]" git config user.email "github-actions[bot]@users.noreply.github.com" - # stage changes git add docs/sdk-reference/ - git add sdk_navigation.json git add docs.json - # commit if there are changes if git diff --staged --quiet; then echo "No changes to commit" else diff --git a/scripts/generate-sdk-nav.js b/scripts/generate-sdk-nav.js index 692df39..35889d9 100644 --- a/scripts/generate-sdk-nav.js +++ b/scripts/generate-sdk-nav.js @@ -1,16 +1,8 @@ #!/usr/bin/env node -/** - * SDK Navigation Generator - * Scans the docs/sdk-reference directory and generates Mintlify-compatible navigation JSON. - * - * Reads SDK configuration from sdks.json for display names, icons, and ordering. - */ - const fs = require('fs'); const path = require('path'); -// try to use semver for sorting, fall back to basic string comparison let semver; try { semver = require('semver'); @@ -24,9 +16,6 @@ const SDK_REF_DIR = path.join(DOCS_DIR, 'docs', 'sdk-reference'); const CONFIG_FILE = path.join(SCRIPT_DIR, 'sdks.json'); const OUTPUT_FILE = path.join(DOCS_DIR, 'sdk_navigation.json'); -/** - * Load SDK configuration from sdks.json - */ function loadSdkConfigs() { try { const config = require(CONFIG_FILE); @@ -36,10 +25,7 @@ function loadSdkConfigs() { { name: sdk.displayName, icon: sdk.icon, - order: sdk.order, - family: sdk.family, - language: sdk.language, - standalone: sdk.standalone + order: sdk.order } ]) ); @@ -49,23 +35,17 @@ function loadSdkConfigs() { } } -/** - * Get all version directories for an SDK - */ function getVersions(sdkDir) { try { const entries = fs.readdirSync(sdkDir, { withFileTypes: true }); - // accept both "v2.9.0" and "2.9.0" formats const versions = entries .filter(e => { if (!e.isDirectory()) return false; - // match version patterns: v1.2.3 or 1.2.3 return /^v?\d+\.\d+\.\d+/.test(e.name); }) .map(e => e.name); - // sort versions (latest first) if (semver) { return versions.sort((a, b) => { const cleanA = a.replace(/^v/, ''); @@ -78,16 +58,12 @@ function getVersions(sdkDir) { }); } - // fallback: basic string sort (won't handle semver correctly) return versions.sort().reverse(); } catch { return []; } } -/** - * Get all MDX modules in a version directory - */ function getModules(versionDir) { try { const entries = fs.readdirSync(versionDir, { withFileTypes: true }); @@ -100,141 +76,57 @@ function getModules(versionDir) { } } -/** - * Generate navigation structure for all SDKs - * Groups SDKs by family (e.g., sdk, code-interpreter, desktop) - */ function generateNavigation() { const SDK_CONFIGS = loadSdkConfigs(); const navigation = []; - // check if sdk-reference directory exists if (!fs.existsSync(SDK_REF_DIR)) { console.log('⚠️ SDK reference directory not found:', SDK_REF_DIR); return navigation; } - // group SDKs by family - const families = {}; for (const [sdkKey, config] of Object.entries(SDK_CONFIGS)) { - const family = config.family || sdkKey; - if (!families[family]) { - families[family] = { - name: getFamilyDisplayName(family), - icon: getFirstIcon(family, config.icon), - order: Math.min(...[config.order]), // use lowest order in family - standalone: config.standalone || false, - languages: [] - }; - } - // update order to be the minimum across all SDKs in family - families[family].order = Math.min(families[family].order, config.order); - families[family].languages.push({ key: sdkKey, config }); - } - - // process each family - for (const [familyKey, family] of Object.entries(families)) { - // get versions from first language (they should all match) - const firstLang = family.languages[0]; - const firstSdkDir = path.join(SDK_REF_DIR, firstLang.key); + const sdkDir = path.join(SDK_REF_DIR, sdkKey); - if (!fs.existsSync(firstSdkDir)) { - console.log(` Skipping ${familyKey} (not found)`); + if (!fs.existsSync(sdkDir)) { + console.log(` Skipping ${sdkKey} (not found)`); continue; } - const versions = getVersions(firstSdkDir); + const versions = getVersions(sdkDir); if (versions.length === 0) { - console.log(` Skipping ${familyKey} (no versions)`); + console.log(` Skipping ${sdkKey} (no versions)`); continue; } - console.log(` Found ${familyKey}: ${versions.length} versions, ${family.languages.length} languages`); + console.log(` Found ${sdkKey}: ${versions.length} versions`); - // create dropdown for this family const dropdown = { - dropdown: family.name, - icon: family.icon, + dropdown: config.name, + icon: config.icon, versions: versions.map((version, index) => { + const versionDir = path.join(sdkDir, version); + const modules = getModules(versionDir); const displayVersion = version.startsWith('v') ? version : `v${version}`; - - // standalone SDKs (like CLI) - pages directly under version - if (family.standalone) { - const versionDir = path.join(firstSdkDir, version); - const modules = getModules(versionDir); - - return { - version: displayVersion, - default: index === 0, - pages: modules.map(module => - `docs/sdk-reference/${firstLang.key}/${version}/${module}` - ) - }; - } - - // multi-language SDKs - groups for each language - const groups = family.languages.map(lang => { - const sdkDir = path.join(SDK_REF_DIR, lang.key); - const versionDir = path.join(sdkDir, version); - - if (!fs.existsSync(versionDir)) { - return null; - } - - const modules = getModules(versionDir); - - return { - group: lang.config.language || lang.config.name, - icon: lang.config.icon, // add icon for the language - pages: modules.map(module => - `docs/sdk-reference/${lang.key}/${version}/${module}` - ) - }; - }).filter(Boolean); return { version: displayVersion, default: index === 0, - groups + pages: modules.map(module => + `docs/sdk-reference/${sdkKey}/${version}/${module}` + ) }; }) }; - navigation.push({ ...dropdown, _order: family.order }); + navigation.push({ ...dropdown, _order: config.order }); } - // sort by order and remove _order field return navigation .sort((a, b) => a._order - b._order) .map(({ _order, ...rest }) => rest); } -/** - * Get display name for SDK family - */ -function getFamilyDisplayName(family) { - const names = { - 'cli': 'CLI', - 'sdk': 'SDK', - 'code-interpreter': 'Code Interpreter SDK', - 'desktop': 'Desktop SDK' - }; - return names[family] || family; -} - -/** - * Get icon for SDK family (prefer brackets-curly for multi-language SDKs) - */ -function getFirstIcon(family, defaultIcon) { - if (family === 'sdk' || family === 'code-interpreter' || family === 'desktop') { - return 'brackets-curly'; - } - return defaultIcon; -} - -/** - * Main entry point - */ function main() { console.log('📝 Generating SDK navigation...'); console.log(` Config: ${CONFIG_FILE}`); @@ -244,23 +136,14 @@ function main() { const navigation = generateNavigation(); - // write output file fs.writeFileSync(OUTPUT_FILE, JSON.stringify(navigation, null, 2)); console.log(''); console.log(`✅ Generated ${OUTPUT_FILE}`); console.log(` Found ${navigation.length} SDKs`); - // summary for (const sdk of navigation) { - const totalPages = sdk.versions.reduce((sum, v) => { - if (v.pages) { - return sum + v.pages.length; - } else if (v.groups) { - return sum + v.groups.reduce((s, g) => s + g.pages.length, 0); - } - return sum; - }, 0); + const totalPages = sdk.versions.reduce((sum, v) => sum + (v.pages?.length || 0), 0); console.log(` - ${sdk.dropdown}: ${sdk.versions.length} versions, ${totalPages} pages`); } } diff --git a/scripts/generate-sdk-reference.sh b/scripts/generate-sdk-reference.sh index 9037e58..da67040 100755 --- a/scripts/generate-sdk-reference.sh +++ b/scripts/generate-sdk-reference.sh @@ -1,24 +1,13 @@ #!/usr/bin/env bash set -euo pipefail -# SDK Reference Documentation Generator -# Usage: ./generate-sdk-reference.sh [--sdk ] [--version ] -# ./generate-sdk-reference.sh --all -# -# Examples: -# ./generate-sdk-reference.sh --sdk js-sdk --version v2.9.0 -# ./generate-sdk-reference.sh --sdk python-sdk --version v2.9.0 -# ./generate-sdk-reference.sh --all --version latest - SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" DOCS_DIR="$(cd "$SCRIPT_DIR/.." && pwd)" CONFIG_FILE="$SCRIPT_DIR/sdks.json" -# defaults SDK_TYPE="all" VERSION="latest" -# parse arguments while [[ $# -gt 0 ]]; do case $1 in --sdk) @@ -48,7 +37,6 @@ while [[ $# -gt 0 ]]; do esac done -# create temp directory for cloning repos TEMP_DIR=$(mktemp -d) trap "rm -rf $TEMP_DIR" EXIT @@ -58,12 +46,10 @@ echo " Version: $VERSION" echo " Temp dir: $TEMP_DIR" echo "" -# get list of SDKs from config get_sdk_list() { node -e "console.log(Object.keys(require('$CONFIG_FILE').sdks).join(' '))" } -# generate SDK documentation run_generator() { local sdk="$1" local version="$2" @@ -72,11 +58,10 @@ run_generator() { chmod +x "$SCRIPT_DIR/generate-sdk.sh" "$SCRIPT_DIR/generate-sdk.sh" "$sdk" "$version" "$TEMP_DIR" "$DOCS_DIR" || { echo " ⚠️ Generator failed for $sdk" - return 0 # continue with other SDKs + return 0 } } -# run generators if [[ "$SDK_TYPE" == "all" ]]; then SDK_LIST=$(get_sdk_list) for sdk in $SDK_LIST; do @@ -86,12 +71,10 @@ else run_generator "$SDK_TYPE" "$VERSION" fi -# generate navigation JSON echo "" echo "📝 Generating navigation JSON..." node "$SCRIPT_DIR/generate-sdk-nav.js" -# merge navigation into docs.json echo "" echo "🔄 Merging navigation into docs.json..." node "$SCRIPT_DIR/merge-sdk-nav.js" diff --git a/scripts/generate-sdk.sh b/scripts/generate-sdk.sh index 5e0dc0b..d08ee28 100755 --- a/scripts/generate-sdk.sh +++ b/scripts/generate-sdk.sh @@ -1,12 +1,6 @@ #!/usr/bin/env bash set -euo pipefail -# Universal SDK Generator -# Usage: ./generate-sdk.sh -# -# This script replaces all individual SDK generator scripts by reading -# configuration from sdks.json and using shared utility functions. - SDK_KEY="$1" VERSION="$2" TEMP_DIR="$3" @@ -16,10 +10,8 @@ SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" CONFIG_FILE="$SCRIPT_DIR/sdks.json" CONFIGS_DIR="$SCRIPT_DIR/configs" -# source shared utilities source "$SCRIPT_DIR/lib/common.sh" -# helper to read config values using node get_config() { local path="$1" node -e "const c = require('$CONFIG_FILE').sdks['$SDK_KEY']; console.log(c && c.$path !== undefined ? c.$path : '')" @@ -30,7 +22,6 @@ get_config_array() { node -e "const c = require('$CONFIG_FILE').sdks['$SDK_KEY']; const v = c && c.$path; if(Array.isArray(v)) console.log(v.join(' '));" } -# read SDK configuration DISPLAY_NAME=$(get_config "displayName") REPO=$(get_config "repo") TAG_PATTERN=$(get_config "tagPattern") @@ -41,7 +32,6 @@ SDK_PATH=$(get_config "sdkPath") SDK_PATHS=$(get_config_array "sdkPaths") PACKAGES=$(get_config_array "packages") -# validate configuration if [[ -z "$DISPLAY_NAME" ]]; then echo " ❌ SDK '$SDK_KEY' not found in configuration" exit 1 @@ -49,7 +39,6 @@ fi echo " → $DISPLAY_NAME version: $VERSION" -# resolve version RESOLVED_VERSION=$(resolve_version "$REPO" "$TAG_PATTERN" "$VERSION") || true if [[ -z "$RESOLVED_VERSION" ]]; then @@ -63,17 +52,12 @@ if [[ -z "$RESOLVED_VERSION" ]]; then fi echo " → Resolved to: $RESOLVED_VERSION" -# build git tag from format GIT_TAG=$(echo "$TAG_FORMAT" | sed "s/{version}/${RESOLVED_VERSION#v}/") - -# clone repo REPO_DIR="$TEMP_DIR/${SDK_KEY}" clone_repo "$REPO" "$GIT_TAG" "$REPO_DIR" -# find SDK directory SDK_DIR="" if [[ -n "$SDK_PATH" ]]; then - # single path specified SDK_DIR="$REPO_DIR/$SDK_PATH" if [[ ! -d "$SDK_DIR" ]]; then echo " ❌ SDK directory not found: $SDK_DIR" @@ -84,7 +68,6 @@ if [[ -n "$SDK_PATH" ]]; then fi fi elif [[ -n "$SDK_PATHS" ]]; then - # multiple paths to try SDK_DIR=$(find_sdk_directory "$REPO_DIR" $SDK_PATHS) || true if [[ -z "$SDK_DIR" ]]; then echo " ⚠️ SDK directory not found in any of: $SDK_PATHS" @@ -98,14 +81,11 @@ elif [[ -n "$SDK_PATHS" ]]; then fi fi else - # default to repo root SDK_DIR="$REPO_DIR" fi -# install dependencies install_dependencies "$SDK_DIR" "$GENERATOR" -# source and run the appropriate generator source "$SCRIPT_DIR/generators/${GENERATOR}.sh" case "$GENERATOR" in @@ -113,11 +93,7 @@ case "$GENERATOR" in generate_typedoc "$SDK_DIR" "$CONFIGS_DIR" ;; pydoc) - # build submodules string if exists - SUBMODULES="" - if [[ "$SDK_KEY" == "python-sdk" ]]; then - SUBMODULES="e2b.template.logger e2b.template.readycmd" - fi + SUBMODULES=$(node -e "const c = require('$CONFIG_FILE').sdks['$SDK_KEY']; const v = c?.submodules?.['e2b.template']; if(Array.isArray(v)) console.log(v.join(' '));" || echo "") generate_pydoc "$SDK_DIR" "$PACKAGES" "$SUBMODULES" ;; cli) @@ -129,11 +105,9 @@ case "$GENERATOR" in ;; esac -# flatten markdown structure (for TypeDoc output) if [[ -d "$SDK_DIR/sdk_ref" ]]; then flatten_markdown "$SDK_DIR/sdk_ref" - # copy to docs repo copy_to_docs "$SDK_DIR/sdk_ref" \ "$DOCS_DIR/docs/sdk-reference/$SDK_KEY/$RESOLVED_VERSION" \ "$DISPLAY_NAME" "$RESOLVED_VERSION" diff --git a/scripts/generators/cli.sh b/scripts/generators/cli.sh index 4ee997e..23e4010 100755 --- a/scripts/generators/cli.sh +++ b/scripts/generators/cli.sh @@ -1,14 +1,10 @@ #!/usr/bin/env bash -# CLI documentation generator -# Builds CLI and generates documentation using commands2md utility - generate_cli_docs() { local sdk_dir="$1" cd "$sdk_dir" - # build CLI first echo " → Building CLI..." if command -v pnpm &> /dev/null; then pnpm run build 2>&1 || npx tsup 2>&1 || { @@ -22,17 +18,14 @@ generate_cli_docs() { } fi - # generate documentation using the CLI's commands2md utility echo " → Generating documentation..." mkdir -p sdk_ref - # the CLI uses -cmd2md flag to generate markdown docs NODE_ENV=development node dist/index.js -cmd2md 2>&1 || { echo " ⚠️ CLI doc generation failed" return 1 } - # rename .md to .mdx (if any .md files exist) cd sdk_ref shopt -s nullglob for file in *.md; do diff --git a/scripts/generators/pydoc.sh b/scripts/generators/pydoc.sh index e7a51e0..2c7609d 100755 --- a/scripts/generators/pydoc.sh +++ b/scripts/generators/pydoc.sh @@ -1,20 +1,12 @@ #!/usr/bin/env bash -# pydoc-markdown generator for Python SDKs -# Generates markdown documentation using pydoc-markdown - -# process generated mdx files (cleanup formatting) process_mdx() { local file="$1" local tmp_file="${file}.tmp" - # remove package path display links sed '/]*>.*<\/a>/d' "${file}" > "${tmp_file}" && mv "${tmp_file}" "${file}" - # remove h1 headers sed '/^# /d' "${file}" > "${tmp_file}" && mv "${tmp_file}" "${file}" - # remove " Objects" suffix from h2 headers sed '/^## / s/ Objects$//' "${file}" > "${tmp_file}" && mv "${tmp_file}" "${file}" - # convert h4 to h3 sed 's/^####/###/' "${file}" > "${tmp_file}" && mv "${tmp_file}" "${file}" } @@ -28,9 +20,8 @@ generate_pydoc() { echo " → Generating documentation for packages..." - # generate for each main package for pkg in $packages; do - local output_name="${pkg##*.}" # get last part after dot + local output_name="${pkg##*.}" echo " → Processing ${pkg}..." if poetry run pydoc-markdown -p "$pkg" > "sdk_ref/${output_name}.mdx" 2>/dev/null; then @@ -41,7 +32,6 @@ generate_pydoc() { fi done - # generate for submodules if provided if [[ -n "$submodules" ]]; then for submod in $submodules; do local output_name="${submod##*.}" diff --git a/scripts/generators/typedoc.sh b/scripts/generators/typedoc.sh index 8782630..512d00c 100755 --- a/scripts/generators/typedoc.sh +++ b/scripts/generators/typedoc.sh @@ -1,15 +1,11 @@ #!/usr/bin/env bash -# TypeDoc generator for JavaScript SDKs -# Generates markdown documentation using TypeDoc with custom theme - generate_typedoc() { local sdk_dir="$1" local configs_dir="$2" cd "$sdk_dir" - # check if repo has its own typedoc config if [[ -f "typedoc.json" ]]; then echo " → Running TypeDoc with repo config..." npx typedoc --plugin typedoc-plugin-markdown \ diff --git a/scripts/lib/common.sh b/scripts/lib/common.sh index 9bfe66b..9a717fa 100755 --- a/scripts/lib/common.sh +++ b/scripts/lib/common.sh @@ -1,10 +1,5 @@ #!/usr/bin/env bash -# Shared utility functions for SDK documentation generation - -# resolve latest version for a repo and tag pattern -# args: repo, tag_pattern, version -# returns: resolved version (e.g., "v2.9.0") or empty string on failure resolve_version() { local repo="$1" local tag_pattern="$2" @@ -15,7 +10,6 @@ resolve_version() { return 0 fi - # escape special characters in tag pattern for sed (needs different escaping than grep) local sed_escaped_pattern=$(echo "$tag_pattern" | sed 's/[\/&@]/\\&/g') local resolved @@ -31,8 +25,6 @@ resolve_version() { echo "$resolved" } -# clone repo at specific tag with fallback to main branch -# args: repo, git_tag, target_dir clone_repo() { local repo="$1" local git_tag="$2" @@ -49,9 +41,6 @@ clone_repo() { } } -# find SDK directory from list of possible paths -# args: base_dir, path1, path2, ... -# returns: full path to SDK directory or empty string find_sdk_directory() { local base_dir="$1" shift @@ -67,8 +56,6 @@ find_sdk_directory() { return 1 } -# install dependencies based on generator type -# args: sdk_dir, generator install_dependencies() { local sdk_dir="$1" local generator="$2" @@ -100,15 +87,12 @@ install_dependencies() { esac } -# flatten markdown files structure for Mintlify -# args: sdk_ref_dir flatten_markdown() { local sdk_ref_dir="$1" cd "$sdk_ref_dir" rm -f README.md - # flatten nested structure: move all md files to root level find . -mindepth 2 -type f -name "*.md" 2>/dev/null | while read -r file; do local dir=$(dirname "$file") local filename=$(basename "$file") @@ -121,18 +105,15 @@ flatten_markdown() { fi done - # remove empty directories find . -type d -empty -delete 2>/dev/null || true - # rename .md to .mdx and add frontmatter (if any .md files exist) shopt -s nullglob for file in *.md; do local mdx_file="${file%.md}.mdx" - # add frontmatter to disable TOC for SDK reference pages { echo "---" echo "sidebarTitle: \"$(basename "$file" .md)\"" - echo "toc: false" + echo "mode: \"center\"" echo "---" echo "" cat "$file" @@ -141,14 +122,13 @@ flatten_markdown() { done shopt -u nullglob - # add frontmatter to existing .mdx files (from pydoc generator) for file in *.mdx; do if ! head -n1 "$file" | grep -q "^---$"; then local tmp_file="${file}.tmp" { echo "---" echo "sidebarTitle: \"$(basename "$file" .mdx)\"" - echo "toc: false" + echo "mode: \"center\"" echo "---" echo "" cat "$file" @@ -158,8 +138,6 @@ flatten_markdown() { done } -# copy generated docs to target directory with reporting -# args: src_dir, target_dir, sdk_name, version copy_to_docs() { local src_dir="$1" local target_dir="$2" @@ -180,19 +158,3 @@ copy_to_docs() { fi } -# read a value from JSON config using node -# args: json_file, jq_path (e.g., ".sdks.js-sdk.displayName") -json_get() { - local json_file="$1" - local path="$2" - node -e "console.log(require('$json_file')$path || '')" -} - -# read array from JSON config using node -# args: json_file, jq_path (e.g., ".sdks.js-sdk.packages") -json_get_array() { - local json_file="$1" - local path="$2" - node -e "const v = require('$json_file')$path; if(Array.isArray(v)) console.log(v.join(' '));" -} - diff --git a/scripts/merge-sdk-nav.js b/scripts/merge-sdk-nav.js index 18a1dd3..6f5c1cc 100644 --- a/scripts/merge-sdk-nav.js +++ b/scripts/merge-sdk-nav.js @@ -1,13 +1,5 @@ #!/usr/bin/env node -/** - * Merge SDK Navigation into docs.json - * - * This script merges the generated sdk_navigation.json into the docs.json - * Mintlify configuration. It finds the "SDK Reference" anchor and replaces - * its dropdowns with the generated navigation, enabling SDK and version selection. - */ - const fs = require('fs'); const path = require('path'); @@ -18,7 +10,6 @@ const SDK_NAV_PATH = path.join(DOCS_DIR, 'sdk_navigation.json'); function main() { console.log('🔄 Merging SDK navigation into docs.json...'); - // read files if (!fs.existsSync(SDK_NAV_PATH)) { console.log('⚠️ sdk_navigation.json not found, skipping merge'); return; @@ -27,7 +18,6 @@ function main() { const docsJson = JSON.parse(fs.readFileSync(DOCS_JSON_PATH, 'utf-8')); const sdkNav = JSON.parse(fs.readFileSync(SDK_NAV_PATH, 'utf-8')); - // find SDK Reference anchor const anchors = docsJson.navigation?.anchors; if (!anchors) { console.error('❌ No anchors found in docs.json'); @@ -40,7 +30,6 @@ function main() { process.exit(1); } - // filter out empty dropdowns and update const validDropdowns = sdkNav.filter(d => d.versions && d.versions.length > 0); if (validDropdowns.length === 0) { @@ -48,29 +37,19 @@ function main() { return; } - // update SDK Reference anchor with generated navigation anchors[sdkRefIndex] = { anchor: 'SDK Reference', icon: 'brackets-curly', dropdowns: validDropdowns }; - // write updated docs.json fs.writeFileSync(DOCS_JSON_PATH, JSON.stringify(docsJson, null, 2) + '\n'); console.log(`✅ Updated docs.json with ${validDropdowns.length} SDK dropdowns`); - // summary for (const dropdown of validDropdowns) { const totalVersions = dropdown.versions.length; - const totalPages = dropdown.versions.reduce((sum, v) => { - if (v.pages) { - return sum + v.pages.length; - } else if (v.groups) { - return sum + v.groups.reduce((s, g) => s + g.pages.length, 0); - } - return sum; - }, 0); + const totalPages = dropdown.versions.reduce((sum, v) => sum + (v.pages?.length || 0), 0); console.log(` - ${dropdown.dropdown}: ${totalVersions} versions, ${totalPages} pages`); } } diff --git a/scripts/sdks.json b/scripts/sdks.json index 6c82756..48dd31b 100644 --- a/scripts/sdks.json +++ b/scripts/sdks.json @@ -4,8 +4,6 @@ "displayName": "CLI", "icon": "terminal", "order": 4, - "family": "cli", - "standalone": true, "repo": "https://github.com/e2b-dev/e2b.git", "tagPattern": "@e2b/cli@", "tagFormat": "@e2b/cli@{version}", @@ -14,11 +12,9 @@ "required": true }, "js-sdk": { - "displayName": "JavaScript", + "displayName": "JavaScript SDK", "icon": "square-js", "order": 1, - "family": "sdk", - "language": "JavaScript", "repo": "https://github.com/e2b-dev/e2b.git", "tagPattern": "e2b@", "tagFormat": "e2b@{version}", @@ -27,11 +23,9 @@ "required": true }, "python-sdk": { - "displayName": "Python", + "displayName": "Python SDK", "icon": "python", - "order": 1, - "family": "sdk", - "language": "Python", + "order": 2, "repo": "https://github.com/e2b-dev/e2b.git", "tagPattern": "e2b@", "tagFormat": "e2b@{version}", @@ -51,11 +45,9 @@ } }, "code-interpreter-js-sdk": { - "displayName": "JavaScript", + "displayName": "Code Interpreter JavaScript SDK", "icon": "square-js", - "order": 2, - "family": "code-interpreter", - "language": "JavaScript", + "order": 5, "repo": "https://github.com/e2b-dev/code-interpreter.git", "tagPattern": "@e2b/code-interpreter@", "tagFormat": "@e2b/code-interpreter@{version}", @@ -64,11 +56,9 @@ "required": false }, "code-interpreter-python-sdk": { - "displayName": "Python", + "displayName": "Code Interpreter Python SDK", "icon": "python", - "order": 2, - "family": "code-interpreter", - "language": "Python", + "order": 6, "repo": "https://github.com/e2b-dev/code-interpreter.git", "tagPattern": "e2b-code-interpreter@", "tagFormat": "e2b-code-interpreter@{version}", @@ -78,11 +68,9 @@ "packages": ["e2b_code_interpreter"] }, "desktop-js-sdk": { - "displayName": "JavaScript", + "displayName": "Desktop JavaScript SDK", "icon": "square-js", - "order": 3, - "family": "desktop", - "language": "JavaScript", + "order": 7, "repo": "https://github.com/e2b-dev/desktop.git", "tagPattern": "@e2b/desktop@", "tagFormat": "@e2b/desktop@{version}", @@ -91,11 +79,9 @@ "required": false }, "desktop-python-sdk": { - "displayName": "Python", + "displayName": "Desktop Python SDK", "icon": "python", - "order": 3, - "family": "desktop", - "language": "Python", + "order": 8, "repo": "https://github.com/e2b-dev/desktop.git", "tagPattern": "e2b-desktop@", "tagFormat": "e2b-desktop@{version}", From 81afe32cb3c2104711a66152fc5cc4f234c7bf7d Mon Sep 17 00:00:00 2001 From: ben-fornefeld Date: Wed, 7 Jan 2026 14:44:30 +0100 Subject: [PATCH 05/39] fix: sdks.json --- scripts/sdks.json | 20 ++++++++++---------- 1 file changed, 10 insertions(+), 10 deletions(-) diff --git a/scripts/sdks.json b/scripts/sdks.json index 48dd31b..362498e 100644 --- a/scripts/sdks.json +++ b/scripts/sdks.json @@ -27,8 +27,8 @@ "icon": "python", "order": 2, "repo": "https://github.com/e2b-dev/e2b.git", - "tagPattern": "e2b@", - "tagFormat": "e2b@{version}", + "tagPattern": "@e2b/python-sdk@", + "tagFormat": "@e2b/python-sdk@{version}", "sdkPath": "packages/python-sdk", "generator": "pydoc", "required": true, @@ -51,7 +51,7 @@ "repo": "https://github.com/e2b-dev/code-interpreter.git", "tagPattern": "@e2b/code-interpreter@", "tagFormat": "@e2b/code-interpreter@{version}", - "sdkPaths": ["js", "packages/js-sdk", "packages/sdk", "js-sdk"], + "sdkPaths": ["js"], "generator": "typedoc", "required": false }, @@ -60,9 +60,9 @@ "icon": "python", "order": 6, "repo": "https://github.com/e2b-dev/code-interpreter.git", - "tagPattern": "e2b-code-interpreter@", - "tagFormat": "e2b-code-interpreter@{version}", - "sdkPaths": ["python", "packages/python-sdk", "packages/python", "python-sdk"], + "tagPattern": "@e2b/code-interpreter-python@", + "tagFormat": "@e2b/code-interpreter-python@{version}", + "sdkPaths": ["python"], "generator": "pydoc", "required": false, "packages": ["e2b_code_interpreter"] @@ -74,7 +74,7 @@ "repo": "https://github.com/e2b-dev/desktop.git", "tagPattern": "@e2b/desktop@", "tagFormat": "@e2b/desktop@{version}", - "sdkPaths": ["js", "packages/js-sdk", "packages/sdk", "js-sdk"], + "sdkPaths": ["packages/js-sdk"], "generator": "typedoc", "required": false }, @@ -83,9 +83,9 @@ "icon": "python", "order": 8, "repo": "https://github.com/e2b-dev/desktop.git", - "tagPattern": "e2b-desktop@", - "tagFormat": "e2b-desktop@{version}", - "sdkPaths": ["python", "packages/python-sdk", "packages/python", "python-sdk"], + "tagPattern": "@e2b/desktop-python@", + "tagFormat": "@e2b/desktop-python@{version}", + "sdkPaths": ["packages/python-sdk"], "generator": "pydoc", "required": false, "packages": ["e2b_desktop"] From e97acb3a0e1832e159c997e77f2928f870621aff Mon Sep 17 00:00:00 2001 From: ben-fornefeld Date: Wed, 7 Jan 2026 16:03:42 +0100 Subject: [PATCH 06/39] Enhance SDK reference generation and configuration - Updated `sdk-reference-sync.yml` to allow version generation for "all" versions by default. - Modified `generate-sdk-reference.sh` to support a new `--limit` option for controlling the number of versions processed. - Improved `generate-sdk.sh` to filter versions based on a minimum version requirement and to handle version discovery more effectively. - Updated `sdks.json` to include `minVersion` attributes for SDKs, ensuring only compatible versions are processed. - Enhanced common library functions for version management and caching during dependency installation. --- .github/workflows/sdk-reference-sync.yml | 8 +- scripts/generate-sdk-reference.sh | 13 ++ scripts/generate-sdk.sh | 223 +++++++++++++++++------ scripts/lib/common.sh | 162 +++++++++++++++- scripts/sdks.json | 25 ++- 5 files changed, 357 insertions(+), 74 deletions(-) diff --git a/.github/workflows/sdk-reference-sync.yml b/.github/workflows/sdk-reference-sync.yml index d1055a8..e3a1b86 100644 --- a/.github/workflows/sdk-reference-sync.yml +++ b/.github/workflows/sdk-reference-sync.yml @@ -19,9 +19,9 @@ on: - desktop-js-sdk - desktop-python-sdk version: - description: "Version to generate (e.g., v2.9.0 or latest)" + description: "Version to generate (all, latest, or specific like v2.9.0)" required: true - default: "latest" + default: "all" type: string # triggered from e2b-dev/e2b repo on release @@ -72,11 +72,13 @@ jobs: VERSION="${{ github.event.inputs.version }}" elif [[ "${{ github.event_name }}" == "repository_dispatch" ]]; then SDK="${{ github.event.client_payload.sdk }}" + # on repository_dispatch, default to "all" to auto-detect missing versions VERSION="${{ github.event.client_payload.version }}" + VERSION="${VERSION:-all}" fi echo "sdk=${SDK:-all}" >> $GITHUB_OUTPUT - echo "version=${VERSION:-latest}" >> $GITHUB_OUTPUT + echo "version=${VERSION:-all}" >> $GITHUB_OUTPUT - name: Generate SDK Reference run: | diff --git a/scripts/generate-sdk-reference.sh b/scripts/generate-sdk-reference.sh index da67040..e6627dc 100755 --- a/scripts/generate-sdk-reference.sh +++ b/scripts/generate-sdk-reference.sh @@ -7,6 +7,7 @@ CONFIG_FILE="$SCRIPT_DIR/sdks.json" SDK_TYPE="all" VERSION="latest" +LIMIT="" while [[ $# -gt 0 ]]; do case $1 in @@ -26,6 +27,14 @@ while [[ $# -gt 0 ]]; do shift fi ;; + --limit) + if [[ -n "${2:-}" && ! "$2" =~ ^-- ]]; then + LIMIT="$2" + shift 2 + else + shift + fi + ;; --all) SDK_TYPE="all" shift @@ -37,12 +46,16 @@ while [[ $# -gt 0 ]]; do esac done +# export limit for child scripts +export SDK_VERSION_LIMIT="$LIMIT" + TEMP_DIR=$(mktemp -d) trap "rm -rf $TEMP_DIR" EXIT echo "🚀 SDK Reference Generator" echo " SDK: $SDK_TYPE" echo " Version: $VERSION" +[[ -n "$LIMIT" ]] && echo " Limit: $LIMIT versions" echo " Temp dir: $TEMP_DIR" echo "" diff --git a/scripts/generate-sdk.sh b/scripts/generate-sdk.sh index d08ee28..4f208c6 100755 --- a/scripts/generate-sdk.sh +++ b/scripts/generate-sdk.sh @@ -31,6 +31,7 @@ REQUIRED=$(get_config "required") SDK_PATH=$(get_config "sdkPath") SDK_PATHS=$(get_config_array "sdkPaths") PACKAGES=$(get_config_array "packages") +MIN_VERSION=$(get_config "minVersion") if [[ -z "$DISPLAY_NAME" ]]; then echo " ❌ SDK '$SDK_KEY' not found in configuration" @@ -39,79 +40,187 @@ fi echo " → $DISPLAY_NAME version: $VERSION" -RESOLVED_VERSION=$(resolve_version "$REPO" "$TAG_PATTERN" "$VERSION") || true +# determine versions to process +VERSIONS_TO_PROCESS="" -if [[ -z "$RESOLVED_VERSION" ]]; then - if [[ "$REQUIRED" == "true" ]]; then - echo " ❌ No tags found for $DISPLAY_NAME" - exit 1 - else - echo " ⚠️ No tags found, skipping..." - exit 0 - fi -fi -echo " → Resolved to: $RESOLVED_VERSION" - -GIT_TAG=$(echo "$TAG_FORMAT" | sed "s/{version}/${RESOLVED_VERSION#v}/") -REPO_DIR="$TEMP_DIR/${SDK_KEY}" -clone_repo "$REPO" "$GIT_TAG" "$REPO_DIR" - -SDK_DIR="" -if [[ -n "$SDK_PATH" ]]; then - SDK_DIR="$REPO_DIR/$SDK_PATH" - if [[ ! -d "$SDK_DIR" ]]; then - echo " ❌ SDK directory not found: $SDK_DIR" +if [[ "$VERSION" == "all" ]]; then + echo " → Discovering all versions..." + ALL_VERSIONS=$(get_all_versions "$REPO" "$TAG_PATTERN") + + if [[ -z "$ALL_VERSIONS" ]]; then if [[ "$REQUIRED" == "true" ]]; then + echo " ❌ No tags found for $DISPLAY_NAME" exit 1 else + echo " ⚠️ No tags found, skipping..." exit 0 fi fi -elif [[ -n "$SDK_PATHS" ]]; then - SDK_DIR=$(find_sdk_directory "$REPO_DIR" $SDK_PATHS) || true - if [[ -z "$SDK_DIR" ]]; then - echo " ⚠️ SDK directory not found in any of: $SDK_PATHS" - echo " → Repo structure:" - ls -la "$REPO_DIR" 2>/dev/null || true - ls -la "$REPO_DIR/packages" 2>/dev/null || true + + # filter by minVersion if set + if [[ -n "$MIN_VERSION" ]]; then + ALL_VERSIONS=$(filter_min_version "$ALL_VERSIONS" "$MIN_VERSION") + echo " → Filtered to versions >= $MIN_VERSION" + fi + + # apply limit if set (from SDK_VERSION_LIMIT env var) + if [[ -n "${SDK_VERSION_LIMIT:-}" && "$SDK_VERSION_LIMIT" =~ ^[0-9]+$ ]]; then + ALL_VERSIONS=$(echo "$ALL_VERSIONS" | head -n "$SDK_VERSION_LIMIT") + echo " → Limited to last $SDK_VERSION_LIMIT versions" + fi + + TOTAL_COUNT=$(echo "$ALL_VERSIONS" | wc -l | tr -d ' ') + EXISTING_COUNT=$(count_sdk_versions "$SDK_KEY" "$DOCS_DIR") + + echo "" + echo " 📊 Version Discovery Report:" + echo " Total tags found: $TOTAL_COUNT" + echo " Already generated: $EXISTING_COUNT" + + # filter to only missing versions + MISSING_VERSIONS="" + SKIP_COUNT=0 + for version in $ALL_VERSIONS; do + if version_exists "$SDK_KEY" "$version" "$DOCS_DIR"; then + ((SKIP_COUNT++)) || true + else + if [[ -z "$MISSING_VERSIONS" ]]; then + MISSING_VERSIONS="$version" + else + MISSING_VERSIONS="$MISSING_VERSIONS $version" + fi + fi + done + + MISSING_COUNT=$(echo "$MISSING_VERSIONS" | wc -w | tr -d ' ') + echo " To generate: $MISSING_COUNT" + echo "" + + if [[ -z "$MISSING_VERSIONS" || "$MISSING_COUNT" -eq 0 ]]; then + echo " ✅ All versions already generated, nothing to do" + exit 0 + fi + + VERSIONS_TO_PROCESS="$MISSING_VERSIONS" +else + # single version (latest or specific) + RESOLVED_VERSION=$(resolve_version "$REPO" "$TAG_PATTERN" "$VERSION") || true + + if [[ -z "$RESOLVED_VERSION" ]]; then if [[ "$REQUIRED" == "true" ]]; then + echo " ❌ No tags found for $DISPLAY_NAME" exit 1 else + echo " ⚠️ No tags found, skipping..." exit 0 fi fi -else - SDK_DIR="$REPO_DIR" + + if version_exists "$SDK_KEY" "$RESOLVED_VERSION" "$DOCS_DIR"; then + echo " ✓ $RESOLVED_VERSION already exists, skipping" + exit 0 + fi + + VERSIONS_TO_PROCESS="$RESOLVED_VERSION" fi -install_dependencies "$SDK_DIR" "$GENERATOR" - -source "$SCRIPT_DIR/generators/${GENERATOR}.sh" +# track generation results +GENERATED_COUNT=0 +FAILED_COUNT=0 +FAILED_VERSIONS="" -case "$GENERATOR" in - typedoc) - generate_typedoc "$SDK_DIR" "$CONFIGS_DIR" - ;; - pydoc) - SUBMODULES=$(node -e "const c = require('$CONFIG_FILE').sdks['$SDK_KEY']; const v = c?.submodules?.['e2b.template']; if(Array.isArray(v)) console.log(v.join(' '));" || echo "") - generate_pydoc "$SDK_DIR" "$PACKAGES" "$SUBMODULES" - ;; - cli) - generate_cli_docs "$SDK_DIR" - ;; - *) - echo " ❌ Unknown generator: $GENERATOR" - exit 1 - ;; -esac - -if [[ -d "$SDK_DIR/sdk_ref" ]]; then - flatten_markdown "$SDK_DIR/sdk_ref" +# process each version +for RESOLVED_VERSION in $VERSIONS_TO_PROCESS; do + echo "" + echo " 📦 Generating $RESOLVED_VERSION..." - copy_to_docs "$SDK_DIR/sdk_ref" \ - "$DOCS_DIR/docs/sdk-reference/$SDK_KEY/$RESOLVED_VERSION" \ - "$DISPLAY_NAME" "$RESOLVED_VERSION" -else - echo " ⚠️ No sdk_ref directory found" + # use version-specific temp dir for isolation + REPO_DIR="$TEMP_DIR/${SDK_KEY}-${RESOLVED_VERSION}" + GIT_TAG=$(echo "$TAG_FORMAT" | sed "s/{version}/${RESOLVED_VERSION#v}/") + + # attempt generation with error handling + if ! ( + set -e + + clone_repo "$REPO" "$GIT_TAG" "$REPO_DIR" + + SDK_DIR="" + if [[ -n "$SDK_PATH" ]]; then + SDK_DIR="$REPO_DIR/$SDK_PATH" + if [[ ! -d "$SDK_DIR" ]]; then + echo " ❌ SDK directory not found: $SDK_DIR" + exit 1 + fi + elif [[ -n "$SDK_PATHS" ]]; then + SDK_DIR=$(find_sdk_directory "$REPO_DIR" $SDK_PATHS) || true + if [[ -z "$SDK_DIR" ]]; then + echo " ⚠️ SDK directory not found in any of: $SDK_PATHS" + exit 1 + fi + else + SDK_DIR="$REPO_DIR" + fi + + install_dependencies_cached "$SDK_DIR" "$GENERATOR" "$TEMP_DIR" + + source "$SCRIPT_DIR/generators/${GENERATOR}.sh" + + case "$GENERATOR" in + typedoc) + generate_typedoc "$SDK_DIR" "$CONFIGS_DIR" + ;; + pydoc) + SUBMODULES=$(node -e "const c = require('$CONFIG_FILE').sdks['$SDK_KEY']; const v = c?.submodules?.['e2b.template']; if(Array.isArray(v)) console.log(v.join(' '));" || echo "") + generate_pydoc "$SDK_DIR" "$PACKAGES" "$SUBMODULES" + ;; + cli) + generate_cli_docs "$SDK_DIR" + ;; + *) + echo " ❌ Unknown generator: $GENERATOR" + exit 1 + ;; + esac + + if [[ -d "$SDK_DIR/sdk_ref" ]]; then + flatten_markdown "$SDK_DIR/sdk_ref" + + copy_to_docs "$SDK_DIR/sdk_ref" \ + "$DOCS_DIR/docs/sdk-reference/$SDK_KEY/$RESOLVED_VERSION" \ + "$DISPLAY_NAME" "$RESOLVED_VERSION" + else + echo " ⚠️ No sdk_ref directory found" + exit 1 + fi + ); then + echo " ❌ Failed to generate $RESOLVED_VERSION" + ((FAILED_COUNT++)) || true + if [[ -z "$FAILED_VERSIONS" ]]; then + FAILED_VERSIONS="$RESOLVED_VERSION" + else + FAILED_VERSIONS="$FAILED_VERSIONS $RESOLVED_VERSION" + fi + # continue to next version instead of failing + continue + fi + + echo " ✅ Complete: $RESOLVED_VERSION" + ((GENERATED_COUNT++)) || true + + # cleanup version-specific temp dir to save space + rm -rf "$REPO_DIR" +done + +# print summary +echo "" +echo " 📊 Generation Summary for $DISPLAY_NAME:" +echo " Successfully generated: $GENERATED_COUNT" +if [[ $FAILED_COUNT -gt 0 ]]; then + echo " Failed: $FAILED_COUNT ($FAILED_VERSIONS)" fi +# exit with error if all failed and required +if [[ $GENERATED_COUNT -eq 0 && "$REQUIRED" == "true" && -n "$VERSIONS_TO_PROCESS" ]]; then + echo " ❌ All versions failed to generate" + exit 1 +fi diff --git a/scripts/lib/common.sh b/scripts/lib/common.sh index 9a717fa..7ad180a 100755 --- a/scripts/lib/common.sh +++ b/scripts/lib/common.sh @@ -1,5 +1,79 @@ #!/usr/bin/env bash +# get all versions matching tag pattern (sorted newest first) +get_all_versions() { + local repo="$1" + local tag_pattern="$2" + + local sed_escaped_pattern=$(echo "$tag_pattern" | sed 's/[\/&@]/\\&/g') + + git ls-remote --tags --refs "$repo" 2>/dev/null | \ + grep "refs/tags/${tag_pattern}" | \ + sed "s|.*refs/tags/${sed_escaped_pattern}|v|" | \ + sort -V -r +} + +# check if version documentation already exists +version_exists() { + local sdk_key="$1" + local version="$2" + local docs_dir="$3" + + local version_dir="$docs_dir/docs/sdk-reference/$sdk_key/$version" + [[ -d "$version_dir" ]] && [[ -n "$(ls -A "$version_dir"/*.mdx 2>/dev/null)" ]] +} + +# validate version string format +is_valid_version() { + local version="$1" + [[ "$version" =~ ^v?[0-9]+\.[0-9]+\.[0-9]+$ ]] +} + +# compare two versions (returns 0 if v1 >= v2) +version_gte() { + local v1="$1" + local v2="$2" + + # strip 'v' prefix if present + v1="${v1#v}" + v2="${v2#v}" + + # use sort -V to compare versions + local higher=$(printf '%s\n%s' "$v1" "$v2" | sort -V -r | head -n1) + [[ "$higher" == "$v1" ]] +} + +# filter versions to only those >= minVersion +filter_min_version() { + local versions="$1" + local min_version="$2" + + if [[ -z "$min_version" ]]; then + echo "$versions" + return 0 + fi + + echo "$versions" | while IFS= read -r version; do + if [[ -n "$version" ]] && version_gte "$version" "$min_version"; then + echo "$version" + fi + done +} + +# count existing versions for an SDK +count_sdk_versions() { + local sdk_key="$1" + local docs_dir="$2" + local sdk_ref_dir="$docs_dir/docs/sdk-reference/$sdk_key" + + if [[ ! -d "$sdk_ref_dir" ]]; then + echo "0" + return + fi + + find "$sdk_ref_dir" -maxdepth 1 -type d \( -name "v*" -o -name "[0-9]*" \) 2>/dev/null | wc -l | tr -d ' ' +} + resolve_version() { local repo="$1" local tag_pattern="$2" @@ -56,6 +130,84 @@ find_sdk_directory() { return 1 } +# find lockfile, searching up directory tree +find_lockfile() { + local dir="$1" + local filename="$2" + + while [[ "$dir" != "/" && "$dir" != "." ]]; do + if [[ -f "$dir/$filename" ]]; then + echo "$dir/$filename" + return 0 + fi + dir=$(dirname "$dir") + done + return 1 +} + +# compute hash of lockfile for caching +get_lockfile_hash() { + local sdk_dir="$1" + local generator="$2" + + local lockfile="" + case "$generator" in + typedoc|cli) + lockfile=$(find_lockfile "$sdk_dir" "pnpm-lock.yaml") || \ + lockfile=$(find_lockfile "$sdk_dir" "package-lock.json") || true + ;; + pydoc) + lockfile=$(find_lockfile "$sdk_dir" "poetry.lock") || true + ;; + esac + + if [[ -n "$lockfile" && -f "$lockfile" ]]; then + # use md5 on macOS, md5sum on Linux + if command -v md5 &>/dev/null; then + md5 -q "$lockfile" + else + md5sum "$lockfile" | cut -d' ' -f1 + fi + fi +} + +# install dependencies with caching support +# for JS: relies on pnpm's global cache (~/.pnpm-store) with --prefer-offline +# for Python: tracks lockfile hash to skip redundant installs +install_dependencies_cached() { + local sdk_dir="$1" + local generator="$2" + local temp_dir="$3" + + case "$generator" in + typedoc|cli) + # pnpm uses content-addressable storage with hardlinks + # --prefer-offline makes it fast, no need to copy node_modules + install_dependencies "$sdk_dir" "$generator" + ;; + pydoc) + local lockfile_hash=$(get_lockfile_hash "$sdk_dir" "$generator") + local cache_marker="$temp_dir/.deps-cache/pydoc-$lockfile_hash/.installed" + + if [[ -n "$lockfile_hash" && -f "$cache_marker" ]]; then + echo " → Poetry dependencies cached (lockfile unchanged)" + return 0 + fi + + install_dependencies "$sdk_dir" "$generator" + + # mark as installed for future versions with same lockfile + if [[ -n "$lockfile_hash" ]]; then + mkdir -p "$(dirname "$cache_marker")" + touch "$cache_marker" + fi + ;; + *) + install_dependencies "$sdk_dir" "$generator" + ;; + esac +} + install_dependencies() { local sdk_dir="$1" local generator="$2" @@ -66,12 +218,12 @@ install_dependencies() { case "$generator" in typedoc) if command -v pnpm &> /dev/null; then - pnpm install --ignore-scripts 2>&1 || { + pnpm install --ignore-scripts --prefer-offline 2>&1 || { echo " ⚠️ pnpm failed, trying npm..." - npm install --legacy-peer-deps 2>&1 + npm install --legacy-peer-deps --prefer-offline 2>&1 } else - npm install --legacy-peer-deps 2>&1 + npm install --legacy-peer-deps --prefer-offline 2>&1 fi ;; pydoc) @@ -79,9 +231,9 @@ install_dependencies() { ;; cli) if command -v pnpm &> /dev/null; then - pnpm install 2>&1 || npm install 2>&1 + pnpm install --prefer-offline 2>&1 || npm install --prefer-offline 2>&1 else - npm install 2>&1 + npm install --prefer-offline 2>&1 fi ;; esac diff --git a/scripts/sdks.json b/scripts/sdks.json index 362498e..3b45f04 100644 --- a/scripts/sdks.json +++ b/scripts/sdks.json @@ -3,13 +3,14 @@ "cli": { "displayName": "CLI", "icon": "terminal", - "order": 4, + "order": 7, "repo": "https://github.com/e2b-dev/e2b.git", "tagPattern": "@e2b/cli@", "tagFormat": "@e2b/cli@{version}", "sdkPath": "packages/cli", "generator": "cli", - "required": true + "required": true, + "minVersion": "1.0.0" }, "js-sdk": { "displayName": "JavaScript SDK", @@ -20,7 +21,8 @@ "tagFormat": "e2b@{version}", "sdkPath": "packages/js-sdk", "generator": "typedoc", - "required": true + "required": true, + "minVersion": "1.0.0" }, "python-sdk": { "displayName": "Python SDK", @@ -32,6 +34,7 @@ "sdkPath": "packages/python-sdk", "generator": "pydoc", "required": true, + "minVersion": "1.0.0", "packages": [ "e2b.sandbox_sync", "e2b.sandbox_async", @@ -47,47 +50,51 @@ "code-interpreter-js-sdk": { "displayName": "Code Interpreter JavaScript SDK", "icon": "square-js", - "order": 5, + "order": 3, "repo": "https://github.com/e2b-dev/code-interpreter.git", "tagPattern": "@e2b/code-interpreter@", "tagFormat": "@e2b/code-interpreter@{version}", "sdkPaths": ["js"], "generator": "typedoc", - "required": false + "required": false, + "minVersion": "1.0.0" }, "code-interpreter-python-sdk": { "displayName": "Code Interpreter Python SDK", "icon": "python", - "order": 6, + "order": 4, "repo": "https://github.com/e2b-dev/code-interpreter.git", "tagPattern": "@e2b/code-interpreter-python@", "tagFormat": "@e2b/code-interpreter-python@{version}", "sdkPaths": ["python"], "generator": "pydoc", "required": false, + "minVersion": "1.0.0", "packages": ["e2b_code_interpreter"] }, "desktop-js-sdk": { "displayName": "Desktop JavaScript SDK", "icon": "square-js", - "order": 7, + "order": 5, "repo": "https://github.com/e2b-dev/desktop.git", "tagPattern": "@e2b/desktop@", "tagFormat": "@e2b/desktop@{version}", "sdkPaths": ["packages/js-sdk"], "generator": "typedoc", - "required": false + "required": false, + "minVersion": "1.0.0" }, "desktop-python-sdk": { "displayName": "Desktop Python SDK", "icon": "python", - "order": 8, + "order": 6, "repo": "https://github.com/e2b-dev/desktop.git", "tagPattern": "@e2b/desktop-python@", "tagFormat": "@e2b/desktop-python@{version}", "sdkPaths": ["packages/python-sdk"], "generator": "pydoc", "required": false, + "minVersion": "1.0.0", "packages": ["e2b_desktop"] } } From a191e97f01cffea85e18c4a9d91cb73f11641e6b Mon Sep 17 00:00:00 2001 From: ben-fornefeld Date: Wed, 7 Jan 2026 17:08:58 +0100 Subject: [PATCH 07/39] improve: better idempotency comparison --- scripts/generate-sdk.sh | 66 ++++++++++++++------ scripts/lib/common.sh | 130 +++++++++++++++++++++++++++++++++++++--- scripts/sdks.json | 12 ++-- 3 files changed, 176 insertions(+), 32 deletions(-) diff --git a/scripts/generate-sdk.sh b/scripts/generate-sdk.sh index 4f208c6..fed2b2b 100755 --- a/scripts/generate-sdk.sh +++ b/scripts/generate-sdk.sh @@ -70,29 +70,41 @@ if [[ "$VERSION" == "all" ]]; then fi TOTAL_COUNT=$(echo "$ALL_VERSIONS" | wc -l | tr -d ' ') - EXISTING_COUNT=$(count_sdk_versions "$SDK_KEY" "$DOCS_DIR") + + # get local versions in one batch (fast) + LOCAL_VERSIONS=$(get_local_versions "$SDK_KEY" "$DOCS_DIR") + if [[ -n "$LOCAL_VERSIONS" ]]; then + EXISTING_COUNT=$(echo "$LOCAL_VERSIONS" | wc -l | tr -d ' ') + else + EXISTING_COUNT=0 + fi echo "" echo " 📊 Version Discovery Report:" echo " Total tags found: $TOTAL_COUNT" echo " Already generated: $EXISTING_COUNT" - # filter to only missing versions - MISSING_VERSIONS="" - SKIP_COUNT=0 - for version in $ALL_VERSIONS; do - if version_exists "$SDK_KEY" "$version" "$DOCS_DIR"; then - ((SKIP_COUNT++)) || true - else - if [[ -z "$MISSING_VERSIONS" ]]; then - MISSING_VERSIONS="$version" - else - MISSING_VERSIONS="$MISSING_VERSIONS $version" - fi + # early exit if all versions exist (O(1) check) + if [[ $TOTAL_COUNT -eq $EXISTING_COUNT && $EXISTING_COUNT -gt 0 ]]; then + echo " → Quick check: counts match, verifying..." + + # verify using batch set difference + MISSING_VERSIONS=$(find_missing_versions "$ALL_VERSIONS" "$LOCAL_VERSIONS") + + if [[ -z "$MISSING_VERSIONS" ]]; then + echo " ✅ All $TOTAL_COUNT versions already generated (verified)" + exit 0 fi - done + else + # use batch set difference (O(n + m) instead of O(n * m)) + MISSING_VERSIONS=$(find_missing_versions "$ALL_VERSIONS" "$LOCAL_VERSIONS") + fi - MISSING_COUNT=$(echo "$MISSING_VERSIONS" | wc -w | tr -d ' ') + if [[ -n "$MISSING_VERSIONS" ]]; then + MISSING_COUNT=$(echo "$MISSING_VERSIONS" | wc -l | tr -d ' ') + else + MISSING_COUNT=0 + fi echo " To generate: $MISSING_COUNT" echo "" @@ -219,8 +231,24 @@ if [[ $FAILED_COUNT -gt 0 ]]; then echo " Failed: $FAILED_COUNT ($FAILED_VERSIONS)" fi -# exit with error if all failed and required -if [[ $GENERATED_COUNT -eq 0 && "$REQUIRED" == "true" && -n "$VERSIONS_TO_PROCESS" ]]; then - echo " ❌ All versions failed to generate" - exit 1 +# strict error handling - abort on unexpected failures +if [[ $FAILED_COUNT -gt 0 ]]; then + if [[ "$REQUIRED" == "true" ]]; then + # any failure in required SDK = abort + echo "" + echo " ❌ WORKFLOW ABORTED: Required SDK '$SDK_KEY' has failures" + echo " ❌ Failed versions: $FAILED_VERSIONS" + echo " ❌ This indicates an unexpected error that must be fixed" + exit 1 + elif [[ $GENERATED_COUNT -eq 0 ]]; then + # all versions failed for non-required SDK = abort + echo "" + echo " ❌ WORKFLOW ABORTED: All versions of '$SDK_KEY' failed to generate" + echo " ❌ Failed versions: $FAILED_VERSIONS" + echo " ❌ This indicates an unexpected error that must be fixed" + exit 1 + else + # some succeeded, some failed for non-required SDK = warn but continue + echo " ⚠️ Some versions failed but continuing (SDK not required)" + fi fi diff --git a/scripts/lib/common.sh b/scripts/lib/common.sh index 7ad180a..afe5ab1 100755 --- a/scripts/lib/common.sh +++ b/scripts/lib/common.sh @@ -23,6 +23,41 @@ version_exists() { [[ -d "$version_dir" ]] && [[ -n "$(ls -A "$version_dir"/*.mdx 2>/dev/null)" ]] } +# get all locally generated versions for an SDK (only those with MDX files) +get_local_versions() { + local sdk_key="$1" + local docs_dir="$2" + local sdk_ref_dir="$docs_dir/docs/sdk-reference/$sdk_key" + + if [[ ! -d "$sdk_ref_dir" ]]; then + return 0 + fi + + find "$sdk_ref_dir" -maxdepth 1 -type d \( -name "v*" -o -name "[0-9]*" \) 2>/dev/null | \ + while read -r dir; do + # only include if has MDX files + if [[ -n "$(ls -A "$dir"/*.mdx 2>/dev/null)" ]]; then + basename "$dir" + fi + done | sort +} + +# find missing versions using set difference (faster than looping) +find_missing_versions() { + local remote_versions="$1" + local local_versions="$2" + + if [[ -z "$local_versions" ]]; then + echo "$remote_versions" + return 0 + fi + + # use comm to find versions in remote but not in local + comm -13 \ + <(echo "$local_versions") \ + <(echo "$remote_versions" | sort) +} + # validate version string format is_valid_version() { local version="$1" @@ -227,7 +262,7 @@ install_dependencies() { fi ;; pydoc) - poetry install --quiet 2>/dev/null || pip install pydoc-markdown + poetry install --quiet 2>/dev/null || pip install --break-system-packages pydoc-markdown 2>&1 ;; cli) if command -v pnpm &> /dev/null; then @@ -239,6 +274,34 @@ install_dependencies() { esac } +# convert to title case, handling snake_case +to_title_case() { + local str="$1" + if [[ -z "$str" ]]; then + echo "" + return + fi + + # replace underscores with spaces, then capitalize each word + local result="" + local word_start=true + + for (( i=0; i<${#str}; i++ )); do + local char="${str:$i:1}" + if [[ "$char" == "_" ]]; then + result="$result " + word_start=true + elif [[ "$word_start" == true ]]; then + result="$result$(echo "$char" | tr '[:lower:]' '[:upper:]')" + word_start=false + else + result="$result$char" + fi + done + + echo "$result" +} + flatten_markdown() { local sdk_ref_dir="$1" @@ -259,12 +322,16 @@ flatten_markdown() { find . -type d -empty -delete 2>/dev/null || true + # remove standalone index.md files (not needed for Mintlify) + rm -f index.md + shopt -s nullglob for file in *.md; do local mdx_file="${file%.md}.mdx" + local title=$(to_title_case "$(basename "$file" .md)") { echo "---" - echo "sidebarTitle: \"$(basename "$file" .md)\"" + echo "sidebarTitle: \"$title\"" echo "mode: \"center\"" echo "---" echo "" @@ -272,14 +339,14 @@ flatten_markdown() { } > "$mdx_file" rm "$file" done - shopt -u nullglob for file in *.mdx; do if ! head -n1 "$file" | grep -q "^---$"; then local tmp_file="${file}.tmp" + local title=$(to_title_case "$(basename "$file" .mdx)") { echo "---" - echo "sidebarTitle: \"$(basename "$file" .mdx)\"" + echo "sidebarTitle: \"$title\"" echo "mode: \"center\"" echo "---" echo "" @@ -288,6 +355,10 @@ flatten_markdown() { mv "$tmp_file" "$file" fi done + shopt -u nullglob + + # remove index.mdx files (not needed for Mintlify) + rm -f index.mdx } copy_to_docs() { @@ -296,16 +367,61 @@ copy_to_docs() { local sdk_name="$3" local version="$4" + # remove any literal "*.mdx" file that might have been created by error + rm -f "$src_dir/*.mdx" 2>/dev/null + + # use find to count actual .mdx files (not globs) + local mdx_count=$(find "$src_dir" -maxdepth 1 -name "*.mdx" -type f 2>/dev/null | wc -l | tr -d ' ') + + if [[ "$mdx_count" -eq 0 ]]; then + echo " ❌ No MDX files generated - documentation generation failed" + echo " ❌ This indicates a problem with the doc generator (typedoc/pydoc)" + return 1 + fi + + # verify files are valid (not empty, not just "*.mdx") + local has_valid_file=false + while IFS= read -r -d '' file; do + local filename=$(basename "$file") + # check if filename is literally "*.mdx" or file is empty + if [[ "$filename" == "*.mdx" ]]; then + echo " ❌ Found invalid file: $filename (glob pattern, not a real file)" + rm -f "$file" + continue + fi + if [[ ! -s "$file" ]]; then + echo " ⚠️ Found empty file: $filename" + continue + fi + has_valid_file=true + done < <(find "$src_dir" -maxdepth 1 -name "*.mdx" -type f -print0) + + if [[ "$has_valid_file" != "true" ]]; then + echo " ❌ No valid MDX files generated - all files are empty or invalid" + return 1 + fi + + # recount after cleanup + mdx_count=$(find "$src_dir" -maxdepth 1 -name "*.mdx" -type f 2>/dev/null | wc -l | tr -d ' ') + + if [[ "$mdx_count" -eq 0 ]]; then + echo " ❌ No valid MDX files to copy" + return 1 + fi + + # only create directory if we have files to copy mkdir -p "$target_dir" - echo " → Copying files to $target_dir" - if cp "$src_dir"/*.mdx "$target_dir/" 2>/dev/null; then + echo " → Copying $mdx_count files to $target_dir" + if find "$src_dir" -maxdepth 1 -name "*.mdx" -type f -exec cp {} "$target_dir/" \; 2>/dev/null; then echo " → Generated files:" ls -la "$target_dir" echo " ✅ $sdk_name $version complete" return 0 else - echo " ⚠️ No MDX files to copy" + echo " ❌ Failed to copy MDX files" + # cleanup empty directory if copy failed + rmdir "$target_dir" 2>/dev/null || true return 1 fi } diff --git a/scripts/sdks.json b/scripts/sdks.json index 3b45f04..bd76b48 100644 --- a/scripts/sdks.json +++ b/scripts/sdks.json @@ -13,7 +13,7 @@ "minVersion": "1.0.0" }, "js-sdk": { - "displayName": "JavaScript SDK", + "displayName": "SDK (JavaScript)", "icon": "square-js", "order": 1, "repo": "https://github.com/e2b-dev/e2b.git", @@ -25,7 +25,7 @@ "minVersion": "1.0.0" }, "python-sdk": { - "displayName": "Python SDK", + "displayName": "SDK (Python)", "icon": "python", "order": 2, "repo": "https://github.com/e2b-dev/e2b.git", @@ -48,7 +48,7 @@ } }, "code-interpreter-js-sdk": { - "displayName": "Code Interpreter JavaScript SDK", + "displayName": "Code Interpreter SDK (JavaScript)", "icon": "square-js", "order": 3, "repo": "https://github.com/e2b-dev/code-interpreter.git", @@ -60,7 +60,7 @@ "minVersion": "1.0.0" }, "code-interpreter-python-sdk": { - "displayName": "Code Interpreter Python SDK", + "displayName": "Code Interpreter SDK (Python)", "icon": "python", "order": 4, "repo": "https://github.com/e2b-dev/code-interpreter.git", @@ -73,7 +73,7 @@ "packages": ["e2b_code_interpreter"] }, "desktop-js-sdk": { - "displayName": "Desktop JavaScript SDK", + "displayName": "Desktop SDK (JavaScript)", "icon": "square-js", "order": 5, "repo": "https://github.com/e2b-dev/desktop.git", @@ -85,7 +85,7 @@ "minVersion": "1.0.0" }, "desktop-python-sdk": { - "displayName": "Desktop Python SDK", + "displayName": "Desktop SDK (Python)", "icon": "python", "order": 6, "repo": "https://github.com/e2b-dev/desktop.git", From ddcf32a59f6e57aaa43c3b3a3446b0bbb8b9cfdd Mon Sep 17 00:00:00 2001 From: ben-fornefeld Date: Wed, 7 Jan 2026 17:18:47 +0100 Subject: [PATCH 08/39] cleanup --- scripts/generate-sdk.sh | 265 +++++++++++------------------ scripts/generators/pydoc.sh | 53 +++--- scripts/lib/common.sh | 330 ++++++++++++------------------------ 3 files changed, 230 insertions(+), 418 deletions(-) diff --git a/scripts/generate-sdk.sh b/scripts/generate-sdk.sh index fed2b2b..c07d86e 100755 --- a/scripts/generate-sdk.sh +++ b/scripts/generate-sdk.sh @@ -2,7 +2,7 @@ set -euo pipefail SDK_KEY="$1" -VERSION="$2" +VERSION_ARG="$2" TEMP_DIR="$3" DOCS_DIR="$4" @@ -12,243 +12,170 @@ CONFIGS_DIR="$SCRIPT_DIR/configs" source "$SCRIPT_DIR/lib/common.sh" -get_config() { - local path="$1" - node -e "const c = require('$CONFIG_FILE').sdks['$SDK_KEY']; console.log(c && c.$path !== undefined ? c.$path : '')" +read_config() { + node -e "const c = require('$CONFIG_FILE').sdks['$SDK_KEY']; console.log(c && c.$1 !== undefined ? c.$1 : '')" } -get_config_array() { - local path="$1" - node -e "const c = require('$CONFIG_FILE').sdks['$SDK_KEY']; const v = c && c.$path; if(Array.isArray(v)) console.log(v.join(' '));" +read_config_array() { + node -e "const c = require('$CONFIG_FILE').sdks['$SDK_KEY']; const v = c && c.$1; if(Array.isArray(v)) console.log(v.join(' '));" } -DISPLAY_NAME=$(get_config "displayName") -REPO=$(get_config "repo") -TAG_PATTERN=$(get_config "tagPattern") -TAG_FORMAT=$(get_config "tagFormat") -GENERATOR=$(get_config "generator") -REQUIRED=$(get_config "required") -SDK_PATH=$(get_config "sdkPath") -SDK_PATHS=$(get_config_array "sdkPaths") -PACKAGES=$(get_config_array "packages") -MIN_VERSION=$(get_config "minVersion") +DISPLAY_NAME=$(read_config "displayName") +REPO=$(read_config "repo") +TAG_PATTERN=$(read_config "tagPattern") +TAG_FORMAT=$(read_config "tagFormat") +GENERATOR=$(read_config "generator") +IS_REQUIRED=$(read_config "required") +SDK_PATH=$(read_config "sdkPath") +SDK_PATHS=$(read_config_array "sdkPaths") +PACKAGES=$(read_config_array "packages") +MIN_VERSION=$(read_config "minVersion") -if [[ -z "$DISPLAY_NAME" ]]; then - echo " ❌ SDK '$SDK_KEY' not found in configuration" - exit 1 -fi +[[ -z "$DISPLAY_NAME" ]] && echo " ❌ SDK '$SDK_KEY' not found in config" && exit 1 -echo " → $DISPLAY_NAME version: $VERSION" +echo " → $DISPLAY_NAME version: $VERSION_ARG" -# determine versions to process -VERSIONS_TO_PROCESS="" +PENDING_VERSIONS="" -if [[ "$VERSION" == "all" ]]; then +if [[ "$VERSION_ARG" == "all" ]]; then echo " → Discovering all versions..." - ALL_VERSIONS=$(get_all_versions "$REPO" "$TAG_PATTERN") + REMOTE_VERSIONS=$(fetch_remote_tags "$REPO" "$TAG_PATTERN") - if [[ -z "$ALL_VERSIONS" ]]; then - if [[ "$REQUIRED" == "true" ]]; then - echo " ❌ No tags found for $DISPLAY_NAME" - exit 1 - else - echo " ⚠️ No tags found, skipping..." - exit 0 - fi + if [[ -z "$REMOTE_VERSIONS" ]]; then + [[ "$IS_REQUIRED" == "true" ]] && echo " ❌ No tags found" && exit 1 + echo " ⚠️ No tags found, skipping..." + exit 0 fi - # filter by minVersion if set - if [[ -n "$MIN_VERSION" ]]; then - ALL_VERSIONS=$(filter_min_version "$ALL_VERSIONS" "$MIN_VERSION") + [[ -n "$MIN_VERSION" ]] && \ + REMOTE_VERSIONS=$(filter_by_min_version "$REMOTE_VERSIONS" "$MIN_VERSION") && \ echo " → Filtered to versions >= $MIN_VERSION" - fi - # apply limit if set (from SDK_VERSION_LIMIT env var) - if [[ -n "${SDK_VERSION_LIMIT:-}" && "$SDK_VERSION_LIMIT" =~ ^[0-9]+$ ]]; then - ALL_VERSIONS=$(echo "$ALL_VERSIONS" | head -n "$SDK_VERSION_LIMIT") + [[ -n "${SDK_VERSION_LIMIT:-}" ]] && [[ "$SDK_VERSION_LIMIT" =~ ^[0-9]+$ ]] && \ + REMOTE_VERSIONS=$(echo "$REMOTE_VERSIONS" | head -n "$SDK_VERSION_LIMIT") && \ echo " → Limited to last $SDK_VERSION_LIMIT versions" - fi - TOTAL_COUNT=$(echo "$ALL_VERSIONS" | wc -l | tr -d ' ') - - # get local versions in one batch (fast) - LOCAL_VERSIONS=$(get_local_versions "$SDK_KEY" "$DOCS_DIR") - if [[ -n "$LOCAL_VERSIONS" ]]; then - EXISTING_COUNT=$(echo "$LOCAL_VERSIONS" | wc -l | tr -d ' ') - else - EXISTING_COUNT=0 - fi + TOTAL=$(echo "$REMOTE_VERSIONS" | wc -l | tr -d ' ') + LOCAL_VERSIONS=$(fetch_local_versions "$SDK_KEY" "$DOCS_DIR") + EXISTING=$(echo "$LOCAL_VERSIONS" | wc -l | tr -d ' ') + [[ -z "$LOCAL_VERSIONS" ]] && EXISTING=0 echo "" - echo " 📊 Version Discovery Report:" - echo " Total tags found: $TOTAL_COUNT" - echo " Already generated: $EXISTING_COUNT" - - # early exit if all versions exist (O(1) check) - if [[ $TOTAL_COUNT -eq $EXISTING_COUNT && $EXISTING_COUNT -gt 0 ]]; then - echo " → Quick check: counts match, verifying..." - - # verify using batch set difference - MISSING_VERSIONS=$(find_missing_versions "$ALL_VERSIONS" "$LOCAL_VERSIONS") - - if [[ -z "$MISSING_VERSIONS" ]]; then - echo " ✅ All $TOTAL_COUNT versions already generated (verified)" - exit 0 - fi + echo " 📊 Version Discovery:" + echo " Remote: $TOTAL" + echo " Local: $EXISTING" + + if [[ $TOTAL -eq $EXISTING && $EXISTING -gt 0 ]]; then + echo " → Quick check: verifying..." + MISSING=$(diff_versions "$REMOTE_VERSIONS" "$LOCAL_VERSIONS") + [[ -z "$MISSING" ]] && echo " ✅ All $TOTAL versions exist" && exit 0 else - # use batch set difference (O(n + m) instead of O(n * m)) - MISSING_VERSIONS=$(find_missing_versions "$ALL_VERSIONS" "$LOCAL_VERSIONS") + MISSING=$(diff_versions "$REMOTE_VERSIONS" "$LOCAL_VERSIONS") fi - if [[ -n "$MISSING_VERSIONS" ]]; then - MISSING_COUNT=$(echo "$MISSING_VERSIONS" | wc -l | tr -d ' ') - else - MISSING_COUNT=0 - fi - echo " To generate: $MISSING_COUNT" + MISSING_COUNT=$(echo "$MISSING" | wc -l | tr -d ' ') + [[ -z "$MISSING" ]] && MISSING_COUNT=0 + + echo " Missing: $MISSING_COUNT" echo "" - if [[ -z "$MISSING_VERSIONS" || "$MISSING_COUNT" -eq 0 ]]; then - echo " ✅ All versions already generated, nothing to do" - exit 0 - fi + [[ $MISSING_COUNT -eq 0 ]] && echo " ✅ Nothing to generate" && exit 0 - VERSIONS_TO_PROCESS="$MISSING_VERSIONS" + PENDING_VERSIONS="$MISSING" else - # single version (latest or specific) - RESOLVED_VERSION=$(resolve_version "$REPO" "$TAG_PATTERN" "$VERSION") || true - - if [[ -z "$RESOLVED_VERSION" ]]; then - if [[ "$REQUIRED" == "true" ]]; then - echo " ❌ No tags found for $DISPLAY_NAME" - exit 1 - else - echo " ⚠️ No tags found, skipping..." - exit 0 - fi - fi + RESOLVED=$(resolve_latest_version "$REPO" "$TAG_PATTERN" "$VERSION_ARG") - if version_exists "$SDK_KEY" "$RESOLVED_VERSION" "$DOCS_DIR"; then - echo " ✓ $RESOLVED_VERSION already exists, skipping" + if [[ -z "$RESOLVED" ]]; then + [[ "$IS_REQUIRED" == "true" ]] && echo " ❌ No tags found" && exit 1 + echo " ⚠️ No tags found, skipping..." exit 0 fi - VERSIONS_TO_PROCESS="$RESOLVED_VERSION" + version_exists "$SDK_KEY" "$RESOLVED" "$DOCS_DIR" && \ + echo " ✓ $RESOLVED already exists" && exit 0 + + PENDING_VERSIONS="$RESOLVED" fi -# track generation results -GENERATED_COUNT=0 -FAILED_COUNT=0 -FAILED_VERSIONS="" +generated=0 +failed=0 +failed_list="" -# process each version -for RESOLVED_VERSION in $VERSIONS_TO_PROCESS; do +for version in $PENDING_VERSIONS; do echo "" - echo " 📦 Generating $RESOLVED_VERSION..." + echo " 📦 Generating $version..." - # use version-specific temp dir for isolation - REPO_DIR="$TEMP_DIR/${SDK_KEY}-${RESOLVED_VERSION}" - GIT_TAG=$(echo "$TAG_FORMAT" | sed "s/{version}/${RESOLVED_VERSION#v}/") + repo_dir="$TEMP_DIR/${SDK_KEY}-${version}" + git_tag=$(echo "$TAG_FORMAT" | sed "s/{version}/${version#v}/") - # attempt generation with error handling if ! ( set -e - clone_repo "$REPO" "$GIT_TAG" "$REPO_DIR" + clone_repo "$REPO" "$git_tag" "$repo_dir" - SDK_DIR="" if [[ -n "$SDK_PATH" ]]; then - SDK_DIR="$REPO_DIR/$SDK_PATH" - if [[ ! -d "$SDK_DIR" ]]; then - echo " ❌ SDK directory not found: $SDK_DIR" - exit 1 - fi + sdk_dir="$repo_dir/$SDK_PATH" + [[ ! -d "$sdk_dir" ]] && echo " ❌ SDK path not found: $SDK_PATH" && exit 1 elif [[ -n "$SDK_PATHS" ]]; then - SDK_DIR=$(find_sdk_directory "$REPO_DIR" $SDK_PATHS) || true - if [[ -z "$SDK_DIR" ]]; then - echo " ⚠️ SDK directory not found in any of: $SDK_PATHS" - exit 1 - fi + sdk_dir=$(locate_sdk_dir "$repo_dir" $SDK_PATHS) + [[ -z "$sdk_dir" ]] && echo " ❌ SDK not found in: $SDK_PATHS" && exit 1 else - SDK_DIR="$REPO_DIR" + sdk_dir="$repo_dir" fi - install_dependencies_cached "$SDK_DIR" "$GENERATOR" "$TEMP_DIR" + install_with_cache "$sdk_dir" "$GENERATOR" "$TEMP_DIR" source "$SCRIPT_DIR/generators/${GENERATOR}.sh" case "$GENERATOR" in typedoc) - generate_typedoc "$SDK_DIR" "$CONFIGS_DIR" + generate_typedoc "$sdk_dir" "$CONFIGS_DIR" ;; pydoc) - SUBMODULES=$(node -e "const c = require('$CONFIG_FILE').sdks['$SDK_KEY']; const v = c?.submodules?.['e2b.template']; if(Array.isArray(v)) console.log(v.join(' '));" || echo "") - generate_pydoc "$SDK_DIR" "$PACKAGES" "$SUBMODULES" + submodules=$(node -e "const c = require('$CONFIG_FILE').sdks['$SDK_KEY']; const v = c?.submodules?.['e2b.template']; if(Array.isArray(v)) console.log(v.join(' '));" || echo "") + generate_pydoc "$sdk_dir" "$PACKAGES" "$submodules" ;; cli) - generate_cli_docs "$SDK_DIR" + generate_cli_docs "$sdk_dir" ;; *) - echo " ❌ Unknown generator: $GENERATOR" - exit 1 + echo " ❌ Unknown generator: $GENERATOR" && exit 1 ;; esac - if [[ -d "$SDK_DIR/sdk_ref" ]]; then - flatten_markdown "$SDK_DIR/sdk_ref" - - copy_to_docs "$SDK_DIR/sdk_ref" \ - "$DOCS_DIR/docs/sdk-reference/$SDK_KEY/$RESOLVED_VERSION" \ - "$DISPLAY_NAME" "$RESOLVED_VERSION" - else - echo " ⚠️ No sdk_ref directory found" - exit 1 - fi + [[ ! -d "$sdk_dir/sdk_ref" ]] && echo " ❌ No sdk_ref directory" && exit 1 + + flatten_markdown "$sdk_dir/sdk_ref" + copy_to_docs "$sdk_dir/sdk_ref" \ + "$DOCS_DIR/docs/sdk-reference/$SDK_KEY/$version" \ + "$DISPLAY_NAME" "$version" ); then - echo " ❌ Failed to generate $RESOLVED_VERSION" - ((FAILED_COUNT++)) || true - if [[ -z "$FAILED_VERSIONS" ]]; then - FAILED_VERSIONS="$RESOLVED_VERSION" - else - FAILED_VERSIONS="$FAILED_VERSIONS $RESOLVED_VERSION" - fi - # continue to next version instead of failing + echo " ❌ Failed: $version" + ((failed++)) || true + failed_list="${failed_list:+$failed_list }$version" continue fi - echo " ✅ Complete: $RESOLVED_VERSION" - ((GENERATED_COUNT++)) || true - - # cleanup version-specific temp dir to save space - rm -rf "$REPO_DIR" + echo " ✅ Complete: $version" + ((generated++)) || true + rm -rf "$repo_dir" done -# print summary echo "" -echo " 📊 Generation Summary for $DISPLAY_NAME:" -echo " Successfully generated: $GENERATED_COUNT" -if [[ $FAILED_COUNT -gt 0 ]]; then - echo " Failed: $FAILED_COUNT ($FAILED_VERSIONS)" -fi +echo " 📊 Summary:" +echo " Generated: $generated" +[[ $failed -gt 0 ]] && echo " Failed: $failed ($failed_list)" -# strict error handling - abort on unexpected failures -if [[ $FAILED_COUNT -gt 0 ]]; then - if [[ "$REQUIRED" == "true" ]]; then - # any failure in required SDK = abort +if [[ $failed -gt 0 ]]; then + if [[ "$IS_REQUIRED" == "true" ]]; then echo "" - echo " ❌ WORKFLOW ABORTED: Required SDK '$SDK_KEY' has failures" - echo " ❌ Failed versions: $FAILED_VERSIONS" - echo " ❌ This indicates an unexpected error that must be fixed" + echo " ❌ WORKFLOW ABORTED: Required SDK has failures" + echo " ❌ Failed: $failed_list" exit 1 - elif [[ $GENERATED_COUNT -eq 0 ]]; then - # all versions failed for non-required SDK = abort + elif [[ $generated -eq 0 ]]; then echo "" - echo " ❌ WORKFLOW ABORTED: All versions of '$SDK_KEY' failed to generate" - echo " ❌ Failed versions: $FAILED_VERSIONS" - echo " ❌ This indicates an unexpected error that must be fixed" + echo " ❌ WORKFLOW ABORTED: All versions failed" + echo " ❌ Failed: $failed_list" exit 1 - else - # some succeeded, some failed for non-required SDK = warn but continue - echo " ⚠️ Some versions failed but continuing (SDK not required)" fi fi diff --git a/scripts/generators/pydoc.sh b/scripts/generators/pydoc.sh index 2c7609d..e45af9c 100755 --- a/scripts/generators/pydoc.sh +++ b/scripts/generators/pydoc.sh @@ -2,12 +2,28 @@ process_mdx() { local file="$1" - local tmp_file="${file}.tmp" + local tmp="${file}.tmp" - sed '/]*>.*<\/a>/d' "${file}" > "${tmp_file}" && mv "${tmp_file}" "${file}" - sed '/^# /d' "${file}" > "${tmp_file}" && mv "${tmp_file}" "${file}" - sed '/^## / s/ Objects$//' "${file}" > "${tmp_file}" && mv "${tmp_file}" "${file}" - sed 's/^####/###/' "${file}" > "${tmp_file}" && mv "${tmp_file}" "${file}" + sed '/]*>.*<\/a>/d' "$file" > "$tmp" && mv "$tmp" "$file" + sed '/^# /d' "$file" > "$tmp" && mv "$tmp" "$file" + sed '/^## / s/ Objects$//' "$file" > "$tmp" && mv "$tmp" "$file" + sed 's/^####/###/' "$file" > "$tmp" && mv "$tmp" "$file" +} + +process_package() { + local pkg="$1" + local sdk_dir="$2" + local name="${pkg##*.}" + name="${name#e2b_}" + + echo " → Processing $pkg..." + + if poetry run pydoc-markdown -p "$pkg" > "$sdk_dir/sdk_ref/${name}.mdx" 2>/dev/null; then + process_mdx "$sdk_dir/sdk_ref/${name}.mdx" + else + echo " ⚠️ Failed to generate docs for $pkg" + rm -f "$sdk_dir/sdk_ref/${name}.mdx" + fi } generate_pydoc() { @@ -21,31 +37,12 @@ generate_pydoc() { echo " → Generating documentation for packages..." for pkg in $packages; do - local output_name="${pkg##*.}" - echo " → Processing ${pkg}..." - - if poetry run pydoc-markdown -p "$pkg" > "sdk_ref/${output_name}.mdx" 2>/dev/null; then - process_mdx "sdk_ref/${output_name}.mdx" - else - echo " ⚠️ Failed to generate docs for ${pkg}" - rm -f "sdk_ref/${output_name}.mdx" - fi + process_package "$pkg" "$sdk_dir" done - if [[ -n "$submodules" ]]; then - for submod in $submodules; do - local output_name="${submod##*.}" - echo " → Processing ${submod}..." - - if poetry run pydoc-markdown -p "$submod" > "sdk_ref/${output_name}.mdx" 2>/dev/null; then - process_mdx "sdk_ref/${output_name}.mdx" - else - echo " ⚠️ Failed to generate docs for ${submod}" - rm -f "sdk_ref/${output_name}.mdx" - fi - done - fi + for submod in $submodules; do + process_package "$submod" "$sdk_dir" + done return 0 } - diff --git a/scripts/lib/common.sh b/scripts/lib/common.sh index afe5ab1..ff7431c 100755 --- a/scripts/lib/common.sh +++ b/scripts/lib/common.sh @@ -1,137 +1,81 @@ #!/usr/bin/env bash -# get all versions matching tag pattern (sorted newest first) -get_all_versions() { +fetch_remote_tags() { local repo="$1" local tag_pattern="$2" - - local sed_escaped_pattern=$(echo "$tag_pattern" | sed 's/[\/&@]/\\&/g') + local escaped_pattern=$(echo "$tag_pattern" | sed 's/[\/&@]/\\&/g') git ls-remote --tags --refs "$repo" 2>/dev/null | \ grep "refs/tags/${tag_pattern}" | \ - sed "s|.*refs/tags/${sed_escaped_pattern}|v|" | \ + sed "s|.*refs/tags/${escaped_pattern}|v|" | \ sort -V -r } -# check if version documentation already exists version_exists() { local sdk_key="$1" local version="$2" local docs_dir="$3" - local version_dir="$docs_dir/docs/sdk-reference/$sdk_key/$version" + [[ -d "$version_dir" ]] && [[ -n "$(ls -A "$version_dir"/*.mdx 2>/dev/null)" ]] } -# get all locally generated versions for an SDK (only those with MDX files) -get_local_versions() { +fetch_local_versions() { local sdk_key="$1" local docs_dir="$2" - local sdk_ref_dir="$docs_dir/docs/sdk-reference/$sdk_key" + local sdk_dir="$docs_dir/docs/sdk-reference/$sdk_key" - if [[ ! -d "$sdk_ref_dir" ]]; then - return 0 - fi + [[ ! -d "$sdk_dir" ]] && return 0 - find "$sdk_ref_dir" -maxdepth 1 -type d \( -name "v*" -o -name "[0-9]*" \) 2>/dev/null | \ + find "$sdk_dir" -maxdepth 1 -type d \( -name "v*" -o -name "[0-9]*" \) 2>/dev/null | \ while read -r dir; do - # only include if has MDX files - if [[ -n "$(ls -A "$dir"/*.mdx 2>/dev/null)" ]]; then - basename "$dir" - fi + [[ -n "$(ls -A "$dir"/*.mdx 2>/dev/null)" ]] && basename "$dir" done | sort } -# find missing versions using set difference (faster than looping) -find_missing_versions() { - local remote_versions="$1" - local local_versions="$2" +diff_versions() { + local remote="$1" + local local="$2" - if [[ -z "$local_versions" ]]; then - echo "$remote_versions" - return 0 - fi + [[ -z "$local" ]] && echo "$remote" && return 0 - # use comm to find versions in remote but not in local - comm -13 \ - <(echo "$local_versions") \ - <(echo "$remote_versions" | sort) + comm -13 <(echo "$local") <(echo "$remote" | sort) } -# validate version string format is_valid_version() { - local version="$1" - [[ "$version" =~ ^v?[0-9]+\.[0-9]+\.[0-9]+$ ]] + [[ "$1" =~ ^v?[0-9]+\.[0-9]+\.[0-9]+$ ]] } -# compare two versions (returns 0 if v1 >= v2) version_gte() { - local v1="$1" - local v2="$2" - - # strip 'v' prefix if present - v1="${v1#v}" - v2="${v2#v}" - - # use sort -V to compare versions + local v1="${1#v}" + local v2="${2#v}" local higher=$(printf '%s\n%s' "$v1" "$v2" | sort -V -r | head -n1) [[ "$higher" == "$v1" ]] } -# filter versions to only those >= minVersion -filter_min_version() { +filter_by_min_version() { local versions="$1" - local min_version="$2" + local min="$2" - if [[ -z "$min_version" ]]; then - echo "$versions" - return 0 - fi + [[ -z "$min" ]] && echo "$versions" && return 0 - echo "$versions" | while IFS= read -r version; do - if [[ -n "$version" ]] && version_gte "$version" "$min_version"; then - echo "$version" - fi + echo "$versions" | while IFS= read -r v; do + [[ -n "$v" ]] && version_gte "$v" "$min" && echo "$v" done } -# count existing versions for an SDK -count_sdk_versions() { - local sdk_key="$1" - local docs_dir="$2" - local sdk_ref_dir="$docs_dir/docs/sdk-reference/$sdk_key" - - if [[ ! -d "$sdk_ref_dir" ]]; then - echo "0" - return - fi - - find "$sdk_ref_dir" -maxdepth 1 -type d \( -name "v*" -o -name "[0-9]*" \) 2>/dev/null | wc -l | tr -d ' ' -} - -resolve_version() { +resolve_latest_version() { local repo="$1" local tag_pattern="$2" local version="$3" - if [[ "$version" != "latest" ]]; then - echo "$version" - return 0 - fi - - local sed_escaped_pattern=$(echo "$tag_pattern" | sed 's/[\/&@]/\\&/g') - - local resolved - resolved=$(git ls-remote --tags --refs "$repo" 2>/dev/null | \ - grep "refs/tags/${tag_pattern}" | \ - sed "s|.*refs/tags/${sed_escaped_pattern}|v|" | \ - sort -V | tail -1) || true - - if [[ -z "$resolved" ]]; then - return 1 - fi + [[ "$version" != "latest" ]] && echo "$version" && return 0 - echo "$resolved" + local escaped=$(echo "$tag_pattern" | sed 's/[\/&@]/\\&/g') + git ls-remote --tags --refs "$repo" 2>/dev/null | \ + grep "refs/tags/${tag_pattern}" | \ + sed "s|.*refs/tags/${escaped}|v|" | \ + sort -V | tail -1 } clone_repo() { @@ -150,97 +94,71 @@ clone_repo() { } } -find_sdk_directory() { - local base_dir="$1" +locate_sdk_dir() { + local repo_dir="$1" shift for path in "$@"; do - local full_path="${base_dir}/${path}" - if [[ -d "$full_path" ]]; then - echo "$full_path" - return 0 - fi + [[ -d "$repo_dir/$path" ]] && echo "$repo_dir/$path" && return 0 done return 1 } -# find lockfile, searching up directory tree -find_lockfile() { +find_lockfile_up() { local dir="$1" local filename="$2" while [[ "$dir" != "/" && "$dir" != "." ]]; do - if [[ -f "$dir/$filename" ]]; then - echo "$dir/$filename" - return 0 - fi + [[ -f "$dir/$filename" ]] && echo "$dir/$filename" && return 0 dir=$(dirname "$dir") done return 1 } -# compute hash of lockfile for caching -get_lockfile_hash() { +hash_lockfile() { local sdk_dir="$1" local generator="$2" - local lockfile="" + case "$generator" in typedoc|cli) - lockfile=$(find_lockfile "$sdk_dir" "pnpm-lock.yaml") || \ - lockfile=$(find_lockfile "$sdk_dir" "package-lock.json") || true + lockfile=$(find_lockfile_up "$sdk_dir" "pnpm-lock.yaml") || \ + lockfile=$(find_lockfile_up "$sdk_dir" "package-lock.json") || true ;; pydoc) - lockfile=$(find_lockfile "$sdk_dir" "poetry.lock") || true + lockfile=$(find_lockfile_up "$sdk_dir" "poetry.lock") || true ;; esac if [[ -n "$lockfile" && -f "$lockfile" ]]; then - # use md5 on macOS, md5sum on Linux - if command -v md5 &>/dev/null; then - md5 -q "$lockfile" - else - md5sum "$lockfile" | cut -d' ' -f1 - fi + command -v md5 &>/dev/null && md5 -q "$lockfile" || md5sum "$lockfile" | cut -d' ' -f1 fi } -# install dependencies with caching support -# for JS: relies on pnpm's global cache (~/.pnpm-store) with --prefer-offline -# for Python: tracks lockfile hash to skip redundant installs -install_dependencies_cached() { +install_with_cache() { local sdk_dir="$1" local generator="$2" local temp_dir="$3" - case "$generator" in - typedoc|cli) - # pnpm uses content-addressable storage with hardlinks - # --prefer-offline makes it fast, no need to copy node_modules - install_dependencies "$sdk_dir" "$generator" - ;; - pydoc) - local lockfile_hash=$(get_lockfile_hash "$sdk_dir" "$generator") - local cache_marker="$temp_dir/.deps-cache/pydoc-$lockfile_hash/.installed" - - if [[ -n "$lockfile_hash" && -f "$cache_marker" ]]; then - echo " → Poetry dependencies cached (lockfile unchanged)" - return 0 - fi - - install_dependencies "$sdk_dir" "$generator" - - # mark as installed for future versions with same lockfile - if [[ -n "$lockfile_hash" ]]; then - mkdir -p "$(dirname "$cache_marker")" - touch "$cache_marker" - fi - ;; - *) - install_dependencies "$sdk_dir" "$generator" - ;; - esac + if [[ "$generator" == "pydoc" ]]; then + local hash=$(hash_lockfile "$sdk_dir" "$generator") + local marker="$temp_dir/.deps-cache/pydoc-$hash/.installed" + + if [[ -n "$hash" && -f "$marker" ]]; then + echo " → Poetry dependencies cached (lockfile unchanged)" + return 0 + fi + + install_dependencies "$sdk_dir" "$generator" + + if [[ -n "$hash" ]]; then + mkdir -p "$(dirname "$marker")" + touch "$marker" + fi + else + install_dependencies "$sdk_dir" "$generator" + fi } install_dependencies() { @@ -274,26 +192,21 @@ install_dependencies() { esac } -# convert to title case, handling snake_case to_title_case() { local str="$1" - if [[ -z "$str" ]]; then - echo "" - return - fi + [[ -z "$str" ]] && return 0 - # replace underscores with spaces, then capitalize each word local result="" - local word_start=true + local capitalize_next=true for (( i=0; i<${#str}; i++ )); do local char="${str:$i:1}" if [[ "$char" == "_" ]]; then result="$result " - word_start=true - elif [[ "$word_start" == true ]]; then + capitalize_next=true + elif [[ "$capitalize_next" == true ]]; then result="$result$(echo "$char" | tr '[:lower:]' '[:upper:]')" - word_start=false + capitalize_next=false else result="$result$char" fi @@ -302,19 +215,32 @@ to_title_case() { echo "$result" } +add_frontmatter() { + local file="$1" + local title=$(to_title_case "$(basename "$file" .mdx)") + local tmp="${file}.tmp" + + { + echo "---" + echo "sidebarTitle: \"$title\"" + echo "mode: \"center\"" + echo "---" + echo "" + cat "$file" + } > "$tmp" + mv "$tmp" "$file" +} + flatten_markdown() { - local sdk_ref_dir="$1" + local ref_dir="$1" + cd "$ref_dir" - cd "$sdk_ref_dir" - rm -f README.md + rm -f README.md index.md find . -mindepth 2 -type f -name "*.md" 2>/dev/null | while read -r file; do - local dir=$(dirname "$file") local filename=$(basename "$file") - if [[ "$filename" == "page.md" || "$filename" == "index.md" ]]; then - local module=$(basename "$dir") - mv "$file" "./${module}.md" 2>/dev/null || true + mv "$file" "./$(basename "$(dirname "$file")").md" 2>/dev/null || true else mv "$file" "./" 2>/dev/null || true fi @@ -322,12 +248,8 @@ flatten_markdown() { find . -type d -empty -delete 2>/dev/null || true - # remove standalone index.md files (not needed for Mintlify) - rm -f index.md - shopt -s nullglob for file in *.md; do - local mdx_file="${file%.md}.mdx" local title=$(to_title_case "$(basename "$file" .md)") { echo "---" @@ -336,92 +258,58 @@ flatten_markdown() { echo "---" echo "" cat "$file" - } > "$mdx_file" + } > "${file%.md}.mdx" rm "$file" done for file in *.mdx; do - if ! head -n1 "$file" | grep -q "^---$"; then - local tmp_file="${file}.tmp" - local title=$(to_title_case "$(basename "$file" .mdx)") - { - echo "---" - echo "sidebarTitle: \"$title\"" - echo "mode: \"center\"" - echo "---" - echo "" - cat "$file" - } > "$tmp_file" - mv "$tmp_file" "$file" - fi + head -n1 "$file" | grep -q "^---$" || add_frontmatter "$file" done shopt -u nullglob - # remove index.mdx files (not needed for Mintlify) rm -f index.mdx } -copy_to_docs() { +validate_mdx_files() { local src_dir="$1" - local target_dir="$2" - local sdk_name="$3" - local version="$4" - - # remove any literal "*.mdx" file that might have been created by error - rm -f "$src_dir/*.mdx" 2>/dev/null + rm -f "$src_dir/*.mdx" - # use find to count actual .mdx files (not globs) - local mdx_count=$(find "$src_dir" -maxdepth 1 -name "*.mdx" -type f 2>/dev/null | wc -l | tr -d ' ') - - if [[ "$mdx_count" -eq 0 ]]; then - echo " ❌ No MDX files generated - documentation generation failed" - echo " ❌ This indicates a problem with the doc generator (typedoc/pydoc)" - return 1 - fi - - # verify files are valid (not empty, not just "*.mdx") - local has_valid_file=false + local valid_count=0 while IFS= read -r -d '' file; do - local filename=$(basename "$file") - # check if filename is literally "*.mdx" or file is empty - if [[ "$filename" == "*.mdx" ]]; then - echo " ❌ Found invalid file: $filename (glob pattern, not a real file)" + local name=$(basename "$file") + if [[ "$name" == "*.mdx" ]]; then rm -f "$file" + elif [[ ! -s "$file" ]]; then continue + else + ((valid_count++)) || true fi - if [[ ! -s "$file" ]]; then - echo " ⚠️ Found empty file: $filename" - continue - fi - has_valid_file=true done < <(find "$src_dir" -maxdepth 1 -name "*.mdx" -type f -print0) - if [[ "$has_valid_file" != "true" ]]; then - echo " ❌ No valid MDX files generated - all files are empty or invalid" - return 1 - fi + echo "$valid_count" +} + +copy_to_docs() { + local src="$1" + local dest="$2" + local sdk_name="$3" + local version="$4" - # recount after cleanup - mdx_count=$(find "$src_dir" -maxdepth 1 -name "*.mdx" -type f 2>/dev/null | wc -l | tr -d ' ') + local count=$(validate_mdx_files "$src") - if [[ "$mdx_count" -eq 0 ]]; then - echo " ❌ No valid MDX files to copy" + if [[ "$count" -eq 0 ]]; then + echo " ❌ No MDX files generated - doc generator failed" return 1 fi - # only create directory if we have files to copy - mkdir -p "$target_dir" + mkdir -p "$dest" - echo " → Copying $mdx_count files to $target_dir" - if find "$src_dir" -maxdepth 1 -name "*.mdx" -type f -exec cp {} "$target_dir/" \; 2>/dev/null; then - echo " → Generated files:" - ls -la "$target_dir" + echo " → Copying $count files to $dest" + if find "$src" -maxdepth 1 -name "*.mdx" -type f ! -size 0 -exec cp {} "$dest/" \; 2>/dev/null; then echo " ✅ $sdk_name $version complete" return 0 else - echo " ❌ Failed to copy MDX files" - # cleanup empty directory if copy failed - rmdir "$target_dir" 2>/dev/null || true + rmdir "$dest" 2>/dev/null || true return 1 fi } From 3890aa23d907771208a92c17da28590310699c7b Mon Sep 17 00:00:00 2001 From: ben-fornefeld Date: Thu, 8 Jan 2026 09:52:39 +0100 Subject: [PATCH 09/39] refactor: bash to typescript generator --- .github/workflows/sdk-reference-sync.yml | 16 +- docs.json | 68 - scripts/generate-sdk-nav.js | 151 -- scripts/generate-sdk-reference.sh | 96 - scripts/generate-sdk.sh | 181 -- scripts/generators/cli.sh | 38 - scripts/generators/pydoc.sh | 48 - scripts/generators/typedoc.sh | 29 - scripts/lib/common.sh | 316 --- scripts/merge-sdk-nav.js | 58 - sdk-reference-generator/.gitignore | 4 + .../configs/typedoc-theme.cjs | 0 .../configs/typedoc.json | 0 sdk-reference-generator/package.json | 29 + sdk-reference-generator/pnpm-lock.yaml | 1703 +++++++++++++++++ .../sdks.json | 0 .../src/__tests__/files.test.ts | 29 + .../src/__tests__/versions.test.ts | 74 + sdk-reference-generator/src/cli.ts | 103 + sdk-reference-generator/src/generator.ts | 200 ++ sdk-reference-generator/src/generators/cli.ts | 43 + .../src/generators/index.ts | 31 + .../src/generators/pydoc.ts | 72 + .../src/generators/typedoc.ts | 51 + sdk-reference-generator/src/lib/cache.ts | 64 + sdk-reference-generator/src/lib/config.ts | 30 + sdk-reference-generator/src/lib/constants.ts | 7 + sdk-reference-generator/src/lib/files.ts | 175 ++ sdk-reference-generator/src/lib/git.ts | 51 + sdk-reference-generator/src/lib/install.ts | 93 + sdk-reference-generator/src/lib/utils.ts | 34 + sdk-reference-generator/src/lib/versions.ts | 75 + sdk-reference-generator/src/navigation.ts | 166 ++ sdk-reference-generator/src/types.ts | 56 + sdk-reference-generator/tsconfig.json | 18 + sdk-reference-generator/vitest.config.ts | 9 + 36 files changed, 3124 insertions(+), 994 deletions(-) delete mode 100644 scripts/generate-sdk-nav.js delete mode 100755 scripts/generate-sdk-reference.sh delete mode 100755 scripts/generate-sdk.sh delete mode 100755 scripts/generators/cli.sh delete mode 100755 scripts/generators/pydoc.sh delete mode 100755 scripts/generators/typedoc.sh delete mode 100755 scripts/lib/common.sh delete mode 100644 scripts/merge-sdk-nav.js create mode 100644 sdk-reference-generator/.gitignore rename scripts/configs/typedoc-theme.js => sdk-reference-generator/configs/typedoc-theme.cjs (100%) rename {scripts => sdk-reference-generator}/configs/typedoc.json (100%) create mode 100644 sdk-reference-generator/package.json create mode 100644 sdk-reference-generator/pnpm-lock.yaml rename {scripts => sdk-reference-generator}/sdks.json (100%) create mode 100644 sdk-reference-generator/src/__tests__/files.test.ts create mode 100644 sdk-reference-generator/src/__tests__/versions.test.ts create mode 100644 sdk-reference-generator/src/cli.ts create mode 100644 sdk-reference-generator/src/generator.ts create mode 100644 sdk-reference-generator/src/generators/cli.ts create mode 100644 sdk-reference-generator/src/generators/index.ts create mode 100644 sdk-reference-generator/src/generators/pydoc.ts create mode 100644 sdk-reference-generator/src/generators/typedoc.ts create mode 100644 sdk-reference-generator/src/lib/cache.ts create mode 100644 sdk-reference-generator/src/lib/config.ts create mode 100644 sdk-reference-generator/src/lib/constants.ts create mode 100644 sdk-reference-generator/src/lib/files.ts create mode 100644 sdk-reference-generator/src/lib/git.ts create mode 100644 sdk-reference-generator/src/lib/install.ts create mode 100644 sdk-reference-generator/src/lib/utils.ts create mode 100644 sdk-reference-generator/src/lib/versions.ts create mode 100644 sdk-reference-generator/src/navigation.ts create mode 100644 sdk-reference-generator/src/types.ts create mode 100644 sdk-reference-generator/tsconfig.json create mode 100644 sdk-reference-generator/vitest.config.ts diff --git a/.github/workflows/sdk-reference-sync.yml b/.github/workflows/sdk-reference-sync.yml index e3a1b86..041cec4 100644 --- a/.github/workflows/sdk-reference-sync.yml +++ b/.github/workflows/sdk-reference-sync.yml @@ -55,9 +55,13 @@ jobs: with: python-version: "3.11" - - name: Install Node dependencies + - name: Install root dependencies run: pnpm install + - name: Install generator dependencies + working-directory: sdk-reference-generator + run: pnpm install --frozen-lockfile + - name: Install Python dependencies run: pip install -r requirements.txt @@ -81,12 +85,9 @@ jobs: echo "version=${VERSION:-all}" >> $GITHUB_OUTPUT - name: Generate SDK Reference + working-directory: sdk-reference-generator run: | - chmod +x scripts/generate-sdk-reference.sh - chmod +x scripts/generate-sdk.sh - chmod +x scripts/lib/*.sh - chmod +x scripts/generators/*.sh - ./scripts/generate-sdk-reference.sh \ + pnpm run generate \ --sdk "${{ steps.params.outputs.sdk }}" \ --version "${{ steps.params.outputs.version }}" @@ -94,9 +95,6 @@ jobs: run: | echo "Generated SDK reference files:" find docs/sdk-reference -type f -name "*.mdx" 2>/dev/null | head -20 || echo "No MDX files found" - echo "" - echo "Navigation JSON:" - cat sdk_navigation.json 2>/dev/null | head -50 || echo "No navigation file found" - name: Commit and push changes run: | diff --git a/docs.json b/docs.json index 17f8f36..dc9df28 100644 --- a/docs.json +++ b/docs.json @@ -197,74 +197,6 @@ ] } ] - }, - { - "anchor": "SDK Reference", - "icon": "brackets-curly", - "dropdowns": [ - { - "dropdown": "CLI", - "icon": "terminal", - "versions": [ - { - "version": "v2.2.0@latest", - "groups": [ - { - "group": "CLI v2.2.0", - "pages": [ - "docs/sdk-reference/cli/v2.2.0/auth", - "docs/sdk-reference/cli/v2.2.0/sandbox", - "docs/sdk-reference/cli/v2.2.0/template" - ] - } - ] - } - ] - }, - { - "dropdown": "JavaScript SDK", - "icon": "square-js", - "versions": [ - { - "version": "v2.9.0@latest", - "groups": [ - { - "group": "JavaScript SDK v2.9.0", - "pages": [ - "docs/sdk-reference/js-sdk/v2.9.0/commands", - "docs/sdk-reference/js-sdk/v2.9.0/errors", - "docs/sdk-reference/js-sdk/v2.9.0/filesystem", - "docs/sdk-reference/js-sdk/v2.9.0/sandbox", - "docs/sdk-reference/js-sdk/v2.9.0/template" - ] - } - ] - } - ] - }, - { - "dropdown": "Python SDK", - "icon": "python", - "versions": [ - { - "version": "v2.9.0@latest", - "groups": [ - { - "group": "Python SDK v2.9.0", - "pages": [ - "docs/sdk-reference/python-sdk/v2.9.0/exceptions", - "docs/sdk-reference/python-sdk/v2.9.0/sandbox_async", - "docs/sdk-reference/python-sdk/v2.9.0/sandbox_sync", - "docs/sdk-reference/python-sdk/v2.9.0/template", - "docs/sdk-reference/python-sdk/v2.9.0/template_async", - "docs/sdk-reference/python-sdk/v2.9.0/template_sync" - ] - } - ] - } - ] - } - ] } ], "global": {} diff --git a/scripts/generate-sdk-nav.js b/scripts/generate-sdk-nav.js deleted file mode 100644 index 35889d9..0000000 --- a/scripts/generate-sdk-nav.js +++ /dev/null @@ -1,151 +0,0 @@ -#!/usr/bin/env node - -const fs = require('fs'); -const path = require('path'); - -let semver; -try { - semver = require('semver'); -} catch { - semver = null; -} - -const SCRIPT_DIR = __dirname; -const DOCS_DIR = path.join(SCRIPT_DIR, '..'); -const SDK_REF_DIR = path.join(DOCS_DIR, 'docs', 'sdk-reference'); -const CONFIG_FILE = path.join(SCRIPT_DIR, 'sdks.json'); -const OUTPUT_FILE = path.join(DOCS_DIR, 'sdk_navigation.json'); - -function loadSdkConfigs() { - try { - const config = require(CONFIG_FILE); - return Object.fromEntries( - Object.entries(config.sdks).map(([key, sdk]) => [ - key, - { - name: sdk.displayName, - icon: sdk.icon, - order: sdk.order - } - ]) - ); - } catch (err) { - console.error('Failed to load sdks.json:', err.message); - process.exit(1); - } -} - -function getVersions(sdkDir) { - try { - const entries = fs.readdirSync(sdkDir, { withFileTypes: true }); - - const versions = entries - .filter(e => { - if (!e.isDirectory()) return false; - return /^v?\d+\.\d+\.\d+/.test(e.name); - }) - .map(e => e.name); - - if (semver) { - return versions.sort((a, b) => { - const cleanA = a.replace(/^v/, ''); - const cleanB = b.replace(/^v/, ''); - try { - return semver.rcompare(cleanA, cleanB); - } catch { - return b.localeCompare(a); - } - }); - } - - return versions.sort().reverse(); - } catch { - return []; - } -} - -function getModules(versionDir) { - try { - const entries = fs.readdirSync(versionDir, { withFileTypes: true }); - return entries - .filter(e => e.isFile() && e.name.endsWith('.mdx')) - .map(e => e.name.replace('.mdx', '')) - .sort(); - } catch { - return []; - } -} - -function generateNavigation() { - const SDK_CONFIGS = loadSdkConfigs(); - const navigation = []; - - if (!fs.existsSync(SDK_REF_DIR)) { - console.log('⚠️ SDK reference directory not found:', SDK_REF_DIR); - return navigation; - } - - for (const [sdkKey, config] of Object.entries(SDK_CONFIGS)) { - const sdkDir = path.join(SDK_REF_DIR, sdkKey); - - if (!fs.existsSync(sdkDir)) { - console.log(` Skipping ${sdkKey} (not found)`); - continue; - } - - const versions = getVersions(sdkDir); - if (versions.length === 0) { - console.log(` Skipping ${sdkKey} (no versions)`); - continue; - } - - console.log(` Found ${sdkKey}: ${versions.length} versions`); - - const dropdown = { - dropdown: config.name, - icon: config.icon, - versions: versions.map((version, index) => { - const versionDir = path.join(sdkDir, version); - const modules = getModules(versionDir); - const displayVersion = version.startsWith('v') ? version : `v${version}`; - - return { - version: displayVersion, - default: index === 0, - pages: modules.map(module => - `docs/sdk-reference/${sdkKey}/${version}/${module}` - ) - }; - }) - }; - - navigation.push({ ...dropdown, _order: config.order }); - } - - return navigation - .sort((a, b) => a._order - b._order) - .map(({ _order, ...rest }) => rest); -} - -function main() { - console.log('📝 Generating SDK navigation...'); - console.log(` Config: ${CONFIG_FILE}`); - console.log(` Source: ${SDK_REF_DIR}`); - console.log(` Output: ${OUTPUT_FILE}`); - console.log(''); - - const navigation = generateNavigation(); - - fs.writeFileSync(OUTPUT_FILE, JSON.stringify(navigation, null, 2)); - - console.log(''); - console.log(`✅ Generated ${OUTPUT_FILE}`); - console.log(` Found ${navigation.length} SDKs`); - - for (const sdk of navigation) { - const totalPages = sdk.versions.reduce((sum, v) => sum + (v.pages?.length || 0), 0); - console.log(` - ${sdk.dropdown}: ${sdk.versions.length} versions, ${totalPages} pages`); - } -} - -main(); diff --git a/scripts/generate-sdk-reference.sh b/scripts/generate-sdk-reference.sh deleted file mode 100755 index e6627dc..0000000 --- a/scripts/generate-sdk-reference.sh +++ /dev/null @@ -1,96 +0,0 @@ -#!/usr/bin/env bash -set -euo pipefail - -SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" -DOCS_DIR="$(cd "$SCRIPT_DIR/.." && pwd)" -CONFIG_FILE="$SCRIPT_DIR/sdks.json" - -SDK_TYPE="all" -VERSION="latest" -LIMIT="" - -while [[ $# -gt 0 ]]; do - case $1 in - --sdk) - if [[ -n "${2:-}" && ! "$2" =~ ^-- ]]; then - SDK_TYPE="$2" - shift 2 - else - shift - fi - ;; - --version) - if [[ -n "${2:-}" && ! "$2" =~ ^-- ]]; then - VERSION="$2" - shift 2 - else - shift - fi - ;; - --limit) - if [[ -n "${2:-}" && ! "$2" =~ ^-- ]]; then - LIMIT="$2" - shift 2 - else - shift - fi - ;; - --all) - SDK_TYPE="all" - shift - ;; - *) - echo "Unknown option: $1" - exit 1 - ;; - esac -done - -# export limit for child scripts -export SDK_VERSION_LIMIT="$LIMIT" - -TEMP_DIR=$(mktemp -d) -trap "rm -rf $TEMP_DIR" EXIT - -echo "🚀 SDK Reference Generator" -echo " SDK: $SDK_TYPE" -echo " Version: $VERSION" -[[ -n "$LIMIT" ]] && echo " Limit: $LIMIT versions" -echo " Temp dir: $TEMP_DIR" -echo "" - -get_sdk_list() { - node -e "console.log(Object.keys(require('$CONFIG_FILE').sdks).join(' '))" -} - -run_generator() { - local sdk="$1" - local version="$2" - - echo "📦 Generating $sdk..." - chmod +x "$SCRIPT_DIR/generate-sdk.sh" - "$SCRIPT_DIR/generate-sdk.sh" "$sdk" "$version" "$TEMP_DIR" "$DOCS_DIR" || { - echo " ⚠️ Generator failed for $sdk" - return 0 - } -} - -if [[ "$SDK_TYPE" == "all" ]]; then - SDK_LIST=$(get_sdk_list) - for sdk in $SDK_LIST; do - run_generator "$sdk" "$VERSION" - done -else - run_generator "$SDK_TYPE" "$VERSION" -fi - -echo "" -echo "📝 Generating navigation JSON..." -node "$SCRIPT_DIR/generate-sdk-nav.js" - -echo "" -echo "🔄 Merging navigation into docs.json..." -node "$SCRIPT_DIR/merge-sdk-nav.js" - -echo "" -echo "✅ SDK reference generation complete" diff --git a/scripts/generate-sdk.sh b/scripts/generate-sdk.sh deleted file mode 100755 index c07d86e..0000000 --- a/scripts/generate-sdk.sh +++ /dev/null @@ -1,181 +0,0 @@ -#!/usr/bin/env bash -set -euo pipefail - -SDK_KEY="$1" -VERSION_ARG="$2" -TEMP_DIR="$3" -DOCS_DIR="$4" - -SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" -CONFIG_FILE="$SCRIPT_DIR/sdks.json" -CONFIGS_DIR="$SCRIPT_DIR/configs" - -source "$SCRIPT_DIR/lib/common.sh" - -read_config() { - node -e "const c = require('$CONFIG_FILE').sdks['$SDK_KEY']; console.log(c && c.$1 !== undefined ? c.$1 : '')" -} - -read_config_array() { - node -e "const c = require('$CONFIG_FILE').sdks['$SDK_KEY']; const v = c && c.$1; if(Array.isArray(v)) console.log(v.join(' '));" -} - -DISPLAY_NAME=$(read_config "displayName") -REPO=$(read_config "repo") -TAG_PATTERN=$(read_config "tagPattern") -TAG_FORMAT=$(read_config "tagFormat") -GENERATOR=$(read_config "generator") -IS_REQUIRED=$(read_config "required") -SDK_PATH=$(read_config "sdkPath") -SDK_PATHS=$(read_config_array "sdkPaths") -PACKAGES=$(read_config_array "packages") -MIN_VERSION=$(read_config "minVersion") - -[[ -z "$DISPLAY_NAME" ]] && echo " ❌ SDK '$SDK_KEY' not found in config" && exit 1 - -echo " → $DISPLAY_NAME version: $VERSION_ARG" - -PENDING_VERSIONS="" - -if [[ "$VERSION_ARG" == "all" ]]; then - echo " → Discovering all versions..." - REMOTE_VERSIONS=$(fetch_remote_tags "$REPO" "$TAG_PATTERN") - - if [[ -z "$REMOTE_VERSIONS" ]]; then - [[ "$IS_REQUIRED" == "true" ]] && echo " ❌ No tags found" && exit 1 - echo " ⚠️ No tags found, skipping..." - exit 0 - fi - - [[ -n "$MIN_VERSION" ]] && \ - REMOTE_VERSIONS=$(filter_by_min_version "$REMOTE_VERSIONS" "$MIN_VERSION") && \ - echo " → Filtered to versions >= $MIN_VERSION" - - [[ -n "${SDK_VERSION_LIMIT:-}" ]] && [[ "$SDK_VERSION_LIMIT" =~ ^[0-9]+$ ]] && \ - REMOTE_VERSIONS=$(echo "$REMOTE_VERSIONS" | head -n "$SDK_VERSION_LIMIT") && \ - echo " → Limited to last $SDK_VERSION_LIMIT versions" - - TOTAL=$(echo "$REMOTE_VERSIONS" | wc -l | tr -d ' ') - LOCAL_VERSIONS=$(fetch_local_versions "$SDK_KEY" "$DOCS_DIR") - EXISTING=$(echo "$LOCAL_VERSIONS" | wc -l | tr -d ' ') - [[ -z "$LOCAL_VERSIONS" ]] && EXISTING=0 - - echo "" - echo " 📊 Version Discovery:" - echo " Remote: $TOTAL" - echo " Local: $EXISTING" - - if [[ $TOTAL -eq $EXISTING && $EXISTING -gt 0 ]]; then - echo " → Quick check: verifying..." - MISSING=$(diff_versions "$REMOTE_VERSIONS" "$LOCAL_VERSIONS") - [[ -z "$MISSING" ]] && echo " ✅ All $TOTAL versions exist" && exit 0 - else - MISSING=$(diff_versions "$REMOTE_VERSIONS" "$LOCAL_VERSIONS") - fi - - MISSING_COUNT=$(echo "$MISSING" | wc -l | tr -d ' ') - [[ -z "$MISSING" ]] && MISSING_COUNT=0 - - echo " Missing: $MISSING_COUNT" - echo "" - - [[ $MISSING_COUNT -eq 0 ]] && echo " ✅ Nothing to generate" && exit 0 - - PENDING_VERSIONS="$MISSING" -else - RESOLVED=$(resolve_latest_version "$REPO" "$TAG_PATTERN" "$VERSION_ARG") - - if [[ -z "$RESOLVED" ]]; then - [[ "$IS_REQUIRED" == "true" ]] && echo " ❌ No tags found" && exit 1 - echo " ⚠️ No tags found, skipping..." - exit 0 - fi - - version_exists "$SDK_KEY" "$RESOLVED" "$DOCS_DIR" && \ - echo " ✓ $RESOLVED already exists" && exit 0 - - PENDING_VERSIONS="$RESOLVED" -fi - -generated=0 -failed=0 -failed_list="" - -for version in $PENDING_VERSIONS; do - echo "" - echo " 📦 Generating $version..." - - repo_dir="$TEMP_DIR/${SDK_KEY}-${version}" - git_tag=$(echo "$TAG_FORMAT" | sed "s/{version}/${version#v}/") - - if ! ( - set -e - - clone_repo "$REPO" "$git_tag" "$repo_dir" - - if [[ -n "$SDK_PATH" ]]; then - sdk_dir="$repo_dir/$SDK_PATH" - [[ ! -d "$sdk_dir" ]] && echo " ❌ SDK path not found: $SDK_PATH" && exit 1 - elif [[ -n "$SDK_PATHS" ]]; then - sdk_dir=$(locate_sdk_dir "$repo_dir" $SDK_PATHS) - [[ -z "$sdk_dir" ]] && echo " ❌ SDK not found in: $SDK_PATHS" && exit 1 - else - sdk_dir="$repo_dir" - fi - - install_with_cache "$sdk_dir" "$GENERATOR" "$TEMP_DIR" - - source "$SCRIPT_DIR/generators/${GENERATOR}.sh" - - case "$GENERATOR" in - typedoc) - generate_typedoc "$sdk_dir" "$CONFIGS_DIR" - ;; - pydoc) - submodules=$(node -e "const c = require('$CONFIG_FILE').sdks['$SDK_KEY']; const v = c?.submodules?.['e2b.template']; if(Array.isArray(v)) console.log(v.join(' '));" || echo "") - generate_pydoc "$sdk_dir" "$PACKAGES" "$submodules" - ;; - cli) - generate_cli_docs "$sdk_dir" - ;; - *) - echo " ❌ Unknown generator: $GENERATOR" && exit 1 - ;; - esac - - [[ ! -d "$sdk_dir/sdk_ref" ]] && echo " ❌ No sdk_ref directory" && exit 1 - - flatten_markdown "$sdk_dir/sdk_ref" - copy_to_docs "$sdk_dir/sdk_ref" \ - "$DOCS_DIR/docs/sdk-reference/$SDK_KEY/$version" \ - "$DISPLAY_NAME" "$version" - ); then - echo " ❌ Failed: $version" - ((failed++)) || true - failed_list="${failed_list:+$failed_list }$version" - continue - fi - - echo " ✅ Complete: $version" - ((generated++)) || true - rm -rf "$repo_dir" -done - -echo "" -echo " 📊 Summary:" -echo " Generated: $generated" -[[ $failed -gt 0 ]] && echo " Failed: $failed ($failed_list)" - -if [[ $failed -gt 0 ]]; then - if [[ "$IS_REQUIRED" == "true" ]]; then - echo "" - echo " ❌ WORKFLOW ABORTED: Required SDK has failures" - echo " ❌ Failed: $failed_list" - exit 1 - elif [[ $generated -eq 0 ]]; then - echo "" - echo " ❌ WORKFLOW ABORTED: All versions failed" - echo " ❌ Failed: $failed_list" - exit 1 - fi -fi diff --git a/scripts/generators/cli.sh b/scripts/generators/cli.sh deleted file mode 100755 index 23e4010..0000000 --- a/scripts/generators/cli.sh +++ /dev/null @@ -1,38 +0,0 @@ -#!/usr/bin/env bash - -generate_cli_docs() { - local sdk_dir="$1" - - cd "$sdk_dir" - - echo " → Building CLI..." - if command -v pnpm &> /dev/null; then - pnpm run build 2>&1 || npx tsup 2>&1 || { - echo " ❌ CLI build failed" - return 1 - } - else - npm run build 2>&1 || npx tsup 2>&1 || { - echo " ❌ CLI build failed" - return 1 - } - fi - - echo " → Generating documentation..." - mkdir -p sdk_ref - - NODE_ENV=development node dist/index.js -cmd2md 2>&1 || { - echo " ⚠️ CLI doc generation failed" - return 1 - } - - cd sdk_ref - shopt -s nullglob - for file in *.md; do - mv "$file" "${file%.md}.mdx" - done - shopt -u nullglob - - return 0 -} - diff --git a/scripts/generators/pydoc.sh b/scripts/generators/pydoc.sh deleted file mode 100755 index e45af9c..0000000 --- a/scripts/generators/pydoc.sh +++ /dev/null @@ -1,48 +0,0 @@ -#!/usr/bin/env bash - -process_mdx() { - local file="$1" - local tmp="${file}.tmp" - - sed '/]*>.*<\/a>/d' "$file" > "$tmp" && mv "$tmp" "$file" - sed '/^# /d' "$file" > "$tmp" && mv "$tmp" "$file" - sed '/^## / s/ Objects$//' "$file" > "$tmp" && mv "$tmp" "$file" - sed 's/^####/###/' "$file" > "$tmp" && mv "$tmp" "$file" -} - -process_package() { - local pkg="$1" - local sdk_dir="$2" - local name="${pkg##*.}" - name="${name#e2b_}" - - echo " → Processing $pkg..." - - if poetry run pydoc-markdown -p "$pkg" > "$sdk_dir/sdk_ref/${name}.mdx" 2>/dev/null; then - process_mdx "$sdk_dir/sdk_ref/${name}.mdx" - else - echo " ⚠️ Failed to generate docs for $pkg" - rm -f "$sdk_dir/sdk_ref/${name}.mdx" - fi -} - -generate_pydoc() { - local sdk_dir="$1" - local packages="$2" - local submodules="$3" - - cd "$sdk_dir" - mkdir -p sdk_ref - - echo " → Generating documentation for packages..." - - for pkg in $packages; do - process_package "$pkg" "$sdk_dir" - done - - for submod in $submodules; do - process_package "$submod" "$sdk_dir" - done - - return 0 -} diff --git a/scripts/generators/typedoc.sh b/scripts/generators/typedoc.sh deleted file mode 100755 index 512d00c..0000000 --- a/scripts/generators/typedoc.sh +++ /dev/null @@ -1,29 +0,0 @@ -#!/usr/bin/env bash - -generate_typedoc() { - local sdk_dir="$1" - local configs_dir="$2" - - cd "$sdk_dir" - - if [[ -f "typedoc.json" ]]; then - echo " → Running TypeDoc with repo config..." - npx typedoc --plugin typedoc-plugin-markdown \ - --plugin "$configs_dir/typedoc-theme.js" || { - echo " ❌ TypeDoc generation failed" - return 1 - } - else - echo " → Running TypeDoc with default config..." - cp "$configs_dir/typedoc.json" ./typedoc.docs.json - npx typedoc --options ./typedoc.docs.json \ - --plugin typedoc-plugin-markdown \ - --plugin "$configs_dir/typedoc-theme.js" || { - echo " ❌ TypeDoc generation failed" - return 1 - } - fi - - return 0 -} - diff --git a/scripts/lib/common.sh b/scripts/lib/common.sh deleted file mode 100755 index ff7431c..0000000 --- a/scripts/lib/common.sh +++ /dev/null @@ -1,316 +0,0 @@ -#!/usr/bin/env bash - -fetch_remote_tags() { - local repo="$1" - local tag_pattern="$2" - local escaped_pattern=$(echo "$tag_pattern" | sed 's/[\/&@]/\\&/g') - - git ls-remote --tags --refs "$repo" 2>/dev/null | \ - grep "refs/tags/${tag_pattern}" | \ - sed "s|.*refs/tags/${escaped_pattern}|v|" | \ - sort -V -r -} - -version_exists() { - local sdk_key="$1" - local version="$2" - local docs_dir="$3" - local version_dir="$docs_dir/docs/sdk-reference/$sdk_key/$version" - - [[ -d "$version_dir" ]] && [[ -n "$(ls -A "$version_dir"/*.mdx 2>/dev/null)" ]] -} - -fetch_local_versions() { - local sdk_key="$1" - local docs_dir="$2" - local sdk_dir="$docs_dir/docs/sdk-reference/$sdk_key" - - [[ ! -d "$sdk_dir" ]] && return 0 - - find "$sdk_dir" -maxdepth 1 -type d \( -name "v*" -o -name "[0-9]*" \) 2>/dev/null | \ - while read -r dir; do - [[ -n "$(ls -A "$dir"/*.mdx 2>/dev/null)" ]] && basename "$dir" - done | sort -} - -diff_versions() { - local remote="$1" - local local="$2" - - [[ -z "$local" ]] && echo "$remote" && return 0 - - comm -13 <(echo "$local") <(echo "$remote" | sort) -} - -is_valid_version() { - [[ "$1" =~ ^v?[0-9]+\.[0-9]+\.[0-9]+$ ]] -} - -version_gte() { - local v1="${1#v}" - local v2="${2#v}" - local higher=$(printf '%s\n%s' "$v1" "$v2" | sort -V -r | head -n1) - [[ "$higher" == "$v1" ]] -} - -filter_by_min_version() { - local versions="$1" - local min="$2" - - [[ -z "$min" ]] && echo "$versions" && return 0 - - echo "$versions" | while IFS= read -r v; do - [[ -n "$v" ]] && version_gte "$v" "$min" && echo "$v" - done -} - -resolve_latest_version() { - local repo="$1" - local tag_pattern="$2" - local version="$3" - - [[ "$version" != "latest" ]] && echo "$version" && return 0 - - local escaped=$(echo "$tag_pattern" | sed 's/[\/&@]/\\&/g') - git ls-remote --tags --refs "$repo" 2>/dev/null | \ - grep "refs/tags/${tag_pattern}" | \ - sed "s|.*refs/tags/${escaped}|v|" | \ - sort -V | tail -1 -} - -clone_repo() { - local repo="$1" - local git_tag="$2" - local target_dir="$3" - - if [[ -d "$target_dir" ]]; then - return 0 - fi - - echo " → Cloning repo at $git_tag..." - git clone --depth 1 --branch "$git_tag" "$repo" "$target_dir" 2>/dev/null || { - echo " ⚠️ Tag $git_tag not found, trying branch main..." - git clone --depth 1 "$repo" "$target_dir" - } -} - -locate_sdk_dir() { - local repo_dir="$1" - shift - - for path in "$@"; do - [[ -d "$repo_dir/$path" ]] && echo "$repo_dir/$path" && return 0 - done - - return 1 -} - -find_lockfile_up() { - local dir="$1" - local filename="$2" - - while [[ "$dir" != "/" && "$dir" != "." ]]; do - [[ -f "$dir/$filename" ]] && echo "$dir/$filename" && return 0 - dir=$(dirname "$dir") - done - return 1 -} - -hash_lockfile() { - local sdk_dir="$1" - local generator="$2" - local lockfile="" - - case "$generator" in - typedoc|cli) - lockfile=$(find_lockfile_up "$sdk_dir" "pnpm-lock.yaml") || \ - lockfile=$(find_lockfile_up "$sdk_dir" "package-lock.json") || true - ;; - pydoc) - lockfile=$(find_lockfile_up "$sdk_dir" "poetry.lock") || true - ;; - esac - - if [[ -n "$lockfile" && -f "$lockfile" ]]; then - command -v md5 &>/dev/null && md5 -q "$lockfile" || md5sum "$lockfile" | cut -d' ' -f1 - fi -} - -install_with_cache() { - local sdk_dir="$1" - local generator="$2" - local temp_dir="$3" - - if [[ "$generator" == "pydoc" ]]; then - local hash=$(hash_lockfile "$sdk_dir" "$generator") - local marker="$temp_dir/.deps-cache/pydoc-$hash/.installed" - - if [[ -n "$hash" && -f "$marker" ]]; then - echo " → Poetry dependencies cached (lockfile unchanged)" - return 0 - fi - - install_dependencies "$sdk_dir" "$generator" - - if [[ -n "$hash" ]]; then - mkdir -p "$(dirname "$marker")" - touch "$marker" - fi - else - install_dependencies "$sdk_dir" "$generator" - fi -} - -install_dependencies() { - local sdk_dir="$1" - local generator="$2" - - cd "$sdk_dir" - - echo " → Installing dependencies..." - case "$generator" in - typedoc) - if command -v pnpm &> /dev/null; then - pnpm install --ignore-scripts --prefer-offline 2>&1 || { - echo " ⚠️ pnpm failed, trying npm..." - npm install --legacy-peer-deps --prefer-offline 2>&1 - } - else - npm install --legacy-peer-deps --prefer-offline 2>&1 - fi - ;; - pydoc) - poetry install --quiet 2>/dev/null || pip install --break-system-packages pydoc-markdown 2>&1 - ;; - cli) - if command -v pnpm &> /dev/null; then - pnpm install --prefer-offline 2>&1 || npm install --prefer-offline 2>&1 - else - npm install --prefer-offline 2>&1 - fi - ;; - esac -} - -to_title_case() { - local str="$1" - [[ -z "$str" ]] && return 0 - - local result="" - local capitalize_next=true - - for (( i=0; i<${#str}; i++ )); do - local char="${str:$i:1}" - if [[ "$char" == "_" ]]; then - result="$result " - capitalize_next=true - elif [[ "$capitalize_next" == true ]]; then - result="$result$(echo "$char" | tr '[:lower:]' '[:upper:]')" - capitalize_next=false - else - result="$result$char" - fi - done - - echo "$result" -} - -add_frontmatter() { - local file="$1" - local title=$(to_title_case "$(basename "$file" .mdx)") - local tmp="${file}.tmp" - - { - echo "---" - echo "sidebarTitle: \"$title\"" - echo "mode: \"center\"" - echo "---" - echo "" - cat "$file" - } > "$tmp" - mv "$tmp" "$file" -} - -flatten_markdown() { - local ref_dir="$1" - cd "$ref_dir" - - rm -f README.md index.md - - find . -mindepth 2 -type f -name "*.md" 2>/dev/null | while read -r file; do - local filename=$(basename "$file") - if [[ "$filename" == "page.md" || "$filename" == "index.md" ]]; then - mv "$file" "./$(basename "$(dirname "$file")").md" 2>/dev/null || true - else - mv "$file" "./" 2>/dev/null || true - fi - done - - find . -type d -empty -delete 2>/dev/null || true - - shopt -s nullglob - for file in *.md; do - local title=$(to_title_case "$(basename "$file" .md)") - { - echo "---" - echo "sidebarTitle: \"$title\"" - echo "mode: \"center\"" - echo "---" - echo "" - cat "$file" - } > "${file%.md}.mdx" - rm "$file" - done - - for file in *.mdx; do - head -n1 "$file" | grep -q "^---$" || add_frontmatter "$file" - done - shopt -u nullglob - - rm -f index.mdx -} - -validate_mdx_files() { - local src_dir="$1" - rm -f "$src_dir/*.mdx" - - local valid_count=0 - while IFS= read -r -d '' file; do - local name=$(basename "$file") - if [[ "$name" == "*.mdx" ]]; then - rm -f "$file" - elif [[ ! -s "$file" ]]; then - continue - else - ((valid_count++)) || true - fi - done < <(find "$src_dir" -maxdepth 1 -name "*.mdx" -type f -print0) - - echo "$valid_count" -} - -copy_to_docs() { - local src="$1" - local dest="$2" - local sdk_name="$3" - local version="$4" - - local count=$(validate_mdx_files "$src") - - if [[ "$count" -eq 0 ]]; then - echo " ❌ No MDX files generated - doc generator failed" - return 1 - fi - - mkdir -p "$dest" - - echo " → Copying $count files to $dest" - if find "$src" -maxdepth 1 -name "*.mdx" -type f ! -size 0 -exec cp {} "$dest/" \; 2>/dev/null; then - echo " ✅ $sdk_name $version complete" - return 0 - else - rmdir "$dest" 2>/dev/null || true - return 1 - fi -} - diff --git a/scripts/merge-sdk-nav.js b/scripts/merge-sdk-nav.js deleted file mode 100644 index 6f5c1cc..0000000 --- a/scripts/merge-sdk-nav.js +++ /dev/null @@ -1,58 +0,0 @@ -#!/usr/bin/env node - -const fs = require('fs'); -const path = require('path'); - -const DOCS_DIR = path.join(__dirname, '..'); -const DOCS_JSON_PATH = path.join(DOCS_DIR, 'docs.json'); -const SDK_NAV_PATH = path.join(DOCS_DIR, 'sdk_navigation.json'); - -function main() { - console.log('🔄 Merging SDK navigation into docs.json...'); - - if (!fs.existsSync(SDK_NAV_PATH)) { - console.log('⚠️ sdk_navigation.json not found, skipping merge'); - return; - } - - const docsJson = JSON.parse(fs.readFileSync(DOCS_JSON_PATH, 'utf-8')); - const sdkNav = JSON.parse(fs.readFileSync(SDK_NAV_PATH, 'utf-8')); - - const anchors = docsJson.navigation?.anchors; - if (!anchors) { - console.error('❌ No anchors found in docs.json'); - process.exit(1); - } - - const sdkRefIndex = anchors.findIndex(a => a.anchor === 'SDK Reference'); - if (sdkRefIndex === -1) { - console.error('❌ SDK Reference anchor not found in docs.json'); - process.exit(1); - } - - const validDropdowns = sdkNav.filter(d => d.versions && d.versions.length > 0); - - if (validDropdowns.length === 0) { - console.log('⚠️ No SDK versions found, keeping existing docs.json'); - return; - } - - anchors[sdkRefIndex] = { - anchor: 'SDK Reference', - icon: 'brackets-curly', - dropdowns: validDropdowns - }; - - fs.writeFileSync(DOCS_JSON_PATH, JSON.stringify(docsJson, null, 2) + '\n'); - - console.log(`✅ Updated docs.json with ${validDropdowns.length} SDK dropdowns`); - - for (const dropdown of validDropdowns) { - const totalVersions = dropdown.versions.length; - const totalPages = dropdown.versions.reduce((sum, v) => sum + (v.pages?.length || 0), 0); - console.log(` - ${dropdown.dropdown}: ${totalVersions} versions, ${totalPages} pages`); - } -} - -main(); - diff --git a/sdk-reference-generator/.gitignore b/sdk-reference-generator/.gitignore new file mode 100644 index 0000000..94973cf --- /dev/null +++ b/sdk-reference-generator/.gitignore @@ -0,0 +1,4 @@ +node_modules/ +dist/ +*.log + diff --git a/scripts/configs/typedoc-theme.js b/sdk-reference-generator/configs/typedoc-theme.cjs similarity index 100% rename from scripts/configs/typedoc-theme.js rename to sdk-reference-generator/configs/typedoc-theme.cjs diff --git a/scripts/configs/typedoc.json b/sdk-reference-generator/configs/typedoc.json similarity index 100% rename from scripts/configs/typedoc.json rename to sdk-reference-generator/configs/typedoc.json diff --git a/sdk-reference-generator/package.json b/sdk-reference-generator/package.json new file mode 100644 index 0000000..bf988ba --- /dev/null +++ b/sdk-reference-generator/package.json @@ -0,0 +1,29 @@ +{ + "name": "e2b-sdk-reference-generator", + "version": "1.0.0", + "type": "module", + "scripts": { + "generate": "tsx src/cli.ts", + "test": "vitest run", + "test:watch": "vitest" + }, + "dependencies": { + "chalk": "^5.4.1", + "commander": "^12.1.0", + "execa": "^9.5.2", + "fs-extra": "^11.2.0", + "glob": "^11.0.0", + "semver": "^7.6.3", + "simple-git": "^3.27.0", + "zod": "^3.24.1" + }, + "devDependencies": { + "@types/fs-extra": "^11.0.4", + "@types/node": "^22.10.2", + "@types/semver": "^7.5.8", + "tsx": "^4.19.2", + "typescript": "^5.7.2", + "vitest": "^2.1.8" + } +} + diff --git a/sdk-reference-generator/pnpm-lock.yaml b/sdk-reference-generator/pnpm-lock.yaml new file mode 100644 index 0000000..62c9eaf --- /dev/null +++ b/sdk-reference-generator/pnpm-lock.yaml @@ -0,0 +1,1703 @@ +lockfileVersion: '9.0' + +settings: + autoInstallPeers: true + excludeLinksFromLockfile: false + +importers: + + .: + dependencies: + chalk: + specifier: ^5.4.1 + version: 5.6.2 + commander: + specifier: ^12.1.0 + version: 12.1.0 + execa: + specifier: ^9.5.2 + version: 9.6.1 + fs-extra: + specifier: ^11.2.0 + version: 11.3.3 + glob: + specifier: ^11.0.0 + version: 11.1.0 + semver: + specifier: ^7.6.3 + version: 7.7.3 + simple-git: + specifier: ^3.27.0 + version: 3.30.0 + zod: + specifier: ^3.24.1 + version: 3.25.76 + devDependencies: + '@types/fs-extra': + specifier: ^11.0.4 + version: 11.0.4 + '@types/node': + specifier: ^22.10.2 + version: 22.19.3 + '@types/semver': + specifier: ^7.5.8 + version: 7.7.1 + tsx: + specifier: ^4.19.2 + version: 4.21.0 + typescript: + specifier: ^5.7.2 + version: 5.9.3 + vitest: + specifier: ^2.1.8 + version: 2.1.9(@types/node@22.19.3) + +packages: + + '@esbuild/aix-ppc64@0.21.5': + resolution: {integrity: sha512-1SDgH6ZSPTlggy1yI6+Dbkiz8xzpHJEVAlF/AM1tHPLsf5STom9rwtjE4hKAF20FfXXNTFqEYXyJNWh1GiZedQ==} + engines: {node: '>=12'} + cpu: [ppc64] + os: [aix] + + '@esbuild/aix-ppc64@0.27.2': + resolution: {integrity: sha512-GZMB+a0mOMZs4MpDbj8RJp4cw+w1WV5NYD6xzgvzUJ5Ek2jerwfO2eADyI6ExDSUED+1X8aMbegahsJi+8mgpw==} + engines: {node: '>=18'} + cpu: [ppc64] + os: [aix] + + '@esbuild/android-arm64@0.21.5': + resolution: {integrity: sha512-c0uX9VAUBQ7dTDCjq+wdyGLowMdtR/GoC2U5IYk/7D1H1JYC0qseD7+11iMP2mRLN9RcCMRcjC4YMclCzGwS/A==} + engines: {node: '>=12'} + cpu: [arm64] + os: [android] + + '@esbuild/android-arm64@0.27.2': + resolution: {integrity: sha512-pvz8ZZ7ot/RBphf8fv60ljmaoydPU12VuXHImtAs0XhLLw+EXBi2BLe3OYSBslR4rryHvweW5gmkKFwTiFy6KA==} + engines: {node: '>=18'} + cpu: [arm64] + os: [android] + + '@esbuild/android-arm@0.21.5': + resolution: {integrity: sha512-vCPvzSjpPHEi1siZdlvAlsPxXl7WbOVUBBAowWug4rJHb68Ox8KualB+1ocNvT5fjv6wpkX6o/iEpbDrf68zcg==} + engines: {node: '>=12'} + cpu: [arm] + os: [android] + + '@esbuild/android-arm@0.27.2': + resolution: {integrity: sha512-DVNI8jlPa7Ujbr1yjU2PfUSRtAUZPG9I1RwW4F4xFB1Imiu2on0ADiI/c3td+KmDtVKNbi+nffGDQMfcIMkwIA==} + engines: {node: '>=18'} + cpu: [arm] + os: [android] + + '@esbuild/android-x64@0.21.5': + resolution: {integrity: sha512-D7aPRUUNHRBwHxzxRvp856rjUHRFW1SdQATKXH2hqA0kAZb1hKmi02OpYRacl0TxIGz/ZmXWlbZgjwWYaCakTA==} + engines: {node: '>=12'} + cpu: [x64] + os: [android] + + '@esbuild/android-x64@0.27.2': + resolution: {integrity: sha512-z8Ank4Byh4TJJOh4wpz8g2vDy75zFL0TlZlkUkEwYXuPSgX8yzep596n6mT7905kA9uHZsf/o2OJZubl2l3M7A==} + engines: {node: '>=18'} + cpu: [x64] + os: [android] + + '@esbuild/darwin-arm64@0.21.5': + resolution: {integrity: sha512-DwqXqZyuk5AiWWf3UfLiRDJ5EDd49zg6O9wclZ7kUMv2WRFr4HKjXp/5t8JZ11QbQfUS6/cRCKGwYhtNAY88kQ==} + engines: {node: '>=12'} + cpu: [arm64] + os: [darwin] + + '@esbuild/darwin-arm64@0.27.2': + resolution: {integrity: sha512-davCD2Zc80nzDVRwXTcQP/28fiJbcOwvdolL0sOiOsbwBa72kegmVU0Wrh1MYrbuCL98Omp5dVhQFWRKR2ZAlg==} + engines: {node: '>=18'} + cpu: [arm64] + os: [darwin] + + '@esbuild/darwin-x64@0.21.5': + resolution: {integrity: sha512-se/JjF8NlmKVG4kNIuyWMV/22ZaerB+qaSi5MdrXtd6R08kvs2qCN4C09miupktDitvh8jRFflwGFBQcxZRjbw==} + engines: {node: '>=12'} + cpu: [x64] + os: [darwin] + + '@esbuild/darwin-x64@0.27.2': + resolution: {integrity: sha512-ZxtijOmlQCBWGwbVmwOF/UCzuGIbUkqB1faQRf5akQmxRJ1ujusWsb3CVfk/9iZKr2L5SMU5wPBi1UWbvL+VQA==} + engines: {node: '>=18'} + cpu: [x64] + os: [darwin] + + '@esbuild/freebsd-arm64@0.21.5': + resolution: {integrity: sha512-5JcRxxRDUJLX8JXp/wcBCy3pENnCgBR9bN6JsY4OmhfUtIHe3ZW0mawA7+RDAcMLrMIZaf03NlQiX9DGyB8h4g==} + engines: {node: '>=12'} + cpu: [arm64] + os: [freebsd] + + '@esbuild/freebsd-arm64@0.27.2': + resolution: {integrity: sha512-lS/9CN+rgqQ9czogxlMcBMGd+l8Q3Nj1MFQwBZJyoEKI50XGxwuzznYdwcav6lpOGv5BqaZXqvBSiB/kJ5op+g==} + engines: {node: '>=18'} + cpu: [arm64] + os: [freebsd] + + '@esbuild/freebsd-x64@0.21.5': + resolution: {integrity: sha512-J95kNBj1zkbMXtHVH29bBriQygMXqoVQOQYA+ISs0/2l3T9/kj42ow2mpqerRBxDJnmkUDCaQT/dfNXWX/ZZCQ==} + engines: {node: '>=12'} + cpu: [x64] + os: [freebsd] + + '@esbuild/freebsd-x64@0.27.2': + resolution: {integrity: sha512-tAfqtNYb4YgPnJlEFu4c212HYjQWSO/w/h/lQaBK7RbwGIkBOuNKQI9tqWzx7Wtp7bTPaGC6MJvWI608P3wXYA==} + engines: {node: '>=18'} + cpu: [x64] + os: [freebsd] + + '@esbuild/linux-arm64@0.21.5': + resolution: {integrity: sha512-ibKvmyYzKsBeX8d8I7MH/TMfWDXBF3db4qM6sy+7re0YXya+K1cem3on9XgdT2EQGMu4hQyZhan7TeQ8XkGp4Q==} + engines: {node: '>=12'} + cpu: [arm64] + os: [linux] + + '@esbuild/linux-arm64@0.27.2': + resolution: {integrity: sha512-hYxN8pr66NsCCiRFkHUAsxylNOcAQaxSSkHMMjcpx0si13t1LHFphxJZUiGwojB1a/Hd5OiPIqDdXONia6bhTw==} + engines: {node: '>=18'} + cpu: [arm64] + os: [linux] + + '@esbuild/linux-arm@0.21.5': + resolution: {integrity: sha512-bPb5AHZtbeNGjCKVZ9UGqGwo8EUu4cLq68E95A53KlxAPRmUyYv2D6F0uUI65XisGOL1hBP5mTronbgo+0bFcA==} + engines: {node: '>=12'} + cpu: [arm] + os: [linux] + + '@esbuild/linux-arm@0.27.2': + resolution: {integrity: sha512-vWfq4GaIMP9AIe4yj1ZUW18RDhx6EPQKjwe7n8BbIecFtCQG4CfHGaHuh7fdfq+y3LIA2vGS/o9ZBGVxIDi9hw==} + engines: {node: '>=18'} + cpu: [arm] + os: [linux] + + '@esbuild/linux-ia32@0.21.5': + resolution: {integrity: sha512-YvjXDqLRqPDl2dvRODYmmhz4rPeVKYvppfGYKSNGdyZkA01046pLWyRKKI3ax8fbJoK5QbxblURkwK/MWY18Tg==} + engines: {node: '>=12'} + cpu: [ia32] + os: [linux] + + '@esbuild/linux-ia32@0.27.2': + resolution: {integrity: sha512-MJt5BRRSScPDwG2hLelYhAAKh9imjHK5+NE/tvnRLbIqUWa+0E9N4WNMjmp/kXXPHZGqPLxggwVhz7QP8CTR8w==} + engines: {node: '>=18'} + cpu: [ia32] + os: [linux] + + '@esbuild/linux-loong64@0.21.5': + resolution: {integrity: sha512-uHf1BmMG8qEvzdrzAqg2SIG/02+4/DHB6a9Kbya0XDvwDEKCoC8ZRWI5JJvNdUjtciBGFQ5PuBlpEOXQj+JQSg==} + engines: {node: '>=12'} + cpu: [loong64] + os: [linux] + + '@esbuild/linux-loong64@0.27.2': + resolution: {integrity: sha512-lugyF1atnAT463aO6KPshVCJK5NgRnU4yb3FUumyVz+cGvZbontBgzeGFO1nF+dPueHD367a2ZXe1NtUkAjOtg==} + engines: {node: '>=18'} + cpu: [loong64] + os: [linux] + + '@esbuild/linux-mips64el@0.21.5': + resolution: {integrity: sha512-IajOmO+KJK23bj52dFSNCMsz1QP1DqM6cwLUv3W1QwyxkyIWecfafnI555fvSGqEKwjMXVLokcV5ygHW5b3Jbg==} + engines: {node: '>=12'} + cpu: [mips64el] + os: [linux] + + '@esbuild/linux-mips64el@0.27.2': + resolution: {integrity: sha512-nlP2I6ArEBewvJ2gjrrkESEZkB5mIoaTswuqNFRv/WYd+ATtUpe9Y09RnJvgvdag7he0OWgEZWhviS1OTOKixw==} + engines: {node: '>=18'} + cpu: [mips64el] + os: [linux] + + '@esbuild/linux-ppc64@0.21.5': + resolution: {integrity: sha512-1hHV/Z4OEfMwpLO8rp7CvlhBDnjsC3CttJXIhBi+5Aj5r+MBvy4egg7wCbe//hSsT+RvDAG7s81tAvpL2XAE4w==} + engines: {node: '>=12'} + cpu: [ppc64] + os: [linux] + + '@esbuild/linux-ppc64@0.27.2': + resolution: {integrity: sha512-C92gnpey7tUQONqg1n6dKVbx3vphKtTHJaNG2Ok9lGwbZil6DrfyecMsp9CrmXGQJmZ7iiVXvvZH6Ml5hL6XdQ==} + engines: {node: '>=18'} + cpu: [ppc64] + os: [linux] + + '@esbuild/linux-riscv64@0.21.5': + resolution: {integrity: sha512-2HdXDMd9GMgTGrPWnJzP2ALSokE/0O5HhTUvWIbD3YdjME8JwvSCnNGBnTThKGEB91OZhzrJ4qIIxk/SBmyDDA==} + engines: {node: '>=12'} + cpu: [riscv64] + os: [linux] + + '@esbuild/linux-riscv64@0.27.2': + resolution: {integrity: sha512-B5BOmojNtUyN8AXlK0QJyvjEZkWwy/FKvakkTDCziX95AowLZKR6aCDhG7LeF7uMCXEJqwa8Bejz5LTPYm8AvA==} + engines: {node: '>=18'} + cpu: [riscv64] + os: [linux] + + '@esbuild/linux-s390x@0.21.5': + resolution: {integrity: sha512-zus5sxzqBJD3eXxwvjN1yQkRepANgxE9lgOW2qLnmr8ikMTphkjgXu1HR01K4FJg8h1kEEDAqDcZQtbrRnB41A==} + engines: {node: '>=12'} + cpu: [s390x] + os: [linux] + + '@esbuild/linux-s390x@0.27.2': + resolution: {integrity: sha512-p4bm9+wsPwup5Z8f4EpfN63qNagQ47Ua2znaqGH6bqLlmJ4bx97Y9JdqxgGZ6Y8xVTixUnEkoKSHcpRlDnNr5w==} + engines: {node: '>=18'} + cpu: [s390x] + os: [linux] + + '@esbuild/linux-x64@0.21.5': + resolution: {integrity: sha512-1rYdTpyv03iycF1+BhzrzQJCdOuAOtaqHTWJZCWvijKD2N5Xu0TtVC8/+1faWqcP9iBCWOmjmhoH94dH82BxPQ==} + engines: {node: '>=12'} + cpu: [x64] + os: [linux] + + '@esbuild/linux-x64@0.27.2': + resolution: {integrity: sha512-uwp2Tip5aPmH+NRUwTcfLb+W32WXjpFejTIOWZFw/v7/KnpCDKG66u4DLcurQpiYTiYwQ9B7KOeMJvLCu/OvbA==} + engines: {node: '>=18'} + cpu: [x64] + os: [linux] + + '@esbuild/netbsd-arm64@0.27.2': + resolution: {integrity: sha512-Kj6DiBlwXrPsCRDeRvGAUb/LNrBASrfqAIok+xB0LxK8CHqxZ037viF13ugfsIpePH93mX7xfJp97cyDuTZ3cw==} + engines: {node: '>=18'} + cpu: [arm64] + os: [netbsd] + + '@esbuild/netbsd-x64@0.21.5': + resolution: {integrity: sha512-Woi2MXzXjMULccIwMnLciyZH4nCIMpWQAs049KEeMvOcNADVxo0UBIQPfSmxB3CWKedngg7sWZdLvLczpe0tLg==} + engines: {node: '>=12'} + cpu: [x64] + os: [netbsd] + + '@esbuild/netbsd-x64@0.27.2': + resolution: {integrity: sha512-HwGDZ0VLVBY3Y+Nw0JexZy9o/nUAWq9MlV7cahpaXKW6TOzfVno3y3/M8Ga8u8Yr7GldLOov27xiCnqRZf0tCA==} + engines: {node: '>=18'} + cpu: [x64] + os: [netbsd] + + '@esbuild/openbsd-arm64@0.27.2': + resolution: {integrity: sha512-DNIHH2BPQ5551A7oSHD0CKbwIA/Ox7+78/AWkbS5QoRzaqlev2uFayfSxq68EkonB+IKjiuxBFoV8ESJy8bOHA==} + engines: {node: '>=18'} + cpu: [arm64] + os: [openbsd] + + '@esbuild/openbsd-x64@0.21.5': + resolution: {integrity: sha512-HLNNw99xsvx12lFBUwoT8EVCsSvRNDVxNpjZ7bPn947b8gJPzeHWyNVhFsaerc0n3TsbOINvRP2byTZ5LKezow==} + engines: {node: '>=12'} + cpu: [x64] + os: [openbsd] + + '@esbuild/openbsd-x64@0.27.2': + resolution: {integrity: sha512-/it7w9Nb7+0KFIzjalNJVR5bOzA9Vay+yIPLVHfIQYG/j+j9VTH84aNB8ExGKPU4AzfaEvN9/V4HV+F+vo8OEg==} + engines: {node: '>=18'} + cpu: [x64] + os: [openbsd] + + '@esbuild/openharmony-arm64@0.27.2': + resolution: {integrity: sha512-LRBbCmiU51IXfeXk59csuX/aSaToeG7w48nMwA6049Y4J4+VbWALAuXcs+qcD04rHDuSCSRKdmY63sruDS5qag==} + engines: {node: '>=18'} + cpu: [arm64] + os: [openharmony] + + '@esbuild/sunos-x64@0.21.5': + resolution: {integrity: sha512-6+gjmFpfy0BHU5Tpptkuh8+uw3mnrvgs+dSPQXQOv3ekbordwnzTVEb4qnIvQcYXq6gzkyTnoZ9dZG+D4garKg==} + engines: {node: '>=12'} + cpu: [x64] + os: [sunos] + + '@esbuild/sunos-x64@0.27.2': + resolution: {integrity: sha512-kMtx1yqJHTmqaqHPAzKCAkDaKsffmXkPHThSfRwZGyuqyIeBvf08KSsYXl+abf5HDAPMJIPnbBfXvP2ZC2TfHg==} + engines: {node: '>=18'} + cpu: [x64] + os: [sunos] + + '@esbuild/win32-arm64@0.21.5': + resolution: {integrity: sha512-Z0gOTd75VvXqyq7nsl93zwahcTROgqvuAcYDUr+vOv8uHhNSKROyU961kgtCD1e95IqPKSQKH7tBTslnS3tA8A==} + engines: {node: '>=12'} + cpu: [arm64] + os: [win32] + + '@esbuild/win32-arm64@0.27.2': + resolution: {integrity: sha512-Yaf78O/B3Kkh+nKABUF++bvJv5Ijoy9AN1ww904rOXZFLWVc5OLOfL56W+C8F9xn5JQZa3UX6m+IktJnIb1Jjg==} + engines: {node: '>=18'} + cpu: [arm64] + os: [win32] + + '@esbuild/win32-ia32@0.21.5': + resolution: {integrity: sha512-SWXFF1CL2RVNMaVs+BBClwtfZSvDgtL//G/smwAc5oVK/UPu2Gu9tIaRgFmYFFKrmg3SyAjSrElf0TiJ1v8fYA==} + engines: {node: '>=12'} + cpu: [ia32] + os: [win32] + + '@esbuild/win32-ia32@0.27.2': + resolution: {integrity: sha512-Iuws0kxo4yusk7sw70Xa2E2imZU5HoixzxfGCdxwBdhiDgt9vX9VUCBhqcwY7/uh//78A1hMkkROMJq9l27oLQ==} + engines: {node: '>=18'} + cpu: [ia32] + os: [win32] + + '@esbuild/win32-x64@0.21.5': + resolution: {integrity: sha512-tQd/1efJuzPC6rCFwEvLtci/xNFcTZknmXs98FYDfGE4wP9ClFV98nyKrzJKVPMhdDnjzLhdUyMX4PsQAPjwIw==} + engines: {node: '>=12'} + cpu: [x64] + os: [win32] + + '@esbuild/win32-x64@0.27.2': + resolution: {integrity: sha512-sRdU18mcKf7F+YgheI/zGf5alZatMUTKj/jNS6l744f9u3WFu4v7twcUI9vu4mknF4Y9aDlblIie0IM+5xxaqQ==} + engines: {node: '>=18'} + cpu: [x64] + os: [win32] + + '@isaacs/balanced-match@4.0.1': + resolution: {integrity: sha512-yzMTt9lEb8Gv7zRioUilSglI0c0smZ9k5D65677DLWLtWJaXIS3CqcGyUFByYKlnUj6TkjLVs54fBl6+TiGQDQ==} + engines: {node: 20 || >=22} + + '@isaacs/brace-expansion@5.0.0': + resolution: {integrity: sha512-ZT55BDLV0yv0RBm2czMiZ+SqCGO7AvmOM3G/w2xhVPH+te0aKgFjmBvGlL1dH+ql2tgGO3MVrbb3jCKyvpgnxA==} + engines: {node: 20 || >=22} + + '@isaacs/cliui@8.0.2': + resolution: {integrity: sha512-O8jcjabXaleOG9DQ0+ARXWZBTfnP4WNAqzuiJK7ll44AmxGKv/J2M4TPjxjY3znBCfvBXFzucm1twdyFybFqEA==} + engines: {node: '>=12'} + + '@jridgewell/sourcemap-codec@1.5.5': + resolution: {integrity: sha512-cYQ9310grqxueWbl+WuIUIaiUaDcj7WOq5fVhEljNVgRfOUhY9fy2zTvfoqWsnebh8Sl70VScFbICvJnLKB0Og==} + + '@kwsites/file-exists@1.1.1': + resolution: {integrity: sha512-m9/5YGR18lIwxSFDwfE3oA7bWuq9kdau6ugN4H2rJeyhFQZcG9AgSHkQtSD15a8WvTgfz9aikZMrKPHvbpqFiw==} + + '@kwsites/promise-deferred@1.1.1': + resolution: {integrity: sha512-GaHYm+c0O9MjZRu0ongGBRbinu8gVAMd2UZjji6jVmqKtZluZnptXGWhz1E8j8D2HJ3f/yMxKAUC0b+57wncIw==} + + '@rollup/rollup-android-arm-eabi@4.55.1': + resolution: {integrity: sha512-9R0DM/ykwfGIlNu6+2U09ga0WXeZ9MRC2Ter8jnz8415VbuIykVuc6bhdrbORFZANDmTDvq26mJrEVTl8TdnDg==} + cpu: [arm] + os: [android] + + '@rollup/rollup-android-arm64@4.55.1': + resolution: {integrity: sha512-eFZCb1YUqhTysgW3sj/55du5cG57S7UTNtdMjCW7LwVcj3dTTcowCsC8p7uBdzKsZYa8J7IDE8lhMI+HX1vQvg==} + cpu: [arm64] + os: [android] + + '@rollup/rollup-darwin-arm64@4.55.1': + resolution: {integrity: sha512-p3grE2PHcQm2e8PSGZdzIhCKbMCw/xi9XvMPErPhwO17vxtvCN5FEA2mSLgmKlCjHGMQTP6phuQTYWUnKewwGg==} + cpu: [arm64] + os: [darwin] + + '@rollup/rollup-darwin-x64@4.55.1': + resolution: {integrity: sha512-rDUjG25C9qoTm+e02Esi+aqTKSBYwVTaoS1wxcN47/Luqef57Vgp96xNANwt5npq9GDxsH7kXxNkJVEsWEOEaQ==} + cpu: [x64] + os: [darwin] + + '@rollup/rollup-freebsd-arm64@4.55.1': + resolution: {integrity: sha512-+JiU7Jbp5cdxekIgdte0jfcu5oqw4GCKr6i3PJTlXTCU5H5Fvtkpbs4XJHRmWNXF+hKmn4v7ogI5OQPaupJgOg==} + cpu: [arm64] + os: [freebsd] + + '@rollup/rollup-freebsd-x64@4.55.1': + resolution: {integrity: sha512-V5xC1tOVWtLLmr3YUk2f6EJK4qksksOYiz/TCsFHu/R+woubcLWdC9nZQmwjOAbmExBIVKsm1/wKmEy4z4u4Bw==} + cpu: [x64] + os: [freebsd] + + '@rollup/rollup-linux-arm-gnueabihf@4.55.1': + resolution: {integrity: sha512-Rn3n+FUk2J5VWx+ywrG/HGPTD9jXNbicRtTM11e/uorplArnXZYsVifnPPqNNP5BsO3roI4n8332ukpY/zN7rQ==} + cpu: [arm] + os: [linux] + + '@rollup/rollup-linux-arm-musleabihf@4.55.1': + resolution: {integrity: sha512-grPNWydeKtc1aEdrJDWk4opD7nFtQbMmV7769hiAaYyUKCT1faPRm2av8CX1YJsZ4TLAZcg9gTR1KvEzoLjXkg==} + cpu: [arm] + os: [linux] + + '@rollup/rollup-linux-arm64-gnu@4.55.1': + resolution: {integrity: sha512-a59mwd1k6x8tXKcUxSyISiquLwB5pX+fJW9TkWU46lCqD/GRDe9uDN31jrMmVP3feI3mhAdvcCClhV8V5MhJFQ==} + cpu: [arm64] + os: [linux] + + '@rollup/rollup-linux-arm64-musl@4.55.1': + resolution: {integrity: sha512-puS1MEgWX5GsHSoiAsF0TYrpomdvkaXm0CofIMG5uVkP6IBV+ZO9xhC5YEN49nsgYo1DuuMquF9+7EDBVYu4uA==} + cpu: [arm64] + os: [linux] + + '@rollup/rollup-linux-loong64-gnu@4.55.1': + resolution: {integrity: sha512-r3Wv40in+lTsULSb6nnoudVbARdOwb2u5fpeoOAZjFLznp6tDU8kd+GTHmJoqZ9lt6/Sys33KdIHUaQihFcu7g==} + cpu: [loong64] + os: [linux] + + '@rollup/rollup-linux-loong64-musl@4.55.1': + resolution: {integrity: sha512-MR8c0+UxAlB22Fq4R+aQSPBayvYa3+9DrwG/i1TKQXFYEaoW3B5b/rkSRIypcZDdWjWnpcvxbNaAJDcSbJU3Lw==} + cpu: [loong64] + os: [linux] + + '@rollup/rollup-linux-ppc64-gnu@4.55.1': + resolution: {integrity: sha512-3KhoECe1BRlSYpMTeVrD4sh2Pw2xgt4jzNSZIIPLFEsnQn9gAnZagW9+VqDqAHgm1Xc77LzJOo2LdigS5qZ+gw==} + cpu: [ppc64] + os: [linux] + + '@rollup/rollup-linux-ppc64-musl@4.55.1': + resolution: {integrity: sha512-ziR1OuZx0vdYZZ30vueNZTg73alF59DicYrPViG0NEgDVN8/Jl87zkAPu4u6VjZST2llgEUjaiNl9JM6HH1Vdw==} + cpu: [ppc64] + os: [linux] + + '@rollup/rollup-linux-riscv64-gnu@4.55.1': + resolution: {integrity: sha512-uW0Y12ih2XJRERZ4jAfKamTyIHVMPQnTZcQjme2HMVDAHY4amf5u414OqNYC+x+LzRdRcnIG1YodLrrtA8xsxw==} + cpu: [riscv64] + os: [linux] + + '@rollup/rollup-linux-riscv64-musl@4.55.1': + resolution: {integrity: sha512-u9yZ0jUkOED1BFrqu3BwMQoixvGHGZ+JhJNkNKY/hyoEgOwlqKb62qu+7UjbPSHYjiVy8kKJHvXKv5coH4wDeg==} + cpu: [riscv64] + os: [linux] + + '@rollup/rollup-linux-s390x-gnu@4.55.1': + resolution: {integrity: sha512-/0PenBCmqM4ZUd0190j7J0UsQ/1nsi735iPRakO8iPciE7BQ495Y6msPzaOmvx0/pn+eJVVlZrNrSh4WSYLxNg==} + cpu: [s390x] + os: [linux] + + '@rollup/rollup-linux-x64-gnu@4.55.1': + resolution: {integrity: sha512-a8G4wiQxQG2BAvo+gU6XrReRRqj+pLS2NGXKm8io19goR+K8lw269eTrPkSdDTALwMmJp4th2Uh0D8J9bEV1vg==} + cpu: [x64] + os: [linux] + + '@rollup/rollup-linux-x64-musl@4.55.1': + resolution: {integrity: sha512-bD+zjpFrMpP/hqkfEcnjXWHMw5BIghGisOKPj+2NaNDuVT+8Ds4mPf3XcPHuat1tz89WRL+1wbcxKY3WSbiT7w==} + cpu: [x64] + os: [linux] + + '@rollup/rollup-openbsd-x64@4.55.1': + resolution: {integrity: sha512-eLXw0dOiqE4QmvikfQ6yjgkg/xDM+MdU9YJuP4ySTibXU0oAvnEWXt7UDJmD4UkYialMfOGFPJnIHSe/kdzPxg==} + cpu: [x64] + os: [openbsd] + + '@rollup/rollup-openharmony-arm64@4.55.1': + resolution: {integrity: sha512-xzm44KgEP11te3S2HCSyYf5zIzWmx3n8HDCc7EE59+lTcswEWNpvMLfd9uJvVX8LCg9QWG67Xt75AuHn4vgsXw==} + cpu: [arm64] + os: [openharmony] + + '@rollup/rollup-win32-arm64-msvc@4.55.1': + resolution: {integrity: sha512-yR6Bl3tMC/gBok5cz/Qi0xYnVbIxGx5Fcf/ca0eB6/6JwOY+SRUcJfI0OpeTpPls7f194as62thCt/2BjxYN8g==} + cpu: [arm64] + os: [win32] + + '@rollup/rollup-win32-ia32-msvc@4.55.1': + resolution: {integrity: sha512-3fZBidchE0eY0oFZBnekYCfg+5wAB0mbpCBuofh5mZuzIU/4jIVkbESmd2dOsFNS78b53CYv3OAtwqkZZmU5nA==} + cpu: [ia32] + os: [win32] + + '@rollup/rollup-win32-x64-gnu@4.55.1': + resolution: {integrity: sha512-xGGY5pXj69IxKb4yv/POoocPy/qmEGhimy/FoTpTSVju3FYXUQQMFCaZZXJVidsmGxRioZAwpThl/4zX41gRKg==} + cpu: [x64] + os: [win32] + + '@rollup/rollup-win32-x64-msvc@4.55.1': + resolution: {integrity: sha512-SPEpaL6DX4rmcXtnhdrQYgzQ5W2uW3SCJch88lB2zImhJRhIIK44fkUrgIV/Q8yUNfw5oyZ5vkeQsZLhCb06lw==} + cpu: [x64] + os: [win32] + + '@sec-ant/readable-stream@0.4.1': + resolution: {integrity: sha512-831qok9r2t8AlxLko40y2ebgSDhenenCatLVeW/uBtnHPyhHOvG0C7TvfgecV+wHzIm5KUICgzmVpWS+IMEAeg==} + + '@sindresorhus/merge-streams@4.0.0': + resolution: {integrity: sha512-tlqY9xq5ukxTUZBmoOp+m61cqwQD5pHJtFY3Mn8CA8ps6yghLH/Hw8UPdqg4OLmFW3IFlcXnQNmo/dh8HzXYIQ==} + engines: {node: '>=18'} + + '@types/estree@1.0.8': + resolution: {integrity: sha512-dWHzHa2WqEXI/O1E9OjrocMTKJl2mSrEolh1Iomrv6U+JuNwaHXsXx9bLu5gG7BUWFIN0skIQJQ/L1rIex4X6w==} + + '@types/fs-extra@11.0.4': + resolution: {integrity: sha512-yTbItCNreRooED33qjunPthRcSjERP1r4MqCZc7wv0u2sUkzTFp45tgUfS5+r7FrZPdmCCNflLhVSP/o+SemsQ==} + + '@types/jsonfile@6.1.4': + resolution: {integrity: sha512-D5qGUYwjvnNNextdU59/+fI+spnwtTFmyQP0h+PfIOSkNfpU6AOICUOkm4i0OnSk+NyjdPJrxCDro0sJsWlRpQ==} + + '@types/node@22.19.3': + resolution: {integrity: sha512-1N9SBnWYOJTrNZCdh/yJE+t910Y128BoyY+zBLWhL3r0TYzlTmFdXrPwHL9DyFZmlEXNQQolTZh3KHV31QDhyA==} + + '@types/semver@7.7.1': + resolution: {integrity: sha512-FmgJfu+MOcQ370SD0ev7EI8TlCAfKYU+B4m5T3yXc1CiRN94g/SZPtsCkk506aUDtlMnFZvasDwHHUcZUEaYuA==} + + '@vitest/expect@2.1.9': + resolution: {integrity: sha512-UJCIkTBenHeKT1TTlKMJWy1laZewsRIzYighyYiJKZreqtdxSos/S1t+ktRMQWu2CKqaarrkeszJx1cgC5tGZw==} + + '@vitest/mocker@2.1.9': + resolution: {integrity: sha512-tVL6uJgoUdi6icpxmdrn5YNo3g3Dxv+IHJBr0GXHaEdTcw3F+cPKnsXFhli6nO+f/6SDKPHEK1UN+k+TQv0Ehg==} + peerDependencies: + msw: ^2.4.9 + vite: ^5.0.0 + peerDependenciesMeta: + msw: + optional: true + vite: + optional: true + + '@vitest/pretty-format@2.1.9': + resolution: {integrity: sha512-KhRIdGV2U9HOUzxfiHmY8IFHTdqtOhIzCpd8WRdJiE7D/HUcZVD0EgQCVjm+Q9gkUXWgBvMmTtZgIG48wq7sOQ==} + + '@vitest/runner@2.1.9': + resolution: {integrity: sha512-ZXSSqTFIrzduD63btIfEyOmNcBmQvgOVsPNPe0jYtESiXkhd8u2erDLnMxmGrDCwHCCHE7hxwRDCT3pt0esT4g==} + + '@vitest/snapshot@2.1.9': + resolution: {integrity: sha512-oBO82rEjsxLNJincVhLhaxxZdEtV0EFHMK5Kmx5sJ6H9L183dHECjiefOAdnqpIgT5eZwT04PoggUnW88vOBNQ==} + + '@vitest/spy@2.1.9': + resolution: {integrity: sha512-E1B35FwzXXTs9FHNK6bDszs7mtydNi5MIfUWpceJ8Xbfb1gBMscAnwLbEu+B44ed6W3XjL9/ehLPHR1fkf1KLQ==} + + '@vitest/utils@2.1.9': + resolution: {integrity: sha512-v0psaMSkNJ3A2NMrUEHFRzJtDPFn+/VWZ5WxImB21T9fjucJRmS7xCS3ppEnARb9y11OAzaD+P2Ps+b+BGX5iQ==} + + ansi-regex@5.0.1: + resolution: {integrity: sha512-quJQXlTSUGL2LH9SUXo8VwsY4soanhgo6LNSm84E1LBcE8s3O0wpdiRzyR9z/ZZJMlMWv37qOOb9pdJlMUEKFQ==} + engines: {node: '>=8'} + + ansi-regex@6.2.2: + resolution: {integrity: sha512-Bq3SmSpyFHaWjPk8If9yc6svM8c56dB5BAtW4Qbw5jHTwwXXcTLoRMkpDJp6VL0XzlWaCHTXrkFURMYmD0sLqg==} + engines: {node: '>=12'} + + ansi-styles@4.3.0: + resolution: {integrity: sha512-zbB9rCJAT1rbjiVDb2hqKFHNYLxgtk8NURxZ3IZwD3F6NtxbXZQCnnSi1Lkx+IDohdPlFp222wVALIheZJQSEg==} + engines: {node: '>=8'} + + ansi-styles@6.2.3: + resolution: {integrity: sha512-4Dj6M28JB+oAH8kFkTLUo+a2jwOFkuqb3yucU0CANcRRUbxS0cP0nZYCGjcc3BNXwRIsUVmDGgzawme7zvJHvg==} + engines: {node: '>=12'} + + assertion-error@2.0.1: + resolution: {integrity: sha512-Izi8RQcffqCeNVgFigKli1ssklIbpHnCYc6AknXGYoB6grJqyeby7jv12JUQgmTAnIDnbck1uxksT4dzN3PWBA==} + engines: {node: '>=12'} + + cac@6.7.14: + resolution: {integrity: sha512-b6Ilus+c3RrdDk+JhLKUAQfzzgLEPy6wcXqS7f/xe1EETvsDP6GORG7SFuOs6cID5YkqchW/LXZbX5bc8j7ZcQ==} + engines: {node: '>=8'} + + chai@5.3.3: + resolution: {integrity: sha512-4zNhdJD/iOjSH0A05ea+Ke6MU5mmpQcbQsSOkgdaUMJ9zTlDTD/GYlwohmIE2u0gaxHYiVHEn1Fw9mZ/ktJWgw==} + engines: {node: '>=18'} + + chalk@5.6.2: + resolution: {integrity: sha512-7NzBL0rN6fMUW+f7A6Io4h40qQlG+xGmtMxfbnH/K7TAtt8JQWVQK+6g0UXKMeVJoyV5EkkNsErQ8pVD3bLHbA==} + engines: {node: ^12.17.0 || ^14.13 || >=16.0.0} + + check-error@2.1.3: + resolution: {integrity: sha512-PAJdDJusoxnwm1VwW07VWwUN1sl7smmC3OKggvndJFadxxDRyFJBX/ggnu/KE4kQAB7a3Dp8f/YXC1FlUprWmA==} + engines: {node: '>= 16'} + + color-convert@2.0.1: + resolution: {integrity: sha512-RRECPsj7iu/xb5oKYcsFHSppFNnsj/52OVTRKb4zP5onXwVF3zVmmToNcOfGC+CRDpfK/U584fMg38ZHCaElKQ==} + engines: {node: '>=7.0.0'} + + color-name@1.1.4: + resolution: {integrity: sha512-dOy+3AuW3a2wNbZHIuMZpTcgjGuLU/uBL/ubcZF9OXbDo8ff4O8yVp5Bf0efS8uEoYo5q4Fx7dY9OgQGXgAsQA==} + + commander@12.1.0: + resolution: {integrity: sha512-Vw8qHK3bZM9y/P10u3Vib8o/DdkvA2OtPtZvD871QKjy74Wj1WSKFILMPRPSdUSx5RFK1arlJzEtA4PkFgnbuA==} + engines: {node: '>=18'} + + cross-spawn@7.0.6: + resolution: {integrity: sha512-uV2QOWP2nWzsy2aMp8aRibhi9dlzF5Hgh5SHaB9OiTGEyDTiJJyx0uy51QXdyWbtAHNua4XJzUKca3OzKUd3vA==} + engines: {node: '>= 8'} + + debug@4.4.3: + resolution: {integrity: sha512-RGwwWnwQvkVfavKVt22FGLw+xYSdzARwm0ru6DhTVA3umU5hZc28V3kO4stgYryrTlLpuvgI9GiijltAjNbcqA==} + engines: {node: '>=6.0'} + peerDependencies: + supports-color: '*' + peerDependenciesMeta: + supports-color: + optional: true + + deep-eql@5.0.2: + resolution: {integrity: sha512-h5k/5U50IJJFpzfL6nO9jaaumfjO/f2NjK/oYB2Djzm4p9L+3T9qWpZqZ2hAbLPuuYq9wrU08WQyBTL5GbPk5Q==} + engines: {node: '>=6'} + + eastasianwidth@0.2.0: + resolution: {integrity: sha512-I88TYZWc9XiYHRQ4/3c5rjjfgkjhLyW2luGIheGERbNQ6OY7yTybanSpDXZa8y7VUP9YmDcYa+eyq4ca7iLqWA==} + + emoji-regex@8.0.0: + resolution: {integrity: sha512-MSjYzcWNOA0ewAHpz0MxpYFvwg6yjy1NG3xteoqz644VCo/RPgnr1/GGt+ic3iJTzQ8Eu3TdM14SawnVUmGE6A==} + + emoji-regex@9.2.2: + resolution: {integrity: sha512-L18DaJsXSUk2+42pv8mLs5jJT2hqFkFE4j21wOmgbUqsZ2hL72NsUU785g9RXgo3s0ZNgVl42TiHp3ZtOv/Vyg==} + + es-module-lexer@1.7.0: + resolution: {integrity: sha512-jEQoCwk8hyb2AZziIOLhDqpm5+2ww5uIE6lkO/6jcOCusfk6LhMHpXXfBLXTZ7Ydyt0j4VoUQv6uGNYbdW+kBA==} + + esbuild@0.21.5: + resolution: {integrity: sha512-mg3OPMV4hXywwpoDxu3Qda5xCKQi+vCTZq8S9J/EpkhB2HzKXq4SNFZE3+NK93JYxc8VMSep+lOUSC/RVKaBqw==} + engines: {node: '>=12'} + hasBin: true + + esbuild@0.27.2: + resolution: {integrity: sha512-HyNQImnsOC7X9PMNaCIeAm4ISCQXs5a5YasTXVliKv4uuBo1dKrG0A+uQS8M5eXjVMnLg3WgXaKvprHlFJQffw==} + engines: {node: '>=18'} + hasBin: true + + estree-walker@3.0.3: + resolution: {integrity: sha512-7RUKfXgSMMkzt6ZuXmqapOurLGPPfgj6l9uRZ7lRGolvk0y2yocc35LdcxKC5PQZdn2DMqioAQ2NoWcrTKmm6g==} + + execa@9.6.1: + resolution: {integrity: sha512-9Be3ZoN4LmYR90tUoVu2te2BsbzHfhJyfEiAVfz7N5/zv+jduIfLrV2xdQXOHbaD6KgpGdO9PRPM1Y4Q9QkPkA==} + engines: {node: ^18.19.0 || >=20.5.0} + + expect-type@1.3.0: + resolution: {integrity: sha512-knvyeauYhqjOYvQ66MznSMs83wmHrCycNEN6Ao+2AeYEfxUIkuiVxdEa1qlGEPK+We3n0THiDciYSsCcgW/DoA==} + engines: {node: '>=12.0.0'} + + figures@6.1.0: + resolution: {integrity: sha512-d+l3qxjSesT4V7v2fh+QnmFnUWv9lSpjarhShNTgBOfA0ttejbQUAlHLitbjkoRiDulW0OPoQPYIGhIC8ohejg==} + engines: {node: '>=18'} + + foreground-child@3.3.1: + resolution: {integrity: sha512-gIXjKqtFuWEgzFRJA9WCQeSJLZDjgJUOMCMzxtvFq/37KojM1BFGufqsCy0r4qSQmYLsZYMeyRqzIWOMup03sw==} + engines: {node: '>=14'} + + fs-extra@11.3.3: + resolution: {integrity: sha512-VWSRii4t0AFm6ixFFmLLx1t7wS1gh+ckoa84aOeapGum0h+EZd1EhEumSB+ZdDLnEPuucsVB9oB7cxJHap6Afg==} + engines: {node: '>=14.14'} + + fsevents@2.3.3: + resolution: {integrity: sha512-5xoDfX+fL7faATnagmWPpbFtwh/R77WmMMqqHGS65C3vvB0YHrgF+B1YmZ3441tMj5n63k0212XNoJwzlhffQw==} + engines: {node: ^8.16.0 || ^10.6.0 || >=11.0.0} + os: [darwin] + + get-stream@9.0.1: + resolution: {integrity: sha512-kVCxPF3vQM/N0B1PmoqVUqgHP+EeVjmZSQn+1oCRPxd2P21P2F19lIgbR3HBosbB1PUhOAoctJnfEn2GbN2eZA==} + engines: {node: '>=18'} + + get-tsconfig@4.13.0: + resolution: {integrity: sha512-1VKTZJCwBrvbd+Wn3AOgQP/2Av+TfTCOlE4AcRJE72W1ksZXbAx8PPBR9RzgTeSPzlPMHrbANMH3LbltH73wxQ==} + + glob@11.1.0: + resolution: {integrity: sha512-vuNwKSaKiqm7g0THUBu2x7ckSs3XJLXE+2ssL7/MfTGPLLcrJQ/4Uq1CjPTtO5cCIiRxqvN6Twy1qOwhL0Xjcw==} + engines: {node: 20 || >=22} + hasBin: true + + graceful-fs@4.2.11: + resolution: {integrity: sha512-RbJ5/jmFcNNCcDV5o9eTnBLJ/HszWV0P73bc+Ff4nS/rJj+YaS6IGyiOL0VoBYX+l1Wrl3k63h/KrH+nhJ0XvQ==} + + human-signals@8.0.1: + resolution: {integrity: sha512-eKCa6bwnJhvxj14kZk5NCPc6Hb6BdsU9DZcOnmQKSnO1VKrfV0zCvtttPZUsBvjmNDn8rpcJfpwSYnHBjc95MQ==} + engines: {node: '>=18.18.0'} + + is-fullwidth-code-point@3.0.0: + resolution: {integrity: sha512-zymm5+u+sCsSWyD9qNaejV3DFvhCKclKdizYaJUuHA83RLjb7nSuGnddCHGv0hk+KY7BMAlsWeK4Ueg6EV6XQg==} + engines: {node: '>=8'} + + is-plain-obj@4.1.0: + resolution: {integrity: sha512-+Pgi+vMuUNkJyExiMBt5IlFoMyKnr5zhJ4Uspz58WOhBF5QoIZkFyNHIbBAtHwzVAgk5RtndVNsDRN61/mmDqg==} + engines: {node: '>=12'} + + is-stream@4.0.1: + resolution: {integrity: sha512-Dnz92NInDqYckGEUJv689RbRiTSEHCQ7wOVeALbkOz999YpqT46yMRIGtSNl2iCL1waAZSx40+h59NV/EwzV/A==} + engines: {node: '>=18'} + + is-unicode-supported@2.1.0: + resolution: {integrity: sha512-mE00Gnza5EEB3Ds0HfMyllZzbBrmLOX3vfWoj9A9PEnTfratQ/BcaJOuMhnkhjXvb2+FkY3VuHqtAGpTPmglFQ==} + engines: {node: '>=18'} + + isexe@2.0.0: + resolution: {integrity: sha512-RHxMLp9lnKHGHRng9QFhRCMbYAcVpn69smSGcq3f36xjgVVWThj4qqLbTLlq7Ssj8B+fIQ1EuCEGI2lKsyQeIw==} + + jackspeak@4.1.1: + resolution: {integrity: sha512-zptv57P3GpL+O0I7VdMJNBZCu+BPHVQUk55Ft8/QCJjTVxrnJHuVuX/0Bl2A6/+2oyR/ZMEuFKwmzqqZ/U5nPQ==} + engines: {node: 20 || >=22} + + jsonfile@6.2.0: + resolution: {integrity: sha512-FGuPw30AdOIUTRMC2OMRtQV+jkVj2cfPqSeWXv1NEAJ1qZ5zb1X6z1mFhbfOB/iy3ssJCD+3KuZ8r8C3uVFlAg==} + + loupe@3.2.1: + resolution: {integrity: sha512-CdzqowRJCeLU72bHvWqwRBBlLcMEtIvGrlvef74kMnV2AolS9Y8xUv1I0U/MNAWMhBlKIoyuEgoJ0t/bbwHbLQ==} + + lru-cache@11.2.4: + resolution: {integrity: sha512-B5Y16Jr9LB9dHVkh6ZevG+vAbOsNOYCX+sXvFWFu7B3Iz5mijW3zdbMyhsh8ANd2mSWBYdJgnqi+mL7/LrOPYg==} + engines: {node: 20 || >=22} + + magic-string@0.30.21: + resolution: {integrity: sha512-vd2F4YUyEXKGcLHoq+TEyCjxueSeHnFxyyjNp80yg0XV4vUhnDer/lvvlqM/arB5bXQN5K2/3oinyCRyx8T2CQ==} + + minimatch@10.1.1: + resolution: {integrity: sha512-enIvLvRAFZYXJzkCYG5RKmPfrFArdLv+R+lbQ53BmIMLIry74bjKzX6iHAm8WYamJkhSSEabrWN5D97XnKObjQ==} + engines: {node: 20 || >=22} + + minipass@7.1.2: + resolution: {integrity: sha512-qOOzS1cBTWYF4BH8fVePDBOO9iptMnGUEZwNc/cMWnTV2nVLZ7VoNWEPHkYczZA0pdoA7dl6e7FL659nX9S2aw==} + engines: {node: '>=16 || 14 >=14.17'} + + ms@2.1.3: + resolution: {integrity: sha512-6FlzubTLZG3J2a/NVCAleEhjzq5oxgHyaCU9yYXvcLsvoVaHJq/s5xXI6/XXP6tz7R9xAOtHnSO/tXtF3WRTlA==} + + nanoid@3.3.11: + resolution: {integrity: sha512-N8SpfPUnUp1bK+PMYW8qSWdl9U+wwNWI4QKxOYDy9JAro3WMX7p2OeVRF9v+347pnakNevPmiHhNmZ2HbFA76w==} + engines: {node: ^10 || ^12 || ^13.7 || ^14 || >=15.0.1} + hasBin: true + + npm-run-path@6.0.0: + resolution: {integrity: sha512-9qny7Z9DsQU8Ou39ERsPU4OZQlSTP47ShQzuKZ6PRXpYLtIFgl/DEBYEXKlvcEa+9tHVcK8CF81Y2V72qaZhWA==} + engines: {node: '>=18'} + + package-json-from-dist@1.0.1: + resolution: {integrity: sha512-UEZIS3/by4OC8vL3P2dTXRETpebLI2NiI5vIrjaD/5UtrkFX/tNbwjTSRAGC/+7CAo2pIcBaRgWmcBBHcsaCIw==} + + parse-ms@4.0.0: + resolution: {integrity: sha512-TXfryirbmq34y8QBwgqCVLi+8oA3oWx2eAnSn62ITyEhEYaWRlVZ2DvMM9eZbMs/RfxPu/PK/aBLyGj4IrqMHw==} + engines: {node: '>=18'} + + path-key@3.1.1: + resolution: {integrity: sha512-ojmeN0qd+y0jszEtoY48r0Peq5dwMEkIlCOu6Q5f41lfkswXuKtYrhgoTpLnyIcHm24Uhqx+5Tqm2InSwLhE6Q==} + engines: {node: '>=8'} + + path-key@4.0.0: + resolution: {integrity: sha512-haREypq7xkM7ErfgIyA0z+Bj4AGKlMSdlQE2jvJo6huWD1EdkKYV+G/T4nq0YEF2vgTT8kqMFKo1uHn950r4SQ==} + engines: {node: '>=12'} + + path-scurry@2.0.1: + resolution: {integrity: sha512-oWyT4gICAu+kaA7QWk/jvCHWarMKNs6pXOGWKDTr7cw4IGcUbW+PeTfbaQiLGheFRpjo6O9J0PmyMfQPjH71oA==} + engines: {node: 20 || >=22} + + pathe@1.1.2: + resolution: {integrity: sha512-whLdWMYL2TwI08hn8/ZqAbrVemu0LNaNNJZX73O6qaIdCTfXutsLhMkjdENX0qhsQ9uIimo4/aQOmXkoon2nDQ==} + + pathval@2.0.1: + resolution: {integrity: sha512-//nshmD55c46FuFw26xV/xFAaB5HF9Xdap7HJBBnrKdAd6/GxDBaNA1870O79+9ueg61cZLSVc+OaFlfmObYVQ==} + engines: {node: '>= 14.16'} + + picocolors@1.1.1: + resolution: {integrity: sha512-xceH2snhtb5M9liqDsmEw56le376mTZkEX/jEb/RxNFyegNul7eNslCXP9FDj/Lcu0X8KEyMceP2ntpaHrDEVA==} + + postcss@8.5.6: + resolution: {integrity: sha512-3Ybi1tAuwAP9s0r1UQ2J4n5Y0G05bJkpUIO0/bI9MhwmD70S5aTWbXGBwxHrelT+XM1k6dM0pk+SwNkpTRN7Pg==} + engines: {node: ^10 || ^12 || >=14} + + pretty-ms@9.3.0: + resolution: {integrity: sha512-gjVS5hOP+M3wMm5nmNOucbIrqudzs9v/57bWRHQWLYklXqoXKrVfYW2W9+glfGsqtPgpiz5WwyEEB+ksXIx3gQ==} + engines: {node: '>=18'} + + resolve-pkg-maps@1.0.0: + resolution: {integrity: sha512-seS2Tj26TBVOC2NIc2rOe2y2ZO7efxITtLZcGSOnHHNOQ7CkiUBfw0Iw2ck6xkIhPwLhKNLS8BO+hEpngQlqzw==} + + rollup@4.55.1: + resolution: {integrity: sha512-wDv/Ht1BNHB4upNbK74s9usvl7hObDnvVzknxqY/E/O3X6rW1U1rV1aENEfJ54eFZDTNo7zv1f5N4edCluH7+A==} + engines: {node: '>=18.0.0', npm: '>=8.0.0'} + hasBin: true + + semver@7.7.3: + resolution: {integrity: sha512-SdsKMrI9TdgjdweUSR9MweHA4EJ8YxHn8DFaDisvhVlUOe4BF1tLD7GAj0lIqWVl+dPb/rExr0Btby5loQm20Q==} + engines: {node: '>=10'} + hasBin: true + + shebang-command@2.0.0: + resolution: {integrity: sha512-kHxr2zZpYtdmrN1qDjrrX/Z1rR1kG8Dx+gkpK1G4eXmvXswmcE1hTWBWYUzlraYw1/yZp6YuDY77YtvbN0dmDA==} + engines: {node: '>=8'} + + shebang-regex@3.0.0: + resolution: {integrity: sha512-7++dFhtcx3353uBaq8DDR4NuxBetBzC7ZQOhmTQInHEd6bSrXdiEyzCvG07Z44UYdLShWUyXt5M/yhz8ekcb1A==} + engines: {node: '>=8'} + + siginfo@2.0.0: + resolution: {integrity: sha512-ybx0WO1/8bSBLEWXZvEd7gMW3Sn3JFlW3TvX1nREbDLRNQNaeNN8WK0meBwPdAaOI7TtRRRJn/Es1zhrrCHu7g==} + + signal-exit@4.1.0: + resolution: {integrity: sha512-bzyZ1e88w9O1iNJbKnOlvYTrWPDl46O1bG0D3XInv+9tkPrxrN8jUUTiFlDkkmKWgn1M6CfIA13SuGqOa9Korw==} + engines: {node: '>=14'} + + simple-git@3.30.0: + resolution: {integrity: sha512-q6lxyDsCmEal/MEGhP1aVyQ3oxnagGlBDOVSIB4XUVLl1iZh0Pah6ebC9V4xBap/RfgP2WlI8EKs0WS0rMEJHg==} + + source-map-js@1.2.1: + resolution: {integrity: sha512-UXWMKhLOwVKb728IUtQPXxfYU+usdybtUrK/8uGE8CQMvrhOpwvzDBwj0QhSL7MQc7vIsISBG8VQ8+IDQxpfQA==} + engines: {node: '>=0.10.0'} + + stackback@0.0.2: + resolution: {integrity: sha512-1XMJE5fQo1jGH6Y/7ebnwPOBEkIEnT4QF32d5R1+VXdXveM0IBMJt8zfaxX1P3QhVwrYe+576+jkANtSS2mBbw==} + + std-env@3.10.0: + resolution: {integrity: sha512-5GS12FdOZNliM5mAOxFRg7Ir0pWz8MdpYm6AY6VPkGpbA7ZzmbzNcBJQ0GPvvyWgcY7QAhCgf9Uy89I03faLkg==} + + string-width@4.2.3: + resolution: {integrity: sha512-wKyQRQpjJ0sIp62ErSZdGsjMJWsap5oRNihHhu6G7JVO/9jIB6UyevL+tXuOqrng8j/cxKTWyWUwvSTriiZz/g==} + engines: {node: '>=8'} + + string-width@5.1.2: + resolution: {integrity: sha512-HnLOCR3vjcY8beoNLtcjZ5/nxn2afmME6lhrDrebokqMap+XbeW8n9TXpPDOqdGK5qcI3oT0GKTW6wC7EMiVqA==} + engines: {node: '>=12'} + + strip-ansi@6.0.1: + resolution: {integrity: sha512-Y38VPSHcqkFrCpFnQ9vuSXmquuv5oXOKpGeT6aGrr3o3Gc9AlVa6JBfUSOCnbxGGZF+/0ooI7KrPuUSztUdU5A==} + engines: {node: '>=8'} + + strip-ansi@7.1.2: + resolution: {integrity: sha512-gmBGslpoQJtgnMAvOVqGZpEz9dyoKTCzy2nfz/n8aIFhN/jCE/rCmcxabB6jOOHV+0WNnylOxaxBQPSvcWklhA==} + engines: {node: '>=12'} + + strip-final-newline@4.0.0: + resolution: {integrity: sha512-aulFJcD6YK8V1G7iRB5tigAP4TsHBZZrOV8pjV++zdUwmeV8uzbY7yn6h9MswN62adStNZFuCIx4haBnRuMDaw==} + engines: {node: '>=18'} + + tinybench@2.9.0: + resolution: {integrity: sha512-0+DUvqWMValLmha6lr4kD8iAMK1HzV0/aKnCtWb9v9641TnP/MFb7Pc2bxoxQjTXAErryXVgUOfv2YqNllqGeg==} + + tinyexec@0.3.2: + resolution: {integrity: sha512-KQQR9yN7R5+OSwaK0XQoj22pwHoTlgYqmUscPYoknOoWCWfj/5/ABTMRi69FrKU5ffPVh5QcFikpWJI/P1ocHA==} + + tinypool@1.1.1: + resolution: {integrity: sha512-Zba82s87IFq9A9XmjiX5uZA/ARWDrB03OHlq+Vw1fSdt0I+4/Kutwy8BP4Y/y/aORMo61FQ0vIb5j44vSo5Pkg==} + engines: {node: ^18.0.0 || >=20.0.0} + + tinyrainbow@1.2.0: + resolution: {integrity: sha512-weEDEq7Z5eTHPDh4xjX789+fHfF+P8boiFB+0vbWzpbnbsEr/GRaohi/uMKxg8RZMXnl1ItAi/IUHWMsjDV7kQ==} + engines: {node: '>=14.0.0'} + + tinyspy@3.0.2: + resolution: {integrity: sha512-n1cw8k1k0x4pgA2+9XrOkFydTerNcJ1zWCO5Nn9scWHTD+5tp8dghT2x1uduQePZTZgd3Tupf+x9BxJjeJi77Q==} + engines: {node: '>=14.0.0'} + + tsx@4.21.0: + resolution: {integrity: sha512-5C1sg4USs1lfG0GFb2RLXsdpXqBSEhAaA/0kPL01wxzpMqLILNxIxIOKiILz+cdg/pLnOUxFYOR5yhHU666wbw==} + engines: {node: '>=18.0.0'} + hasBin: true + + typescript@5.9.3: + resolution: {integrity: sha512-jl1vZzPDinLr9eUt3J/t7V6FgNEw9QjvBPdysz9KfQDD41fQrC2Y4vKQdiaUpFT4bXlb1RHhLpp8wtm6M5TgSw==} + engines: {node: '>=14.17'} + hasBin: true + + undici-types@6.21.0: + resolution: {integrity: sha512-iwDZqg0QAGrg9Rav5H4n0M64c3mkR59cJ6wQp+7C4nI0gsmExaedaYLNO44eT4AtBBwjbTiGPMlt2Md0T9H9JQ==} + + unicorn-magic@0.3.0: + resolution: {integrity: sha512-+QBBXBCvifc56fsbuxZQ6Sic3wqqc3WWaqxs58gvJrcOuN83HGTCwz3oS5phzU9LthRNE9VrJCFCLUgHeeFnfA==} + engines: {node: '>=18'} + + universalify@2.0.1: + resolution: {integrity: sha512-gptHNQghINnc/vTGIk0SOFGFNXw7JVrlRUtConJRlvaw6DuX0wO5Jeko9sWrMBhh+PsYAZ7oXAiOnf/UKogyiw==} + engines: {node: '>= 10.0.0'} + + vite-node@2.1.9: + resolution: {integrity: sha512-AM9aQ/IPrW/6ENLQg3AGY4K1N2TGZdR5e4gu/MmmR2xR3Ll1+dib+nook92g4TV3PXVyeyxdWwtaCAiUL0hMxA==} + engines: {node: ^18.0.0 || >=20.0.0} + hasBin: true + + vite@5.4.21: + resolution: {integrity: sha512-o5a9xKjbtuhY6Bi5S3+HvbRERmouabWbyUcpXXUA1u+GNUKoROi9byOJ8M0nHbHYHkYICiMlqxkg1KkYmm25Sw==} + engines: {node: ^18.0.0 || >=20.0.0} + hasBin: true + peerDependencies: + '@types/node': ^18.0.0 || >=20.0.0 + less: '*' + lightningcss: ^1.21.0 + sass: '*' + sass-embedded: '*' + stylus: '*' + sugarss: '*' + terser: ^5.4.0 + peerDependenciesMeta: + '@types/node': + optional: true + less: + optional: true + lightningcss: + optional: true + sass: + optional: true + sass-embedded: + optional: true + stylus: + optional: true + sugarss: + optional: true + terser: + optional: true + + vitest@2.1.9: + resolution: {integrity: sha512-MSmPM9REYqDGBI8439mA4mWhV5sKmDlBKWIYbA3lRb2PTHACE0mgKwA8yQ2xq9vxDTuk4iPrECBAEW2aoFXY0Q==} + engines: {node: ^18.0.0 || >=20.0.0} + hasBin: true + peerDependencies: + '@edge-runtime/vm': '*' + '@types/node': ^18.0.0 || >=20.0.0 + '@vitest/browser': 2.1.9 + '@vitest/ui': 2.1.9 + happy-dom: '*' + jsdom: '*' + peerDependenciesMeta: + '@edge-runtime/vm': + optional: true + '@types/node': + optional: true + '@vitest/browser': + optional: true + '@vitest/ui': + optional: true + happy-dom: + optional: true + jsdom: + optional: true + + which@2.0.2: + resolution: {integrity: sha512-BLI3Tl1TW3Pvl70l3yq3Y64i+awpwXqsGBYWkkqMtnbXgrMD+yj7rhW0kuEDxzJaYXGjEW5ogapKNMEKNMjibA==} + engines: {node: '>= 8'} + hasBin: true + + why-is-node-running@2.3.0: + resolution: {integrity: sha512-hUrmaWBdVDcxvYqnyh09zunKzROWjbZTiNy8dBEjkS7ehEDQibXJ7XvlmtbwuTclUiIyN+CyXQD4Vmko8fNm8w==} + engines: {node: '>=8'} + hasBin: true + + wrap-ansi@7.0.0: + resolution: {integrity: sha512-YVGIj2kamLSTxw6NsZjoBxfSwsn0ycdesmc4p+Q21c5zPuZ1pl+NfxVdxPtdHvmNVOQ6XSYG4AUtyt/Fi7D16Q==} + engines: {node: '>=10'} + + wrap-ansi@8.1.0: + resolution: {integrity: sha512-si7QWI6zUMq56bESFvagtmzMdGOtoxfR+Sez11Mobfc7tm+VkUckk9bW2UeffTGVUbOksxmSw0AA2gs8g71NCQ==} + engines: {node: '>=12'} + + yoctocolors@2.1.2: + resolution: {integrity: sha512-CzhO+pFNo8ajLM2d2IW/R93ipy99LWjtwblvC1RsoSUMZgyLbYFr221TnSNT7GjGdYui6P459mw9JH/g/zW2ug==} + engines: {node: '>=18'} + + zod@3.25.76: + resolution: {integrity: sha512-gzUt/qt81nXsFGKIFcC3YnfEAx5NkunCfnDlvuBSSFS02bcXu4Lmea0AFIUwbLWxWPx3d9p8S5QoaujKcNQxcQ==} + +snapshots: + + '@esbuild/aix-ppc64@0.21.5': + optional: true + + '@esbuild/aix-ppc64@0.27.2': + optional: true + + '@esbuild/android-arm64@0.21.5': + optional: true + + '@esbuild/android-arm64@0.27.2': + optional: true + + '@esbuild/android-arm@0.21.5': + optional: true + + '@esbuild/android-arm@0.27.2': + optional: true + + '@esbuild/android-x64@0.21.5': + optional: true + + '@esbuild/android-x64@0.27.2': + optional: true + + '@esbuild/darwin-arm64@0.21.5': + optional: true + + '@esbuild/darwin-arm64@0.27.2': + optional: true + + '@esbuild/darwin-x64@0.21.5': + optional: true + + '@esbuild/darwin-x64@0.27.2': + optional: true + + '@esbuild/freebsd-arm64@0.21.5': + optional: true + + '@esbuild/freebsd-arm64@0.27.2': + optional: true + + '@esbuild/freebsd-x64@0.21.5': + optional: true + + '@esbuild/freebsd-x64@0.27.2': + optional: true + + '@esbuild/linux-arm64@0.21.5': + optional: true + + '@esbuild/linux-arm64@0.27.2': + optional: true + + '@esbuild/linux-arm@0.21.5': + optional: true + + '@esbuild/linux-arm@0.27.2': + optional: true + + '@esbuild/linux-ia32@0.21.5': + optional: true + + '@esbuild/linux-ia32@0.27.2': + optional: true + + '@esbuild/linux-loong64@0.21.5': + optional: true + + '@esbuild/linux-loong64@0.27.2': + optional: true + + '@esbuild/linux-mips64el@0.21.5': + optional: true + + '@esbuild/linux-mips64el@0.27.2': + optional: true + + '@esbuild/linux-ppc64@0.21.5': + optional: true + + '@esbuild/linux-ppc64@0.27.2': + optional: true + + '@esbuild/linux-riscv64@0.21.5': + optional: true + + '@esbuild/linux-riscv64@0.27.2': + optional: true + + '@esbuild/linux-s390x@0.21.5': + optional: true + + '@esbuild/linux-s390x@0.27.2': + optional: true + + '@esbuild/linux-x64@0.21.5': + optional: true + + '@esbuild/linux-x64@0.27.2': + optional: true + + '@esbuild/netbsd-arm64@0.27.2': + optional: true + + '@esbuild/netbsd-x64@0.21.5': + optional: true + + '@esbuild/netbsd-x64@0.27.2': + optional: true + + '@esbuild/openbsd-arm64@0.27.2': + optional: true + + '@esbuild/openbsd-x64@0.21.5': + optional: true + + '@esbuild/openbsd-x64@0.27.2': + optional: true + + '@esbuild/openharmony-arm64@0.27.2': + optional: true + + '@esbuild/sunos-x64@0.21.5': + optional: true + + '@esbuild/sunos-x64@0.27.2': + optional: true + + '@esbuild/win32-arm64@0.21.5': + optional: true + + '@esbuild/win32-arm64@0.27.2': + optional: true + + '@esbuild/win32-ia32@0.21.5': + optional: true + + '@esbuild/win32-ia32@0.27.2': + optional: true + + '@esbuild/win32-x64@0.21.5': + optional: true + + '@esbuild/win32-x64@0.27.2': + optional: true + + '@isaacs/balanced-match@4.0.1': {} + + '@isaacs/brace-expansion@5.0.0': + dependencies: + '@isaacs/balanced-match': 4.0.1 + + '@isaacs/cliui@8.0.2': + dependencies: + string-width: 5.1.2 + string-width-cjs: string-width@4.2.3 + strip-ansi: 7.1.2 + strip-ansi-cjs: strip-ansi@6.0.1 + wrap-ansi: 8.1.0 + wrap-ansi-cjs: wrap-ansi@7.0.0 + + '@jridgewell/sourcemap-codec@1.5.5': {} + + '@kwsites/file-exists@1.1.1': + dependencies: + debug: 4.4.3 + transitivePeerDependencies: + - supports-color + + '@kwsites/promise-deferred@1.1.1': {} + + '@rollup/rollup-android-arm-eabi@4.55.1': + optional: true + + '@rollup/rollup-android-arm64@4.55.1': + optional: true + + '@rollup/rollup-darwin-arm64@4.55.1': + optional: true + + '@rollup/rollup-darwin-x64@4.55.1': + optional: true + + '@rollup/rollup-freebsd-arm64@4.55.1': + optional: true + + '@rollup/rollup-freebsd-x64@4.55.1': + optional: true + + '@rollup/rollup-linux-arm-gnueabihf@4.55.1': + optional: true + + '@rollup/rollup-linux-arm-musleabihf@4.55.1': + optional: true + + '@rollup/rollup-linux-arm64-gnu@4.55.1': + optional: true + + '@rollup/rollup-linux-arm64-musl@4.55.1': + optional: true + + '@rollup/rollup-linux-loong64-gnu@4.55.1': + optional: true + + '@rollup/rollup-linux-loong64-musl@4.55.1': + optional: true + + '@rollup/rollup-linux-ppc64-gnu@4.55.1': + optional: true + + '@rollup/rollup-linux-ppc64-musl@4.55.1': + optional: true + + '@rollup/rollup-linux-riscv64-gnu@4.55.1': + optional: true + + '@rollup/rollup-linux-riscv64-musl@4.55.1': + optional: true + + '@rollup/rollup-linux-s390x-gnu@4.55.1': + optional: true + + '@rollup/rollup-linux-x64-gnu@4.55.1': + optional: true + + '@rollup/rollup-linux-x64-musl@4.55.1': + optional: true + + '@rollup/rollup-openbsd-x64@4.55.1': + optional: true + + '@rollup/rollup-openharmony-arm64@4.55.1': + optional: true + + '@rollup/rollup-win32-arm64-msvc@4.55.1': + optional: true + + '@rollup/rollup-win32-ia32-msvc@4.55.1': + optional: true + + '@rollup/rollup-win32-x64-gnu@4.55.1': + optional: true + + '@rollup/rollup-win32-x64-msvc@4.55.1': + optional: true + + '@sec-ant/readable-stream@0.4.1': {} + + '@sindresorhus/merge-streams@4.0.0': {} + + '@types/estree@1.0.8': {} + + '@types/fs-extra@11.0.4': + dependencies: + '@types/jsonfile': 6.1.4 + '@types/node': 22.19.3 + + '@types/jsonfile@6.1.4': + dependencies: + '@types/node': 22.19.3 + + '@types/node@22.19.3': + dependencies: + undici-types: 6.21.0 + + '@types/semver@7.7.1': {} + + '@vitest/expect@2.1.9': + dependencies: + '@vitest/spy': 2.1.9 + '@vitest/utils': 2.1.9 + chai: 5.3.3 + tinyrainbow: 1.2.0 + + '@vitest/mocker@2.1.9(vite@5.4.21(@types/node@22.19.3))': + dependencies: + '@vitest/spy': 2.1.9 + estree-walker: 3.0.3 + magic-string: 0.30.21 + optionalDependencies: + vite: 5.4.21(@types/node@22.19.3) + + '@vitest/pretty-format@2.1.9': + dependencies: + tinyrainbow: 1.2.0 + + '@vitest/runner@2.1.9': + dependencies: + '@vitest/utils': 2.1.9 + pathe: 1.1.2 + + '@vitest/snapshot@2.1.9': + dependencies: + '@vitest/pretty-format': 2.1.9 + magic-string: 0.30.21 + pathe: 1.1.2 + + '@vitest/spy@2.1.9': + dependencies: + tinyspy: 3.0.2 + + '@vitest/utils@2.1.9': + dependencies: + '@vitest/pretty-format': 2.1.9 + loupe: 3.2.1 + tinyrainbow: 1.2.0 + + ansi-regex@5.0.1: {} + + ansi-regex@6.2.2: {} + + ansi-styles@4.3.0: + dependencies: + color-convert: 2.0.1 + + ansi-styles@6.2.3: {} + + assertion-error@2.0.1: {} + + cac@6.7.14: {} + + chai@5.3.3: + dependencies: + assertion-error: 2.0.1 + check-error: 2.1.3 + deep-eql: 5.0.2 + loupe: 3.2.1 + pathval: 2.0.1 + + chalk@5.6.2: {} + + check-error@2.1.3: {} + + color-convert@2.0.1: + dependencies: + color-name: 1.1.4 + + color-name@1.1.4: {} + + commander@12.1.0: {} + + cross-spawn@7.0.6: + dependencies: + path-key: 3.1.1 + shebang-command: 2.0.0 + which: 2.0.2 + + debug@4.4.3: + dependencies: + ms: 2.1.3 + + deep-eql@5.0.2: {} + + eastasianwidth@0.2.0: {} + + emoji-regex@8.0.0: {} + + emoji-regex@9.2.2: {} + + es-module-lexer@1.7.0: {} + + esbuild@0.21.5: + optionalDependencies: + '@esbuild/aix-ppc64': 0.21.5 + '@esbuild/android-arm': 0.21.5 + '@esbuild/android-arm64': 0.21.5 + '@esbuild/android-x64': 0.21.5 + '@esbuild/darwin-arm64': 0.21.5 + '@esbuild/darwin-x64': 0.21.5 + '@esbuild/freebsd-arm64': 0.21.5 + '@esbuild/freebsd-x64': 0.21.5 + '@esbuild/linux-arm': 0.21.5 + '@esbuild/linux-arm64': 0.21.5 + '@esbuild/linux-ia32': 0.21.5 + '@esbuild/linux-loong64': 0.21.5 + '@esbuild/linux-mips64el': 0.21.5 + '@esbuild/linux-ppc64': 0.21.5 + '@esbuild/linux-riscv64': 0.21.5 + '@esbuild/linux-s390x': 0.21.5 + '@esbuild/linux-x64': 0.21.5 + '@esbuild/netbsd-x64': 0.21.5 + '@esbuild/openbsd-x64': 0.21.5 + '@esbuild/sunos-x64': 0.21.5 + '@esbuild/win32-arm64': 0.21.5 + '@esbuild/win32-ia32': 0.21.5 + '@esbuild/win32-x64': 0.21.5 + + esbuild@0.27.2: + optionalDependencies: + '@esbuild/aix-ppc64': 0.27.2 + '@esbuild/android-arm': 0.27.2 + '@esbuild/android-arm64': 0.27.2 + '@esbuild/android-x64': 0.27.2 + '@esbuild/darwin-arm64': 0.27.2 + '@esbuild/darwin-x64': 0.27.2 + '@esbuild/freebsd-arm64': 0.27.2 + '@esbuild/freebsd-x64': 0.27.2 + '@esbuild/linux-arm': 0.27.2 + '@esbuild/linux-arm64': 0.27.2 + '@esbuild/linux-ia32': 0.27.2 + '@esbuild/linux-loong64': 0.27.2 + '@esbuild/linux-mips64el': 0.27.2 + '@esbuild/linux-ppc64': 0.27.2 + '@esbuild/linux-riscv64': 0.27.2 + '@esbuild/linux-s390x': 0.27.2 + '@esbuild/linux-x64': 0.27.2 + '@esbuild/netbsd-arm64': 0.27.2 + '@esbuild/netbsd-x64': 0.27.2 + '@esbuild/openbsd-arm64': 0.27.2 + '@esbuild/openbsd-x64': 0.27.2 + '@esbuild/openharmony-arm64': 0.27.2 + '@esbuild/sunos-x64': 0.27.2 + '@esbuild/win32-arm64': 0.27.2 + '@esbuild/win32-ia32': 0.27.2 + '@esbuild/win32-x64': 0.27.2 + + estree-walker@3.0.3: + dependencies: + '@types/estree': 1.0.8 + + execa@9.6.1: + dependencies: + '@sindresorhus/merge-streams': 4.0.0 + cross-spawn: 7.0.6 + figures: 6.1.0 + get-stream: 9.0.1 + human-signals: 8.0.1 + is-plain-obj: 4.1.0 + is-stream: 4.0.1 + npm-run-path: 6.0.0 + pretty-ms: 9.3.0 + signal-exit: 4.1.0 + strip-final-newline: 4.0.0 + yoctocolors: 2.1.2 + + expect-type@1.3.0: {} + + figures@6.1.0: + dependencies: + is-unicode-supported: 2.1.0 + + foreground-child@3.3.1: + dependencies: + cross-spawn: 7.0.6 + signal-exit: 4.1.0 + + fs-extra@11.3.3: + dependencies: + graceful-fs: 4.2.11 + jsonfile: 6.2.0 + universalify: 2.0.1 + + fsevents@2.3.3: + optional: true + + get-stream@9.0.1: + dependencies: + '@sec-ant/readable-stream': 0.4.1 + is-stream: 4.0.1 + + get-tsconfig@4.13.0: + dependencies: + resolve-pkg-maps: 1.0.0 + + glob@11.1.0: + dependencies: + foreground-child: 3.3.1 + jackspeak: 4.1.1 + minimatch: 10.1.1 + minipass: 7.1.2 + package-json-from-dist: 1.0.1 + path-scurry: 2.0.1 + + graceful-fs@4.2.11: {} + + human-signals@8.0.1: {} + + is-fullwidth-code-point@3.0.0: {} + + is-plain-obj@4.1.0: {} + + is-stream@4.0.1: {} + + is-unicode-supported@2.1.0: {} + + isexe@2.0.0: {} + + jackspeak@4.1.1: + dependencies: + '@isaacs/cliui': 8.0.2 + + jsonfile@6.2.0: + dependencies: + universalify: 2.0.1 + optionalDependencies: + graceful-fs: 4.2.11 + + loupe@3.2.1: {} + + lru-cache@11.2.4: {} + + magic-string@0.30.21: + dependencies: + '@jridgewell/sourcemap-codec': 1.5.5 + + minimatch@10.1.1: + dependencies: + '@isaacs/brace-expansion': 5.0.0 + + minipass@7.1.2: {} + + ms@2.1.3: {} + + nanoid@3.3.11: {} + + npm-run-path@6.0.0: + dependencies: + path-key: 4.0.0 + unicorn-magic: 0.3.0 + + package-json-from-dist@1.0.1: {} + + parse-ms@4.0.0: {} + + path-key@3.1.1: {} + + path-key@4.0.0: {} + + path-scurry@2.0.1: + dependencies: + lru-cache: 11.2.4 + minipass: 7.1.2 + + pathe@1.1.2: {} + + pathval@2.0.1: {} + + picocolors@1.1.1: {} + + postcss@8.5.6: + dependencies: + nanoid: 3.3.11 + picocolors: 1.1.1 + source-map-js: 1.2.1 + + pretty-ms@9.3.0: + dependencies: + parse-ms: 4.0.0 + + resolve-pkg-maps@1.0.0: {} + + rollup@4.55.1: + dependencies: + '@types/estree': 1.0.8 + optionalDependencies: + '@rollup/rollup-android-arm-eabi': 4.55.1 + '@rollup/rollup-android-arm64': 4.55.1 + '@rollup/rollup-darwin-arm64': 4.55.1 + '@rollup/rollup-darwin-x64': 4.55.1 + '@rollup/rollup-freebsd-arm64': 4.55.1 + '@rollup/rollup-freebsd-x64': 4.55.1 + '@rollup/rollup-linux-arm-gnueabihf': 4.55.1 + '@rollup/rollup-linux-arm-musleabihf': 4.55.1 + '@rollup/rollup-linux-arm64-gnu': 4.55.1 + '@rollup/rollup-linux-arm64-musl': 4.55.1 + '@rollup/rollup-linux-loong64-gnu': 4.55.1 + '@rollup/rollup-linux-loong64-musl': 4.55.1 + '@rollup/rollup-linux-ppc64-gnu': 4.55.1 + '@rollup/rollup-linux-ppc64-musl': 4.55.1 + '@rollup/rollup-linux-riscv64-gnu': 4.55.1 + '@rollup/rollup-linux-riscv64-musl': 4.55.1 + '@rollup/rollup-linux-s390x-gnu': 4.55.1 + '@rollup/rollup-linux-x64-gnu': 4.55.1 + '@rollup/rollup-linux-x64-musl': 4.55.1 + '@rollup/rollup-openbsd-x64': 4.55.1 + '@rollup/rollup-openharmony-arm64': 4.55.1 + '@rollup/rollup-win32-arm64-msvc': 4.55.1 + '@rollup/rollup-win32-ia32-msvc': 4.55.1 + '@rollup/rollup-win32-x64-gnu': 4.55.1 + '@rollup/rollup-win32-x64-msvc': 4.55.1 + fsevents: 2.3.3 + + semver@7.7.3: {} + + shebang-command@2.0.0: + dependencies: + shebang-regex: 3.0.0 + + shebang-regex@3.0.0: {} + + siginfo@2.0.0: {} + + signal-exit@4.1.0: {} + + simple-git@3.30.0: + dependencies: + '@kwsites/file-exists': 1.1.1 + '@kwsites/promise-deferred': 1.1.1 + debug: 4.4.3 + transitivePeerDependencies: + - supports-color + + source-map-js@1.2.1: {} + + stackback@0.0.2: {} + + std-env@3.10.0: {} + + string-width@4.2.3: + dependencies: + emoji-regex: 8.0.0 + is-fullwidth-code-point: 3.0.0 + strip-ansi: 6.0.1 + + string-width@5.1.2: + dependencies: + eastasianwidth: 0.2.0 + emoji-regex: 9.2.2 + strip-ansi: 7.1.2 + + strip-ansi@6.0.1: + dependencies: + ansi-regex: 5.0.1 + + strip-ansi@7.1.2: + dependencies: + ansi-regex: 6.2.2 + + strip-final-newline@4.0.0: {} + + tinybench@2.9.0: {} + + tinyexec@0.3.2: {} + + tinypool@1.1.1: {} + + tinyrainbow@1.2.0: {} + + tinyspy@3.0.2: {} + + tsx@4.21.0: + dependencies: + esbuild: 0.27.2 + get-tsconfig: 4.13.0 + optionalDependencies: + fsevents: 2.3.3 + + typescript@5.9.3: {} + + undici-types@6.21.0: {} + + unicorn-magic@0.3.0: {} + + universalify@2.0.1: {} + + vite-node@2.1.9(@types/node@22.19.3): + dependencies: + cac: 6.7.14 + debug: 4.4.3 + es-module-lexer: 1.7.0 + pathe: 1.1.2 + vite: 5.4.21(@types/node@22.19.3) + transitivePeerDependencies: + - '@types/node' + - less + - lightningcss + - sass + - sass-embedded + - stylus + - sugarss + - supports-color + - terser + + vite@5.4.21(@types/node@22.19.3): + dependencies: + esbuild: 0.21.5 + postcss: 8.5.6 + rollup: 4.55.1 + optionalDependencies: + '@types/node': 22.19.3 + fsevents: 2.3.3 + + vitest@2.1.9(@types/node@22.19.3): + dependencies: + '@vitest/expect': 2.1.9 + '@vitest/mocker': 2.1.9(vite@5.4.21(@types/node@22.19.3)) + '@vitest/pretty-format': 2.1.9 + '@vitest/runner': 2.1.9 + '@vitest/snapshot': 2.1.9 + '@vitest/spy': 2.1.9 + '@vitest/utils': 2.1.9 + chai: 5.3.3 + debug: 4.4.3 + expect-type: 1.3.0 + magic-string: 0.30.21 + pathe: 1.1.2 + std-env: 3.10.0 + tinybench: 2.9.0 + tinyexec: 0.3.2 + tinypool: 1.1.1 + tinyrainbow: 1.2.0 + vite: 5.4.21(@types/node@22.19.3) + vite-node: 2.1.9(@types/node@22.19.3) + why-is-node-running: 2.3.0 + optionalDependencies: + '@types/node': 22.19.3 + transitivePeerDependencies: + - less + - lightningcss + - msw + - sass + - sass-embedded + - stylus + - sugarss + - supports-color + - terser + + which@2.0.2: + dependencies: + isexe: 2.0.0 + + why-is-node-running@2.3.0: + dependencies: + siginfo: 2.0.0 + stackback: 0.0.2 + + wrap-ansi@7.0.0: + dependencies: + ansi-styles: 4.3.0 + string-width: 4.2.3 + strip-ansi: 6.0.1 + + wrap-ansi@8.1.0: + dependencies: + ansi-styles: 6.2.3 + string-width: 5.1.2 + strip-ansi: 7.1.2 + + yoctocolors@2.1.2: {} + + zod@3.25.76: {} diff --git a/scripts/sdks.json b/sdk-reference-generator/sdks.json similarity index 100% rename from scripts/sdks.json rename to sdk-reference-generator/sdks.json diff --git a/sdk-reference-generator/src/__tests__/files.test.ts b/sdk-reference-generator/src/__tests__/files.test.ts new file mode 100644 index 0000000..a9a5082 --- /dev/null +++ b/sdk-reference-generator/src/__tests__/files.test.ts @@ -0,0 +1,29 @@ +import { describe, it, expect } from 'vitest'; +import { toTitleCase } from '../lib/files.js'; + +describe('toTitleCase', () => { + it('converts snake_case to Title Case', () => { + expect(toTitleCase('sandbox_sync')).toBe('Sandbox Sync'); + expect(toTitleCase('sandbox_async')).toBe('Sandbox Async'); + expect(toTitleCase('template_async')).toBe('Template Async'); + }); + + it('capitalizes single words', () => { + expect(toTitleCase('sandbox')).toBe('Sandbox'); + expect(toTitleCase('exceptions')).toBe('Exceptions'); + }); + + it('handles already capitalized words', () => { + expect(toTitleCase('Sandbox')).toBe('Sandbox'); + expect(toTitleCase('SANDBOX')).toBe('SANDBOX'); + }); + + it('handles empty string', () => { + expect(toTitleCase('')).toBe(''); + }); + + it('handles multiple underscores', () => { + expect(toTitleCase('a_b_c')).toBe('A B C'); + }); +}); + diff --git a/sdk-reference-generator/src/__tests__/versions.test.ts b/sdk-reference-generator/src/__tests__/versions.test.ts new file mode 100644 index 0000000..912dba1 --- /dev/null +++ b/sdk-reference-generator/src/__tests__/versions.test.ts @@ -0,0 +1,74 @@ +import { describe, it, expect } from 'vitest'; +import { + isValidVersion, + versionGte, + filterByMinVersion, + diffVersions, +} from '../lib/versions.js'; + +describe('isValidVersion', () => { + it('accepts valid semver versions', () => { + expect(isValidVersion('1.0.0')).toBe(true); + expect(isValidVersion('v1.0.0')).toBe(true); + expect(isValidVersion('v2.9.0')).toBe(true); + expect(isValidVersion('10.20.30')).toBe(true); + }); + + it('rejects invalid versions', () => { + expect(isValidVersion('main')).toBe(false); + expect(isValidVersion('latest')).toBe(false); + expect(isValidVersion('1.0')).toBe(false); + expect(isValidVersion('')).toBe(false); + }); +}); + +describe('versionGte', () => { + it('compares versions correctly', () => { + expect(versionGte('2.0.0', '1.0.0')).toBe(true); + expect(versionGte('1.0.0', '1.0.0')).toBe(true); + expect(versionGte('1.0.0', '2.0.0')).toBe(false); + }); + + it('handles v prefix', () => { + expect(versionGte('v2.0.0', '1.0.0')).toBe(true); + expect(versionGte('2.0.0', 'v1.0.0')).toBe(true); + expect(versionGte('v2.0.0', 'v1.0.0')).toBe(true); + }); +}); + +describe('filterByMinVersion', () => { + it('filters versions below minimum', () => { + const versions = ['v0.9.0', 'v1.0.0', 'v1.5.0', 'v2.0.0']; + const result = filterByMinVersion(versions, '1.0.0'); + expect(result).toEqual(['v1.0.0', 'v1.5.0', 'v2.0.0']); + }); + + it('returns all versions when no minimum specified', () => { + const versions = ['v0.9.0', 'v1.0.0', 'v2.0.0']; + const result = filterByMinVersion(versions); + expect(result).toEqual(versions); + }); + + it('handles empty array', () => { + expect(filterByMinVersion([], '1.0.0')).toEqual([]); + }); +}); + +describe('diffVersions', () => { + it('finds versions in remote not in local', () => { + const remote = ['v1.0.0', 'v2.0.0', 'v3.0.0']; + const local = ['v1.0.0', 'v3.0.0']; + expect(diffVersions(remote, local)).toEqual(['v2.0.0']); + }); + + it('returns all remote when local is empty', () => { + const remote = ['v1.0.0', 'v2.0.0']; + expect(diffVersions(remote, [])).toEqual(remote); + }); + + it('returns empty when all versions exist locally', () => { + const versions = ['v1.0.0', 'v2.0.0']; + expect(diffVersions(versions, versions)).toEqual([]); + }); +}); + diff --git a/sdk-reference-generator/src/cli.ts b/sdk-reference-generator/src/cli.ts new file mode 100644 index 0000000..4e37dfa --- /dev/null +++ b/sdk-reference-generator/src/cli.ts @@ -0,0 +1,103 @@ +#!/usr/bin/env node + +import { Command } from 'commander'; +import fs from 'fs-extra'; +import path from 'path'; +import os from 'os'; +import { fileURLToPath } from 'url'; +import { initConfig, getAllSDKKeys } from './lib/config.js'; +import { generateSDK } from './generator.js'; +import { buildNavigation, mergeNavigation } from './navigation.js'; +import type { GenerationContext, GenerationResult } from './types.js'; + +const __filename = fileURLToPath(import.meta.url); +const __dirname = path.dirname(__filename); + +const SCRIPT_DIR = path.resolve(__dirname, '..'); +const DOCS_DIR = path.resolve(SCRIPT_DIR, '..'); +const CONFIGS_DIR = path.join(SCRIPT_DIR, 'configs'); + +initConfig(SCRIPT_DIR); + +const program = new Command() + .name('generate-sdk-reference') + .description('Generate SDK reference documentation') + .option('--sdk ', 'SDK to generate (or "all")', 'all') + .option('--version ', 'Version to generate (or "all", "latest")', 'all') + .option('--limit ', 'Limit number of versions to generate', parseInt) + .parse(); + +const opts = program.opts<{ + sdk: string; + version: string; + limit?: number; +}>(); + +async function main(): Promise { + const tempDir = await fs.mkdtemp(path.join(os.tmpdir(), 'sdk-gen-')); + + console.log('🚀 SDK Reference Generator'); + console.log(` SDK: ${opts.sdk}`); + console.log(` Version: ${opts.version}`); + if (opts.limit) { + console.log(` Limit: ${opts.limit} versions`); + } + console.log(` Temp dir: ${tempDir}`); + console.log(''); + + const ctx: GenerationContext = { + tempDir, + docsDir: DOCS_DIR, + configsDir: CONFIGS_DIR, + limit: opts.limit, + }; + + try { + const sdkKeys = + opts.sdk === 'all' ? await getAllSDKKeys() : [opts.sdk]; + + const results: Map = new Map(); + + for (const sdkKey of sdkKeys) { + console.log(`📦 Generating ${sdkKey}...`); + const result = await generateSDK(sdkKey, opts.version, ctx); + results.set(sdkKey, result); + } + + console.log(''); + console.log('📝 Generating navigation JSON...'); + const navigation = await buildNavigation(DOCS_DIR); + + console.log(''); + console.log('🔄 Merging navigation into docs.json...'); + await mergeNavigation(navigation, DOCS_DIR); + + console.log(''); + console.log('✅ SDK reference generation complete'); + + let totalGenerated = 0; + let totalFailed = 0; + + for (const [sdkKey, result] of results) { + totalGenerated += result.generated; + totalFailed += result.failed; + } + + if (totalGenerated > 0 || totalFailed > 0) { + console.log(''); + console.log('📊 Final Summary:'); + console.log(` Total generated: ${totalGenerated}`); + if (totalFailed > 0) { + console.log(` Total failed: ${totalFailed}`); + } + } + } finally { + await fs.remove(tempDir); + } +} + +main().catch((error) => { + console.error('❌ Fatal error:', error.message); + process.exit(1); +}); + diff --git a/sdk-reference-generator/src/generator.ts b/sdk-reference-generator/src/generator.ts new file mode 100644 index 0000000..1da71d9 --- /dev/null +++ b/sdk-reference-generator/src/generator.ts @@ -0,0 +1,200 @@ +import fs from "fs-extra"; +import path from "path"; +import type { + SDKConfig, + GenerationContext, + GenerationResult, +} from "./types.js"; +import { getSDKConfig } from "./lib/config.js"; +import { + fetchRemoteTags, + cloneAtTag, + resolveLatestVersion, +} from "./lib/git.js"; +import { + fetchLocalVersions, + filterByMinVersion, + diffVersions, + versionExists, +} from "./lib/versions.js"; +import { flattenMarkdown, copyToDocs, locateSDKDir } from "./lib/files.js"; +import { installWithCache } from "./lib/install.js"; +import { runGenerator } from "./generators/index.js"; +import { buildSDKPath } from "./lib/utils.js"; +import { CONSTANTS } from "./lib/constants.js"; + +async function generateVersion( + sdkKey: string, + config: SDKConfig, + version: string, + ctx: GenerationContext +): Promise { + const repoDir = path.join(ctx.tempDir, `${sdkKey}-${version}`); + + try { + const tagName = config.tagFormat.replace( + "{version}", + version.replace(/^v/, "") + ); + + await cloneAtTag(config.repo, tagName, repoDir); + + const sdkDir = await locateSDKDir(repoDir, config.sdkPath, config.sdkPaths); + if (!sdkDir) { + throw new Error( + `SDK path not found: ${config.sdkPath || config.sdkPaths?.join(", ")}` + ); + } + + await installWithCache(sdkDir, config.generator, ctx.tempDir); + + await runGenerator(sdkDir, config, ctx); + + const generatedDocsDir = path.join(sdkDir, CONSTANTS.SDK_REF_DIR); + if (!(await fs.pathExists(generatedDocsDir))) { + throw new Error("No sdk_ref directory generated"); + } + + await flattenMarkdown(generatedDocsDir); + + const destDir = buildSDKPath(ctx.docsDir, sdkKey, version); + const success = await copyToDocs( + generatedDocsDir, + destDir, + config.displayName, + version + ); + + if (!success) { + throw new Error("Failed to copy generated files"); + } + } finally { + await fs.remove(repoDir); + } +} + +export async function generateSDK( + sdkKey: string, + versionArg: string, + ctx: GenerationContext +): Promise { + const config = await getSDKConfig(sdkKey); + + if (!config) { + console.log(` ❌ SDK '${sdkKey}' not found in config`); + return { generated: 0, failed: 1, failedVersions: [sdkKey] }; + } + + console.log(` → ${config.displayName} version: ${versionArg}`); + + let versionsToProcess: string[] = []; + + if (versionArg === "all") { + console.log(" → Discovering all versions..."); + + let remote = await fetchRemoteTags(config.repo, config.tagPattern); + + if (remote.length === 0) { + if (config.required) { + console.log(" ❌ No tags found"); + return { generated: 0, failed: 1, failedVersions: ["no-tags"] }; + } + console.log(" ⚠️ No tags found, skipping..."); + return { generated: 0, failed: 0, failedVersions: [] }; + } + + if (config.minVersion) { + remote = filterByMinVersion(remote, config.minVersion); + console.log(` → Filtered to versions >= ${config.minVersion}`); + } + + if (ctx.limit && ctx.limit > 0) { + remote = remote.slice(0, ctx.limit); + console.log(` → Limited to last ${ctx.limit} versions`); + } + + const local = await fetchLocalVersions(sdkKey, ctx.docsDir); + + console.log(""); + console.log(" 📊 Version Discovery:"); + console.log(` Remote: ${remote.length}`); + console.log(` Local: ${local.length}`); + + const missing = diffVersions(remote, local); + + console.log(` Missing: ${missing.length}`); + console.log(""); + + if (missing.length === 0) { + console.log(" ✅ Nothing to generate"); + return { generated: 0, failed: 0, failedVersions: [] }; + } + + versionsToProcess = missing; + } else { + const resolved = await resolveLatestVersion( + config.repo, + config.tagPattern, + versionArg + ); + + if (!resolved) { + if (config.required) { + console.log(" ❌ No tags found"); + return { generated: 0, failed: 1, failedVersions: ["no-tags"] }; + } + console.log(" ⚠️ No tags found, skipping..."); + return { generated: 0, failed: 0, failedVersions: [] }; + } + + if (await versionExists(sdkKey, resolved, ctx.docsDir)) { + console.log(` ✓ ${resolved} already exists`); + return { generated: 0, failed: 0, failedVersions: [] }; + } + + versionsToProcess = [resolved]; + } + + let generated = 0; + let failed = 0; + const failedVersions: string[] = []; + + for (const version of versionsToProcess) { + console.log(""); + console.log(` 📦 Generating ${version}...`); + + try { + await generateVersion(sdkKey, config, version, ctx); + console.log(` ✅ Complete: ${version}`); + generated++; + } catch (error) { + const msg = error instanceof Error ? error.message : String(error); + console.log(` ❌ Failed: ${version} - ${msg}`); + failed++; + failedVersions.push(version); + } + } + + console.log(""); + console.log(" 📊 Summary:"); + console.log(` Generated: ${generated}`); + if (failed > 0) { + console.log(` Failed: ${failed} (${failedVersions.join(" ")})`); + } + + if (failed > 0) { + if (config.required) { + console.log(""); + console.log(" ❌ WORKFLOW ABORTED: Required SDK has failures"); + console.log(` ❌ Failed: ${failedVersions.join(" ")}`); + process.exit(1); + } else if (generated === 0) { + console.log(""); + console.log(" ❌ WORKFLOW ABORTED: All versions failed"); + console.log(` ❌ Failed: ${failedVersions.join(" ")}`); + process.exit(1); + } + } + + return { generated, failed, failedVersions }; +} diff --git a/sdk-reference-generator/src/generators/cli.ts b/sdk-reference-generator/src/generators/cli.ts new file mode 100644 index 0000000..59ad100 --- /dev/null +++ b/sdk-reference-generator/src/generators/cli.ts @@ -0,0 +1,43 @@ +import { execa } from "execa"; +import fs from "fs-extra"; +import path from "path"; +import { glob } from "glob"; +import { CONSTANTS } from "../lib/constants.js"; + +export async function generateCli(sdkDir: string): Promise { + console.log(" → Building CLI..."); + + try { + await execa("pnpm", ["run", "build"], { + cwd: sdkDir, + stdio: "pipe", + }); + } catch { + await execa("npx", ["tsup"], { + cwd: sdkDir, + stdio: "pipe", + }); + } + + console.log(" → Generating documentation..."); + + await fs.ensureDir(path.join(sdkDir, CONSTANTS.SDK_REF_DIR)); + + await execa("node", ["dist/index.js", "-cmd2md"], { + cwd: sdkDir, + env: { ...process.env, NODE_ENV: "development" }, + stdio: "pipe", + }); + + const sdkRef = path.join(sdkDir, CONSTANTS.SDK_REF_DIR); + const mdFiles = await glob(`*${CONSTANTS.MD_EXTENSION}`, { cwd: sdkRef }); + + for (const file of mdFiles) { + const srcPath = path.join(sdkRef, file); + const destPath = srcPath.replace( + CONSTANTS.MD_EXTENSION, + CONSTANTS.MDX_EXTENSION + ); + await fs.move(srcPath, destPath); + } +} diff --git a/sdk-reference-generator/src/generators/index.ts b/sdk-reference-generator/src/generators/index.ts new file mode 100644 index 0000000..4363bbb --- /dev/null +++ b/sdk-reference-generator/src/generators/index.ts @@ -0,0 +1,31 @@ +import type { SDKConfig, GenerationContext } from '../types.js'; +import { generateTypedoc } from './typedoc.js'; +import { generatePydoc } from './pydoc.js'; +import { generateCli } from './cli.js'; + +export async function runGenerator( + sdkDir: string, + config: SDKConfig, + ctx: GenerationContext +): Promise { + switch (config.generator) { + case 'typedoc': + await generateTypedoc(sdkDir, ctx.configsDir); + break; + + case 'pydoc': + await generatePydoc(sdkDir, config.packages || [], config.submodules); + break; + + case 'cli': + await generateCli(sdkDir); + break; + + default: + throw new Error(`Unknown generator: ${config.generator}`); + } +} + +export { generateTypedoc } from './typedoc.js'; +export { generatePydoc } from './pydoc.js'; +export { generateCli } from './cli.js'; diff --git a/sdk-reference-generator/src/generators/pydoc.ts b/sdk-reference-generator/src/generators/pydoc.ts new file mode 100644 index 0000000..5fa960e --- /dev/null +++ b/sdk-reference-generator/src/generators/pydoc.ts @@ -0,0 +1,72 @@ +import { execa } from 'execa'; +import fs from 'fs-extra'; +import path from 'path'; +import { CONSTANTS } from '../lib/constants.js'; + +async function processMdx(file: string): Promise { + let content = await fs.readFile(file, 'utf-8'); + + content = content.replace(/]*>.*?<\/a>/g, ''); + + content = content + .split('\n') + .filter((line) => !line.startsWith('# ')) + .join('\n'); + + content = content.replace(/^(## .+) Objects$/gm, '$1'); + + content = content.replace(/^####/gm, '###'); + + await fs.writeFile(file, content); +} + +async function processPackage( + pkg: string, + sdkDir: string +): Promise { + const rawName = pkg.split('.').pop() || pkg; + const name = rawName.replace(/^e2b_/, ''); + + console.log(` → Processing ${pkg}...`); + + const outputFile = path.join(sdkDir, CONSTANTS.SDK_REF_DIR, `${name}${CONSTANTS.MDX_EXTENSION}`); + + try { + const result = await execa('poetry', ['run', 'pydoc-markdown', '-p', pkg], { + cwd: sdkDir, + stdio: 'pipe', + }); + + await fs.writeFile(outputFile, result.stdout); + await processMdx(outputFile); + return true; + } catch { + console.log(` ⚠️ Failed to generate docs for ${pkg}`); + await fs.remove(outputFile); + return false; + } +} + +export async function generatePydoc( + sdkDir: string, + packages: string[], + submodules?: Record +): Promise { + await fs.ensureDir(path.join(sdkDir, CONSTANTS.SDK_REF_DIR)); + + console.log(' → Generating documentation for packages...'); + + for (const pkg of packages) { + await processPackage(pkg, sdkDir); + } + + if (submodules) { + for (const [parentPkg, submoduleNames] of Object.entries(submodules)) { + for (const submod of submoduleNames) { + const fullPkg = `${parentPkg}.${submod}`; + await processPackage(fullPkg, sdkDir); + } + } + } +} + diff --git a/sdk-reference-generator/src/generators/typedoc.ts b/sdk-reference-generator/src/generators/typedoc.ts new file mode 100644 index 0000000..5a24050 --- /dev/null +++ b/sdk-reference-generator/src/generators/typedoc.ts @@ -0,0 +1,51 @@ +import { execa } from 'execa'; +import fs from 'fs-extra'; +import path from 'path'; + +export async function generateTypedoc( + sdkDir: string, + configsDir: string +): Promise { + const hasRepoConfig = await fs.pathExists(path.join(sdkDir, 'typedoc.json')); + + if (hasRepoConfig) { + console.log(' → Running TypeDoc with repo config...'); + await execa( + 'npx', + [ + 'typedoc', + '--plugin', + 'typedoc-plugin-markdown', + '--plugin', + path.join(configsDir, 'typedoc-theme.cjs'), + ], + { + cwd: sdkDir, + stdio: 'pipe', + } + ); + } else { + console.log(' → Running TypeDoc with default config...'); + await fs.copy( + path.join(configsDir, 'typedoc.json'), + path.join(sdkDir, 'typedoc.docs.json') + ); + + await execa( + 'npx', + [ + 'typedoc', + '--options', + './typedoc.docs.json', + '--plugin', + 'typedoc-plugin-markdown', + '--plugin', + path.join(configsDir, 'typedoc-theme.cjs'), + ], + { + cwd: sdkDir, + stdio: 'pipe', + } + ); + } +} diff --git a/sdk-reference-generator/src/lib/cache.ts b/sdk-reference-generator/src/lib/cache.ts new file mode 100644 index 0000000..3e91785 --- /dev/null +++ b/sdk-reference-generator/src/lib/cache.ts @@ -0,0 +1,64 @@ +import { createHash } from 'crypto'; +import fs from 'fs-extra'; +import path from 'path'; +import type { GeneratorType } from '../types.js'; + +const LOCKFILES: Record = { + typedoc: ['pnpm-lock.yaml', 'package-lock.json'], + cli: ['pnpm-lock.yaml', 'package-lock.json'], + pydoc: ['poetry.lock'], +}; + +async function findLockfileUp( + dir: string, + filename: string +): Promise { + let current = dir; + + while (current !== '/' && current !== '.') { + const lockPath = path.join(current, filename); + if (await fs.pathExists(lockPath)) { + return lockPath; + } + current = path.dirname(current); + } + + return null; +} + +export async function hashLockfile( + sdkDir: string, + generator: GeneratorType +): Promise { + const lockfiles = LOCKFILES[generator]; + + for (const filename of lockfiles) { + const lockPath = await findLockfileUp(sdkDir, filename); + if (lockPath) { + const content = await fs.readFile(lockPath, 'utf-8'); + return createHash('md5').update(content).digest('hex'); + } + } + + return null; +} + +export async function isCached( + hash: string, + generator: GeneratorType, + tempDir: string +): Promise { + const marker = path.join(tempDir, '.deps-cache', `${generator}-${hash}`, '.installed'); + return fs.pathExists(marker); +} + +export async function markCached( + hash: string, + generator: GeneratorType, + tempDir: string +): Promise { + const marker = path.join(tempDir, '.deps-cache', `${generator}-${hash}`, '.installed'); + await fs.ensureDir(path.dirname(marker)); + await fs.writeFile(marker, ''); +} + diff --git a/sdk-reference-generator/src/lib/config.ts b/sdk-reference-generator/src/lib/config.ts new file mode 100644 index 0000000..f1ec4fd --- /dev/null +++ b/sdk-reference-generator/src/lib/config.ts @@ -0,0 +1,30 @@ +import fs from 'fs-extra'; +import path from 'path'; +import { ConfigFileSchema, type SDKConfig, type ConfigFile } from '../types.js'; + +let cachedConfig: ConfigFile | null = null; +let configPath: string = ''; + +export function initConfig(scriptDir: string): void { + configPath = path.join(scriptDir, 'sdks.json'); + cachedConfig = null; +} + +export async function loadConfig(): Promise { + if (cachedConfig) return cachedConfig; + + const raw = await fs.readJSON(configPath); + cachedConfig = ConfigFileSchema.parse(raw); + return cachedConfig; +} + +export async function getSDKConfig(sdkKey: string): Promise { + const config = await loadConfig(); + return config.sdks[sdkKey] || null; +} + +export async function getAllSDKKeys(): Promise { + const config = await loadConfig(); + return Object.keys(config.sdks); +} + diff --git a/sdk-reference-generator/src/lib/constants.ts b/sdk-reference-generator/src/lib/constants.ts new file mode 100644 index 0000000..22315ad --- /dev/null +++ b/sdk-reference-generator/src/lib/constants.ts @@ -0,0 +1,7 @@ +export const CONSTANTS = { + SDK_REF_DIR: "sdk_ref", + DOCS_SDK_REF_PATH: "docs/sdk-reference", + MDX_EXTENSION: ".mdx", + MD_EXTENSION: ".md", + SDK_REFERENCE_ANCHOR: "SDK Reference", +} as const; diff --git a/sdk-reference-generator/src/lib/files.ts b/sdk-reference-generator/src/lib/files.ts new file mode 100644 index 0000000..4d7c028 --- /dev/null +++ b/sdk-reference-generator/src/lib/files.ts @@ -0,0 +1,175 @@ +import fs from 'fs-extra'; +import path from 'path'; +import { glob } from 'glob'; +import { createFrontmatter } from './utils.js'; +import { CONSTANTS } from './constants.js'; + +export function toTitleCase(str: string): string { + if (!str) return ''; + + return str + .split('_') + .map((word) => word.charAt(0).toUpperCase() + word.slice(1)) + .join(' '); +} + +export async function addFrontmatter( + file: string, + title: string +): Promise { + const content = await fs.readFile(file, 'utf-8'); + + if (content.startsWith('---')) { + return; + } + + await fs.writeFile(file, createFrontmatter(title) + content); +} + +export async function flattenMarkdown(refDir: string): Promise { + await fs.remove(path.join(refDir, 'README.md')); + await fs.remove(path.join(refDir, 'index.md')); + + const nestedFiles = await glob('**/*.md', { + cwd: refDir, + ignore: '*.md', + }); + + for (const file of nestedFiles) { + const filename = path.basename(file); + const dirName = path.basename(path.dirname(file)); + + let targetName: string; + if (filename === 'page.md' || filename === 'index.md') { + targetName = `${dirName}.md`; + } else { + targetName = filename; + } + + const sourcePath = path.join(refDir, file); + const targetPath = path.join(refDir, targetName); + + await fs.move(sourcePath, targetPath, { overwrite: true }); + } + + const dirs = await glob('**/', { cwd: refDir }); + for (const dir of dirs.reverse()) { + const dirPath = path.join(refDir, dir); + try { + const files = await fs.readdir(dirPath); + if (files.length === 0) { + await fs.remove(dirPath); + } + } catch { + // ignore + } + } + + const mdFiles = await glob('*.md', { cwd: refDir }); + + for (const file of mdFiles) { + const fullPath = path.join(refDir, file); + const title = toTitleCase(path.basename(file, CONSTANTS.MD_EXTENSION)); + const content = await fs.readFile(fullPath, 'utf-8'); + + const mdxPath = fullPath.replace(CONSTANTS.MD_EXTENSION, CONSTANTS.MDX_EXTENSION); + await fs.writeFile(mdxPath, createFrontmatter(title) + content); + await fs.remove(fullPath); + } + + const mdxFiles = await glob(`*${CONSTANTS.MDX_EXTENSION}`, { cwd: refDir }); + + for (const file of mdxFiles) { + const fullPath = path.join(refDir, file); + const content = await fs.readFile(fullPath, 'utf-8'); + + if (!content.startsWith('---')) { + const title = toTitleCase(path.basename(file, CONSTANTS.MDX_EXTENSION)); + await addFrontmatter(fullPath, title); + } + } + + await fs.remove(path.join(refDir, `index${CONSTANTS.MDX_EXTENSION}`)); +} + +export async function validateMdxFiles(srcDir: string): Promise { + await fs.remove(path.join(srcDir, `*${CONSTANTS.MDX_EXTENSION}`)); + + const files = await glob(`*${CONSTANTS.MDX_EXTENSION}`, { cwd: srcDir }); + + let validCount = 0; + for (const file of files) { + if (file === `*${CONSTANTS.MDX_EXTENSION}`) continue; + + const fullPath = path.join(srcDir, file); + const stat = await fs.stat(fullPath); + + if (stat.size === 0) continue; + + validCount++; + } + + return validCount; +} + +export async function copyToDocs( + srcDir: string, + destDir: string, + sdkName: string, + version: string +): Promise { + const count = await validateMdxFiles(srcDir); + + if (count === 0) { + console.log(' ❌ No MDX files generated - doc generator failed'); + return false; + } + + await fs.ensureDir(destDir); + + console.log(` → Copying ${count} files to ${destDir}`); + + const files = await glob(`*${CONSTANTS.MDX_EXTENSION}`, { cwd: srcDir }); + + for (const file of files) { + if (file === `*${CONSTANTS.MDX_EXTENSION}`) continue; + + const srcPath = path.join(srcDir, file); + const destPath = path.join(destDir, file); + const stat = await fs.stat(srcPath); + + if (stat.size > 0) { + await fs.copy(srcPath, destPath); + } + } + + console.log(` ✅ ${sdkName} ${version} complete`); + return true; +} + +export async function locateSDKDir( + repoDir: string, + sdkPath?: string, + sdkPaths?: string[] +): Promise { + if (sdkPath) { + const dir = path.join(repoDir, sdkPath); + if (await fs.pathExists(dir)) { + return dir; + } + return null; + } + + if (sdkPaths) { + for (const p of sdkPaths) { + const dir = path.join(repoDir, p); + if (await fs.pathExists(dir)) { + return dir; + } + } + return null; + } + + return repoDir; +} + diff --git a/sdk-reference-generator/src/lib/git.ts b/sdk-reference-generator/src/lib/git.ts new file mode 100644 index 0000000..31b8d8f --- /dev/null +++ b/sdk-reference-generator/src/lib/git.ts @@ -0,0 +1,51 @@ +import { simpleGit, SimpleGit } from 'simple-git'; +import { sortVersionsDescending } from './utils.js'; + +const git: SimpleGit = simpleGit(); + +export async function fetchRemoteTags( + repo: string, + tagPattern: string +): Promise { + const output = await git.listRemote(['--tags', '--refs', repo]); + + const versions = output + .split('\n') + .filter((line: string) => line.includes(`refs/tags/${tagPattern}`)) + .map((line: string) => { + const match = line.match(/refs\/tags\/(.+)$/); + if (!match) return null; + const tag = match[1]; + return 'v' + tag.replace(tagPattern, ''); + }) + .filter((v: string | null): v is string => v !== null && v !== 'v'); + + return sortVersionsDescending(versions); +} + +export async function cloneAtTag( + repo: string, + tag: string, + targetDir: string +): Promise { + try { + await git.clone(repo, targetDir, ['--depth', '1', '--branch', tag]); + } catch { + console.log(` ⚠️ Tag ${tag} not found, trying default branch...`); + await git.clone(repo, targetDir, ['--depth', '1']); + } +} + +export async function resolveLatestVersion( + repo: string, + tagPattern: string, + version: string +): Promise { + if (version !== 'latest') { + return version; + } + + const versions = await fetchRemoteTags(repo, tagPattern); + return versions[0] || null; +} + diff --git a/sdk-reference-generator/src/lib/install.ts b/sdk-reference-generator/src/lib/install.ts new file mode 100644 index 0000000..233742b --- /dev/null +++ b/sdk-reference-generator/src/lib/install.ts @@ -0,0 +1,93 @@ +import { execa } from 'execa'; +import type { GeneratorType } from '../types.js'; +import { hashLockfile, isCached, markCached } from './cache.js'; + +async function installDependencies( + sdkDir: string, + generator: GeneratorType +): Promise { + console.log(' → Installing dependencies...'); + + switch (generator) { + case 'typedoc': { + try { + await execa( + 'pnpm', + ['install', '--ignore-scripts', '--prefer-offline'], + { + cwd: sdkDir, + stdio: 'pipe', + } + ); + } catch { + console.log(' ⚠️ pnpm failed, trying npm...'); + await execa( + 'npm', + ['install', '--legacy-peer-deps', '--prefer-offline'], + { + cwd: sdkDir, + stdio: 'pipe', + } + ); + } + break; + } + + case 'cli': { + try { + await execa('pnpm', ['install', '--prefer-offline'], { + cwd: sdkDir, + stdio: 'pipe', + }); + } catch { + await execa('npm', ['install', '--prefer-offline'], { + cwd: sdkDir, + stdio: 'pipe', + }); + } + break; + } + + case 'pydoc': { + try { + await execa('poetry', ['install', '--quiet'], { + cwd: sdkDir, + stdio: 'pipe', + }); + } catch { + await execa( + 'pip', + ['install', '--break-system-packages', 'pydoc-markdown'], + { + cwd: sdkDir, + stdio: 'pipe', + } + ); + } + break; + } + } +} + +export async function installWithCache( + sdkDir: string, + generator: GeneratorType, + tempDir: string +): Promise { + if (generator === 'pydoc') { + const hash = await hashLockfile(sdkDir, generator); + + if (hash && (await isCached(hash, generator, tempDir))) { + console.log(' → Poetry dependencies cached (lockfile unchanged)'); + return; + } + + await installDependencies(sdkDir, generator); + + if (hash) { + await markCached(hash, generator, tempDir); + } + } else { + await installDependencies(sdkDir, generator); + } +} diff --git a/sdk-reference-generator/src/lib/utils.ts b/sdk-reference-generator/src/lib/utils.ts new file mode 100644 index 0000000..4b13ccb --- /dev/null +++ b/sdk-reference-generator/src/lib/utils.ts @@ -0,0 +1,34 @@ +import semver from "semver"; +import path from "path"; +import { CONSTANTS } from "./constants.js"; + +export function stripV(version: string): string { + return version.replace(/^v/, ""); +} + +export function sortVersionsDescending(versions: string[]): string[] { + return versions.sort((a, b) => { + try { + return semver.rcompare(stripV(a), stripV(b)); + } catch { + return b.localeCompare(a); + } + }); +} + +export function createFrontmatter(title: string): string { + return `--- +sidebarTitle: "${title}" +mode: "center" +--- + +`; +} + +export function buildSDKPath( + docsDir: string, + sdkKey: string, + version: string +): string { + return path.join(docsDir, CONSTANTS.DOCS_SDK_REF_PATH, sdkKey, version); +} diff --git a/sdk-reference-generator/src/lib/versions.ts b/sdk-reference-generator/src/lib/versions.ts new file mode 100644 index 0000000..6aa12e5 --- /dev/null +++ b/sdk-reference-generator/src/lib/versions.ts @@ -0,0 +1,75 @@ +import fs from 'fs-extra'; +import path from 'path'; +import semver from 'semver'; +import { stripV, sortVersionsDescending } from './utils.js'; +import { CONSTANTS } from './constants.js'; + +export function isValidVersion(version: string): boolean { + return /^v?\d+\.\d+\.\d+/.test(version); +} + +export function versionGte(v1: string, v2: string): boolean { + try { + return semver.gte(stripV(v1), stripV(v2)); + } catch { + return stripV(v1) >= stripV(v2); + } +} + +export function filterByMinVersion( + versions: string[], + minVersion?: string +): string[] { + if (!minVersion) return versions; + return versions.filter((v) => versionGte(v, minVersion)); +} + +export async function fetchLocalVersions( + sdkKey: string, + docsDir: string +): Promise { + const sdkDir = path.join(docsDir, CONSTANTS.DOCS_SDK_REF_PATH, sdkKey); + + if (!(await fs.pathExists(sdkDir))) { + return []; + } + + const entries = await fs.readdir(sdkDir, { withFileTypes: true }); + const versions: string[] = []; + + for (const entry of entries) { + if (!entry.isDirectory()) continue; + if (!isValidVersion(entry.name)) continue; + + const versionDir = path.join(sdkDir, entry.name); + const files = await fs.readdir(versionDir); + const hasMdx = files.some((f) => f.endsWith(CONSTANTS.MDX_EXTENSION)); + + if (hasMdx) { + versions.push(entry.name); + } + } + + return sortVersionsDescending(versions); +} + +export function diffVersions(remote: string[], local: string[]): string[] { + const localSet = new Set(local); + return remote.filter((v) => !localSet.has(v)); +} + +export async function versionExists( + sdkKey: string, + version: string, + docsDir: string +): Promise { + const versionDir = path.join(docsDir, CONSTANTS.DOCS_SDK_REF_PATH, sdkKey, version); + + if (!(await fs.pathExists(versionDir))) { + return false; + } + + const files = await fs.readdir(versionDir); + return files.some((f) => f.endsWith(CONSTANTS.MDX_EXTENSION)); +} + diff --git a/sdk-reference-generator/src/navigation.ts b/sdk-reference-generator/src/navigation.ts new file mode 100644 index 0000000..89656ac --- /dev/null +++ b/sdk-reference-generator/src/navigation.ts @@ -0,0 +1,166 @@ +import fs from "fs-extra"; +import path from "path"; +import { loadConfig } from "./lib/config.js"; +import { sortVersionsDescending } from "./lib/utils.js"; +import { CONSTANTS } from "./lib/constants.js"; +import type { + NavigationDropdown, + NavigationDropdownWithOrder, +} from "./types.js"; + +async function getVersions(sdkDir: string): Promise { + try { + const entries = await fs.readdir(sdkDir, { withFileTypes: true }); + + const versions = entries + .filter((e) => { + if (!e.isDirectory()) return false; + return /^v?\d+\.\d+\.\d+/.test(e.name); + }) + .map((e) => e.name); + + return sortVersionsDescending(versions); + } catch { + return []; + } +} + +async function getModules(versionDir: string): Promise { + try { + const entries = await fs.readdir(versionDir, { withFileTypes: true }); + return entries + .filter((e) => e.isFile() && e.name.endsWith(CONSTANTS.MDX_EXTENSION)) + .map((e) => e.name.replace(CONSTANTS.MDX_EXTENSION, "")) + .sort(); + } catch { + return []; + } +} + +export async function buildNavigation( + docsDir: string +): Promise { + const config = await loadConfig(); + const sdkRefDir = path.join(docsDir, CONSTANTS.DOCS_SDK_REF_PATH); + + if (!(await fs.pathExists(sdkRefDir))) { + console.log("⚠️ SDK reference directory not found:", sdkRefDir); + return []; + } + + const navigation: NavigationDropdownWithOrder[] = []; + + for (const [sdkKey, sdkConfig] of Object.entries(config.sdks)) { + const sdkDir = path.join(sdkRefDir, sdkKey); + + if (!(await fs.pathExists(sdkDir))) { + console.log(` Skipping ${sdkKey} (not found)`); + continue; + } + + const versions = await getVersions(sdkDir); + if (versions.length === 0) { + console.log(` Skipping ${sdkKey} (no versions)`); + continue; + } + + console.log(` Found ${sdkKey}: ${versions.length} versions`); + + const dropdown: NavigationDropdownWithOrder = { + dropdown: sdkConfig.displayName, + icon: sdkConfig.icon, + versions: await Promise.all( + versions.map(async (version, index) => { + const versionDir = path.join(sdkDir, version); + const modules = await getModules(versionDir); + const displayVersion = version.startsWith("v") + ? version + : `v${version}`; + + return { + version: displayVersion, + default: index === 0, + pages: modules.map( + (module) => + `${CONSTANTS.DOCS_SDK_REF_PATH}/${sdkKey}/${version}/${module}` + ), + }; + }) + ), + _order: sdkConfig.order, + }; + + navigation.push(dropdown); + } + + return navigation + .sort((a, b) => a._order - b._order) + .map(({ _order, ...rest }) => rest); +} + +export async function mergeNavigation( + navigation: NavigationDropdown[], + docsDir: string +): Promise { + const docsJsonPath = path.join(docsDir, "docs.json"); + + if (!(await fs.pathExists(docsJsonPath))) { + console.log("❌ docs.json not found"); + process.exit(1); + } + + const docsJson = await fs.readJSON(docsJsonPath); + + const anchors = docsJson.navigation?.anchors; + if (!anchors) { + console.log("❌ No anchors found in docs.json"); + process.exit(1); + } + + const sdkRefIndex = anchors.findIndex( + (a: { anchor?: string }) => a.anchor === CONSTANTS.SDK_REFERENCE_ANCHOR + ); + + if (sdkRefIndex === -1) { + console.log( + `❌ ${CONSTANTS.SDK_REFERENCE_ANCHOR} anchor not found in docs.json` + ); + process.exit(1); + } + + const validDropdowns = navigation.filter( + (d) => d.versions && d.versions.length > 0 + ); + + if (validDropdowns.length === 0) { + console.log("⚠️ No SDK versions found, keeping existing docs.json"); + return; + } + + anchors[sdkRefIndex] = { + anchor: CONSTANTS.SDK_REFERENCE_ANCHOR, + icon: "brackets-curly", + dropdowns: validDropdowns, + }; + + await fs.writeJSON(docsJsonPath, docsJson, { spaces: 2 }); + const content = await fs.readFile(docsJsonPath, "utf-8"); + if (!content.endsWith("\n")) { + await fs.appendFile(docsJsonPath, "\n"); + } + + console.log( + `✅ Updated docs.json with ${validDropdowns.length} SDK dropdowns` + ); + + for (const dropdown of validDropdowns) { + const totalVersions = dropdown.versions.length; + const totalPages = dropdown.versions.reduce( + (sum, v) => sum + (v.pages?.length || 0), + 0 + ); + console.log( + ` - ${dropdown.dropdown}: ${totalVersions} versions, ${totalPages} pages` + ); + } +} diff --git a/sdk-reference-generator/src/types.ts b/sdk-reference-generator/src/types.ts new file mode 100644 index 0000000..88ee8f2 --- /dev/null +++ b/sdk-reference-generator/src/types.ts @@ -0,0 +1,56 @@ +import { z } from 'zod'; + +export const GeneratorType = z.enum(['typedoc', 'pydoc', 'cli']); +export type GeneratorType = z.infer; + +export const SDKConfigSchema = z.object({ + displayName: z.string(), + icon: z.string(), + order: z.number(), + repo: z.string().url(), + tagPattern: z.string(), + tagFormat: z.string(), + generator: GeneratorType, + required: z.boolean(), + minVersion: z.string().optional(), + sdkPath: z.string().optional(), + sdkPaths: z.array(z.string()).optional(), + packages: z.array(z.string()).optional(), + submodules: z.record(z.string(), z.array(z.string())).optional(), +}); +export type SDKConfig = z.infer; + +export const ConfigFileSchema = z.object({ + sdks: z.record(z.string(), SDKConfigSchema), +}); +export type ConfigFile = z.infer; + +export interface GenerationContext { + tempDir: string; + docsDir: string; + configsDir: string; + limit?: number; +} + +export interface GenerationResult { + generated: number; + failed: number; + failedVersions: string[]; +} + +export interface NavigationVersion { + version: string; + default: boolean; + pages: string[]; +} + +export interface NavigationDropdown { + dropdown: string; + icon: string; + versions: NavigationVersion[]; +} + +export interface NavigationDropdownWithOrder extends NavigationDropdown { + _order: number; +} + diff --git a/sdk-reference-generator/tsconfig.json b/sdk-reference-generator/tsconfig.json new file mode 100644 index 0000000..3ac3cc8 --- /dev/null +++ b/sdk-reference-generator/tsconfig.json @@ -0,0 +1,18 @@ +{ + "compilerOptions": { + "target": "ES2022", + "module": "NodeNext", + "moduleResolution": "NodeNext", + "esModuleInterop": true, + "strict": true, + "skipLibCheck": true, + "outDir": "dist", + "rootDir": "src", + "declaration": true, + "resolveJsonModule": true, + "allowSyntheticDefaultImports": true + }, + "include": ["src/**/*"], + "exclude": ["node_modules", "dist"] +} + diff --git a/sdk-reference-generator/vitest.config.ts b/sdk-reference-generator/vitest.config.ts new file mode 100644 index 0000000..9fe1d91 --- /dev/null +++ b/sdk-reference-generator/vitest.config.ts @@ -0,0 +1,9 @@ +import { defineConfig } from 'vitest/config'; + +export default defineConfig({ + test: { + globals: true, + environment: 'node', + }, +}); + From c0ecf0bf6c8e1cc32e07a9ccc58ff043ded97e87 Mon Sep 17 00:00:00 2001 From: ben-fornefeld Date: Thu, 8 Jan 2026 10:56:50 +0100 Subject: [PATCH 10/39] cleanup: - Added verification functions to ensure generated documentation meets quality standards, including checks for empty files and missing frontmatter. - Implemented a logging utility for better output management during the generation process. - Created a `.mintignore` file to exclude specific directories from version control. - Enhanced CLI commands for improved user experience and added options for forced regeneration of existing versions. --- .mintignore | 3 + sdk-reference-generator/README.md | 168 ++++++++++++++++++ .../src/__tests__/verify.test.ts | 119 +++++++++++++ sdk-reference-generator/src/cli.ts | 127 ++++++++----- sdk-reference-generator/src/generator.ts | 121 ++++++++----- sdk-reference-generator/src/generators/cli.ts | 26 +-- .../src/generators/index.ts | 36 ++-- .../src/generators/pydoc.ts | 155 ++++++++++++---- .../src/generators/typedoc.ts | 29 ++- sdk-reference-generator/src/lib/files.ts | 122 ++++++------- sdk-reference-generator/src/lib/git.ts | 3 +- sdk-reference-generator/src/lib/install.ts | 67 ++++--- sdk-reference-generator/src/lib/log.ts | 59 ++++++ sdk-reference-generator/src/lib/verify.ts | 127 +++++++++++++ sdk-reference-generator/src/navigation.ts | 47 +++-- sdk-reference-generator/src/types.ts | 9 +- 16 files changed, 932 insertions(+), 286 deletions(-) create mode 100644 .mintignore create mode 100644 sdk-reference-generator/README.md create mode 100644 sdk-reference-generator/src/__tests__/verify.test.ts create mode 100644 sdk-reference-generator/src/lib/log.ts create mode 100644 sdk-reference-generator/src/lib/verify.ts diff --git a/.mintignore b/.mintignore new file mode 100644 index 0000000..8881a60 --- /dev/null +++ b/.mintignore @@ -0,0 +1,3 @@ +sdk-reference-generator/ + +scripts/ \ No newline at end of file diff --git a/sdk-reference-generator/README.md b/sdk-reference-generator/README.md new file mode 100644 index 0000000..1d963e0 --- /dev/null +++ b/sdk-reference-generator/README.md @@ -0,0 +1,168 @@ +# SDK Reference Documentation Generator + +TypeScript-based documentation generator for E2B SDKs with automatic versioning, caching, and CI/CD integration. + +## Features + +- **Multi-SDK Support**: JS, Python, CLI, Code Interpreter, Desktop SDKs +- **Automatic Version Discovery**: Detects and generates missing versions +- **Intelligent Caching**: Skips reinstalling dependencies when lockfile unchanged +- **Idempotent**: Safe to run repeatedly, only generates what's missing +- **Full Visibility**: Complete logging of all subcommands for debugging +- **Verification**: Validates generated docs before finalizing +- **CI/CD Ready**: GitHub Actions integration with safety checks + +## Usage + +```bash +# generate all SDKs, all versions +pnpm run generate + +# generate specific SDK, latest version +pnpm run generate --sdk js-sdk --version latest + +# generate specific version +pnpm run generate --sdk python-sdk --version v2.8.0 + +# limit to last N versions (useful for testing) +pnpm run generate --sdk all --version all --limit 5 + +# force regenerate existing versions (useful after config changes) +pnpm run generate --sdk js-sdk --version all --force + +# combine flags +pnpm run generate --sdk all --version all --limit 3 --force +``` + +## Architecture + +``` +src/ +├── cli.ts # Entry point with CLI argument parsing +├── generator.ts # Core SDK generation orchestration +├── navigation.ts # Mintlify navigation builder +├── types.ts # TypeScript interfaces and Zod schemas +├── lib/ +│ ├── constants.ts # Centralized magic strings +│ ├── utils.ts # Pure utility functions +│ ├── config.ts # SDK configuration loading +│ ├── git.ts # Git operations (clone, tags) +│ ├── versions.ts # Version comparison and filtering +│ ├── files.ts # Markdown processing +│ ├── cache.ts # Dependency caching +│ ├── install.ts # Package manager abstraction +│ └── verify.ts # Post-generation validation +└── generators/ + ├── typedoc.ts # JavaScript/TypeScript docs + ├── pydoc.ts # Python docs + └── cli.ts # CLI command docs +``` + +## Configuration + +SDKs are configured in `sdks.json`: + +```json +{ + "sdks": { + "js-sdk": { + "displayName": "SDK (JavaScript)", + "icon": "square-js", + "order": 1, + "repo": "https://github.com/e2b-dev/e2b.git", + "tagPattern": "e2b@", + "tagFormat": "e2b@{version}", + "generator": "typedoc", + "required": true, + "minVersion": "1.0.0", + "sdkPath": "packages/js-sdk" + } + } +} +``` + +## Error Handling + +### Strict Safety Model + +1. **Required SDKs**: Any failure aborts workflow +2. **Optional SDKs**: All versions failing aborts workflow +3. **Partial failures**: Non-required SDK with some successes continues +4. **Verification**: Post-generation validation ensures quality + +### Progressive Dependency Resolution + +For maximum compatibility across SDK versions: + +1. **Try strict install** - Uses exact engine requirements +2. **Try relaxed install** - Ignores engine constraints (`--engine-strict=false`) +3. **Try npm fallback** - Uses npm with `--force` and `--legacy-peer-deps` + +Each strategy visible in logs for debugging. If all strategies fail, workflow aborts. + +### What Gets Logged + +- ✅ Package manager output (pnpm/npm/poetry/pip) +- ✅ Build tool output (TypeDoc, pydoc-markdown, CLI builds) +- ✅ File operations (copying, flattening) +- ✅ Validation results (empty files, missing frontmatter) +- ✅ Final statistics (files, SDKs, versions) + +## Verification Checks + +Before finalizing, the generator verifies: + +1. **Generated Files**: No empty MDX files +2. **Frontmatter**: All files have proper frontmatter +3. **Structure**: Valid directory structure +4. **docs.json**: Valid JSON with correct navigation structure + +## Testing + +```bash +# run unit tests +pnpm test + +# run with watch mode +pnpm test:watch + +# type check +npx tsc --noEmit +``` + +Tests cover: +- Version comparison and filtering (10 tests) +- File operations and title casing (5 tests) +- Verification logic (7 tests) + +## CI/CD Integration + +The generator runs in GitHub Actions on: +- Manual workflow dispatch +- Automatic repository dispatch from SDK repos on release + +Safety features: +- Validates all generated files before committing +- Only commits if changes detected +- Skips CI on doc updates (`[skip ci]` in commit message) +- Full logging visible in workflow runs + +## Performance + +- **Dependency Caching**: Poetry installs cached by lockfile hash +- **Version Deduplication**: Batch comparison skips already-generated versions +- **Parallel Generation**: Could process multiple versions concurrently (future enhancement) + +## Development + +```bash +# install dependencies +pnpm install + +# run generator locally +pnpm run generate --sdk js-sdk --limit 1 + +# run tests +pnpm test +``` + diff --git a/sdk-reference-generator/src/__tests__/verify.test.ts b/sdk-reference-generator/src/__tests__/verify.test.ts new file mode 100644 index 0000000..1b72a52 --- /dev/null +++ b/sdk-reference-generator/src/__tests__/verify.test.ts @@ -0,0 +1,119 @@ +import { describe, it, expect, beforeEach, afterEach } from 'vitest'; +import fs from 'fs-extra'; +import path from 'path'; +import os from 'os'; +import { verifyGeneratedDocs, verifyDocsJson } from '../lib/verify.js'; +import { CONSTANTS } from '../lib/constants.js'; + +describe('verifyGeneratedDocs', () => { + let tempDir: string; + + beforeEach(async () => { + tempDir = await fs.mkdtemp(path.join(os.tmpdir(), 'verify-test-')); + }); + + afterEach(async () => { + await fs.remove(tempDir); + }); + + it('validates correct SDK structure', async () => { + const sdkPath = path.join(tempDir, CONSTANTS.DOCS_SDK_REF_PATH, 'test-sdk', 'v1.0.0'); + await fs.ensureDir(sdkPath); + await fs.writeFile( + path.join(sdkPath, 'test.mdx'), + '---\nsidebarTitle: "Test"\n---\n\nContent' + ); + + const result = await verifyGeneratedDocs(tempDir); + + expect(result.valid).toBe(true); + expect(result.errors).toHaveLength(0); + expect(result.stats.totalMdxFiles).toBe(1); + expect(result.stats.totalSDKs).toBe(1); + expect(result.stats.totalVersions).toBe(1); + }); + + it('detects empty MDX files', async () => { + const sdkPath = path.join(tempDir, CONSTANTS.DOCS_SDK_REF_PATH, 'test-sdk', 'v1.0.0'); + await fs.ensureDir(sdkPath); + await fs.writeFile(path.join(sdkPath, 'empty.mdx'), ''); + + const result = await verifyGeneratedDocs(tempDir); + + expect(result.valid).toBe(false); + expect(result.errors.length).toBeGreaterThan(0); + expect(result.errors[0]).toContain('Empty file'); + }); + + it('detects missing frontmatter', async () => { + const sdkPath = path.join(tempDir, CONSTANTS.DOCS_SDK_REF_PATH, 'test-sdk', 'v1.0.0'); + await fs.ensureDir(sdkPath); + await fs.writeFile(path.join(sdkPath, 'no-frontmatter.mdx'), 'Just content'); + + const result = await verifyGeneratedDocs(tempDir); + + expect(result.valid).toBe(false); + expect(result.errors.length).toBeGreaterThan(0); + expect(result.errors[0]).toContain('Missing frontmatter'); + }); + + it('warns about versions with no MDX files', async () => { + const sdkPath = path.join(tempDir, CONSTANTS.DOCS_SDK_REF_PATH, 'test-sdk', 'v1.0.0'); + await fs.ensureDir(sdkPath); + + const result = await verifyGeneratedDocs(tempDir); + + expect(result.warnings.length).toBeGreaterThan(0); + expect(result.warnings[0]).toContain('has no MDX files'); + }); +}); + +describe('verifyDocsJson', () => { + let tempDir: string; + + beforeEach(async () => { + tempDir = await fs.mkdtemp(path.join(os.tmpdir(), 'verify-test-')); + }); + + afterEach(async () => { + await fs.remove(tempDir); + }); + + it('validates correct docs.json structure', async () => { + const docsJson = { + navigation: { + anchors: [ + { + anchor: CONSTANTS.SDK_REFERENCE_ANCHOR, + icon: 'brackets-curly', + dropdowns: [], + }, + ], + }, + }; + + await fs.writeJSON(path.join(tempDir, 'docs.json'), docsJson); + + const result = await verifyDocsJson(tempDir); + expect(result).toBe(true); + }); + + it('fails when docs.json missing', async () => { + const result = await verifyDocsJson(tempDir); + expect(result).toBe(false); + }); + + it('fails when SDK Reference anchor missing', async () => { + const docsJson = { + navigation: { + anchors: [{ anchor: 'Other', dropdowns: [] }], + }, + }; + + await fs.writeJSON(path.join(tempDir, 'docs.json'), docsJson); + + const result = await verifyDocsJson(tempDir); + expect(result).toBe(false); + }); +}); + diff --git a/sdk-reference-generator/src/cli.ts b/sdk-reference-generator/src/cli.ts index 4e37dfa..8193e8a 100644 --- a/sdk-reference-generator/src/cli.ts +++ b/sdk-reference-generator/src/cli.ts @@ -1,79 +1,114 @@ #!/usr/bin/env node -import { Command } from 'commander'; -import fs from 'fs-extra'; -import path from 'path'; -import os from 'os'; -import { fileURLToPath } from 'url'; -import { initConfig, getAllSDKKeys } from './lib/config.js'; -import { generateSDK } from './generator.js'; -import { buildNavigation, mergeNavigation } from './navigation.js'; -import type { GenerationContext, GenerationResult } from './types.js'; +import { Command } from "commander"; +import fs from "fs-extra"; +import path from "path"; +import os from "os"; +import { fileURLToPath } from "url"; +import { initConfig, getAllSDKKeys } from "./lib/config.js"; +import { generateSDK } from "./generator.js"; +import { buildNavigation, mergeNavigation } from "./navigation.js"; +import { verifyGeneratedDocs, verifyDocsJson } from "./lib/verify.js"; +import { log } from "./lib/log.js"; +import type { GenerationContext, GenerationResult } from "./types.js"; const __filename = fileURLToPath(import.meta.url); const __dirname = path.dirname(__filename); -const SCRIPT_DIR = path.resolve(__dirname, '..'); -const DOCS_DIR = path.resolve(SCRIPT_DIR, '..'); -const CONFIGS_DIR = path.join(SCRIPT_DIR, 'configs'); +const SCRIPT_DIR = path.resolve(__dirname, ".."); +const DOCS_DIR = path.resolve(SCRIPT_DIR, ".."); +const CONFIGS_DIR = path.join(SCRIPT_DIR, "configs"); initConfig(SCRIPT_DIR); const program = new Command() - .name('generate-sdk-reference') - .description('Generate SDK reference documentation') - .option('--sdk ', 'SDK to generate (or "all")', 'all') - .option('--version ', 'Version to generate (or "all", "latest")', 'all') - .option('--limit ', 'Limit number of versions to generate', parseInt) + .name("generate-sdk-reference") + .description("Generate SDK reference documentation") + .option("--sdk ", 'SDK to generate (or "all")', "all") + .option( + "--version ", + 'Version to generate (or "all", "latest")', + "all" + ) + .option("--limit ", "Limit number of versions to generate", parseInt) + .option("--force", "Force regenerate existing versions") .parse(); const opts = program.opts<{ sdk: string; version: string; limit?: number; + force?: boolean; }>(); async function main(): Promise { - const tempDir = await fs.mkdtemp(path.join(os.tmpdir(), 'sdk-gen-')); - - console.log('🚀 SDK Reference Generator'); - console.log(` SDK: ${opts.sdk}`); - console.log(` Version: ${opts.version}`); - if (opts.limit) { - console.log(` Limit: ${opts.limit} versions`); - } - console.log(` Temp dir: ${tempDir}`); - console.log(''); + const tempDir = await fs.mkdtemp(path.join(os.tmpdir(), "sdk-gen-")); + + log.header("SDK Reference Generator"); + log.stats([ + { label: "SDK", value: opts.sdk }, + { label: "Version", value: opts.version }, + ...(opts.limit ? [{ label: "Limit", value: `${opts.limit} versions` }] : []), + ...(opts.force ? [{ label: "Force", value: "true" }] : []), + { label: "Temp", value: tempDir }, + ]); + log.blank(); const ctx: GenerationContext = { tempDir, docsDir: DOCS_DIR, configsDir: CONFIGS_DIR, limit: opts.limit, + force: opts.force, }; try { - const sdkKeys = - opts.sdk === 'all' ? await getAllSDKKeys() : [opts.sdk]; + const sdkKeys = opts.sdk === "all" ? await getAllSDKKeys() : [opts.sdk]; const results: Map = new Map(); for (const sdkKey of sdkKeys) { - console.log(`📦 Generating ${sdkKey}...`); + log.section(`Generating ${sdkKey}`); const result = await generateSDK(sdkKey, opts.version, ctx); results.set(sdkKey, result); } - console.log(''); - console.log('📝 Generating navigation JSON...'); + log.blank(); + log.section("Building navigation"); const navigation = await buildNavigation(DOCS_DIR); - console.log(''); - console.log('🔄 Merging navigation into docs.json...'); + log.blank(); + log.section("Merging into docs.json"); await mergeNavigation(navigation, DOCS_DIR); - console.log(''); - console.log('✅ SDK reference generation complete'); + log.blank(); + log.section("Verifying documentation"); + const verification = await verifyGeneratedDocs(DOCS_DIR); + + if (verification.warnings.length > 0) { + log.warn("Warnings detected:"); + for (const warning of verification.warnings) { + log.data(`- ${warning}`, 1); + } + } + + if (!verification.valid) { + log.blank(); + log.error("Verification failed:"); + for (const error of verification.errors) { + log.data(`- ${error}`, 1); + } + process.exit(1); + } + + const docsJsonValid = await verifyDocsJson(DOCS_DIR); + if (!docsJsonValid) { + log.error("docs.json validation failed"); + process.exit(1); + } + + log.blank(); + log.success("SDK reference generation complete"); let totalGenerated = 0; let totalFailed = 0; @@ -83,21 +118,21 @@ async function main(): Promise { totalFailed += result.failed; } - if (totalGenerated > 0 || totalFailed > 0) { - console.log(''); - console.log('📊 Final Summary:'); - console.log(` Total generated: ${totalGenerated}`); - if (totalFailed > 0) { - console.log(` Total failed: ${totalFailed}`); - } - } + log.blank(); + log.summary("Final Summary"); + log.stats([ + { label: "Generated", value: totalGenerated }, + ...(totalFailed > 0 ? [{ label: "Failed", value: totalFailed }] : []), + { label: "Total MDX files", value: verification.stats.totalMdxFiles }, + { label: "Total SDKs", value: verification.stats.totalSDKs }, + { label: "Total versions", value: verification.stats.totalVersions }, + ], 0); } finally { await fs.remove(tempDir); } } main().catch((error) => { - console.error('❌ Fatal error:', error.message); + log.error(`Fatal error: ${error.message}`); process.exit(1); }); - diff --git a/sdk-reference-generator/src/generator.ts b/sdk-reference-generator/src/generator.ts index 1da71d9..f8f95cf 100644 --- a/sdk-reference-generator/src/generator.ts +++ b/sdk-reference-generator/src/generator.ts @@ -6,6 +6,7 @@ import type { GenerationResult, } from "./types.js"; import { getSDKConfig } from "./lib/config.js"; +import { log } from "./lib/log.js"; import { fetchRemoteTags, cloneAtTag, @@ -32,10 +33,8 @@ async function generateVersion( const repoDir = path.join(ctx.tempDir, `${sdkKey}-${version}`); try { - const tagName = config.tagFormat.replace( - "{version}", - version.replace(/^v/, "") - ); + const versionWithoutV = version.replace(/^v/, ""); + const tagName = config.tagFormat.replace("{version}", versionWithoutV); await cloneAtTag(config.repo, tagName, repoDir); @@ -48,18 +47,19 @@ async function generateVersion( await installWithCache(sdkDir, config.generator, ctx.tempDir); - await runGenerator(sdkDir, config, ctx); + const generatedDocsDir = await runGenerator(sdkDir, config, ctx); - const generatedDocsDir = path.join(sdkDir, CONSTANTS.SDK_REF_DIR); - if (!(await fs.pathExists(generatedDocsDir))) { - throw new Error("No sdk_ref directory generated"); + const sdkRefDir = path.join(sdkDir, CONSTANTS.SDK_REF_DIR); + if (generatedDocsDir !== sdkRefDir) { + log.info(`Normalizing ${path.basename(generatedDocsDir)} to sdk_ref`, 1); + await fs.move(generatedDocsDir, sdkRefDir); } - await flattenMarkdown(generatedDocsDir); + await flattenMarkdown(sdkRefDir); const destDir = buildSDKPath(ctx.docsDir, sdkKey, version); const success = await copyToDocs( - generatedDocsDir, + sdkRefDir, destDir, config.displayName, version @@ -81,55 +81,72 @@ export async function generateSDK( const config = await getSDKConfig(sdkKey); if (!config) { - console.log(` ❌ SDK '${sdkKey}' not found in config`); + log.error(`SDK '${sdkKey}' not found in config`, 1); return { generated: 0, failed: 1, failedVersions: [sdkKey] }; } - console.log(` → ${config.displayName} version: ${versionArg}`); + log.info(`${config.displayName} version: ${versionArg}`, 1); let versionsToProcess: string[] = []; if (versionArg === "all") { - console.log(" → Discovering all versions..."); + log.info("Discovering all versions...", 1); let remote = await fetchRemoteTags(config.repo, config.tagPattern); if (remote.length === 0) { if (config.required) { - console.log(" ❌ No tags found"); + log.error("No tags found", 1); return { generated: 0, failed: 1, failedVersions: ["no-tags"] }; } - console.log(" ⚠️ No tags found, skipping..."); + log.warn("No tags found, skipping...", 1); return { generated: 0, failed: 0, failedVersions: [] }; } if (config.minVersion) { remote = filterByMinVersion(remote, config.minVersion); - console.log(` → Filtered to versions >= ${config.minVersion}`); + log.info(`Filtered to versions >= ${config.minVersion}`, 1); } if (ctx.limit && ctx.limit > 0) { remote = remote.slice(0, ctx.limit); - console.log(` → Limited to last ${ctx.limit} versions`); + log.info(`Limited to last ${ctx.limit} versions`, 1); } const local = await fetchLocalVersions(sdkKey, ctx.docsDir); - console.log(""); - console.log(" 📊 Version Discovery:"); - console.log(` Remote: ${remote.length}`); - console.log(` Local: ${local.length}`); + log.blank(); + log.step("Version Discovery", 1); + log.stats( + [ + { label: "Remote", value: remote.length }, + { label: "Local", value: local.length }, + ], + 1 + ); - const missing = diffVersions(remote, local); + const missing = ctx.force ? remote : diffVersions(remote, local); - console.log(` Missing: ${missing.length}`); - console.log(""); + log.stats( + [ + { + label: ctx.force ? "To Generate (forced)" : "Missing", + value: missing.length, + }, + ], + 1 + ); + log.blank(); if (missing.length === 0) { - console.log(" ✅ Nothing to generate"); + log.success("Nothing to generate", 1); return { generated: 0, failed: 0, failedVersions: [] }; } + if (ctx.force && local.length > 0) { + log.warn("FORCE MODE: Will regenerate existing versions", 1); + } + versionsToProcess = missing; } else { const resolved = await resolveLatestVersion( @@ -140,18 +157,22 @@ export async function generateSDK( if (!resolved) { if (config.required) { - console.log(" ❌ No tags found"); + log.error("No tags found", 1); return { generated: 0, failed: 1, failedVersions: ["no-tags"] }; } - console.log(" ⚠️ No tags found, skipping..."); + log.warn("No tags found, skipping...", 1); return { generated: 0, failed: 0, failedVersions: [] }; } - if (await versionExists(sdkKey, resolved, ctx.docsDir)) { - console.log(` ✓ ${resolved} already exists`); + if (!ctx.force && (await versionExists(sdkKey, resolved, ctx.docsDir))) { + log.success(`${resolved} already exists`, 1); return { generated: 0, failed: 0, failedVersions: [] }; } + if (ctx.force) { + log.warn("FORCE MODE: Will regenerate existing version", 1); + } + versionsToProcess = [resolved]; } @@ -160,38 +181,48 @@ export async function generateSDK( const failedVersions: string[] = []; for (const version of versionsToProcess) { - console.log(""); - console.log(` 📦 Generating ${version}...`); + log.blank(); + log.step(`Generating ${version}`, 1); try { await generateVersion(sdkKey, config, version, ctx); - console.log(` ✅ Complete: ${version}`); + log.success(`Complete: ${version}`, 1); generated++; } catch (error) { const msg = error instanceof Error ? error.message : String(error); - console.log(` ❌ Failed: ${version} - ${msg}`); + log.error(`Failed: ${version} - ${msg}`, 1); failed++; failedVersions.push(version); } } - console.log(""); - console.log(" 📊 Summary:"); - console.log(` Generated: ${generated}`); - if (failed > 0) { - console.log(` Failed: ${failed} (${failedVersions.join(" ")})`); - } + log.blank(); + log.step("Summary", 1); + log.stats( + [ + { label: "Generated", value: generated }, + ...(failed > 0 + ? [ + { + label: "Failed", + value: `${failed} (${failedVersions.join(" ")})`, + }, + ] + : []), + ], + 1 + ); if (failed > 0) { if (config.required) { - console.log(""); - console.log(" ❌ WORKFLOW ABORTED: Required SDK has failures"); - console.log(` ❌ Failed: ${failedVersions.join(" ")}`); + log.blank(); + log.error("WORKFLOW ABORTED: Required SDK has failures", 1); + log.error(`Failed: ${failedVersions.join(" ")}`, 1); process.exit(1); } else if (generated === 0) { - console.log(""); - console.log(" ❌ WORKFLOW ABORTED: All versions failed"); - console.log(` ❌ Failed: ${failedVersions.join(" ")}`); + log.blank(); + log.error("WORKFLOW ABORTED: All versions failed", 1); + log.error(`Failed: ${failedVersions.join(" ")}`, 1); process.exit(1); } } diff --git a/sdk-reference-generator/src/generators/cli.ts b/sdk-reference-generator/src/generators/cli.ts index 59ad100..4adc1e9 100644 --- a/sdk-reference-generator/src/generators/cli.ts +++ b/sdk-reference-generator/src/generators/cli.ts @@ -3,41 +3,45 @@ import fs from "fs-extra"; import path from "path"; import { glob } from "glob"; import { CONSTANTS } from "../lib/constants.js"; +import { log } from "../lib/log.js"; -export async function generateCli(sdkDir: string): Promise { - console.log(" → Building CLI..."); +export async function generateCli(sdkDir: string): Promise { + log.info("Building CLI...", 1); try { await execa("pnpm", ["run", "build"], { cwd: sdkDir, - stdio: "pipe", + stdio: "inherit", }); - } catch { + } catch (error) { + log.warn("pnpm build failed, trying tsup...", 1); await execa("npx", ["tsup"], { cwd: sdkDir, - stdio: "pipe", + stdio: "inherit", }); } - console.log(" → Generating documentation..."); + log.info("Generating documentation...", 1); - await fs.ensureDir(path.join(sdkDir, CONSTANTS.SDK_REF_DIR)); + const outputDir = path.join(sdkDir, CONSTANTS.SDK_REF_DIR); + await fs.ensureDir(outputDir); await execa("node", ["dist/index.js", "-cmd2md"], { cwd: sdkDir, env: { ...process.env, NODE_ENV: "development" }, - stdio: "pipe", + stdio: "inherit", }); - const sdkRef = path.join(sdkDir, CONSTANTS.SDK_REF_DIR); - const mdFiles = await glob(`*${CONSTANTS.MD_EXTENSION}`, { cwd: sdkRef }); + const mdFiles = await glob(`*${CONSTANTS.MD_EXTENSION}`, { cwd: outputDir }); for (const file of mdFiles) { - const srcPath = path.join(sdkRef, file); + const srcPath = path.join(outputDir, file); const destPath = srcPath.replace( CONSTANTS.MD_EXTENSION, CONSTANTS.MDX_EXTENSION ); await fs.move(srcPath, destPath); } + + return outputDir; } diff --git a/sdk-reference-generator/src/generators/index.ts b/sdk-reference-generator/src/generators/index.ts index 4363bbb..388c34c 100644 --- a/sdk-reference-generator/src/generators/index.ts +++ b/sdk-reference-generator/src/generators/index.ts @@ -1,31 +1,33 @@ -import type { SDKConfig, GenerationContext } from '../types.js'; -import { generateTypedoc } from './typedoc.js'; -import { generatePydoc } from './pydoc.js'; -import { generateCli } from './cli.js'; +import type { SDKConfig, GenerationContext } from "../types.js"; +import { generateTypedoc } from "./typedoc.js"; +import { generatePydoc } from "./pydoc.js"; +import { generateCli } from "./cli.js"; export async function runGenerator( sdkDir: string, config: SDKConfig, ctx: GenerationContext -): Promise { +): Promise { switch (config.generator) { - case 'typedoc': - await generateTypedoc(sdkDir, ctx.configsDir); - break; + case "typedoc": + return await generateTypedoc(sdkDir, ctx.configsDir); - case 'pydoc': - await generatePydoc(sdkDir, config.packages || [], config.submodules); - break; + case "pydoc": + return await generatePydoc( + sdkDir, + config.fallbackPackages || [], + config.submodules, + config.basePackage + ); - case 'cli': - await generateCli(sdkDir); - break; + case "cli": + return await generateCli(sdkDir); default: throw new Error(`Unknown generator: ${config.generator}`); } } -export { generateTypedoc } from './typedoc.js'; -export { generatePydoc } from './pydoc.js'; -export { generateCli } from './cli.js'; +export { generateTypedoc } from "./typedoc.js"; +export { generatePydoc } from "./pydoc.js"; +export { generateCli } from "./cli.js"; diff --git a/sdk-reference-generator/src/generators/pydoc.ts b/sdk-reference-generator/src/generators/pydoc.ts index 5fa960e..1f7f6bb 100644 --- a/sdk-reference-generator/src/generators/pydoc.ts +++ b/sdk-reference-generator/src/generators/pydoc.ts @@ -1,47 +1,121 @@ -import { execa } from 'execa'; -import fs from 'fs-extra'; -import path from 'path'; -import { CONSTANTS } from '../lib/constants.js'; +import { execa } from "execa"; +import fs from "fs-extra"; +import path from "path"; +import { CONSTANTS } from "../lib/constants.js"; +import { log } from "../lib/log.js"; + +async function discoverPythonPackages( + sdkDir: string, + basePackage: string = "e2b" +): Promise { + try { + const script = ` +import warnings +warnings.filterwarnings('ignore') + +import sys +import pkgutil +import importlib + +try: + base = importlib.import_module('${basePackage}') + modules = [] + + for importer, modname, ispkg in pkgutil.iter_modules(base.__path__, base.__name__ + '.'): + modules.append(modname) + + if modules: + print('\\n'.join(sorted(modules))) +except ImportError: + pass +`; + + const result = await execa( + "poetry", + ["run", "python", "-W", "ignore", "-c", script], + { + cwd: sdkDir, + stdio: "pipe", + reject: false, + } + ); + + if (result.exitCode !== 0) { + log.warn(`Discovery failed for ${basePackage} (using fallback)`, 1); + return []; + } + + const packages = result.stdout + .split("\n") + .filter(Boolean) + .filter((pkg) => !pkg.includes("__pycache__")); + + if (packages.length > 0) { + log.info(`Discovered ${packages.length} packages from ${basePackage}`, 1); + } + + return packages; + } catch (error) { + log.warn("Discovery failed (using fallback)", 1); + return []; + } +} async function processMdx(file: string): Promise { - let content = await fs.readFile(file, 'utf-8'); + let content = await fs.readFile(file, "utf-8"); - content = content.replace(/]*>.*?<\/a>/g, ''); + content = content.replace(/]*>.*?<\/a>/g, ""); content = content - .split('\n') - .filter((line) => !line.startsWith('# ')) - .join('\n'); + .split("\n") + .filter((line) => !line.startsWith("# ")) + .join("\n"); - content = content.replace(/^(## .+) Objects$/gm, '$1'); + content = content.replace(/^(## .+) Objects$/gm, "$1"); - content = content.replace(/^####/gm, '###'); + content = content.replace(/^####/gm, "###"); await fs.writeFile(file, content); } -async function processPackage( - pkg: string, - sdkDir: string -): Promise { - const rawName = pkg.split('.').pop() || pkg; - const name = rawName.replace(/^e2b_/, ''); +async function processPackage(pkg: string, sdkDir: string): Promise { + const rawName = pkg.split(".").pop() || pkg; + const name = rawName.replace(/^e2b_/, ""); - console.log(` → Processing ${pkg}...`); + log.step(`Processing ${pkg}`, 2); - const outputFile = path.join(sdkDir, CONSTANTS.SDK_REF_DIR, `${name}${CONSTANTS.MDX_EXTENSION}`); + const outputFile = path.join( + sdkDir, + CONSTANTS.SDK_REF_DIR, + `${name}${CONSTANTS.MDX_EXTENSION}` + ); try { - const result = await execa('poetry', ['run', 'pydoc-markdown', '-p', pkg], { + const result = await execa("poetry", ["run", "pydoc-markdown", "-p", pkg], { cwd: sdkDir, - stdio: 'pipe', + stdio: "pipe", }); + const rawContent = result.stdout.trim(); + if (rawContent.length < 50) { + log.warn(`${pkg} generated no content - skipping`, 2); + return false; + } + await fs.writeFile(outputFile, result.stdout); await processMdx(outputFile); + + const stat = await fs.stat(outputFile); + if (stat.size < 100) { + log.warn(`${pkg} has no meaningful content - removing`, 2); + await fs.remove(outputFile); + return false; + } + return true; - } catch { - console.log(` ⚠️ Failed to generate docs for ${pkg}`); + } catch (error) { + const msg = error instanceof Error ? error.message : String(error); + log.warn(`Failed to generate docs for ${pkg}: ${msg}`, 2); await fs.remove(outputFile); return false; } @@ -49,17 +123,33 @@ async function processPackage( export async function generatePydoc( sdkDir: string, - packages: string[], - submodules?: Record -): Promise { - await fs.ensureDir(path.join(sdkDir, CONSTANTS.SDK_REF_DIR)); - - console.log(' → Generating documentation for packages...'); + fallbackPackages: string[], + submodules?: Record, + basePackage?: string +): Promise { + const outputDir = path.join(sdkDir, CONSTANTS.SDK_REF_DIR); + await fs.ensureDir(outputDir); + + log.info("Discovering Python packages...", 1); + const discovered = await discoverPythonPackages(sdkDir, basePackage); + + const packagesToProcess = + discovered.length > 0 ? discovered : fallbackPackages; + + if (discovered.length > 0) { + log.info(`Found ${packagesToProcess.length} packages (auto-discovered)`, 1); + } else if (fallbackPackages.length > 0) { + log.info(`Using ${fallbackPackages.length} fallback packages`, 1); + } - for (const pkg of packages) { - await processPackage(pkg, sdkDir); + let successful = 0; + for (const pkg of packagesToProcess) { + const result = await processPackage(pkg, sdkDir); + if (result) successful++; } + log.step(`Generated docs for ${successful}/${packagesToProcess.length} packages`, 1); + if (submodules) { for (const [parentPkg, submoduleNames] of Object.entries(submodules)) { for (const submod of submoduleNames) { @@ -68,5 +158,6 @@ export async function generatePydoc( } } } -} + return outputDir; +} diff --git a/sdk-reference-generator/src/generators/typedoc.ts b/sdk-reference-generator/src/generators/typedoc.ts index 5a24050..565d31b 100644 --- a/sdk-reference-generator/src/generators/typedoc.ts +++ b/sdk-reference-generator/src/generators/typedoc.ts @@ -1,15 +1,32 @@ import { execa } from 'execa'; import fs from 'fs-extra'; import path from 'path'; +import { log } from '../lib/log.js'; + +async function getTypedocOutputDir(sdkDir: string): Promise { + const configPath = path.join(sdkDir, 'typedoc.json'); + + if (await fs.pathExists(configPath)) { + try { + const config = await fs.readJSON(configPath); + return config.out || 'sdk_ref'; + } catch { + return 'sdk_ref'; + } + } + + return 'sdk_ref'; +} export async function generateTypedoc( sdkDir: string, configsDir: string -): Promise { +): Promise { const hasRepoConfig = await fs.pathExists(path.join(sdkDir, 'typedoc.json')); + const outputDir = await getTypedocOutputDir(sdkDir); if (hasRepoConfig) { - console.log(' → Running TypeDoc with repo config...'); + log.info('Running TypeDoc with repo config...', 1); await execa( 'npx', [ @@ -21,11 +38,11 @@ export async function generateTypedoc( ], { cwd: sdkDir, - stdio: 'pipe', + stdio: 'inherit', } ); } else { - console.log(' → Running TypeDoc with default config...'); + log.info('Running TypeDoc with default config...', 1); await fs.copy( path.join(configsDir, 'typedoc.json'), path.join(sdkDir, 'typedoc.docs.json') @@ -44,8 +61,10 @@ export async function generateTypedoc( ], { cwd: sdkDir, - stdio: 'pipe', + stdio: 'inherit', } ); } + + return path.join(sdkDir, outputDir); } diff --git a/sdk-reference-generator/src/lib/files.ts b/sdk-reference-generator/src/lib/files.ts index 4d7c028..b304eb5 100644 --- a/sdk-reference-generator/src/lib/files.ts +++ b/sdk-reference-generator/src/lib/files.ts @@ -1,25 +1,26 @@ -import fs from 'fs-extra'; -import path from 'path'; -import { glob } from 'glob'; -import { createFrontmatter } from './utils.js'; -import { CONSTANTS } from './constants.js'; +import fs from "fs-extra"; +import path from "path"; +import { glob } from "glob"; +import { createFrontmatter } from "./utils.js"; +import { CONSTANTS } from "./constants.js"; +import { log } from "./log.js"; export function toTitleCase(str: string): string { - if (!str) return ''; + if (!str) return ""; return str - .split('_') + .split("_") .map((word) => word.charAt(0).toUpperCase() + word.slice(1)) - .join(' '); + .join(" "); } export async function addFrontmatter( file: string, title: string ): Promise { - const content = await fs.readFile(file, 'utf-8'); + const content = await fs.readFile(file, "utf-8"); - if (content.startsWith('---')) { + if (content.startsWith("---")) { return; } @@ -27,32 +28,31 @@ export async function addFrontmatter( } export async function flattenMarkdown(refDir: string): Promise { - await fs.remove(path.join(refDir, 'README.md')); - await fs.remove(path.join(refDir, 'index.md')); + await fs.remove(path.join(refDir, "README.md")); + await fs.remove(path.join(refDir, "index.md")); - const nestedFiles = await glob('**/*.md', { + const nestedFiles = await glob("**/*.md", { cwd: refDir, - ignore: '*.md', + ignore: "*.md", }); for (const file of nestedFiles) { const filename = path.basename(file); - const dirName = path.basename(path.dirname(file)); - - let targetName: string; - if (filename === 'page.md' || filename === 'index.md') { - targetName = `${dirName}.md`; - } else { - targetName = filename; - } - - const sourcePath = path.join(refDir, file); - const targetPath = path.join(refDir, targetName); - - await fs.move(sourcePath, targetPath, { overwrite: true }); + const parentDirName = path.basename(path.dirname(file)); + + const targetName = + filename === "page.md" || filename === "index.md" + ? `${parentDirName}.md` + : filename; + + await fs.move( + path.join(refDir, file), + path.join(refDir, targetName), + { overwrite: true } + ); } - const dirs = await glob('**/', { cwd: refDir }); + const dirs = await glob("**/", { cwd: refDir }); for (const dir of dirs.reverse()) { const dirPath = path.join(refDir, dir); try { @@ -60,19 +60,20 @@ export async function flattenMarkdown(refDir: string): Promise { if (files.length === 0) { await fs.remove(dirPath); } - } catch { - // ignore - } + } catch {} } - const mdFiles = await glob('*.md', { cwd: refDir }); + const mdFiles = await glob("*.md", { cwd: refDir }); for (const file of mdFiles) { const fullPath = path.join(refDir, file); const title = toTitleCase(path.basename(file, CONSTANTS.MD_EXTENSION)); - const content = await fs.readFile(fullPath, 'utf-8'); + const content = await fs.readFile(fullPath, "utf-8"); - const mdxPath = fullPath.replace(CONSTANTS.MD_EXTENSION, CONSTANTS.MDX_EXTENSION); + const mdxPath = fullPath.replace( + CONSTANTS.MD_EXTENSION, + CONSTANTS.MDX_EXTENSION + ); await fs.writeFile(mdxPath, createFrontmatter(title) + content); await fs.remove(fullPath); } @@ -81,9 +82,9 @@ export async function flattenMarkdown(refDir: string): Promise { for (const file of mdxFiles) { const fullPath = path.join(refDir, file); - const content = await fs.readFile(fullPath, 'utf-8'); + const content = await fs.readFile(fullPath, "utf-8"); - if (!content.startsWith('---')) { + if (!content.startsWith("---")) { const title = toTitleCase(path.basename(file, CONSTANTS.MDX_EXTENSION)); await addFrontmatter(fullPath, title); } @@ -92,24 +93,22 @@ export async function flattenMarkdown(refDir: string): Promise { await fs.remove(path.join(refDir, `index${CONSTANTS.MDX_EXTENSION}`)); } -export async function validateMdxFiles(srcDir: string): Promise { - await fs.remove(path.join(srcDir, `*${CONSTANTS.MDX_EXTENSION}`)); +async function getNonEmptyMdxFiles(dir: string): Promise { + await fs.remove(path.join(dir, `*${CONSTANTS.MDX_EXTENSION}`)); - const files = await glob(`*${CONSTANTS.MDX_EXTENSION}`, { cwd: srcDir }); + const allFiles = await glob(`*${CONSTANTS.MDX_EXTENSION}`, { cwd: dir }); + const nonEmptyFiles: string[] = []; - let validCount = 0; - for (const file of files) { + for (const file of allFiles) { if (file === `*${CONSTANTS.MDX_EXTENSION}`) continue; - const fullPath = path.join(srcDir, file); - const stat = await fs.stat(fullPath); - - if (stat.size === 0) continue; - - validCount++; + const stat = await fs.stat(path.join(dir, file)); + if (stat.size > 0) { + nonEmptyFiles.push(file); + } } - return validCount; + return nonEmptyFiles; } export async function copyToDocs( @@ -118,32 +117,24 @@ export async function copyToDocs( sdkName: string, version: string ): Promise { - const count = await validateMdxFiles(srcDir); + const files = await getNonEmptyMdxFiles(srcDir); - if (count === 0) { - console.log(' ❌ No MDX files generated - doc generator failed'); + if (files.length === 0) { + log.error("No MDX files generated - doc generator failed", 1); return false; } await fs.ensureDir(destDir); - - console.log(` → Copying ${count} files to ${destDir}`); - - const files = await glob(`*${CONSTANTS.MDX_EXTENSION}`, { cwd: srcDir }); + log.info(`Copying ${files.length} files to ${destDir}`, 1); for (const file of files) { - if (file === `*${CONSTANTS.MDX_EXTENSION}`) continue; - - const srcPath = path.join(srcDir, file); - const destPath = path.join(destDir, file); - const stat = await fs.stat(srcPath); - - if (stat.size > 0) { - await fs.copy(srcPath, destPath); - } + await fs.copy( + path.join(srcDir, file), + path.join(destDir, file) + ); } - console.log(` ✅ ${sdkName} ${version} complete`); + log.success(`${sdkName} ${version} complete`, 1); return true; } @@ -172,4 +163,3 @@ export async function locateSDKDir( return repoDir; } - diff --git a/sdk-reference-generator/src/lib/git.ts b/sdk-reference-generator/src/lib/git.ts index 31b8d8f..d945396 100644 --- a/sdk-reference-generator/src/lib/git.ts +++ b/sdk-reference-generator/src/lib/git.ts @@ -1,5 +1,6 @@ import { simpleGit, SimpleGit } from 'simple-git'; import { sortVersionsDescending } from './utils.js'; +import { log } from './log.js'; const git: SimpleGit = simpleGit(); @@ -31,7 +32,7 @@ export async function cloneAtTag( try { await git.clone(repo, targetDir, ['--depth', '1', '--branch', tag]); } catch { - console.log(` ⚠️ Tag ${tag} not found, trying default branch...`); + log.warn(`Tag ${tag} not found, trying default branch...`, 1); await git.clone(repo, targetDir, ['--depth', '1']); } } diff --git a/sdk-reference-generator/src/lib/install.ts b/sdk-reference-generator/src/lib/install.ts index 233742b..2c59995 100644 --- a/sdk-reference-generator/src/lib/install.ts +++ b/sdk-reference-generator/src/lib/install.ts @@ -1,66 +1,63 @@ import { execa } from 'execa'; import type { GeneratorType } from '../types.js'; import { hashLockfile, isCached, markCached } from './cache.js'; +import { log } from './log.js'; async function installDependencies( sdkDir: string, generator: GeneratorType ): Promise { - console.log(' → Installing dependencies...'); + log.info('Installing dependencies...', 1); switch (generator) { - case 'typedoc': { - try { - await execa( - 'pnpm', - ['install', '--ignore-scripts', '--prefer-offline'], - { - cwd: sdkDir, - stdio: 'pipe', - } - ); - } catch { - console.log(' ⚠️ pnpm failed, trying npm...'); - await execa( - 'npm', - ['install', '--legacy-peer-deps', '--prefer-offline'], - { - cwd: sdkDir, - stdio: 'pipe', - } - ); - } - break; - } - + case 'typedoc': case 'cli': { + const isTypedoc = generator === 'typedoc'; + const baseArgs = isTypedoc + ? ['install', '--ignore-scripts', '--prefer-offline'] + : ['install', '--prefer-offline']; + try { - await execa('pnpm', ['install', '--prefer-offline'], { + await execa('pnpm', baseArgs, { cwd: sdkDir, - stdio: 'pipe', + stdio: 'inherit', }); } catch { - await execa('npm', ['install', '--prefer-offline'], { - cwd: sdkDir, - stdio: 'pipe', - }); + log.warn('Trying with relaxed engine constraints...', 1); + try { + await execa('pnpm', ['--engine-strict=false', ...baseArgs], { + cwd: sdkDir, + stdio: 'inherit', + }); + } catch { + log.warn('pnpm failed, trying npm...', 1); + await execa( + 'npm', + ['install', '--legacy-peer-deps', '--force', '--prefer-offline'], + { + cwd: sdkDir, + stdio: 'inherit', + } + ); + } } break; } case 'pydoc': { try { - await execa('poetry', ['install', '--quiet'], { + await execa('poetry', ['install', '--no-interaction'], { cwd: sdkDir, - stdio: 'pipe', + stdio: 'inherit', }); } catch { + log.warn('poetry failed, using global pydoc-markdown...', 1); await execa( 'pip', ['install', '--break-system-packages', 'pydoc-markdown'], { cwd: sdkDir, - stdio: 'pipe', + stdio: 'inherit', } ); } @@ -78,7 +75,7 @@ export async function installWithCache( const hash = await hashLockfile(sdkDir, generator); if (hash && (await isCached(hash, generator, tempDir))) { - console.log(' → Poetry dependencies cached (lockfile unchanged)'); + log.info('Poetry dependencies cached (lockfile unchanged)', 1); return; } diff --git a/sdk-reference-generator/src/lib/log.ts b/sdk-reference-generator/src/lib/log.ts new file mode 100644 index 0000000..aa67bf4 --- /dev/null +++ b/sdk-reference-generator/src/lib/log.ts @@ -0,0 +1,59 @@ +import chalk from "chalk"; + +export const log = { + header(message: string): void { + console.log(chalk.bold.cyan(`\n▸ ${message.toUpperCase()}`)); + }, + + section(message: string): void { + console.log(chalk.bold(`\n${message}`)); + }, + + info(message: string, indent = 0): void { + const prefix = " ".repeat(indent); + console.log(`${prefix}${chalk.dim(">")} ${message}`); + }, + + success(message: string, indent = 0): void { + const prefix = " ".repeat(indent); + console.log(`${prefix}${chalk.green("✓")} ${message}`); + }, + + warn(message: string, indent = 0): void { + const prefix = " ".repeat(indent); + console.log(`${prefix}${chalk.yellow("!")} ${message}`); + }, + + error(message: string, indent = 0): void { + const prefix = " ".repeat(indent); + console.log(`${prefix}${chalk.red("✗")} ${message}`); + }, + + step(message: string, indent = 0): void { + const prefix = " ".repeat(indent); + console.log(`${prefix}${chalk.blue("-")} ${message}`); + }, + + stats( + items: Array<{ label: string; value: string | number }>, + indent = 0 + ): void { + const prefix = " ".repeat(indent); + for (const { label, value } of items) { + console.log(`${prefix} ${chalk.gray(label + ":")} ${value}`); + } + }, + + blank(): void { + console.log(""); + }, + + data(message: string, indent = 0): void { + const prefix = " ".repeat(indent); + console.log(`${prefix} ${chalk.dim(message)}`); + }, + + summary(title: string): void { + console.log(chalk.bold.white(`\n${title}`)); + }, +}; diff --git a/sdk-reference-generator/src/lib/verify.ts b/sdk-reference-generator/src/lib/verify.ts new file mode 100644 index 0000000..d64272f --- /dev/null +++ b/sdk-reference-generator/src/lib/verify.ts @@ -0,0 +1,127 @@ +import fs from 'fs-extra'; +import path from 'path'; +import { glob } from 'glob'; +import { CONSTANTS } from './constants.js'; +import { log } from './log.js'; + +export interface VerificationResult { + valid: boolean; + errors: string[]; + warnings: string[]; + stats: { + totalMdxFiles: number; + totalSDKs: number; + totalVersions: number; + }; +} + +export async function verifyGeneratedDocs( + docsDir: string +): Promise { + const errors: string[] = []; + const warnings: string[] = []; + const stats = { totalMdxFiles: 0, totalSDKs: 0, totalVersions: 0 }; + + const sdkRefDir = path.join(docsDir, CONSTANTS.DOCS_SDK_REF_PATH); + + if (!(await fs.pathExists(sdkRefDir))) { + errors.push('SDK reference directory does not exist'); + return { valid: false, errors, warnings, stats }; + } + + const sdkDirs = await fs.readdir(sdkRefDir, { withFileTypes: true }); + + for (const sdkEntry of sdkDirs) { + if (!sdkEntry.isDirectory()) continue; + + stats.totalSDKs++; + const sdkPath = path.join(sdkRefDir, sdkEntry.name); + const versionDirs = await fs.readdir(sdkPath, { withFileTypes: true }); + + for (const versionEntry of versionDirs) { + if (!versionEntry.isDirectory()) continue; + if (!/^v?\d+\.\d+\.\d+/.test(versionEntry.name)) continue; + + stats.totalVersions++; + const versionPath = path.join(sdkPath, versionEntry.name); + + const mdxFiles = await glob(`*${CONSTANTS.MDX_EXTENSION}`, { + cwd: versionPath, + }); + + if (mdxFiles.length === 0) { + warnings.push( + `${sdkEntry.name}/${versionEntry.name} has no MDX files` + ); + continue; + } + + for (const file of mdxFiles) { + const filePath = path.join(versionPath, file); + const stat = await fs.stat(filePath); + + if (stat.size === 0) { + errors.push( + `Empty file: ${sdkEntry.name}/${versionEntry.name}/${file}` + ); + } else { + stats.totalMdxFiles++; + + const content = await fs.readFile(filePath, 'utf-8'); + if (!content.startsWith('---')) { + errors.push( + `Missing frontmatter: ${sdkEntry.name}/${versionEntry.name}/${file}` + ); + } + } + } + } + } + + return { + valid: errors.length === 0, + errors, + warnings, + stats, + }; +} + +export async function verifyDocsJson(docsDir: string): Promise { + const docsJsonPath = path.join(docsDir, 'docs.json'); + + if (!(await fs.pathExists(docsJsonPath))) { + log.error('docs.json not found'); + return false; + } + + try { + const docsJson = await fs.readJSON(docsJsonPath); + + const anchors = docsJson.navigation?.anchors; + if (!Array.isArray(anchors)) { + log.error('Invalid docs.json: navigation.anchors is not an array'); + return false; + } + + const sdkRefAnchor = anchors.find( + (a: { anchor?: string }) => a.anchor === CONSTANTS.SDK_REFERENCE_ANCHOR + ); + + if (!sdkRefAnchor) { + log.error(`${CONSTANTS.SDK_REFERENCE_ANCHOR} anchor not found in docs.json`); + return false; + } + + if (!Array.isArray(sdkRefAnchor.dropdowns)) { + log.error('SDK Reference anchor has no dropdowns array'); + return false; + } + + return true; + } catch (error) { + const msg = error instanceof Error ? error.message : String(error); + log.error(`Failed to parse docs.json: ${msg}`); + return false; + } +} + diff --git a/sdk-reference-generator/src/navigation.ts b/sdk-reference-generator/src/navigation.ts index 89656ac..7c7b7e7 100644 --- a/sdk-reference-generator/src/navigation.ts +++ b/sdk-reference-generator/src/navigation.ts @@ -3,6 +3,7 @@ import path from "path"; import { loadConfig } from "./lib/config.js"; import { sortVersionsDescending } from "./lib/utils.js"; import { CONSTANTS } from "./lib/constants.js"; +import { log } from "./lib/log.js"; import type { NavigationDropdown, NavigationDropdownWithOrder, @@ -44,7 +45,7 @@ export async function buildNavigation( const sdkRefDir = path.join(docsDir, CONSTANTS.DOCS_SDK_REF_PATH); if (!(await fs.pathExists(sdkRefDir))) { - console.log("⚠️ SDK reference directory not found:", sdkRefDir); + log.warn(`SDK reference directory not found: ${sdkRefDir}`); return []; } @@ -54,17 +55,17 @@ export async function buildNavigation( const sdkDir = path.join(sdkRefDir, sdkKey); if (!(await fs.pathExists(sdkDir))) { - console.log(` Skipping ${sdkKey} (not found)`); + log.data(`Skipping ${sdkKey} (not found)`); continue; } const versions = await getVersions(sdkDir); if (versions.length === 0) { - console.log(` Skipping ${sdkKey} (no versions)`); + log.data(`Skipping ${sdkKey} (no versions)`); continue; } - console.log(` Found ${sdkKey}: ${versions.length} versions`); + log.data(`Found ${sdkKey}: ${versions.length} versions`); const dropdown: NavigationDropdownWithOrder = { dropdown: sdkConfig.displayName, @@ -105,7 +106,7 @@ export async function mergeNavigation( const docsJsonPath = path.join(docsDir, "docs.json"); if (!(await fs.pathExists(docsJsonPath))) { - console.log("❌ docs.json not found"); + log.error("docs.json not found"); process.exit(1); } @@ -113,18 +114,7 @@ export async function mergeNavigation( const anchors = docsJson.navigation?.anchors; if (!anchors) { - console.log("❌ No anchors found in docs.json"); - process.exit(1); - } - - const sdkRefIndex = anchors.findIndex( - (a: { anchor?: string }) => a.anchor === CONSTANTS.SDK_REFERENCE_ANCHOR - ); - - if (sdkRefIndex === -1) { - console.log( - `❌ ${CONSTANTS.SDK_REFERENCE_ANCHOR} anchor not found in docs.json` - ); + log.error("No anchors found in docs.json"); process.exit(1); } @@ -133,25 +123,34 @@ export async function mergeNavigation( ); if (validDropdowns.length === 0) { - console.log("⚠️ No SDK versions found, keeping existing docs.json"); + log.warn("No SDK versions found, keeping existing docs.json"); return; } - anchors[sdkRefIndex] = { + const sdkRefAnchor = { anchor: CONSTANTS.SDK_REFERENCE_ANCHOR, icon: "brackets-curly", dropdowns: validDropdowns, }; + const sdkRefIndex = anchors.findIndex( + (a: { anchor?: string }) => a.anchor === CONSTANTS.SDK_REFERENCE_ANCHOR + ); + + if (sdkRefIndex === -1) { + log.info(`Creating new ${CONSTANTS.SDK_REFERENCE_ANCHOR} anchor`, 1); + anchors.push(sdkRefAnchor); + } else { + anchors[sdkRefIndex] = sdkRefAnchor; + } + await fs.writeJSON(docsJsonPath, docsJson, { spaces: 2 }); const content = await fs.readFile(docsJsonPath, "utf-8"); if (!content.endsWith("\n")) { await fs.appendFile(docsJsonPath, "\n"); } - console.log( - `✅ Updated docs.json with ${validDropdowns.length} SDK dropdowns` - ); + log.success(`Updated docs.json with ${validDropdowns.length} SDK dropdowns`); for (const dropdown of validDropdowns) { const totalVersions = dropdown.versions.length; @@ -159,8 +158,8 @@ export async function mergeNavigation( (sum, v) => sum + (v.pages?.length || 0), 0 ); - console.log( - ` - ${dropdown.dropdown}: ${totalVersions} versions, ${totalPages} pages` + log.data( + `${dropdown.dropdown}: ${totalVersions} versions, ${totalPages} pages` ); } } diff --git a/sdk-reference-generator/src/types.ts b/sdk-reference-generator/src/types.ts index 88ee8f2..790a46d 100644 --- a/sdk-reference-generator/src/types.ts +++ b/sdk-reference-generator/src/types.ts @@ -1,6 +1,6 @@ -import { z } from 'zod'; +import { z } from "zod"; -export const GeneratorType = z.enum(['typedoc', 'pydoc', 'cli']); +export const GeneratorType = z.enum(["typedoc", "pydoc", "cli"]); export type GeneratorType = z.infer; export const SDKConfigSchema = z.object({ @@ -15,8 +15,9 @@ export const SDKConfigSchema = z.object({ minVersion: z.string().optional(), sdkPath: z.string().optional(), sdkPaths: z.array(z.string()).optional(), - packages: z.array(z.string()).optional(), + fallbackPackages: z.array(z.string()).optional().describe('Used if auto-discovery fails'), submodules: z.record(z.string(), z.array(z.string())).optional(), + basePackage: z.string().optional().describe('Base Python package name for discovery'), }); export type SDKConfig = z.infer; @@ -30,6 +31,7 @@ export interface GenerationContext { docsDir: string; configsDir: string; limit?: number; + force?: boolean; } export interface GenerationResult { @@ -53,4 +55,3 @@ export interface NavigationDropdown { export interface NavigationDropdownWithOrder extends NavigationDropdown { _order: number; } - From cb7be7f885848570e5684dc4d790570761348cf9 Mon Sep 17 00:00:00 2001 From: ben-fornefeld Date: Thu, 8 Jan 2026 11:56:28 +0100 Subject: [PATCH 11/39] refactor: migrate SDK configuration from JSON to TypeScript - Introduced a new `sdks.config.ts` file to define SDK configurations in TypeScript, enhancing type safety and maintainability. - Removed the outdated `sdks.json` file to streamline the configuration process. - Updated relevant code to utilize the new configuration structure, including adjustments in the CLI and navigation logic. - Improved type definitions for SDK configurations to support additional properties and ensure consistency across the codebase. --- sdk-reference-generator/sdks.config.ts | 112 ++++++++++++++++++ sdk-reference-generator/sdks.json | 102 ---------------- sdk-reference-generator/src/cli.ts | 25 ++-- .../src/generators/index.ts | 3 - .../src/generators/pydoc.ts | 15 ++- sdk-reference-generator/src/lib/config.ts | 26 +--- sdk-reference-generator/src/lib/install.ts | 14 +-- sdk-reference-generator/src/navigation.ts | 4 +- sdk-reference-generator/src/types.ts | 61 +++++----- sdk-reference-generator/tsconfig.json | 3 +- 10 files changed, 185 insertions(+), 180 deletions(-) create mode 100644 sdk-reference-generator/sdks.config.ts delete mode 100644 sdk-reference-generator/sdks.json diff --git a/sdk-reference-generator/sdks.config.ts b/sdk-reference-generator/sdks.config.ts new file mode 100644 index 0000000..4a1d99c --- /dev/null +++ b/sdk-reference-generator/sdks.config.ts @@ -0,0 +1,112 @@ +import type { SDKConfig } from "./src/types.js"; + +const sdks = { + cli: { + displayName: "CLI", + icon: "terminal", + order: 7, + repo: "https://github.com/e2b-dev/e2b.git", + tagPattern: "@e2b/cli@", + tagFormat: "@e2b/cli@{version}", + sdkPath: "packages/cli", + generator: "cli", + required: true, + minVersion: "1.0.0", + }, + + "js-sdk": { + displayName: "SDK (JavaScript)", + icon: "square-js", + order: 1, + repo: "https://github.com/e2b-dev/e2b.git", + tagPattern: "e2b@", + tagFormat: "e2b@{version}", + sdkPath: "packages/js-sdk", + generator: "typedoc", + required: true, + minVersion: "1.0.0", + }, + + "python-sdk": { + displayName: "SDK (Python)", + icon: "python", + order: 2, + repo: "https://github.com/e2b-dev/e2b.git", + tagPattern: "@e2b/python-sdk@", + tagFormat: "@e2b/python-sdk@{version}", + sdkPath: "packages/python-sdk", + generator: "pydoc", + required: true, + minVersion: "1.0.0", + basePackage: "e2b", + fallbackPackages: [ + "e2b.sandbox_sync", + "e2b.sandbox_async", + "e2b.exceptions", + "e2b.template", + "e2b.template_sync", + "e2b.template_async", + ], + submodules: { + "e2b.template": ["logger", "readycmd"], + }, + }, + + "code-interpreter-js-sdk": { + displayName: "Code Interpreter SDK (JavaScript)", + icon: "square-js", + order: 3, + repo: "https://github.com/e2b-dev/code-interpreter.git", + tagPattern: "@e2b/code-interpreter@", + tagFormat: "@e2b/code-interpreter@{version}", + sdkPaths: ["js"], + generator: "typedoc", + required: false, + minVersion: "1.0.0", + }, + + "code-interpreter-python-sdk": { + displayName: "Code Interpreter SDK (Python)", + icon: "python", + order: 4, + repo: "https://github.com/e2b-dev/code-interpreter.git", + tagPattern: "@e2b/code-interpreter-python@", + tagFormat: "@e2b/code-interpreter-python@{version}", + sdkPaths: ["python"], + generator: "pydoc", + required: false, + minVersion: "1.0.0", + basePackage: "e2b_code_interpreter", + fallbackPackages: ["e2b_code_interpreter"], + }, + + "desktop-js-sdk": { + displayName: "Desktop SDK (JavaScript)", + icon: "square-js", + order: 5, + repo: "https://github.com/e2b-dev/desktop.git", + tagPattern: "@e2b/desktop@", + tagFormat: "@e2b/desktop@{version}", + sdkPaths: ["packages/js-sdk"], + generator: "typedoc", + required: false, + minVersion: "1.0.0", + }, + + "desktop-python-sdk": { + displayName: "Desktop SDK (Python)", + icon: "python", + order: 6, + repo: "https://github.com/e2b-dev/desktop.git", + tagPattern: "@e2b/desktop-python@", + tagFormat: "@e2b/desktop-python@{version}", + sdkPaths: ["packages/python-sdk"], + generator: "pydoc", + required: false, + minVersion: "1.0.0", + basePackage: "e2b_desktop", + fallbackPackages: ["e2b_desktop"], + }, +} as const satisfies Record; + +export default sdks; diff --git a/sdk-reference-generator/sdks.json b/sdk-reference-generator/sdks.json deleted file mode 100644 index bd76b48..0000000 --- a/sdk-reference-generator/sdks.json +++ /dev/null @@ -1,102 +0,0 @@ -{ - "sdks": { - "cli": { - "displayName": "CLI", - "icon": "terminal", - "order": 7, - "repo": "https://github.com/e2b-dev/e2b.git", - "tagPattern": "@e2b/cli@", - "tagFormat": "@e2b/cli@{version}", - "sdkPath": "packages/cli", - "generator": "cli", - "required": true, - "minVersion": "1.0.0" - }, - "js-sdk": { - "displayName": "SDK (JavaScript)", - "icon": "square-js", - "order": 1, - "repo": "https://github.com/e2b-dev/e2b.git", - "tagPattern": "e2b@", - "tagFormat": "e2b@{version}", - "sdkPath": "packages/js-sdk", - "generator": "typedoc", - "required": true, - "minVersion": "1.0.0" - }, - "python-sdk": { - "displayName": "SDK (Python)", - "icon": "python", - "order": 2, - "repo": "https://github.com/e2b-dev/e2b.git", - "tagPattern": "@e2b/python-sdk@", - "tagFormat": "@e2b/python-sdk@{version}", - "sdkPath": "packages/python-sdk", - "generator": "pydoc", - "required": true, - "minVersion": "1.0.0", - "packages": [ - "e2b.sandbox_sync", - "e2b.sandbox_async", - "e2b.exceptions", - "e2b.template", - "e2b.template_sync", - "e2b.template_async" - ], - "submodules": { - "e2b.template": ["logger", "readycmd"] - } - }, - "code-interpreter-js-sdk": { - "displayName": "Code Interpreter SDK (JavaScript)", - "icon": "square-js", - "order": 3, - "repo": "https://github.com/e2b-dev/code-interpreter.git", - "tagPattern": "@e2b/code-interpreter@", - "tagFormat": "@e2b/code-interpreter@{version}", - "sdkPaths": ["js"], - "generator": "typedoc", - "required": false, - "minVersion": "1.0.0" - }, - "code-interpreter-python-sdk": { - "displayName": "Code Interpreter SDK (Python)", - "icon": "python", - "order": 4, - "repo": "https://github.com/e2b-dev/code-interpreter.git", - "tagPattern": "@e2b/code-interpreter-python@", - "tagFormat": "@e2b/code-interpreter-python@{version}", - "sdkPaths": ["python"], - "generator": "pydoc", - "required": false, - "minVersion": "1.0.0", - "packages": ["e2b_code_interpreter"] - }, - "desktop-js-sdk": { - "displayName": "Desktop SDK (JavaScript)", - "icon": "square-js", - "order": 5, - "repo": "https://github.com/e2b-dev/desktop.git", - "tagPattern": "@e2b/desktop@", - "tagFormat": "@e2b/desktop@{version}", - "sdkPaths": ["packages/js-sdk"], - "generator": "typedoc", - "required": false, - "minVersion": "1.0.0" - }, - "desktop-python-sdk": { - "displayName": "Desktop SDK (Python)", - "icon": "python", - "order": 6, - "repo": "https://github.com/e2b-dev/desktop.git", - "tagPattern": "@e2b/desktop-python@", - "tagFormat": "@e2b/desktop-python@{version}", - "sdkPaths": ["packages/python-sdk"], - "generator": "pydoc", - "required": false, - "minVersion": "1.0.0", - "packages": ["e2b_desktop"] - } - } -} - diff --git a/sdk-reference-generator/src/cli.ts b/sdk-reference-generator/src/cli.ts index 8193e8a..8228ca4 100644 --- a/sdk-reference-generator/src/cli.ts +++ b/sdk-reference-generator/src/cli.ts @@ -5,7 +5,7 @@ import fs from "fs-extra"; import path from "path"; import os from "os"; import { fileURLToPath } from "url"; -import { initConfig, getAllSDKKeys } from "./lib/config.js"; +import { getAllSDKKeys } from "./lib/config.js"; import { generateSDK } from "./generator.js"; import { buildNavigation, mergeNavigation } from "./navigation.js"; import { verifyGeneratedDocs, verifyDocsJson } from "./lib/verify.js"; @@ -19,8 +19,6 @@ const SCRIPT_DIR = path.resolve(__dirname, ".."); const DOCS_DIR = path.resolve(SCRIPT_DIR, ".."); const CONFIGS_DIR = path.join(SCRIPT_DIR, "configs"); -initConfig(SCRIPT_DIR); - const program = new Command() .name("generate-sdk-reference") .description("Generate SDK reference documentation") @@ -48,7 +46,9 @@ async function main(): Promise { log.stats([ { label: "SDK", value: opts.sdk }, { label: "Version", value: opts.version }, - ...(opts.limit ? [{ label: "Limit", value: `${opts.limit} versions` }] : []), + ...(opts.limit + ? [{ label: "Limit", value: `${opts.limit} versions` }] + : []), ...(opts.force ? [{ label: "Force", value: "true" }] : []), { label: "Temp", value: tempDir }, ]); @@ -120,13 +120,16 @@ async function main(): Promise { log.blank(); log.summary("Final Summary"); - log.stats([ - { label: "Generated", value: totalGenerated }, - ...(totalFailed > 0 ? [{ label: "Failed", value: totalFailed }] : []), - { label: "Total MDX files", value: verification.stats.totalMdxFiles }, - { label: "Total SDKs", value: verification.stats.totalSDKs }, - { label: "Total versions", value: verification.stats.totalVersions }, - ], 0); + log.stats( + [ + { label: "Generated", value: totalGenerated }, + ...(totalFailed > 0 ? [{ label: "Failed", value: totalFailed }] : []), + { label: "Total MDX files", value: verification.stats.totalMdxFiles }, + { label: "Total SDKs", value: verification.stats.totalSDKs }, + { label: "Total versions", value: verification.stats.totalVersions }, + ], + 0 + ); } finally { await fs.remove(tempDir); } diff --git a/sdk-reference-generator/src/generators/index.ts b/sdk-reference-generator/src/generators/index.ts index 388c34c..1dbf60c 100644 --- a/sdk-reference-generator/src/generators/index.ts +++ b/sdk-reference-generator/src/generators/index.ts @@ -22,9 +22,6 @@ export async function runGenerator( case "cli": return await generateCli(sdkDir); - - default: - throw new Error(`Unknown generator: ${config.generator}`); } } diff --git a/sdk-reference-generator/src/generators/pydoc.ts b/sdk-reference-generator/src/generators/pydoc.ts index 1f7f6bb..427df6f 100644 --- a/sdk-reference-generator/src/generators/pydoc.ts +++ b/sdk-reference-generator/src/generators/pydoc.ts @@ -6,7 +6,7 @@ import { log } from "../lib/log.js"; async function discoverPythonPackages( sdkDir: string, - basePackage: string = "e2b" + basePackage: string ): Promise { try { const script = ` @@ -111,7 +111,7 @@ async function processPackage(pkg: string, sdkDir: string): Promise { await fs.remove(outputFile); return false; } - + return true; } catch (error) { const msg = error instanceof Error ? error.message : String(error); @@ -123,9 +123,9 @@ async function processPackage(pkg: string, sdkDir: string): Promise { export async function generatePydoc( sdkDir: string, - fallbackPackages: string[], - submodules?: Record, - basePackage?: string + fallbackPackages: readonly string[], + submodules?: Record, + basePackage: string = "e2b" ): Promise { const outputDir = path.join(sdkDir, CONSTANTS.SDK_REF_DIR); await fs.ensureDir(outputDir); @@ -148,7 +148,10 @@ export async function generatePydoc( if (result) successful++; } - log.step(`Generated docs for ${successful}/${packagesToProcess.length} packages`, 1); + log.step( + `Generated docs for ${successful}/${packagesToProcess.length} packages`, + 1 + ); if (submodules) { for (const [parentPkg, submoduleNames] of Object.entries(submodules)) { diff --git a/sdk-reference-generator/src/lib/config.ts b/sdk-reference-generator/src/lib/config.ts index f1ec4fd..db25f4c 100644 --- a/sdk-reference-generator/src/lib/config.ts +++ b/sdk-reference-generator/src/lib/config.ts @@ -1,30 +1,16 @@ -import fs from 'fs-extra'; -import path from 'path'; -import { ConfigFileSchema, type SDKConfig, type ConfigFile } from '../types.js'; +import sdks from "../../sdks.config.js"; +import type { SDKConfig, ConfigFile } from "../types.js"; -let cachedConfig: ConfigFile | null = null; -let configPath: string = ''; - -export function initConfig(scriptDir: string): void { - configPath = path.join(scriptDir, 'sdks.json'); - cachedConfig = null; -} - -export async function loadConfig(): Promise { - if (cachedConfig) return cachedConfig; - - const raw = await fs.readJSON(configPath); - cachedConfig = ConfigFileSchema.parse(raw); - return cachedConfig; +export async function getConfig(): Promise { + return { sdks }; } export async function getSDKConfig(sdkKey: string): Promise { - const config = await loadConfig(); + const config = await getConfig(); return config.sdks[sdkKey] || null; } export async function getAllSDKKeys(): Promise { - const config = await loadConfig(); + const config = await getConfig(); return Object.keys(config.sdks); } - diff --git a/sdk-reference-generator/src/lib/install.ts b/sdk-reference-generator/src/lib/install.ts index 2c59995..4ccfc62 100644 --- a/sdk-reference-generator/src/lib/install.ts +++ b/sdk-reference-generator/src/lib/install.ts @@ -29,17 +29,17 @@ async function installDependencies( cwd: sdkDir, stdio: 'inherit', }); - } catch { + } catch { log.warn('pnpm failed, trying npm...', 1); - await execa( + await execa( 'npm', ['install', '--legacy-peer-deps', '--force', '--prefer-offline'], - { - cwd: sdkDir, + { + cwd: sdkDir, stdio: 'inherit', - } - ); - } + } + ); + } } break; } diff --git a/sdk-reference-generator/src/navigation.ts b/sdk-reference-generator/src/navigation.ts index 7c7b7e7..050262d 100644 --- a/sdk-reference-generator/src/navigation.ts +++ b/sdk-reference-generator/src/navigation.ts @@ -1,6 +1,6 @@ import fs from "fs-extra"; import path from "path"; -import { loadConfig } from "./lib/config.js"; +import { getConfig } from "./lib/config.js"; import { sortVersionsDescending } from "./lib/utils.js"; import { CONSTANTS } from "./lib/constants.js"; import { log } from "./lib/log.js"; @@ -41,7 +41,7 @@ async function getModules(versionDir: string): Promise { export async function buildNavigation( docsDir: string ): Promise { - const config = await loadConfig(); + const config = await getConfig(); const sdkRefDir = path.join(docsDir, CONSTANTS.DOCS_SDK_REF_PATH); if (!(await fs.pathExists(sdkRefDir))) { diff --git a/sdk-reference-generator/src/types.ts b/sdk-reference-generator/src/types.ts index 790a46d..d7e35dc 100644 --- a/sdk-reference-generator/src/types.ts +++ b/sdk-reference-generator/src/types.ts @@ -1,30 +1,37 @@ -import { z } from "zod"; - -export const GeneratorType = z.enum(["typedoc", "pydoc", "cli"]); -export type GeneratorType = z.infer; - -export const SDKConfigSchema = z.object({ - displayName: z.string(), - icon: z.string(), - order: z.number(), - repo: z.string().url(), - tagPattern: z.string(), - tagFormat: z.string(), - generator: GeneratorType, - required: z.boolean(), - minVersion: z.string().optional(), - sdkPath: z.string().optional(), - sdkPaths: z.array(z.string()).optional(), - fallbackPackages: z.array(z.string()).optional().describe('Used if auto-discovery fails'), - submodules: z.record(z.string(), z.array(z.string())).optional(), - basePackage: z.string().optional().describe('Base Python package name for discovery'), -}); -export type SDKConfig = z.infer; - -export const ConfigFileSchema = z.object({ - sdks: z.record(z.string(), SDKConfigSchema), -}); -export type ConfigFile = z.infer; +type BaseSDKConfig = { + displayName: string; + icon: string; + order: number; + repo: string; + tagPattern: string; + tagFormat: string; + required: boolean; + minVersion?: string; + sdkPath?: string; + sdkPaths?: string[]; +}; + +type TypedocSDKConfig = BaseSDKConfig & { + generator: "typedoc"; +}; + +type PydocSDKConfig = BaseSDKConfig & { + generator: "pydoc"; + basePackage: string; + fallbackPackages?: readonly string[]; + submodules?: Record; +}; + +type CLISDKConfig = BaseSDKConfig & { + generator: "cli"; +}; + +export type SDKConfig = TypedocSDKConfig | PydocSDKConfig | CLISDKConfig; +export type GeneratorType = SDKConfig["generator"]; + +export type ConfigFile = { + sdks: Record; +}; export interface GenerationContext { tempDir: string; diff --git a/sdk-reference-generator/tsconfig.json b/sdk-reference-generator/tsconfig.json index 3ac3cc8..33193b1 100644 --- a/sdk-reference-generator/tsconfig.json +++ b/sdk-reference-generator/tsconfig.json @@ -7,12 +7,11 @@ "strict": true, "skipLibCheck": true, "outDir": "dist", - "rootDir": "src", "declaration": true, "resolveJsonModule": true, "allowSyntheticDefaultImports": true }, - "include": ["src/**/*"], + "include": ["src/**/*", "sdks.config.ts"], "exclude": ["node_modules", "dist"] } From 24b4430966fe91e0a83396422c5cbb1608fee612 Mon Sep 17 00:00:00 2001 From: ben-fornefeld Date: Thu, 8 Jan 2026 12:54:20 +0100 Subject: [PATCH 12/39] refactor: improve SDK reference generation and navigation - Updated CSS styles for version switcher to enhance UI consistency and usability. - Modified GitHub Actions workflow to streamline SDK generation input descriptions and improve summary output. - Refactored context handling in SDK generation functions for better clarity and maintainability. - Introduced new utility functions for version validation and normalization, enhancing version management. - Added tests for cache handling and file processing to ensure robustness in SDK reference generation. --- .github/workflows/sdk-reference-sync.yml | 15 +- .../src/__tests__/cache.test.ts | 127 ++++++++++ .../src/__tests__/files.test.ts | 69 +++-- .../src/__tests__/git.test.ts | 143 +++++++++++ sdk-reference-generator/src/cli.ts | 4 +- sdk-reference-generator/src/generator.ts | 235 +++++++++++------- .../src/generators/index.ts | 4 +- .../src/generators/pydoc.ts | 3 - sdk-reference-generator/src/lib/cache.ts | 44 ++-- sdk-reference-generator/src/lib/files.ts | 66 +++-- sdk-reference-generator/src/lib/git.ts | 71 ++++-- sdk-reference-generator/src/lib/utils.ts | 12 +- sdk-reference-generator/src/lib/versions.ts | 10 +- sdk-reference-generator/src/navigation.ts | 16 +- style.css | 16 +- 15 files changed, 636 insertions(+), 199 deletions(-) create mode 100644 sdk-reference-generator/src/__tests__/cache.test.ts create mode 100644 sdk-reference-generator/src/__tests__/git.test.ts diff --git a/.github/workflows/sdk-reference-sync.yml b/.github/workflows/sdk-reference-sync.yml index 041cec4..d66f563 100644 --- a/.github/workflows/sdk-reference-sync.yml +++ b/.github/workflows/sdk-reference-sync.yml @@ -5,19 +5,10 @@ on: workflow_dispatch: inputs: sdk: - description: "SDK to generate (js-sdk, python-sdk, cli, code-interpreter-js-sdk, code-interpreter-python-sdk, desktop-js-sdk, desktop-python-sdk, all)" + description: "SDK to generate (see sdks.config.ts for available SDKs, or use 'all')" required: true default: "all" - type: choice - options: - - all - - js-sdk - - python-sdk - - cli - - code-interpreter-js-sdk - - code-interpreter-python-sdk - - desktop-js-sdk - - desktop-python-sdk + type: string version: description: "Version to generate (all, latest, or specific like v2.9.0)" required: true @@ -120,6 +111,6 @@ jobs: echo "" >> $GITHUB_STEP_SUMMARY echo "### Generated Files" >> $GITHUB_STEP_SUMMARY echo '```' >> $GITHUB_STEP_SUMMARY - find docs/sdk-reference -type f -name "*.mdx" | wc -l | xargs echo "Total MDX files:" + find docs/sdk-reference -type f -name "*.mdx" | wc -l | xargs echo "Total MDX files:" >> $GITHUB_STEP_SUMMARY find docs/sdk-reference -type f -name "*.mdx" >> $GITHUB_STEP_SUMMARY || true echo '```' >> $GITHUB_STEP_SUMMARY diff --git a/sdk-reference-generator/src/__tests__/cache.test.ts b/sdk-reference-generator/src/__tests__/cache.test.ts new file mode 100644 index 0000000..128aa49 --- /dev/null +++ b/sdk-reference-generator/src/__tests__/cache.test.ts @@ -0,0 +1,127 @@ +import { describe, it, expect, vi, beforeEach, afterEach } from "vitest"; +import path from "path"; +import fs from "fs-extra"; +import { hashLockfile } from "../lib/cache.js"; + +// mock fs-extra +vi.mock("fs-extra"); + +describe("hashLockfile", () => { + beforeEach(() => { + vi.clearAllMocks(); + }); + + afterEach(() => { + vi.restoreAllMocks(); + }); + + it("finds lockfile in current directory", async () => { + const mockPathExists = vi.mocked(fs.pathExists); + const mockReadFile = vi.mocked(fs.readFile); + + mockPathExists.mockImplementation((p: string) => { + return Promise.resolve(p === path.join("/test/dir", "pnpm-lock.yaml")); + }); + + mockReadFile.mockImplementation(() => { + return Promise.resolve(Buffer.from("lockfile content")); + }); + + const result = await hashLockfile("/test/dir", "typedoc"); + + expect(result).not.toBeNull(); + expect(result).toHaveLength(32); + expect(mockPathExists).toHaveBeenCalledWith( + path.join("/test/dir", "pnpm-lock.yaml") + ); + }); + + it("finds lockfile in parent directory", async () => { + const mockPathExists = vi.mocked(fs.pathExists); + const mockReadFile = vi.mocked(fs.readFile); + + mockPathExists.mockImplementation((p: string) => { + return Promise.resolve(p === path.join("/test", "pnpm-lock.yaml")); + }); + + mockReadFile.mockImplementation(() => { + return Promise.resolve(Buffer.from("parent lockfile")); + }); + + const result = await hashLockfile("/test/dir/subdir", "typedoc"); + + expect(result).not.toBeNull(); + }); + + it("stops at filesystem root without infinite loop (Unix)", async () => { + const mockPathExists = vi.mocked(fs.pathExists); + mockPathExists.mockImplementation(() => Promise.resolve(false)); + + const result = await hashLockfile("/deep/nested/dir", "typedoc"); + + expect(result).toBeNull(); + expect(mockPathExists.mock.calls.length).toBeLessThan(20); + }); + + it("stops at filesystem root without infinite loop (Windows-style path)", async () => { + const mockPathExists = vi.mocked(fs.pathExists); + mockPathExists.mockImplementation(() => Promise.resolve(false)); + + const result = await hashLockfile("C:\\deep\\nested\\dir", "typedoc"); + + expect(result).toBeNull(); + expect(mockPathExists.mock.calls.length).toBeLessThan(20); + }); + + it("returns null when no lockfile found", async () => { + const mockPathExists = vi.mocked(fs.pathExists); + mockPathExists.mockImplementation(() => Promise.resolve(false)); + + const result = await hashLockfile("/test/dir", "typedoc"); + + expect(result).toBeNull(); + }); + + it("tries multiple lockfile patterns in order", async () => { + const mockPathExists = vi.mocked(fs.pathExists); + const mockReadFile = vi.mocked(fs.readFile); + + mockPathExists.mockImplementation((p: string) => { + return Promise.resolve(p.includes("package-lock.json")); + }); + + mockReadFile.mockImplementation(() => { + return Promise.resolve(Buffer.from("npm lockfile")); + }); + + const result = await hashLockfile("/test/dir", "typedoc"); + + expect(result).not.toBeNull(); + expect(mockPathExists).toHaveBeenCalledWith( + path.join("/test/dir", "pnpm-lock.yaml") + ); + expect(mockPathExists).toHaveBeenCalledWith( + path.join("/test/dir", "package-lock.json") + ); + }); + + it("handles pydoc generator with poetry.lock", async () => { + const mockPathExists = vi.mocked(fs.pathExists); + const mockReadFile = vi.mocked(fs.readFile); + + mockPathExists.mockImplementation((p: string) => { + return Promise.resolve(p.includes("poetry.lock")); + }); + + mockReadFile.mockImplementation(() => { + return Promise.resolve(Buffer.from("poetry lockfile")); + }); + + const result = await hashLockfile("/test/python-project", "pydoc"); + + expect(result).not.toBeNull(); + expect(mockPathExists).toHaveBeenCalledWith( + path.join("/test/python-project", "poetry.lock") + ); + }); +}); diff --git a/sdk-reference-generator/src/__tests__/files.test.ts b/sdk-reference-generator/src/__tests__/files.test.ts index a9a5082..63ac8c4 100644 --- a/sdk-reference-generator/src/__tests__/files.test.ts +++ b/sdk-reference-generator/src/__tests__/files.test.ts @@ -1,29 +1,64 @@ -import { describe, it, expect } from 'vitest'; -import { toTitleCase } from '../lib/files.js'; +import { describe, it, expect } from "vitest"; +import { toTitleCase, extractTitle } from "../lib/files.js"; -describe('toTitleCase', () => { - it('converts snake_case to Title Case', () => { - expect(toTitleCase('sandbox_sync')).toBe('Sandbox Sync'); - expect(toTitleCase('sandbox_async')).toBe('Sandbox Async'); - expect(toTitleCase('template_async')).toBe('Template Async'); +describe("toTitleCase", () => { + it("converts snake_case to Title Case", () => { + expect(toTitleCase("sandbox_sync")).toBe("Sandbox Sync"); + expect(toTitleCase("sandbox_async")).toBe("Sandbox Async"); + expect(toTitleCase("template_async")).toBe("Template Async"); }); - it('capitalizes single words', () => { - expect(toTitleCase('sandbox')).toBe('Sandbox'); - expect(toTitleCase('exceptions')).toBe('Exceptions'); + it("capitalizes single words", () => { + expect(toTitleCase("sandbox")).toBe("Sandbox"); + expect(toTitleCase("exceptions")).toBe("Exceptions"); }); - it('handles already capitalized words', () => { - expect(toTitleCase('Sandbox')).toBe('Sandbox'); - expect(toTitleCase('SANDBOX')).toBe('SANDBOX'); + it("handles already capitalized words", () => { + expect(toTitleCase("Sandbox")).toBe("Sandbox"); + expect(toTitleCase("SANDBOX")).toBe("SANDBOX"); }); - it('handles empty string', () => { - expect(toTitleCase('')).toBe(''); + it("handles empty string", () => { + expect(toTitleCase("")).toBe(""); }); - it('handles multiple underscores', () => { - expect(toTitleCase('a_b_c')).toBe('A B C'); + it("handles multiple underscores", () => { + expect(toTitleCase("a_b_c")).toBe("A B C"); }); }); +describe("extractTitle", () => { + it("strips directory prefix from flattened filenames", () => { + expect(extractTitle("modules-Sandbox")).toBe("Sandbox"); + expect(extractTitle("classes-MyClass")).toBe("MyClass"); + expect(extractTitle("interfaces-IUser")).toBe("IUser"); + expect(extractTitle("types-CustomType")).toBe("CustomType"); + }); + + it("handles nested directory prefixes", () => { + expect(extractTitle("modules-sandbox-Sandbox")).toBe("Sandbox"); + expect(extractTitle("classes-internal-MyClass")).toBe("MyClass"); + }); + + it("handles snake_case after prefix removal", () => { + expect(extractTitle("modules-sandbox_sync")).toBe("Sandbox Sync"); + expect(extractTitle("classes-my_class")).toBe("My Class"); + }); + + it("handles files without directory prefix", () => { + expect(extractTitle("Sandbox")).toBe("Sandbox"); + expect(extractTitle("sandbox_sync")).toBe("Sandbox Sync"); + }); + + it("handles empty string", () => { + expect(extractTitle("")).toBe(""); + }); + + it("handles edge cases correctly", () => { + // files with hyphenated prefixes get the prefix stripped + expect(extractTitle("some-file")).toBe("File"); + // files without hyphens are processed as-is + expect(extractTitle("MyClass")).toBe("MyClass"); + expect(extractTitle("simple")).toBe("Simple"); + }); +}); diff --git a/sdk-reference-generator/src/__tests__/git.test.ts b/sdk-reference-generator/src/__tests__/git.test.ts new file mode 100644 index 0000000..3d585d9 --- /dev/null +++ b/sdk-reference-generator/src/__tests__/git.test.ts @@ -0,0 +1,143 @@ +import { describe, it, expect, vi, beforeEach } from 'vitest'; + +const mockClone = vi.fn(); +const mockListRemote = vi.fn(); + +// mock simple-git before importing our module +vi.mock('simple-git', () => ({ + simpleGit: vi.fn(() => ({ + clone: mockClone, + listRemote: mockListRemote, + })), +})); + +// mock timers to avoid actual delays in tests +vi.useFakeTimers(); + +// now import our module after mocking +const { cloneAtTag } = await import('../lib/git.js'); + +describe('cloneAtTag', () => { + beforeEach(() => { + vi.clearAllMocks(); + mockClone.mockReset(); + mockListRemote.mockReset(); + }); + + it('succeeds on first attempt', async () => { + mockClone.mockResolvedValueOnce(undefined as any); + + await expect( + cloneAtTag('https://github.com/test/repo', 'v1.0.0', '/tmp/test') + ).resolves.toBeUndefined(); + + expect(mockClone).toHaveBeenCalledTimes(1); + expect(mockClone).toHaveBeenCalledWith( + 'https://github.com/test/repo', + '/tmp/test', + ['--depth', '1', '--branch', 'v1.0.0'] + ); + }); + + it('retries 3 times for tag-not-found errors', async () => { + const tagNotFoundError = new Error( + "fatal: Remote branch v1.0.0 not found in upstream origin" + ); + + mockClone + .mockRejectedValueOnce(tagNotFoundError) + .mockRejectedValueOnce(tagNotFoundError) + .mockRejectedValueOnce(tagNotFoundError); + + const promise = expect( + cloneAtTag('https://github.com/test/repo', 'v1.0.0', '/tmp/test') + ).rejects.toThrow(/Tag v1\.0\.0 not found in repository.*after 3 attempts/); + + // advance timers for all retry delays + await vi.runAllTimersAsync(); + await promise; + + expect(mockClone).toHaveBeenCalledTimes(3); + }); + + it('succeeds on second attempt after tag-not-found retry', async () => { + const tagNotFoundError = new Error( + "fatal: Remote branch v1.0.0 not found in upstream origin" + ); + + mockClone + .mockRejectedValueOnce(tagNotFoundError) + .mockResolvedValueOnce(undefined as any); + + const promise = expect( + cloneAtTag('https://github.com/test/repo', 'v1.0.0', '/tmp/test') + ).resolves.toBeUndefined(); + + // advance timers for retry delay + await vi.runAllTimersAsync(); + await promise; + + expect(mockClone).toHaveBeenCalledTimes(2); + }); + + it('throws immediately for network errors without retrying', async () => { + const networkError = new Error( + "fatal: unable to access 'https://github.com/test/repo': Could not resolve host" + ); + + mockClone.mockRejectedValueOnce(networkError); + + await expect( + cloneAtTag('https://github.com/test/repo', 'v1.0.0', '/tmp/test') + ).rejects.toThrow(/Failed to clone repository.*network, authentication, or system error/); + + // should NOT retry for network errors + expect(mockClone).toHaveBeenCalledTimes(1); + }); + + it('throws immediately for authentication errors without retrying', async () => { + const authError = new Error( + "fatal: Authentication failed for 'https://github.com/test/repo'" + ); + + mockClone.mockRejectedValueOnce(authError); + + await expect( + cloneAtTag('https://github.com/test/repo', 'v1.0.0', '/tmp/test') + ).rejects.toThrow(/Failed to clone repository.*network, authentication, or system error/); + + expect(mockClone).toHaveBeenCalledTimes(1); + }); + + it('recognizes various tag-not-found error formats', async () => { + const errorFormats = [ + "fatal: Remote branch v1.0.0 not found in upstream origin", + "fatal: couldn't find remote ref v1.0.0", + "error: invalid refspec 'v1.0.0'", + "fatal: reference is not a tree: v1.0.0", + ]; + + for (const errorMessage of errorFormats) { + vi.clearAllMocks(); + mockClone.mockReset(); + const error = new Error(errorMessage); + + mockClone + .mockRejectedValueOnce(error) + .mockRejectedValueOnce(error) + .mockRejectedValueOnce(error); + + const promise = expect( + cloneAtTag('https://github.com/test/repo', 'v1.0.0', '/tmp/test') + ).rejects.toThrow(/Tag v1\.0\.0 not found/); + + // advance timers for all retry delays + await vi.runAllTimersAsync(); + await promise; + + // should retry for all tag-not-found formats + expect(mockClone).toHaveBeenCalledTimes(3); + } + }); +}); + diff --git a/sdk-reference-generator/src/cli.ts b/sdk-reference-generator/src/cli.ts index 8228ca4..2eaa903 100644 --- a/sdk-reference-generator/src/cli.ts +++ b/sdk-reference-generator/src/cli.ts @@ -54,7 +54,7 @@ async function main(): Promise { ]); log.blank(); - const ctx: GenerationContext = { + const context: GenerationContext = { tempDir, docsDir: DOCS_DIR, configsDir: CONFIGS_DIR, @@ -69,7 +69,7 @@ async function main(): Promise { for (const sdkKey of sdkKeys) { log.section(`Generating ${sdkKey}`); - const result = await generateSDK(sdkKey, opts.version, ctx); + const result = await generateSDK(sdkKey, opts.version, context); results.set(sdkKey, result); } diff --git a/sdk-reference-generator/src/generator.ts b/sdk-reference-generator/src/generator.ts index f8f95cf..32b31d8 100644 --- a/sdk-reference-generator/src/generator.ts +++ b/sdk-reference-generator/src/generator.ts @@ -28,13 +28,15 @@ async function generateVersion( sdkKey: string, config: SDKConfig, version: string, - ctx: GenerationContext + context: GenerationContext ): Promise { - const repoDir = path.join(ctx.tempDir, `${sdkKey}-${version}`); + const repoDir = path.join(context.tempDir, `${sdkKey}-${version}`); try { - const versionWithoutV = version.replace(/^v/, ""); - const tagName = config.tagFormat.replace("{version}", versionWithoutV); + const tagName = config.tagFormat.replace( + "{version}", + version.replace(/^v/, "") + ); await cloneAtTag(config.repo, tagName, repoDir); @@ -45,9 +47,8 @@ async function generateVersion( ); } - await installWithCache(sdkDir, config.generator, ctx.tempDir); - - const generatedDocsDir = await runGenerator(sdkDir, config, ctx); + await installWithCache(sdkDir, config.generator, context.tempDir); + const generatedDocsDir = await runGenerator(sdkDir, config, context); const sdkRefDir = path.join(sdkDir, CONSTANTS.SDK_REF_DIR); if (generatedDocsDir !== sdkRefDir) { @@ -57,7 +58,7 @@ async function generateVersion( await flattenMarkdown(sdkRefDir); - const destDir = buildSDKPath(ctx.docsDir, sdkKey, version); + const destDir = buildSDKPath(context.docsDir, sdkKey, version); const success = await copyToDocs( sdkRefDir, destDir, @@ -73,119 +74,123 @@ async function generateVersion( } } -export async function generateSDK( +async function discoverAllVersions( sdkKey: string, - versionArg: string, - ctx: GenerationContext -): Promise { - const config = await getSDKConfig(sdkKey); - - if (!config) { - log.error(`SDK '${sdkKey}' not found in config`, 1); - return { generated: 0, failed: 1, failedVersions: [sdkKey] }; - } - - log.info(`${config.displayName} version: ${versionArg}`, 1); - - let versionsToProcess: string[] = []; - - if (versionArg === "all") { - log.info("Discovering all versions...", 1); + config: SDKConfig, + context: GenerationContext +): Promise { + log.info("Discovering all versions...", 1); - let remote = await fetchRemoteTags(config.repo, config.tagPattern); + let remote = await fetchRemoteTags(config.repo, config.tagPattern); - if (remote.length === 0) { - if (config.required) { - log.error("No tags found", 1); - return { generated: 0, failed: 1, failedVersions: ["no-tags"] }; - } - log.warn("No tags found, skipping...", 1); - return { generated: 0, failed: 0, failedVersions: [] }; + if (remote.length === 0) { + if (config.required) { + log.error("No tags found", 1); + process.exit(1); } + log.warn("No tags found, skipping...", 1); + return []; + } - if (config.minVersion) { - remote = filterByMinVersion(remote, config.minVersion); - log.info(`Filtered to versions >= ${config.minVersion}`, 1); - } + if (config.minVersion) { + remote = filterByMinVersion(remote, config.minVersion); + log.info(`Filtered to versions >= ${config.minVersion}`, 1); + } - if (ctx.limit && ctx.limit > 0) { - remote = remote.slice(0, ctx.limit); - log.info(`Limited to last ${ctx.limit} versions`, 1); - } + if (context.limit && context.limit > 0) { + remote = remote.slice(0, context.limit); + log.info(`Limited to last ${context.limit} versions`, 1); + } - const local = await fetchLocalVersions(sdkKey, ctx.docsDir); + const local = await fetchLocalVersions(sdkKey, context.docsDir); - log.blank(); - log.step("Version Discovery", 1); - log.stats( - [ - { label: "Remote", value: remote.length }, - { label: "Local", value: local.length }, - ], - 1 - ); + log.blank(); + log.step("Version Discovery", 1); + log.stats( + [ + { label: "Remote", value: remote.length }, + { label: "Local", value: local.length }, + ], + 1 + ); - const missing = ctx.force ? remote : diffVersions(remote, local); + const missing = context.force ? remote : diffVersions(remote, local); - log.stats( - [ - { - label: ctx.force ? "To Generate (forced)" : "Missing", - value: missing.length, - }, - ], - 1 - ); - log.blank(); + log.stats( + [ + { + label: context.force ? "To Generate (forced)" : "Missing", + value: missing.length, + }, + ], + 1 + ); + log.blank(); - if (missing.length === 0) { - log.success("Nothing to generate", 1); - return { generated: 0, failed: 0, failedVersions: [] }; - } + if (missing.length === 0) { + log.success("Nothing to generate", 1); + return []; + } - if (ctx.force && local.length > 0) { - log.warn("FORCE MODE: Will regenerate existing versions", 1); - } + if (context.force && local.length > 0) { + log.warn("FORCE MODE: Will regenerate existing versions", 1); + } - versionsToProcess = missing; - } else { - const resolved = await resolveLatestVersion( - config.repo, - config.tagPattern, - versionArg - ); + return missing; +} - if (!resolved) { - if (config.required) { - log.error("No tags found", 1); - return { generated: 0, failed: 1, failedVersions: ["no-tags"] }; - } - log.warn("No tags found, skipping...", 1); - return { generated: 0, failed: 0, failedVersions: [] }; - } +async function resolveSpecificVersion( + sdkKey: string, + config: SDKConfig, + versionArg: string, + context: GenerationContext +): Promise { + const resolved = await resolveLatestVersion( + config.repo, + config.tagPattern, + versionArg + ); - if (!ctx.force && (await versionExists(sdkKey, resolved, ctx.docsDir))) { - log.success(`${resolved} already exists`, 1); - return { generated: 0, failed: 0, failedVersions: [] }; + if (!resolved) { + if (config.required) { + log.error("No tags found", 1); + process.exit(1); } + log.warn("No tags found, skipping...", 1); + return []; + } - if (ctx.force) { - log.warn("FORCE MODE: Will regenerate existing version", 1); - } + if ( + !context.force && + (await versionExists(sdkKey, resolved, context.docsDir)) + ) { + log.success(`${resolved} already exists`, 1); + return []; + } - versionsToProcess = [resolved]; + if (context.force) { + log.warn("FORCE MODE: Will regenerate existing version", 1); } + return [resolved]; +} + +async function processVersionBatch( + sdkKey: string, + config: SDKConfig, + versions: string[], + context: GenerationContext +): Promise { let generated = 0; let failed = 0; const failedVersions: string[] = []; - for (const version of versionsToProcess) { + for (const version of versions) { log.blank(); log.step(`Generating ${version}`, 1); try { - await generateVersion(sdkKey, config, version, ctx); + await generateVersion(sdkKey, config, version, context); log.success(`Complete: ${version}`, 1); generated++; } catch (error) { @@ -196,6 +201,15 @@ export async function generateSDK( } } + return { generated, failed, failedVersions }; +} + +function handleGenerationFailures( + config: SDKConfig, + result: GenerationResult +): void { + const { generated, failed, failedVersions } = result; + log.blank(); log.step("Summary", 1); log.stats( @@ -226,6 +240,39 @@ export async function generateSDK( process.exit(1); } } +} - return { generated, failed, failedVersions }; +export async function generateSDK( + sdkKey: string, + versionArg: string, + context: GenerationContext +): Promise { + const config = await getSDKConfig(sdkKey); + + if (!config) { + log.error(`SDK '${sdkKey}' not found in config`, 1); + return { generated: 0, failed: 1, failedVersions: [sdkKey] }; + } + + log.info(`${config.displayName} version: ${versionArg}`, 1); + + const versionsToProcess = + versionArg === "all" + ? await discoverAllVersions(sdkKey, config, context) + : await resolveSpecificVersion(sdkKey, config, versionArg, context); + + if (versionsToProcess.length === 0) { + return { generated: 0, failed: 0, failedVersions: [] }; + } + + const result = await processVersionBatch( + sdkKey, + config, + versionsToProcess, + context + ); + + handleGenerationFailures(config, result); + + return result; } diff --git a/sdk-reference-generator/src/generators/index.ts b/sdk-reference-generator/src/generators/index.ts index 1dbf60c..18c4639 100644 --- a/sdk-reference-generator/src/generators/index.ts +++ b/sdk-reference-generator/src/generators/index.ts @@ -6,11 +6,11 @@ import { generateCli } from "./cli.js"; export async function runGenerator( sdkDir: string, config: SDKConfig, - ctx: GenerationContext + context: GenerationContext ): Promise { switch (config.generator) { case "typedoc": - return await generateTypedoc(sdkDir, ctx.configsDir); + return await generateTypedoc(sdkDir, context.configsDir); case "pydoc": return await generatePydoc( diff --git a/sdk-reference-generator/src/generators/pydoc.ts b/sdk-reference-generator/src/generators/pydoc.ts index 427df6f..9c91352 100644 --- a/sdk-reference-generator/src/generators/pydoc.ts +++ b/sdk-reference-generator/src/generators/pydoc.ts @@ -65,14 +65,11 @@ async function processMdx(file: string): Promise { let content = await fs.readFile(file, "utf-8"); content = content.replace(/]*>.*?<\/a>/g, ""); - content = content .split("\n") .filter((line) => !line.startsWith("# ")) .join("\n"); - content = content.replace(/^(## .+) Objects$/gm, "$1"); - content = content.replace(/^####/gm, "###"); await fs.writeFile(file, content); diff --git a/sdk-reference-generator/src/lib/cache.ts b/sdk-reference-generator/src/lib/cache.ts index 3e91785..7406d3a 100644 --- a/sdk-reference-generator/src/lib/cache.ts +++ b/sdk-reference-generator/src/lib/cache.ts @@ -1,12 +1,12 @@ -import { createHash } from 'crypto'; -import fs from 'fs-extra'; -import path from 'path'; -import type { GeneratorType } from '../types.js'; +import { createHash } from "crypto"; +import fs from "fs-extra"; +import path from "path"; +import type { GeneratorType } from "../types.js"; const LOCKFILES: Record = { - typedoc: ['pnpm-lock.yaml', 'package-lock.json'], - cli: ['pnpm-lock.yaml', 'package-lock.json'], - pydoc: ['poetry.lock'], + typedoc: ["pnpm-lock.yaml", "package-lock.json"], + cli: ["pnpm-lock.yaml", "package-lock.json"], + pydoc: ["poetry.lock"], }; async function findLockfileUp( @@ -15,12 +15,17 @@ async function findLockfileUp( ): Promise { let current = dir; - while (current !== '/' && current !== '.') { + while (true) { const lockPath = path.join(current, filename); if (await fs.pathExists(lockPath)) { return lockPath; } - current = path.dirname(current); + + const parent = path.dirname(current); + if (parent === current) { + break; + } + current = parent; } return null; @@ -35,8 +40,8 @@ export async function hashLockfile( for (const filename of lockfiles) { const lockPath = await findLockfileUp(sdkDir, filename); if (lockPath) { - const content = await fs.readFile(lockPath, 'utf-8'); - return createHash('md5').update(content).digest('hex'); + const content = await fs.readFile(lockPath, "utf-8"); + return createHash("md5").update(content).digest("hex"); } } @@ -48,7 +53,12 @@ export async function isCached( generator: GeneratorType, tempDir: string ): Promise { - const marker = path.join(tempDir, '.deps-cache', `${generator}-${hash}`, '.installed'); + const marker = path.join( + tempDir, + ".deps-cache", + `${generator}-${hash}`, + ".installed" + ); return fs.pathExists(marker); } @@ -57,8 +67,12 @@ export async function markCached( generator: GeneratorType, tempDir: string ): Promise { - const marker = path.join(tempDir, '.deps-cache', `${generator}-${hash}`, '.installed'); + const marker = path.join( + tempDir, + ".deps-cache", + `${generator}-${hash}`, + ".installed" + ); await fs.ensureDir(path.dirname(marker)); - await fs.writeFile(marker, ''); + await fs.writeFile(marker, ""); } - diff --git a/sdk-reference-generator/src/lib/files.ts b/sdk-reference-generator/src/lib/files.ts index b304eb5..63a467c 100644 --- a/sdk-reference-generator/src/lib/files.ts +++ b/sdk-reference-generator/src/lib/files.ts @@ -14,6 +14,29 @@ export function toTitleCase(str: string): string { .join(" "); } +/** + * Extracts a clean title from a flattened filename. + * Removes directory prefixes added during flattening. + * + * @example + * extractTitle('modules-Sandbox') // 'Sandbox' + * extractTitle('classes-MyClass') // 'MyClass' + * extractTitle('sandbox_sync') // 'Sandbox Sync' + * extractTitle('modules-sandbox_sync') // 'Sandbox Sync' + */ +export function extractTitle(filename: string): string { + if (!filename) return ""; + + const prefixMatch = filename.match(/^([a-z]+-)+(.+)$/); + + if (prefixMatch) { + const withoutPrefix = prefixMatch[2]; + return toTitleCase(withoutPrefix); + } + + return toTitleCase(filename); +} + export async function addFrontmatter( file: string, title: string @@ -36,20 +59,36 @@ export async function flattenMarkdown(refDir: string): Promise { ignore: "*.md", }); + const targetFiles = new Set(); + const collisions: string[] = []; + for (const file of nestedFiles) { const filename = path.basename(file); const parentDirName = path.basename(path.dirname(file)); + const dirPath = path.dirname(file).replace(/\//g, "-"); - const targetName = - filename === "page.md" || filename === "index.md" - ? `${parentDirName}.md` - : filename; + let targetName: string; - await fs.move( - path.join(refDir, file), - path.join(refDir, targetName), - { overwrite: true } - ); + if (filename === "page.md" || filename === "index.md") { + targetName = `${parentDirName}.md`; + } else { + const baseName = path.basename(filename, ".md"); + targetName = `${dirPath}-${baseName}.md`; + } + + if (targetFiles.has(targetName)) { + collisions.push(`${file} → ${targetName}`); + } + targetFiles.add(targetName); + + await fs.move(path.join(refDir, file), path.join(refDir, targetName), { + overwrite: false, + }); + } + + if (collisions.length > 0) { + log.warn(`Detected ${collisions.length} filename collision(s):`, 1); + collisions.forEach((c) => log.data(c, 2)); } const dirs = await glob("**/", { cwd: refDir }); @@ -67,7 +106,7 @@ export async function flattenMarkdown(refDir: string): Promise { for (const file of mdFiles) { const fullPath = path.join(refDir, file); - const title = toTitleCase(path.basename(file, CONSTANTS.MD_EXTENSION)); + const title = extractTitle(path.basename(file, CONSTANTS.MD_EXTENSION)); const content = await fs.readFile(fullPath, "utf-8"); const mdxPath = fullPath.replace( @@ -85,7 +124,7 @@ export async function flattenMarkdown(refDir: string): Promise { const content = await fs.readFile(fullPath, "utf-8"); if (!content.startsWith("---")) { - const title = toTitleCase(path.basename(file, CONSTANTS.MDX_EXTENSION)); + const title = extractTitle(path.basename(file, CONSTANTS.MDX_EXTENSION)); await addFrontmatter(fullPath, title); } } @@ -128,10 +167,7 @@ export async function copyToDocs( log.info(`Copying ${files.length} files to ${destDir}`, 1); for (const file of files) { - await fs.copy( - path.join(srcDir, file), - path.join(destDir, file) - ); + await fs.copy(path.join(srcDir, file), path.join(destDir, file)); } log.success(`${sdkName} ${version} complete`, 1); diff --git a/sdk-reference-generator/src/lib/git.ts b/sdk-reference-generator/src/lib/git.ts index d945396..f15f4a1 100644 --- a/sdk-reference-generator/src/lib/git.ts +++ b/sdk-reference-generator/src/lib/git.ts @@ -1,6 +1,6 @@ -import { simpleGit, SimpleGit } from 'simple-git'; -import { sortVersionsDescending } from './utils.js'; -import { log } from './log.js'; +import { simpleGit, SimpleGit } from "simple-git"; +import { sortVersionsDescending } from "./utils.js"; +import { log } from "./log.js"; const git: SimpleGit = simpleGit(); @@ -8,33 +8,77 @@ export async function fetchRemoteTags( repo: string, tagPattern: string ): Promise { - const output = await git.listRemote(['--tags', '--refs', repo]); + const output = await git.listRemote(["--tags", "--refs", repo]); const versions = output - .split('\n') + .split("\n") .filter((line: string) => line.includes(`refs/tags/${tagPattern}`)) .map((line: string) => { const match = line.match(/refs\/tags\/(.+)$/); if (!match) return null; const tag = match[1]; - return 'v' + tag.replace(tagPattern, ''); + return "v" + tag.replace(tagPattern, ""); }) - .filter((v: string | null): v is string => v !== null && v !== 'v'); + .filter((v: string | null): v is string => v !== null && v !== "v"); return sortVersionsDescending(versions); } +function isTagNotFoundError(error: unknown): boolean { + if (!(error instanceof Error)) return false; + + const message = error.message.toLowerCase(); + return ( + (message.includes("remote branch") && message.includes("not found")) || + message.includes("couldn't find remote ref") || + message.includes("invalid refspec") || + message.includes("reference is not a tree") + ); +} + +async function sleep(ms: number): Promise { + return new Promise((resolve) => setTimeout(resolve, ms)); +} + export async function cloneAtTag( repo: string, tag: string, targetDir: string ): Promise { - try { - await git.clone(repo, targetDir, ['--depth', '1', '--branch', tag]); - } catch { - log.warn(`Tag ${tag} not found, trying default branch...`, 1); - await git.clone(repo, targetDir, ['--depth', '1']); + const maxRetries = 3; + let lastError: Error | null = null; + + for (let attempt = 1; attempt <= maxRetries; attempt++) { + try { + await git.clone(repo, targetDir, ["--depth", "1", "--branch", tag]); + return; + } catch (error) { + lastError = error instanceof Error ? error : new Error(String(error)); + + // only retry if it's a tag-not-found error + if (!isTagNotFoundError(error)) { + throw new Error( + `Failed to clone repository: ${lastError.message}. ` + + `This appears to be a network, authentication, or system error, not a missing tag.` + ); + } + + if (attempt < maxRetries) { + const backoffMs = attempt * 1000; + log.warn( + `Tag ${tag} not found (attempt ${attempt}/${maxRetries}), retrying in ${backoffMs}ms...`, + 1 + ); + await sleep(backoffMs); + } + } } + + throw new Error( + `Tag ${tag} not found in repository ${repo} after ${maxRetries} attempts. ` + + `Cancelling generation to avoid publishing incorrect documentation. ` + + `Original error: ${lastError?.message}` + ); } export async function resolveLatestVersion( @@ -42,11 +86,10 @@ export async function resolveLatestVersion( tagPattern: string, version: string ): Promise { - if (version !== 'latest') { + if (version !== "latest") { return version; } const versions = await fetchRemoteTags(repo, tagPattern); return versions[0] || null; } - diff --git a/sdk-reference-generator/src/lib/utils.ts b/sdk-reference-generator/src/lib/utils.ts index 4b13ccb..ee8f112 100644 --- a/sdk-reference-generator/src/lib/utils.ts +++ b/sdk-reference-generator/src/lib/utils.ts @@ -2,14 +2,22 @@ import semver from "semver"; import path from "path"; import { CONSTANTS } from "./constants.js"; -export function stripV(version: string): string { +export function normalizeVersion(version: string): string { + return version.startsWith("v") ? version : `v${version}`; +} + +export function stripVersionPrefix(version: string): string { return version.replace(/^v/, ""); } +export function isValidVersion(version: string): boolean { + return /^v?\d+\.\d+\.\d+/.test(version); +} + export function sortVersionsDescending(versions: string[]): string[] { return versions.sort((a, b) => { try { - return semver.rcompare(stripV(a), stripV(b)); + return semver.rcompare(stripVersionPrefix(a), stripVersionPrefix(b)); } catch { return b.localeCompare(a); } diff --git a/sdk-reference-generator/src/lib/versions.ts b/sdk-reference-generator/src/lib/versions.ts index 6aa12e5..595cf8c 100644 --- a/sdk-reference-generator/src/lib/versions.ts +++ b/sdk-reference-generator/src/lib/versions.ts @@ -1,18 +1,16 @@ import fs from 'fs-extra'; import path from 'path'; import semver from 'semver'; -import { stripV, sortVersionsDescending } from './utils.js'; +import { stripVersionPrefix, sortVersionsDescending, isValidVersion } from './utils.js'; import { CONSTANTS } from './constants.js'; -export function isValidVersion(version: string): boolean { - return /^v?\d+\.\d+\.\d+/.test(version); -} +export { isValidVersion }; export function versionGte(v1: string, v2: string): boolean { try { - return semver.gte(stripV(v1), stripV(v2)); + return semver.gte(stripVersionPrefix(v1), stripVersionPrefix(v2)); } catch { - return stripV(v1) >= stripV(v2); + return stripVersionPrefix(v1) >= stripVersionPrefix(v2); } } diff --git a/sdk-reference-generator/src/navigation.ts b/sdk-reference-generator/src/navigation.ts index 050262d..c9448c7 100644 --- a/sdk-reference-generator/src/navigation.ts +++ b/sdk-reference-generator/src/navigation.ts @@ -1,7 +1,11 @@ import fs from "fs-extra"; import path from "path"; import { getConfig } from "./lib/config.js"; -import { sortVersionsDescending } from "./lib/utils.js"; +import { + sortVersionsDescending, + isValidVersion, + normalizeVersion, +} from "./lib/utils.js"; import { CONSTANTS } from "./lib/constants.js"; import { log } from "./lib/log.js"; import type { @@ -14,10 +18,7 @@ async function getVersions(sdkDir: string): Promise { const entries = await fs.readdir(sdkDir, { withFileTypes: true }); const versions = entries - .filter((e) => { - if (!e.isDirectory()) return false; - return /^v?\d+\.\d+\.\d+/.test(e.name); - }) + .filter((e) => e.isDirectory() && isValidVersion(e.name)) .map((e) => e.name); return sortVersionsDescending(versions); @@ -74,12 +75,9 @@ export async function buildNavigation( versions.map(async (version, index) => { const versionDir = path.join(sdkDir, version); const modules = await getModules(versionDir); - const displayVersion = version.startsWith("v") - ? version - : `v${version}`; return { - version: displayVersion, + version: normalizeVersion(version), default: index === 0, pages: modules.map( (module) => diff --git a/style.css b/style.css index 63bba09..e4c3329 100644 --- a/style.css +++ b/style.css @@ -63,8 +63,8 @@ code { } /* Version switcher styles - subtle highlight */ -#sidebar ul:last-child li button, -#sidebar ul:last-child li select { +#sidebar ul:last-child:not(.sidebar-group) li button, +#sidebar ul:last-child:not(.sidebar-group) li select { background-color: rgba(255, 136, 0, 0.1) !important; /* 10% orange tint */ color: #ff8800 !important; /* Orange text */ border: 1px solid rgba(255, 136, 0, 0.3) !important; /* 30% orange border */ @@ -74,22 +74,22 @@ code { transition: all 0.2s ease !important; } -#sidebar ul:last-child li button:hover, -#sidebar ul:last-child li select:hover { +#sidebar ul:last-child:not(.sidebar-group) li button:hover, +#sidebar ul:last-child:not(.sidebar-group) li select:hover { background-color: rgba(255, 136, 0, 0.15) !important; /* Slightly darker on hover */ border-color: rgba(255, 136, 0, 0.5) !important; } /* Dark mode version switcher */ -.dark #sidebar ul:last-child li button, -.dark #sidebar ul:last-child li select { +.dark #sidebar ul:last-child:not(.sidebar-group) li button, +.dark #sidebar ul:last-child:not(.sidebar-group) li select { background-color: rgba(255, 136, 0, 0.15) !important; /* Slightly more visible in dark */ color: #ffaa44 !important; /* Lighter orange for contrast */ border-color: rgba(255, 136, 0, 0.4) !important; } -.dark #sidebar ul:last-child li button:hover, -.dark #sidebar ul:last-child li select:hover { +.dark #sidebar ul:last-child:not(.sidebar-group) li button:hover, +.dark #sidebar ul:last-child:not(.sidebar-group) li select:hover { background-color: rgba(255, 136, 0, 0.25) !important; border-color: rgba(255, 136, 0, 0.6) !important; } From 87e0c1d39b5dcca7187c476c7455692e4e1d78e7 Mon Sep 17 00:00:00 2001 From: ben-fornefeld Date: Thu, 8 Jan 2026 13:05:22 +0100 Subject: [PATCH 13/39] chore: remove package.json and pnpm-lock.yaml - Deleted `package.json` and `pnpm-lock.yaml` files to clean up the project structure as they are no longer needed for SDK reference generation. --- .github/workflows/sdk-reference-sync.yml | 3 - package.json | 18 - pnpm-lock.yaml | 461 ----------------------- 3 files changed, 482 deletions(-) delete mode 100644 package.json delete mode 100644 pnpm-lock.yaml diff --git a/.github/workflows/sdk-reference-sync.yml b/.github/workflows/sdk-reference-sync.yml index d66f563..8b02db6 100644 --- a/.github/workflows/sdk-reference-sync.yml +++ b/.github/workflows/sdk-reference-sync.yml @@ -46,9 +46,6 @@ jobs: with: python-version: "3.11" - - name: Install root dependencies - run: pnpm install - - name: Install generator dependencies working-directory: sdk-reference-generator run: pnpm install --frozen-lockfile diff --git a/package.json b/package.json deleted file mode 100644 index ac01fff..0000000 --- a/package.json +++ /dev/null @@ -1,18 +0,0 @@ -{ - "name": "e2b-docs", - "version": "1.0.0", - "private": true, - "description": "E2B Documentation - SDK Reference Generator", - "scripts": { - "generate-sdk-ref": "bash scripts/generate-sdk-reference.sh", - "generate-sdk-nav": "node scripts/generate-sdk-nav.js", - "merge-sdk-nav": "node scripts/merge-sdk-nav.js", - "generate-all": "pnpm run generate-sdk-ref -- --all" - }, - "devDependencies": { - "typedoc": "0.26.8", - "typedoc-plugin-markdown": "4.2.7", - "semver": "^7.7.2" - } -} - diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml deleted file mode 100644 index 2715af0..0000000 --- a/pnpm-lock.yaml +++ /dev/null @@ -1,461 +0,0 @@ -lockfileVersion: '9.0' - -settings: - autoInstallPeers: true - excludeLinksFromLockfile: false - -importers: - - .: - devDependencies: - semver: - specifier: ^7.7.2 - version: 7.7.3 - typedoc: - specifier: 0.26.8 - version: 0.26.8(typescript@5.6.3) - typedoc-plugin-markdown: - specifier: 4.2.7 - version: 4.2.7(typedoc@0.26.8(typescript@5.6.3)) - -packages: - - '@shikijs/core@1.29.2': - resolution: {integrity: sha512-vju0lY9r27jJfOY4Z7+Rt/nIOjzJpZ3y+nYpqtUZInVoXQ/TJZcfGnNOGnKjFdVZb8qexiCuSlZRKcGfhhTTZQ==} - - '@shikijs/engine-javascript@1.29.2': - resolution: {integrity: sha512-iNEZv4IrLYPv64Q6k7EPpOCE/nuvGiKl7zxdq0WFuRPF5PAE9PRo2JGq/d8crLusM59BRemJ4eOqrFrC4wiQ+A==} - - '@shikijs/engine-oniguruma@1.29.2': - resolution: {integrity: sha512-7iiOx3SG8+g1MnlzZVDYiaeHe7Ez2Kf2HrJzdmGwkRisT7r4rak0e655AcM/tF9JG/kg5fMNYlLLKglbN7gBqA==} - - '@shikijs/langs@1.29.2': - resolution: {integrity: sha512-FIBA7N3LZ+223U7cJDUYd5shmciFQlYkFXlkKVaHsCPgfVLiO+e12FmQE6Tf9vuyEsFe3dIl8qGWKXgEHL9wmQ==} - - '@shikijs/themes@1.29.2': - resolution: {integrity: sha512-i9TNZlsq4uoyqSbluIcZkmPL9Bfi3djVxRnofUHwvx/h6SRW3cwgBC5SML7vsDcWyukY0eCzVN980rqP6qNl9g==} - - '@shikijs/types@1.29.2': - resolution: {integrity: sha512-VJjK0eIijTZf0QSTODEXCqinjBn0joAHQ+aPSBzrv4O2d/QSbsMw+ZeSRx03kV34Hy7NzUvV/7NqfYGRLrASmw==} - - '@shikijs/vscode-textmate@10.0.2': - resolution: {integrity: sha512-83yeghZ2xxin3Nj8z1NMd/NCuca+gsYXswywDy5bHvwlWL8tpTQmzGeUuHd9FC3E/SBEMvzJRwWEOz5gGes9Qg==} - - '@types/hast@3.0.4': - resolution: {integrity: sha512-WPs+bbQw5aCj+x6laNGWLH3wviHtoCv/P3+otBhbOhJgG8qtpdAMlTCxLtsTWA7LH1Oh/bFCHsBn0TPS5m30EQ==} - - '@types/mdast@4.0.4': - resolution: {integrity: sha512-kGaNbPh1k7AFzgpud/gMdvIm5xuECykRR+JnWKQno9TAXVa6WIVCGTPvYGekIDL4uwCZQSYbUxNBSb1aUo79oA==} - - '@types/unist@3.0.3': - resolution: {integrity: sha512-ko/gIFJRv177XgZsZcBwnqJN5x/Gien8qNOn0D5bQU/zAzVf9Zt3BlcUiLqhV9y4ARk0GbT3tnUiPNgnTXzc/Q==} - - '@ungap/structured-clone@1.3.0': - resolution: {integrity: sha512-WmoN8qaIAo7WTYWbAZuG8PYEhn5fkz7dZrqTBZ7dtt//lL2Gwms1IcnQ5yHqjDfX8Ft5j4YzDM23f87zBfDe9g==} - - argparse@2.0.1: - resolution: {integrity: sha512-8+9WqebbFzpX9OR+Wa6O29asIogeRMzcGtAINdpMHHyAg10f05aSFVBbcEqGf/PXw1EjAZ+q2/bEBg3DvurK3Q==} - - balanced-match@1.0.2: - resolution: {integrity: sha512-3oSeUO0TMV67hN1AmbXsK4yaqU7tjiHlbxRDZOpH0KW9+CeX4bRAaX0Anxt0tx2MrpRpWwQaPwIlISEJhYU5Pw==} - - brace-expansion@2.0.2: - resolution: {integrity: sha512-Jt0vHyM+jmUBqojB7E1NIYadt0vI0Qxjxd2TErW94wDz+E2LAm5vKMXXwg6ZZBTHPuUlDgQHKXvjGBdfcF1ZDQ==} - - ccount@2.0.1: - resolution: {integrity: sha512-eyrF0jiFpY+3drT6383f1qhkbGsLSifNAjA61IUjZjmLCWjItY6LB9ft9YhoDgwfmclB2zhu51Lc7+95b8NRAg==} - - character-entities-html4@2.1.0: - resolution: {integrity: sha512-1v7fgQRj6hnSwFpq1Eu0ynr/CDEw0rXo2B61qXrLNdHZmPKgb7fqS1a2JwF0rISo9q77jDI8VMEHoApn8qDoZA==} - - character-entities-legacy@3.0.0: - resolution: {integrity: sha512-RpPp0asT/6ufRm//AJVwpViZbGM/MkjQFxJccQRHmISF/22NBtsHqAWmL+/pmkPWoIUJdWyeVleTl1wydHATVQ==} - - comma-separated-tokens@2.0.3: - resolution: {integrity: sha512-Fu4hJdvzeylCfQPp9SGWidpzrMs7tTrlu6Vb8XGaRGck8QSNZJJp538Wrb60Lax4fPwR64ViY468OIUTbRlGZg==} - - dequal@2.0.3: - resolution: {integrity: sha512-0je+qPKHEMohvfRTCEo3CrPG6cAzAYgmzKyxRiYSSDkS6eGJdyVJm7WaYA5ECaAD9wLB2T4EEeymA5aFVcYXCA==} - engines: {node: '>=6'} - - devlop@1.1.0: - resolution: {integrity: sha512-RWmIqhcFf1lRYBvNmr7qTNuyCt/7/ns2jbpp1+PalgE/rDQcBT0fioSMUpJ93irlUhC5hrg4cYqe6U+0ImW0rA==} - - emoji-regex-xs@1.0.0: - resolution: {integrity: sha512-LRlerrMYoIDrT6jgpeZ2YYl/L8EulRTt5hQcYjy5AInh7HWXKimpqx68aknBFpGL2+/IcogTcaydJEgaTmOpDg==} - - entities@4.5.0: - resolution: {integrity: sha512-V0hjH4dGPh9Ao5p0MoRY6BVqtwCjhz6vI5LT8AJ55H+4g9/4vbHx1I54fS0XuclLhDHArPQCiMjDxjaL8fPxhw==} - engines: {node: '>=0.12'} - - hast-util-to-html@9.0.5: - resolution: {integrity: sha512-OguPdidb+fbHQSU4Q4ZiLKnzWo8Wwsf5bZfbvu7//a9oTYoqD/fWpe96NuHkoS9h0ccGOTe0C4NGXdtS0iObOw==} - - hast-util-whitespace@3.0.0: - resolution: {integrity: sha512-88JUN06ipLwsnv+dVn+OIYOvAuvBMy/Qoi6O7mQHxdPXpjy+Cd6xRkWwux7DKO+4sYILtLBRIKgsdpS2gQc7qw==} - - html-void-elements@3.0.0: - resolution: {integrity: sha512-bEqo66MRXsUGxWHV5IP0PUiAWwoEjba4VCzg0LjFJBpchPaTfyfCKTG6bc5F8ucKec3q5y6qOdGyYTSBEvhCrg==} - - linkify-it@5.0.0: - resolution: {integrity: sha512-5aHCbzQRADcdP+ATqnDuhhJ/MRIqDkZX5pyjFHRRysS8vZ5AbqGEoFIb6pYHPZ+L/OC2Lc+xT8uHVVR5CAK/wQ==} - - lunr@2.3.9: - resolution: {integrity: sha512-zTU3DaZaF3Rt9rhN3uBMGQD3dD2/vFQqnvZCDv4dl5iOzq2IZQqTxu90r4E5J+nP70J3ilqVCrbho2eWaeW8Ow==} - - markdown-it@14.1.0: - resolution: {integrity: sha512-a54IwgWPaeBCAAsv13YgmALOF1elABB08FxO9i+r4VFk5Vl4pKokRPeX8u5TCgSsPi6ec1otfLjdOpVcgbpshg==} - hasBin: true - - mdast-util-to-hast@13.2.1: - resolution: {integrity: sha512-cctsq2wp5vTsLIcaymblUriiTcZd0CwWtCbLvrOzYCDZoWyMNV8sZ7krj09FSnsiJi3WVsHLM4k6Dq/yaPyCXA==} - - mdurl@2.0.0: - resolution: {integrity: sha512-Lf+9+2r+Tdp5wXDXC4PcIBjTDtq4UKjCPMQhKIuzpJNW0b96kVqSwW0bT7FhRSfmAiFYgP+SCRvdrDozfh0U5w==} - - micromark-util-character@2.1.1: - resolution: {integrity: sha512-wv8tdUTJ3thSFFFJKtpYKOYiGP2+v96Hvk4Tu8KpCAsTMs6yi+nVmGh1syvSCsaxz45J6Jbw+9DD6g97+NV67Q==} - - micromark-util-encode@2.0.1: - resolution: {integrity: sha512-c3cVx2y4KqUnwopcO9b/SCdo2O67LwJJ/UyqGfbigahfegL9myoEFoDYZgkT7f36T0bLrM9hZTAaAyH+PCAXjw==} - - micromark-util-sanitize-uri@2.0.1: - resolution: {integrity: sha512-9N9IomZ/YuGGZZmQec1MbgxtlgougxTodVwDzzEouPKo3qFWvymFHWcnDi2vzV1ff6kas9ucW+o3yzJK9YB1AQ==} - - micromark-util-symbol@2.0.1: - resolution: {integrity: sha512-vs5t8Apaud9N28kgCrRUdEed4UJ+wWNvicHLPxCa9ENlYuAY31M0ETy5y1vA33YoNPDFTghEbnh6efaE8h4x0Q==} - - micromark-util-types@2.0.2: - resolution: {integrity: sha512-Yw0ECSpJoViF1qTU4DC6NwtC4aWGt1EkzaQB8KPPyCRR8z9TWeV0HbEFGTO+ZY1wB22zmxnJqhPyTpOVCpeHTA==} - - minimatch@9.0.5: - resolution: {integrity: sha512-G6T0ZX48xgozx7587koeX9Ys2NYy6Gmv//P89sEte9V9whIapMNF4idKxnW2QtCcLiTWlb/wfCabAtAFWhhBow==} - engines: {node: '>=16 || 14 >=14.17'} - - oniguruma-to-es@2.3.0: - resolution: {integrity: sha512-bwALDxriqfKGfUufKGGepCzu9x7nJQuoRoAFp4AnwehhC2crqrDIAP/uN2qdlsAvSMpeRC3+Yzhqc7hLmle5+g==} - - property-information@7.1.0: - resolution: {integrity: sha512-TwEZ+X+yCJmYfL7TPUOcvBZ4QfoT5YenQiJuX//0th53DE6w0xxLEtfK3iyryQFddXuvkIk51EEgrJQ0WJkOmQ==} - - punycode.js@2.3.1: - resolution: {integrity: sha512-uxFIHU0YlHYhDQtV4R9J6a52SLx28BCjT+4ieh7IGbgwVJWO+km431c4yRlREUAsAmt/uMjQUyQHNEPf0M39CA==} - engines: {node: '>=6'} - - regex-recursion@5.1.1: - resolution: {integrity: sha512-ae7SBCbzVNrIjgSbh7wMznPcQel1DNlDtzensnFxpiNpXt1U2ju/bHugH422r+4LAVS1FpW1YCwilmnNsjum9w==} - - regex-utilities@2.3.0: - resolution: {integrity: sha512-8VhliFJAWRaUiVvREIiW2NXXTmHs4vMNnSzuJVhscgmGav3g9VDxLrQndI3dZZVVdp0ZO/5v0xmX516/7M9cng==} - - regex@5.1.1: - resolution: {integrity: sha512-dN5I359AVGPnwzJm2jN1k0W9LPZ+ePvoOeVMMfqIMFz53sSwXkxaJoxr50ptnsC771lK95BnTrVSZxq0b9yCGw==} - - semver@7.7.3: - resolution: {integrity: sha512-SdsKMrI9TdgjdweUSR9MweHA4EJ8YxHn8DFaDisvhVlUOe4BF1tLD7GAj0lIqWVl+dPb/rExr0Btby5loQm20Q==} - engines: {node: '>=10'} - hasBin: true - - shiki@1.29.2: - resolution: {integrity: sha512-njXuliz/cP+67jU2hukkxCNuH1yUi4QfdZZY+sMr5PPrIyXSu5iTb/qYC4BiWWB0vZ+7TbdvYUCeL23zpwCfbg==} - - space-separated-tokens@2.0.2: - resolution: {integrity: sha512-PEGlAwrG8yXGXRjW32fGbg66JAlOAwbObuqVoJpv/mRgoWDQfgH1wDPvtzWyUSNAXBGSk8h755YDbbcEy3SH2Q==} - - stringify-entities@4.0.4: - resolution: {integrity: sha512-IwfBptatlO+QCJUo19AqvrPNqlVMpW9YEL2LIVY+Rpv2qsjCGxaDLNRgeGsQWJhfItebuJhsGSLjaBbNSQ+ieg==} - - trim-lines@3.0.1: - resolution: {integrity: sha512-kRj8B+YHZCc9kQYdWfJB2/oUl9rA99qbowYYBtr4ui4mZyAQ2JpvVBd/6U2YloATfqBhBTSMhTpgBHtU0Mf3Rg==} - - typedoc-plugin-markdown@4.2.7: - resolution: {integrity: sha512-bLsQdweSm48P9j6kGqQ3/4GCH5zu2EnURSkkxqirNc+uVFE9YK825ogDw+WbNkRHIV6eZK/1U43gT7YfglyYOg==} - engines: {node: '>= 18'} - peerDependencies: - typedoc: 0.26.x - - typedoc@0.26.8: - resolution: {integrity: sha512-QBF0BMbnNeUc6U7pRHY7Jb8pjhmiNWZNQT8LU6uk9qP9t3goP9bJptdlNqMC0wBB2w9sQrxjZt835bpRSSq1LA==} - engines: {node: '>= 18'} - hasBin: true - peerDependencies: - typescript: 4.6.x || 4.7.x || 4.8.x || 4.9.x || 5.0.x || 5.1.x || 5.2.x || 5.3.x || 5.4.x || 5.5.x || 5.6.x - - typescript@5.6.3: - resolution: {integrity: sha512-hjcS1mhfuyi4WW8IWtjP7brDrG2cuDZukyrYrSauoXGNgx0S7zceP07adYkJycEr56BOUTNPzbInooiN3fn1qw==} - engines: {node: '>=14.17'} - hasBin: true - - uc.micro@2.1.0: - resolution: {integrity: sha512-ARDJmphmdvUk6Glw7y9DQ2bFkKBHwQHLi2lsaH6PPmz/Ka9sFOBsBluozhDltWmnv9u/cF6Rt87znRTPV+yp/A==} - - unist-util-is@6.0.1: - resolution: {integrity: sha512-LsiILbtBETkDz8I9p1dQ0uyRUWuaQzd/cuEeS1hoRSyW5E5XGmTzlwY1OrNzzakGowI9Dr/I8HVaw4hTtnxy8g==} - - unist-util-position@5.0.0: - resolution: {integrity: sha512-fucsC7HjXvkB5R3kTCO7kUjRdrS0BJt3M/FPxmHMBOm8JQi2BsHAHFsy27E0EolP8rp0NzXsJ+jNPyDWvOJZPA==} - - unist-util-stringify-position@4.0.0: - resolution: {integrity: sha512-0ASV06AAoKCDkS2+xw5RXJywruurpbC4JZSm7nr7MOt1ojAzvyyaO+UxZf18j8FCF6kmzCZKcAgN/yu2gm2XgQ==} - - unist-util-visit-parents@6.0.2: - resolution: {integrity: sha512-goh1s1TBrqSqukSc8wrjwWhL0hiJxgA8m4kFxGlQ+8FYQ3C/m11FcTs4YYem7V664AhHVvgoQLk890Ssdsr2IQ==} - - unist-util-visit@5.0.0: - resolution: {integrity: sha512-MR04uvD+07cwl/yhVuVWAtw+3GOR/knlL55Nd/wAdblk27GCVt3lqpTivy/tkJcZoNPzTwS1Y+KMojlLDhoTzg==} - - vfile-message@4.0.3: - resolution: {integrity: sha512-QTHzsGd1EhbZs4AsQ20JX1rC3cOlt/IWJruk893DfLRr57lcnOeMaWG4K0JrRta4mIJZKth2Au3mM3u03/JWKw==} - - vfile@6.0.3: - resolution: {integrity: sha512-KzIbH/9tXat2u30jf+smMwFCsno4wHVdNmzFyL+T/L3UGqqk6JKfVqOFOZEpZSHADH1k40ab6NUIXZq422ov3Q==} - - yaml@2.8.2: - resolution: {integrity: sha512-mplynKqc1C2hTVYxd0PU2xQAc22TI1vShAYGksCCfxbn/dFwnHTNi1bvYsBTkhdUNtGIf5xNOg938rrSSYvS9A==} - engines: {node: '>= 14.6'} - hasBin: true - - zwitch@2.0.4: - resolution: {integrity: sha512-bXE4cR/kVZhKZX/RjPEflHaKVhUVl85noU3v6b8apfQEc1x4A+zBxjZ4lN8LqGd6WZ3dl98pY4o717VFmoPp+A==} - -snapshots: - - '@shikijs/core@1.29.2': - dependencies: - '@shikijs/engine-javascript': 1.29.2 - '@shikijs/engine-oniguruma': 1.29.2 - '@shikijs/types': 1.29.2 - '@shikijs/vscode-textmate': 10.0.2 - '@types/hast': 3.0.4 - hast-util-to-html: 9.0.5 - - '@shikijs/engine-javascript@1.29.2': - dependencies: - '@shikijs/types': 1.29.2 - '@shikijs/vscode-textmate': 10.0.2 - oniguruma-to-es: 2.3.0 - - '@shikijs/engine-oniguruma@1.29.2': - dependencies: - '@shikijs/types': 1.29.2 - '@shikijs/vscode-textmate': 10.0.2 - - '@shikijs/langs@1.29.2': - dependencies: - '@shikijs/types': 1.29.2 - - '@shikijs/themes@1.29.2': - dependencies: - '@shikijs/types': 1.29.2 - - '@shikijs/types@1.29.2': - dependencies: - '@shikijs/vscode-textmate': 10.0.2 - '@types/hast': 3.0.4 - - '@shikijs/vscode-textmate@10.0.2': {} - - '@types/hast@3.0.4': - dependencies: - '@types/unist': 3.0.3 - - '@types/mdast@4.0.4': - dependencies: - '@types/unist': 3.0.3 - - '@types/unist@3.0.3': {} - - '@ungap/structured-clone@1.3.0': {} - - argparse@2.0.1: {} - - balanced-match@1.0.2: {} - - brace-expansion@2.0.2: - dependencies: - balanced-match: 1.0.2 - - ccount@2.0.1: {} - - character-entities-html4@2.1.0: {} - - character-entities-legacy@3.0.0: {} - - comma-separated-tokens@2.0.3: {} - - dequal@2.0.3: {} - - devlop@1.1.0: - dependencies: - dequal: 2.0.3 - - emoji-regex-xs@1.0.0: {} - - entities@4.5.0: {} - - hast-util-to-html@9.0.5: - dependencies: - '@types/hast': 3.0.4 - '@types/unist': 3.0.3 - ccount: 2.0.1 - comma-separated-tokens: 2.0.3 - hast-util-whitespace: 3.0.0 - html-void-elements: 3.0.0 - mdast-util-to-hast: 13.2.1 - property-information: 7.1.0 - space-separated-tokens: 2.0.2 - stringify-entities: 4.0.4 - zwitch: 2.0.4 - - hast-util-whitespace@3.0.0: - dependencies: - '@types/hast': 3.0.4 - - html-void-elements@3.0.0: {} - - linkify-it@5.0.0: - dependencies: - uc.micro: 2.1.0 - - lunr@2.3.9: {} - - markdown-it@14.1.0: - dependencies: - argparse: 2.0.1 - entities: 4.5.0 - linkify-it: 5.0.0 - mdurl: 2.0.0 - punycode.js: 2.3.1 - uc.micro: 2.1.0 - - mdast-util-to-hast@13.2.1: - dependencies: - '@types/hast': 3.0.4 - '@types/mdast': 4.0.4 - '@ungap/structured-clone': 1.3.0 - devlop: 1.1.0 - micromark-util-sanitize-uri: 2.0.1 - trim-lines: 3.0.1 - unist-util-position: 5.0.0 - unist-util-visit: 5.0.0 - vfile: 6.0.3 - - mdurl@2.0.0: {} - - micromark-util-character@2.1.1: - dependencies: - micromark-util-symbol: 2.0.1 - micromark-util-types: 2.0.2 - - micromark-util-encode@2.0.1: {} - - micromark-util-sanitize-uri@2.0.1: - dependencies: - micromark-util-character: 2.1.1 - micromark-util-encode: 2.0.1 - micromark-util-symbol: 2.0.1 - - micromark-util-symbol@2.0.1: {} - - micromark-util-types@2.0.2: {} - - minimatch@9.0.5: - dependencies: - brace-expansion: 2.0.2 - - oniguruma-to-es@2.3.0: - dependencies: - emoji-regex-xs: 1.0.0 - regex: 5.1.1 - regex-recursion: 5.1.1 - - property-information@7.1.0: {} - - punycode.js@2.3.1: {} - - regex-recursion@5.1.1: - dependencies: - regex: 5.1.1 - regex-utilities: 2.3.0 - - regex-utilities@2.3.0: {} - - regex@5.1.1: - dependencies: - regex-utilities: 2.3.0 - - semver@7.7.3: {} - - shiki@1.29.2: - dependencies: - '@shikijs/core': 1.29.2 - '@shikijs/engine-javascript': 1.29.2 - '@shikijs/engine-oniguruma': 1.29.2 - '@shikijs/langs': 1.29.2 - '@shikijs/themes': 1.29.2 - '@shikijs/types': 1.29.2 - '@shikijs/vscode-textmate': 10.0.2 - '@types/hast': 3.0.4 - - space-separated-tokens@2.0.2: {} - - stringify-entities@4.0.4: - dependencies: - character-entities-html4: 2.1.0 - character-entities-legacy: 3.0.0 - - trim-lines@3.0.1: {} - - typedoc-plugin-markdown@4.2.7(typedoc@0.26.8(typescript@5.6.3)): - dependencies: - typedoc: 0.26.8(typescript@5.6.3) - - typedoc@0.26.8(typescript@5.6.3): - dependencies: - lunr: 2.3.9 - markdown-it: 14.1.0 - minimatch: 9.0.5 - shiki: 1.29.2 - typescript: 5.6.3 - yaml: 2.8.2 - - typescript@5.6.3: {} - - uc.micro@2.1.0: {} - - unist-util-is@6.0.1: - dependencies: - '@types/unist': 3.0.3 - - unist-util-position@5.0.0: - dependencies: - '@types/unist': 3.0.3 - - unist-util-stringify-position@4.0.0: - dependencies: - '@types/unist': 3.0.3 - - unist-util-visit-parents@6.0.2: - dependencies: - '@types/unist': 3.0.3 - unist-util-is: 6.0.1 - - unist-util-visit@5.0.0: - dependencies: - '@types/unist': 3.0.3 - unist-util-is: 6.0.1 - unist-util-visit-parents: 6.0.2 - - vfile-message@4.0.3: - dependencies: - '@types/unist': 3.0.3 - unist-util-stringify-position: 4.0.0 - - vfile@6.0.3: - dependencies: - '@types/unist': 3.0.3 - vfile-message: 4.0.3 - - yaml@2.8.2: {} - - zwitch@2.0.4: {} From 89d811670c05e3d94febece0375a7f6b6b7166a1 Mon Sep 17 00:00:00 2001 From: ben-fornefeld Date: Thu, 8 Jan 2026 13:17:17 +0100 Subject: [PATCH 14/39] fix: config --- sdk-reference-generator/src/cli.ts | 2 +- sdk-reference-generator/src/generator.ts | 2 +- sdk-reference-generator/src/lib/config.ts | 10 +++++----- sdk-reference-generator/src/navigation.ts | 2 +- 4 files changed, 8 insertions(+), 8 deletions(-) diff --git a/sdk-reference-generator/src/cli.ts b/sdk-reference-generator/src/cli.ts index 2eaa903..f04f7f1 100644 --- a/sdk-reference-generator/src/cli.ts +++ b/sdk-reference-generator/src/cli.ts @@ -63,7 +63,7 @@ async function main(): Promise { }; try { - const sdkKeys = opts.sdk === "all" ? await getAllSDKKeys() : [opts.sdk]; + const sdkKeys = opts.sdk === "all" ? getAllSDKKeys() : [opts.sdk]; const results: Map = new Map(); diff --git a/sdk-reference-generator/src/generator.ts b/sdk-reference-generator/src/generator.ts index 32b31d8..e06a938 100644 --- a/sdk-reference-generator/src/generator.ts +++ b/sdk-reference-generator/src/generator.ts @@ -247,7 +247,7 @@ export async function generateSDK( versionArg: string, context: GenerationContext ): Promise { - const config = await getSDKConfig(sdkKey); + const config = getSDKConfig(sdkKey); if (!config) { log.error(`SDK '${sdkKey}' not found in config`, 1); diff --git a/sdk-reference-generator/src/lib/config.ts b/sdk-reference-generator/src/lib/config.ts index db25f4c..d007e37 100644 --- a/sdk-reference-generator/src/lib/config.ts +++ b/sdk-reference-generator/src/lib/config.ts @@ -1,16 +1,16 @@ import sdks from "../../sdks.config.js"; import type { SDKConfig, ConfigFile } from "../types.js"; -export async function getConfig(): Promise { +export function getConfig(): ConfigFile { return { sdks }; } -export async function getSDKConfig(sdkKey: string): Promise { - const config = await getConfig(); +export function getSDKConfig(sdkKey: string): SDKConfig | null { + const config = getConfig(); return config.sdks[sdkKey] || null; } -export async function getAllSDKKeys(): Promise { - const config = await getConfig(); +export function getAllSDKKeys(): string[] { + const config = getConfig(); return Object.keys(config.sdks); } diff --git a/sdk-reference-generator/src/navigation.ts b/sdk-reference-generator/src/navigation.ts index c9448c7..2528798 100644 --- a/sdk-reference-generator/src/navigation.ts +++ b/sdk-reference-generator/src/navigation.ts @@ -42,7 +42,7 @@ async function getModules(versionDir: string): Promise { export async function buildNavigation( docsDir: string ): Promise { - const config = await getConfig(); + const config = getConfig(); const sdkRefDir = path.join(docsDir, CONSTANTS.DOCS_SDK_REF_PATH); if (!(await fs.pathExists(sdkRefDir))) { From c9f0fd6d4ce66ca1830b0e940b0c10def40f12f2 Mon Sep 17 00:00:00 2001 From: ben-fornefeld Date: Thu, 8 Jan 2026 13:51:29 +0100 Subject: [PATCH 15/39] refactor: update SDK configuration and improve generation logic - Replaced `basePackage` and `fallbackPackages` with `allowedPackages` in SDK configurations for better clarity and usage. - Refactored the `generateVersion` function to utilize a new `CheckoutManager` for handling repository checkouts and version switching. - Simplified the `generatePydoc` function to focus on allowed packages, removing the need for fallback and submodule handling. - Introduced a new `checkout.ts` file to manage SDK checkouts, enhancing code organization and maintainability. - Removed obsolete cache handling code and related tests to streamline the project structure. --- sdk-reference-generator/sdks.config.ts | 14 +- .../src/__tests__/cache.test.ts | 127 ------------ .../src/__tests__/checkout.test.ts | 180 ++++++++++++++++++ sdk-reference-generator/src/generator.ts | 127 +++++++----- .../src/generators/index.ts | 7 +- .../src/generators/pydoc.ts | 89 +-------- sdk-reference-generator/src/lib/cache.ts | 78 -------- sdk-reference-generator/src/lib/checkout.ts | 48 +++++ sdk-reference-generator/src/lib/git.ts | 18 ++ sdk-reference-generator/src/lib/install.ts | 90 ++++----- sdk-reference-generator/src/types.ts | 4 +- 11 files changed, 368 insertions(+), 414 deletions(-) delete mode 100644 sdk-reference-generator/src/__tests__/cache.test.ts create mode 100644 sdk-reference-generator/src/__tests__/checkout.test.ts delete mode 100644 sdk-reference-generator/src/lib/cache.ts create mode 100644 sdk-reference-generator/src/lib/checkout.ts diff --git a/sdk-reference-generator/sdks.config.ts b/sdk-reference-generator/sdks.config.ts index 4a1d99c..28cc667 100644 --- a/sdk-reference-generator/sdks.config.ts +++ b/sdk-reference-generator/sdks.config.ts @@ -38,18 +38,16 @@ const sdks = { generator: "pydoc", required: true, minVersion: "1.0.0", - basePackage: "e2b", - fallbackPackages: [ + allowedPackages: [ "e2b.sandbox_sync", "e2b.sandbox_async", "e2b.exceptions", "e2b.template", "e2b.template_sync", "e2b.template_async", + "e2b.template.logger", + "e2b.template.readycmd", ], - submodules: { - "e2b.template": ["logger", "readycmd"], - }, }, "code-interpreter-js-sdk": { @@ -76,8 +74,7 @@ const sdks = { generator: "pydoc", required: false, minVersion: "1.0.0", - basePackage: "e2b_code_interpreter", - fallbackPackages: ["e2b_code_interpreter"], + allowedPackages: ["e2b_code_interpreter"], }, "desktop-js-sdk": { @@ -104,8 +101,7 @@ const sdks = { generator: "pydoc", required: false, minVersion: "1.0.0", - basePackage: "e2b_desktop", - fallbackPackages: ["e2b_desktop"], + allowedPackages: ["e2b_desktop"], }, } as const satisfies Record; diff --git a/sdk-reference-generator/src/__tests__/cache.test.ts b/sdk-reference-generator/src/__tests__/cache.test.ts deleted file mode 100644 index 128aa49..0000000 --- a/sdk-reference-generator/src/__tests__/cache.test.ts +++ /dev/null @@ -1,127 +0,0 @@ -import { describe, it, expect, vi, beforeEach, afterEach } from "vitest"; -import path from "path"; -import fs from "fs-extra"; -import { hashLockfile } from "../lib/cache.js"; - -// mock fs-extra -vi.mock("fs-extra"); - -describe("hashLockfile", () => { - beforeEach(() => { - vi.clearAllMocks(); - }); - - afterEach(() => { - vi.restoreAllMocks(); - }); - - it("finds lockfile in current directory", async () => { - const mockPathExists = vi.mocked(fs.pathExists); - const mockReadFile = vi.mocked(fs.readFile); - - mockPathExists.mockImplementation((p: string) => { - return Promise.resolve(p === path.join("/test/dir", "pnpm-lock.yaml")); - }); - - mockReadFile.mockImplementation(() => { - return Promise.resolve(Buffer.from("lockfile content")); - }); - - const result = await hashLockfile("/test/dir", "typedoc"); - - expect(result).not.toBeNull(); - expect(result).toHaveLength(32); - expect(mockPathExists).toHaveBeenCalledWith( - path.join("/test/dir", "pnpm-lock.yaml") - ); - }); - - it("finds lockfile in parent directory", async () => { - const mockPathExists = vi.mocked(fs.pathExists); - const mockReadFile = vi.mocked(fs.readFile); - - mockPathExists.mockImplementation((p: string) => { - return Promise.resolve(p === path.join("/test", "pnpm-lock.yaml")); - }); - - mockReadFile.mockImplementation(() => { - return Promise.resolve(Buffer.from("parent lockfile")); - }); - - const result = await hashLockfile("/test/dir/subdir", "typedoc"); - - expect(result).not.toBeNull(); - }); - - it("stops at filesystem root without infinite loop (Unix)", async () => { - const mockPathExists = vi.mocked(fs.pathExists); - mockPathExists.mockImplementation(() => Promise.resolve(false)); - - const result = await hashLockfile("/deep/nested/dir", "typedoc"); - - expect(result).toBeNull(); - expect(mockPathExists.mock.calls.length).toBeLessThan(20); - }); - - it("stops at filesystem root without infinite loop (Windows-style path)", async () => { - const mockPathExists = vi.mocked(fs.pathExists); - mockPathExists.mockImplementation(() => Promise.resolve(false)); - - const result = await hashLockfile("C:\\deep\\nested\\dir", "typedoc"); - - expect(result).toBeNull(); - expect(mockPathExists.mock.calls.length).toBeLessThan(20); - }); - - it("returns null when no lockfile found", async () => { - const mockPathExists = vi.mocked(fs.pathExists); - mockPathExists.mockImplementation(() => Promise.resolve(false)); - - const result = await hashLockfile("/test/dir", "typedoc"); - - expect(result).toBeNull(); - }); - - it("tries multiple lockfile patterns in order", async () => { - const mockPathExists = vi.mocked(fs.pathExists); - const mockReadFile = vi.mocked(fs.readFile); - - mockPathExists.mockImplementation((p: string) => { - return Promise.resolve(p.includes("package-lock.json")); - }); - - mockReadFile.mockImplementation(() => { - return Promise.resolve(Buffer.from("npm lockfile")); - }); - - const result = await hashLockfile("/test/dir", "typedoc"); - - expect(result).not.toBeNull(); - expect(mockPathExists).toHaveBeenCalledWith( - path.join("/test/dir", "pnpm-lock.yaml") - ); - expect(mockPathExists).toHaveBeenCalledWith( - path.join("/test/dir", "package-lock.json") - ); - }); - - it("handles pydoc generator with poetry.lock", async () => { - const mockPathExists = vi.mocked(fs.pathExists); - const mockReadFile = vi.mocked(fs.readFile); - - mockPathExists.mockImplementation((p: string) => { - return Promise.resolve(p.includes("poetry.lock")); - }); - - mockReadFile.mockImplementation(() => { - return Promise.resolve(Buffer.from("poetry lockfile")); - }); - - const result = await hashLockfile("/test/python-project", "pydoc"); - - expect(result).not.toBeNull(); - expect(mockPathExists).toHaveBeenCalledWith( - path.join("/test/python-project", "poetry.lock") - ); - }); -}); diff --git a/sdk-reference-generator/src/__tests__/checkout.test.ts b/sdk-reference-generator/src/__tests__/checkout.test.ts new file mode 100644 index 0000000..3db07e4 --- /dev/null +++ b/sdk-reference-generator/src/__tests__/checkout.test.ts @@ -0,0 +1,180 @@ +import { describe, it, expect, vi, beforeEach } from "vitest"; +import { CheckoutManager } from "../lib/checkout.js"; + +vi.mock("../lib/git.js", () => ({ + cloneAtTag: vi.fn(), + checkoutTag: vi.fn(), +})); + +vi.mock("fs-extra", () => ({ + default: { + remove: vi.fn(), + }, +})); + +import { cloneAtTag, checkoutTag } from "../lib/git.js"; +import fs from "fs-extra"; + +const mockCloneAtTag = vi.mocked(cloneAtTag); +const mockCheckoutTag = vi.mocked(checkoutTag); +const mockRemove = vi.mocked(fs.remove); + +describe("CheckoutManager", () => { + beforeEach(() => { + vi.clearAllMocks(); + }); + + describe("getOrClone", () => { + it("clones repo on first call", async () => { + const mgr = new CheckoutManager(); + + const repoDir = await mgr.getOrClone( + "test-sdk", + "https://github.com/test/repo.git", + "v1.0.0", + "/tmp" + ); + + expect(repoDir).toBe("/tmp/shared-test-sdk"); + expect(mockCloneAtTag).toHaveBeenCalledWith( + "https://github.com/test/repo.git", + "v1.0.0", + "/tmp/shared-test-sdk" + ); + }); + + it("returns cached dir on subsequent calls", async () => { + const mgr = new CheckoutManager(); + + await mgr.getOrClone( + "test-sdk", + "https://github.com/test/repo.git", + "v1.0.0", + "/tmp" + ); + + mockCloneAtTag.mockClear(); + + const repoDir = await mgr.getOrClone( + "test-sdk", + "https://github.com/test/repo.git", + "v2.0.0", + "/tmp" + ); + + expect(repoDir).toBe("/tmp/shared-test-sdk"); + expect(mockCloneAtTag).not.toHaveBeenCalled(); + }); + + it("handles multiple SDKs independently", async () => { + const mgr = new CheckoutManager(); + + const dir1 = await mgr.getOrClone( + "sdk-a", + "https://github.com/test/a.git", + "v1.0.0", + "/tmp" + ); + + const dir2 = await mgr.getOrClone( + "sdk-b", + "https://github.com/test/b.git", + "v2.0.0", + "/tmp" + ); + + expect(dir1).toBe("/tmp/shared-sdk-a"); + expect(dir2).toBe("/tmp/shared-sdk-b"); + expect(mockCloneAtTag).toHaveBeenCalledTimes(2); + }); + }); + + describe("switchVersion", () => { + it("switches to new tag in existing checkout", async () => { + const mgr = new CheckoutManager(); + + await mgr.getOrClone( + "test-sdk", + "https://github.com/test/repo.git", + "v1.0.0", + "/tmp" + ); + + await mgr.switchVersion("test-sdk", "v2.0.0"); + + expect(mockCheckoutTag).toHaveBeenCalledWith( + "/tmp/shared-test-sdk", + "v2.0.0" + ); + }); + + it("throws if checkout not initialized", async () => { + const mgr = new CheckoutManager(); + + await expect(mgr.switchVersion("unknown-sdk", "v1.0.0")).rejects.toThrow( + "Checkout not initialized for unknown-sdk" + ); + }); + }); + + describe("getRepoDir", () => { + it("returns undefined for unknown SDK", () => { + const mgr = new CheckoutManager(); + expect(mgr.getRepoDir("unknown")).toBeUndefined(); + }); + + it("returns path for initialized SDK", async () => { + const mgr = new CheckoutManager(); + + await mgr.getOrClone( + "test-sdk", + "https://github.com/test/repo.git", + "v1.0.0", + "/tmp" + ); + + expect(mgr.getRepoDir("test-sdk")).toBe("/tmp/shared-test-sdk"); + }); + }); + + describe("cleanup", () => { + it("removes all checkout directories", async () => { + const mgr = new CheckoutManager(); + + await mgr.getOrClone( + "sdk-a", + "https://github.com/test/a.git", + "v1.0.0", + "/tmp" + ); + + await mgr.getOrClone( + "sdk-b", + "https://github.com/test/b.git", + "v1.0.0", + "/tmp" + ); + + await mgr.cleanup(); + + expect(mockRemove).toHaveBeenCalledWith("/tmp/shared-sdk-a"); + expect(mockRemove).toHaveBeenCalledWith("/tmp/shared-sdk-b"); + }); + + it("clears internal state after cleanup", async () => { + const mgr = new CheckoutManager(); + + await mgr.getOrClone( + "test-sdk", + "https://github.com/test/repo.git", + "v1.0.0", + "/tmp" + ); + + await mgr.cleanup(); + + expect(mgr.getRepoDir("test-sdk")).toBeUndefined(); + }); + }); +}); + diff --git a/sdk-reference-generator/src/generator.ts b/sdk-reference-generator/src/generator.ts index e06a938..d62a043 100644 --- a/sdk-reference-generator/src/generator.ts +++ b/sdk-reference-generator/src/generator.ts @@ -7,11 +7,7 @@ import type { } from "./types.js"; import { getSDKConfig } from "./lib/config.js"; import { log } from "./lib/log.js"; -import { - fetchRemoteTags, - cloneAtTag, - resolveLatestVersion, -} from "./lib/git.js"; +import { fetchRemoteTags, resolveLatestVersion } from "./lib/git.js"; import { fetchLocalVersions, filterByMinVersion, @@ -19,58 +15,69 @@ import { versionExists, } from "./lib/versions.js"; import { flattenMarkdown, copyToDocs, locateSDKDir } from "./lib/files.js"; -import { installWithCache } from "./lib/install.js"; +import { installDependencies } from "./lib/install.js"; import { runGenerator } from "./generators/index.js"; import { buildSDKPath } from "./lib/utils.js"; import { CONSTANTS } from "./lib/constants.js"; +import { CheckoutManager } from "./lib/checkout.js"; async function generateVersion( sdkKey: string, config: SDKConfig, version: string, - context: GenerationContext + context: GenerationContext, + checkoutMgr: CheckoutManager, + isFirstVersion: boolean ): Promise { - const repoDir = path.join(context.tempDir, `${sdkKey}-${version}`); + const tagName = config.tagFormat.replace( + "{version}", + version.replace(/^v/, "") + ); - try { - const tagName = config.tagFormat.replace( - "{version}", - version.replace(/^v/, "") + let repoDir: string; + + if (isFirstVersion) { + repoDir = await checkoutMgr.getOrClone( + sdkKey, + config.repo, + tagName, + context.tempDir ); + } else { + await checkoutMgr.switchVersion(sdkKey, tagName); + repoDir = checkoutMgr.getRepoDir(sdkKey)!; + } - await cloneAtTag(config.repo, tagName, repoDir); + const sdkDir = await locateSDKDir(repoDir, config.sdkPath, config.sdkPaths); + if (!sdkDir) { + throw new Error( + `SDK path not found: ${config.sdkPath || config.sdkPaths?.join(", ")}` + ); + } - const sdkDir = await locateSDKDir(repoDir, config.sdkPath, config.sdkPaths); - if (!sdkDir) { - throw new Error( - `SDK path not found: ${config.sdkPath || config.sdkPaths?.join(", ")}` - ); - } + const sdkRefDir = path.join(sdkDir, CONSTANTS.SDK_REF_DIR); + await fs.remove(sdkRefDir); - await installWithCache(sdkDir, config.generator, context.tempDir); - const generatedDocsDir = await runGenerator(sdkDir, config, context); + await installDependencies(sdkDir, config.generator); + const generatedDocsDir = await runGenerator(sdkDir, config, context); - const sdkRefDir = path.join(sdkDir, CONSTANTS.SDK_REF_DIR); - if (generatedDocsDir !== sdkRefDir) { - log.info(`Normalizing ${path.basename(generatedDocsDir)} to sdk_ref`, 1); - await fs.move(generatedDocsDir, sdkRefDir); - } + if (generatedDocsDir !== sdkRefDir) { + log.info(`Normalizing ${path.basename(generatedDocsDir)} to sdk_ref`, 1); + await fs.move(generatedDocsDir, sdkRefDir, { overwrite: true }); + } - await flattenMarkdown(sdkRefDir); + await flattenMarkdown(sdkRefDir); - const destDir = buildSDKPath(context.docsDir, sdkKey, version); - const success = await copyToDocs( - sdkRefDir, - destDir, - config.displayName, - version - ); + const destDir = buildSDKPath(context.docsDir, sdkKey, version); + const success = await copyToDocs( + sdkRefDir, + destDir, + config.displayName, + version + ); - if (!success) { - throw new Error("Failed to copy generated files"); - } - } finally { - await fs.remove(repoDir); + if (!success) { + throw new Error("Failed to copy generated files"); } } @@ -185,20 +192,36 @@ async function processVersionBatch( let failed = 0; const failedVersions: string[] = []; - for (const version of versions) { - log.blank(); - log.step(`Generating ${version}`, 1); - - try { - await generateVersion(sdkKey, config, version, context); - log.success(`Complete: ${version}`, 1); - generated++; - } catch (error) { - const msg = error instanceof Error ? error.message : String(error); - log.error(`Failed: ${version} - ${msg}`, 1); - failed++; - failedVersions.push(version); + const checkoutMgr = new CheckoutManager(); + + try { + for (let i = 0; i < versions.length; i++) { + const version = versions[i]; + const isFirstVersion = i === 0; + + log.blank(); + log.step(`Generating ${version}`, 1); + + try { + await generateVersion( + sdkKey, + config, + version, + context, + checkoutMgr, + isFirstVersion + ); + log.success(`Complete: ${version}`, 1); + generated++; + } catch (error) { + const msg = error instanceof Error ? error.message : String(error); + log.error(`Failed: ${version} - ${msg}`, 1); + failed++; + failedVersions.push(version); + } } + } finally { + await checkoutMgr.cleanup(); } return { generated, failed, failedVersions }; diff --git a/sdk-reference-generator/src/generators/index.ts b/sdk-reference-generator/src/generators/index.ts index 18c4639..c30e354 100644 --- a/sdk-reference-generator/src/generators/index.ts +++ b/sdk-reference-generator/src/generators/index.ts @@ -13,12 +13,7 @@ export async function runGenerator( return await generateTypedoc(sdkDir, context.configsDir); case "pydoc": - return await generatePydoc( - sdkDir, - config.fallbackPackages || [], - config.submodules, - config.basePackage - ); + return await generatePydoc(sdkDir, config.allowedPackages); case "cli": return await generateCli(sdkDir); diff --git a/sdk-reference-generator/src/generators/pydoc.ts b/sdk-reference-generator/src/generators/pydoc.ts index 9c91352..0e10258 100644 --- a/sdk-reference-generator/src/generators/pydoc.ts +++ b/sdk-reference-generator/src/generators/pydoc.ts @@ -4,63 +4,6 @@ import path from "path"; import { CONSTANTS } from "../lib/constants.js"; import { log } from "../lib/log.js"; -async function discoverPythonPackages( - sdkDir: string, - basePackage: string -): Promise { - try { - const script = ` -import warnings -warnings.filterwarnings('ignore') - -import sys -import pkgutil -import importlib - -try: - base = importlib.import_module('${basePackage}') - modules = [] - - for importer, modname, ispkg in pkgutil.iter_modules(base.__path__, base.__name__ + '.'): - modules.append(modname) - - if modules: - print('\\n'.join(sorted(modules))) -except ImportError: - pass -`; - - const result = await execa( - "poetry", - ["run", "python", "-W", "ignore", "-c", script], - { - cwd: sdkDir, - stdio: "pipe", - reject: false, - } - ); - - if (result.exitCode !== 0) { - log.warn(`Discovery failed for ${basePackage} (using fallback)`, 1); - return []; - } - - const packages = result.stdout - .split("\n") - .filter(Boolean) - .filter((pkg) => !pkg.includes("__pycache__")); - - if (packages.length > 0) { - log.info(`Discovered ${packages.length} packages from ${basePackage}`, 1); - } - - return packages; - } catch (error) { - log.warn("Discovery failed (using fallback)", 1); - return []; - } -} - async function processMdx(file: string): Promise { let content = await fs.readFile(file, "utf-8"); @@ -120,44 +63,26 @@ async function processPackage(pkg: string, sdkDir: string): Promise { export async function generatePydoc( sdkDir: string, - fallbackPackages: readonly string[], - submodules?: Record, - basePackage: string = "e2b" + allowedPackages: readonly string[] ): Promise { const outputDir = path.join(sdkDir, CONSTANTS.SDK_REF_DIR); await fs.ensureDir(outputDir); - log.info("Discovering Python packages...", 1); - const discovered = await discoverPythonPackages(sdkDir, basePackage); - - const packagesToProcess = - discovered.length > 0 ? discovered : fallbackPackages; - - if (discovered.length > 0) { - log.info(`Found ${packagesToProcess.length} packages (auto-discovered)`, 1); - } else if (fallbackPackages.length > 0) { - log.info(`Using ${fallbackPackages.length} fallback packages`, 1); - } + log.info( + `Attempting to generate docs for ${allowedPackages.length} packages`, + 1 + ); let successful = 0; - for (const pkg of packagesToProcess) { + for (const pkg of allowedPackages) { const result = await processPackage(pkg, sdkDir); if (result) successful++; } log.step( - `Generated docs for ${successful}/${packagesToProcess.length} packages`, + `Generated docs for ${successful}/${allowedPackages.length} packages`, 1 ); - if (submodules) { - for (const [parentPkg, submoduleNames] of Object.entries(submodules)) { - for (const submod of submoduleNames) { - const fullPkg = `${parentPkg}.${submod}`; - await processPackage(fullPkg, sdkDir); - } - } - } - return outputDir; } diff --git a/sdk-reference-generator/src/lib/cache.ts b/sdk-reference-generator/src/lib/cache.ts deleted file mode 100644 index 7406d3a..0000000 --- a/sdk-reference-generator/src/lib/cache.ts +++ /dev/null @@ -1,78 +0,0 @@ -import { createHash } from "crypto"; -import fs from "fs-extra"; -import path from "path"; -import type { GeneratorType } from "../types.js"; - -const LOCKFILES: Record = { - typedoc: ["pnpm-lock.yaml", "package-lock.json"], - cli: ["pnpm-lock.yaml", "package-lock.json"], - pydoc: ["poetry.lock"], -}; - -async function findLockfileUp( - dir: string, - filename: string -): Promise { - let current = dir; - - while (true) { - const lockPath = path.join(current, filename); - if (await fs.pathExists(lockPath)) { - return lockPath; - } - - const parent = path.dirname(current); - if (parent === current) { - break; - } - current = parent; - } - - return null; -} - -export async function hashLockfile( - sdkDir: string, - generator: GeneratorType -): Promise { - const lockfiles = LOCKFILES[generator]; - - for (const filename of lockfiles) { - const lockPath = await findLockfileUp(sdkDir, filename); - if (lockPath) { - const content = await fs.readFile(lockPath, "utf-8"); - return createHash("md5").update(content).digest("hex"); - } - } - - return null; -} - -export async function isCached( - hash: string, - generator: GeneratorType, - tempDir: string -): Promise { - const marker = path.join( - tempDir, - ".deps-cache", - `${generator}-${hash}`, - ".installed" - ); - return fs.pathExists(marker); -} - -export async function markCached( - hash: string, - generator: GeneratorType, - tempDir: string -): Promise { - const marker = path.join( - tempDir, - ".deps-cache", - `${generator}-${hash}`, - ".installed" - ); - await fs.ensureDir(path.dirname(marker)); - await fs.writeFile(marker, ""); -} diff --git a/sdk-reference-generator/src/lib/checkout.ts b/sdk-reference-generator/src/lib/checkout.ts new file mode 100644 index 0000000..a95434d --- /dev/null +++ b/sdk-reference-generator/src/lib/checkout.ts @@ -0,0 +1,48 @@ +import fs from "fs-extra"; +import path from "path"; +import { cloneAtTag, checkoutTag } from "./git.js"; +import { log } from "./log.js"; + +export class CheckoutManager { + private checkouts = new Map(); + + async getOrClone( + sdkKey: string, + repo: string, + tag: string, + tempDir: string + ): Promise { + const existing = this.checkouts.get(sdkKey); + if (existing) { + return existing; + } + + const repoDir = path.join(tempDir, `shared-${sdkKey}`); + log.info(`Cloning ${sdkKey} repository...`, 1); + await cloneAtTag(repo, tag, repoDir); + this.checkouts.set(sdkKey, repoDir); + return repoDir; + } + + async switchVersion(sdkKey: string, tag: string): Promise { + const repoDir = this.checkouts.get(sdkKey); + if (!repoDir) { + throw new Error(`Checkout not initialized for ${sdkKey}`); + } + + log.info(`Switching to ${tag}...`, 1); + await checkoutTag(repoDir, tag); + } + + getRepoDir(sdkKey: string): string | undefined { + return this.checkouts.get(sdkKey); + } + + async cleanup(): Promise { + for (const [sdkKey, dir] of this.checkouts.entries()) { + log.info(`Cleaning up ${sdkKey}...`, 1); + await fs.remove(dir); + } + this.checkouts.clear(); + } +} diff --git a/sdk-reference-generator/src/lib/git.ts b/sdk-reference-generator/src/lib/git.ts index f15f4a1..6adf395 100644 --- a/sdk-reference-generator/src/lib/git.ts +++ b/sdk-reference-generator/src/lib/git.ts @@ -93,3 +93,21 @@ export async function resolveLatestVersion( const versions = await fetchRemoteTags(repo, tagPattern); return versions[0] || null; } + +export async function checkoutTag(repoDir: string, tag: string): Promise { + const repoGit = simpleGit(repoDir); + + // fetch the specific tag with minimal depth + await repoGit.fetch([ + "origin", + `refs/tags/${tag}:refs/tags/${tag}`, + "--depth", + "1", + ]); + + // force checkout to discard any local changes + await repoGit.checkout(tag, ["--force"]); + + // clean untracked files (like node_modules changes) + await repoGit.clean("f", ["-d"]); +} diff --git a/sdk-reference-generator/src/lib/install.ts b/sdk-reference-generator/src/lib/install.ts index 4ccfc62..9f7750d 100644 --- a/sdk-reference-generator/src/lib/install.ts +++ b/sdk-reference-generator/src/lib/install.ts @@ -1,63 +1,62 @@ -import { execa } from 'execa'; -import type { GeneratorType } from '../types.js'; -import { hashLockfile, isCached, markCached } from './cache.js'; -import { log } from './log.js'; +import { execa } from "execa"; +import type { GeneratorType } from "../types.js"; +import { log } from "./log.js"; -async function installDependencies( +export async function installDependencies( sdkDir: string, generator: GeneratorType ): Promise { - log.info('Installing dependencies...', 1); + log.info("Installing dependencies...", 1); switch (generator) { - case 'typedoc': - case 'cli': { - const isTypedoc = generator === 'typedoc'; + case "typedoc": + case "cli": { + const isTypedoc = generator === "typedoc"; const baseArgs = isTypedoc - ? ['install', '--ignore-scripts', '--prefer-offline'] - : ['install', '--prefer-offline']; + ? ["install", "--ignore-scripts", "--prefer-offline"] + : ["install", "--prefer-offline"]; try { - await execa('pnpm', baseArgs, { + await execa("pnpm", baseArgs, { cwd: sdkDir, - stdio: 'inherit', + stdio: "inherit", }); } catch { - log.warn('Trying with relaxed engine constraints...', 1); + log.warn("Trying with relaxed engine constraints...", 1); try { - await execa('pnpm', ['--engine-strict=false', ...baseArgs], { + await execa("pnpm", ["--engine-strict=false", ...baseArgs], { cwd: sdkDir, - stdio: 'inherit', + stdio: "inherit", }); - } catch { - log.warn('pnpm failed, trying npm...', 1); - await execa( - 'npm', - ['install', '--legacy-peer-deps', '--force', '--prefer-offline'], - { - cwd: sdkDir, - stdio: 'inherit', - } - ); - } + } catch { + log.warn("pnpm failed, trying npm...", 1); + await execa( + "npm", + ["install", "--legacy-peer-deps", "--force", "--prefer-offline"], + { + cwd: sdkDir, + stdio: "inherit", + } + ); + } } break; } - case 'pydoc': { + case "pydoc": { try { - await execa('poetry', ['install', '--no-interaction'], { + await execa("poetry", ["install", "--no-interaction"], { cwd: sdkDir, - stdio: 'inherit', + stdio: "inherit", }); } catch { - log.warn('poetry failed, using global pydoc-markdown...', 1); + log.warn("poetry failed, using global pydoc-markdown...", 1); await execa( - 'pip', - ['install', '--break-system-packages', 'pydoc-markdown'], + "pip", + ["install", "--break-system-packages", "pydoc-markdown"], { cwd: sdkDir, - stdio: 'inherit', + stdio: "inherit", } ); } @@ -65,26 +64,3 @@ async function installDependencies( } } } - -export async function installWithCache( - sdkDir: string, - generator: GeneratorType, - tempDir: string -): Promise { - if (generator === 'pydoc') { - const hash = await hashLockfile(sdkDir, generator); - - if (hash && (await isCached(hash, generator, tempDir))) { - log.info('Poetry dependencies cached (lockfile unchanged)', 1); - return; - } - - await installDependencies(sdkDir, generator); - - if (hash) { - await markCached(hash, generator, tempDir); - } - } else { - await installDependencies(sdkDir, generator); - } -} diff --git a/sdk-reference-generator/src/types.ts b/sdk-reference-generator/src/types.ts index d7e35dc..2953b1e 100644 --- a/sdk-reference-generator/src/types.ts +++ b/sdk-reference-generator/src/types.ts @@ -17,9 +17,7 @@ type TypedocSDKConfig = BaseSDKConfig & { type PydocSDKConfig = BaseSDKConfig & { generator: "pydoc"; - basePackage: string; - fallbackPackages?: readonly string[]; - submodules?: Record; + allowedPackages: readonly string[]; }; type CLISDKConfig = BaseSDKConfig & { From 9ce811fc495b325a9b22aa06e193514b805faad0 Mon Sep 17 00:00:00 2001 From: ben-fornefeld Date: Thu, 8 Jan 2026 13:54:21 +0100 Subject: [PATCH 16/39] chore --- sdk-reference-generator/src/lib/git.ts | 3 --- 1 file changed, 3 deletions(-) diff --git a/sdk-reference-generator/src/lib/git.ts b/sdk-reference-generator/src/lib/git.ts index 6adf395..6fa8468 100644 --- a/sdk-reference-generator/src/lib/git.ts +++ b/sdk-reference-generator/src/lib/git.ts @@ -97,7 +97,6 @@ export async function resolveLatestVersion( export async function checkoutTag(repoDir: string, tag: string): Promise { const repoGit = simpleGit(repoDir); - // fetch the specific tag with minimal depth await repoGit.fetch([ "origin", `refs/tags/${tag}:refs/tags/${tag}`, @@ -105,9 +104,7 @@ export async function checkoutTag(repoDir: string, tag: string): Promise { "1", ]); - // force checkout to discard any local changes await repoGit.checkout(tag, ["--force"]); - // clean untracked files (like node_modules changes) await repoGit.clean("f", ["-d"]); } From a0aa2e415ac693c8bac61096459c926f6cdd54eb Mon Sep 17 00:00:00 2001 From: ben-fornefeld Date: Thu, 8 Jan 2026 14:14:37 +0100 Subject: [PATCH 17/39] cleanup --- sdk-reference-generator/README.md | 16 +++--- .../configs/typedoc-theme.cjs | 2 +- .../src/__tests__/verify.test.ts | 55 ++++++++++++++++--- sdk-reference-generator/src/cli.ts | 15 ++--- sdk-reference-generator/src/generator.ts | 45 +++++++++------ .../src/generators/index.ts | 25 --------- sdk-reference-generator/src/lib/config.ts | 16 ------ sdk-reference-generator/src/lib/files.ts | 23 ++++++-- sdk-reference-generator/src/lib/install.ts | 26 +++------ sdk-reference-generator/src/lib/verify.ts | 11 +++- sdk-reference-generator/src/navigation.ts | 5 +- 11 files changed, 126 insertions(+), 113 deletions(-) delete mode 100644 sdk-reference-generator/src/generators/index.ts delete mode 100644 sdk-reference-generator/src/lib/config.ts diff --git a/sdk-reference-generator/README.md b/sdk-reference-generator/README.md index 1d963e0..792ef07 100644 --- a/sdk-reference-generator/README.md +++ b/sdk-reference-generator/README.md @@ -41,15 +41,14 @@ src/ ├── cli.ts # Entry point with CLI argument parsing ├── generator.ts # Core SDK generation orchestration ├── navigation.ts # Mintlify navigation builder -├── types.ts # TypeScript interfaces and Zod schemas +├── types.ts # TypeScript interfaces ├── lib/ │ ├── constants.ts # Centralized magic strings │ ├── utils.ts # Pure utility functions -│ ├── config.ts # SDK configuration loading │ ├── git.ts # Git operations (clone, tags) +│ ├── checkout.ts # Manages repo checkouts and version switching │ ├── versions.ts # Version comparison and filtering -│ ├── files.ts # Markdown processing -│ ├── cache.ts # Dependency caching +│ ├── files.ts # Markdown processing and flattening │ ├── install.ts # Package manager abstraction │ └── verify.ts # Post-generation validation └── generators/ @@ -94,11 +93,10 @@ SDKs are configured in `sdks.json`: For maximum compatibility across SDK versions: -1. **Try strict install** - Uses exact engine requirements -2. **Try relaxed install** - Ignores engine constraints (`--engine-strict=false`) -3. **Try npm fallback** - Uses npm with `--force` and `--legacy-peer-deps` +1. **Try pnpm install** - Primary package manager with caching +2. **Try npm fallback** - Uses npm with `--force` and `--legacy-peer-deps` -Each strategy visible in logs for debugging. If all strategies fail, workflow aborts. +Each strategy visible in logs for debugging. If both strategies fail, workflow aborts. ### What Gets Logged @@ -149,7 +147,7 @@ Safety features: ## Performance -- **Dependency Caching**: Poetry installs cached by lockfile hash +- **Checkout Reuse**: Repository cloned once, versions switched via git checkout - **Version Deduplication**: Batch comparison skips already-generated versions - **Parallel Generation**: Could process multiple versions concurrently (future enhancement) diff --git a/sdk-reference-generator/configs/typedoc-theme.cjs b/sdk-reference-generator/configs/typedoc-theme.cjs index c434d84..b1cb1de 100644 --- a/sdk-reference-generator/configs/typedoc-theme.cjs +++ b/sdk-reference-generator/configs/typedoc-theme.cjs @@ -53,7 +53,7 @@ function removeLinesWithConditions(text) { continue } - filteredLines.push(convertH5toH3(lines[i])) + filteredLines.push(lines[i]) } return filteredLines.join('\n') diff --git a/sdk-reference-generator/src/__tests__/verify.test.ts b/sdk-reference-generator/src/__tests__/verify.test.ts index 1b72a52..c31ea49 100644 --- a/sdk-reference-generator/src/__tests__/verify.test.ts +++ b/sdk-reference-generator/src/__tests__/verify.test.ts @@ -2,7 +2,7 @@ import { describe, it, expect, beforeEach, afterEach } from 'vitest'; import fs from 'fs-extra'; import path from 'path'; import os from 'os'; -import { verifyGeneratedDocs, verifyDocsJson } from '../lib/verify.js'; +import { verifyGeneratedDocs } from '../lib/verify.js'; import { CONSTANTS } from '../lib/constants.js'; describe('verifyGeneratedDocs', () => { @@ -24,9 +24,24 @@ describe('verifyGeneratedDocs', () => { '---\nsidebarTitle: "Test"\n---\n\nContent' ); + // create valid docs.json + const docsJson = { + navigation: { + anchors: [ + { + anchor: CONSTANTS.SDK_REFERENCE_ANCHOR, + icon: 'brackets-curly', + dropdowns: [], + }, + ], + }, + }; + await fs.writeJSON(path.join(tempDir, 'docs.json'), docsJson); + const result = await verifyGeneratedDocs(tempDir); expect(result.valid).toBe(true); + expect(result.docsJsonValid).toBe(true); expect(result.errors).toHaveLength(0); expect(result.stats.totalMdxFiles).toBe(1); expect(result.stats.totalSDKs).toBe(1); @@ -68,7 +83,7 @@ describe('verifyGeneratedDocs', () => { }); }); -describe('verifyDocsJson', () => { +describe('verifyDocsJson via verifyGeneratedDocs', () => { let tempDir: string; beforeEach(async () => { @@ -80,6 +95,13 @@ describe('verifyDocsJson', () => { }); it('validates correct docs.json structure', async () => { + const sdkPath = path.join(tempDir, CONSTANTS.DOCS_SDK_REF_PATH, 'test-sdk', 'v1.0.0'); + await fs.ensureDir(sdkPath); + await fs.writeFile( + path.join(sdkPath, 'test.mdx'), + '---\nsidebarTitle: "Test"\n---\n\nContent' + ); + const docsJson = { navigation: { anchors: [ @@ -94,16 +116,32 @@ describe('verifyDocsJson', () => { await fs.writeJSON(path.join(tempDir, 'docs.json'), docsJson); - const result = await verifyDocsJson(tempDir); - expect(result).toBe(true); + const result = await verifyGeneratedDocs(tempDir); + expect(result.docsJsonValid).toBe(true); + expect(result.valid).toBe(true); }); it('fails when docs.json missing', async () => { - const result = await verifyDocsJson(tempDir); - expect(result).toBe(false); + const sdkPath = path.join(tempDir, CONSTANTS.DOCS_SDK_REF_PATH, 'test-sdk', 'v1.0.0'); + await fs.ensureDir(sdkPath); + await fs.writeFile( + path.join(sdkPath, 'test.mdx'), + '---\nsidebarTitle: "Test"\n---\n\nContent' + ); + + const result = await verifyGeneratedDocs(tempDir); + expect(result.docsJsonValid).toBe(false); + expect(result.valid).toBe(false); }); it('fails when SDK Reference anchor missing', async () => { + const sdkPath = path.join(tempDir, CONSTANTS.DOCS_SDK_REF_PATH, 'test-sdk', 'v1.0.0'); + await fs.ensureDir(sdkPath); + await fs.writeFile( + path.join(sdkPath, 'test.mdx'), + '---\nsidebarTitle: "Test"\n---\n\nContent' + ); + const docsJson = { navigation: { anchors: [{ anchor: 'Other', dropdowns: [] }], @@ -112,8 +150,9 @@ describe('verifyDocsJson', () => { await fs.writeJSON(path.join(tempDir, 'docs.json'), docsJson); - const result = await verifyDocsJson(tempDir); - expect(result).toBe(false); + const result = await verifyGeneratedDocs(tempDir); + expect(result.docsJsonValid).toBe(false); + expect(result.valid).toBe(false); }); }); diff --git a/sdk-reference-generator/src/cli.ts b/sdk-reference-generator/src/cli.ts index f04f7f1..c6230c8 100644 --- a/sdk-reference-generator/src/cli.ts +++ b/sdk-reference-generator/src/cli.ts @@ -5,10 +5,10 @@ import fs from "fs-extra"; import path from "path"; import os from "os"; import { fileURLToPath } from "url"; -import { getAllSDKKeys } from "./lib/config.js"; +import sdks from "../sdks.config.js"; import { generateSDK } from "./generator.js"; import { buildNavigation, mergeNavigation } from "./navigation.js"; -import { verifyGeneratedDocs, verifyDocsJson } from "./lib/verify.js"; +import { verifyGeneratedDocs } from "./lib/verify.js"; import { log } from "./lib/log.js"; import type { GenerationContext, GenerationResult } from "./types.js"; @@ -63,7 +63,7 @@ async function main(): Promise { }; try { - const sdkKeys = opts.sdk === "all" ? getAllSDKKeys() : [opts.sdk]; + const sdkKeys = opts.sdk === "all" ? Object.keys(sdks) : [opts.sdk]; const results: Map = new Map(); @@ -98,12 +98,9 @@ async function main(): Promise { for (const error of verification.errors) { log.data(`- ${error}`, 1); } - process.exit(1); - } - - const docsJsonValid = await verifyDocsJson(DOCS_DIR); - if (!docsJsonValid) { - log.error("docs.json validation failed"); + if (!verification.docsJsonValid) { + log.error("docs.json validation failed"); + } process.exit(1); } diff --git a/sdk-reference-generator/src/generator.ts b/sdk-reference-generator/src/generator.ts index d62a043..f44aa77 100644 --- a/sdk-reference-generator/src/generator.ts +++ b/sdk-reference-generator/src/generator.ts @@ -5,7 +5,7 @@ import type { GenerationContext, GenerationResult, } from "./types.js"; -import { getSDKConfig } from "./lib/config.js"; +import sdks from "../sdks.config.js"; import { log } from "./lib/log.js"; import { fetchRemoteTags, resolveLatestVersion } from "./lib/git.js"; import { @@ -16,7 +16,9 @@ import { } from "./lib/versions.js"; import { flattenMarkdown, copyToDocs, locateSDKDir } from "./lib/files.js"; import { installDependencies } from "./lib/install.js"; -import { runGenerator } from "./generators/index.js"; +import { generateTypedoc } from "./generators/typedoc.js"; +import { generatePydoc } from "./generators/pydoc.js"; +import { generateCli } from "./generators/cli.js"; import { buildSDKPath } from "./lib/utils.js"; import { CONSTANTS } from "./lib/constants.js"; import { CheckoutManager } from "./lib/checkout.js"; @@ -59,7 +61,19 @@ async function generateVersion( await fs.remove(sdkRefDir); await installDependencies(sdkDir, config.generator); - const generatedDocsDir = await runGenerator(sdkDir, config, context); + + let generatedDocsDir: string; + switch (config.generator) { + case "typedoc": + generatedDocsDir = await generateTypedoc(sdkDir, context.configsDir); + break; + case "pydoc": + generatedDocsDir = await generatePydoc(sdkDir, config.allowedPackages); + break; + case "cli": + generatedDocsDir = await generateCli(sdkDir); + break; + } if (generatedDocsDir !== sdkRefDir) { log.info(`Normalizing ${path.basename(generatedDocsDir)} to sdk_ref`, 1); @@ -250,18 +264,17 @@ function handleGenerationFailures( 1 ); - if (failed > 0) { - if (config.required) { - log.blank(); - log.error("WORKFLOW ABORTED: Required SDK has failures", 1); - log.error(`Failed: ${failedVersions.join(" ")}`, 1); - process.exit(1); - } else if (generated === 0) { - log.blank(); - log.error("WORKFLOW ABORTED: All versions failed", 1); - log.error(`Failed: ${failedVersions.join(" ")}`, 1); - process.exit(1); - } + if (failed === 0) return; + + const shouldAbort = config.required || generated === 0; + if (shouldAbort) { + log.blank(); + const reason = config.required + ? "Required SDK has failures" + : "All versions failed"; + log.error(`WORKFLOW ABORTED: ${reason}`, 1); + log.error(`Failed: ${failedVersions.join(" ")}`, 1); + process.exit(1); } } @@ -270,7 +283,7 @@ export async function generateSDK( versionArg: string, context: GenerationContext ): Promise { - const config = getSDKConfig(sdkKey); + const config = sdks[sdkKey as keyof typeof sdks]; if (!config) { log.error(`SDK '${sdkKey}' not found in config`, 1); diff --git a/sdk-reference-generator/src/generators/index.ts b/sdk-reference-generator/src/generators/index.ts deleted file mode 100644 index c30e354..0000000 --- a/sdk-reference-generator/src/generators/index.ts +++ /dev/null @@ -1,25 +0,0 @@ -import type { SDKConfig, GenerationContext } from "../types.js"; -import { generateTypedoc } from "./typedoc.js"; -import { generatePydoc } from "./pydoc.js"; -import { generateCli } from "./cli.js"; - -export async function runGenerator( - sdkDir: string, - config: SDKConfig, - context: GenerationContext -): Promise { - switch (config.generator) { - case "typedoc": - return await generateTypedoc(sdkDir, context.configsDir); - - case "pydoc": - return await generatePydoc(sdkDir, config.allowedPackages); - - case "cli": - return await generateCli(sdkDir); - } -} - -export { generateTypedoc } from "./typedoc.js"; -export { generatePydoc } from "./pydoc.js"; -export { generateCli } from "./cli.js"; diff --git a/sdk-reference-generator/src/lib/config.ts b/sdk-reference-generator/src/lib/config.ts deleted file mode 100644 index d007e37..0000000 --- a/sdk-reference-generator/src/lib/config.ts +++ /dev/null @@ -1,16 +0,0 @@ -import sdks from "../../sdks.config.js"; -import type { SDKConfig, ConfigFile } from "../types.js"; - -export function getConfig(): ConfigFile { - return { sdks }; -} - -export function getSDKConfig(sdkKey: string): SDKConfig | null { - const config = getConfig(); - return config.sdks[sdkKey] || null; -} - -export function getAllSDKKeys(): string[] { - const config = getConfig(); - return Object.keys(config.sdks); -} diff --git a/sdk-reference-generator/src/lib/files.ts b/sdk-reference-generator/src/lib/files.ts index 63a467c..f00372b 100644 --- a/sdk-reference-generator/src/lib/files.ts +++ b/sdk-reference-generator/src/lib/files.ts @@ -50,10 +50,13 @@ export async function addFrontmatter( await fs.writeFile(file, createFrontmatter(title) + content); } -export async function flattenMarkdown(refDir: string): Promise { +async function removeUnwantedFiles(refDir: string): Promise { await fs.remove(path.join(refDir, "README.md")); await fs.remove(path.join(refDir, "index.md")); + await fs.remove(path.join(refDir, `index${CONSTANTS.MDX_EXTENSION}`)); +} +async function flattenNestedFiles(refDir: string): Promise { const nestedFiles = await glob("**/*.md", { cwd: refDir, ignore: "*.md", @@ -90,7 +93,9 @@ export async function flattenMarkdown(refDir: string): Promise { log.warn(`Detected ${collisions.length} filename collision(s):`, 1); collisions.forEach((c) => log.data(c, 2)); } +} +async function removeEmptyDirectories(refDir: string): Promise { const dirs = await glob("**/", { cwd: refDir }); for (const dir of dirs.reverse()) { const dirPath = path.join(refDir, dir); @@ -101,7 +106,9 @@ export async function flattenMarkdown(refDir: string): Promise { } } catch {} } +} +async function convertMdToMdx(refDir: string): Promise { const mdFiles = await glob("*.md", { cwd: refDir }); for (const file of mdFiles) { @@ -116,7 +123,9 @@ export async function flattenMarkdown(refDir: string): Promise { await fs.writeFile(mdxPath, createFrontmatter(title) + content); await fs.remove(fullPath); } +} +async function ensureFrontmatter(refDir: string): Promise { const mdxFiles = await glob(`*${CONSTANTS.MDX_EXTENSION}`, { cwd: refDir }); for (const file of mdxFiles) { @@ -128,19 +137,21 @@ export async function flattenMarkdown(refDir: string): Promise { await addFrontmatter(fullPath, title); } } +} - await fs.remove(path.join(refDir, `index${CONSTANTS.MDX_EXTENSION}`)); +export async function flattenMarkdown(refDir: string): Promise { + await removeUnwantedFiles(refDir); + await flattenNestedFiles(refDir); + await removeEmptyDirectories(refDir); + await convertMdToMdx(refDir); + await ensureFrontmatter(refDir); } async function getNonEmptyMdxFiles(dir: string): Promise { - await fs.remove(path.join(dir, `*${CONSTANTS.MDX_EXTENSION}`)); - const allFiles = await glob(`*${CONSTANTS.MDX_EXTENSION}`, { cwd: dir }); const nonEmptyFiles: string[] = []; for (const file of allFiles) { - if (file === `*${CONSTANTS.MDX_EXTENSION}`) continue; - const stat = await fs.stat(path.join(dir, file)); if (stat.size > 0) { nonEmptyFiles.push(file); diff --git a/sdk-reference-generator/src/lib/install.ts b/sdk-reference-generator/src/lib/install.ts index 9f7750d..dac7345 100644 --- a/sdk-reference-generator/src/lib/install.ts +++ b/sdk-reference-generator/src/lib/install.ts @@ -12,33 +12,25 @@ export async function installDependencies( case "typedoc": case "cli": { const isTypedoc = generator === "typedoc"; - const baseArgs = isTypedoc + const pnpmArgs = isTypedoc ? ["install", "--ignore-scripts", "--prefer-offline"] : ["install", "--prefer-offline"]; try { - await execa("pnpm", baseArgs, { + await execa("pnpm", pnpmArgs, { cwd: sdkDir, stdio: "inherit", }); } catch { - log.warn("Trying with relaxed engine constraints...", 1); - try { - await execa("pnpm", ["--engine-strict=false", ...baseArgs], { + log.warn("pnpm failed, falling back to npm...", 1); + await execa( + "npm", + ["install", "--legacy-peer-deps", "--force", "--prefer-offline"], + { cwd: sdkDir, stdio: "inherit", - }); - } catch { - log.warn("pnpm failed, trying npm...", 1); - await execa( - "npm", - ["install", "--legacy-peer-deps", "--force", "--prefer-offline"], - { - cwd: sdkDir, - stdio: "inherit", - } - ); - } + } + ); } break; } diff --git a/sdk-reference-generator/src/lib/verify.ts b/sdk-reference-generator/src/lib/verify.ts index d64272f..130ff9f 100644 --- a/sdk-reference-generator/src/lib/verify.ts +++ b/sdk-reference-generator/src/lib/verify.ts @@ -13,6 +13,7 @@ export interface VerificationResult { totalSDKs: number; totalVersions: number; }; + docsJsonValid: boolean; } export async function verifyGeneratedDocs( @@ -26,7 +27,7 @@ export async function verifyGeneratedDocs( if (!(await fs.pathExists(sdkRefDir))) { errors.push('SDK reference directory does not exist'); - return { valid: false, errors, warnings, stats }; + return { valid: false, errors, warnings, stats, docsJsonValid: false }; } const sdkDirs = await fs.readdir(sdkRefDir, { withFileTypes: true }); @@ -78,15 +79,19 @@ export async function verifyGeneratedDocs( } } + // verify docs.json + const docsJsonValid = await verifyDocsJson(docsDir); + return { - valid: errors.length === 0, + valid: errors.length === 0 && docsJsonValid, errors, warnings, stats, + docsJsonValid, }; } -export async function verifyDocsJson(docsDir: string): Promise { +async function verifyDocsJson(docsDir: string): Promise { const docsJsonPath = path.join(docsDir, 'docs.json'); if (!(await fs.pathExists(docsJsonPath))) { diff --git a/sdk-reference-generator/src/navigation.ts b/sdk-reference-generator/src/navigation.ts index 2528798..0a2145b 100644 --- a/sdk-reference-generator/src/navigation.ts +++ b/sdk-reference-generator/src/navigation.ts @@ -1,6 +1,6 @@ import fs from "fs-extra"; import path from "path"; -import { getConfig } from "./lib/config.js"; +import sdks from "../sdks.config.js"; import { sortVersionsDescending, isValidVersion, @@ -42,7 +42,6 @@ async function getModules(versionDir: string): Promise { export async function buildNavigation( docsDir: string ): Promise { - const config = getConfig(); const sdkRefDir = path.join(docsDir, CONSTANTS.DOCS_SDK_REF_PATH); if (!(await fs.pathExists(sdkRefDir))) { @@ -52,7 +51,7 @@ export async function buildNavigation( const navigation: NavigationDropdownWithOrder[] = []; - for (const [sdkKey, sdkConfig] of Object.entries(config.sdks)) { + for (const [sdkKey, sdkConfig] of Object.entries(sdks)) { const sdkDir = path.join(sdkRefDir, sdkKey); if (!(await fs.pathExists(sdkDir))) { From 38682df4dddb13d0c75b9400eec4e85d5ca532c0 Mon Sep 17 00:00:00 2001 From: ben-fornefeld Date: Thu, 8 Jan 2026 14:38:42 +0100 Subject: [PATCH 18/39] refactor: improve error handling and logging in CLI and generator - Enhanced error handling in the CLI to ensure proper exit on validation failures. - Improved logging for workflow abort scenarios in the generator, ensuring clearer output. - Introduced a new function to find the CLI output directory, enhancing the generation process and error reporting for missing markdown files. --- sdk-reference-generator/src/cli.ts | 2 +- sdk-reference-generator/src/generator.ts | 6 ++-- sdk-reference-generator/src/generators/cli.ts | 30 +++++++++++++++++-- sdk-reference-generator/src/lib/install.ts | 16 +++++----- 4 files changed, 39 insertions(+), 15 deletions(-) diff --git a/sdk-reference-generator/src/cli.ts b/sdk-reference-generator/src/cli.ts index c6230c8..c935684 100644 --- a/sdk-reference-generator/src/cli.ts +++ b/sdk-reference-generator/src/cli.ts @@ -100,7 +100,7 @@ async function main(): Promise { } if (!verification.docsJsonValid) { log.error("docs.json validation failed"); - } + } process.exit(1); } diff --git a/sdk-reference-generator/src/generator.ts b/sdk-reference-generator/src/generator.ts index f44aa77..04aebb0 100644 --- a/sdk-reference-generator/src/generator.ts +++ b/sdk-reference-generator/src/generator.ts @@ -268,13 +268,13 @@ function handleGenerationFailures( const shouldAbort = config.required || generated === 0; if (shouldAbort) { - log.blank(); + log.blank(); const reason = config.required ? "Required SDK has failures" : "All versions failed"; log.error(`WORKFLOW ABORTED: ${reason}`, 1); - log.error(`Failed: ${failedVersions.join(" ")}`, 1); - process.exit(1); + log.error(`Failed: ${failedVersions.join(" ")}`, 1); + process.exit(1); } } diff --git a/sdk-reference-generator/src/generators/cli.ts b/sdk-reference-generator/src/generators/cli.ts index 4adc1e9..d6fc9d9 100644 --- a/sdk-reference-generator/src/generators/cli.ts +++ b/sdk-reference-generator/src/generators/cli.ts @@ -5,6 +5,25 @@ import { glob } from "glob"; import { CONSTANTS } from "../lib/constants.js"; import { log } from "../lib/log.js"; +async function findCliOutputDir(sdkDir: string): Promise { + const possibleDirs = ["sdk_ref", "api_ref"]; + + for (const dir of possibleDirs) { + const fullPath = path.join(sdkDir, dir); + if (await fs.pathExists(fullPath)) { + const mdFiles = await glob(`*${CONSTANTS.MD_EXTENSION}`, { + cwd: fullPath, + }); + if (mdFiles.length > 0) { + log.info(`Found CLI docs in ${dir}/`, 1); + return fullPath; + } + } + } + + return null; +} + export async function generateCli(sdkDir: string): Promise { log.info("Building CLI...", 1); @@ -23,15 +42,20 @@ export async function generateCli(sdkDir: string): Promise { log.info("Generating documentation...", 1); - const outputDir = path.join(sdkDir, CONSTANTS.SDK_REF_DIR); - await fs.ensureDir(outputDir); - await execa("node", ["dist/index.js", "-cmd2md"], { cwd: sdkDir, env: { ...process.env, NODE_ENV: "development" }, stdio: "inherit", }); + const outputDir = await findCliOutputDir(sdkDir); + + if (!outputDir) { + throw new Error( + "CLI generator did not create any markdown files in sdk_ref/ or api_ref/" + ); + } + const mdFiles = await glob(`*${CONSTANTS.MD_EXTENSION}`, { cwd: outputDir }); for (const file of mdFiles) { diff --git a/sdk-reference-generator/src/lib/install.ts b/sdk-reference-generator/src/lib/install.ts index dac7345..b6b2ee0 100644 --- a/sdk-reference-generator/src/lib/install.ts +++ b/sdk-reference-generator/src/lib/install.ts @@ -23,14 +23,14 @@ export async function installDependencies( }); } catch { log.warn("pnpm failed, falling back to npm...", 1); - await execa( - "npm", - ["install", "--legacy-peer-deps", "--force", "--prefer-offline"], - { - cwd: sdkDir, - stdio: "inherit", - } - ); + await execa( + "npm", + ["install", "--legacy-peer-deps", "--force", "--prefer-offline"], + { + cwd: sdkDir, + stdio: "inherit", + } + ); } break; } From 42c4f4f9a7471a94d48ade40f7b1fff5603b5c70 Mon Sep 17 00:00:00 2001 From: ben-fornefeld Date: Thu, 8 Jan 2026 14:38:54 +0100 Subject: [PATCH 19/39] add: last 3 versions of all sdks to docs --- docs.json | 357 +++ docs/sdk-reference/cli/1.0.0/auth.mdx | 63 + docs/sdk-reference/cli/1.0.0/sandbox.mdx | 94 + docs/sdk-reference/cli/1.0.0/template.mdx | 95 + docs/sdk-reference/cli/v2.3.3/auth.mdx | 63 + docs/sdk-reference/cli/v2.3.3/sandbox.mdx | 140 ++ docs/sdk-reference/cli/v2.3.3/template.mdx | 185 ++ docs/sdk-reference/cli/v2.4.0/auth.mdx | 63 + docs/sdk-reference/cli/v2.4.0/sandbox.mdx | 140 ++ docs/sdk-reference/cli/v2.4.0/template.mdx | 185 ++ docs/sdk-reference/cli/v2.4.1/auth.mdx | 63 + docs/sdk-reference/cli/v2.4.1/sandbox.mdx | 140 ++ docs/sdk-reference/cli/v2.4.1/template.mdx | 185 ++ docs/sdk-reference/cli/v2.4.2/auth.mdx | 63 + docs/sdk-reference/cli/v2.4.2/sandbox.mdx | 140 ++ docs/sdk-reference/cli/v2.4.2/template.mdx | 185 ++ .../code-interpreter-js-sdk/v2.3.0/charts.mdx | 245 ++ .../code-interpreter-js-sdk/v2.3.0/consts.mdx | 18 + .../v2.3.0/messaging.mdx | 331 +++ .../v2.3.0/sandbox.mdx | 371 +++ .../code-interpreter-js-sdk/v2.3.1/charts.mdx | 245 ++ .../code-interpreter-js-sdk/v2.3.1/consts.mdx | 18 + .../v2.3.1/messaging.mdx | 331 +++ .../v2.3.1/sandbox.mdx | 371 +++ .../code-interpreter-js-sdk/v2.3.2/charts.mdx | 245 ++ .../code-interpreter-js-sdk/v2.3.2/consts.mdx | 18 + .../v2.3.2/messaging.mdx | 331 +++ .../v2.3.2/sandbox.mdx | 371 +++ .../code-interpreter-js-sdk/v2.3.3/charts.mdx | 245 ++ .../code-interpreter-js-sdk/v2.3.3/consts.mdx | 18 + .../v2.3.3/messaging.mdx | 331 +++ .../v2.3.3/sandbox.mdx | 371 +++ .../1.0.1/code_interpreter.mdx | 786 +++++++ .../1.0.4/code_interpreter.mdx | 786 +++++++ .../v2.2.1/code_interpreter.mdx | 789 +++++++ .../v2.3.0/code_interpreter.mdx | 789 +++++++ .../v2.4.0/code_interpreter.mdx | 889 +++++++ .../v2.4.1/code_interpreter.mdx | 889 +++++++ .../desktop-js-sdk/v2.1.0/sandbox.mdx | 697 ++++++ .../desktop-js-sdk/v2.2.0/sandbox.mdx | 697 ++++++ .../desktop-js-sdk/v2.2.1/sandbox.mdx | 697 ++++++ .../desktop-js-sdk/v2.2.2/sandbox.mdx | 697 ++++++ .../desktop-python-sdk/v2.0.0/desktop.mdx | 371 +++ .../desktop-python-sdk/v2.0.1/desktop.mdx | 371 +++ .../desktop-python-sdk/v2.1.0/desktop.mdx | 371 +++ .../desktop-python-sdk/v2.2.0/desktop.mdx | 371 +++ docs/sdk-reference/js-sdk/1.0.0/errors.mdx | 197 ++ .../js-sdk/1.0.0/sandbox-filesystem.mdx | 521 +++++ docs/sdk-reference/js-sdk/1.0.0/sandbox.mdx | 586 +++++ docs/sdk-reference/js-sdk/v2.8.2/errors.mdx | 271 +++ .../js-sdk/v2.8.2/sandbox-commands.mdx | 533 +++++ .../js-sdk/v2.8.2/sandbox-filesystem.mdx | 627 +++++ docs/sdk-reference/js-sdk/v2.8.2/sandbox.mdx | 712 ++++++ .../js-sdk/v2.8.2/template-logger.mdx | 196 ++ .../js-sdk/v2.8.2/template-readycmd.mdx | 202 ++ docs/sdk-reference/js-sdk/v2.8.2/template.mdx | 2042 ++++++++++++++++ docs/sdk-reference/js-sdk/v2.8.3/errors.mdx | 271 +++ .../js-sdk/v2.8.3/sandbox-commands.mdx | 533 +++++ .../js-sdk/v2.8.3/sandbox-filesystem.mdx | 627 +++++ docs/sdk-reference/js-sdk/v2.8.3/sandbox.mdx | 712 ++++++ .../js-sdk/v2.8.3/template-logger.mdx | 196 ++ .../js-sdk/v2.8.3/template-readycmd.mdx | 202 ++ docs/sdk-reference/js-sdk/v2.8.3/template.mdx | 2042 ++++++++++++++++ docs/sdk-reference/js-sdk/v2.8.4/errors.mdx | 271 +++ .../js-sdk/v2.8.4/sandbox-commands.mdx | 533 +++++ .../js-sdk/v2.8.4/sandbox-filesystem.mdx | 627 +++++ docs/sdk-reference/js-sdk/v2.8.4/sandbox.mdx | 712 ++++++ .../js-sdk/v2.8.4/template-logger.mdx | 196 ++ .../js-sdk/v2.8.4/template-readycmd.mdx | 202 ++ docs/sdk-reference/js-sdk/v2.8.4/template.mdx | 2042 ++++++++++++++++ docs/sdk-reference/js-sdk/v2.9.0/errors.mdx | 271 +++ .../js-sdk/v2.9.0/sandbox-commands.mdx | 554 +++++ .../js-sdk/v2.9.0/sandbox-filesystem.mdx | 627 +++++ docs/sdk-reference/js-sdk/v2.9.0/sandbox.mdx | 712 ++++++ .../js-sdk/v2.9.0/template-logger.mdx | 196 ++ .../js-sdk/v2.9.0/template-readycmd.mdx | 202 ++ docs/sdk-reference/js-sdk/v2.9.0/template.mdx | 2044 +++++++++++++++++ .../python-sdk/1.0.0/exceptions.mdx | 87 + .../python-sdk/1.0.0/sandbox_async.mdx | 985 ++++++++ .../python-sdk/1.0.0/sandbox_sync.mdx | 959 ++++++++ .../python-sdk/v2.7.0/exceptions.mdx | 117 + .../python-sdk/v2.7.0/logger.mdx | 106 + .../python-sdk/v2.7.0/readycmd.mdx | 168 ++ .../python-sdk/v2.7.0/sandbox_async.mdx | 1387 +++++++++++ .../python-sdk/v2.7.0/sandbox_sync.mdx | 1343 +++++++++++ .../python-sdk/v2.7.0/template.mdx | 1686 ++++++++++++++ .../python-sdk/v2.7.0/template_async.mdx | 150 ++ .../python-sdk/v2.7.0/template_sync.mdx | 150 ++ .../python-sdk/v2.8.0/exceptions.mdx | 117 + .../python-sdk/v2.8.0/logger.mdx | 106 + .../python-sdk/v2.8.0/readycmd.mdx | 168 ++ .../python-sdk/v2.8.0/sandbox_async.mdx | 1387 +++++++++++ .../python-sdk/v2.8.0/sandbox_sync.mdx | 1343 +++++++++++ .../python-sdk/v2.8.0/template.mdx | 1686 ++++++++++++++ .../python-sdk/v2.8.0/template_async.mdx | 150 ++ .../python-sdk/v2.8.0/template_sync.mdx | 150 ++ .../python-sdk/v2.8.1/exceptions.mdx | 117 + .../python-sdk/v2.8.1/logger.mdx | 106 + .../python-sdk/v2.8.1/readycmd.mdx | 168 ++ .../python-sdk/v2.8.1/sandbox_async.mdx | 1387 +++++++++++ .../python-sdk/v2.8.1/sandbox_sync.mdx | 1343 +++++++++++ .../python-sdk/v2.8.1/template.mdx | 1704 ++++++++++++++ .../python-sdk/v2.8.1/template_async.mdx | 150 ++ .../python-sdk/v2.8.1/template_sync.mdx | 150 ++ .../python-sdk/v2.9.0/exceptions.mdx | 117 + .../python-sdk/v2.9.0/logger.mdx | 106 + .../python-sdk/v2.9.0/readycmd.mdx | 168 ++ .../python-sdk/v2.9.0/sandbox_async.mdx | 1412 ++++++++++++ .../python-sdk/v2.9.0/sandbox_sync.mdx | 1365 +++++++++++ .../python-sdk/v2.9.0/template.mdx | 1706 ++++++++++++++ .../python-sdk/v2.9.0/template_async.mdx | 150 ++ .../python-sdk/v2.9.0/template_sync.mdx | 150 ++ sdk-reference-generator/src/lib/files.ts | 6 +- 113 files changed, 57427 insertions(+), 3 deletions(-) create mode 100644 docs/sdk-reference/cli/1.0.0/auth.mdx create mode 100644 docs/sdk-reference/cli/1.0.0/sandbox.mdx create mode 100644 docs/sdk-reference/cli/1.0.0/template.mdx create mode 100644 docs/sdk-reference/cli/v2.3.3/auth.mdx create mode 100644 docs/sdk-reference/cli/v2.3.3/sandbox.mdx create mode 100644 docs/sdk-reference/cli/v2.3.3/template.mdx create mode 100644 docs/sdk-reference/cli/v2.4.0/auth.mdx create mode 100644 docs/sdk-reference/cli/v2.4.0/sandbox.mdx create mode 100644 docs/sdk-reference/cli/v2.4.0/template.mdx create mode 100644 docs/sdk-reference/cli/v2.4.1/auth.mdx create mode 100644 docs/sdk-reference/cli/v2.4.1/sandbox.mdx create mode 100644 docs/sdk-reference/cli/v2.4.1/template.mdx create mode 100644 docs/sdk-reference/cli/v2.4.2/auth.mdx create mode 100644 docs/sdk-reference/cli/v2.4.2/sandbox.mdx create mode 100644 docs/sdk-reference/cli/v2.4.2/template.mdx create mode 100644 docs/sdk-reference/code-interpreter-js-sdk/v2.3.0/charts.mdx create mode 100644 docs/sdk-reference/code-interpreter-js-sdk/v2.3.0/consts.mdx create mode 100644 docs/sdk-reference/code-interpreter-js-sdk/v2.3.0/messaging.mdx create mode 100644 docs/sdk-reference/code-interpreter-js-sdk/v2.3.0/sandbox.mdx create mode 100644 docs/sdk-reference/code-interpreter-js-sdk/v2.3.1/charts.mdx create mode 100644 docs/sdk-reference/code-interpreter-js-sdk/v2.3.1/consts.mdx create mode 100644 docs/sdk-reference/code-interpreter-js-sdk/v2.3.1/messaging.mdx create mode 100644 docs/sdk-reference/code-interpreter-js-sdk/v2.3.1/sandbox.mdx create mode 100644 docs/sdk-reference/code-interpreter-js-sdk/v2.3.2/charts.mdx create mode 100644 docs/sdk-reference/code-interpreter-js-sdk/v2.3.2/consts.mdx create mode 100644 docs/sdk-reference/code-interpreter-js-sdk/v2.3.2/messaging.mdx create mode 100644 docs/sdk-reference/code-interpreter-js-sdk/v2.3.2/sandbox.mdx create mode 100644 docs/sdk-reference/code-interpreter-js-sdk/v2.3.3/charts.mdx create mode 100644 docs/sdk-reference/code-interpreter-js-sdk/v2.3.3/consts.mdx create mode 100644 docs/sdk-reference/code-interpreter-js-sdk/v2.3.3/messaging.mdx create mode 100644 docs/sdk-reference/code-interpreter-js-sdk/v2.3.3/sandbox.mdx create mode 100644 docs/sdk-reference/code-interpreter-python-sdk/1.0.1/code_interpreter.mdx create mode 100644 docs/sdk-reference/code-interpreter-python-sdk/1.0.4/code_interpreter.mdx create mode 100644 docs/sdk-reference/code-interpreter-python-sdk/v2.2.1/code_interpreter.mdx create mode 100644 docs/sdk-reference/code-interpreter-python-sdk/v2.3.0/code_interpreter.mdx create mode 100644 docs/sdk-reference/code-interpreter-python-sdk/v2.4.0/code_interpreter.mdx create mode 100644 docs/sdk-reference/code-interpreter-python-sdk/v2.4.1/code_interpreter.mdx create mode 100644 docs/sdk-reference/desktop-js-sdk/v2.1.0/sandbox.mdx create mode 100644 docs/sdk-reference/desktop-js-sdk/v2.2.0/sandbox.mdx create mode 100644 docs/sdk-reference/desktop-js-sdk/v2.2.1/sandbox.mdx create mode 100644 docs/sdk-reference/desktop-js-sdk/v2.2.2/sandbox.mdx create mode 100644 docs/sdk-reference/desktop-python-sdk/v2.0.0/desktop.mdx create mode 100644 docs/sdk-reference/desktop-python-sdk/v2.0.1/desktop.mdx create mode 100644 docs/sdk-reference/desktop-python-sdk/v2.1.0/desktop.mdx create mode 100644 docs/sdk-reference/desktop-python-sdk/v2.2.0/desktop.mdx create mode 100644 docs/sdk-reference/js-sdk/1.0.0/errors.mdx create mode 100644 docs/sdk-reference/js-sdk/1.0.0/sandbox-filesystem.mdx create mode 100644 docs/sdk-reference/js-sdk/1.0.0/sandbox.mdx create mode 100644 docs/sdk-reference/js-sdk/v2.8.2/errors.mdx create mode 100644 docs/sdk-reference/js-sdk/v2.8.2/sandbox-commands.mdx create mode 100644 docs/sdk-reference/js-sdk/v2.8.2/sandbox-filesystem.mdx create mode 100644 docs/sdk-reference/js-sdk/v2.8.2/sandbox.mdx create mode 100644 docs/sdk-reference/js-sdk/v2.8.2/template-logger.mdx create mode 100644 docs/sdk-reference/js-sdk/v2.8.2/template-readycmd.mdx create mode 100644 docs/sdk-reference/js-sdk/v2.8.2/template.mdx create mode 100644 docs/sdk-reference/js-sdk/v2.8.3/errors.mdx create mode 100644 docs/sdk-reference/js-sdk/v2.8.3/sandbox-commands.mdx create mode 100644 docs/sdk-reference/js-sdk/v2.8.3/sandbox-filesystem.mdx create mode 100644 docs/sdk-reference/js-sdk/v2.8.3/sandbox.mdx create mode 100644 docs/sdk-reference/js-sdk/v2.8.3/template-logger.mdx create mode 100644 docs/sdk-reference/js-sdk/v2.8.3/template-readycmd.mdx create mode 100644 docs/sdk-reference/js-sdk/v2.8.3/template.mdx create mode 100644 docs/sdk-reference/js-sdk/v2.8.4/errors.mdx create mode 100644 docs/sdk-reference/js-sdk/v2.8.4/sandbox-commands.mdx create mode 100644 docs/sdk-reference/js-sdk/v2.8.4/sandbox-filesystem.mdx create mode 100644 docs/sdk-reference/js-sdk/v2.8.4/sandbox.mdx create mode 100644 docs/sdk-reference/js-sdk/v2.8.4/template-logger.mdx create mode 100644 docs/sdk-reference/js-sdk/v2.8.4/template-readycmd.mdx create mode 100644 docs/sdk-reference/js-sdk/v2.8.4/template.mdx create mode 100644 docs/sdk-reference/js-sdk/v2.9.0/errors.mdx create mode 100644 docs/sdk-reference/js-sdk/v2.9.0/sandbox-commands.mdx create mode 100644 docs/sdk-reference/js-sdk/v2.9.0/sandbox-filesystem.mdx create mode 100644 docs/sdk-reference/js-sdk/v2.9.0/sandbox.mdx create mode 100644 docs/sdk-reference/js-sdk/v2.9.0/template-logger.mdx create mode 100644 docs/sdk-reference/js-sdk/v2.9.0/template-readycmd.mdx create mode 100644 docs/sdk-reference/js-sdk/v2.9.0/template.mdx create mode 100644 docs/sdk-reference/python-sdk/1.0.0/exceptions.mdx create mode 100644 docs/sdk-reference/python-sdk/1.0.0/sandbox_async.mdx create mode 100644 docs/sdk-reference/python-sdk/1.0.0/sandbox_sync.mdx create mode 100644 docs/sdk-reference/python-sdk/v2.7.0/exceptions.mdx create mode 100644 docs/sdk-reference/python-sdk/v2.7.0/logger.mdx create mode 100644 docs/sdk-reference/python-sdk/v2.7.0/readycmd.mdx create mode 100644 docs/sdk-reference/python-sdk/v2.7.0/sandbox_async.mdx create mode 100644 docs/sdk-reference/python-sdk/v2.7.0/sandbox_sync.mdx create mode 100644 docs/sdk-reference/python-sdk/v2.7.0/template.mdx create mode 100644 docs/sdk-reference/python-sdk/v2.7.0/template_async.mdx create mode 100644 docs/sdk-reference/python-sdk/v2.7.0/template_sync.mdx create mode 100644 docs/sdk-reference/python-sdk/v2.8.0/exceptions.mdx create mode 100644 docs/sdk-reference/python-sdk/v2.8.0/logger.mdx create mode 100644 docs/sdk-reference/python-sdk/v2.8.0/readycmd.mdx create mode 100644 docs/sdk-reference/python-sdk/v2.8.0/sandbox_async.mdx create mode 100644 docs/sdk-reference/python-sdk/v2.8.0/sandbox_sync.mdx create mode 100644 docs/sdk-reference/python-sdk/v2.8.0/template.mdx create mode 100644 docs/sdk-reference/python-sdk/v2.8.0/template_async.mdx create mode 100644 docs/sdk-reference/python-sdk/v2.8.0/template_sync.mdx create mode 100644 docs/sdk-reference/python-sdk/v2.8.1/exceptions.mdx create mode 100644 docs/sdk-reference/python-sdk/v2.8.1/logger.mdx create mode 100644 docs/sdk-reference/python-sdk/v2.8.1/readycmd.mdx create mode 100644 docs/sdk-reference/python-sdk/v2.8.1/sandbox_async.mdx create mode 100644 docs/sdk-reference/python-sdk/v2.8.1/sandbox_sync.mdx create mode 100644 docs/sdk-reference/python-sdk/v2.8.1/template.mdx create mode 100644 docs/sdk-reference/python-sdk/v2.8.1/template_async.mdx create mode 100644 docs/sdk-reference/python-sdk/v2.8.1/template_sync.mdx create mode 100644 docs/sdk-reference/python-sdk/v2.9.0/exceptions.mdx create mode 100644 docs/sdk-reference/python-sdk/v2.9.0/logger.mdx create mode 100644 docs/sdk-reference/python-sdk/v2.9.0/readycmd.mdx create mode 100644 docs/sdk-reference/python-sdk/v2.9.0/sandbox_async.mdx create mode 100644 docs/sdk-reference/python-sdk/v2.9.0/sandbox_sync.mdx create mode 100644 docs/sdk-reference/python-sdk/v2.9.0/template.mdx create mode 100644 docs/sdk-reference/python-sdk/v2.9.0/template_async.mdx create mode 100644 docs/sdk-reference/python-sdk/v2.9.0/template_sync.mdx diff --git a/docs.json b/docs.json index dc9df28..04a7a24 100644 --- a/docs.json +++ b/docs.json @@ -197,6 +197,363 @@ ] } ] + }, + { + "anchor": "SDK Reference", + "icon": "brackets-curly", + "dropdowns": [ + { + "dropdown": "SDK (JavaScript)", + "icon": "square-js", + "versions": [ + { + "version": "v2.9.0", + "default": true, + "pages": [ + "docs/sdk-reference/js-sdk/v2.9.0/errors", + "docs/sdk-reference/js-sdk/v2.9.0/sandbox", + "docs/sdk-reference/js-sdk/v2.9.0/sandbox-commands", + "docs/sdk-reference/js-sdk/v2.9.0/sandbox-filesystem", + "docs/sdk-reference/js-sdk/v2.9.0/template", + "docs/sdk-reference/js-sdk/v2.9.0/template-logger", + "docs/sdk-reference/js-sdk/v2.9.0/template-readycmd" + ] + }, + { + "version": "v2.8.4", + "default": false, + "pages": [ + "docs/sdk-reference/js-sdk/v2.8.4/errors", + "docs/sdk-reference/js-sdk/v2.8.4/sandbox", + "docs/sdk-reference/js-sdk/v2.8.4/sandbox-commands", + "docs/sdk-reference/js-sdk/v2.8.4/sandbox-filesystem", + "docs/sdk-reference/js-sdk/v2.8.4/template", + "docs/sdk-reference/js-sdk/v2.8.4/template-logger", + "docs/sdk-reference/js-sdk/v2.8.4/template-readycmd" + ] + }, + { + "version": "v2.8.3", + "default": false, + "pages": [ + "docs/sdk-reference/js-sdk/v2.8.3/errors", + "docs/sdk-reference/js-sdk/v2.8.3/sandbox", + "docs/sdk-reference/js-sdk/v2.8.3/sandbox-commands", + "docs/sdk-reference/js-sdk/v2.8.3/sandbox-filesystem", + "docs/sdk-reference/js-sdk/v2.8.3/template", + "docs/sdk-reference/js-sdk/v2.8.3/template-logger", + "docs/sdk-reference/js-sdk/v2.8.3/template-readycmd" + ] + }, + { + "version": "v2.8.2", + "default": false, + "pages": [ + "docs/sdk-reference/js-sdk/v2.8.2/errors", + "docs/sdk-reference/js-sdk/v2.8.2/sandbox", + "docs/sdk-reference/js-sdk/v2.8.2/sandbox-commands", + "docs/sdk-reference/js-sdk/v2.8.2/sandbox-filesystem", + "docs/sdk-reference/js-sdk/v2.8.2/template", + "docs/sdk-reference/js-sdk/v2.8.2/template-logger", + "docs/sdk-reference/js-sdk/v2.8.2/template-readycmd" + ] + }, + { + "version": "v1.0.0", + "default": false, + "pages": [ + "docs/sdk-reference/js-sdk/1.0.0/errors", + "docs/sdk-reference/js-sdk/1.0.0/sandbox", + "docs/sdk-reference/js-sdk/1.0.0/sandbox-filesystem" + ] + } + ] + }, + { + "dropdown": "SDK (Python)", + "icon": "python", + "versions": [ + { + "version": "v2.9.0", + "default": true, + "pages": [ + "docs/sdk-reference/python-sdk/v2.9.0/exceptions", + "docs/sdk-reference/python-sdk/v2.9.0/logger", + "docs/sdk-reference/python-sdk/v2.9.0/readycmd", + "docs/sdk-reference/python-sdk/v2.9.0/sandbox_async", + "docs/sdk-reference/python-sdk/v2.9.0/sandbox_sync", + "docs/sdk-reference/python-sdk/v2.9.0/template", + "docs/sdk-reference/python-sdk/v2.9.0/template_async", + "docs/sdk-reference/python-sdk/v2.9.0/template_sync" + ] + }, + { + "version": "v2.8.1", + "default": false, + "pages": [ + "docs/sdk-reference/python-sdk/v2.8.1/exceptions", + "docs/sdk-reference/python-sdk/v2.8.1/logger", + "docs/sdk-reference/python-sdk/v2.8.1/readycmd", + "docs/sdk-reference/python-sdk/v2.8.1/sandbox_async", + "docs/sdk-reference/python-sdk/v2.8.1/sandbox_sync", + "docs/sdk-reference/python-sdk/v2.8.1/template", + "docs/sdk-reference/python-sdk/v2.8.1/template_async", + "docs/sdk-reference/python-sdk/v2.8.1/template_sync" + ] + }, + { + "version": "v2.8.0", + "default": false, + "pages": [ + "docs/sdk-reference/python-sdk/v2.8.0/exceptions", + "docs/sdk-reference/python-sdk/v2.8.0/logger", + "docs/sdk-reference/python-sdk/v2.8.0/readycmd", + "docs/sdk-reference/python-sdk/v2.8.0/sandbox_async", + "docs/sdk-reference/python-sdk/v2.8.0/sandbox_sync", + "docs/sdk-reference/python-sdk/v2.8.0/template", + "docs/sdk-reference/python-sdk/v2.8.0/template_async", + "docs/sdk-reference/python-sdk/v2.8.0/template_sync" + ] + }, + { + "version": "v2.7.0", + "default": false, + "pages": [ + "docs/sdk-reference/python-sdk/v2.7.0/exceptions", + "docs/sdk-reference/python-sdk/v2.7.0/logger", + "docs/sdk-reference/python-sdk/v2.7.0/readycmd", + "docs/sdk-reference/python-sdk/v2.7.0/sandbox_async", + "docs/sdk-reference/python-sdk/v2.7.0/sandbox_sync", + "docs/sdk-reference/python-sdk/v2.7.0/template", + "docs/sdk-reference/python-sdk/v2.7.0/template_async", + "docs/sdk-reference/python-sdk/v2.7.0/template_sync" + ] + }, + { + "version": "v1.0.0", + "default": false, + "pages": [ + "docs/sdk-reference/python-sdk/1.0.0/exceptions", + "docs/sdk-reference/python-sdk/1.0.0/sandbox_async", + "docs/sdk-reference/python-sdk/1.0.0/sandbox_sync" + ] + } + ] + }, + { + "dropdown": "Code Interpreter SDK (JavaScript)", + "icon": "square-js", + "versions": [ + { + "version": "v2.3.3", + "default": true, + "pages": [ + "docs/sdk-reference/code-interpreter-js-sdk/v2.3.3/charts", + "docs/sdk-reference/code-interpreter-js-sdk/v2.3.3/consts", + "docs/sdk-reference/code-interpreter-js-sdk/v2.3.3/messaging", + "docs/sdk-reference/code-interpreter-js-sdk/v2.3.3/sandbox" + ] + }, + { + "version": "v2.3.2", + "default": false, + "pages": [ + "docs/sdk-reference/code-interpreter-js-sdk/v2.3.2/charts", + "docs/sdk-reference/code-interpreter-js-sdk/v2.3.2/consts", + "docs/sdk-reference/code-interpreter-js-sdk/v2.3.2/messaging", + "docs/sdk-reference/code-interpreter-js-sdk/v2.3.2/sandbox" + ] + }, + { + "version": "v2.3.1", + "default": false, + "pages": [ + "docs/sdk-reference/code-interpreter-js-sdk/v2.3.1/charts", + "docs/sdk-reference/code-interpreter-js-sdk/v2.3.1/consts", + "docs/sdk-reference/code-interpreter-js-sdk/v2.3.1/messaging", + "docs/sdk-reference/code-interpreter-js-sdk/v2.3.1/sandbox" + ] + }, + { + "version": "v2.3.0", + "default": false, + "pages": [ + "docs/sdk-reference/code-interpreter-js-sdk/v2.3.0/charts", + "docs/sdk-reference/code-interpreter-js-sdk/v2.3.0/consts", + "docs/sdk-reference/code-interpreter-js-sdk/v2.3.0/messaging", + "docs/sdk-reference/code-interpreter-js-sdk/v2.3.0/sandbox" + ] + } + ] + }, + { + "dropdown": "Code Interpreter SDK (Python)", + "icon": "python", + "versions": [ + { + "version": "v2.4.1", + "default": true, + "pages": [ + "docs/sdk-reference/code-interpreter-python-sdk/v2.4.1/code_interpreter" + ] + }, + { + "version": "v2.4.0", + "default": false, + "pages": [ + "docs/sdk-reference/code-interpreter-python-sdk/v2.4.0/code_interpreter" + ] + }, + { + "version": "v2.3.0", + "default": false, + "pages": [ + "docs/sdk-reference/code-interpreter-python-sdk/v2.3.0/code_interpreter" + ] + }, + { + "version": "v2.2.1", + "default": false, + "pages": [ + "docs/sdk-reference/code-interpreter-python-sdk/v2.2.1/code_interpreter" + ] + }, + { + "version": "v1.0.4", + "default": false, + "pages": [ + "docs/sdk-reference/code-interpreter-python-sdk/1.0.4/code_interpreter" + ] + }, + { + "version": "v1.0.1", + "default": false, + "pages": [ + "docs/sdk-reference/code-interpreter-python-sdk/1.0.1/code_interpreter" + ] + } + ] + }, + { + "dropdown": "Desktop SDK (JavaScript)", + "icon": "square-js", + "versions": [ + { + "version": "v2.2.2", + "default": true, + "pages": [ + "docs/sdk-reference/desktop-js-sdk/v2.2.2/sandbox" + ] + }, + { + "version": "v2.2.1", + "default": false, + "pages": [ + "docs/sdk-reference/desktop-js-sdk/v2.2.1/sandbox" + ] + }, + { + "version": "v2.2.0", + "default": false, + "pages": [ + "docs/sdk-reference/desktop-js-sdk/v2.2.0/sandbox" + ] + }, + { + "version": "v2.1.0", + "default": false, + "pages": [ + "docs/sdk-reference/desktop-js-sdk/v2.1.0/sandbox" + ] + } + ] + }, + { + "dropdown": "Desktop SDK (Python)", + "icon": "python", + "versions": [ + { + "version": "v2.2.0", + "default": true, + "pages": [ + "docs/sdk-reference/desktop-python-sdk/v2.2.0/desktop" + ] + }, + { + "version": "v2.1.0", + "default": false, + "pages": [ + "docs/sdk-reference/desktop-python-sdk/v2.1.0/desktop" + ] + }, + { + "version": "v2.0.1", + "default": false, + "pages": [ + "docs/sdk-reference/desktop-python-sdk/v2.0.1/desktop" + ] + }, + { + "version": "v2.0.0", + "default": false, + "pages": [ + "docs/sdk-reference/desktop-python-sdk/v2.0.0/desktop" + ] + } + ] + }, + { + "dropdown": "CLI", + "icon": "terminal", + "versions": [ + { + "version": "v2.4.2", + "default": true, + "pages": [ + "docs/sdk-reference/cli/v2.4.2/auth", + "docs/sdk-reference/cli/v2.4.2/sandbox", + "docs/sdk-reference/cli/v2.4.2/template" + ] + }, + { + "version": "v2.4.1", + "default": false, + "pages": [ + "docs/sdk-reference/cli/v2.4.1/auth", + "docs/sdk-reference/cli/v2.4.1/sandbox", + "docs/sdk-reference/cli/v2.4.1/template" + ] + }, + { + "version": "v2.4.0", + "default": false, + "pages": [ + "docs/sdk-reference/cli/v2.4.0/auth", + "docs/sdk-reference/cli/v2.4.0/sandbox", + "docs/sdk-reference/cli/v2.4.0/template" + ] + }, + { + "version": "v2.3.3", + "default": false, + "pages": [ + "docs/sdk-reference/cli/v2.3.3/auth", + "docs/sdk-reference/cli/v2.3.3/sandbox", + "docs/sdk-reference/cli/v2.3.3/template" + ] + }, + { + "version": "v1.0.0", + "default": false, + "pages": [ + "docs/sdk-reference/cli/1.0.0/auth", + "docs/sdk-reference/cli/1.0.0/sandbox", + "docs/sdk-reference/cli/1.0.0/template" + ] + } + ] + } + ] } ], "global": {} diff --git a/docs/sdk-reference/cli/1.0.0/auth.mdx b/docs/sdk-reference/cli/1.0.0/auth.mdx new file mode 100644 index 0000000..d64eb00 --- /dev/null +++ b/docs/sdk-reference/cli/1.0.0/auth.mdx @@ -0,0 +1,63 @@ +--- +sidebarTitle: "Auth" +mode: "center" +--- + +# e2b auth + + +authentication commands + +## Usage + +```bash +e2b auth [options] [command] +``` +# e2b auth login + + +log in to CLI + +## Usage + +```bash +e2b auth login [options] +``` + + +# e2b auth logout + + +log out of CLI + +## Usage + +```bash +e2b auth logout [options] +``` + + +# e2b auth info + + +get information about the current user + +## Usage + +```bash +e2b auth info [options] +``` + + +# e2b auth configure + + +configure user + +## Usage + +```bash +e2b auth configure [options] +``` + + diff --git a/docs/sdk-reference/cli/1.0.0/sandbox.mdx b/docs/sdk-reference/cli/1.0.0/sandbox.mdx new file mode 100644 index 0000000..ae14239 --- /dev/null +++ b/docs/sdk-reference/cli/1.0.0/sandbox.mdx @@ -0,0 +1,94 @@ +--- +sidebarTitle: "Sandbox" +mode: "center" +--- + +# e2b sandbox + + +work with sandboxes + +## Usage + +```bash +e2b sandbox [options] [command] +``` +# e2b sandbox connect + + +connect terminal to already running sandbox + +## Usage + +```bash +e2b sandbox connect [options] +``` + + +# e2b sandbox list + + +list all running sandboxes + +## Usage + +```bash +e2b sandbox list [options] +``` + + +# e2b sandbox kill + + +kill sandbox + +## Usage + +```bash +e2b sandbox kill [options] [sandboxID] +``` + +## Options + + + - `-a, --all: kill all running sandboxes ` + + +# e2b sandbox spawn + + +spawn sandbox and connect terminal to it + +## Usage + +```bash +e2b sandbox spawn [options] [template] +``` + +## Options + + + - `-p, --path : change root directory where command is executed to  directory ` + - `--config : specify path to the E2B config toml. By default E2B tries to find ./e2b.toml in root directory. ` + + +# e2b sandbox logs + + +show logs for sandbox + +## Usage + +```bash +e2b sandbox logs [options] +``` + +## Options + + + - `--level : filter logs by level (DEBUG, INFO, WARN, ERROR). The logs with the higher levels will be also shown. [default: INFO]` + - `-f, --follow: keep streaming logs until the sandbox is closed ` + - `--format : specify format for printing logs (json, pretty) [default: pretty]` + - `--loggers [loggers]: filter logs by loggers. Specify multiple loggers by separating them with a comma. ` + + diff --git a/docs/sdk-reference/cli/1.0.0/template.mdx b/docs/sdk-reference/cli/1.0.0/template.mdx new file mode 100644 index 0000000..9ebf6cf --- /dev/null +++ b/docs/sdk-reference/cli/1.0.0/template.mdx @@ -0,0 +1,95 @@ +--- +sidebarTitle: "Template" +mode: "center" +--- + +# e2b template + + +manage sandbox templates + +## Usage + +```bash +e2b template [options] [command] +``` +# e2b template build + + +build sandbox template defined by ./e2b.Dockerfile or ./Dockerfile in root directory. By default the root directory is the current working directory. This command also creates e2b.toml config. + +## Usage + +```bash +e2b template build [options] [template] +``` + +## Options + + + - `-p, --path : change root directory where command is executed to  directory ` + - `-d, --dockerfile : specify path to Dockerfile. By default E2B tries to find e2b.Dockerfile or Dockerfile in root directory. ` + - `-n, --name : specify sandbox template name. You can use the template name to start the sandbox with SDK. The template name must be lowercase and contain only letters, numbers, dashes and underscores. ` + - `-c, --cmd : specify command that will be executed when the sandbox is started. ` + - `-t, --team : specify the team ID that the operation will be associated with. You can find team ID in the team settings in the E2B dashboard (https://e2b.dev/dashboard?tab=team). ` + - `--config : specify path to the E2B config toml. By default E2B tries to find ./e2b.toml in root directory. ` + - `--cpu-count : specify the number of CPUs that will be used to run the sandbox. The default value is 2. ` + - `--memory-mb : specify the amount of memory in megabytes that will be used to run the sandbox. Must be an even number. The default value is 512. ` + - `--build-arg : specify additional build arguments for the build command. The format should be =. ` + + +# e2b template list + + +list sandbox templates + +## Usage + +```bash +e2b template list [options] +``` + +## Options + + + - `-t, --team : specify the team ID that the operation will be associated with. You can find team ID in the team settings in the E2B dashboard (https://e2b.dev/dashboard?tab=team). ` + + +# e2b template init + + +create basic E2B Dockerfile (./e2b.Dockerfile) in root directory. You can then run e2b template build to build sandbox template from this Dockerfile + +## Usage + +```bash +e2b template init [options] +``` + +## Options + + + - `-p, --path : change root directory where command is executed to  directory ` + + +# e2b template delete + + +delete sandbox template and e2b.toml config + +## Usage + +```bash +e2b template delete [options] [template] +``` + +## Options + + + - `-p, --path : change root directory where command is executed to  directory ` + - `--config : specify path to the E2B config toml. By default E2B tries to find ./e2b.toml in root directory. ` + - `-s, --select: select sandbox template from interactive list ` + - `-t, --team : specify the team ID that the operation will be associated with. You can find team ID in the team settings in the E2B dashboard (https://e2b.dev/dashboard?tab=team). ` + - `-y, --yes: skip manual delete confirmation ` + + diff --git a/docs/sdk-reference/cli/v2.3.3/auth.mdx b/docs/sdk-reference/cli/v2.3.3/auth.mdx new file mode 100644 index 0000000..c223c57 --- /dev/null +++ b/docs/sdk-reference/cli/v2.3.3/auth.mdx @@ -0,0 +1,63 @@ +--- +sidebarTitle: "Auth" +mode: "center" +--- + +## e2b auth + + +authentication commands + +### Usage + +```bash +e2b auth [options] [command] +``` +## e2b auth login + + +log in to CLI + +### Usage + +```bash +e2b auth login [options] +``` + + +## e2b auth logout + + +log out of CLI + +### Usage + +```bash +e2b auth logout [options] +``` + + +## e2b auth info + + +get information about the current user + +### Usage + +```bash +e2b auth info [options] +``` + + +## e2b auth configure + + +configure user + +### Usage + +```bash +e2b auth configure [options] +``` + + diff --git a/docs/sdk-reference/cli/v2.3.3/sandbox.mdx b/docs/sdk-reference/cli/v2.3.3/sandbox.mdx new file mode 100644 index 0000000..cc9ed31 --- /dev/null +++ b/docs/sdk-reference/cli/v2.3.3/sandbox.mdx @@ -0,0 +1,140 @@ +--- +sidebarTitle: "Sandbox" +mode: "center" +--- + +## e2b sandbox + + +work with sandboxes + +### Usage + +```bash +e2b sandbox [options] [command] +``` +## e2b sandbox connect + + +connect terminal to already running sandbox + +### Usage + +```bash +e2b sandbox connect [options] +``` + + +## e2b sandbox list + + +list all sandboxes, by default it list only running ones + +### Usage + +```bash +e2b sandbox list [options] +``` + +### Options + + + - `-s, --state : filter by state, eg. running, paused. Defaults to running ` + - `-m, --metadata : filter by metadata, eg. key1=value1 ` + - `-l, --limit : limit the number of sandboxes returned ` + - `-f, --format : output format, eg. json, pretty ` + + +## e2b sandbox kill + + +kill sandbox + +### Usage + +```bash +e2b sandbox kill [options] [sandboxIDs...] +``` + +### Options + + + - `-a, --all: kill all sandboxes ` + - `-s, --state : when used with -a/--all flag, filter by state, eg. running, paused. Defaults to running ` + - `-m, --metadata : when used with -a/--all flag, filter by metadata, eg. key1=value1 ` + + +## e2b sandbox create + + +create sandbox and connect terminal to it + +### Usage + +```bash +e2b sandbox create [options] [template] +``` + +### Options + + + - `-p, --path : change root directory where command is executed to  directory ` + - `--config : specify path to the E2B config toml. By default E2B tries to find ./e2b.toml in root directory. ` + + +## e2b sandbox spawn + + +create sandbox and connect terminal to it + +### Usage + +```bash +e2b sandbox spawn [options] [template] +``` + +### Options + + + - `-p, --path : change root directory where command is executed to  directory ` + - `--config : specify path to the E2B config toml. By default E2B tries to find ./e2b.toml in root directory. ` + + +## e2b sandbox logs + + +show logs for sandbox + +### Usage + +```bash +e2b sandbox logs [options] +``` + +### Options + + + - `--level : filter logs by level (DEBUG, INFO, WARN, ERROR). The logs with the higher levels will be also shown. [default: INFO]` + - `-f, --follow: keep streaming logs until the sandbox is closed ` + - `--format : specify format for printing logs (json, pretty) [default: pretty]` + - `--loggers [loggers]: filter logs by loggers. Specify multiple loggers by separating them with a comma. ` + + +## e2b sandbox metrics + + +show metrics for sandbox + +### Usage + +```bash +e2b sandbox metrics [options] +``` + +### Options + + + - `-f, --follow: keep streaming metrics until the sandbox is closed ` + - `--format : specify format for printing metrics (json, pretty) [default: pretty]` + + diff --git a/docs/sdk-reference/cli/v2.3.3/template.mdx b/docs/sdk-reference/cli/v2.3.3/template.mdx new file mode 100644 index 0000000..8e0b766 --- /dev/null +++ b/docs/sdk-reference/cli/v2.3.3/template.mdx @@ -0,0 +1,185 @@ +--- +sidebarTitle: "Template" +mode: "center" +--- + +## e2b template + + +manage sandbox templates + +### Usage + +```bash +e2b template [options] [command] +``` +## e2b template create + + +build Dockerfile as a Sandbox template. This command reads a Dockerfile and builds it directly. + +### Usage + +```bash +e2b template create [options] +``` + +### Options + + + - `-p, --path : change root directory where command is executed to  directory ` + - `-d, --dockerfile : specify path to Dockerfile. By default E2B tries to find e2b.Dockerfile or Dockerfile in root directory. ` + - `-c, --cmd : specify command that will be executed when the sandbox is started. ` + - `--ready-cmd : specify command that will need to exit 0 for the template to be ready. ` + - `--cpu-count : specify the number of CPUs that will be used to run the sandbox. The default value is 2. ` + - `--memory-mb : specify the amount of memory in megabytes that will be used to run the sandbox. Must be an even number. The default value is 512. ` + - `--no-cache: skip cache when building the template. ` + + +## e2b template build + + +build sandbox template defined by ./e2b.Dockerfile or ./Dockerfile in root directory. By default the root directory is the current working directory. This command also creates e2b.toml config. + +### Usage + +```bash +e2b template build [options] [template] +``` + +### Options + + + - `-p, --path : change root directory where command is executed to  directory ` + - `-d, --dockerfile : specify path to Dockerfile. By default E2B tries to find e2b.Dockerfile or Dockerfile in root directory. ` + - `-n, --name : specify sandbox template name. You can use the template name to start the sandbox with SDK. The template name must be lowercase and contain only letters, numbers, dashes and underscores. ` + - `-c, --cmd : specify command that will be executed when the sandbox is started. ` + - `--ready-cmd : specify command that will need to exit 0 for the template to be ready. ` + - `-t, --team : specify the team ID that the operation will be associated with. You can find team ID in the team settings in the E2B dashboard (https://e2b.dev/dashboard?tab=team). ` + - `--config : specify path to the E2B config toml. By default E2B tries to find ./e2b.toml in root directory. ` + - `--cpu-count : specify the number of CPUs that will be used to run the sandbox. The default value is 2. ` + - `--memory-mb : specify the amount of memory in megabytes that will be used to run the sandbox. Must be an even number. The default value is 512. ` + - `--build-arg : specify additional build arguments for the build command. The format should be =. ` + - `--no-cache: skip cache when building the template. ` + + +## e2b template list + + +list sandbox templates + +### Usage + +```bash +e2b template list [options] +``` + +### Options + + + - `-t, --team : specify the team ID that the operation will be associated with. You can find team ID in the team settings in the E2B dashboard (https://e2b.dev/dashboard?tab=team). ` + - `-f, --format : output format, eg. json, pretty ` + + +## e2b template init + + +initialize a new sandbox template using the SDK + +### Usage + +```bash +e2b template init [options] +``` + +### Options + + + - `-p, --path : change root directory where command is executed to  directory ` + - `-n, --name : template name (alias) ` + - `-l, --language : target language: typescript, python-sync, python-async ` + + +## e2b template delete + + +delete sandbox template and e2b.toml config + +### Usage + +```bash +e2b template delete [options] [template] +``` + +### Options + + + - `-p, --path : change root directory where command is executed to  directory ` + - `--config : specify path to the E2B config toml. By default E2B tries to find ./e2b.toml in root directory. ` + - `-s, --select: select sandbox template from interactive list ` + - `-t, --team : specify the team ID that the operation will be associated with. You can find team ID in the team settings in the E2B dashboard (https://e2b.dev/dashboard?tab=team). ` + - `-y, --yes: skip manual delete confirmation ` + + +## e2b template publish + + +publish sandbox template + +### Usage + +```bash +e2b template publish [options] [template] +``` + +### Options + + + - `-p, --path : change root directory where command is executed to  directory ` + - `--config : specify path to the E2B config toml. By default E2B tries to find ./e2b.toml in root directory. ` + - `-s, --select: select sandbox template from interactive list ` + - `-t, --team : specify the team ID that the operation will be associated with. You can find team ID in the team settings in the E2B dashboard (https://e2b.dev/dashboard?tab=team). ` + - `-y, --yes: skip manual publish confirmation ` + + +## e2b template unpublish + + +unpublish sandbox template + +### Usage + +```bash +e2b template unpublish [options] [template] +``` + +### Options + + + - `-p, --path : change root directory where command is executed to  directory ` + - `--config : specify path to the E2B config toml. By default E2B tries to find ./e2b.toml in root directory. ` + - `-s, --select: select sandbox template from interactive list ` + - `-t, --team : specify the team ID that the operation will be associated with. You can find team ID in the team settings in the E2B dashboard (https://e2b.dev/dashboard?tab=team). ` + - `-y, --yes: skip manual unpublish confirmation ` + + +## e2b template migrate + + +migrate e2b.Dockerfile and e2b.toml to new Template SDK format + +### Usage + +```bash +e2b template migrate [options] +``` + +### Options + + + - `-d, --dockerfile : specify path to Dockerfile. Defaults to e2b.Dockerfile ` + - `--config : specify path to the E2B config toml. By default E2B tries to find ./e2b.toml in root directory. ` + - `-l, --language : specify target language: typescript, python-sync, python-async ` + - `-p, --path : change root directory where command is executed to  directory ` + + diff --git a/docs/sdk-reference/cli/v2.4.0/auth.mdx b/docs/sdk-reference/cli/v2.4.0/auth.mdx new file mode 100644 index 0000000..c223c57 --- /dev/null +++ b/docs/sdk-reference/cli/v2.4.0/auth.mdx @@ -0,0 +1,63 @@ +--- +sidebarTitle: "Auth" +mode: "center" +--- + +## e2b auth + + +authentication commands + +### Usage + +```bash +e2b auth [options] [command] +``` +## e2b auth login + + +log in to CLI + +### Usage + +```bash +e2b auth login [options] +``` + + +## e2b auth logout + + +log out of CLI + +### Usage + +```bash +e2b auth logout [options] +``` + + +## e2b auth info + + +get information about the current user + +### Usage + +```bash +e2b auth info [options] +``` + + +## e2b auth configure + + +configure user + +### Usage + +```bash +e2b auth configure [options] +``` + + diff --git a/docs/sdk-reference/cli/v2.4.0/sandbox.mdx b/docs/sdk-reference/cli/v2.4.0/sandbox.mdx new file mode 100644 index 0000000..cc9ed31 --- /dev/null +++ b/docs/sdk-reference/cli/v2.4.0/sandbox.mdx @@ -0,0 +1,140 @@ +--- +sidebarTitle: "Sandbox" +mode: "center" +--- + +## e2b sandbox + + +work with sandboxes + +### Usage + +```bash +e2b sandbox [options] [command] +``` +## e2b sandbox connect + + +connect terminal to already running sandbox + +### Usage + +```bash +e2b sandbox connect [options] +``` + + +## e2b sandbox list + + +list all sandboxes, by default it list only running ones + +### Usage + +```bash +e2b sandbox list [options] +``` + +### Options + + + - `-s, --state : filter by state, eg. running, paused. Defaults to running ` + - `-m, --metadata : filter by metadata, eg. key1=value1 ` + - `-l, --limit : limit the number of sandboxes returned ` + - `-f, --format : output format, eg. json, pretty ` + + +## e2b sandbox kill + + +kill sandbox + +### Usage + +```bash +e2b sandbox kill [options] [sandboxIDs...] +``` + +### Options + + + - `-a, --all: kill all sandboxes ` + - `-s, --state : when used with -a/--all flag, filter by state, eg. running, paused. Defaults to running ` + - `-m, --metadata : when used with -a/--all flag, filter by metadata, eg. key1=value1 ` + + +## e2b sandbox create + + +create sandbox and connect terminal to it + +### Usage + +```bash +e2b sandbox create [options] [template] +``` + +### Options + + + - `-p, --path : change root directory where command is executed to  directory ` + - `--config : specify path to the E2B config toml. By default E2B tries to find ./e2b.toml in root directory. ` + + +## e2b sandbox spawn + + +create sandbox and connect terminal to it + +### Usage + +```bash +e2b sandbox spawn [options] [template] +``` + +### Options + + + - `-p, --path : change root directory where command is executed to  directory ` + - `--config : specify path to the E2B config toml. By default E2B tries to find ./e2b.toml in root directory. ` + + +## e2b sandbox logs + + +show logs for sandbox + +### Usage + +```bash +e2b sandbox logs [options] +``` + +### Options + + + - `--level : filter logs by level (DEBUG, INFO, WARN, ERROR). The logs with the higher levels will be also shown. [default: INFO]` + - `-f, --follow: keep streaming logs until the sandbox is closed ` + - `--format : specify format for printing logs (json, pretty) [default: pretty]` + - `--loggers [loggers]: filter logs by loggers. Specify multiple loggers by separating them with a comma. ` + + +## e2b sandbox metrics + + +show metrics for sandbox + +### Usage + +```bash +e2b sandbox metrics [options] +``` + +### Options + + + - `-f, --follow: keep streaming metrics until the sandbox is closed ` + - `--format : specify format for printing metrics (json, pretty) [default: pretty]` + + diff --git a/docs/sdk-reference/cli/v2.4.0/template.mdx b/docs/sdk-reference/cli/v2.4.0/template.mdx new file mode 100644 index 0000000..8e0b766 --- /dev/null +++ b/docs/sdk-reference/cli/v2.4.0/template.mdx @@ -0,0 +1,185 @@ +--- +sidebarTitle: "Template" +mode: "center" +--- + +## e2b template + + +manage sandbox templates + +### Usage + +```bash +e2b template [options] [command] +``` +## e2b template create + + +build Dockerfile as a Sandbox template. This command reads a Dockerfile and builds it directly. + +### Usage + +```bash +e2b template create [options] +``` + +### Options + + + - `-p, --path : change root directory where command is executed to  directory ` + - `-d, --dockerfile : specify path to Dockerfile. By default E2B tries to find e2b.Dockerfile or Dockerfile in root directory. ` + - `-c, --cmd : specify command that will be executed when the sandbox is started. ` + - `--ready-cmd : specify command that will need to exit 0 for the template to be ready. ` + - `--cpu-count : specify the number of CPUs that will be used to run the sandbox. The default value is 2. ` + - `--memory-mb : specify the amount of memory in megabytes that will be used to run the sandbox. Must be an even number. The default value is 512. ` + - `--no-cache: skip cache when building the template. ` + + +## e2b template build + + +build sandbox template defined by ./e2b.Dockerfile or ./Dockerfile in root directory. By default the root directory is the current working directory. This command also creates e2b.toml config. + +### Usage + +```bash +e2b template build [options] [template] +``` + +### Options + + + - `-p, --path : change root directory where command is executed to  directory ` + - `-d, --dockerfile : specify path to Dockerfile. By default E2B tries to find e2b.Dockerfile or Dockerfile in root directory. ` + - `-n, --name : specify sandbox template name. You can use the template name to start the sandbox with SDK. The template name must be lowercase and contain only letters, numbers, dashes and underscores. ` + - `-c, --cmd : specify command that will be executed when the sandbox is started. ` + - `--ready-cmd : specify command that will need to exit 0 for the template to be ready. ` + - `-t, --team : specify the team ID that the operation will be associated with. You can find team ID in the team settings in the E2B dashboard (https://e2b.dev/dashboard?tab=team). ` + - `--config : specify path to the E2B config toml. By default E2B tries to find ./e2b.toml in root directory. ` + - `--cpu-count : specify the number of CPUs that will be used to run the sandbox. The default value is 2. ` + - `--memory-mb : specify the amount of memory in megabytes that will be used to run the sandbox. Must be an even number. The default value is 512. ` + - `--build-arg : specify additional build arguments for the build command. The format should be =. ` + - `--no-cache: skip cache when building the template. ` + + +## e2b template list + + +list sandbox templates + +### Usage + +```bash +e2b template list [options] +``` + +### Options + + + - `-t, --team : specify the team ID that the operation will be associated with. You can find team ID in the team settings in the E2B dashboard (https://e2b.dev/dashboard?tab=team). ` + - `-f, --format : output format, eg. json, pretty ` + + +## e2b template init + + +initialize a new sandbox template using the SDK + +### Usage + +```bash +e2b template init [options] +``` + +### Options + + + - `-p, --path : change root directory where command is executed to  directory ` + - `-n, --name : template name (alias) ` + - `-l, --language : target language: typescript, python-sync, python-async ` + + +## e2b template delete + + +delete sandbox template and e2b.toml config + +### Usage + +```bash +e2b template delete [options] [template] +``` + +### Options + + + - `-p, --path : change root directory where command is executed to  directory ` + - `--config : specify path to the E2B config toml. By default E2B tries to find ./e2b.toml in root directory. ` + - `-s, --select: select sandbox template from interactive list ` + - `-t, --team : specify the team ID that the operation will be associated with. You can find team ID in the team settings in the E2B dashboard (https://e2b.dev/dashboard?tab=team). ` + - `-y, --yes: skip manual delete confirmation ` + + +## e2b template publish + + +publish sandbox template + +### Usage + +```bash +e2b template publish [options] [template] +``` + +### Options + + + - `-p, --path : change root directory where command is executed to  directory ` + - `--config : specify path to the E2B config toml. By default E2B tries to find ./e2b.toml in root directory. ` + - `-s, --select: select sandbox template from interactive list ` + - `-t, --team : specify the team ID that the operation will be associated with. You can find team ID in the team settings in the E2B dashboard (https://e2b.dev/dashboard?tab=team). ` + - `-y, --yes: skip manual publish confirmation ` + + +## e2b template unpublish + + +unpublish sandbox template + +### Usage + +```bash +e2b template unpublish [options] [template] +``` + +### Options + + + - `-p, --path : change root directory where command is executed to  directory ` + - `--config : specify path to the E2B config toml. By default E2B tries to find ./e2b.toml in root directory. ` + - `-s, --select: select sandbox template from interactive list ` + - `-t, --team : specify the team ID that the operation will be associated with. You can find team ID in the team settings in the E2B dashboard (https://e2b.dev/dashboard?tab=team). ` + - `-y, --yes: skip manual unpublish confirmation ` + + +## e2b template migrate + + +migrate e2b.Dockerfile and e2b.toml to new Template SDK format + +### Usage + +```bash +e2b template migrate [options] +``` + +### Options + + + - `-d, --dockerfile : specify path to Dockerfile. Defaults to e2b.Dockerfile ` + - `--config : specify path to the E2B config toml. By default E2B tries to find ./e2b.toml in root directory. ` + - `-l, --language : specify target language: typescript, python-sync, python-async ` + - `-p, --path : change root directory where command is executed to  directory ` + + diff --git a/docs/sdk-reference/cli/v2.4.1/auth.mdx b/docs/sdk-reference/cli/v2.4.1/auth.mdx new file mode 100644 index 0000000..c223c57 --- /dev/null +++ b/docs/sdk-reference/cli/v2.4.1/auth.mdx @@ -0,0 +1,63 @@ +--- +sidebarTitle: "Auth" +mode: "center" +--- + +## e2b auth + + +authentication commands + +### Usage + +```bash +e2b auth [options] [command] +``` +## e2b auth login + + +log in to CLI + +### Usage + +```bash +e2b auth login [options] +``` + + +## e2b auth logout + + +log out of CLI + +### Usage + +```bash +e2b auth logout [options] +``` + + +## e2b auth info + + +get information about the current user + +### Usage + +```bash +e2b auth info [options] +``` + + +## e2b auth configure + + +configure user + +### Usage + +```bash +e2b auth configure [options] +``` + + diff --git a/docs/sdk-reference/cli/v2.4.1/sandbox.mdx b/docs/sdk-reference/cli/v2.4.1/sandbox.mdx new file mode 100644 index 0000000..cc9ed31 --- /dev/null +++ b/docs/sdk-reference/cli/v2.4.1/sandbox.mdx @@ -0,0 +1,140 @@ +--- +sidebarTitle: "Sandbox" +mode: "center" +--- + +## e2b sandbox + + +work with sandboxes + +### Usage + +```bash +e2b sandbox [options] [command] +``` +## e2b sandbox connect + + +connect terminal to already running sandbox + +### Usage + +```bash +e2b sandbox connect [options] +``` + + +## e2b sandbox list + + +list all sandboxes, by default it list only running ones + +### Usage + +```bash +e2b sandbox list [options] +``` + +### Options + + + - `-s, --state : filter by state, eg. running, paused. Defaults to running ` + - `-m, --metadata : filter by metadata, eg. key1=value1 ` + - `-l, --limit : limit the number of sandboxes returned ` + - `-f, --format : output format, eg. json, pretty ` + + +## e2b sandbox kill + + +kill sandbox + +### Usage + +```bash +e2b sandbox kill [options] [sandboxIDs...] +``` + +### Options + + + - `-a, --all: kill all sandboxes ` + - `-s, --state : when used with -a/--all flag, filter by state, eg. running, paused. Defaults to running ` + - `-m, --metadata : when used with -a/--all flag, filter by metadata, eg. key1=value1 ` + + +## e2b sandbox create + + +create sandbox and connect terminal to it + +### Usage + +```bash +e2b sandbox create [options] [template] +``` + +### Options + + + - `-p, --path : change root directory where command is executed to  directory ` + - `--config : specify path to the E2B config toml. By default E2B tries to find ./e2b.toml in root directory. ` + + +## e2b sandbox spawn + + +create sandbox and connect terminal to it + +### Usage + +```bash +e2b sandbox spawn [options] [template] +``` + +### Options + + + - `-p, --path : change root directory where command is executed to  directory ` + - `--config : specify path to the E2B config toml. By default E2B tries to find ./e2b.toml in root directory. ` + + +## e2b sandbox logs + + +show logs for sandbox + +### Usage + +```bash +e2b sandbox logs [options] +``` + +### Options + + + - `--level : filter logs by level (DEBUG, INFO, WARN, ERROR). The logs with the higher levels will be also shown. [default: INFO]` + - `-f, --follow: keep streaming logs until the sandbox is closed ` + - `--format : specify format for printing logs (json, pretty) [default: pretty]` + - `--loggers [loggers]: filter logs by loggers. Specify multiple loggers by separating them with a comma. ` + + +## e2b sandbox metrics + + +show metrics for sandbox + +### Usage + +```bash +e2b sandbox metrics [options] +``` + +### Options + + + - `-f, --follow: keep streaming metrics until the sandbox is closed ` + - `--format : specify format for printing metrics (json, pretty) [default: pretty]` + + diff --git a/docs/sdk-reference/cli/v2.4.1/template.mdx b/docs/sdk-reference/cli/v2.4.1/template.mdx new file mode 100644 index 0000000..8e0b766 --- /dev/null +++ b/docs/sdk-reference/cli/v2.4.1/template.mdx @@ -0,0 +1,185 @@ +--- +sidebarTitle: "Template" +mode: "center" +--- + +## e2b template + + +manage sandbox templates + +### Usage + +```bash +e2b template [options] [command] +``` +## e2b template create + + +build Dockerfile as a Sandbox template. This command reads a Dockerfile and builds it directly. + +### Usage + +```bash +e2b template create [options] +``` + +### Options + + + - `-p, --path : change root directory where command is executed to  directory ` + - `-d, --dockerfile : specify path to Dockerfile. By default E2B tries to find e2b.Dockerfile or Dockerfile in root directory. ` + - `-c, --cmd : specify command that will be executed when the sandbox is started. ` + - `--ready-cmd : specify command that will need to exit 0 for the template to be ready. ` + - `--cpu-count : specify the number of CPUs that will be used to run the sandbox. The default value is 2. ` + - `--memory-mb : specify the amount of memory in megabytes that will be used to run the sandbox. Must be an even number. The default value is 512. ` + - `--no-cache: skip cache when building the template. ` + + +## e2b template build + + +build sandbox template defined by ./e2b.Dockerfile or ./Dockerfile in root directory. By default the root directory is the current working directory. This command also creates e2b.toml config. + +### Usage + +```bash +e2b template build [options] [template] +``` + +### Options + + + - `-p, --path : change root directory where command is executed to  directory ` + - `-d, --dockerfile : specify path to Dockerfile. By default E2B tries to find e2b.Dockerfile or Dockerfile in root directory. ` + - `-n, --name : specify sandbox template name. You can use the template name to start the sandbox with SDK. The template name must be lowercase and contain only letters, numbers, dashes and underscores. ` + - `-c, --cmd : specify command that will be executed when the sandbox is started. ` + - `--ready-cmd : specify command that will need to exit 0 for the template to be ready. ` + - `-t, --team : specify the team ID that the operation will be associated with. You can find team ID in the team settings in the E2B dashboard (https://e2b.dev/dashboard?tab=team). ` + - `--config : specify path to the E2B config toml. By default E2B tries to find ./e2b.toml in root directory. ` + - `--cpu-count : specify the number of CPUs that will be used to run the sandbox. The default value is 2. ` + - `--memory-mb : specify the amount of memory in megabytes that will be used to run the sandbox. Must be an even number. The default value is 512. ` + - `--build-arg : specify additional build arguments for the build command. The format should be =. ` + - `--no-cache: skip cache when building the template. ` + + +## e2b template list + + +list sandbox templates + +### Usage + +```bash +e2b template list [options] +``` + +### Options + + + - `-t, --team : specify the team ID that the operation will be associated with. You can find team ID in the team settings in the E2B dashboard (https://e2b.dev/dashboard?tab=team). ` + - `-f, --format : output format, eg. json, pretty ` + + +## e2b template init + + +initialize a new sandbox template using the SDK + +### Usage + +```bash +e2b template init [options] +``` + +### Options + + + - `-p, --path : change root directory where command is executed to  directory ` + - `-n, --name : template name (alias) ` + - `-l, --language : target language: typescript, python-sync, python-async ` + + +## e2b template delete + + +delete sandbox template and e2b.toml config + +### Usage + +```bash +e2b template delete [options] [template] +``` + +### Options + + + - `-p, --path : change root directory where command is executed to  directory ` + - `--config : specify path to the E2B config toml. By default E2B tries to find ./e2b.toml in root directory. ` + - `-s, --select: select sandbox template from interactive list ` + - `-t, --team : specify the team ID that the operation will be associated with. You can find team ID in the team settings in the E2B dashboard (https://e2b.dev/dashboard?tab=team). ` + - `-y, --yes: skip manual delete confirmation ` + + +## e2b template publish + + +publish sandbox template + +### Usage + +```bash +e2b template publish [options] [template] +``` + +### Options + + + - `-p, --path : change root directory where command is executed to  directory ` + - `--config : specify path to the E2B config toml. By default E2B tries to find ./e2b.toml in root directory. ` + - `-s, --select: select sandbox template from interactive list ` + - `-t, --team : specify the team ID that the operation will be associated with. You can find team ID in the team settings in the E2B dashboard (https://e2b.dev/dashboard?tab=team). ` + - `-y, --yes: skip manual publish confirmation ` + + +## e2b template unpublish + + +unpublish sandbox template + +### Usage + +```bash +e2b template unpublish [options] [template] +``` + +### Options + + + - `-p, --path : change root directory where command is executed to  directory ` + - `--config : specify path to the E2B config toml. By default E2B tries to find ./e2b.toml in root directory. ` + - `-s, --select: select sandbox template from interactive list ` + - `-t, --team : specify the team ID that the operation will be associated with. You can find team ID in the team settings in the E2B dashboard (https://e2b.dev/dashboard?tab=team). ` + - `-y, --yes: skip manual unpublish confirmation ` + + +## e2b template migrate + + +migrate e2b.Dockerfile and e2b.toml to new Template SDK format + +### Usage + +```bash +e2b template migrate [options] +``` + +### Options + + + - `-d, --dockerfile : specify path to Dockerfile. Defaults to e2b.Dockerfile ` + - `--config : specify path to the E2B config toml. By default E2B tries to find ./e2b.toml in root directory. ` + - `-l, --language : specify target language: typescript, python-sync, python-async ` + - `-p, --path : change root directory where command is executed to  directory ` + + diff --git a/docs/sdk-reference/cli/v2.4.2/auth.mdx b/docs/sdk-reference/cli/v2.4.2/auth.mdx new file mode 100644 index 0000000..c223c57 --- /dev/null +++ b/docs/sdk-reference/cli/v2.4.2/auth.mdx @@ -0,0 +1,63 @@ +--- +sidebarTitle: "Auth" +mode: "center" +--- + +## e2b auth + + +authentication commands + +### Usage + +```bash +e2b auth [options] [command] +``` +## e2b auth login + + +log in to CLI + +### Usage + +```bash +e2b auth login [options] +``` + + +## e2b auth logout + + +log out of CLI + +### Usage + +```bash +e2b auth logout [options] +``` + + +## e2b auth info + + +get information about the current user + +### Usage + +```bash +e2b auth info [options] +``` + + +## e2b auth configure + + +configure user + +### Usage + +```bash +e2b auth configure [options] +``` + + diff --git a/docs/sdk-reference/cli/v2.4.2/sandbox.mdx b/docs/sdk-reference/cli/v2.4.2/sandbox.mdx new file mode 100644 index 0000000..cc9ed31 --- /dev/null +++ b/docs/sdk-reference/cli/v2.4.2/sandbox.mdx @@ -0,0 +1,140 @@ +--- +sidebarTitle: "Sandbox" +mode: "center" +--- + +## e2b sandbox + + +work with sandboxes + +### Usage + +```bash +e2b sandbox [options] [command] +``` +## e2b sandbox connect + + +connect terminal to already running sandbox + +### Usage + +```bash +e2b sandbox connect [options] +``` + + +## e2b sandbox list + + +list all sandboxes, by default it list only running ones + +### Usage + +```bash +e2b sandbox list [options] +``` + +### Options + + + - `-s, --state : filter by state, eg. running, paused. Defaults to running ` + - `-m, --metadata : filter by metadata, eg. key1=value1 ` + - `-l, --limit : limit the number of sandboxes returned ` + - `-f, --format : output format, eg. json, pretty ` + + +## e2b sandbox kill + + +kill sandbox + +### Usage + +```bash +e2b sandbox kill [options] [sandboxIDs...] +``` + +### Options + + + - `-a, --all: kill all sandboxes ` + - `-s, --state : when used with -a/--all flag, filter by state, eg. running, paused. Defaults to running ` + - `-m, --metadata : when used with -a/--all flag, filter by metadata, eg. key1=value1 ` + + +## e2b sandbox create + + +create sandbox and connect terminal to it + +### Usage + +```bash +e2b sandbox create [options] [template] +``` + +### Options + + + - `-p, --path : change root directory where command is executed to  directory ` + - `--config : specify path to the E2B config toml. By default E2B tries to find ./e2b.toml in root directory. ` + + +## e2b sandbox spawn + + +create sandbox and connect terminal to it + +### Usage + +```bash +e2b sandbox spawn [options] [template] +``` + +### Options + + + - `-p, --path : change root directory where command is executed to  directory ` + - `--config : specify path to the E2B config toml. By default E2B tries to find ./e2b.toml in root directory. ` + + +## e2b sandbox logs + + +show logs for sandbox + +### Usage + +```bash +e2b sandbox logs [options] +``` + +### Options + + + - `--level : filter logs by level (DEBUG, INFO, WARN, ERROR). The logs with the higher levels will be also shown. [default: INFO]` + - `-f, --follow: keep streaming logs until the sandbox is closed ` + - `--format : specify format for printing logs (json, pretty) [default: pretty]` + - `--loggers [loggers]: filter logs by loggers. Specify multiple loggers by separating them with a comma. ` + + +## e2b sandbox metrics + + +show metrics for sandbox + +### Usage + +```bash +e2b sandbox metrics [options] +``` + +### Options + + + - `-f, --follow: keep streaming metrics until the sandbox is closed ` + - `--format : specify format for printing metrics (json, pretty) [default: pretty]` + + diff --git a/docs/sdk-reference/cli/v2.4.2/template.mdx b/docs/sdk-reference/cli/v2.4.2/template.mdx new file mode 100644 index 0000000..8e0b766 --- /dev/null +++ b/docs/sdk-reference/cli/v2.4.2/template.mdx @@ -0,0 +1,185 @@ +--- +sidebarTitle: "Template" +mode: "center" +--- + +## e2b template + + +manage sandbox templates + +### Usage + +```bash +e2b template [options] [command] +``` +## e2b template create + + +build Dockerfile as a Sandbox template. This command reads a Dockerfile and builds it directly. + +### Usage + +```bash +e2b template create [options] +``` + +### Options + + + - `-p, --path : change root directory where command is executed to  directory ` + - `-d, --dockerfile : specify path to Dockerfile. By default E2B tries to find e2b.Dockerfile or Dockerfile in root directory. ` + - `-c, --cmd : specify command that will be executed when the sandbox is started. ` + - `--ready-cmd : specify command that will need to exit 0 for the template to be ready. ` + - `--cpu-count : specify the number of CPUs that will be used to run the sandbox. The default value is 2. ` + - `--memory-mb : specify the amount of memory in megabytes that will be used to run the sandbox. Must be an even number. The default value is 512. ` + - `--no-cache: skip cache when building the template. ` + + +## e2b template build + + +build sandbox template defined by ./e2b.Dockerfile or ./Dockerfile in root directory. By default the root directory is the current working directory. This command also creates e2b.toml config. + +### Usage + +```bash +e2b template build [options] [template] +``` + +### Options + + + - `-p, --path : change root directory where command is executed to  directory ` + - `-d, --dockerfile : specify path to Dockerfile. By default E2B tries to find e2b.Dockerfile or Dockerfile in root directory. ` + - `-n, --name : specify sandbox template name. You can use the template name to start the sandbox with SDK. The template name must be lowercase and contain only letters, numbers, dashes and underscores. ` + - `-c, --cmd : specify command that will be executed when the sandbox is started. ` + - `--ready-cmd : specify command that will need to exit 0 for the template to be ready. ` + - `-t, --team : specify the team ID that the operation will be associated with. You can find team ID in the team settings in the E2B dashboard (https://e2b.dev/dashboard?tab=team). ` + - `--config : specify path to the E2B config toml. By default E2B tries to find ./e2b.toml in root directory. ` + - `--cpu-count : specify the number of CPUs that will be used to run the sandbox. The default value is 2. ` + - `--memory-mb : specify the amount of memory in megabytes that will be used to run the sandbox. Must be an even number. The default value is 512. ` + - `--build-arg : specify additional build arguments for the build command. The format should be =. ` + - `--no-cache: skip cache when building the template. ` + + +## e2b template list + + +list sandbox templates + +### Usage + +```bash +e2b template list [options] +``` + +### Options + + + - `-t, --team : specify the team ID that the operation will be associated with. You can find team ID in the team settings in the E2B dashboard (https://e2b.dev/dashboard?tab=team). ` + - `-f, --format : output format, eg. json, pretty ` + + +## e2b template init + + +initialize a new sandbox template using the SDK + +### Usage + +```bash +e2b template init [options] +``` + +### Options + + + - `-p, --path : change root directory where command is executed to  directory ` + - `-n, --name : template name (alias) ` + - `-l, --language : target language: typescript, python-sync, python-async ` + + +## e2b template delete + + +delete sandbox template and e2b.toml config + +### Usage + +```bash +e2b template delete [options] [template] +``` + +### Options + + + - `-p, --path : change root directory where command is executed to  directory ` + - `--config : specify path to the E2B config toml. By default E2B tries to find ./e2b.toml in root directory. ` + - `-s, --select: select sandbox template from interactive list ` + - `-t, --team : specify the team ID that the operation will be associated with. You can find team ID in the team settings in the E2B dashboard (https://e2b.dev/dashboard?tab=team). ` + - `-y, --yes: skip manual delete confirmation ` + + +## e2b template publish + + +publish sandbox template + +### Usage + +```bash +e2b template publish [options] [template] +``` + +### Options + + + - `-p, --path : change root directory where command is executed to  directory ` + - `--config : specify path to the E2B config toml. By default E2B tries to find ./e2b.toml in root directory. ` + - `-s, --select: select sandbox template from interactive list ` + - `-t, --team : specify the team ID that the operation will be associated with. You can find team ID in the team settings in the E2B dashboard (https://e2b.dev/dashboard?tab=team). ` + - `-y, --yes: skip manual publish confirmation ` + + +## e2b template unpublish + + +unpublish sandbox template + +### Usage + +```bash +e2b template unpublish [options] [template] +``` + +### Options + + + - `-p, --path : change root directory where command is executed to  directory ` + - `--config : specify path to the E2B config toml. By default E2B tries to find ./e2b.toml in root directory. ` + - `-s, --select: select sandbox template from interactive list ` + - `-t, --team : specify the team ID that the operation will be associated with. You can find team ID in the team settings in the E2B dashboard (https://e2b.dev/dashboard?tab=team). ` + - `-y, --yes: skip manual unpublish confirmation ` + + +## e2b template migrate + + +migrate e2b.Dockerfile and e2b.toml to new Template SDK format + +### Usage + +```bash +e2b template migrate [options] +``` + +### Options + + + - `-d, --dockerfile : specify path to Dockerfile. Defaults to e2b.Dockerfile ` + - `--config : specify path to the E2B config toml. By default E2B tries to find ./e2b.toml in root directory. ` + - `-l, --language : specify target language: typescript, python-sync, python-async ` + - `-p, --path : change root directory where command is executed to  directory ` + + diff --git a/docs/sdk-reference/code-interpreter-js-sdk/v2.3.0/charts.mdx b/docs/sdk-reference/code-interpreter-js-sdk/v2.3.0/charts.mdx new file mode 100644 index 0000000..d4cf7ad --- /dev/null +++ b/docs/sdk-reference/code-interpreter-js-sdk/v2.3.0/charts.mdx @@ -0,0 +1,245 @@ +--- +sidebarTitle: "Charts" +mode: "center" +--- + +### ChartType + +Chart types + +#### Enumeration Members + +| Enumeration Member | Value | +| ------ | ------ | +| `BAR` | `"bar"` | +| `BOX_AND_WHISKER` | `"box_and_whisker"` | +| `LINE` | `"line"` | +| `PIE` | `"pie"` | +| `SCATTER` | `"scatter"` | +| `SUPERCHART` | `"superchart"` | +| `UNKNOWN` | `"unknown"` | + +*** + +### ScaleType + +Ax scale types + +#### Enumeration Members + +| Enumeration Member | Value | +| ------ | ------ | +| `ASINH` | `"asinh"` | +| `CATEGORICAL` | `"categorical"` | +| `DATETIME` | `"datetime"` | +| `FUNCTION` | `"function"` | +| `FUNCTIONLOG` | `"functionlog"` | +| `LINEAR` | `"linear"` | +| `LOG` | `"log"` | +| `LOGIT` | `"logit"` | +| `SYMLOG` | `"symlog"` | + +## Type Aliases + +### BarChart + +```ts +type BarChart: Chart2D & object; +``` + +#### Type declaration + +| Name | Type | +| ------ | ------ | +| `elements` | `BarData`[] | +| `type` | `ChartType.BAR` | + +*** + +### BarData + +```ts +type BarData: object; +``` + +#### Type declaration + +| Name | Type | +| ------ | ------ | +| `group` | `string` | +| `label` | `string` | +| `value` | `string` | + +*** + +### BoxAndWhiskerChart + +```ts +type BoxAndWhiskerChart: Chart2D & object; +``` + +#### Type declaration + +| Name | Type | +| ------ | ------ | +| `elements` | `BoxAndWhiskerData`[] | +| `type` | `ChartType.BOX_AND_WHISKER` | + +*** + +### BoxAndWhiskerData + +```ts +type BoxAndWhiskerData: object; +``` + +#### Type declaration + +| Name | Type | +| ------ | ------ | +| `first_quartile` | `number` | +| `label` | `string` | +| `max` | `number` | +| `median` | `number` | +| `min` | `number` | +| `outliers` | `number`[] | +| `third_quartile` | `number` | + +*** + +### Chart + +```ts +type Chart: object; +``` + +Represents a chart. + +#### Type declaration + +| Name | Type | +| ------ | ------ | +| `elements` | `any`[] | +| `title` | `string` | +| `type` | `ChartType` | + +*** + +### ChartTypes + +```ts +type ChartTypes: + | LineChart + | ScatterChart + | BarChart + | PieChart + | BoxAndWhiskerChart + | SuperChart; +``` + +*** + +### LineChart + +```ts +type LineChart: PointChart & object; +``` + +#### Type declaration + +| Name | Type | +| ------ | ------ | +| `type` | `ChartType.LINE` | + +*** + +### PieChart + +```ts +type PieChart: Chart & object; +``` + +#### Type declaration + +| Name | Type | +| ------ | ------ | +| `elements` | `PieData`[] | +| `type` | `ChartType.PIE` | + +*** + +### PieData + +```ts +type PieData: object; +``` + +#### Type declaration + +| Name | Type | +| ------ | ------ | +| `angle` | `number` | +| `label` | `string` | +| `radius` | `number` | + +*** + +### PointData + +```ts +type PointData: object; +``` + +#### Type declaration + +| Name | Type | +| ------ | ------ | +| `label` | `string` | +| `points` | [`number` \| `string`, `number` \| `string`][] | + +*** + +### ScatterChart + +```ts +type ScatterChart: PointChart & object; +``` + +#### Type declaration + +| Name | Type | +| ------ | ------ | +| `type` | `ChartType.SCATTER` | + +*** + +### SuperChart + +```ts +type SuperChart: Chart & object; +``` + +#### Type declaration + +| Name | Type | +| ------ | ------ | +| `elements` | `Chart`[] | +| `type` | `ChartType.SUPERCHART` | + +## Functions + +### deserializeChart() + +```ts +function deserializeChart(data: any): Chart +``` + +#### Parameters + +| Parameter | Type | +| ------ | ------ | +| `data` | `any` | + +#### Returns + +`Chart` diff --git a/docs/sdk-reference/code-interpreter-js-sdk/v2.3.0/consts.mdx b/docs/sdk-reference/code-interpreter-js-sdk/v2.3.0/consts.mdx new file mode 100644 index 0000000..07462e7 --- /dev/null +++ b/docs/sdk-reference/code-interpreter-js-sdk/v2.3.0/consts.mdx @@ -0,0 +1,18 @@ +--- +sidebarTitle: "Consts" +mode: "center" +--- + +### DEFAULT\_TIMEOUT\_MS + +```ts +const DEFAULT_TIMEOUT_MS: 60000 = 60_000; +``` + +*** + +### JUPYTER\_PORT + +```ts +const JUPYTER_PORT: 49999 = 49999; +``` diff --git a/docs/sdk-reference/code-interpreter-js-sdk/v2.3.0/messaging.mdx b/docs/sdk-reference/code-interpreter-js-sdk/v2.3.0/messaging.mdx new file mode 100644 index 0000000..ef4f3e7 --- /dev/null +++ b/docs/sdk-reference/code-interpreter-js-sdk/v2.3.0/messaging.mdx @@ -0,0 +1,331 @@ +--- +sidebarTitle: "Messaging" +mode: "center" +--- + +### Execution + +Represents the result of a cell execution. + +#### Constructors + +```ts +new Execution( + results: Result[], + logs: Logs, + error?: ExecutionError, + executionCount?: number): Execution +``` + +###### Parameters + +| Parameter | Type | Default value | Description | +| ------ | ------ | ------ | ------ | +| `results` | `Result`[] | `[]` | List of result of the cell (interactively interpreted last line), display calls (e.g. matplotlib plots). | +| `logs` | `Logs` | `...` | Logs printed to stdout and stderr during execution. | +| `error`? | `ExecutionError` | `undefined` | An Error object if an error occurred, null otherwise. | +| `executionCount`? | `number` | `undefined` | Execution count of the cell. | + +###### Returns + +`Execution` + +#### Properties + +| Property | Modifier | Type | Default value | Description | +| ------ | ------ | ------ | ------ | ------ | +| `error?` | `public` | `ExecutionError` | `undefined` | An Error object if an error occurred, null otherwise. | +| `executionCount?` | `public` | `number` | `undefined` | Execution count of the cell. | +| `logs` | `public` | `Logs` | `undefined` | Logs printed to stdout and stderr during execution. | +| `results` | `public` | `Result`[] | `[]` | List of result of the cell (interactively interpreted last line), display calls (e.g. matplotlib plots). | + +#### Accessors + +### text + +```ts +get text(): undefined | string +``` + +Returns the text representation of the main result of the cell. + +###### Returns + +`undefined` \| `string` + +#### Methods + +### toJSON() + +```ts +toJSON(): object +``` + +Returns the serializable representation of the execution result. + +###### Returns + +`object` + +| Name | Type | +| ------ | ------ | +| `error` | `undefined` \| `ExecutionError` | +| `logs` | `Logs` | +| `results` | `Result`[] | + +*** + +### ExecutionError + +Represents an error that occurred during the execution of a cell. +The error contains the name of the error, the value of the error, and the traceback. + +#### Constructors + +```ts +new ExecutionError( + name: string, + value: string, + traceback: string): ExecutionError +``` + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `name` | `string` | Name of the error. | +| `value` | `string` | Value of the error. | +| `traceback` | `string` | The raw traceback of the error. | + +###### Returns + +`ExecutionError` + +#### Properties + +| Property | Modifier | Type | Description | +| ------ | ------ | ------ | ------ | +| `name` | `public` | `string` | Name of the error. | +| `traceback` | `public` | `string` | The raw traceback of the error. | +| `value` | `public` | `string` | Value of the error. | + +*** + +### OutputMessage + +Represents an output message from the sandbox code execution. + +#### Constructors + +```ts +new OutputMessage( + line: string, + timestamp: number, + error: boolean): OutputMessage +``` + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `line` | `string` | The output line. | +| `timestamp` | `number` | Unix epoch in nanoseconds. | +| `error` | `boolean` | Whether the output is an error. | + +###### Returns + +`OutputMessage` + +#### Properties + +| Property | Modifier | Type | Description | +| ------ | ------ | ------ | ------ | +| `error` | `readonly` | `boolean` | Whether the output is an error. | +| `line` | `readonly` | `string` | The output line. | +| `timestamp` | `readonly` | `number` | Unix epoch in nanoseconds. | + +#### Methods + +### toString() + +```ts +toString(): string +``` + +###### Returns + +`string` + +*** + +### Result + +Represents the data to be displayed as a result of executing a cell in a Jupyter notebook. +The result is similar to the structure returned by ipython kernel: https://ipython.readthedocs.io/en/stable/development/execution.html#execution-semantics + +The result can contain multiple types of data, such as text, images, plots, etc. Each type of data is represented +as a string, and the result can contain multiple types of data. The display calls don't have to have text representation, +for the actual result the representation is always present for the result, the other representations are always optional. + +#### Constructors + +```ts +new Result(rawData: RawData, isMainResult: boolean): Result +``` + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `rawData` | `RawData` | +| `isMainResult` | `boolean` | + +###### Returns + +`Result` + +#### Properties + +| Property | Modifier | Type | Description | +| ------ | ------ | ------ | ------ | +| `chart?` | `readonly` | `ChartTypes` | Contains the chart data. | +| `data?` | `readonly` | `Record`\<`string`, `unknown`\> | Contains the data from DataFrame. | +| `extra?` | `readonly` | `any` | Extra data that can be included. Not part of the standard types. | +| `html?` | `readonly` | `string` | HTML representation of the data. | +| `isMainResult` | `readonly` | `boolean` | - | +| `javascript?` | `readonly` | `string` | JavaScript representation of the data. | +| `jpeg?` | `readonly` | `string` | JPEG representation of the data. | +| `json?` | `readonly` | `string` | JSON representation of the data. | +| `latex?` | `readonly` | `string` | LaTeX representation of the data. | +| `markdown?` | `readonly` | `string` | Markdown representation of the data. | +| `pdf?` | `readonly` | `string` | PDF representation of the data. | +| `png?` | `readonly` | `string` | PNG representation of the data. | +| `raw` | `readonly` | `RawData` | - | +| `svg?` | `readonly` | `string` | SVG representation of the data. | +| `text?` | `readonly` | `string` | Text representation of the result. | + +#### Methods + +### formats() + +```ts +formats(): string[] +``` + +Returns all the formats available for the result. + +###### Returns + +`string`[] + +Array of strings representing the formats available for the result. + +### toJSON() + +```ts +toJSON(): object +``` + +Returns the serializable representation of the result. + +###### Returns + +`object` + +| Name | Type | +| ------ | ------ | +| `extra`? | `any` | +| `html` | `undefined` \| `string` | +| `javascript` | `undefined` \| `string` | +| `jpeg` | `undefined` \| `string` | +| `json` | `undefined` \| `string` | +| `latex` | `undefined` \| `string` | +| `markdown` | `undefined` \| `string` | +| `pdf` | `undefined` \| `string` | +| `png` | `undefined` \| `string` | +| `svg` | `undefined` \| `string` | +| `text` | `undefined` \| `string` | + +## Type Aliases + +### Logs + +```ts +type Logs: object; +``` + +Data printed to stdout and stderr during execution, usually by print statements, logs, warnings, subprocesses, etc. + +#### Type declaration + +| Name | Type | Description | +| ------ | ------ | ------ | +| `stderr` | `string`[] | List of strings printed to stderr by prints, subprocesses, etc. | +| `stdout` | `string`[] | List of strings printed to stdout by prints, subprocesses, etc. | + +*** + +### MIMEType + +```ts +type MIMEType: string; +``` + +Represents a MIME type. + +*** + +### RawData + +```ts +type RawData: object & E2BData; +``` + +Dictionary that maps MIME types to their corresponding representations of the data. + +## Functions + +### extractError() + +```ts +function extractError(res: Response): Promise +``` + +#### Parameters + +| Parameter | Type | +| ------ | ------ | +| `res` | `Response` | + +#### Returns + +`Promise`\<`undefined` \| `SandboxError`\> + +*** + +### parseOutput() + +```ts +function parseOutput( + execution: Execution, + line: string, + onStdout?: (output: OutputMessage) => any, + onStderr?: (output: OutputMessage) => any, + onResult?: (data: Result) => any, +onError?: (error: ExecutionError) => any): Promise +``` + +#### Parameters + +| Parameter | Type | +| ------ | ------ | +| `execution` | `Execution` | +| `line` | `string` | +| `onStdout`? | (`output`: `OutputMessage`) => `any` | +| `onStderr`? | (`output`: `OutputMessage`) => `any` | +| `onResult`? | (`data`: `Result`) => `any` | +| `onError`? | (`error`: `ExecutionError`) => `any` | + +#### Returns + +`Promise`\<`void`\> diff --git a/docs/sdk-reference/code-interpreter-js-sdk/v2.3.0/sandbox.mdx b/docs/sdk-reference/code-interpreter-js-sdk/v2.3.0/sandbox.mdx new file mode 100644 index 0000000..fb801ca --- /dev/null +++ b/docs/sdk-reference/code-interpreter-js-sdk/v2.3.0/sandbox.mdx @@ -0,0 +1,371 @@ +--- +sidebarTitle: "Sandbox" +mode: "center" +--- + +### Sandbox + +E2B cloud sandbox is a secure and isolated cloud environment. + +The sandbox allows you to: +- Access Linux OS +- Create, list, and delete files and directories +- Run commands +- Run isolated code +- Access the internet + +Check docs here. + +Use Sandbox.create to create a new sandbox. + +#### Example + +```ts +import { Sandbox } from '@e2b/code-interpreter' + +const sandbox = await Sandbox.create() +``` + +#### Methods + +### createCodeContext() + +```ts +createCodeContext(opts?: CreateCodeContextOpts): Promise +``` + +Creates a new context to run code in. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `opts`? | `CreateCodeContextOpts` | options for creating the context. | + +###### Returns + +`Promise`\<`Context`\> + +context object. + +### listCodeContexts() + +```ts +listCodeContexts(): Promise +``` + +List all contexts. + +###### Returns + +`Promise`\<`Context`[]\> + +list of contexts. + +### removeCodeContext() + +```ts +removeCodeContext(context: string | Context): Promise +``` + +Removes a context. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `context` | `string` \| `Context` | context to remove. | + +###### Returns + +`Promise`\<`void`\> + +void. + +### restartCodeContext() + +```ts +restartCodeContext(context: string | Context): Promise +``` + +Restart a context. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `context` | `string` \| `Context` | context to restart. | + +###### Returns + +`Promise`\<`void`\> + +void. + +### runCode() + +###### runCode(code, opts) + +```ts +runCode(code: string, opts?: RunCodeOpts & object): Promise +``` + +Run the code as Python. + +Specify the `language` or `context` option to run the code as a different language or in a different `Context`. + +You can reference previously defined variables, imports, and functions in the code. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `code` | `string` | code to execute. | +| `opts`? | `RunCodeOpts` & `object` | options for executing the code. | + +###### Returns + +`Promise`\<`Execution`\> + +`Execution` result object. + +###### runCode(code, opts) + +```ts +runCode(code: string, opts?: RunCodeOpts & object): Promise +``` + +Run the code for the specified language. + +Specify the `language` or `context` option to run the code as a different language or in a different `Context`. +If no language is specified, Python is used. + +You can reference previously defined variables, imports, and functions in the code. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `code` | `string` | code to execute. | +| `opts`? | `RunCodeOpts` & `object` | options for executing the code. | + +###### Returns + +`Promise`\<`Execution`\> + +`Execution` result object. + +###### runCode(code, opts) + +```ts +runCode(code: string, opts?: RunCodeOpts & object): Promise +``` + +Runs the code in the specified context, if not specified, the default context is used. + +Specify the `language` or `context` option to run the code as a different language or in a different `Context`. + +You can reference previously defined variables, imports, and functions in the code. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `code` | `string` | code to execute. | +| `opts`? | `RunCodeOpts` & `object` | options for executing the code | + +###### Returns + +`Promise`\<`Execution`\> + +`Execution` result object + +## Interfaces + +### CreateCodeContextOpts + +Options for creating a code context. + +#### Properties + +### cwd? + +```ts +optional cwd: string; +``` + +Working directory for the context. + +###### Default + +```ts +/home/user +``` + +### language? + +```ts +optional language: string; +``` + +Language for the context. + +###### Default + +```ts +python +``` + +### requestTimeoutMs? + +```ts +optional requestTimeoutMs: number; +``` + +Timeout for the request in **milliseconds**. + +###### Default + +```ts +30_000 // 30 seconds +``` + +*** + +### RunCodeOpts + +Options for running code. + +#### Properties + +### envs? + +```ts +optional envs: Record; +``` + +Custom environment variables for code execution. + +###### Default + +```ts +{} +``` + +### onError()? + +```ts +optional onError: (error: ExecutionError) => any; +``` + +Callback for handling the `ExecutionError` object. + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `error` | `ExecutionError` | + +###### Returns + +`any` + +### onResult()? + +```ts +optional onResult: (data: Result) => any; +``` + +Callback for handling the final execution result. + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `data` | `Result` | + +###### Returns + +`any` + +### onStderr()? + +```ts +optional onStderr: (output: OutputMessage) => any; +``` + +Callback for handling stderr messages. + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `output` | `OutputMessage` | + +###### Returns + +`any` + +### onStdout()? + +```ts +optional onStdout: (output: OutputMessage) => any; +``` + +Callback for handling stdout messages. + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `output` | `OutputMessage` | + +###### Returns + +`any` + +### requestTimeoutMs? + +```ts +optional requestTimeoutMs: number; +``` + +Timeout for the request in **milliseconds**. + +###### Default + +```ts +30_000 // 30 seconds +``` + +### timeoutMs? + +```ts +optional timeoutMs: number; +``` + +Timeout for the code execution in **milliseconds**. + +###### Default + +```ts +60_000 // 60 seconds +``` + +## Type Aliases + +### Context + +```ts +type Context: object; +``` + +Represents a context for code execution. + +#### Type declaration + +| Name | Type | Description | +| ------ | ------ | ------ | +| `cwd` | `string` | The working directory of the context. | +| `id` | `string` | The ID of the context. | +| `language` | `string` | The language of the context. | diff --git a/docs/sdk-reference/code-interpreter-js-sdk/v2.3.1/charts.mdx b/docs/sdk-reference/code-interpreter-js-sdk/v2.3.1/charts.mdx new file mode 100644 index 0000000..d4cf7ad --- /dev/null +++ b/docs/sdk-reference/code-interpreter-js-sdk/v2.3.1/charts.mdx @@ -0,0 +1,245 @@ +--- +sidebarTitle: "Charts" +mode: "center" +--- + +### ChartType + +Chart types + +#### Enumeration Members + +| Enumeration Member | Value | +| ------ | ------ | +| `BAR` | `"bar"` | +| `BOX_AND_WHISKER` | `"box_and_whisker"` | +| `LINE` | `"line"` | +| `PIE` | `"pie"` | +| `SCATTER` | `"scatter"` | +| `SUPERCHART` | `"superchart"` | +| `UNKNOWN` | `"unknown"` | + +*** + +### ScaleType + +Ax scale types + +#### Enumeration Members + +| Enumeration Member | Value | +| ------ | ------ | +| `ASINH` | `"asinh"` | +| `CATEGORICAL` | `"categorical"` | +| `DATETIME` | `"datetime"` | +| `FUNCTION` | `"function"` | +| `FUNCTIONLOG` | `"functionlog"` | +| `LINEAR` | `"linear"` | +| `LOG` | `"log"` | +| `LOGIT` | `"logit"` | +| `SYMLOG` | `"symlog"` | + +## Type Aliases + +### BarChart + +```ts +type BarChart: Chart2D & object; +``` + +#### Type declaration + +| Name | Type | +| ------ | ------ | +| `elements` | `BarData`[] | +| `type` | `ChartType.BAR` | + +*** + +### BarData + +```ts +type BarData: object; +``` + +#### Type declaration + +| Name | Type | +| ------ | ------ | +| `group` | `string` | +| `label` | `string` | +| `value` | `string` | + +*** + +### BoxAndWhiskerChart + +```ts +type BoxAndWhiskerChart: Chart2D & object; +``` + +#### Type declaration + +| Name | Type | +| ------ | ------ | +| `elements` | `BoxAndWhiskerData`[] | +| `type` | `ChartType.BOX_AND_WHISKER` | + +*** + +### BoxAndWhiskerData + +```ts +type BoxAndWhiskerData: object; +``` + +#### Type declaration + +| Name | Type | +| ------ | ------ | +| `first_quartile` | `number` | +| `label` | `string` | +| `max` | `number` | +| `median` | `number` | +| `min` | `number` | +| `outliers` | `number`[] | +| `third_quartile` | `number` | + +*** + +### Chart + +```ts +type Chart: object; +``` + +Represents a chart. + +#### Type declaration + +| Name | Type | +| ------ | ------ | +| `elements` | `any`[] | +| `title` | `string` | +| `type` | `ChartType` | + +*** + +### ChartTypes + +```ts +type ChartTypes: + | LineChart + | ScatterChart + | BarChart + | PieChart + | BoxAndWhiskerChart + | SuperChart; +``` + +*** + +### LineChart + +```ts +type LineChart: PointChart & object; +``` + +#### Type declaration + +| Name | Type | +| ------ | ------ | +| `type` | `ChartType.LINE` | + +*** + +### PieChart + +```ts +type PieChart: Chart & object; +``` + +#### Type declaration + +| Name | Type | +| ------ | ------ | +| `elements` | `PieData`[] | +| `type` | `ChartType.PIE` | + +*** + +### PieData + +```ts +type PieData: object; +``` + +#### Type declaration + +| Name | Type | +| ------ | ------ | +| `angle` | `number` | +| `label` | `string` | +| `radius` | `number` | + +*** + +### PointData + +```ts +type PointData: object; +``` + +#### Type declaration + +| Name | Type | +| ------ | ------ | +| `label` | `string` | +| `points` | [`number` \| `string`, `number` \| `string`][] | + +*** + +### ScatterChart + +```ts +type ScatterChart: PointChart & object; +``` + +#### Type declaration + +| Name | Type | +| ------ | ------ | +| `type` | `ChartType.SCATTER` | + +*** + +### SuperChart + +```ts +type SuperChart: Chart & object; +``` + +#### Type declaration + +| Name | Type | +| ------ | ------ | +| `elements` | `Chart`[] | +| `type` | `ChartType.SUPERCHART` | + +## Functions + +### deserializeChart() + +```ts +function deserializeChart(data: any): Chart +``` + +#### Parameters + +| Parameter | Type | +| ------ | ------ | +| `data` | `any` | + +#### Returns + +`Chart` diff --git a/docs/sdk-reference/code-interpreter-js-sdk/v2.3.1/consts.mdx b/docs/sdk-reference/code-interpreter-js-sdk/v2.3.1/consts.mdx new file mode 100644 index 0000000..07462e7 --- /dev/null +++ b/docs/sdk-reference/code-interpreter-js-sdk/v2.3.1/consts.mdx @@ -0,0 +1,18 @@ +--- +sidebarTitle: "Consts" +mode: "center" +--- + +### DEFAULT\_TIMEOUT\_MS + +```ts +const DEFAULT_TIMEOUT_MS: 60000 = 60_000; +``` + +*** + +### JUPYTER\_PORT + +```ts +const JUPYTER_PORT: 49999 = 49999; +``` diff --git a/docs/sdk-reference/code-interpreter-js-sdk/v2.3.1/messaging.mdx b/docs/sdk-reference/code-interpreter-js-sdk/v2.3.1/messaging.mdx new file mode 100644 index 0000000..ef4f3e7 --- /dev/null +++ b/docs/sdk-reference/code-interpreter-js-sdk/v2.3.1/messaging.mdx @@ -0,0 +1,331 @@ +--- +sidebarTitle: "Messaging" +mode: "center" +--- + +### Execution + +Represents the result of a cell execution. + +#### Constructors + +```ts +new Execution( + results: Result[], + logs: Logs, + error?: ExecutionError, + executionCount?: number): Execution +``` + +###### Parameters + +| Parameter | Type | Default value | Description | +| ------ | ------ | ------ | ------ | +| `results` | `Result`[] | `[]` | List of result of the cell (interactively interpreted last line), display calls (e.g. matplotlib plots). | +| `logs` | `Logs` | `...` | Logs printed to stdout and stderr during execution. | +| `error`? | `ExecutionError` | `undefined` | An Error object if an error occurred, null otherwise. | +| `executionCount`? | `number` | `undefined` | Execution count of the cell. | + +###### Returns + +`Execution` + +#### Properties + +| Property | Modifier | Type | Default value | Description | +| ------ | ------ | ------ | ------ | ------ | +| `error?` | `public` | `ExecutionError` | `undefined` | An Error object if an error occurred, null otherwise. | +| `executionCount?` | `public` | `number` | `undefined` | Execution count of the cell. | +| `logs` | `public` | `Logs` | `undefined` | Logs printed to stdout and stderr during execution. | +| `results` | `public` | `Result`[] | `[]` | List of result of the cell (interactively interpreted last line), display calls (e.g. matplotlib plots). | + +#### Accessors + +### text + +```ts +get text(): undefined | string +``` + +Returns the text representation of the main result of the cell. + +###### Returns + +`undefined` \| `string` + +#### Methods + +### toJSON() + +```ts +toJSON(): object +``` + +Returns the serializable representation of the execution result. + +###### Returns + +`object` + +| Name | Type | +| ------ | ------ | +| `error` | `undefined` \| `ExecutionError` | +| `logs` | `Logs` | +| `results` | `Result`[] | + +*** + +### ExecutionError + +Represents an error that occurred during the execution of a cell. +The error contains the name of the error, the value of the error, and the traceback. + +#### Constructors + +```ts +new ExecutionError( + name: string, + value: string, + traceback: string): ExecutionError +``` + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `name` | `string` | Name of the error. | +| `value` | `string` | Value of the error. | +| `traceback` | `string` | The raw traceback of the error. | + +###### Returns + +`ExecutionError` + +#### Properties + +| Property | Modifier | Type | Description | +| ------ | ------ | ------ | ------ | +| `name` | `public` | `string` | Name of the error. | +| `traceback` | `public` | `string` | The raw traceback of the error. | +| `value` | `public` | `string` | Value of the error. | + +*** + +### OutputMessage + +Represents an output message from the sandbox code execution. + +#### Constructors + +```ts +new OutputMessage( + line: string, + timestamp: number, + error: boolean): OutputMessage +``` + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `line` | `string` | The output line. | +| `timestamp` | `number` | Unix epoch in nanoseconds. | +| `error` | `boolean` | Whether the output is an error. | + +###### Returns + +`OutputMessage` + +#### Properties + +| Property | Modifier | Type | Description | +| ------ | ------ | ------ | ------ | +| `error` | `readonly` | `boolean` | Whether the output is an error. | +| `line` | `readonly` | `string` | The output line. | +| `timestamp` | `readonly` | `number` | Unix epoch in nanoseconds. | + +#### Methods + +### toString() + +```ts +toString(): string +``` + +###### Returns + +`string` + +*** + +### Result + +Represents the data to be displayed as a result of executing a cell in a Jupyter notebook. +The result is similar to the structure returned by ipython kernel: https://ipython.readthedocs.io/en/stable/development/execution.html#execution-semantics + +The result can contain multiple types of data, such as text, images, plots, etc. Each type of data is represented +as a string, and the result can contain multiple types of data. The display calls don't have to have text representation, +for the actual result the representation is always present for the result, the other representations are always optional. + +#### Constructors + +```ts +new Result(rawData: RawData, isMainResult: boolean): Result +``` + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `rawData` | `RawData` | +| `isMainResult` | `boolean` | + +###### Returns + +`Result` + +#### Properties + +| Property | Modifier | Type | Description | +| ------ | ------ | ------ | ------ | +| `chart?` | `readonly` | `ChartTypes` | Contains the chart data. | +| `data?` | `readonly` | `Record`\<`string`, `unknown`\> | Contains the data from DataFrame. | +| `extra?` | `readonly` | `any` | Extra data that can be included. Not part of the standard types. | +| `html?` | `readonly` | `string` | HTML representation of the data. | +| `isMainResult` | `readonly` | `boolean` | - | +| `javascript?` | `readonly` | `string` | JavaScript representation of the data. | +| `jpeg?` | `readonly` | `string` | JPEG representation of the data. | +| `json?` | `readonly` | `string` | JSON representation of the data. | +| `latex?` | `readonly` | `string` | LaTeX representation of the data. | +| `markdown?` | `readonly` | `string` | Markdown representation of the data. | +| `pdf?` | `readonly` | `string` | PDF representation of the data. | +| `png?` | `readonly` | `string` | PNG representation of the data. | +| `raw` | `readonly` | `RawData` | - | +| `svg?` | `readonly` | `string` | SVG representation of the data. | +| `text?` | `readonly` | `string` | Text representation of the result. | + +#### Methods + +### formats() + +```ts +formats(): string[] +``` + +Returns all the formats available for the result. + +###### Returns + +`string`[] + +Array of strings representing the formats available for the result. + +### toJSON() + +```ts +toJSON(): object +``` + +Returns the serializable representation of the result. + +###### Returns + +`object` + +| Name | Type | +| ------ | ------ | +| `extra`? | `any` | +| `html` | `undefined` \| `string` | +| `javascript` | `undefined` \| `string` | +| `jpeg` | `undefined` \| `string` | +| `json` | `undefined` \| `string` | +| `latex` | `undefined` \| `string` | +| `markdown` | `undefined` \| `string` | +| `pdf` | `undefined` \| `string` | +| `png` | `undefined` \| `string` | +| `svg` | `undefined` \| `string` | +| `text` | `undefined` \| `string` | + +## Type Aliases + +### Logs + +```ts +type Logs: object; +``` + +Data printed to stdout and stderr during execution, usually by print statements, logs, warnings, subprocesses, etc. + +#### Type declaration + +| Name | Type | Description | +| ------ | ------ | ------ | +| `stderr` | `string`[] | List of strings printed to stderr by prints, subprocesses, etc. | +| `stdout` | `string`[] | List of strings printed to stdout by prints, subprocesses, etc. | + +*** + +### MIMEType + +```ts +type MIMEType: string; +``` + +Represents a MIME type. + +*** + +### RawData + +```ts +type RawData: object & E2BData; +``` + +Dictionary that maps MIME types to their corresponding representations of the data. + +## Functions + +### extractError() + +```ts +function extractError(res: Response): Promise +``` + +#### Parameters + +| Parameter | Type | +| ------ | ------ | +| `res` | `Response` | + +#### Returns + +`Promise`\<`undefined` \| `SandboxError`\> + +*** + +### parseOutput() + +```ts +function parseOutput( + execution: Execution, + line: string, + onStdout?: (output: OutputMessage) => any, + onStderr?: (output: OutputMessage) => any, + onResult?: (data: Result) => any, +onError?: (error: ExecutionError) => any): Promise +``` + +#### Parameters + +| Parameter | Type | +| ------ | ------ | +| `execution` | `Execution` | +| `line` | `string` | +| `onStdout`? | (`output`: `OutputMessage`) => `any` | +| `onStderr`? | (`output`: `OutputMessage`) => `any` | +| `onResult`? | (`data`: `Result`) => `any` | +| `onError`? | (`error`: `ExecutionError`) => `any` | + +#### Returns + +`Promise`\<`void`\> diff --git a/docs/sdk-reference/code-interpreter-js-sdk/v2.3.1/sandbox.mdx b/docs/sdk-reference/code-interpreter-js-sdk/v2.3.1/sandbox.mdx new file mode 100644 index 0000000..fb801ca --- /dev/null +++ b/docs/sdk-reference/code-interpreter-js-sdk/v2.3.1/sandbox.mdx @@ -0,0 +1,371 @@ +--- +sidebarTitle: "Sandbox" +mode: "center" +--- + +### Sandbox + +E2B cloud sandbox is a secure and isolated cloud environment. + +The sandbox allows you to: +- Access Linux OS +- Create, list, and delete files and directories +- Run commands +- Run isolated code +- Access the internet + +Check docs here. + +Use Sandbox.create to create a new sandbox. + +#### Example + +```ts +import { Sandbox } from '@e2b/code-interpreter' + +const sandbox = await Sandbox.create() +``` + +#### Methods + +### createCodeContext() + +```ts +createCodeContext(opts?: CreateCodeContextOpts): Promise +``` + +Creates a new context to run code in. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `opts`? | `CreateCodeContextOpts` | options for creating the context. | + +###### Returns + +`Promise`\<`Context`\> + +context object. + +### listCodeContexts() + +```ts +listCodeContexts(): Promise +``` + +List all contexts. + +###### Returns + +`Promise`\<`Context`[]\> + +list of contexts. + +### removeCodeContext() + +```ts +removeCodeContext(context: string | Context): Promise +``` + +Removes a context. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `context` | `string` \| `Context` | context to remove. | + +###### Returns + +`Promise`\<`void`\> + +void. + +### restartCodeContext() + +```ts +restartCodeContext(context: string | Context): Promise +``` + +Restart a context. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `context` | `string` \| `Context` | context to restart. | + +###### Returns + +`Promise`\<`void`\> + +void. + +### runCode() + +###### runCode(code, opts) + +```ts +runCode(code: string, opts?: RunCodeOpts & object): Promise +``` + +Run the code as Python. + +Specify the `language` or `context` option to run the code as a different language or in a different `Context`. + +You can reference previously defined variables, imports, and functions in the code. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `code` | `string` | code to execute. | +| `opts`? | `RunCodeOpts` & `object` | options for executing the code. | + +###### Returns + +`Promise`\<`Execution`\> + +`Execution` result object. + +###### runCode(code, opts) + +```ts +runCode(code: string, opts?: RunCodeOpts & object): Promise +``` + +Run the code for the specified language. + +Specify the `language` or `context` option to run the code as a different language or in a different `Context`. +If no language is specified, Python is used. + +You can reference previously defined variables, imports, and functions in the code. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `code` | `string` | code to execute. | +| `opts`? | `RunCodeOpts` & `object` | options for executing the code. | + +###### Returns + +`Promise`\<`Execution`\> + +`Execution` result object. + +###### runCode(code, opts) + +```ts +runCode(code: string, opts?: RunCodeOpts & object): Promise +``` + +Runs the code in the specified context, if not specified, the default context is used. + +Specify the `language` or `context` option to run the code as a different language or in a different `Context`. + +You can reference previously defined variables, imports, and functions in the code. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `code` | `string` | code to execute. | +| `opts`? | `RunCodeOpts` & `object` | options for executing the code | + +###### Returns + +`Promise`\<`Execution`\> + +`Execution` result object + +## Interfaces + +### CreateCodeContextOpts + +Options for creating a code context. + +#### Properties + +### cwd? + +```ts +optional cwd: string; +``` + +Working directory for the context. + +###### Default + +```ts +/home/user +``` + +### language? + +```ts +optional language: string; +``` + +Language for the context. + +###### Default + +```ts +python +``` + +### requestTimeoutMs? + +```ts +optional requestTimeoutMs: number; +``` + +Timeout for the request in **milliseconds**. + +###### Default + +```ts +30_000 // 30 seconds +``` + +*** + +### RunCodeOpts + +Options for running code. + +#### Properties + +### envs? + +```ts +optional envs: Record; +``` + +Custom environment variables for code execution. + +###### Default + +```ts +{} +``` + +### onError()? + +```ts +optional onError: (error: ExecutionError) => any; +``` + +Callback for handling the `ExecutionError` object. + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `error` | `ExecutionError` | + +###### Returns + +`any` + +### onResult()? + +```ts +optional onResult: (data: Result) => any; +``` + +Callback for handling the final execution result. + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `data` | `Result` | + +###### Returns + +`any` + +### onStderr()? + +```ts +optional onStderr: (output: OutputMessage) => any; +``` + +Callback for handling stderr messages. + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `output` | `OutputMessage` | + +###### Returns + +`any` + +### onStdout()? + +```ts +optional onStdout: (output: OutputMessage) => any; +``` + +Callback for handling stdout messages. + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `output` | `OutputMessage` | + +###### Returns + +`any` + +### requestTimeoutMs? + +```ts +optional requestTimeoutMs: number; +``` + +Timeout for the request in **milliseconds**. + +###### Default + +```ts +30_000 // 30 seconds +``` + +### timeoutMs? + +```ts +optional timeoutMs: number; +``` + +Timeout for the code execution in **milliseconds**. + +###### Default + +```ts +60_000 // 60 seconds +``` + +## Type Aliases + +### Context + +```ts +type Context: object; +``` + +Represents a context for code execution. + +#### Type declaration + +| Name | Type | Description | +| ------ | ------ | ------ | +| `cwd` | `string` | The working directory of the context. | +| `id` | `string` | The ID of the context. | +| `language` | `string` | The language of the context. | diff --git a/docs/sdk-reference/code-interpreter-js-sdk/v2.3.2/charts.mdx b/docs/sdk-reference/code-interpreter-js-sdk/v2.3.2/charts.mdx new file mode 100644 index 0000000..d4cf7ad --- /dev/null +++ b/docs/sdk-reference/code-interpreter-js-sdk/v2.3.2/charts.mdx @@ -0,0 +1,245 @@ +--- +sidebarTitle: "Charts" +mode: "center" +--- + +### ChartType + +Chart types + +#### Enumeration Members + +| Enumeration Member | Value | +| ------ | ------ | +| `BAR` | `"bar"` | +| `BOX_AND_WHISKER` | `"box_and_whisker"` | +| `LINE` | `"line"` | +| `PIE` | `"pie"` | +| `SCATTER` | `"scatter"` | +| `SUPERCHART` | `"superchart"` | +| `UNKNOWN` | `"unknown"` | + +*** + +### ScaleType + +Ax scale types + +#### Enumeration Members + +| Enumeration Member | Value | +| ------ | ------ | +| `ASINH` | `"asinh"` | +| `CATEGORICAL` | `"categorical"` | +| `DATETIME` | `"datetime"` | +| `FUNCTION` | `"function"` | +| `FUNCTIONLOG` | `"functionlog"` | +| `LINEAR` | `"linear"` | +| `LOG` | `"log"` | +| `LOGIT` | `"logit"` | +| `SYMLOG` | `"symlog"` | + +## Type Aliases + +### BarChart + +```ts +type BarChart: Chart2D & object; +``` + +#### Type declaration + +| Name | Type | +| ------ | ------ | +| `elements` | `BarData`[] | +| `type` | `ChartType.BAR` | + +*** + +### BarData + +```ts +type BarData: object; +``` + +#### Type declaration + +| Name | Type | +| ------ | ------ | +| `group` | `string` | +| `label` | `string` | +| `value` | `string` | + +*** + +### BoxAndWhiskerChart + +```ts +type BoxAndWhiskerChart: Chart2D & object; +``` + +#### Type declaration + +| Name | Type | +| ------ | ------ | +| `elements` | `BoxAndWhiskerData`[] | +| `type` | `ChartType.BOX_AND_WHISKER` | + +*** + +### BoxAndWhiskerData + +```ts +type BoxAndWhiskerData: object; +``` + +#### Type declaration + +| Name | Type | +| ------ | ------ | +| `first_quartile` | `number` | +| `label` | `string` | +| `max` | `number` | +| `median` | `number` | +| `min` | `number` | +| `outliers` | `number`[] | +| `third_quartile` | `number` | + +*** + +### Chart + +```ts +type Chart: object; +``` + +Represents a chart. + +#### Type declaration + +| Name | Type | +| ------ | ------ | +| `elements` | `any`[] | +| `title` | `string` | +| `type` | `ChartType` | + +*** + +### ChartTypes + +```ts +type ChartTypes: + | LineChart + | ScatterChart + | BarChart + | PieChart + | BoxAndWhiskerChart + | SuperChart; +``` + +*** + +### LineChart + +```ts +type LineChart: PointChart & object; +``` + +#### Type declaration + +| Name | Type | +| ------ | ------ | +| `type` | `ChartType.LINE` | + +*** + +### PieChart + +```ts +type PieChart: Chart & object; +``` + +#### Type declaration + +| Name | Type | +| ------ | ------ | +| `elements` | `PieData`[] | +| `type` | `ChartType.PIE` | + +*** + +### PieData + +```ts +type PieData: object; +``` + +#### Type declaration + +| Name | Type | +| ------ | ------ | +| `angle` | `number` | +| `label` | `string` | +| `radius` | `number` | + +*** + +### PointData + +```ts +type PointData: object; +``` + +#### Type declaration + +| Name | Type | +| ------ | ------ | +| `label` | `string` | +| `points` | [`number` \| `string`, `number` \| `string`][] | + +*** + +### ScatterChart + +```ts +type ScatterChart: PointChart & object; +``` + +#### Type declaration + +| Name | Type | +| ------ | ------ | +| `type` | `ChartType.SCATTER` | + +*** + +### SuperChart + +```ts +type SuperChart: Chart & object; +``` + +#### Type declaration + +| Name | Type | +| ------ | ------ | +| `elements` | `Chart`[] | +| `type` | `ChartType.SUPERCHART` | + +## Functions + +### deserializeChart() + +```ts +function deserializeChart(data: any): Chart +``` + +#### Parameters + +| Parameter | Type | +| ------ | ------ | +| `data` | `any` | + +#### Returns + +`Chart` diff --git a/docs/sdk-reference/code-interpreter-js-sdk/v2.3.2/consts.mdx b/docs/sdk-reference/code-interpreter-js-sdk/v2.3.2/consts.mdx new file mode 100644 index 0000000..07462e7 --- /dev/null +++ b/docs/sdk-reference/code-interpreter-js-sdk/v2.3.2/consts.mdx @@ -0,0 +1,18 @@ +--- +sidebarTitle: "Consts" +mode: "center" +--- + +### DEFAULT\_TIMEOUT\_MS + +```ts +const DEFAULT_TIMEOUT_MS: 60000 = 60_000; +``` + +*** + +### JUPYTER\_PORT + +```ts +const JUPYTER_PORT: 49999 = 49999; +``` diff --git a/docs/sdk-reference/code-interpreter-js-sdk/v2.3.2/messaging.mdx b/docs/sdk-reference/code-interpreter-js-sdk/v2.3.2/messaging.mdx new file mode 100644 index 0000000..ef4f3e7 --- /dev/null +++ b/docs/sdk-reference/code-interpreter-js-sdk/v2.3.2/messaging.mdx @@ -0,0 +1,331 @@ +--- +sidebarTitle: "Messaging" +mode: "center" +--- + +### Execution + +Represents the result of a cell execution. + +#### Constructors + +```ts +new Execution( + results: Result[], + logs: Logs, + error?: ExecutionError, + executionCount?: number): Execution +``` + +###### Parameters + +| Parameter | Type | Default value | Description | +| ------ | ------ | ------ | ------ | +| `results` | `Result`[] | `[]` | List of result of the cell (interactively interpreted last line), display calls (e.g. matplotlib plots). | +| `logs` | `Logs` | `...` | Logs printed to stdout and stderr during execution. | +| `error`? | `ExecutionError` | `undefined` | An Error object if an error occurred, null otherwise. | +| `executionCount`? | `number` | `undefined` | Execution count of the cell. | + +###### Returns + +`Execution` + +#### Properties + +| Property | Modifier | Type | Default value | Description | +| ------ | ------ | ------ | ------ | ------ | +| `error?` | `public` | `ExecutionError` | `undefined` | An Error object if an error occurred, null otherwise. | +| `executionCount?` | `public` | `number` | `undefined` | Execution count of the cell. | +| `logs` | `public` | `Logs` | `undefined` | Logs printed to stdout and stderr during execution. | +| `results` | `public` | `Result`[] | `[]` | List of result of the cell (interactively interpreted last line), display calls (e.g. matplotlib plots). | + +#### Accessors + +### text + +```ts +get text(): undefined | string +``` + +Returns the text representation of the main result of the cell. + +###### Returns + +`undefined` \| `string` + +#### Methods + +### toJSON() + +```ts +toJSON(): object +``` + +Returns the serializable representation of the execution result. + +###### Returns + +`object` + +| Name | Type | +| ------ | ------ | +| `error` | `undefined` \| `ExecutionError` | +| `logs` | `Logs` | +| `results` | `Result`[] | + +*** + +### ExecutionError + +Represents an error that occurred during the execution of a cell. +The error contains the name of the error, the value of the error, and the traceback. + +#### Constructors + +```ts +new ExecutionError( + name: string, + value: string, + traceback: string): ExecutionError +``` + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `name` | `string` | Name of the error. | +| `value` | `string` | Value of the error. | +| `traceback` | `string` | The raw traceback of the error. | + +###### Returns + +`ExecutionError` + +#### Properties + +| Property | Modifier | Type | Description | +| ------ | ------ | ------ | ------ | +| `name` | `public` | `string` | Name of the error. | +| `traceback` | `public` | `string` | The raw traceback of the error. | +| `value` | `public` | `string` | Value of the error. | + +*** + +### OutputMessage + +Represents an output message from the sandbox code execution. + +#### Constructors + +```ts +new OutputMessage( + line: string, + timestamp: number, + error: boolean): OutputMessage +``` + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `line` | `string` | The output line. | +| `timestamp` | `number` | Unix epoch in nanoseconds. | +| `error` | `boolean` | Whether the output is an error. | + +###### Returns + +`OutputMessage` + +#### Properties + +| Property | Modifier | Type | Description | +| ------ | ------ | ------ | ------ | +| `error` | `readonly` | `boolean` | Whether the output is an error. | +| `line` | `readonly` | `string` | The output line. | +| `timestamp` | `readonly` | `number` | Unix epoch in nanoseconds. | + +#### Methods + +### toString() + +```ts +toString(): string +``` + +###### Returns + +`string` + +*** + +### Result + +Represents the data to be displayed as a result of executing a cell in a Jupyter notebook. +The result is similar to the structure returned by ipython kernel: https://ipython.readthedocs.io/en/stable/development/execution.html#execution-semantics + +The result can contain multiple types of data, such as text, images, plots, etc. Each type of data is represented +as a string, and the result can contain multiple types of data. The display calls don't have to have text representation, +for the actual result the representation is always present for the result, the other representations are always optional. + +#### Constructors + +```ts +new Result(rawData: RawData, isMainResult: boolean): Result +``` + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `rawData` | `RawData` | +| `isMainResult` | `boolean` | + +###### Returns + +`Result` + +#### Properties + +| Property | Modifier | Type | Description | +| ------ | ------ | ------ | ------ | +| `chart?` | `readonly` | `ChartTypes` | Contains the chart data. | +| `data?` | `readonly` | `Record`\<`string`, `unknown`\> | Contains the data from DataFrame. | +| `extra?` | `readonly` | `any` | Extra data that can be included. Not part of the standard types. | +| `html?` | `readonly` | `string` | HTML representation of the data. | +| `isMainResult` | `readonly` | `boolean` | - | +| `javascript?` | `readonly` | `string` | JavaScript representation of the data. | +| `jpeg?` | `readonly` | `string` | JPEG representation of the data. | +| `json?` | `readonly` | `string` | JSON representation of the data. | +| `latex?` | `readonly` | `string` | LaTeX representation of the data. | +| `markdown?` | `readonly` | `string` | Markdown representation of the data. | +| `pdf?` | `readonly` | `string` | PDF representation of the data. | +| `png?` | `readonly` | `string` | PNG representation of the data. | +| `raw` | `readonly` | `RawData` | - | +| `svg?` | `readonly` | `string` | SVG representation of the data. | +| `text?` | `readonly` | `string` | Text representation of the result. | + +#### Methods + +### formats() + +```ts +formats(): string[] +``` + +Returns all the formats available for the result. + +###### Returns + +`string`[] + +Array of strings representing the formats available for the result. + +### toJSON() + +```ts +toJSON(): object +``` + +Returns the serializable representation of the result. + +###### Returns + +`object` + +| Name | Type | +| ------ | ------ | +| `extra`? | `any` | +| `html` | `undefined` \| `string` | +| `javascript` | `undefined` \| `string` | +| `jpeg` | `undefined` \| `string` | +| `json` | `undefined` \| `string` | +| `latex` | `undefined` \| `string` | +| `markdown` | `undefined` \| `string` | +| `pdf` | `undefined` \| `string` | +| `png` | `undefined` \| `string` | +| `svg` | `undefined` \| `string` | +| `text` | `undefined` \| `string` | + +## Type Aliases + +### Logs + +```ts +type Logs: object; +``` + +Data printed to stdout and stderr during execution, usually by print statements, logs, warnings, subprocesses, etc. + +#### Type declaration + +| Name | Type | Description | +| ------ | ------ | ------ | +| `stderr` | `string`[] | List of strings printed to stderr by prints, subprocesses, etc. | +| `stdout` | `string`[] | List of strings printed to stdout by prints, subprocesses, etc. | + +*** + +### MIMEType + +```ts +type MIMEType: string; +``` + +Represents a MIME type. + +*** + +### RawData + +```ts +type RawData: object & E2BData; +``` + +Dictionary that maps MIME types to their corresponding representations of the data. + +## Functions + +### extractError() + +```ts +function extractError(res: Response): Promise +``` + +#### Parameters + +| Parameter | Type | +| ------ | ------ | +| `res` | `Response` | + +#### Returns + +`Promise`\<`undefined` \| `SandboxError`\> + +*** + +### parseOutput() + +```ts +function parseOutput( + execution: Execution, + line: string, + onStdout?: (output: OutputMessage) => any, + onStderr?: (output: OutputMessage) => any, + onResult?: (data: Result) => any, +onError?: (error: ExecutionError) => any): Promise +``` + +#### Parameters + +| Parameter | Type | +| ------ | ------ | +| `execution` | `Execution` | +| `line` | `string` | +| `onStdout`? | (`output`: `OutputMessage`) => `any` | +| `onStderr`? | (`output`: `OutputMessage`) => `any` | +| `onResult`? | (`data`: `Result`) => `any` | +| `onError`? | (`error`: `ExecutionError`) => `any` | + +#### Returns + +`Promise`\<`void`\> diff --git a/docs/sdk-reference/code-interpreter-js-sdk/v2.3.2/sandbox.mdx b/docs/sdk-reference/code-interpreter-js-sdk/v2.3.2/sandbox.mdx new file mode 100644 index 0000000..fb801ca --- /dev/null +++ b/docs/sdk-reference/code-interpreter-js-sdk/v2.3.2/sandbox.mdx @@ -0,0 +1,371 @@ +--- +sidebarTitle: "Sandbox" +mode: "center" +--- + +### Sandbox + +E2B cloud sandbox is a secure and isolated cloud environment. + +The sandbox allows you to: +- Access Linux OS +- Create, list, and delete files and directories +- Run commands +- Run isolated code +- Access the internet + +Check docs here. + +Use Sandbox.create to create a new sandbox. + +#### Example + +```ts +import { Sandbox } from '@e2b/code-interpreter' + +const sandbox = await Sandbox.create() +``` + +#### Methods + +### createCodeContext() + +```ts +createCodeContext(opts?: CreateCodeContextOpts): Promise +``` + +Creates a new context to run code in. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `opts`? | `CreateCodeContextOpts` | options for creating the context. | + +###### Returns + +`Promise`\<`Context`\> + +context object. + +### listCodeContexts() + +```ts +listCodeContexts(): Promise +``` + +List all contexts. + +###### Returns + +`Promise`\<`Context`[]\> + +list of contexts. + +### removeCodeContext() + +```ts +removeCodeContext(context: string | Context): Promise +``` + +Removes a context. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `context` | `string` \| `Context` | context to remove. | + +###### Returns + +`Promise`\<`void`\> + +void. + +### restartCodeContext() + +```ts +restartCodeContext(context: string | Context): Promise +``` + +Restart a context. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `context` | `string` \| `Context` | context to restart. | + +###### Returns + +`Promise`\<`void`\> + +void. + +### runCode() + +###### runCode(code, opts) + +```ts +runCode(code: string, opts?: RunCodeOpts & object): Promise +``` + +Run the code as Python. + +Specify the `language` or `context` option to run the code as a different language or in a different `Context`. + +You can reference previously defined variables, imports, and functions in the code. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `code` | `string` | code to execute. | +| `opts`? | `RunCodeOpts` & `object` | options for executing the code. | + +###### Returns + +`Promise`\<`Execution`\> + +`Execution` result object. + +###### runCode(code, opts) + +```ts +runCode(code: string, opts?: RunCodeOpts & object): Promise +``` + +Run the code for the specified language. + +Specify the `language` or `context` option to run the code as a different language or in a different `Context`. +If no language is specified, Python is used. + +You can reference previously defined variables, imports, and functions in the code. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `code` | `string` | code to execute. | +| `opts`? | `RunCodeOpts` & `object` | options for executing the code. | + +###### Returns + +`Promise`\<`Execution`\> + +`Execution` result object. + +###### runCode(code, opts) + +```ts +runCode(code: string, opts?: RunCodeOpts & object): Promise +``` + +Runs the code in the specified context, if not specified, the default context is used. + +Specify the `language` or `context` option to run the code as a different language or in a different `Context`. + +You can reference previously defined variables, imports, and functions in the code. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `code` | `string` | code to execute. | +| `opts`? | `RunCodeOpts` & `object` | options for executing the code | + +###### Returns + +`Promise`\<`Execution`\> + +`Execution` result object + +## Interfaces + +### CreateCodeContextOpts + +Options for creating a code context. + +#### Properties + +### cwd? + +```ts +optional cwd: string; +``` + +Working directory for the context. + +###### Default + +```ts +/home/user +``` + +### language? + +```ts +optional language: string; +``` + +Language for the context. + +###### Default + +```ts +python +``` + +### requestTimeoutMs? + +```ts +optional requestTimeoutMs: number; +``` + +Timeout for the request in **milliseconds**. + +###### Default + +```ts +30_000 // 30 seconds +``` + +*** + +### RunCodeOpts + +Options for running code. + +#### Properties + +### envs? + +```ts +optional envs: Record; +``` + +Custom environment variables for code execution. + +###### Default + +```ts +{} +``` + +### onError()? + +```ts +optional onError: (error: ExecutionError) => any; +``` + +Callback for handling the `ExecutionError` object. + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `error` | `ExecutionError` | + +###### Returns + +`any` + +### onResult()? + +```ts +optional onResult: (data: Result) => any; +``` + +Callback for handling the final execution result. + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `data` | `Result` | + +###### Returns + +`any` + +### onStderr()? + +```ts +optional onStderr: (output: OutputMessage) => any; +``` + +Callback for handling stderr messages. + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `output` | `OutputMessage` | + +###### Returns + +`any` + +### onStdout()? + +```ts +optional onStdout: (output: OutputMessage) => any; +``` + +Callback for handling stdout messages. + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `output` | `OutputMessage` | + +###### Returns + +`any` + +### requestTimeoutMs? + +```ts +optional requestTimeoutMs: number; +``` + +Timeout for the request in **milliseconds**. + +###### Default + +```ts +30_000 // 30 seconds +``` + +### timeoutMs? + +```ts +optional timeoutMs: number; +``` + +Timeout for the code execution in **milliseconds**. + +###### Default + +```ts +60_000 // 60 seconds +``` + +## Type Aliases + +### Context + +```ts +type Context: object; +``` + +Represents a context for code execution. + +#### Type declaration + +| Name | Type | Description | +| ------ | ------ | ------ | +| `cwd` | `string` | The working directory of the context. | +| `id` | `string` | The ID of the context. | +| `language` | `string` | The language of the context. | diff --git a/docs/sdk-reference/code-interpreter-js-sdk/v2.3.3/charts.mdx b/docs/sdk-reference/code-interpreter-js-sdk/v2.3.3/charts.mdx new file mode 100644 index 0000000..d4cf7ad --- /dev/null +++ b/docs/sdk-reference/code-interpreter-js-sdk/v2.3.3/charts.mdx @@ -0,0 +1,245 @@ +--- +sidebarTitle: "Charts" +mode: "center" +--- + +### ChartType + +Chart types + +#### Enumeration Members + +| Enumeration Member | Value | +| ------ | ------ | +| `BAR` | `"bar"` | +| `BOX_AND_WHISKER` | `"box_and_whisker"` | +| `LINE` | `"line"` | +| `PIE` | `"pie"` | +| `SCATTER` | `"scatter"` | +| `SUPERCHART` | `"superchart"` | +| `UNKNOWN` | `"unknown"` | + +*** + +### ScaleType + +Ax scale types + +#### Enumeration Members + +| Enumeration Member | Value | +| ------ | ------ | +| `ASINH` | `"asinh"` | +| `CATEGORICAL` | `"categorical"` | +| `DATETIME` | `"datetime"` | +| `FUNCTION` | `"function"` | +| `FUNCTIONLOG` | `"functionlog"` | +| `LINEAR` | `"linear"` | +| `LOG` | `"log"` | +| `LOGIT` | `"logit"` | +| `SYMLOG` | `"symlog"` | + +## Type Aliases + +### BarChart + +```ts +type BarChart: Chart2D & object; +``` + +#### Type declaration + +| Name | Type | +| ------ | ------ | +| `elements` | `BarData`[] | +| `type` | `ChartType.BAR` | + +*** + +### BarData + +```ts +type BarData: object; +``` + +#### Type declaration + +| Name | Type | +| ------ | ------ | +| `group` | `string` | +| `label` | `string` | +| `value` | `string` | + +*** + +### BoxAndWhiskerChart + +```ts +type BoxAndWhiskerChart: Chart2D & object; +``` + +#### Type declaration + +| Name | Type | +| ------ | ------ | +| `elements` | `BoxAndWhiskerData`[] | +| `type` | `ChartType.BOX_AND_WHISKER` | + +*** + +### BoxAndWhiskerData + +```ts +type BoxAndWhiskerData: object; +``` + +#### Type declaration + +| Name | Type | +| ------ | ------ | +| `first_quartile` | `number` | +| `label` | `string` | +| `max` | `number` | +| `median` | `number` | +| `min` | `number` | +| `outliers` | `number`[] | +| `third_quartile` | `number` | + +*** + +### Chart + +```ts +type Chart: object; +``` + +Represents a chart. + +#### Type declaration + +| Name | Type | +| ------ | ------ | +| `elements` | `any`[] | +| `title` | `string` | +| `type` | `ChartType` | + +*** + +### ChartTypes + +```ts +type ChartTypes: + | LineChart + | ScatterChart + | BarChart + | PieChart + | BoxAndWhiskerChart + | SuperChart; +``` + +*** + +### LineChart + +```ts +type LineChart: PointChart & object; +``` + +#### Type declaration + +| Name | Type | +| ------ | ------ | +| `type` | `ChartType.LINE` | + +*** + +### PieChart + +```ts +type PieChart: Chart & object; +``` + +#### Type declaration + +| Name | Type | +| ------ | ------ | +| `elements` | `PieData`[] | +| `type` | `ChartType.PIE` | + +*** + +### PieData + +```ts +type PieData: object; +``` + +#### Type declaration + +| Name | Type | +| ------ | ------ | +| `angle` | `number` | +| `label` | `string` | +| `radius` | `number` | + +*** + +### PointData + +```ts +type PointData: object; +``` + +#### Type declaration + +| Name | Type | +| ------ | ------ | +| `label` | `string` | +| `points` | [`number` \| `string`, `number` \| `string`][] | + +*** + +### ScatterChart + +```ts +type ScatterChart: PointChart & object; +``` + +#### Type declaration + +| Name | Type | +| ------ | ------ | +| `type` | `ChartType.SCATTER` | + +*** + +### SuperChart + +```ts +type SuperChart: Chart & object; +``` + +#### Type declaration + +| Name | Type | +| ------ | ------ | +| `elements` | `Chart`[] | +| `type` | `ChartType.SUPERCHART` | + +## Functions + +### deserializeChart() + +```ts +function deserializeChart(data: any): Chart +``` + +#### Parameters + +| Parameter | Type | +| ------ | ------ | +| `data` | `any` | + +#### Returns + +`Chart` diff --git a/docs/sdk-reference/code-interpreter-js-sdk/v2.3.3/consts.mdx b/docs/sdk-reference/code-interpreter-js-sdk/v2.3.3/consts.mdx new file mode 100644 index 0000000..07462e7 --- /dev/null +++ b/docs/sdk-reference/code-interpreter-js-sdk/v2.3.3/consts.mdx @@ -0,0 +1,18 @@ +--- +sidebarTitle: "Consts" +mode: "center" +--- + +### DEFAULT\_TIMEOUT\_MS + +```ts +const DEFAULT_TIMEOUT_MS: 60000 = 60_000; +``` + +*** + +### JUPYTER\_PORT + +```ts +const JUPYTER_PORT: 49999 = 49999; +``` diff --git a/docs/sdk-reference/code-interpreter-js-sdk/v2.3.3/messaging.mdx b/docs/sdk-reference/code-interpreter-js-sdk/v2.3.3/messaging.mdx new file mode 100644 index 0000000..ef4f3e7 --- /dev/null +++ b/docs/sdk-reference/code-interpreter-js-sdk/v2.3.3/messaging.mdx @@ -0,0 +1,331 @@ +--- +sidebarTitle: "Messaging" +mode: "center" +--- + +### Execution + +Represents the result of a cell execution. + +#### Constructors + +```ts +new Execution( + results: Result[], + logs: Logs, + error?: ExecutionError, + executionCount?: number): Execution +``` + +###### Parameters + +| Parameter | Type | Default value | Description | +| ------ | ------ | ------ | ------ | +| `results` | `Result`[] | `[]` | List of result of the cell (interactively interpreted last line), display calls (e.g. matplotlib plots). | +| `logs` | `Logs` | `...` | Logs printed to stdout and stderr during execution. | +| `error`? | `ExecutionError` | `undefined` | An Error object if an error occurred, null otherwise. | +| `executionCount`? | `number` | `undefined` | Execution count of the cell. | + +###### Returns + +`Execution` + +#### Properties + +| Property | Modifier | Type | Default value | Description | +| ------ | ------ | ------ | ------ | ------ | +| `error?` | `public` | `ExecutionError` | `undefined` | An Error object if an error occurred, null otherwise. | +| `executionCount?` | `public` | `number` | `undefined` | Execution count of the cell. | +| `logs` | `public` | `Logs` | `undefined` | Logs printed to stdout and stderr during execution. | +| `results` | `public` | `Result`[] | `[]` | List of result of the cell (interactively interpreted last line), display calls (e.g. matplotlib plots). | + +#### Accessors + +### text + +```ts +get text(): undefined | string +``` + +Returns the text representation of the main result of the cell. + +###### Returns + +`undefined` \| `string` + +#### Methods + +### toJSON() + +```ts +toJSON(): object +``` + +Returns the serializable representation of the execution result. + +###### Returns + +`object` + +| Name | Type | +| ------ | ------ | +| `error` | `undefined` \| `ExecutionError` | +| `logs` | `Logs` | +| `results` | `Result`[] | + +*** + +### ExecutionError + +Represents an error that occurred during the execution of a cell. +The error contains the name of the error, the value of the error, and the traceback. + +#### Constructors + +```ts +new ExecutionError( + name: string, + value: string, + traceback: string): ExecutionError +``` + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `name` | `string` | Name of the error. | +| `value` | `string` | Value of the error. | +| `traceback` | `string` | The raw traceback of the error. | + +###### Returns + +`ExecutionError` + +#### Properties + +| Property | Modifier | Type | Description | +| ------ | ------ | ------ | ------ | +| `name` | `public` | `string` | Name of the error. | +| `traceback` | `public` | `string` | The raw traceback of the error. | +| `value` | `public` | `string` | Value of the error. | + +*** + +### OutputMessage + +Represents an output message from the sandbox code execution. + +#### Constructors + +```ts +new OutputMessage( + line: string, + timestamp: number, + error: boolean): OutputMessage +``` + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `line` | `string` | The output line. | +| `timestamp` | `number` | Unix epoch in nanoseconds. | +| `error` | `boolean` | Whether the output is an error. | + +###### Returns + +`OutputMessage` + +#### Properties + +| Property | Modifier | Type | Description | +| ------ | ------ | ------ | ------ | +| `error` | `readonly` | `boolean` | Whether the output is an error. | +| `line` | `readonly` | `string` | The output line. | +| `timestamp` | `readonly` | `number` | Unix epoch in nanoseconds. | + +#### Methods + +### toString() + +```ts +toString(): string +``` + +###### Returns + +`string` + +*** + +### Result + +Represents the data to be displayed as a result of executing a cell in a Jupyter notebook. +The result is similar to the structure returned by ipython kernel: https://ipython.readthedocs.io/en/stable/development/execution.html#execution-semantics + +The result can contain multiple types of data, such as text, images, plots, etc. Each type of data is represented +as a string, and the result can contain multiple types of data. The display calls don't have to have text representation, +for the actual result the representation is always present for the result, the other representations are always optional. + +#### Constructors + +```ts +new Result(rawData: RawData, isMainResult: boolean): Result +``` + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `rawData` | `RawData` | +| `isMainResult` | `boolean` | + +###### Returns + +`Result` + +#### Properties + +| Property | Modifier | Type | Description | +| ------ | ------ | ------ | ------ | +| `chart?` | `readonly` | `ChartTypes` | Contains the chart data. | +| `data?` | `readonly` | `Record`\<`string`, `unknown`\> | Contains the data from DataFrame. | +| `extra?` | `readonly` | `any` | Extra data that can be included. Not part of the standard types. | +| `html?` | `readonly` | `string` | HTML representation of the data. | +| `isMainResult` | `readonly` | `boolean` | - | +| `javascript?` | `readonly` | `string` | JavaScript representation of the data. | +| `jpeg?` | `readonly` | `string` | JPEG representation of the data. | +| `json?` | `readonly` | `string` | JSON representation of the data. | +| `latex?` | `readonly` | `string` | LaTeX representation of the data. | +| `markdown?` | `readonly` | `string` | Markdown representation of the data. | +| `pdf?` | `readonly` | `string` | PDF representation of the data. | +| `png?` | `readonly` | `string` | PNG representation of the data. | +| `raw` | `readonly` | `RawData` | - | +| `svg?` | `readonly` | `string` | SVG representation of the data. | +| `text?` | `readonly` | `string` | Text representation of the result. | + +#### Methods + +### formats() + +```ts +formats(): string[] +``` + +Returns all the formats available for the result. + +###### Returns + +`string`[] + +Array of strings representing the formats available for the result. + +### toJSON() + +```ts +toJSON(): object +``` + +Returns the serializable representation of the result. + +###### Returns + +`object` + +| Name | Type | +| ------ | ------ | +| `extra`? | `any` | +| `html` | `undefined` \| `string` | +| `javascript` | `undefined` \| `string` | +| `jpeg` | `undefined` \| `string` | +| `json` | `undefined` \| `string` | +| `latex` | `undefined` \| `string` | +| `markdown` | `undefined` \| `string` | +| `pdf` | `undefined` \| `string` | +| `png` | `undefined` \| `string` | +| `svg` | `undefined` \| `string` | +| `text` | `undefined` \| `string` | + +## Type Aliases + +### Logs + +```ts +type Logs: object; +``` + +Data printed to stdout and stderr during execution, usually by print statements, logs, warnings, subprocesses, etc. + +#### Type declaration + +| Name | Type | Description | +| ------ | ------ | ------ | +| `stderr` | `string`[] | List of strings printed to stderr by prints, subprocesses, etc. | +| `stdout` | `string`[] | List of strings printed to stdout by prints, subprocesses, etc. | + +*** + +### MIMEType + +```ts +type MIMEType: string; +``` + +Represents a MIME type. + +*** + +### RawData + +```ts +type RawData: object & E2BData; +``` + +Dictionary that maps MIME types to their corresponding representations of the data. + +## Functions + +### extractError() + +```ts +function extractError(res: Response): Promise +``` + +#### Parameters + +| Parameter | Type | +| ------ | ------ | +| `res` | `Response` | + +#### Returns + +`Promise`\<`undefined` \| `SandboxError`\> + +*** + +### parseOutput() + +```ts +function parseOutput( + execution: Execution, + line: string, + onStdout?: (output: OutputMessage) => any, + onStderr?: (output: OutputMessage) => any, + onResult?: (data: Result) => any, +onError?: (error: ExecutionError) => any): Promise +``` + +#### Parameters + +| Parameter | Type | +| ------ | ------ | +| `execution` | `Execution` | +| `line` | `string` | +| `onStdout`? | (`output`: `OutputMessage`) => `any` | +| `onStderr`? | (`output`: `OutputMessage`) => `any` | +| `onResult`? | (`data`: `Result`) => `any` | +| `onError`? | (`error`: `ExecutionError`) => `any` | + +#### Returns + +`Promise`\<`void`\> diff --git a/docs/sdk-reference/code-interpreter-js-sdk/v2.3.3/sandbox.mdx b/docs/sdk-reference/code-interpreter-js-sdk/v2.3.3/sandbox.mdx new file mode 100644 index 0000000..fb801ca --- /dev/null +++ b/docs/sdk-reference/code-interpreter-js-sdk/v2.3.3/sandbox.mdx @@ -0,0 +1,371 @@ +--- +sidebarTitle: "Sandbox" +mode: "center" +--- + +### Sandbox + +E2B cloud sandbox is a secure and isolated cloud environment. + +The sandbox allows you to: +- Access Linux OS +- Create, list, and delete files and directories +- Run commands +- Run isolated code +- Access the internet + +Check docs here. + +Use Sandbox.create to create a new sandbox. + +#### Example + +```ts +import { Sandbox } from '@e2b/code-interpreter' + +const sandbox = await Sandbox.create() +``` + +#### Methods + +### createCodeContext() + +```ts +createCodeContext(opts?: CreateCodeContextOpts): Promise +``` + +Creates a new context to run code in. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `opts`? | `CreateCodeContextOpts` | options for creating the context. | + +###### Returns + +`Promise`\<`Context`\> + +context object. + +### listCodeContexts() + +```ts +listCodeContexts(): Promise +``` + +List all contexts. + +###### Returns + +`Promise`\<`Context`[]\> + +list of contexts. + +### removeCodeContext() + +```ts +removeCodeContext(context: string | Context): Promise +``` + +Removes a context. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `context` | `string` \| `Context` | context to remove. | + +###### Returns + +`Promise`\<`void`\> + +void. + +### restartCodeContext() + +```ts +restartCodeContext(context: string | Context): Promise +``` + +Restart a context. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `context` | `string` \| `Context` | context to restart. | + +###### Returns + +`Promise`\<`void`\> + +void. + +### runCode() + +###### runCode(code, opts) + +```ts +runCode(code: string, opts?: RunCodeOpts & object): Promise +``` + +Run the code as Python. + +Specify the `language` or `context` option to run the code as a different language or in a different `Context`. + +You can reference previously defined variables, imports, and functions in the code. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `code` | `string` | code to execute. | +| `opts`? | `RunCodeOpts` & `object` | options for executing the code. | + +###### Returns + +`Promise`\<`Execution`\> + +`Execution` result object. + +###### runCode(code, opts) + +```ts +runCode(code: string, opts?: RunCodeOpts & object): Promise +``` + +Run the code for the specified language. + +Specify the `language` or `context` option to run the code as a different language or in a different `Context`. +If no language is specified, Python is used. + +You can reference previously defined variables, imports, and functions in the code. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `code` | `string` | code to execute. | +| `opts`? | `RunCodeOpts` & `object` | options for executing the code. | + +###### Returns + +`Promise`\<`Execution`\> + +`Execution` result object. + +###### runCode(code, opts) + +```ts +runCode(code: string, opts?: RunCodeOpts & object): Promise +``` + +Runs the code in the specified context, if not specified, the default context is used. + +Specify the `language` or `context` option to run the code as a different language or in a different `Context`. + +You can reference previously defined variables, imports, and functions in the code. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `code` | `string` | code to execute. | +| `opts`? | `RunCodeOpts` & `object` | options for executing the code | + +###### Returns + +`Promise`\<`Execution`\> + +`Execution` result object + +## Interfaces + +### CreateCodeContextOpts + +Options for creating a code context. + +#### Properties + +### cwd? + +```ts +optional cwd: string; +``` + +Working directory for the context. + +###### Default + +```ts +/home/user +``` + +### language? + +```ts +optional language: string; +``` + +Language for the context. + +###### Default + +```ts +python +``` + +### requestTimeoutMs? + +```ts +optional requestTimeoutMs: number; +``` + +Timeout for the request in **milliseconds**. + +###### Default + +```ts +30_000 // 30 seconds +``` + +*** + +### RunCodeOpts + +Options for running code. + +#### Properties + +### envs? + +```ts +optional envs: Record; +``` + +Custom environment variables for code execution. + +###### Default + +```ts +{} +``` + +### onError()? + +```ts +optional onError: (error: ExecutionError) => any; +``` + +Callback for handling the `ExecutionError` object. + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `error` | `ExecutionError` | + +###### Returns + +`any` + +### onResult()? + +```ts +optional onResult: (data: Result) => any; +``` + +Callback for handling the final execution result. + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `data` | `Result` | + +###### Returns + +`any` + +### onStderr()? + +```ts +optional onStderr: (output: OutputMessage) => any; +``` + +Callback for handling stderr messages. + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `output` | `OutputMessage` | + +###### Returns + +`any` + +### onStdout()? + +```ts +optional onStdout: (output: OutputMessage) => any; +``` + +Callback for handling stdout messages. + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `output` | `OutputMessage` | + +###### Returns + +`any` + +### requestTimeoutMs? + +```ts +optional requestTimeoutMs: number; +``` + +Timeout for the request in **milliseconds**. + +###### Default + +```ts +30_000 // 30 seconds +``` + +### timeoutMs? + +```ts +optional timeoutMs: number; +``` + +Timeout for the code execution in **milliseconds**. + +###### Default + +```ts +60_000 // 60 seconds +``` + +## Type Aliases + +### Context + +```ts +type Context: object; +``` + +Represents a context for code execution. + +#### Type declaration + +| Name | Type | Description | +| ------ | ------ | ------ | +| `cwd` | `string` | The working directory of the context. | +| `id` | `string` | The ID of the context. | +| `language` | `string` | The language of the context. | diff --git a/docs/sdk-reference/code-interpreter-python-sdk/1.0.1/code_interpreter.mdx b/docs/sdk-reference/code-interpreter-python-sdk/1.0.1/code_interpreter.mdx new file mode 100644 index 0000000..0d3e5ea --- /dev/null +++ b/docs/sdk-reference/code-interpreter-python-sdk/1.0.1/code_interpreter.mdx @@ -0,0 +1,786 @@ +--- +sidebarTitle: "Code Interpreter" +mode: "center" +--- + + + + + + + + + +## AsyncSandbox + +```python +class AsyncSandbox(BaseAsyncSandbox) +``` + +E2B cloud sandbox is a secure and isolated cloud environment. + +The sandbox allows you to: +- Access Linux OS +- Create, list, and delete files and directories +- Run commands +- Run isolated code +- Access the internet + +Check docs [here](https://e2b.dev/docs). + +Use the `AsyncSandbox.create()` to create a new sandbox. + +**Example**: + +```python +from e2b_code_interpreter import AsyncSandbox +sandbox = await AsyncSandbox.create() +``` + + + +### run\_code + +```python +@overload +async def run_code(code: str, + language: Union[Literal["python"], None] = None, + on_stdout: Optional[OutputHandler[OutputMessage]] = None, + on_stderr: Optional[OutputHandler[OutputMessage]] = None, + on_result: Optional[OutputHandler[Result]] = None, + on_error: Optional[OutputHandler[ExecutionError]] = None, + envs: Optional[Dict[str, str]] = None, + timeout: Optional[float] = None, + request_timeout: Optional[float] = None) -> Execution +``` + +Runs the code as Python. + +Specify the `language` or `context` option to run the code as a different language or in a different `Context`. + +You can reference previously defined variables, imports, and functions in the code. + +**Arguments**: + +- `code`: Code to execute +- `language`: Language to use for code execution. If not defined, the default Python context is used. +- `on_stdout`: Callback for stdout messages +- `on_stderr`: Callback for stderr messages +- `on_result`: Callback for the `Result` object +- `on_error`: Callback for the `ExecutionError` object +- `envs`: Custom environment variables +- `timeout`: Timeout for the code execution in **seconds** +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`Execution` result object + + + +### run\_code + +```python +@overload +async def run_code(code: str, + language: Optional[str] = None, + on_stdout: Optional[OutputHandler[OutputMessage]] = None, + on_stderr: Optional[OutputHandler[OutputMessage]] = None, + on_result: Optional[OutputHandler[Result]] = None, + on_error: Optional[OutputHandler[ExecutionError]] = None, + envs: Optional[Dict[str, str]] = None, + timeout: Optional[float] = None, + request_timeout: Optional[float] = None) -> Execution +``` + +Runs the code for the specified language. + +Specify the `language` or `context` option to run the code as a different language or in a different `Context`. +If no language is specified, Python is used. + +You can reference previously defined variables, imports, and functions in the code. + +**Arguments**: + +- `code`: Code to execute +- `language`: Language to use for code execution. If not defined, the default Python context is used. +- `on_stdout`: Callback for stdout messages +- `on_stderr`: Callback for stderr messages +- `on_result`: Callback for the `Result` object +- `on_error`: Callback for the `ExecutionError` object +- `envs`: Custom environment variables +- `timeout`: Timeout for the code execution in **seconds** +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`Execution` result object + + + +### run\_code + +```python +@overload +async def run_code(code: str, + context: Optional[Context] = None, + on_stdout: Optional[OutputHandler[OutputMessage]] = None, + on_stderr: Optional[OutputHandler[OutputMessage]] = None, + on_result: Optional[OutputHandler[Result]] = None, + on_error: Optional[OutputHandler[ExecutionError]] = None, + envs: Optional[Dict[str, str]] = None, + timeout: Optional[float] = None, + request_timeout: Optional[float] = None) -> Execution +``` + +Runs the code in the specified context, if not specified, the default context is used. + +Specify the `language` or `context` option to run the code as a different language or in a different `Context`. + +You can reference previously defined variables, imports, and functions in the code. + +**Arguments**: + +- `code`: Code to execute +- `context`: Concrete context to run the code in. If not specified, the default context for the language is used. It's mutually exclusive with the language. +- `on_stdout`: Callback for stdout messages +- `on_stderr`: Callback for stderr messages +- `on_result`: Callback for the `Result` object +- `on_error`: Callback for the `ExecutionError` object +- `envs`: Custom environment variables +- `timeout`: Timeout for the code execution in **seconds** +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`Execution` result object + + + +### create\_code\_context + +```python +async def create_code_context( + cwd: Optional[str] = None, + language: Optional[str] = None, + request_timeout: Optional[float] = None) -> Context +``` + +Creates a new context to run code in. + +**Arguments**: + +- `cwd`: Set the current working directory for the context, defaults to `/home/user` +- `language`: Language of the context. If not specified, defaults to Python +- `request_timeout`: Timeout for the request in **milliseconds** + +**Returns**: + +Context object + + + + + + +## OutputMessage + +```python +@dataclass +class OutputMessage() +``` + +Represents an output message from the sandbox code execution. + + + +### line + +The output line. + + + +### timestamp + +Unix epoch in nanoseconds + + + +### error + +Whether the output is an error. + + + +## ExecutionError + +```python +@dataclass +class ExecutionError() +``` + +Represents an error that occurred during the execution of a cell. +The error contains the name of the error, the value of the error, and the traceback. + + + +### name + +Name of the error. + + + +### value + +Value of the error. + + + +### traceback + +The raw traceback of the error. + + + +### to\_json + +```python +def to_json() -> str +``` + +Returns the JSON representation of the Error object. + + + +## MIMEType + +```python +class MIMEType(str) +``` + +Represents a MIME type. + + + +## Result + +```python +@dataclass +class Result() +``` + +Represents the data to be displayed as a result of executing a cell in a Jupyter notebook. +The result is similar to the structure returned by ipython kernel: https://ipython.readthedocs.io/en/stable/development/execution.html#execution-semantics + +The result can contain multiple types of data, such as text, images, plots, etc. Each type of data is represented +as a string, and the result can contain multiple types of data. The display calls don't have to have text representation, +for the actual result the representation is always present for the result, the other representations are always optional. + + + +### is\_main\_result + +Whether this data is the result of the cell. Data can be produced by display calls of which can be multiple in a cell. + + + +### extra + +Extra data that can be included. Not part of the standard types. + + + +### formats + +```python +def formats() -> Iterable[str] +``` + +Returns all available formats of the result. + +**Returns**: + +All available formats of the result in MIME types. + + + +### \_\_str\_\_ + +```python +def __str__() -> Optional[str] +``` + +Returns the text representation of the data. + +**Returns**: + +The text representation of the data. + + + +### \_repr\_html\_ + +```python +def _repr_html_() -> Optional[str] +``` + +Returns the HTML representation of the data. + +**Returns**: + +The HTML representation of the data. + + + +### \_repr\_markdown\_ + +```python +def _repr_markdown_() -> Optional[str] +``` + +Returns the Markdown representation of the data. + +**Returns**: + +The Markdown representation of the data. + + + +### \_repr\_svg\_ + +```python +def _repr_svg_() -> Optional[str] +``` + +Returns the SVG representation of the data. + +**Returns**: + +The SVG representation of the data. + + + +### \_repr\_png\_ + +```python +def _repr_png_() -> Optional[str] +``` + +Returns the base64 representation of the PNG data. + +**Returns**: + +The base64 representation of the PNG data. + + + +### \_repr\_jpeg\_ + +```python +def _repr_jpeg_() -> Optional[str] +``` + +Returns the base64 representation of the JPEG data. + +**Returns**: + +The base64 representation of the JPEG data. + + + +### \_repr\_pdf\_ + +```python +def _repr_pdf_() -> Optional[str] +``` + +Returns the PDF representation of the data. + +**Returns**: + +The PDF representation of the data. + + + +### \_repr\_latex\_ + +```python +def _repr_latex_() -> Optional[str] +``` + +Returns the LaTeX representation of the data. + +**Returns**: + +The LaTeX representation of the data. + + + +### \_repr\_json\_ + +```python +def _repr_json_() -> Optional[dict] +``` + +Returns the JSON representation of the data. + +**Returns**: + +The JSON representation of the data. + + + +### \_repr\_javascript\_ + +```python +def _repr_javascript_() -> Optional[str] +``` + +Returns the JavaScript representation of the data. + +**Returns**: + +The JavaScript representation of the data. + + + +## Logs + +```python +@dataclass(repr=False) +class Logs() +``` + +Data printed to stdout and stderr during execution, usually by print statements, logs, warnings, subprocesses, etc. + + + +### stdout + +List of strings printed to stdout by prints, subprocesses, etc. + + + +### stderr + +List of strings printed to stderr by prints, subprocesses, etc. + + + +### to\_json + +```python +def to_json() -> str +``` + +Returns the JSON representation of the Logs object. + + + +### serialize\_results + +```python +def serialize_results(results: List[Result]) -> List[Dict[str, str]] +``` + +Serializes the results to JSON. + + + +## Execution + +```python +@dataclass(repr=False) +class Execution() +``` + +Represents the result of a cell execution. + + + +### results + +List of the result of the cell (interactively interpreted last line), display calls (e.g. matplotlib plots). + + + +### logs + +Logs printed to stdout and stderr during execution. + + + +### error + +Error object if an error occurred, None otherwise. + + + +### execution\_count + +Execution count of the cell. + + + +### text + +```python +@property +def text() -> Optional[str] +``` + +Returns the text representation of the result. + +**Returns**: + +The text representation of the result. + + + +### to\_json + +```python +def to_json() -> str +``` + +Returns the JSON representation of the Execution object. + + + +## Context + +```python +@dataclass +class Context() +``` + +Represents a context for code execution. + + + +### id + +The ID of the context. + + + +### language + +The language of the context. + + + +### cwd + +The working directory of the context. + + + + + + +## ChartType + +```python +class ChartType(str, enum.Enum) +``` + +Chart types + + + +## ScaleType + +```python +class ScaleType(str, enum.Enum) +``` + +Ax scale types + + + +## Chart + +```python +class Chart() +``` + +Extracted data from a chart. It's useful for building an interactive charts or custom visualizations. + + + + + + +## Sandbox + +```python +class Sandbox(BaseSandbox) +``` + +E2B cloud sandbox is a secure and isolated cloud environment. + +The sandbox allows you to: +- Access Linux OS +- Create, list, and delete files and directories +- Run commands +- Run isolated code +- Access the internet + +Check docs [here](https://e2b.dev/docs). + +Use the `Sandbox()` to create a new sandbox. + +**Example**: + +```python +from e2b_code_interpreter import Sandbox + +sandbox = Sandbox() +``` + + + +### run\_code + +```python +@overload +def run_code(code: str, + language: Union[Literal["python"], None] = None, + on_stdout: Optional[OutputHandler[OutputMessage]] = None, + on_stderr: Optional[OutputHandler[OutputMessage]] = None, + on_result: Optional[OutputHandler[Result]] = None, + on_error: Optional[OutputHandler[ExecutionError]] = None, + envs: Optional[Dict[str, str]] = None, + timeout: Optional[float] = None, + request_timeout: Optional[float] = None) -> Execution +``` + +Runs the code as Python. + +Specify the `language` or `context` option to run the code as a different language or in a different `Context`. + +You can reference previously defined variables, imports, and functions in the code. + +**Arguments**: + +- `code`: Code to execute +- `language`: Language to use for code execution. If not defined, the default Python context is used. +- `on_stdout`: Callback for stdout messages +- `on_stderr`: Callback for stderr messages +- `on_result`: Callback for the `Result` object +- `on_error`: Callback for the `ExecutionError` object +- `envs`: Custom environment variables +- `timeout`: Timeout for the code execution in **seconds** +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`Execution` result object + + + +### run\_code + +```python +@overload +def run_code(code: str, + language: Optional[str] = None, + on_stdout: Optional[OutputHandler[OutputMessage]] = None, + on_stderr: Optional[OutputHandler[OutputMessage]] = None, + on_result: Optional[OutputHandler[Result]] = None, + on_error: Optional[OutputHandler[ExecutionError]] = None, + envs: Optional[Dict[str, str]] = None, + timeout: Optional[float] = None, + request_timeout: Optional[float] = None) -> Execution +``` + +Runs the code for the specified language. + +Specify the `language` or `context` option to run the code as a different language or in a different `Context`. +If no language is specified, Python is used. + +You can reference previously defined variables, imports, and functions in the code. + +**Arguments**: + +- `code`: Code to execute +- `language`: Language to use for code execution. If not defined, the default Python context is used. +- `on_stdout`: Callback for stdout messages +- `on_stderr`: Callback for stderr messages +- `on_result`: Callback for the `Result` object +- `on_error`: Callback for the `ExecutionError` object +- `envs`: Custom environment variables +- `timeout`: Timeout for the code execution in **seconds** +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`Execution` result object + + + +### run\_code + +```python +@overload +def run_code(code: str, + context: Optional[Context] = None, + on_stdout: Optional[OutputHandler[OutputMessage]] = None, + on_stderr: Optional[OutputHandler[OutputMessage]] = None, + on_result: Optional[OutputHandler[Result]] = None, + on_error: Optional[OutputHandler[ExecutionError]] = None, + envs: Optional[Dict[str, str]] = None, + timeout: Optional[float] = None, + request_timeout: Optional[float] = None) -> Execution +``` + +Runs the code in the specified context, if not specified, the default context is used. + +Specify the `language` or `context` option to run the code as a different language or in a different `Context`. + +You can reference previously defined variables, imports, and functions in the code. + +**Arguments**: + +- `code`: Code to execute +- `context`: Concrete context to run the code in. If not specified, the default context for the language is used. It's mutually exclusive with the language. +- `on_stdout`: Callback for stdout messages +- `on_stderr`: Callback for stderr messages +- `on_result`: Callback for the `Result` object +- `on_error`: Callback for the `ExecutionError` object +- `envs`: Custom environment variables +- `timeout`: Timeout for the code execution in **seconds** +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`Execution` result object + + + +### create\_code\_context + +```python +def create_code_context(cwd: Optional[str] = None, + language: Optional[str] = None, + request_timeout: Optional[float] = None) -> Context +``` + +Creates a new context to run code in. + +**Arguments**: + +- `cwd`: Set the current working directory for the context, defaults to `/home/user` +- `language`: Language of the context. If not specified, defaults to Python +- `request_timeout`: Timeout for the request in **milliseconds** + +**Returns**: + +Context object + + + + + + diff --git a/docs/sdk-reference/code-interpreter-python-sdk/1.0.4/code_interpreter.mdx b/docs/sdk-reference/code-interpreter-python-sdk/1.0.4/code_interpreter.mdx new file mode 100644 index 0000000..0d3e5ea --- /dev/null +++ b/docs/sdk-reference/code-interpreter-python-sdk/1.0.4/code_interpreter.mdx @@ -0,0 +1,786 @@ +--- +sidebarTitle: "Code Interpreter" +mode: "center" +--- + + + + + + + + + +## AsyncSandbox + +```python +class AsyncSandbox(BaseAsyncSandbox) +``` + +E2B cloud sandbox is a secure and isolated cloud environment. + +The sandbox allows you to: +- Access Linux OS +- Create, list, and delete files and directories +- Run commands +- Run isolated code +- Access the internet + +Check docs [here](https://e2b.dev/docs). + +Use the `AsyncSandbox.create()` to create a new sandbox. + +**Example**: + +```python +from e2b_code_interpreter import AsyncSandbox +sandbox = await AsyncSandbox.create() +``` + + + +### run\_code + +```python +@overload +async def run_code(code: str, + language: Union[Literal["python"], None] = None, + on_stdout: Optional[OutputHandler[OutputMessage]] = None, + on_stderr: Optional[OutputHandler[OutputMessage]] = None, + on_result: Optional[OutputHandler[Result]] = None, + on_error: Optional[OutputHandler[ExecutionError]] = None, + envs: Optional[Dict[str, str]] = None, + timeout: Optional[float] = None, + request_timeout: Optional[float] = None) -> Execution +``` + +Runs the code as Python. + +Specify the `language` or `context` option to run the code as a different language or in a different `Context`. + +You can reference previously defined variables, imports, and functions in the code. + +**Arguments**: + +- `code`: Code to execute +- `language`: Language to use for code execution. If not defined, the default Python context is used. +- `on_stdout`: Callback for stdout messages +- `on_stderr`: Callback for stderr messages +- `on_result`: Callback for the `Result` object +- `on_error`: Callback for the `ExecutionError` object +- `envs`: Custom environment variables +- `timeout`: Timeout for the code execution in **seconds** +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`Execution` result object + + + +### run\_code + +```python +@overload +async def run_code(code: str, + language: Optional[str] = None, + on_stdout: Optional[OutputHandler[OutputMessage]] = None, + on_stderr: Optional[OutputHandler[OutputMessage]] = None, + on_result: Optional[OutputHandler[Result]] = None, + on_error: Optional[OutputHandler[ExecutionError]] = None, + envs: Optional[Dict[str, str]] = None, + timeout: Optional[float] = None, + request_timeout: Optional[float] = None) -> Execution +``` + +Runs the code for the specified language. + +Specify the `language` or `context` option to run the code as a different language or in a different `Context`. +If no language is specified, Python is used. + +You can reference previously defined variables, imports, and functions in the code. + +**Arguments**: + +- `code`: Code to execute +- `language`: Language to use for code execution. If not defined, the default Python context is used. +- `on_stdout`: Callback for stdout messages +- `on_stderr`: Callback for stderr messages +- `on_result`: Callback for the `Result` object +- `on_error`: Callback for the `ExecutionError` object +- `envs`: Custom environment variables +- `timeout`: Timeout for the code execution in **seconds** +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`Execution` result object + + + +### run\_code + +```python +@overload +async def run_code(code: str, + context: Optional[Context] = None, + on_stdout: Optional[OutputHandler[OutputMessage]] = None, + on_stderr: Optional[OutputHandler[OutputMessage]] = None, + on_result: Optional[OutputHandler[Result]] = None, + on_error: Optional[OutputHandler[ExecutionError]] = None, + envs: Optional[Dict[str, str]] = None, + timeout: Optional[float] = None, + request_timeout: Optional[float] = None) -> Execution +``` + +Runs the code in the specified context, if not specified, the default context is used. + +Specify the `language` or `context` option to run the code as a different language or in a different `Context`. + +You can reference previously defined variables, imports, and functions in the code. + +**Arguments**: + +- `code`: Code to execute +- `context`: Concrete context to run the code in. If not specified, the default context for the language is used. It's mutually exclusive with the language. +- `on_stdout`: Callback for stdout messages +- `on_stderr`: Callback for stderr messages +- `on_result`: Callback for the `Result` object +- `on_error`: Callback for the `ExecutionError` object +- `envs`: Custom environment variables +- `timeout`: Timeout for the code execution in **seconds** +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`Execution` result object + + + +### create\_code\_context + +```python +async def create_code_context( + cwd: Optional[str] = None, + language: Optional[str] = None, + request_timeout: Optional[float] = None) -> Context +``` + +Creates a new context to run code in. + +**Arguments**: + +- `cwd`: Set the current working directory for the context, defaults to `/home/user` +- `language`: Language of the context. If not specified, defaults to Python +- `request_timeout`: Timeout for the request in **milliseconds** + +**Returns**: + +Context object + + + + + + +## OutputMessage + +```python +@dataclass +class OutputMessage() +``` + +Represents an output message from the sandbox code execution. + + + +### line + +The output line. + + + +### timestamp + +Unix epoch in nanoseconds + + + +### error + +Whether the output is an error. + + + +## ExecutionError + +```python +@dataclass +class ExecutionError() +``` + +Represents an error that occurred during the execution of a cell. +The error contains the name of the error, the value of the error, and the traceback. + + + +### name + +Name of the error. + + + +### value + +Value of the error. + + + +### traceback + +The raw traceback of the error. + + + +### to\_json + +```python +def to_json() -> str +``` + +Returns the JSON representation of the Error object. + + + +## MIMEType + +```python +class MIMEType(str) +``` + +Represents a MIME type. + + + +## Result + +```python +@dataclass +class Result() +``` + +Represents the data to be displayed as a result of executing a cell in a Jupyter notebook. +The result is similar to the structure returned by ipython kernel: https://ipython.readthedocs.io/en/stable/development/execution.html#execution-semantics + +The result can contain multiple types of data, such as text, images, plots, etc. Each type of data is represented +as a string, and the result can contain multiple types of data. The display calls don't have to have text representation, +for the actual result the representation is always present for the result, the other representations are always optional. + + + +### is\_main\_result + +Whether this data is the result of the cell. Data can be produced by display calls of which can be multiple in a cell. + + + +### extra + +Extra data that can be included. Not part of the standard types. + + + +### formats + +```python +def formats() -> Iterable[str] +``` + +Returns all available formats of the result. + +**Returns**: + +All available formats of the result in MIME types. + + + +### \_\_str\_\_ + +```python +def __str__() -> Optional[str] +``` + +Returns the text representation of the data. + +**Returns**: + +The text representation of the data. + + + +### \_repr\_html\_ + +```python +def _repr_html_() -> Optional[str] +``` + +Returns the HTML representation of the data. + +**Returns**: + +The HTML representation of the data. + + + +### \_repr\_markdown\_ + +```python +def _repr_markdown_() -> Optional[str] +``` + +Returns the Markdown representation of the data. + +**Returns**: + +The Markdown representation of the data. + + + +### \_repr\_svg\_ + +```python +def _repr_svg_() -> Optional[str] +``` + +Returns the SVG representation of the data. + +**Returns**: + +The SVG representation of the data. + + + +### \_repr\_png\_ + +```python +def _repr_png_() -> Optional[str] +``` + +Returns the base64 representation of the PNG data. + +**Returns**: + +The base64 representation of the PNG data. + + + +### \_repr\_jpeg\_ + +```python +def _repr_jpeg_() -> Optional[str] +``` + +Returns the base64 representation of the JPEG data. + +**Returns**: + +The base64 representation of the JPEG data. + + + +### \_repr\_pdf\_ + +```python +def _repr_pdf_() -> Optional[str] +``` + +Returns the PDF representation of the data. + +**Returns**: + +The PDF representation of the data. + + + +### \_repr\_latex\_ + +```python +def _repr_latex_() -> Optional[str] +``` + +Returns the LaTeX representation of the data. + +**Returns**: + +The LaTeX representation of the data. + + + +### \_repr\_json\_ + +```python +def _repr_json_() -> Optional[dict] +``` + +Returns the JSON representation of the data. + +**Returns**: + +The JSON representation of the data. + + + +### \_repr\_javascript\_ + +```python +def _repr_javascript_() -> Optional[str] +``` + +Returns the JavaScript representation of the data. + +**Returns**: + +The JavaScript representation of the data. + + + +## Logs + +```python +@dataclass(repr=False) +class Logs() +``` + +Data printed to stdout and stderr during execution, usually by print statements, logs, warnings, subprocesses, etc. + + + +### stdout + +List of strings printed to stdout by prints, subprocesses, etc. + + + +### stderr + +List of strings printed to stderr by prints, subprocesses, etc. + + + +### to\_json + +```python +def to_json() -> str +``` + +Returns the JSON representation of the Logs object. + + + +### serialize\_results + +```python +def serialize_results(results: List[Result]) -> List[Dict[str, str]] +``` + +Serializes the results to JSON. + + + +## Execution + +```python +@dataclass(repr=False) +class Execution() +``` + +Represents the result of a cell execution. + + + +### results + +List of the result of the cell (interactively interpreted last line), display calls (e.g. matplotlib plots). + + + +### logs + +Logs printed to stdout and stderr during execution. + + + +### error + +Error object if an error occurred, None otherwise. + + + +### execution\_count + +Execution count of the cell. + + + +### text + +```python +@property +def text() -> Optional[str] +``` + +Returns the text representation of the result. + +**Returns**: + +The text representation of the result. + + + +### to\_json + +```python +def to_json() -> str +``` + +Returns the JSON representation of the Execution object. + + + +## Context + +```python +@dataclass +class Context() +``` + +Represents a context for code execution. + + + +### id + +The ID of the context. + + + +### language + +The language of the context. + + + +### cwd + +The working directory of the context. + + + + + + +## ChartType + +```python +class ChartType(str, enum.Enum) +``` + +Chart types + + + +## ScaleType + +```python +class ScaleType(str, enum.Enum) +``` + +Ax scale types + + + +## Chart + +```python +class Chart() +``` + +Extracted data from a chart. It's useful for building an interactive charts or custom visualizations. + + + + + + +## Sandbox + +```python +class Sandbox(BaseSandbox) +``` + +E2B cloud sandbox is a secure and isolated cloud environment. + +The sandbox allows you to: +- Access Linux OS +- Create, list, and delete files and directories +- Run commands +- Run isolated code +- Access the internet + +Check docs [here](https://e2b.dev/docs). + +Use the `Sandbox()` to create a new sandbox. + +**Example**: + +```python +from e2b_code_interpreter import Sandbox + +sandbox = Sandbox() +``` + + + +### run\_code + +```python +@overload +def run_code(code: str, + language: Union[Literal["python"], None] = None, + on_stdout: Optional[OutputHandler[OutputMessage]] = None, + on_stderr: Optional[OutputHandler[OutputMessage]] = None, + on_result: Optional[OutputHandler[Result]] = None, + on_error: Optional[OutputHandler[ExecutionError]] = None, + envs: Optional[Dict[str, str]] = None, + timeout: Optional[float] = None, + request_timeout: Optional[float] = None) -> Execution +``` + +Runs the code as Python. + +Specify the `language` or `context` option to run the code as a different language or in a different `Context`. + +You can reference previously defined variables, imports, and functions in the code. + +**Arguments**: + +- `code`: Code to execute +- `language`: Language to use for code execution. If not defined, the default Python context is used. +- `on_stdout`: Callback for stdout messages +- `on_stderr`: Callback for stderr messages +- `on_result`: Callback for the `Result` object +- `on_error`: Callback for the `ExecutionError` object +- `envs`: Custom environment variables +- `timeout`: Timeout for the code execution in **seconds** +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`Execution` result object + + + +### run\_code + +```python +@overload +def run_code(code: str, + language: Optional[str] = None, + on_stdout: Optional[OutputHandler[OutputMessage]] = None, + on_stderr: Optional[OutputHandler[OutputMessage]] = None, + on_result: Optional[OutputHandler[Result]] = None, + on_error: Optional[OutputHandler[ExecutionError]] = None, + envs: Optional[Dict[str, str]] = None, + timeout: Optional[float] = None, + request_timeout: Optional[float] = None) -> Execution +``` + +Runs the code for the specified language. + +Specify the `language` or `context` option to run the code as a different language or in a different `Context`. +If no language is specified, Python is used. + +You can reference previously defined variables, imports, and functions in the code. + +**Arguments**: + +- `code`: Code to execute +- `language`: Language to use for code execution. If not defined, the default Python context is used. +- `on_stdout`: Callback for stdout messages +- `on_stderr`: Callback for stderr messages +- `on_result`: Callback for the `Result` object +- `on_error`: Callback for the `ExecutionError` object +- `envs`: Custom environment variables +- `timeout`: Timeout for the code execution in **seconds** +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`Execution` result object + + + +### run\_code + +```python +@overload +def run_code(code: str, + context: Optional[Context] = None, + on_stdout: Optional[OutputHandler[OutputMessage]] = None, + on_stderr: Optional[OutputHandler[OutputMessage]] = None, + on_result: Optional[OutputHandler[Result]] = None, + on_error: Optional[OutputHandler[ExecutionError]] = None, + envs: Optional[Dict[str, str]] = None, + timeout: Optional[float] = None, + request_timeout: Optional[float] = None) -> Execution +``` + +Runs the code in the specified context, if not specified, the default context is used. + +Specify the `language` or `context` option to run the code as a different language or in a different `Context`. + +You can reference previously defined variables, imports, and functions in the code. + +**Arguments**: + +- `code`: Code to execute +- `context`: Concrete context to run the code in. If not specified, the default context for the language is used. It's mutually exclusive with the language. +- `on_stdout`: Callback for stdout messages +- `on_stderr`: Callback for stderr messages +- `on_result`: Callback for the `Result` object +- `on_error`: Callback for the `ExecutionError` object +- `envs`: Custom environment variables +- `timeout`: Timeout for the code execution in **seconds** +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`Execution` result object + + + +### create\_code\_context + +```python +def create_code_context(cwd: Optional[str] = None, + language: Optional[str] = None, + request_timeout: Optional[float] = None) -> Context +``` + +Creates a new context to run code in. + +**Arguments**: + +- `cwd`: Set the current working directory for the context, defaults to `/home/user` +- `language`: Language of the context. If not specified, defaults to Python +- `request_timeout`: Timeout for the request in **milliseconds** + +**Returns**: + +Context object + + + + + + diff --git a/docs/sdk-reference/code-interpreter-python-sdk/v2.2.1/code_interpreter.mdx b/docs/sdk-reference/code-interpreter-python-sdk/v2.2.1/code_interpreter.mdx new file mode 100644 index 0000000..f250edb --- /dev/null +++ b/docs/sdk-reference/code-interpreter-python-sdk/v2.2.1/code_interpreter.mdx @@ -0,0 +1,789 @@ +--- +sidebarTitle: "Code Interpreter" +mode: "center" +--- + + + + + + + + + +## AsyncSandbox + +```python +class AsyncSandbox(BaseAsyncSandbox) +``` + +E2B cloud sandbox is a secure and isolated cloud environment. + +The sandbox allows you to: +- Access Linux OS +- Create, list, and delete files and directories +- Run commands +- Run isolated code +- Access the internet + +Check docs [here](https://e2b.dev/docs). + +Use the `AsyncSandbox.create()` to create a new sandbox. + +**Example**: + +```python +from e2b_code_interpreter import AsyncSandbox +sandbox = await AsyncSandbox.create() +``` + + + +### run\_code + +```python +@overload +async def run_code( + code: str, + language: Union[Literal["python"], None] = None, + on_stdout: Optional[OutputHandlerWithAsync[OutputMessage]] = None, + on_stderr: Optional[OutputHandlerWithAsync[OutputMessage]] = None, + on_result: Optional[OutputHandlerWithAsync[Result]] = None, + on_error: Optional[OutputHandlerWithAsync[ExecutionError]] = None, + envs: Optional[Dict[str, str]] = None, + timeout: Optional[float] = None, + request_timeout: Optional[float] = None) -> Execution +``` + +Runs the code as Python. + +Specify the `language` or `context` option to run the code as a different language or in a different `Context`. + +You can reference previously defined variables, imports, and functions in the code. + +**Arguments**: + +- `code`: Code to execute +- `language`: Language to use for code execution. If not defined, the default Python context is used. +- `on_stdout`: Callback for stdout messages +- `on_stderr`: Callback for stderr messages +- `on_result`: Callback for the `Result` object +- `on_error`: Callback for the `ExecutionError` object +- `envs`: Custom environment variables +- `timeout`: Timeout for the code execution in **seconds** +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`Execution` result object + + + +### run\_code + +```python +@overload +async def run_code( + code: str, + language: Optional[str] = None, + on_stdout: Optional[OutputHandlerWithAsync[OutputMessage]] = None, + on_stderr: Optional[OutputHandlerWithAsync[OutputMessage]] = None, + on_result: Optional[OutputHandlerWithAsync[Result]] = None, + on_error: Optional[OutputHandlerWithAsync[ExecutionError]] = None, + envs: Optional[Dict[str, str]] = None, + timeout: Optional[float] = None, + request_timeout: Optional[float] = None) -> Execution +``` + +Runs the code for the specified language. + +Specify the `language` or `context` option to run the code as a different language or in a different `Context`. +If no language is specified, Python is used. + +You can reference previously defined variables, imports, and functions in the code. + +**Arguments**: + +- `code`: Code to execute +- `language`: Language to use for code execution. If not defined, the default Python context is used. +- `on_stdout`: Callback for stdout messages +- `on_stderr`: Callback for stderr messages +- `on_result`: Callback for the `Result` object +- `on_error`: Callback for the `ExecutionError` object +- `envs`: Custom environment variables +- `timeout`: Timeout for the code execution in **seconds** +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`Execution` result object + + + +### run\_code + +```python +@overload +async def run_code( + code: str, + context: Optional[Context] = None, + on_stdout: Optional[OutputHandlerWithAsync[OutputMessage]] = None, + on_stderr: Optional[OutputHandlerWithAsync[OutputMessage]] = None, + on_result: Optional[OutputHandlerWithAsync[Result]] = None, + on_error: Optional[OutputHandlerWithAsync[ExecutionError]] = None, + envs: Optional[Dict[str, str]] = None, + timeout: Optional[float] = None, + request_timeout: Optional[float] = None) -> Execution +``` + +Runs the code in the specified context, if not specified, the default context is used. + +Specify the `language` or `context` option to run the code as a different language or in a different `Context`. + +You can reference previously defined variables, imports, and functions in the code. + +**Arguments**: + +- `code`: Code to execute +- `context`: Concrete context to run the code in. If not specified, the default context for the language is used. It's mutually exclusive with the language. +- `on_stdout`: Callback for stdout messages +- `on_stderr`: Callback for stderr messages +- `on_result`: Callback for the `Result` object +- `on_error`: Callback for the `ExecutionError` object +- `envs`: Custom environment variables +- `timeout`: Timeout for the code execution in **seconds** +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`Execution` result object + + + +### create\_code\_context + +```python +async def create_code_context( + cwd: Optional[str] = None, + language: Optional[str] = None, + request_timeout: Optional[float] = None) -> Context +``` + +Creates a new context to run code in. + +**Arguments**: + +- `cwd`: Set the current working directory for the context, defaults to `/home/user` +- `language`: Language of the context. If not specified, defaults to Python +- `request_timeout`: Timeout for the request in **milliseconds** + +**Returns**: + +Context object + + + + + + +## OutputMessage + +```python +@dataclass +class OutputMessage() +``` + +Represents an output message from the sandbox code execution. + + + +### line + +The output line. + + + +### timestamp + +Unix epoch in nanoseconds + + + +### error + +Whether the output is an error. + + + +## ExecutionError + +```python +@dataclass +class ExecutionError() +``` + +Represents an error that occurred during the execution of a cell. +The error contains the name of the error, the value of the error, and the traceback. + + + +### name + +Name of the error. + + + +### value + +Value of the error. + + + +### traceback + +The raw traceback of the error. + + + +### to\_json + +```python +def to_json() -> str +``` + +Returns the JSON representation of the Error object. + + + +## MIMEType + +```python +class MIMEType(str) +``` + +Represents a MIME type. + + + +## Result + +```python +@dataclass +class Result() +``` + +Represents the data to be displayed as a result of executing a cell in a Jupyter notebook. +The result is similar to the structure returned by ipython kernel: https://ipython.readthedocs.io/en/stable/development/execution.html#execution-semantics + +The result can contain multiple types of data, such as text, images, plots, etc. Each type of data is represented +as a string, and the result can contain multiple types of data. The display calls don't have to have text representation, +for the actual result the representation is always present for the result, the other representations are always optional. + + + +### is\_main\_result + +Whether this data is the result of the cell. Data can be produced by display calls of which can be multiple in a cell. + + + +### extra + +Extra data that can be included. Not part of the standard types. + + + +### formats + +```python +def formats() -> Iterable[str] +``` + +Returns all available formats of the result. + +**Returns**: + +All available formats of the result in MIME types. + + + +### \_\_str\_\_ + +```python +def __str__() -> Optional[str] +``` + +Returns the text representation of the data. + +**Returns**: + +The text representation of the data. + + + +### \_repr\_html\_ + +```python +def _repr_html_() -> Optional[str] +``` + +Returns the HTML representation of the data. + +**Returns**: + +The HTML representation of the data. + + + +### \_repr\_markdown\_ + +```python +def _repr_markdown_() -> Optional[str] +``` + +Returns the Markdown representation of the data. + +**Returns**: + +The Markdown representation of the data. + + + +### \_repr\_svg\_ + +```python +def _repr_svg_() -> Optional[str] +``` + +Returns the SVG representation of the data. + +**Returns**: + +The SVG representation of the data. + + + +### \_repr\_png\_ + +```python +def _repr_png_() -> Optional[str] +``` + +Returns the base64 representation of the PNG data. + +**Returns**: + +The base64 representation of the PNG data. + + + +### \_repr\_jpeg\_ + +```python +def _repr_jpeg_() -> Optional[str] +``` + +Returns the base64 representation of the JPEG data. + +**Returns**: + +The base64 representation of the JPEG data. + + + +### \_repr\_pdf\_ + +```python +def _repr_pdf_() -> Optional[str] +``` + +Returns the PDF representation of the data. + +**Returns**: + +The PDF representation of the data. + + + +### \_repr\_latex\_ + +```python +def _repr_latex_() -> Optional[str] +``` + +Returns the LaTeX representation of the data. + +**Returns**: + +The LaTeX representation of the data. + + + +### \_repr\_json\_ + +```python +def _repr_json_() -> Optional[dict] +``` + +Returns the JSON representation of the data. + +**Returns**: + +The JSON representation of the data. + + + +### \_repr\_javascript\_ + +```python +def _repr_javascript_() -> Optional[str] +``` + +Returns the JavaScript representation of the data. + +**Returns**: + +The JavaScript representation of the data. + + + +## Logs + +```python +@dataclass(repr=False) +class Logs() +``` + +Data printed to stdout and stderr during execution, usually by print statements, logs, warnings, subprocesses, etc. + + + +### stdout + +List of strings printed to stdout by prints, subprocesses, etc. + + + +### stderr + +List of strings printed to stderr by prints, subprocesses, etc. + + + +### to\_json + +```python +def to_json() -> str +``` + +Returns the JSON representation of the Logs object. + + + +### serialize\_results + +```python +def serialize_results(results: List[Result]) -> List[Dict[str, str]] +``` + +Serializes the results to JSON. + + + +## Execution + +```python +@dataclass(repr=False) +class Execution() +``` + +Represents the result of a cell execution. + + + +### results + +List of the result of the cell (interactively interpreted last line), display calls (e.g. matplotlib plots). + + + +### logs + +Logs printed to stdout and stderr during execution. + + + +### error + +Error object if an error occurred, None otherwise. + + + +### execution\_count + +Execution count of the cell. + + + +### text + +```python +@property +def text() -> Optional[str] +``` + +Returns the text representation of the result. + +**Returns**: + +The text representation of the result. + + + +### to\_json + +```python +def to_json() -> str +``` + +Returns the JSON representation of the Execution object. + + + +## Context + +```python +@dataclass +class Context() +``` + +Represents a context for code execution. + + + +### id + +The ID of the context. + + + +### language + +The language of the context. + + + +### cwd + +The working directory of the context. + + + + + + +## ChartType + +```python +class ChartType(str, enum.Enum) +``` + +Chart types + + + +## ScaleType + +```python +class ScaleType(str, enum.Enum) +``` + +Ax scale types + + + +## Chart + +```python +class Chart() +``` + +Extracted data from a chart. It's useful for building an interactive charts or custom visualizations. + + + + + + +## Sandbox + +```python +class Sandbox(BaseSandbox) +``` + +E2B cloud sandbox is a secure and isolated cloud environment. + +The sandbox allows you to: +- Access Linux OS +- Create, list, and delete files and directories +- Run commands +- Run isolated code +- Access the internet + +Check docs [here](https://e2b.dev/docs). + +Use the `Sandbox.create()` to create a new sandbox. + +**Example**: + +```python +from e2b_code_interpreter import Sandbox + +sandbox = Sandbox.create() +``` + + + +### run\_code + +```python +@overload +def run_code(code: str, + language: Union[Literal["python"], None] = None, + on_stdout: Optional[OutputHandler[OutputMessage]] = None, + on_stderr: Optional[OutputHandler[OutputMessage]] = None, + on_result: Optional[OutputHandler[Result]] = None, + on_error: Optional[OutputHandler[ExecutionError]] = None, + envs: Optional[Dict[str, str]] = None, + timeout: Optional[float] = None, + request_timeout: Optional[float] = None) -> Execution +``` + +Runs the code as Python. + +Specify the `language` or `context` option to run the code as a different language or in a different `Context`. + +You can reference previously defined variables, imports, and functions in the code. + +**Arguments**: + +- `code`: Code to execute +- `language`: Language to use for code execution. If not defined, the default Python context is used. +- `on_stdout`: Callback for stdout messages +- `on_stderr`: Callback for stderr messages +- `on_result`: Callback for the `Result` object +- `on_error`: Callback for the `ExecutionError` object +- `envs`: Custom environment variables +- `timeout`: Timeout for the code execution in **seconds** +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`Execution` result object + + + +### run\_code + +```python +@overload +def run_code(code: str, + language: Optional[str] = None, + on_stdout: Optional[OutputHandler[OutputMessage]] = None, + on_stderr: Optional[OutputHandler[OutputMessage]] = None, + on_result: Optional[OutputHandler[Result]] = None, + on_error: Optional[OutputHandler[ExecutionError]] = None, + envs: Optional[Dict[str, str]] = None, + timeout: Optional[float] = None, + request_timeout: Optional[float] = None) -> Execution +``` + +Runs the code for the specified language. + +Specify the `language` or `context` option to run the code as a different language or in a different `Context`. +If no language is specified, Python is used. + +You can reference previously defined variables, imports, and functions in the code. + +**Arguments**: + +- `code`: Code to execute +- `language`: Language to use for code execution. If not defined, the default Python context is used. +- `on_stdout`: Callback for stdout messages +- `on_stderr`: Callback for stderr messages +- `on_result`: Callback for the `Result` object +- `on_error`: Callback for the `ExecutionError` object +- `envs`: Custom environment variables +- `timeout`: Timeout for the code execution in **seconds** +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`Execution` result object + + + +### run\_code + +```python +@overload +def run_code(code: str, + context: Optional[Context] = None, + on_stdout: Optional[OutputHandler[OutputMessage]] = None, + on_stderr: Optional[OutputHandler[OutputMessage]] = None, + on_result: Optional[OutputHandler[Result]] = None, + on_error: Optional[OutputHandler[ExecutionError]] = None, + envs: Optional[Dict[str, str]] = None, + timeout: Optional[float] = None, + request_timeout: Optional[float] = None) -> Execution +``` + +Runs the code in the specified context, if not specified, the default context is used. + +Specify the `language` or `context` option to run the code as a different language or in a different `Context`. + +You can reference previously defined variables, imports, and functions in the code. + +**Arguments**: + +- `code`: Code to execute +- `context`: Concrete context to run the code in. If not specified, the default context for the language is used. It's mutually exclusive with the language. +- `on_stdout`: Callback for stdout messages +- `on_stderr`: Callback for stderr messages +- `on_result`: Callback for the `Result` object +- `on_error`: Callback for the `ExecutionError` object +- `envs`: Custom environment variables +- `timeout`: Timeout for the code execution in **seconds** +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`Execution` result object + + + +### create\_code\_context + +```python +def create_code_context(cwd: Optional[str] = None, + language: Optional[str] = None, + request_timeout: Optional[float] = None) -> Context +``` + +Creates a new context to run code in. + +**Arguments**: + +- `cwd`: Set the current working directory for the context, defaults to `/home/user` +- `language`: Language of the context. If not specified, defaults to Python +- `request_timeout`: Timeout for the request in **milliseconds** + +**Returns**: + +Context object + + + + + + diff --git a/docs/sdk-reference/code-interpreter-python-sdk/v2.3.0/code_interpreter.mdx b/docs/sdk-reference/code-interpreter-python-sdk/v2.3.0/code_interpreter.mdx new file mode 100644 index 0000000..f250edb --- /dev/null +++ b/docs/sdk-reference/code-interpreter-python-sdk/v2.3.0/code_interpreter.mdx @@ -0,0 +1,789 @@ +--- +sidebarTitle: "Code Interpreter" +mode: "center" +--- + + + + + + + + + +## AsyncSandbox + +```python +class AsyncSandbox(BaseAsyncSandbox) +``` + +E2B cloud sandbox is a secure and isolated cloud environment. + +The sandbox allows you to: +- Access Linux OS +- Create, list, and delete files and directories +- Run commands +- Run isolated code +- Access the internet + +Check docs [here](https://e2b.dev/docs). + +Use the `AsyncSandbox.create()` to create a new sandbox. + +**Example**: + +```python +from e2b_code_interpreter import AsyncSandbox +sandbox = await AsyncSandbox.create() +``` + + + +### run\_code + +```python +@overload +async def run_code( + code: str, + language: Union[Literal["python"], None] = None, + on_stdout: Optional[OutputHandlerWithAsync[OutputMessage]] = None, + on_stderr: Optional[OutputHandlerWithAsync[OutputMessage]] = None, + on_result: Optional[OutputHandlerWithAsync[Result]] = None, + on_error: Optional[OutputHandlerWithAsync[ExecutionError]] = None, + envs: Optional[Dict[str, str]] = None, + timeout: Optional[float] = None, + request_timeout: Optional[float] = None) -> Execution +``` + +Runs the code as Python. + +Specify the `language` or `context` option to run the code as a different language or in a different `Context`. + +You can reference previously defined variables, imports, and functions in the code. + +**Arguments**: + +- `code`: Code to execute +- `language`: Language to use for code execution. If not defined, the default Python context is used. +- `on_stdout`: Callback for stdout messages +- `on_stderr`: Callback for stderr messages +- `on_result`: Callback for the `Result` object +- `on_error`: Callback for the `ExecutionError` object +- `envs`: Custom environment variables +- `timeout`: Timeout for the code execution in **seconds** +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`Execution` result object + + + +### run\_code + +```python +@overload +async def run_code( + code: str, + language: Optional[str] = None, + on_stdout: Optional[OutputHandlerWithAsync[OutputMessage]] = None, + on_stderr: Optional[OutputHandlerWithAsync[OutputMessage]] = None, + on_result: Optional[OutputHandlerWithAsync[Result]] = None, + on_error: Optional[OutputHandlerWithAsync[ExecutionError]] = None, + envs: Optional[Dict[str, str]] = None, + timeout: Optional[float] = None, + request_timeout: Optional[float] = None) -> Execution +``` + +Runs the code for the specified language. + +Specify the `language` or `context` option to run the code as a different language or in a different `Context`. +If no language is specified, Python is used. + +You can reference previously defined variables, imports, and functions in the code. + +**Arguments**: + +- `code`: Code to execute +- `language`: Language to use for code execution. If not defined, the default Python context is used. +- `on_stdout`: Callback for stdout messages +- `on_stderr`: Callback for stderr messages +- `on_result`: Callback for the `Result` object +- `on_error`: Callback for the `ExecutionError` object +- `envs`: Custom environment variables +- `timeout`: Timeout for the code execution in **seconds** +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`Execution` result object + + + +### run\_code + +```python +@overload +async def run_code( + code: str, + context: Optional[Context] = None, + on_stdout: Optional[OutputHandlerWithAsync[OutputMessage]] = None, + on_stderr: Optional[OutputHandlerWithAsync[OutputMessage]] = None, + on_result: Optional[OutputHandlerWithAsync[Result]] = None, + on_error: Optional[OutputHandlerWithAsync[ExecutionError]] = None, + envs: Optional[Dict[str, str]] = None, + timeout: Optional[float] = None, + request_timeout: Optional[float] = None) -> Execution +``` + +Runs the code in the specified context, if not specified, the default context is used. + +Specify the `language` or `context` option to run the code as a different language or in a different `Context`. + +You can reference previously defined variables, imports, and functions in the code. + +**Arguments**: + +- `code`: Code to execute +- `context`: Concrete context to run the code in. If not specified, the default context for the language is used. It's mutually exclusive with the language. +- `on_stdout`: Callback for stdout messages +- `on_stderr`: Callback for stderr messages +- `on_result`: Callback for the `Result` object +- `on_error`: Callback for the `ExecutionError` object +- `envs`: Custom environment variables +- `timeout`: Timeout for the code execution in **seconds** +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`Execution` result object + + + +### create\_code\_context + +```python +async def create_code_context( + cwd: Optional[str] = None, + language: Optional[str] = None, + request_timeout: Optional[float] = None) -> Context +``` + +Creates a new context to run code in. + +**Arguments**: + +- `cwd`: Set the current working directory for the context, defaults to `/home/user` +- `language`: Language of the context. If not specified, defaults to Python +- `request_timeout`: Timeout for the request in **milliseconds** + +**Returns**: + +Context object + + + + + + +## OutputMessage + +```python +@dataclass +class OutputMessage() +``` + +Represents an output message from the sandbox code execution. + + + +### line + +The output line. + + + +### timestamp + +Unix epoch in nanoseconds + + + +### error + +Whether the output is an error. + + + +## ExecutionError + +```python +@dataclass +class ExecutionError() +``` + +Represents an error that occurred during the execution of a cell. +The error contains the name of the error, the value of the error, and the traceback. + + + +### name + +Name of the error. + + + +### value + +Value of the error. + + + +### traceback + +The raw traceback of the error. + + + +### to\_json + +```python +def to_json() -> str +``` + +Returns the JSON representation of the Error object. + + + +## MIMEType + +```python +class MIMEType(str) +``` + +Represents a MIME type. + + + +## Result + +```python +@dataclass +class Result() +``` + +Represents the data to be displayed as a result of executing a cell in a Jupyter notebook. +The result is similar to the structure returned by ipython kernel: https://ipython.readthedocs.io/en/stable/development/execution.html#execution-semantics + +The result can contain multiple types of data, such as text, images, plots, etc. Each type of data is represented +as a string, and the result can contain multiple types of data. The display calls don't have to have text representation, +for the actual result the representation is always present for the result, the other representations are always optional. + + + +### is\_main\_result + +Whether this data is the result of the cell. Data can be produced by display calls of which can be multiple in a cell. + + + +### extra + +Extra data that can be included. Not part of the standard types. + + + +### formats + +```python +def formats() -> Iterable[str] +``` + +Returns all available formats of the result. + +**Returns**: + +All available formats of the result in MIME types. + + + +### \_\_str\_\_ + +```python +def __str__() -> Optional[str] +``` + +Returns the text representation of the data. + +**Returns**: + +The text representation of the data. + + + +### \_repr\_html\_ + +```python +def _repr_html_() -> Optional[str] +``` + +Returns the HTML representation of the data. + +**Returns**: + +The HTML representation of the data. + + + +### \_repr\_markdown\_ + +```python +def _repr_markdown_() -> Optional[str] +``` + +Returns the Markdown representation of the data. + +**Returns**: + +The Markdown representation of the data. + + + +### \_repr\_svg\_ + +```python +def _repr_svg_() -> Optional[str] +``` + +Returns the SVG representation of the data. + +**Returns**: + +The SVG representation of the data. + + + +### \_repr\_png\_ + +```python +def _repr_png_() -> Optional[str] +``` + +Returns the base64 representation of the PNG data. + +**Returns**: + +The base64 representation of the PNG data. + + + +### \_repr\_jpeg\_ + +```python +def _repr_jpeg_() -> Optional[str] +``` + +Returns the base64 representation of the JPEG data. + +**Returns**: + +The base64 representation of the JPEG data. + + + +### \_repr\_pdf\_ + +```python +def _repr_pdf_() -> Optional[str] +``` + +Returns the PDF representation of the data. + +**Returns**: + +The PDF representation of the data. + + + +### \_repr\_latex\_ + +```python +def _repr_latex_() -> Optional[str] +``` + +Returns the LaTeX representation of the data. + +**Returns**: + +The LaTeX representation of the data. + + + +### \_repr\_json\_ + +```python +def _repr_json_() -> Optional[dict] +``` + +Returns the JSON representation of the data. + +**Returns**: + +The JSON representation of the data. + + + +### \_repr\_javascript\_ + +```python +def _repr_javascript_() -> Optional[str] +``` + +Returns the JavaScript representation of the data. + +**Returns**: + +The JavaScript representation of the data. + + + +## Logs + +```python +@dataclass(repr=False) +class Logs() +``` + +Data printed to stdout and stderr during execution, usually by print statements, logs, warnings, subprocesses, etc. + + + +### stdout + +List of strings printed to stdout by prints, subprocesses, etc. + + + +### stderr + +List of strings printed to stderr by prints, subprocesses, etc. + + + +### to\_json + +```python +def to_json() -> str +``` + +Returns the JSON representation of the Logs object. + + + +### serialize\_results + +```python +def serialize_results(results: List[Result]) -> List[Dict[str, str]] +``` + +Serializes the results to JSON. + + + +## Execution + +```python +@dataclass(repr=False) +class Execution() +``` + +Represents the result of a cell execution. + + + +### results + +List of the result of the cell (interactively interpreted last line), display calls (e.g. matplotlib plots). + + + +### logs + +Logs printed to stdout and stderr during execution. + + + +### error + +Error object if an error occurred, None otherwise. + + + +### execution\_count + +Execution count of the cell. + + + +### text + +```python +@property +def text() -> Optional[str] +``` + +Returns the text representation of the result. + +**Returns**: + +The text representation of the result. + + + +### to\_json + +```python +def to_json() -> str +``` + +Returns the JSON representation of the Execution object. + + + +## Context + +```python +@dataclass +class Context() +``` + +Represents a context for code execution. + + + +### id + +The ID of the context. + + + +### language + +The language of the context. + + + +### cwd + +The working directory of the context. + + + + + + +## ChartType + +```python +class ChartType(str, enum.Enum) +``` + +Chart types + + + +## ScaleType + +```python +class ScaleType(str, enum.Enum) +``` + +Ax scale types + + + +## Chart + +```python +class Chart() +``` + +Extracted data from a chart. It's useful for building an interactive charts or custom visualizations. + + + + + + +## Sandbox + +```python +class Sandbox(BaseSandbox) +``` + +E2B cloud sandbox is a secure and isolated cloud environment. + +The sandbox allows you to: +- Access Linux OS +- Create, list, and delete files and directories +- Run commands +- Run isolated code +- Access the internet + +Check docs [here](https://e2b.dev/docs). + +Use the `Sandbox.create()` to create a new sandbox. + +**Example**: + +```python +from e2b_code_interpreter import Sandbox + +sandbox = Sandbox.create() +``` + + + +### run\_code + +```python +@overload +def run_code(code: str, + language: Union[Literal["python"], None] = None, + on_stdout: Optional[OutputHandler[OutputMessage]] = None, + on_stderr: Optional[OutputHandler[OutputMessage]] = None, + on_result: Optional[OutputHandler[Result]] = None, + on_error: Optional[OutputHandler[ExecutionError]] = None, + envs: Optional[Dict[str, str]] = None, + timeout: Optional[float] = None, + request_timeout: Optional[float] = None) -> Execution +``` + +Runs the code as Python. + +Specify the `language` or `context` option to run the code as a different language or in a different `Context`. + +You can reference previously defined variables, imports, and functions in the code. + +**Arguments**: + +- `code`: Code to execute +- `language`: Language to use for code execution. If not defined, the default Python context is used. +- `on_stdout`: Callback for stdout messages +- `on_stderr`: Callback for stderr messages +- `on_result`: Callback for the `Result` object +- `on_error`: Callback for the `ExecutionError` object +- `envs`: Custom environment variables +- `timeout`: Timeout for the code execution in **seconds** +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`Execution` result object + + + +### run\_code + +```python +@overload +def run_code(code: str, + language: Optional[str] = None, + on_stdout: Optional[OutputHandler[OutputMessage]] = None, + on_stderr: Optional[OutputHandler[OutputMessage]] = None, + on_result: Optional[OutputHandler[Result]] = None, + on_error: Optional[OutputHandler[ExecutionError]] = None, + envs: Optional[Dict[str, str]] = None, + timeout: Optional[float] = None, + request_timeout: Optional[float] = None) -> Execution +``` + +Runs the code for the specified language. + +Specify the `language` or `context` option to run the code as a different language or in a different `Context`. +If no language is specified, Python is used. + +You can reference previously defined variables, imports, and functions in the code. + +**Arguments**: + +- `code`: Code to execute +- `language`: Language to use for code execution. If not defined, the default Python context is used. +- `on_stdout`: Callback for stdout messages +- `on_stderr`: Callback for stderr messages +- `on_result`: Callback for the `Result` object +- `on_error`: Callback for the `ExecutionError` object +- `envs`: Custom environment variables +- `timeout`: Timeout for the code execution in **seconds** +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`Execution` result object + + + +### run\_code + +```python +@overload +def run_code(code: str, + context: Optional[Context] = None, + on_stdout: Optional[OutputHandler[OutputMessage]] = None, + on_stderr: Optional[OutputHandler[OutputMessage]] = None, + on_result: Optional[OutputHandler[Result]] = None, + on_error: Optional[OutputHandler[ExecutionError]] = None, + envs: Optional[Dict[str, str]] = None, + timeout: Optional[float] = None, + request_timeout: Optional[float] = None) -> Execution +``` + +Runs the code in the specified context, if not specified, the default context is used. + +Specify the `language` or `context` option to run the code as a different language or in a different `Context`. + +You can reference previously defined variables, imports, and functions in the code. + +**Arguments**: + +- `code`: Code to execute +- `context`: Concrete context to run the code in. If not specified, the default context for the language is used. It's mutually exclusive with the language. +- `on_stdout`: Callback for stdout messages +- `on_stderr`: Callback for stderr messages +- `on_result`: Callback for the `Result` object +- `on_error`: Callback for the `ExecutionError` object +- `envs`: Custom environment variables +- `timeout`: Timeout for the code execution in **seconds** +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`Execution` result object + + + +### create\_code\_context + +```python +def create_code_context(cwd: Optional[str] = None, + language: Optional[str] = None, + request_timeout: Optional[float] = None) -> Context +``` + +Creates a new context to run code in. + +**Arguments**: + +- `cwd`: Set the current working directory for the context, defaults to `/home/user` +- `language`: Language of the context. If not specified, defaults to Python +- `request_timeout`: Timeout for the request in **milliseconds** + +**Returns**: + +Context object + + + + + + diff --git a/docs/sdk-reference/code-interpreter-python-sdk/v2.4.0/code_interpreter.mdx b/docs/sdk-reference/code-interpreter-python-sdk/v2.4.0/code_interpreter.mdx new file mode 100644 index 0000000..f4a3f16 --- /dev/null +++ b/docs/sdk-reference/code-interpreter-python-sdk/v2.4.0/code_interpreter.mdx @@ -0,0 +1,889 @@ +--- +sidebarTitle: "Code Interpreter" +mode: "center" +--- + + + + + + + + + +## AsyncSandbox + +```python +class AsyncSandbox(BaseAsyncSandbox) +``` + +E2B cloud sandbox is a secure and isolated cloud environment. + +The sandbox allows you to: +- Access Linux OS +- Create, list, and delete files and directories +- Run commands +- Run isolated code +- Access the internet + +Check docs [here](https://e2b.dev/docs). + +Use the `AsyncSandbox.create()` to create a new sandbox. + +**Example**: + +```python +from e2b_code_interpreter import AsyncSandbox +sandbox = await AsyncSandbox.create() +``` + + + +### run\_code + +```python +@overload +async def run_code( + code: str, + language: Union[Literal["python"], None] = None, + on_stdout: Optional[OutputHandlerWithAsync[OutputMessage]] = None, + on_stderr: Optional[OutputHandlerWithAsync[OutputMessage]] = None, + on_result: Optional[OutputHandlerWithAsync[Result]] = None, + on_error: Optional[OutputHandlerWithAsync[ExecutionError]] = None, + envs: Optional[Dict[str, str]] = None, + timeout: Optional[float] = None, + request_timeout: Optional[float] = None) -> Execution +``` + +Runs the code as Python. + +Specify the `language` or `context` option to run the code as a different language or in a different `Context`. + +You can reference previously defined variables, imports, and functions in the code. + +**Arguments**: + +- `code`: Code to execute +- `language`: Language to use for code execution. If not defined, the default Python context is used. +- `on_stdout`: Callback for stdout messages +- `on_stderr`: Callback for stderr messages +- `on_result`: Callback for the `Result` object +- `on_error`: Callback for the `ExecutionError` object +- `envs`: Custom environment variables +- `timeout`: Timeout for the code execution in **seconds** +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`Execution` result object + + + +### run\_code + +```python +@overload +async def run_code( + code: str, + language: Optional[str] = None, + on_stdout: Optional[OutputHandlerWithAsync[OutputMessage]] = None, + on_stderr: Optional[OutputHandlerWithAsync[OutputMessage]] = None, + on_result: Optional[OutputHandlerWithAsync[Result]] = None, + on_error: Optional[OutputHandlerWithAsync[ExecutionError]] = None, + envs: Optional[Dict[str, str]] = None, + timeout: Optional[float] = None, + request_timeout: Optional[float] = None) -> Execution +``` + +Runs the code for the specified language. + +Specify the `language` or `context` option to run the code as a different language or in a different `Context`. +If no language is specified, Python is used. + +You can reference previously defined variables, imports, and functions in the code. + +**Arguments**: + +- `code`: Code to execute +- `language`: Language to use for code execution. If not defined, the default Python context is used. +- `on_stdout`: Callback for stdout messages +- `on_stderr`: Callback for stderr messages +- `on_result`: Callback for the `Result` object +- `on_error`: Callback for the `ExecutionError` object +- `envs`: Custom environment variables +- `timeout`: Timeout for the code execution in **seconds** +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`Execution` result object + + + +### run\_code + +```python +@overload +async def run_code( + code: str, + context: Optional[Context] = None, + on_stdout: Optional[OutputHandlerWithAsync[OutputMessage]] = None, + on_stderr: Optional[OutputHandlerWithAsync[OutputMessage]] = None, + on_result: Optional[OutputHandlerWithAsync[Result]] = None, + on_error: Optional[OutputHandlerWithAsync[ExecutionError]] = None, + envs: Optional[Dict[str, str]] = None, + timeout: Optional[float] = None, + request_timeout: Optional[float] = None) -> Execution +``` + +Runs the code in the specified context, if not specified, the default context is used. + +Specify the `language` or `context` option to run the code as a different language or in a different `Context`. + +You can reference previously defined variables, imports, and functions in the code. + +**Arguments**: + +- `code`: Code to execute +- `context`: Concrete context to run the code in. If not specified, the default context for the language is used. It's mutually exclusive with the language. +- `on_stdout`: Callback for stdout messages +- `on_stderr`: Callback for stderr messages +- `on_result`: Callback for the `Result` object +- `on_error`: Callback for the `ExecutionError` object +- `envs`: Custom environment variables +- `timeout`: Timeout for the code execution in **seconds** +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`Execution` result object + + + +### create\_code\_context + +```python +async def create_code_context( + cwd: Optional[str] = None, + language: Optional[str] = None, + request_timeout: Optional[float] = None) -> Context +``` + +Creates a new context to run code in. + +**Arguments**: + +- `cwd`: Set the current working directory for the context, defaults to `/home/user` +- `language`: Language of the context. If not specified, defaults to Python +- `request_timeout`: Timeout for the request in **milliseconds** + +**Returns**: + +Context object + + + +### remove\_code\_context + +```python +async def remove_code_context(context: Union[Context, str]) -> None +``` + +Removes a context. + +**Arguments**: + +- `context`: Context to remove. Can be a Context object or a context ID string. + +**Returns**: + +None + + + +### list\_code\_contexts + +```python +async def list_code_contexts() -> List[Context] +``` + +List all contexts. + +**Returns**: + +List of contexts. + + + +### restart\_code\_context + +```python +async def restart_code_context(context: Union[Context, str]) -> None +``` + +Restart a context. + +**Arguments**: + +- `context`: Context to restart. Can be a Context object or a context ID string. + +**Returns**: + +None + + + + + + +## OutputMessage + +```python +@dataclass +class OutputMessage() +``` + +Represents an output message from the sandbox code execution. + + + +### line + +The output line. + + + +### timestamp + +Unix epoch in nanoseconds + + + +### error + +Whether the output is an error. + + + +## ExecutionError + +```python +@dataclass +class ExecutionError() +``` + +Represents an error that occurred during the execution of a cell. +The error contains the name of the error, the value of the error, and the traceback. + + + +### name + +Name of the error. + + + +### value + +Value of the error. + + + +### traceback + +The raw traceback of the error. + + + +### to\_json + +```python +def to_json() -> str +``` + +Returns the JSON representation of the Error object. + + + +## MIMEType + +```python +class MIMEType(str) +``` + +Represents a MIME type. + + + +## Result + +```python +@dataclass +class Result() +``` + +Represents the data to be displayed as a result of executing a cell in a Jupyter notebook. +The result is similar to the structure returned by ipython kernel: https://ipython.readthedocs.io/en/stable/development/execution.html#execution-semantics + +The result can contain multiple types of data, such as text, images, plots, etc. Each type of data is represented +as a string, and the result can contain multiple types of data. The display calls don't have to have text representation, +for the actual result the representation is always present for the result, the other representations are always optional. + + + +### is\_main\_result + +Whether this data is the result of the cell. Data can be produced by display calls of which can be multiple in a cell. + + + +### extra + +Extra data that can be included. Not part of the standard types. + + + +### formats + +```python +def formats() -> Iterable[str] +``` + +Returns all available formats of the result. + +**Returns**: + +All available formats of the result in MIME types. + + + +### \_\_str\_\_ + +```python +def __str__() -> Optional[str] +``` + +Returns the text representation of the data. + +**Returns**: + +The text representation of the data. + + + +### \_repr\_html\_ + +```python +def _repr_html_() -> Optional[str] +``` + +Returns the HTML representation of the data. + +**Returns**: + +The HTML representation of the data. + + + +### \_repr\_markdown\_ + +```python +def _repr_markdown_() -> Optional[str] +``` + +Returns the Markdown representation of the data. + +**Returns**: + +The Markdown representation of the data. + + + +### \_repr\_svg\_ + +```python +def _repr_svg_() -> Optional[str] +``` + +Returns the SVG representation of the data. + +**Returns**: + +The SVG representation of the data. + + + +### \_repr\_png\_ + +```python +def _repr_png_() -> Optional[str] +``` + +Returns the base64 representation of the PNG data. + +**Returns**: + +The base64 representation of the PNG data. + + + +### \_repr\_jpeg\_ + +```python +def _repr_jpeg_() -> Optional[str] +``` + +Returns the base64 representation of the JPEG data. + +**Returns**: + +The base64 representation of the JPEG data. + + + +### \_repr\_pdf\_ + +```python +def _repr_pdf_() -> Optional[str] +``` + +Returns the PDF representation of the data. + +**Returns**: + +The PDF representation of the data. + + + +### \_repr\_latex\_ + +```python +def _repr_latex_() -> Optional[str] +``` + +Returns the LaTeX representation of the data. + +**Returns**: + +The LaTeX representation of the data. + + + +### \_repr\_json\_ + +```python +def _repr_json_() -> Optional[dict] +``` + +Returns the JSON representation of the data. + +**Returns**: + +The JSON representation of the data. + + + +### \_repr\_javascript\_ + +```python +def _repr_javascript_() -> Optional[str] +``` + +Returns the JavaScript representation of the data. + +**Returns**: + +The JavaScript representation of the data. + + + +## Logs + +```python +@dataclass(repr=False) +class Logs() +``` + +Data printed to stdout and stderr during execution, usually by print statements, logs, warnings, subprocesses, etc. + + + +### stdout + +List of strings printed to stdout by prints, subprocesses, etc. + + + +### stderr + +List of strings printed to stderr by prints, subprocesses, etc. + + + +### to\_json + +```python +def to_json() -> str +``` + +Returns the JSON representation of the Logs object. + + + +### serialize\_results + +```python +def serialize_results(results: List[Result]) -> List[Dict[str, str]] +``` + +Serializes the results to JSON. + + + +## Execution + +```python +@dataclass(repr=False) +class Execution() +``` + +Represents the result of a cell execution. + + + +### results + +List of the result of the cell (interactively interpreted last line), display calls (e.g. matplotlib plots). + + + +### logs + +Logs printed to stdout and stderr during execution. + + + +### error + +Error object if an error occurred, None otherwise. + + + +### execution\_count + +Execution count of the cell. + + + +### text + +```python +@property +def text() -> Optional[str] +``` + +Returns the text representation of the result. + +**Returns**: + +The text representation of the result. + + + +### to\_json + +```python +def to_json() -> str +``` + +Returns the JSON representation of the Execution object. + + + +## Context + +```python +@dataclass +class Context() +``` + +Represents a context for code execution. + + + +### id + +The ID of the context. + + + +### language + +The language of the context. + + + +### cwd + +The working directory of the context. + + + + + + +## ChartType + +```python +class ChartType(str, enum.Enum) +``` + +Chart types + + + +## ScaleType + +```python +class ScaleType(str, enum.Enum) +``` + +Ax scale types + + + +## Chart + +```python +class Chart() +``` + +Extracted data from a chart. It's useful for building an interactive charts or custom visualizations. + + + + + + +## Sandbox + +```python +class Sandbox(BaseSandbox) +``` + +E2B cloud sandbox is a secure and isolated cloud environment. + +The sandbox allows you to: +- Access Linux OS +- Create, list, and delete files and directories +- Run commands +- Run isolated code +- Access the internet + +Check docs [here](https://e2b.dev/docs). + +Use the `Sandbox.create()` to create a new sandbox. + +**Example**: + +```python +from e2b_code_interpreter import Sandbox + +sandbox = Sandbox.create() +``` + + + +### run\_code + +```python +@overload +def run_code(code: str, + language: Union[Literal["python"], None] = None, + on_stdout: Optional[OutputHandler[OutputMessage]] = None, + on_stderr: Optional[OutputHandler[OutputMessage]] = None, + on_result: Optional[OutputHandler[Result]] = None, + on_error: Optional[OutputHandler[ExecutionError]] = None, + envs: Optional[Dict[str, str]] = None, + timeout: Optional[float] = None, + request_timeout: Optional[float] = None) -> Execution +``` + +Runs the code as Python. + +Specify the `language` or `context` option to run the code as a different language or in a different `Context`. + +You can reference previously defined variables, imports, and functions in the code. + +**Arguments**: + +- `code`: Code to execute +- `language`: Language to use for code execution. If not defined, the default Python context is used. +- `on_stdout`: Callback for stdout messages +- `on_stderr`: Callback for stderr messages +- `on_result`: Callback for the `Result` object +- `on_error`: Callback for the `ExecutionError` object +- `envs`: Custom environment variables +- `timeout`: Timeout for the code execution in **seconds** +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`Execution` result object + + + +### run\_code + +```python +@overload +def run_code(code: str, + language: Optional[str] = None, + on_stdout: Optional[OutputHandler[OutputMessage]] = None, + on_stderr: Optional[OutputHandler[OutputMessage]] = None, + on_result: Optional[OutputHandler[Result]] = None, + on_error: Optional[OutputHandler[ExecutionError]] = None, + envs: Optional[Dict[str, str]] = None, + timeout: Optional[float] = None, + request_timeout: Optional[float] = None) -> Execution +``` + +Runs the code for the specified language. + +Specify the `language` or `context` option to run the code as a different language or in a different `Context`. +If no language is specified, Python is used. + +You can reference previously defined variables, imports, and functions in the code. + +**Arguments**: + +- `code`: Code to execute +- `language`: Language to use for code execution. If not defined, the default Python context is used. +- `on_stdout`: Callback for stdout messages +- `on_stderr`: Callback for stderr messages +- `on_result`: Callback for the `Result` object +- `on_error`: Callback for the `ExecutionError` object +- `envs`: Custom environment variables +- `timeout`: Timeout for the code execution in **seconds** +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`Execution` result object + + + +### run\_code + +```python +@overload +def run_code(code: str, + context: Optional[Context] = None, + on_stdout: Optional[OutputHandler[OutputMessage]] = None, + on_stderr: Optional[OutputHandler[OutputMessage]] = None, + on_result: Optional[OutputHandler[Result]] = None, + on_error: Optional[OutputHandler[ExecutionError]] = None, + envs: Optional[Dict[str, str]] = None, + timeout: Optional[float] = None, + request_timeout: Optional[float] = None) -> Execution +``` + +Runs the code in the specified context, if not specified, the default context is used. + +Specify the `language` or `context` option to run the code as a different language or in a different `Context`. + +You can reference previously defined variables, imports, and functions in the code. + +**Arguments**: + +- `code`: Code to execute +- `context`: Concrete context to run the code in. If not specified, the default context for the language is used. It's mutually exclusive with the language. +- `on_stdout`: Callback for stdout messages +- `on_stderr`: Callback for stderr messages +- `on_result`: Callback for the `Result` object +- `on_error`: Callback for the `ExecutionError` object +- `envs`: Custom environment variables +- `timeout`: Timeout for the code execution in **seconds** +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`Execution` result object + + + +### create\_code\_context + +```python +def create_code_context(cwd: Optional[str] = None, + language: Optional[str] = None, + request_timeout: Optional[float] = None) -> Context +``` + +Creates a new context to run code in. + +**Arguments**: + +- `cwd`: Set the current working directory for the context, defaults to `/home/user` +- `language`: Language of the context. If not specified, defaults to Python +- `request_timeout`: Timeout for the request in **milliseconds** + +**Returns**: + +Context object + + + +### remove\_code\_context + +```python +def remove_code_context(context: Union[Context, str]) -> None +``` + +Removes a context. + +**Arguments**: + +- `context`: Context to remove. Can be a Context object or a context ID string. + +**Returns**: + +None + + + +### list\_code\_contexts + +```python +def list_code_contexts() -> List[Context] +``` + +List all contexts. + +**Returns**: + +List of contexts. + + + +### restart\_code\_context + +```python +def restart_code_context(context: Union[Context, str]) -> None +``` + +Restart a context. + +**Arguments**: + +- `context`: Context to restart. Can be a Context object or a context ID string. + +**Returns**: + +None + + + + + + diff --git a/docs/sdk-reference/code-interpreter-python-sdk/v2.4.1/code_interpreter.mdx b/docs/sdk-reference/code-interpreter-python-sdk/v2.4.1/code_interpreter.mdx new file mode 100644 index 0000000..f4a3f16 --- /dev/null +++ b/docs/sdk-reference/code-interpreter-python-sdk/v2.4.1/code_interpreter.mdx @@ -0,0 +1,889 @@ +--- +sidebarTitle: "Code Interpreter" +mode: "center" +--- + + + + + + + + + +## AsyncSandbox + +```python +class AsyncSandbox(BaseAsyncSandbox) +``` + +E2B cloud sandbox is a secure and isolated cloud environment. + +The sandbox allows you to: +- Access Linux OS +- Create, list, and delete files and directories +- Run commands +- Run isolated code +- Access the internet + +Check docs [here](https://e2b.dev/docs). + +Use the `AsyncSandbox.create()` to create a new sandbox. + +**Example**: + +```python +from e2b_code_interpreter import AsyncSandbox +sandbox = await AsyncSandbox.create() +``` + + + +### run\_code + +```python +@overload +async def run_code( + code: str, + language: Union[Literal["python"], None] = None, + on_stdout: Optional[OutputHandlerWithAsync[OutputMessage]] = None, + on_stderr: Optional[OutputHandlerWithAsync[OutputMessage]] = None, + on_result: Optional[OutputHandlerWithAsync[Result]] = None, + on_error: Optional[OutputHandlerWithAsync[ExecutionError]] = None, + envs: Optional[Dict[str, str]] = None, + timeout: Optional[float] = None, + request_timeout: Optional[float] = None) -> Execution +``` + +Runs the code as Python. + +Specify the `language` or `context` option to run the code as a different language or in a different `Context`. + +You can reference previously defined variables, imports, and functions in the code. + +**Arguments**: + +- `code`: Code to execute +- `language`: Language to use for code execution. If not defined, the default Python context is used. +- `on_stdout`: Callback for stdout messages +- `on_stderr`: Callback for stderr messages +- `on_result`: Callback for the `Result` object +- `on_error`: Callback for the `ExecutionError` object +- `envs`: Custom environment variables +- `timeout`: Timeout for the code execution in **seconds** +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`Execution` result object + + + +### run\_code + +```python +@overload +async def run_code( + code: str, + language: Optional[str] = None, + on_stdout: Optional[OutputHandlerWithAsync[OutputMessage]] = None, + on_stderr: Optional[OutputHandlerWithAsync[OutputMessage]] = None, + on_result: Optional[OutputHandlerWithAsync[Result]] = None, + on_error: Optional[OutputHandlerWithAsync[ExecutionError]] = None, + envs: Optional[Dict[str, str]] = None, + timeout: Optional[float] = None, + request_timeout: Optional[float] = None) -> Execution +``` + +Runs the code for the specified language. + +Specify the `language` or `context` option to run the code as a different language or in a different `Context`. +If no language is specified, Python is used. + +You can reference previously defined variables, imports, and functions in the code. + +**Arguments**: + +- `code`: Code to execute +- `language`: Language to use for code execution. If not defined, the default Python context is used. +- `on_stdout`: Callback for stdout messages +- `on_stderr`: Callback for stderr messages +- `on_result`: Callback for the `Result` object +- `on_error`: Callback for the `ExecutionError` object +- `envs`: Custom environment variables +- `timeout`: Timeout for the code execution in **seconds** +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`Execution` result object + + + +### run\_code + +```python +@overload +async def run_code( + code: str, + context: Optional[Context] = None, + on_stdout: Optional[OutputHandlerWithAsync[OutputMessage]] = None, + on_stderr: Optional[OutputHandlerWithAsync[OutputMessage]] = None, + on_result: Optional[OutputHandlerWithAsync[Result]] = None, + on_error: Optional[OutputHandlerWithAsync[ExecutionError]] = None, + envs: Optional[Dict[str, str]] = None, + timeout: Optional[float] = None, + request_timeout: Optional[float] = None) -> Execution +``` + +Runs the code in the specified context, if not specified, the default context is used. + +Specify the `language` or `context` option to run the code as a different language or in a different `Context`. + +You can reference previously defined variables, imports, and functions in the code. + +**Arguments**: + +- `code`: Code to execute +- `context`: Concrete context to run the code in. If not specified, the default context for the language is used. It's mutually exclusive with the language. +- `on_stdout`: Callback for stdout messages +- `on_stderr`: Callback for stderr messages +- `on_result`: Callback for the `Result` object +- `on_error`: Callback for the `ExecutionError` object +- `envs`: Custom environment variables +- `timeout`: Timeout for the code execution in **seconds** +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`Execution` result object + + + +### create\_code\_context + +```python +async def create_code_context( + cwd: Optional[str] = None, + language: Optional[str] = None, + request_timeout: Optional[float] = None) -> Context +``` + +Creates a new context to run code in. + +**Arguments**: + +- `cwd`: Set the current working directory for the context, defaults to `/home/user` +- `language`: Language of the context. If not specified, defaults to Python +- `request_timeout`: Timeout for the request in **milliseconds** + +**Returns**: + +Context object + + + +### remove\_code\_context + +```python +async def remove_code_context(context: Union[Context, str]) -> None +``` + +Removes a context. + +**Arguments**: + +- `context`: Context to remove. Can be a Context object or a context ID string. + +**Returns**: + +None + + + +### list\_code\_contexts + +```python +async def list_code_contexts() -> List[Context] +``` + +List all contexts. + +**Returns**: + +List of contexts. + + + +### restart\_code\_context + +```python +async def restart_code_context(context: Union[Context, str]) -> None +``` + +Restart a context. + +**Arguments**: + +- `context`: Context to restart. Can be a Context object or a context ID string. + +**Returns**: + +None + + + + + + +## OutputMessage + +```python +@dataclass +class OutputMessage() +``` + +Represents an output message from the sandbox code execution. + + + +### line + +The output line. + + + +### timestamp + +Unix epoch in nanoseconds + + + +### error + +Whether the output is an error. + + + +## ExecutionError + +```python +@dataclass +class ExecutionError() +``` + +Represents an error that occurred during the execution of a cell. +The error contains the name of the error, the value of the error, and the traceback. + + + +### name + +Name of the error. + + + +### value + +Value of the error. + + + +### traceback + +The raw traceback of the error. + + + +### to\_json + +```python +def to_json() -> str +``` + +Returns the JSON representation of the Error object. + + + +## MIMEType + +```python +class MIMEType(str) +``` + +Represents a MIME type. + + + +## Result + +```python +@dataclass +class Result() +``` + +Represents the data to be displayed as a result of executing a cell in a Jupyter notebook. +The result is similar to the structure returned by ipython kernel: https://ipython.readthedocs.io/en/stable/development/execution.html#execution-semantics + +The result can contain multiple types of data, such as text, images, plots, etc. Each type of data is represented +as a string, and the result can contain multiple types of data. The display calls don't have to have text representation, +for the actual result the representation is always present for the result, the other representations are always optional. + + + +### is\_main\_result + +Whether this data is the result of the cell. Data can be produced by display calls of which can be multiple in a cell. + + + +### extra + +Extra data that can be included. Not part of the standard types. + + + +### formats + +```python +def formats() -> Iterable[str] +``` + +Returns all available formats of the result. + +**Returns**: + +All available formats of the result in MIME types. + + + +### \_\_str\_\_ + +```python +def __str__() -> Optional[str] +``` + +Returns the text representation of the data. + +**Returns**: + +The text representation of the data. + + + +### \_repr\_html\_ + +```python +def _repr_html_() -> Optional[str] +``` + +Returns the HTML representation of the data. + +**Returns**: + +The HTML representation of the data. + + + +### \_repr\_markdown\_ + +```python +def _repr_markdown_() -> Optional[str] +``` + +Returns the Markdown representation of the data. + +**Returns**: + +The Markdown representation of the data. + + + +### \_repr\_svg\_ + +```python +def _repr_svg_() -> Optional[str] +``` + +Returns the SVG representation of the data. + +**Returns**: + +The SVG representation of the data. + + + +### \_repr\_png\_ + +```python +def _repr_png_() -> Optional[str] +``` + +Returns the base64 representation of the PNG data. + +**Returns**: + +The base64 representation of the PNG data. + + + +### \_repr\_jpeg\_ + +```python +def _repr_jpeg_() -> Optional[str] +``` + +Returns the base64 representation of the JPEG data. + +**Returns**: + +The base64 representation of the JPEG data. + + + +### \_repr\_pdf\_ + +```python +def _repr_pdf_() -> Optional[str] +``` + +Returns the PDF representation of the data. + +**Returns**: + +The PDF representation of the data. + + + +### \_repr\_latex\_ + +```python +def _repr_latex_() -> Optional[str] +``` + +Returns the LaTeX representation of the data. + +**Returns**: + +The LaTeX representation of the data. + + + +### \_repr\_json\_ + +```python +def _repr_json_() -> Optional[dict] +``` + +Returns the JSON representation of the data. + +**Returns**: + +The JSON representation of the data. + + + +### \_repr\_javascript\_ + +```python +def _repr_javascript_() -> Optional[str] +``` + +Returns the JavaScript representation of the data. + +**Returns**: + +The JavaScript representation of the data. + + + +## Logs + +```python +@dataclass(repr=False) +class Logs() +``` + +Data printed to stdout and stderr during execution, usually by print statements, logs, warnings, subprocesses, etc. + + + +### stdout + +List of strings printed to stdout by prints, subprocesses, etc. + + + +### stderr + +List of strings printed to stderr by prints, subprocesses, etc. + + + +### to\_json + +```python +def to_json() -> str +``` + +Returns the JSON representation of the Logs object. + + + +### serialize\_results + +```python +def serialize_results(results: List[Result]) -> List[Dict[str, str]] +``` + +Serializes the results to JSON. + + + +## Execution + +```python +@dataclass(repr=False) +class Execution() +``` + +Represents the result of a cell execution. + + + +### results + +List of the result of the cell (interactively interpreted last line), display calls (e.g. matplotlib plots). + + + +### logs + +Logs printed to stdout and stderr during execution. + + + +### error + +Error object if an error occurred, None otherwise. + + + +### execution\_count + +Execution count of the cell. + + + +### text + +```python +@property +def text() -> Optional[str] +``` + +Returns the text representation of the result. + +**Returns**: + +The text representation of the result. + + + +### to\_json + +```python +def to_json() -> str +``` + +Returns the JSON representation of the Execution object. + + + +## Context + +```python +@dataclass +class Context() +``` + +Represents a context for code execution. + + + +### id + +The ID of the context. + + + +### language + +The language of the context. + + + +### cwd + +The working directory of the context. + + + + + + +## ChartType + +```python +class ChartType(str, enum.Enum) +``` + +Chart types + + + +## ScaleType + +```python +class ScaleType(str, enum.Enum) +``` + +Ax scale types + + + +## Chart + +```python +class Chart() +``` + +Extracted data from a chart. It's useful for building an interactive charts or custom visualizations. + + + + + + +## Sandbox + +```python +class Sandbox(BaseSandbox) +``` + +E2B cloud sandbox is a secure and isolated cloud environment. + +The sandbox allows you to: +- Access Linux OS +- Create, list, and delete files and directories +- Run commands +- Run isolated code +- Access the internet + +Check docs [here](https://e2b.dev/docs). + +Use the `Sandbox.create()` to create a new sandbox. + +**Example**: + +```python +from e2b_code_interpreter import Sandbox + +sandbox = Sandbox.create() +``` + + + +### run\_code + +```python +@overload +def run_code(code: str, + language: Union[Literal["python"], None] = None, + on_stdout: Optional[OutputHandler[OutputMessage]] = None, + on_stderr: Optional[OutputHandler[OutputMessage]] = None, + on_result: Optional[OutputHandler[Result]] = None, + on_error: Optional[OutputHandler[ExecutionError]] = None, + envs: Optional[Dict[str, str]] = None, + timeout: Optional[float] = None, + request_timeout: Optional[float] = None) -> Execution +``` + +Runs the code as Python. + +Specify the `language` or `context` option to run the code as a different language or in a different `Context`. + +You can reference previously defined variables, imports, and functions in the code. + +**Arguments**: + +- `code`: Code to execute +- `language`: Language to use for code execution. If not defined, the default Python context is used. +- `on_stdout`: Callback for stdout messages +- `on_stderr`: Callback for stderr messages +- `on_result`: Callback for the `Result` object +- `on_error`: Callback for the `ExecutionError` object +- `envs`: Custom environment variables +- `timeout`: Timeout for the code execution in **seconds** +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`Execution` result object + + + +### run\_code + +```python +@overload +def run_code(code: str, + language: Optional[str] = None, + on_stdout: Optional[OutputHandler[OutputMessage]] = None, + on_stderr: Optional[OutputHandler[OutputMessage]] = None, + on_result: Optional[OutputHandler[Result]] = None, + on_error: Optional[OutputHandler[ExecutionError]] = None, + envs: Optional[Dict[str, str]] = None, + timeout: Optional[float] = None, + request_timeout: Optional[float] = None) -> Execution +``` + +Runs the code for the specified language. + +Specify the `language` or `context` option to run the code as a different language or in a different `Context`. +If no language is specified, Python is used. + +You can reference previously defined variables, imports, and functions in the code. + +**Arguments**: + +- `code`: Code to execute +- `language`: Language to use for code execution. If not defined, the default Python context is used. +- `on_stdout`: Callback for stdout messages +- `on_stderr`: Callback for stderr messages +- `on_result`: Callback for the `Result` object +- `on_error`: Callback for the `ExecutionError` object +- `envs`: Custom environment variables +- `timeout`: Timeout for the code execution in **seconds** +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`Execution` result object + + + +### run\_code + +```python +@overload +def run_code(code: str, + context: Optional[Context] = None, + on_stdout: Optional[OutputHandler[OutputMessage]] = None, + on_stderr: Optional[OutputHandler[OutputMessage]] = None, + on_result: Optional[OutputHandler[Result]] = None, + on_error: Optional[OutputHandler[ExecutionError]] = None, + envs: Optional[Dict[str, str]] = None, + timeout: Optional[float] = None, + request_timeout: Optional[float] = None) -> Execution +``` + +Runs the code in the specified context, if not specified, the default context is used. + +Specify the `language` or `context` option to run the code as a different language or in a different `Context`. + +You can reference previously defined variables, imports, and functions in the code. + +**Arguments**: + +- `code`: Code to execute +- `context`: Concrete context to run the code in. If not specified, the default context for the language is used. It's mutually exclusive with the language. +- `on_stdout`: Callback for stdout messages +- `on_stderr`: Callback for stderr messages +- `on_result`: Callback for the `Result` object +- `on_error`: Callback for the `ExecutionError` object +- `envs`: Custom environment variables +- `timeout`: Timeout for the code execution in **seconds** +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`Execution` result object + + + +### create\_code\_context + +```python +def create_code_context(cwd: Optional[str] = None, + language: Optional[str] = None, + request_timeout: Optional[float] = None) -> Context +``` + +Creates a new context to run code in. + +**Arguments**: + +- `cwd`: Set the current working directory for the context, defaults to `/home/user` +- `language`: Language of the context. If not specified, defaults to Python +- `request_timeout`: Timeout for the request in **milliseconds** + +**Returns**: + +Context object + + + +### remove\_code\_context + +```python +def remove_code_context(context: Union[Context, str]) -> None +``` + +Removes a context. + +**Arguments**: + +- `context`: Context to remove. Can be a Context object or a context ID string. + +**Returns**: + +None + + + +### list\_code\_contexts + +```python +def list_code_contexts() -> List[Context] +``` + +List all contexts. + +**Returns**: + +List of contexts. + + + +### restart\_code\_context + +```python +def restart_code_context(context: Union[Context, str]) -> None +``` + +Restart a context. + +**Arguments**: + +- `context`: Context to restart. Can be a Context object or a context ID string. + +**Returns**: + +None + + + + + + diff --git a/docs/sdk-reference/desktop-js-sdk/v2.1.0/sandbox.mdx b/docs/sdk-reference/desktop-js-sdk/v2.1.0/sandbox.mdx new file mode 100644 index 0000000..890b05b --- /dev/null +++ b/docs/sdk-reference/desktop-js-sdk/v2.1.0/sandbox.mdx @@ -0,0 +1,697 @@ +--- +sidebarTitle: "Sandbox" +mode: "center" +--- + +### Sandbox + +#### Properties + +| Property | Modifier | Type | Default value | +| ------ | ------ | ------ | ------ | +| `display` | `public` | `string` | `':0'` | +| `stream` | `public` | `VNCServer` | `undefined` | + +#### Methods + +### doubleClick() + +```ts +doubleClick(x?: number, y?: number): Promise +``` + +Double left click on the mouse position. + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `x`? | `number` | +| `y`? | `number` | + +###### Returns + +`Promise`\<`void`\> + +### drag() + +```ts +drag(from: [number, number], to: [number, number]): Promise +``` + +Drag the mouse from the given position to the given position. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `from` | [`number`, `number`] | The starting position. | +| `to` | [`number`, `number`] | The ending position. | + +###### Returns + +`Promise`\<`void`\> + +### getApplicationWindows() + +```ts +getApplicationWindows(application: string): Promise +``` + +Get the window ID of the window with the given title. + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `application` | `string` | + +###### Returns + +`Promise`\<`string`[]\> + +The ID of the window. + +### getCurrentWindowId() + +```ts +getCurrentWindowId(): Promise +``` + +Get the current window ID. + +###### Returns + +`Promise`\<`string`\> + +The ID of the current window. + +### getCursorPosition() + +```ts +getCursorPosition(): Promise +``` + +Get the current cursor position. + +###### Returns + +`Promise`\<`CursorPosition`\> + +A object with the x and y coordinates + +###### Throws + +Error if cursor position cannot be determined + +### getScreenSize() + +```ts +getScreenSize(): Promise +``` + +Get the current screen size. + +###### Returns + +`Promise`\<`ScreenSize`\> + +An ScreenSize object + +###### Throws + +Error if screen size cannot be determined + +### getWindowTitle() + +```ts +getWindowTitle(windowId: string): Promise +``` + +Get the title of the window with the given ID. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `windowId` | `string` | The ID of the window. | + +###### Returns + +`Promise`\<`string`\> + +The title of the window. + +### launch() + +```ts +launch(application: string, uri?: string): Promise +``` + +Launch an application. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `application` | `string` | The application to launch. | +| `uri`? | `string` | The URI to open in the application. | + +###### Returns + +`Promise`\<`void`\> + +### leftClick() + +```ts +leftClick(x?: number, y?: number): Promise +``` + +Left click on the mouse position. + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `x`? | `number` | +| `y`? | `number` | + +###### Returns + +`Promise`\<`void`\> + +### middleClick() + +```ts +middleClick(x?: number, y?: number): Promise +``` + +Middle click on the mouse position. + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `x`? | `number` | +| `y`? | `number` | + +###### Returns + +`Promise`\<`void`\> + +### mousePress() + +```ts +mousePress(button: "left" | "right" | "middle"): Promise +``` + +Press the mouse button. + +###### Parameters + +| Parameter | Type | Default value | +| ------ | ------ | ------ | +| `button` | `"left"` \| `"right"` \| `"middle"` | `'left'` | + +###### Returns + +`Promise`\<`void`\> + +### mouseRelease() + +```ts +mouseRelease(button: "left" | "right" | "middle"): Promise +``` + +Release the mouse button. + +###### Parameters + +| Parameter | Type | Default value | +| ------ | ------ | ------ | +| `button` | `"left"` \| `"right"` \| `"middle"` | `'left'` | + +###### Returns + +`Promise`\<`void`\> + +### moveMouse() + +```ts +moveMouse(x: number, y: number): Promise +``` + +Move the mouse to the given coordinates. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `x` | `number` | The x coordinate. | +| `y` | `number` | The y coordinate. | + +###### Returns + +`Promise`\<`void`\> + +### open() + +```ts +open(fileOrUrl: string): Promise +``` + +Open a file or a URL in the default application. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `fileOrUrl` | `string` | The file or URL to open. | + +###### Returns + +`Promise`\<`void`\> + +### press() + +```ts +press(key: string | string[]): Promise +``` + +Press a key. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `key` | `string` \| `string`[] | The key to press (e.g. "enter", "space", "backspace", etc.). Can be a single key or an array of keys. | + +###### Returns + +`Promise`\<`void`\> + +### rightClick() + +```ts +rightClick(x?: number, y?: number): Promise +``` + +Right click on the mouse position. + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `x`? | `number` | +| `y`? | `number` | + +###### Returns + +`Promise`\<`void`\> + +### screenshot() + +###### screenshot() + +```ts +screenshot(): Promise> +``` + +Take a screenshot and save it to the given name. + +###### Returns + +`Promise`\<`Uint8Array`\<`ArrayBufferLike`\>\> + +A Uint8Array bytes representation of the screenshot. + +###### screenshot(format) + +```ts +screenshot(format: "bytes"): Promise> +``` + +Take a screenshot and save it to the given name. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `format` | `"bytes"` | The format of the screenshot. | + +###### Returns + +`Promise`\<`Uint8Array`\<`ArrayBufferLike`\>\> + +A Uint8Array bytes representation of the screenshot. + +###### screenshot(format) + +```ts +screenshot(format: "blob"): Promise +``` + +Take a screenshot and save it to the given name. + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `format` | `"blob"` | + +###### Returns + +`Promise`\<`Blob`\> + +A Blob representation of the screenshot. + +###### screenshot(format) + +```ts +screenshot(format: "stream"): Promise>> +``` + +Take a screenshot and save it to the given name. + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `format` | `"stream"` | + +###### Returns + +`Promise`\<`ReadableStream`\<`Uint8Array`\<`ArrayBufferLike`\>\>\> + +A ReadableStream of bytes representation of the screenshot. + +### scroll() + +```ts +scroll(direction: "down" | "up", amount: number): Promise +``` + +Scroll the mouse wheel by the given amount. + +###### Parameters + +| Parameter | Type | Default value | Description | +| ------ | ------ | ------ | ------ | +| `direction` | `"down"` \| `"up"` | `'down'` | The direction to scroll. Can be "up" or "down". | +| `amount` | `number` | `1` | The amount to scroll. | + +###### Returns + +`Promise`\<`void`\> + +### wait() + +```ts +wait(ms: number): Promise +``` + +Wait for the given amount of time. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `ms` | `number` | The amount of time to wait in milliseconds. | + +###### Returns + +`Promise`\<`void`\> + +### waitAndVerify() + +```ts +waitAndVerify( + cmd: string, + onResult: (result: CommandResult) => boolean, + timeout: number, +interval: number): Promise +``` + +Wait for a command to return a specific result. + +###### Parameters + +| Parameter | Type | Default value | Description | +| ------ | ------ | ------ | ------ | +| `cmd` | `string` | `undefined` | The command to run. | +| `onResult` | (`result`: `CommandResult`) => `boolean` | `undefined` | The function to check the result of the command. | +| `timeout` | `number` | `10` | The maximum time to wait for the command to return the result. | +| `interval` | `number` | `0.5` | The interval to wait between checks. | + +###### Returns + +`Promise`\<`boolean`\> + +`true` if the command returned the result within the timeout, otherwise `false`. + +### write() + +```ts +write(text: string, options: object): Promise +``` + +Write the given text at the current cursor position. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `text` | `string` | The text to write. | +| `options` | `object` | An object containing the chunk size and delay between each chunk of text. | +| `options.chunkSize` | `number` | The size of each chunk of text to write. Default is 25 characters. | +| `options.delayInMs` | `number` | The delay between each chunk of text. Default is 75 ms. | + +###### Returns + +`Promise`\<`void`\> + +### betaCreate() + +###### betaCreate(this, opts) + +```ts +static betaCreate(this: S, opts?: SandboxBetaCreateOpts): Promise> +``` + +Create a new sandbox from the default `desktop` sandbox template. + +###### Type Parameters + +| Type Parameter | +| ------ | +| `S` *extends* *typeof* `Sandbox` | + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `this` | `S` | - | +| `opts`? | `SandboxBetaCreateOpts` | connection options. | + +###### Returns + +`Promise`\<`InstanceType`\<`S`\>\> + +sandbox instance for the new sandbox. + +###### Example + +```ts +const sandbox = await Sandbox.create() +``` + +###### Constructs + +Sandbox + +###### betaCreate(this, template, opts) + +```ts +static betaCreate( + this: S, + template: string, +opts?: SandboxBetaCreateOpts): Promise> +``` + +Create a new sandbox from the specified sandbox template. + +###### Type Parameters + +| Type Parameter | +| ------ | +| `S` *extends* *typeof* `Sandbox` | + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `this` | `S` | - | +| `template` | `string` | sandbox template name or ID. | +| `opts`? | `SandboxBetaCreateOpts` | connection options. | + +###### Returns + +`Promise`\<`InstanceType`\<`S`\>\> + +sandbox instance for the new sandbox. + +###### Example + +```ts +const sandbox = await Sandbox.create('') +``` + +###### Constructs + +Sandbox + +### create() + +###### create(this, opts) + +```ts +static create(this: S, opts?: SandboxOpts): Promise> +``` + +Create a new sandbox from the default `desktop` sandbox template. + +###### Type Parameters + +| Type Parameter | +| ------ | +| `S` *extends* *typeof* `Sandbox` | + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `this` | `S` | - | +| `opts`? | `SandboxOpts` | connection options. | + +###### Returns + +`Promise`\<`InstanceType`\<`S`\>\> + +sandbox instance for the new sandbox. + +###### Example + +```ts +const sandbox = await Sandbox.create() +``` + +###### Constructs + +Sandbox + +###### create(this, template, opts) + +```ts +static create( + this: S, + template: string, +opts?: SandboxOpts): Promise> +``` + +Create a new sandbox from the specified sandbox template. + +###### Type Parameters + +| Type Parameter | +| ------ | +| `S` *extends* *typeof* `Sandbox` | + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `this` | `S` | - | +| `template` | `string` | sandbox template name or ID. | +| `opts`? | `SandboxOpts` | connection options. | + +###### Returns + +`Promise`\<`InstanceType`\<`S`\>\> + +sandbox instance for the new sandbox. + +###### Example + +```ts +const sandbox = await Sandbox.create('') +``` + +###### Constructs + +Sandbox + +## Interfaces + +### SandboxBetaCreateOpts + +Configuration options for the Sandbox environment. + SandboxOpts + +#### Properties + +### display? + +```ts +optional display: string; +``` + +Display identifier. + +### dpi? + +```ts +optional dpi: number; +``` + +Dots per inch (DPI) setting for the display. + +### resolution? + +```ts +optional resolution: [number, number]; +``` + +The screen resolution in pixels, specified as [width, height]. + +*** + +### SandboxOpts + +Configuration options for the Sandbox environment. + SandboxOpts + +#### Properties + +### display? + +```ts +optional display: string; +``` + +Display identifier. + +### dpi? + +```ts +optional dpi: number; +``` + +Dots per inch (DPI) setting for the display. + +### resolution? + +```ts +optional resolution: [number, number]; +``` + +The screen resolution in pixels, specified as [width, height]. diff --git a/docs/sdk-reference/desktop-js-sdk/v2.2.0/sandbox.mdx b/docs/sdk-reference/desktop-js-sdk/v2.2.0/sandbox.mdx new file mode 100644 index 0000000..890b05b --- /dev/null +++ b/docs/sdk-reference/desktop-js-sdk/v2.2.0/sandbox.mdx @@ -0,0 +1,697 @@ +--- +sidebarTitle: "Sandbox" +mode: "center" +--- + +### Sandbox + +#### Properties + +| Property | Modifier | Type | Default value | +| ------ | ------ | ------ | ------ | +| `display` | `public` | `string` | `':0'` | +| `stream` | `public` | `VNCServer` | `undefined` | + +#### Methods + +### doubleClick() + +```ts +doubleClick(x?: number, y?: number): Promise +``` + +Double left click on the mouse position. + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `x`? | `number` | +| `y`? | `number` | + +###### Returns + +`Promise`\<`void`\> + +### drag() + +```ts +drag(from: [number, number], to: [number, number]): Promise +``` + +Drag the mouse from the given position to the given position. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `from` | [`number`, `number`] | The starting position. | +| `to` | [`number`, `number`] | The ending position. | + +###### Returns + +`Promise`\<`void`\> + +### getApplicationWindows() + +```ts +getApplicationWindows(application: string): Promise +``` + +Get the window ID of the window with the given title. + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `application` | `string` | + +###### Returns + +`Promise`\<`string`[]\> + +The ID of the window. + +### getCurrentWindowId() + +```ts +getCurrentWindowId(): Promise +``` + +Get the current window ID. + +###### Returns + +`Promise`\<`string`\> + +The ID of the current window. + +### getCursorPosition() + +```ts +getCursorPosition(): Promise +``` + +Get the current cursor position. + +###### Returns + +`Promise`\<`CursorPosition`\> + +A object with the x and y coordinates + +###### Throws + +Error if cursor position cannot be determined + +### getScreenSize() + +```ts +getScreenSize(): Promise +``` + +Get the current screen size. + +###### Returns + +`Promise`\<`ScreenSize`\> + +An ScreenSize object + +###### Throws + +Error if screen size cannot be determined + +### getWindowTitle() + +```ts +getWindowTitle(windowId: string): Promise +``` + +Get the title of the window with the given ID. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `windowId` | `string` | The ID of the window. | + +###### Returns + +`Promise`\<`string`\> + +The title of the window. + +### launch() + +```ts +launch(application: string, uri?: string): Promise +``` + +Launch an application. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `application` | `string` | The application to launch. | +| `uri`? | `string` | The URI to open in the application. | + +###### Returns + +`Promise`\<`void`\> + +### leftClick() + +```ts +leftClick(x?: number, y?: number): Promise +``` + +Left click on the mouse position. + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `x`? | `number` | +| `y`? | `number` | + +###### Returns + +`Promise`\<`void`\> + +### middleClick() + +```ts +middleClick(x?: number, y?: number): Promise +``` + +Middle click on the mouse position. + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `x`? | `number` | +| `y`? | `number` | + +###### Returns + +`Promise`\<`void`\> + +### mousePress() + +```ts +mousePress(button: "left" | "right" | "middle"): Promise +``` + +Press the mouse button. + +###### Parameters + +| Parameter | Type | Default value | +| ------ | ------ | ------ | +| `button` | `"left"` \| `"right"` \| `"middle"` | `'left'` | + +###### Returns + +`Promise`\<`void`\> + +### mouseRelease() + +```ts +mouseRelease(button: "left" | "right" | "middle"): Promise +``` + +Release the mouse button. + +###### Parameters + +| Parameter | Type | Default value | +| ------ | ------ | ------ | +| `button` | `"left"` \| `"right"` \| `"middle"` | `'left'` | + +###### Returns + +`Promise`\<`void`\> + +### moveMouse() + +```ts +moveMouse(x: number, y: number): Promise +``` + +Move the mouse to the given coordinates. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `x` | `number` | The x coordinate. | +| `y` | `number` | The y coordinate. | + +###### Returns + +`Promise`\<`void`\> + +### open() + +```ts +open(fileOrUrl: string): Promise +``` + +Open a file or a URL in the default application. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `fileOrUrl` | `string` | The file or URL to open. | + +###### Returns + +`Promise`\<`void`\> + +### press() + +```ts +press(key: string | string[]): Promise +``` + +Press a key. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `key` | `string` \| `string`[] | The key to press (e.g. "enter", "space", "backspace", etc.). Can be a single key or an array of keys. | + +###### Returns + +`Promise`\<`void`\> + +### rightClick() + +```ts +rightClick(x?: number, y?: number): Promise +``` + +Right click on the mouse position. + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `x`? | `number` | +| `y`? | `number` | + +###### Returns + +`Promise`\<`void`\> + +### screenshot() + +###### screenshot() + +```ts +screenshot(): Promise> +``` + +Take a screenshot and save it to the given name. + +###### Returns + +`Promise`\<`Uint8Array`\<`ArrayBufferLike`\>\> + +A Uint8Array bytes representation of the screenshot. + +###### screenshot(format) + +```ts +screenshot(format: "bytes"): Promise> +``` + +Take a screenshot and save it to the given name. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `format` | `"bytes"` | The format of the screenshot. | + +###### Returns + +`Promise`\<`Uint8Array`\<`ArrayBufferLike`\>\> + +A Uint8Array bytes representation of the screenshot. + +###### screenshot(format) + +```ts +screenshot(format: "blob"): Promise +``` + +Take a screenshot and save it to the given name. + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `format` | `"blob"` | + +###### Returns + +`Promise`\<`Blob`\> + +A Blob representation of the screenshot. + +###### screenshot(format) + +```ts +screenshot(format: "stream"): Promise>> +``` + +Take a screenshot and save it to the given name. + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `format` | `"stream"` | + +###### Returns + +`Promise`\<`ReadableStream`\<`Uint8Array`\<`ArrayBufferLike`\>\>\> + +A ReadableStream of bytes representation of the screenshot. + +### scroll() + +```ts +scroll(direction: "down" | "up", amount: number): Promise +``` + +Scroll the mouse wheel by the given amount. + +###### Parameters + +| Parameter | Type | Default value | Description | +| ------ | ------ | ------ | ------ | +| `direction` | `"down"` \| `"up"` | `'down'` | The direction to scroll. Can be "up" or "down". | +| `amount` | `number` | `1` | The amount to scroll. | + +###### Returns + +`Promise`\<`void`\> + +### wait() + +```ts +wait(ms: number): Promise +``` + +Wait for the given amount of time. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `ms` | `number` | The amount of time to wait in milliseconds. | + +###### Returns + +`Promise`\<`void`\> + +### waitAndVerify() + +```ts +waitAndVerify( + cmd: string, + onResult: (result: CommandResult) => boolean, + timeout: number, +interval: number): Promise +``` + +Wait for a command to return a specific result. + +###### Parameters + +| Parameter | Type | Default value | Description | +| ------ | ------ | ------ | ------ | +| `cmd` | `string` | `undefined` | The command to run. | +| `onResult` | (`result`: `CommandResult`) => `boolean` | `undefined` | The function to check the result of the command. | +| `timeout` | `number` | `10` | The maximum time to wait for the command to return the result. | +| `interval` | `number` | `0.5` | The interval to wait between checks. | + +###### Returns + +`Promise`\<`boolean`\> + +`true` if the command returned the result within the timeout, otherwise `false`. + +### write() + +```ts +write(text: string, options: object): Promise +``` + +Write the given text at the current cursor position. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `text` | `string` | The text to write. | +| `options` | `object` | An object containing the chunk size and delay between each chunk of text. | +| `options.chunkSize` | `number` | The size of each chunk of text to write. Default is 25 characters. | +| `options.delayInMs` | `number` | The delay between each chunk of text. Default is 75 ms. | + +###### Returns + +`Promise`\<`void`\> + +### betaCreate() + +###### betaCreate(this, opts) + +```ts +static betaCreate(this: S, opts?: SandboxBetaCreateOpts): Promise> +``` + +Create a new sandbox from the default `desktop` sandbox template. + +###### Type Parameters + +| Type Parameter | +| ------ | +| `S` *extends* *typeof* `Sandbox` | + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `this` | `S` | - | +| `opts`? | `SandboxBetaCreateOpts` | connection options. | + +###### Returns + +`Promise`\<`InstanceType`\<`S`\>\> + +sandbox instance for the new sandbox. + +###### Example + +```ts +const sandbox = await Sandbox.create() +``` + +###### Constructs + +Sandbox + +###### betaCreate(this, template, opts) + +```ts +static betaCreate( + this: S, + template: string, +opts?: SandboxBetaCreateOpts): Promise> +``` + +Create a new sandbox from the specified sandbox template. + +###### Type Parameters + +| Type Parameter | +| ------ | +| `S` *extends* *typeof* `Sandbox` | + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `this` | `S` | - | +| `template` | `string` | sandbox template name or ID. | +| `opts`? | `SandboxBetaCreateOpts` | connection options. | + +###### Returns + +`Promise`\<`InstanceType`\<`S`\>\> + +sandbox instance for the new sandbox. + +###### Example + +```ts +const sandbox = await Sandbox.create('') +``` + +###### Constructs + +Sandbox + +### create() + +###### create(this, opts) + +```ts +static create(this: S, opts?: SandboxOpts): Promise> +``` + +Create a new sandbox from the default `desktop` sandbox template. + +###### Type Parameters + +| Type Parameter | +| ------ | +| `S` *extends* *typeof* `Sandbox` | + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `this` | `S` | - | +| `opts`? | `SandboxOpts` | connection options. | + +###### Returns + +`Promise`\<`InstanceType`\<`S`\>\> + +sandbox instance for the new sandbox. + +###### Example + +```ts +const sandbox = await Sandbox.create() +``` + +###### Constructs + +Sandbox + +###### create(this, template, opts) + +```ts +static create( + this: S, + template: string, +opts?: SandboxOpts): Promise> +``` + +Create a new sandbox from the specified sandbox template. + +###### Type Parameters + +| Type Parameter | +| ------ | +| `S` *extends* *typeof* `Sandbox` | + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `this` | `S` | - | +| `template` | `string` | sandbox template name or ID. | +| `opts`? | `SandboxOpts` | connection options. | + +###### Returns + +`Promise`\<`InstanceType`\<`S`\>\> + +sandbox instance for the new sandbox. + +###### Example + +```ts +const sandbox = await Sandbox.create('') +``` + +###### Constructs + +Sandbox + +## Interfaces + +### SandboxBetaCreateOpts + +Configuration options for the Sandbox environment. + SandboxOpts + +#### Properties + +### display? + +```ts +optional display: string; +``` + +Display identifier. + +### dpi? + +```ts +optional dpi: number; +``` + +Dots per inch (DPI) setting for the display. + +### resolution? + +```ts +optional resolution: [number, number]; +``` + +The screen resolution in pixels, specified as [width, height]. + +*** + +### SandboxOpts + +Configuration options for the Sandbox environment. + SandboxOpts + +#### Properties + +### display? + +```ts +optional display: string; +``` + +Display identifier. + +### dpi? + +```ts +optional dpi: number; +``` + +Dots per inch (DPI) setting for the display. + +### resolution? + +```ts +optional resolution: [number, number]; +``` + +The screen resolution in pixels, specified as [width, height]. diff --git a/docs/sdk-reference/desktop-js-sdk/v2.2.1/sandbox.mdx b/docs/sdk-reference/desktop-js-sdk/v2.2.1/sandbox.mdx new file mode 100644 index 0000000..890b05b --- /dev/null +++ b/docs/sdk-reference/desktop-js-sdk/v2.2.1/sandbox.mdx @@ -0,0 +1,697 @@ +--- +sidebarTitle: "Sandbox" +mode: "center" +--- + +### Sandbox + +#### Properties + +| Property | Modifier | Type | Default value | +| ------ | ------ | ------ | ------ | +| `display` | `public` | `string` | `':0'` | +| `stream` | `public` | `VNCServer` | `undefined` | + +#### Methods + +### doubleClick() + +```ts +doubleClick(x?: number, y?: number): Promise +``` + +Double left click on the mouse position. + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `x`? | `number` | +| `y`? | `number` | + +###### Returns + +`Promise`\<`void`\> + +### drag() + +```ts +drag(from: [number, number], to: [number, number]): Promise +``` + +Drag the mouse from the given position to the given position. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `from` | [`number`, `number`] | The starting position. | +| `to` | [`number`, `number`] | The ending position. | + +###### Returns + +`Promise`\<`void`\> + +### getApplicationWindows() + +```ts +getApplicationWindows(application: string): Promise +``` + +Get the window ID of the window with the given title. + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `application` | `string` | + +###### Returns + +`Promise`\<`string`[]\> + +The ID of the window. + +### getCurrentWindowId() + +```ts +getCurrentWindowId(): Promise +``` + +Get the current window ID. + +###### Returns + +`Promise`\<`string`\> + +The ID of the current window. + +### getCursorPosition() + +```ts +getCursorPosition(): Promise +``` + +Get the current cursor position. + +###### Returns + +`Promise`\<`CursorPosition`\> + +A object with the x and y coordinates + +###### Throws + +Error if cursor position cannot be determined + +### getScreenSize() + +```ts +getScreenSize(): Promise +``` + +Get the current screen size. + +###### Returns + +`Promise`\<`ScreenSize`\> + +An ScreenSize object + +###### Throws + +Error if screen size cannot be determined + +### getWindowTitle() + +```ts +getWindowTitle(windowId: string): Promise +``` + +Get the title of the window with the given ID. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `windowId` | `string` | The ID of the window. | + +###### Returns + +`Promise`\<`string`\> + +The title of the window. + +### launch() + +```ts +launch(application: string, uri?: string): Promise +``` + +Launch an application. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `application` | `string` | The application to launch. | +| `uri`? | `string` | The URI to open in the application. | + +###### Returns + +`Promise`\<`void`\> + +### leftClick() + +```ts +leftClick(x?: number, y?: number): Promise +``` + +Left click on the mouse position. + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `x`? | `number` | +| `y`? | `number` | + +###### Returns + +`Promise`\<`void`\> + +### middleClick() + +```ts +middleClick(x?: number, y?: number): Promise +``` + +Middle click on the mouse position. + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `x`? | `number` | +| `y`? | `number` | + +###### Returns + +`Promise`\<`void`\> + +### mousePress() + +```ts +mousePress(button: "left" | "right" | "middle"): Promise +``` + +Press the mouse button. + +###### Parameters + +| Parameter | Type | Default value | +| ------ | ------ | ------ | +| `button` | `"left"` \| `"right"` \| `"middle"` | `'left'` | + +###### Returns + +`Promise`\<`void`\> + +### mouseRelease() + +```ts +mouseRelease(button: "left" | "right" | "middle"): Promise +``` + +Release the mouse button. + +###### Parameters + +| Parameter | Type | Default value | +| ------ | ------ | ------ | +| `button` | `"left"` \| `"right"` \| `"middle"` | `'left'` | + +###### Returns + +`Promise`\<`void`\> + +### moveMouse() + +```ts +moveMouse(x: number, y: number): Promise +``` + +Move the mouse to the given coordinates. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `x` | `number` | The x coordinate. | +| `y` | `number` | The y coordinate. | + +###### Returns + +`Promise`\<`void`\> + +### open() + +```ts +open(fileOrUrl: string): Promise +``` + +Open a file or a URL in the default application. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `fileOrUrl` | `string` | The file or URL to open. | + +###### Returns + +`Promise`\<`void`\> + +### press() + +```ts +press(key: string | string[]): Promise +``` + +Press a key. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `key` | `string` \| `string`[] | The key to press (e.g. "enter", "space", "backspace", etc.). Can be a single key or an array of keys. | + +###### Returns + +`Promise`\<`void`\> + +### rightClick() + +```ts +rightClick(x?: number, y?: number): Promise +``` + +Right click on the mouse position. + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `x`? | `number` | +| `y`? | `number` | + +###### Returns + +`Promise`\<`void`\> + +### screenshot() + +###### screenshot() + +```ts +screenshot(): Promise> +``` + +Take a screenshot and save it to the given name. + +###### Returns + +`Promise`\<`Uint8Array`\<`ArrayBufferLike`\>\> + +A Uint8Array bytes representation of the screenshot. + +###### screenshot(format) + +```ts +screenshot(format: "bytes"): Promise> +``` + +Take a screenshot and save it to the given name. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `format` | `"bytes"` | The format of the screenshot. | + +###### Returns + +`Promise`\<`Uint8Array`\<`ArrayBufferLike`\>\> + +A Uint8Array bytes representation of the screenshot. + +###### screenshot(format) + +```ts +screenshot(format: "blob"): Promise +``` + +Take a screenshot and save it to the given name. + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `format` | `"blob"` | + +###### Returns + +`Promise`\<`Blob`\> + +A Blob representation of the screenshot. + +###### screenshot(format) + +```ts +screenshot(format: "stream"): Promise>> +``` + +Take a screenshot and save it to the given name. + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `format` | `"stream"` | + +###### Returns + +`Promise`\<`ReadableStream`\<`Uint8Array`\<`ArrayBufferLike`\>\>\> + +A ReadableStream of bytes representation of the screenshot. + +### scroll() + +```ts +scroll(direction: "down" | "up", amount: number): Promise +``` + +Scroll the mouse wheel by the given amount. + +###### Parameters + +| Parameter | Type | Default value | Description | +| ------ | ------ | ------ | ------ | +| `direction` | `"down"` \| `"up"` | `'down'` | The direction to scroll. Can be "up" or "down". | +| `amount` | `number` | `1` | The amount to scroll. | + +###### Returns + +`Promise`\<`void`\> + +### wait() + +```ts +wait(ms: number): Promise +``` + +Wait for the given amount of time. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `ms` | `number` | The amount of time to wait in milliseconds. | + +###### Returns + +`Promise`\<`void`\> + +### waitAndVerify() + +```ts +waitAndVerify( + cmd: string, + onResult: (result: CommandResult) => boolean, + timeout: number, +interval: number): Promise +``` + +Wait for a command to return a specific result. + +###### Parameters + +| Parameter | Type | Default value | Description | +| ------ | ------ | ------ | ------ | +| `cmd` | `string` | `undefined` | The command to run. | +| `onResult` | (`result`: `CommandResult`) => `boolean` | `undefined` | The function to check the result of the command. | +| `timeout` | `number` | `10` | The maximum time to wait for the command to return the result. | +| `interval` | `number` | `0.5` | The interval to wait between checks. | + +###### Returns + +`Promise`\<`boolean`\> + +`true` if the command returned the result within the timeout, otherwise `false`. + +### write() + +```ts +write(text: string, options: object): Promise +``` + +Write the given text at the current cursor position. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `text` | `string` | The text to write. | +| `options` | `object` | An object containing the chunk size and delay between each chunk of text. | +| `options.chunkSize` | `number` | The size of each chunk of text to write. Default is 25 characters. | +| `options.delayInMs` | `number` | The delay between each chunk of text. Default is 75 ms. | + +###### Returns + +`Promise`\<`void`\> + +### betaCreate() + +###### betaCreate(this, opts) + +```ts +static betaCreate(this: S, opts?: SandboxBetaCreateOpts): Promise> +``` + +Create a new sandbox from the default `desktop` sandbox template. + +###### Type Parameters + +| Type Parameter | +| ------ | +| `S` *extends* *typeof* `Sandbox` | + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `this` | `S` | - | +| `opts`? | `SandboxBetaCreateOpts` | connection options. | + +###### Returns + +`Promise`\<`InstanceType`\<`S`\>\> + +sandbox instance for the new sandbox. + +###### Example + +```ts +const sandbox = await Sandbox.create() +``` + +###### Constructs + +Sandbox + +###### betaCreate(this, template, opts) + +```ts +static betaCreate( + this: S, + template: string, +opts?: SandboxBetaCreateOpts): Promise> +``` + +Create a new sandbox from the specified sandbox template. + +###### Type Parameters + +| Type Parameter | +| ------ | +| `S` *extends* *typeof* `Sandbox` | + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `this` | `S` | - | +| `template` | `string` | sandbox template name or ID. | +| `opts`? | `SandboxBetaCreateOpts` | connection options. | + +###### Returns + +`Promise`\<`InstanceType`\<`S`\>\> + +sandbox instance for the new sandbox. + +###### Example + +```ts +const sandbox = await Sandbox.create('') +``` + +###### Constructs + +Sandbox + +### create() + +###### create(this, opts) + +```ts +static create(this: S, opts?: SandboxOpts): Promise> +``` + +Create a new sandbox from the default `desktop` sandbox template. + +###### Type Parameters + +| Type Parameter | +| ------ | +| `S` *extends* *typeof* `Sandbox` | + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `this` | `S` | - | +| `opts`? | `SandboxOpts` | connection options. | + +###### Returns + +`Promise`\<`InstanceType`\<`S`\>\> + +sandbox instance for the new sandbox. + +###### Example + +```ts +const sandbox = await Sandbox.create() +``` + +###### Constructs + +Sandbox + +###### create(this, template, opts) + +```ts +static create( + this: S, + template: string, +opts?: SandboxOpts): Promise> +``` + +Create a new sandbox from the specified sandbox template. + +###### Type Parameters + +| Type Parameter | +| ------ | +| `S` *extends* *typeof* `Sandbox` | + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `this` | `S` | - | +| `template` | `string` | sandbox template name or ID. | +| `opts`? | `SandboxOpts` | connection options. | + +###### Returns + +`Promise`\<`InstanceType`\<`S`\>\> + +sandbox instance for the new sandbox. + +###### Example + +```ts +const sandbox = await Sandbox.create('') +``` + +###### Constructs + +Sandbox + +## Interfaces + +### SandboxBetaCreateOpts + +Configuration options for the Sandbox environment. + SandboxOpts + +#### Properties + +### display? + +```ts +optional display: string; +``` + +Display identifier. + +### dpi? + +```ts +optional dpi: number; +``` + +Dots per inch (DPI) setting for the display. + +### resolution? + +```ts +optional resolution: [number, number]; +``` + +The screen resolution in pixels, specified as [width, height]. + +*** + +### SandboxOpts + +Configuration options for the Sandbox environment. + SandboxOpts + +#### Properties + +### display? + +```ts +optional display: string; +``` + +Display identifier. + +### dpi? + +```ts +optional dpi: number; +``` + +Dots per inch (DPI) setting for the display. + +### resolution? + +```ts +optional resolution: [number, number]; +``` + +The screen resolution in pixels, specified as [width, height]. diff --git a/docs/sdk-reference/desktop-js-sdk/v2.2.2/sandbox.mdx b/docs/sdk-reference/desktop-js-sdk/v2.2.2/sandbox.mdx new file mode 100644 index 0000000..890b05b --- /dev/null +++ b/docs/sdk-reference/desktop-js-sdk/v2.2.2/sandbox.mdx @@ -0,0 +1,697 @@ +--- +sidebarTitle: "Sandbox" +mode: "center" +--- + +### Sandbox + +#### Properties + +| Property | Modifier | Type | Default value | +| ------ | ------ | ------ | ------ | +| `display` | `public` | `string` | `':0'` | +| `stream` | `public` | `VNCServer` | `undefined` | + +#### Methods + +### doubleClick() + +```ts +doubleClick(x?: number, y?: number): Promise +``` + +Double left click on the mouse position. + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `x`? | `number` | +| `y`? | `number` | + +###### Returns + +`Promise`\<`void`\> + +### drag() + +```ts +drag(from: [number, number], to: [number, number]): Promise +``` + +Drag the mouse from the given position to the given position. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `from` | [`number`, `number`] | The starting position. | +| `to` | [`number`, `number`] | The ending position. | + +###### Returns + +`Promise`\<`void`\> + +### getApplicationWindows() + +```ts +getApplicationWindows(application: string): Promise +``` + +Get the window ID of the window with the given title. + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `application` | `string` | + +###### Returns + +`Promise`\<`string`[]\> + +The ID of the window. + +### getCurrentWindowId() + +```ts +getCurrentWindowId(): Promise +``` + +Get the current window ID. + +###### Returns + +`Promise`\<`string`\> + +The ID of the current window. + +### getCursorPosition() + +```ts +getCursorPosition(): Promise +``` + +Get the current cursor position. + +###### Returns + +`Promise`\<`CursorPosition`\> + +A object with the x and y coordinates + +###### Throws + +Error if cursor position cannot be determined + +### getScreenSize() + +```ts +getScreenSize(): Promise +``` + +Get the current screen size. + +###### Returns + +`Promise`\<`ScreenSize`\> + +An ScreenSize object + +###### Throws + +Error if screen size cannot be determined + +### getWindowTitle() + +```ts +getWindowTitle(windowId: string): Promise +``` + +Get the title of the window with the given ID. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `windowId` | `string` | The ID of the window. | + +###### Returns + +`Promise`\<`string`\> + +The title of the window. + +### launch() + +```ts +launch(application: string, uri?: string): Promise +``` + +Launch an application. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `application` | `string` | The application to launch. | +| `uri`? | `string` | The URI to open in the application. | + +###### Returns + +`Promise`\<`void`\> + +### leftClick() + +```ts +leftClick(x?: number, y?: number): Promise +``` + +Left click on the mouse position. + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `x`? | `number` | +| `y`? | `number` | + +###### Returns + +`Promise`\<`void`\> + +### middleClick() + +```ts +middleClick(x?: number, y?: number): Promise +``` + +Middle click on the mouse position. + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `x`? | `number` | +| `y`? | `number` | + +###### Returns + +`Promise`\<`void`\> + +### mousePress() + +```ts +mousePress(button: "left" | "right" | "middle"): Promise +``` + +Press the mouse button. + +###### Parameters + +| Parameter | Type | Default value | +| ------ | ------ | ------ | +| `button` | `"left"` \| `"right"` \| `"middle"` | `'left'` | + +###### Returns + +`Promise`\<`void`\> + +### mouseRelease() + +```ts +mouseRelease(button: "left" | "right" | "middle"): Promise +``` + +Release the mouse button. + +###### Parameters + +| Parameter | Type | Default value | +| ------ | ------ | ------ | +| `button` | `"left"` \| `"right"` \| `"middle"` | `'left'` | + +###### Returns + +`Promise`\<`void`\> + +### moveMouse() + +```ts +moveMouse(x: number, y: number): Promise +``` + +Move the mouse to the given coordinates. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `x` | `number` | The x coordinate. | +| `y` | `number` | The y coordinate. | + +###### Returns + +`Promise`\<`void`\> + +### open() + +```ts +open(fileOrUrl: string): Promise +``` + +Open a file or a URL in the default application. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `fileOrUrl` | `string` | The file or URL to open. | + +###### Returns + +`Promise`\<`void`\> + +### press() + +```ts +press(key: string | string[]): Promise +``` + +Press a key. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `key` | `string` \| `string`[] | The key to press (e.g. "enter", "space", "backspace", etc.). Can be a single key or an array of keys. | + +###### Returns + +`Promise`\<`void`\> + +### rightClick() + +```ts +rightClick(x?: number, y?: number): Promise +``` + +Right click on the mouse position. + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `x`? | `number` | +| `y`? | `number` | + +###### Returns + +`Promise`\<`void`\> + +### screenshot() + +###### screenshot() + +```ts +screenshot(): Promise> +``` + +Take a screenshot and save it to the given name. + +###### Returns + +`Promise`\<`Uint8Array`\<`ArrayBufferLike`\>\> + +A Uint8Array bytes representation of the screenshot. + +###### screenshot(format) + +```ts +screenshot(format: "bytes"): Promise> +``` + +Take a screenshot and save it to the given name. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `format` | `"bytes"` | The format of the screenshot. | + +###### Returns + +`Promise`\<`Uint8Array`\<`ArrayBufferLike`\>\> + +A Uint8Array bytes representation of the screenshot. + +###### screenshot(format) + +```ts +screenshot(format: "blob"): Promise +``` + +Take a screenshot and save it to the given name. + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `format` | `"blob"` | + +###### Returns + +`Promise`\<`Blob`\> + +A Blob representation of the screenshot. + +###### screenshot(format) + +```ts +screenshot(format: "stream"): Promise>> +``` + +Take a screenshot and save it to the given name. + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `format` | `"stream"` | + +###### Returns + +`Promise`\<`ReadableStream`\<`Uint8Array`\<`ArrayBufferLike`\>\>\> + +A ReadableStream of bytes representation of the screenshot. + +### scroll() + +```ts +scroll(direction: "down" | "up", amount: number): Promise +``` + +Scroll the mouse wheel by the given amount. + +###### Parameters + +| Parameter | Type | Default value | Description | +| ------ | ------ | ------ | ------ | +| `direction` | `"down"` \| `"up"` | `'down'` | The direction to scroll. Can be "up" or "down". | +| `amount` | `number` | `1` | The amount to scroll. | + +###### Returns + +`Promise`\<`void`\> + +### wait() + +```ts +wait(ms: number): Promise +``` + +Wait for the given amount of time. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `ms` | `number` | The amount of time to wait in milliseconds. | + +###### Returns + +`Promise`\<`void`\> + +### waitAndVerify() + +```ts +waitAndVerify( + cmd: string, + onResult: (result: CommandResult) => boolean, + timeout: number, +interval: number): Promise +``` + +Wait for a command to return a specific result. + +###### Parameters + +| Parameter | Type | Default value | Description | +| ------ | ------ | ------ | ------ | +| `cmd` | `string` | `undefined` | The command to run. | +| `onResult` | (`result`: `CommandResult`) => `boolean` | `undefined` | The function to check the result of the command. | +| `timeout` | `number` | `10` | The maximum time to wait for the command to return the result. | +| `interval` | `number` | `0.5` | The interval to wait between checks. | + +###### Returns + +`Promise`\<`boolean`\> + +`true` if the command returned the result within the timeout, otherwise `false`. + +### write() + +```ts +write(text: string, options: object): Promise +``` + +Write the given text at the current cursor position. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `text` | `string` | The text to write. | +| `options` | `object` | An object containing the chunk size and delay between each chunk of text. | +| `options.chunkSize` | `number` | The size of each chunk of text to write. Default is 25 characters. | +| `options.delayInMs` | `number` | The delay between each chunk of text. Default is 75 ms. | + +###### Returns + +`Promise`\<`void`\> + +### betaCreate() + +###### betaCreate(this, opts) + +```ts +static betaCreate(this: S, opts?: SandboxBetaCreateOpts): Promise> +``` + +Create a new sandbox from the default `desktop` sandbox template. + +###### Type Parameters + +| Type Parameter | +| ------ | +| `S` *extends* *typeof* `Sandbox` | + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `this` | `S` | - | +| `opts`? | `SandboxBetaCreateOpts` | connection options. | + +###### Returns + +`Promise`\<`InstanceType`\<`S`\>\> + +sandbox instance for the new sandbox. + +###### Example + +```ts +const sandbox = await Sandbox.create() +``` + +###### Constructs + +Sandbox + +###### betaCreate(this, template, opts) + +```ts +static betaCreate( + this: S, + template: string, +opts?: SandboxBetaCreateOpts): Promise> +``` + +Create a new sandbox from the specified sandbox template. + +###### Type Parameters + +| Type Parameter | +| ------ | +| `S` *extends* *typeof* `Sandbox` | + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `this` | `S` | - | +| `template` | `string` | sandbox template name or ID. | +| `opts`? | `SandboxBetaCreateOpts` | connection options. | + +###### Returns + +`Promise`\<`InstanceType`\<`S`\>\> + +sandbox instance for the new sandbox. + +###### Example + +```ts +const sandbox = await Sandbox.create('') +``` + +###### Constructs + +Sandbox + +### create() + +###### create(this, opts) + +```ts +static create(this: S, opts?: SandboxOpts): Promise> +``` + +Create a new sandbox from the default `desktop` sandbox template. + +###### Type Parameters + +| Type Parameter | +| ------ | +| `S` *extends* *typeof* `Sandbox` | + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `this` | `S` | - | +| `opts`? | `SandboxOpts` | connection options. | + +###### Returns + +`Promise`\<`InstanceType`\<`S`\>\> + +sandbox instance for the new sandbox. + +###### Example + +```ts +const sandbox = await Sandbox.create() +``` + +###### Constructs + +Sandbox + +###### create(this, template, opts) + +```ts +static create( + this: S, + template: string, +opts?: SandboxOpts): Promise> +``` + +Create a new sandbox from the specified sandbox template. + +###### Type Parameters + +| Type Parameter | +| ------ | +| `S` *extends* *typeof* `Sandbox` | + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `this` | `S` | - | +| `template` | `string` | sandbox template name or ID. | +| `opts`? | `SandboxOpts` | connection options. | + +###### Returns + +`Promise`\<`InstanceType`\<`S`\>\> + +sandbox instance for the new sandbox. + +###### Example + +```ts +const sandbox = await Sandbox.create('') +``` + +###### Constructs + +Sandbox + +## Interfaces + +### SandboxBetaCreateOpts + +Configuration options for the Sandbox environment. + SandboxOpts + +#### Properties + +### display? + +```ts +optional display: string; +``` + +Display identifier. + +### dpi? + +```ts +optional dpi: number; +``` + +Dots per inch (DPI) setting for the display. + +### resolution? + +```ts +optional resolution: [number, number]; +``` + +The screen resolution in pixels, specified as [width, height]. + +*** + +### SandboxOpts + +Configuration options for the Sandbox environment. + SandboxOpts + +#### Properties + +### display? + +```ts +optional display: string; +``` + +Display identifier. + +### dpi? + +```ts +optional dpi: number; +``` + +Dots per inch (DPI) setting for the display. + +### resolution? + +```ts +optional resolution: [number, number]; +``` + +The screen resolution in pixels, specified as [width, height]. diff --git a/docs/sdk-reference/desktop-python-sdk/v2.0.0/desktop.mdx b/docs/sdk-reference/desktop-python-sdk/v2.0.0/desktop.mdx new file mode 100644 index 0000000..391f449 --- /dev/null +++ b/docs/sdk-reference/desktop-python-sdk/v2.0.0/desktop.mdx @@ -0,0 +1,371 @@ +--- +sidebarTitle: "Desktop" +mode: "center" +--- + + + + + + + + + +## Sandbox + +```python +class Sandbox(SandboxBase) +``` + + + +### create + +```python +@classmethod +def create(cls, + template: Optional[str] = None, + resolution: Optional[Tuple[int, int]] = None, + dpi: Optional[int] = None, + display: Optional[str] = None, + timeout: Optional[int] = None, + metadata: Optional[Dict[str, str]] = None, + envs: Optional[Dict[str, str]] = None, + secure: bool = True, + allow_internet_access: bool = True, + **opts: Unpack[ApiParams]) -> Self +``` + +Create a new sandbox. + +By default, the sandbox is created from the default `desktop` sandbox template. + +**Arguments**: + +- `template`: Sandbox template name or ID +- `resolution`: Startup the desktop with custom screen resolution. Defaults to (1024, 768) +- `dpi`: Startup the desktop with custom DPI. Defaults to 96 +- `display`: Startup the desktop with custom display. Defaults to ":0" +- `timeout`: Timeout for the sandbox in **seconds**, default to 300 seconds. The maximum time a sandbox can be kept alive is 24 hours (86_400 seconds) for Pro users and 1 hour (3_600 seconds) for Hobby users. +- `metadata`: Custom metadata for the sandbox +- `envs`: Custom environment variables for the sandbox +- `secure`: Envd is secured with access token and cannot be used without it +- `allow_internet_access`: Allow sandbox to access the internet, defaults to `True`. + +**Returns**: + +A Sandbox instance for the new sandbox +Use this method instead of using the constructor to create a new sandbox. + + + +### beta\_create + +```python +@classmethod +def beta_create(cls, + template: Optional[str] = None, + resolution: Optional[Tuple[int, int]] = None, + dpi: Optional[int] = None, + display: Optional[str] = None, + timeout: Optional[int] = None, + auto_pause: Optional[bool] = False, + metadata: Optional[Dict[str, str]] = None, + envs: Optional[Dict[str, str]] = None, + secure: bool = True, + allow_internet_access: bool = True, + **opts: Unpack[ApiParams]) -> Self +``` + +[BETA] This feature is in beta and may change in the future. + +Create a new sandbox. + +By default, the sandbox is created from the default `desktop` sandbox template. + +**Arguments**: + +- `template`: Sandbox template name or ID +- `resolution`: Startup the desktop with custom screen resolution. Defaults to (1024, 768) +- `dpi`: Startup the desktop with custom DPI. Defaults to 96 +- `display`: Startup the desktop with custom display. Defaults to ":0" +- `timeout`: Timeout for the sandbox in **seconds**, default to 300 seconds. The maximum time a sandbox can be kept alive is 24 hours (86_400 seconds) for Pro users and 1 hour (3_600 seconds) for Hobby users. +- `auto_pause`: Automatically pause the sandbox after the timeout expires. Defaults to `False`. +- `metadata`: Custom metadata for the sandbox +- `envs`: Custom environment variables for the sandbox +- `secure`: Envd is secured with access token and cannot be used without it +- `allow_internet_access`: Allow sandbox to access the internet, defaults to `True`. + +**Returns**: + +A Sandbox instance for the new sandbox +Use this method instead of using the constructor to create a new sandbox. + + + +### screenshot + +```python +@overload +def screenshot(format: Literal["stream"]) -> Iterator[bytes] +``` + +Take a screenshot and return it as a stream of bytes. + + + +### screenshot + +```python +@overload +def screenshot(format: Literal["bytes"]) -> bytearray +``` + +Take a screenshot and return it as a bytearray. + + + +### screenshot + +```python +def screenshot(format: Literal["bytes", "stream"] = "bytes") +``` + +Take a screenshot and return it in the specified format. + +**Arguments**: + +- `format`: The format of the screenshot. Can be 'bytes', 'blob', or 'stream'. + +**Returns**: + +The screenshot in the specified format. + + + +### left\_click + +```python +def left_click(x: Optional[int] = None, y: Optional[int] = None) +``` + +Left click on the mouse position. + + + +### double\_click + +```python +def double_click(x: Optional[int] = None, y: Optional[int] = None) +``` + +Double left click on the mouse position. + + + +### middle\_click + +```python +def middle_click(x: Optional[int] = None, y: Optional[int] = None) +``` + +Middle click on the mouse position. + + + +### scroll + +```python +def scroll(direction: Literal["up", "down"] = "down", amount: int = 1) +``` + +Scroll the mouse wheel by the given amount. + +**Arguments**: + +- `direction`: The direction to scroll. Can be "up" or "down". +- `amount`: The amount to scroll. + + + +### move\_mouse + +```python +def move_mouse(x: int, y: int) +``` + +Move the mouse to the given coordinates. + +**Arguments**: + +- `x`: The x coordinate. +- `y`: The y coordinate. + + + +### mouse\_press + +```python +def mouse_press(button: Literal["left", "right", "middle"] = "left") +``` + +Press the mouse button. + + + +### mouse\_release + +```python +def mouse_release(button: Literal["left", "right", "middle"] = "left") +``` + +Release the mouse button. + + + +### get\_cursor\_position + +```python +def get_cursor_position() -> tuple[int, int] +``` + +Get the current cursor position. + +**Raises**: + +- `RuntimeError`: If the cursor position cannot be determined + +**Returns**: + +A tuple with the x and y coordinates + + + +### get\_screen\_size + +```python +def get_screen_size() -> tuple[int, int] +``` + +Get the current screen size. + +**Raises**: + +- `RuntimeError`: If the screen size cannot be determined + +**Returns**: + +A tuple with the width and height + + + +### write + +```python +def write(text: str, *, chunk_size: int = 25, delay_in_ms: int = 75) -> None +``` + +Write the given text at the current cursor position. + +**Arguments**: + +- `text`: The text to write. +- `chunk_size`: The size of each chunk of text to write. +- `delay_in_ms`: The delay between each chunk of text. + + + +### press + +```python +def press(key: Union[str, list[str]]) +``` + +Press a key. + +**Arguments**: + +- `key`: The key to press (e.g. "enter", "space", "backspace", etc.). + + + +### drag + +```python +def drag(fr: tuple[int, int], to: tuple[int, int]) +``` + +Drag the mouse from the given position to the given position. + +**Arguments**: + +- `from`: The starting position. +- `to`: The ending position. + + + +### wait + +```python +def wait(ms: int) +``` + +Wait for the given amount of time. + +**Arguments**: + +- `ms`: The amount of time to wait in milliseconds. + + + +### open + +```python +def open(file_or_url: str) +``` + +Open a file or a URL in the default application. + +**Arguments**: + +- `file_or_url`: The file or URL to open. + + + +### get\_current\_window\_id + +```python +def get_current_window_id() -> str +``` + +Get the current window ID. + + + +### get\_application\_windows + +```python +def get_application_windows(application: str) -> list[str] +``` + +Get the window IDs of all windows for the given application. + + + +### get\_window\_title + +```python +def get_window_title(window_id: str) -> str +``` + +Get the title of the window with the given ID. + + + +### launch + +```python +def launch(application: str, uri: Optional[str] = None) +``` + +Launch an application. diff --git a/docs/sdk-reference/desktop-python-sdk/v2.0.1/desktop.mdx b/docs/sdk-reference/desktop-python-sdk/v2.0.1/desktop.mdx new file mode 100644 index 0000000..391f449 --- /dev/null +++ b/docs/sdk-reference/desktop-python-sdk/v2.0.1/desktop.mdx @@ -0,0 +1,371 @@ +--- +sidebarTitle: "Desktop" +mode: "center" +--- + + + + + + + + + +## Sandbox + +```python +class Sandbox(SandboxBase) +``` + + + +### create + +```python +@classmethod +def create(cls, + template: Optional[str] = None, + resolution: Optional[Tuple[int, int]] = None, + dpi: Optional[int] = None, + display: Optional[str] = None, + timeout: Optional[int] = None, + metadata: Optional[Dict[str, str]] = None, + envs: Optional[Dict[str, str]] = None, + secure: bool = True, + allow_internet_access: bool = True, + **opts: Unpack[ApiParams]) -> Self +``` + +Create a new sandbox. + +By default, the sandbox is created from the default `desktop` sandbox template. + +**Arguments**: + +- `template`: Sandbox template name or ID +- `resolution`: Startup the desktop with custom screen resolution. Defaults to (1024, 768) +- `dpi`: Startup the desktop with custom DPI. Defaults to 96 +- `display`: Startup the desktop with custom display. Defaults to ":0" +- `timeout`: Timeout for the sandbox in **seconds**, default to 300 seconds. The maximum time a sandbox can be kept alive is 24 hours (86_400 seconds) for Pro users and 1 hour (3_600 seconds) for Hobby users. +- `metadata`: Custom metadata for the sandbox +- `envs`: Custom environment variables for the sandbox +- `secure`: Envd is secured with access token and cannot be used without it +- `allow_internet_access`: Allow sandbox to access the internet, defaults to `True`. + +**Returns**: + +A Sandbox instance for the new sandbox +Use this method instead of using the constructor to create a new sandbox. + + + +### beta\_create + +```python +@classmethod +def beta_create(cls, + template: Optional[str] = None, + resolution: Optional[Tuple[int, int]] = None, + dpi: Optional[int] = None, + display: Optional[str] = None, + timeout: Optional[int] = None, + auto_pause: Optional[bool] = False, + metadata: Optional[Dict[str, str]] = None, + envs: Optional[Dict[str, str]] = None, + secure: bool = True, + allow_internet_access: bool = True, + **opts: Unpack[ApiParams]) -> Self +``` + +[BETA] This feature is in beta and may change in the future. + +Create a new sandbox. + +By default, the sandbox is created from the default `desktop` sandbox template. + +**Arguments**: + +- `template`: Sandbox template name or ID +- `resolution`: Startup the desktop with custom screen resolution. Defaults to (1024, 768) +- `dpi`: Startup the desktop with custom DPI. Defaults to 96 +- `display`: Startup the desktop with custom display. Defaults to ":0" +- `timeout`: Timeout for the sandbox in **seconds**, default to 300 seconds. The maximum time a sandbox can be kept alive is 24 hours (86_400 seconds) for Pro users and 1 hour (3_600 seconds) for Hobby users. +- `auto_pause`: Automatically pause the sandbox after the timeout expires. Defaults to `False`. +- `metadata`: Custom metadata for the sandbox +- `envs`: Custom environment variables for the sandbox +- `secure`: Envd is secured with access token and cannot be used without it +- `allow_internet_access`: Allow sandbox to access the internet, defaults to `True`. + +**Returns**: + +A Sandbox instance for the new sandbox +Use this method instead of using the constructor to create a new sandbox. + + + +### screenshot + +```python +@overload +def screenshot(format: Literal["stream"]) -> Iterator[bytes] +``` + +Take a screenshot and return it as a stream of bytes. + + + +### screenshot + +```python +@overload +def screenshot(format: Literal["bytes"]) -> bytearray +``` + +Take a screenshot and return it as a bytearray. + + + +### screenshot + +```python +def screenshot(format: Literal["bytes", "stream"] = "bytes") +``` + +Take a screenshot and return it in the specified format. + +**Arguments**: + +- `format`: The format of the screenshot. Can be 'bytes', 'blob', or 'stream'. + +**Returns**: + +The screenshot in the specified format. + + + +### left\_click + +```python +def left_click(x: Optional[int] = None, y: Optional[int] = None) +``` + +Left click on the mouse position. + + + +### double\_click + +```python +def double_click(x: Optional[int] = None, y: Optional[int] = None) +``` + +Double left click on the mouse position. + + + +### middle\_click + +```python +def middle_click(x: Optional[int] = None, y: Optional[int] = None) +``` + +Middle click on the mouse position. + + + +### scroll + +```python +def scroll(direction: Literal["up", "down"] = "down", amount: int = 1) +``` + +Scroll the mouse wheel by the given amount. + +**Arguments**: + +- `direction`: The direction to scroll. Can be "up" or "down". +- `amount`: The amount to scroll. + + + +### move\_mouse + +```python +def move_mouse(x: int, y: int) +``` + +Move the mouse to the given coordinates. + +**Arguments**: + +- `x`: The x coordinate. +- `y`: The y coordinate. + + + +### mouse\_press + +```python +def mouse_press(button: Literal["left", "right", "middle"] = "left") +``` + +Press the mouse button. + + + +### mouse\_release + +```python +def mouse_release(button: Literal["left", "right", "middle"] = "left") +``` + +Release the mouse button. + + + +### get\_cursor\_position + +```python +def get_cursor_position() -> tuple[int, int] +``` + +Get the current cursor position. + +**Raises**: + +- `RuntimeError`: If the cursor position cannot be determined + +**Returns**: + +A tuple with the x and y coordinates + + + +### get\_screen\_size + +```python +def get_screen_size() -> tuple[int, int] +``` + +Get the current screen size. + +**Raises**: + +- `RuntimeError`: If the screen size cannot be determined + +**Returns**: + +A tuple with the width and height + + + +### write + +```python +def write(text: str, *, chunk_size: int = 25, delay_in_ms: int = 75) -> None +``` + +Write the given text at the current cursor position. + +**Arguments**: + +- `text`: The text to write. +- `chunk_size`: The size of each chunk of text to write. +- `delay_in_ms`: The delay between each chunk of text. + + + +### press + +```python +def press(key: Union[str, list[str]]) +``` + +Press a key. + +**Arguments**: + +- `key`: The key to press (e.g. "enter", "space", "backspace", etc.). + + + +### drag + +```python +def drag(fr: tuple[int, int], to: tuple[int, int]) +``` + +Drag the mouse from the given position to the given position. + +**Arguments**: + +- `from`: The starting position. +- `to`: The ending position. + + + +### wait + +```python +def wait(ms: int) +``` + +Wait for the given amount of time. + +**Arguments**: + +- `ms`: The amount of time to wait in milliseconds. + + + +### open + +```python +def open(file_or_url: str) +``` + +Open a file or a URL in the default application. + +**Arguments**: + +- `file_or_url`: The file or URL to open. + + + +### get\_current\_window\_id + +```python +def get_current_window_id() -> str +``` + +Get the current window ID. + + + +### get\_application\_windows + +```python +def get_application_windows(application: str) -> list[str] +``` + +Get the window IDs of all windows for the given application. + + + +### get\_window\_title + +```python +def get_window_title(window_id: str) -> str +``` + +Get the title of the window with the given ID. + + + +### launch + +```python +def launch(application: str, uri: Optional[str] = None) +``` + +Launch an application. diff --git a/docs/sdk-reference/desktop-python-sdk/v2.1.0/desktop.mdx b/docs/sdk-reference/desktop-python-sdk/v2.1.0/desktop.mdx new file mode 100644 index 0000000..391f449 --- /dev/null +++ b/docs/sdk-reference/desktop-python-sdk/v2.1.0/desktop.mdx @@ -0,0 +1,371 @@ +--- +sidebarTitle: "Desktop" +mode: "center" +--- + + + + + + + + + +## Sandbox + +```python +class Sandbox(SandboxBase) +``` + + + +### create + +```python +@classmethod +def create(cls, + template: Optional[str] = None, + resolution: Optional[Tuple[int, int]] = None, + dpi: Optional[int] = None, + display: Optional[str] = None, + timeout: Optional[int] = None, + metadata: Optional[Dict[str, str]] = None, + envs: Optional[Dict[str, str]] = None, + secure: bool = True, + allow_internet_access: bool = True, + **opts: Unpack[ApiParams]) -> Self +``` + +Create a new sandbox. + +By default, the sandbox is created from the default `desktop` sandbox template. + +**Arguments**: + +- `template`: Sandbox template name or ID +- `resolution`: Startup the desktop with custom screen resolution. Defaults to (1024, 768) +- `dpi`: Startup the desktop with custom DPI. Defaults to 96 +- `display`: Startup the desktop with custom display. Defaults to ":0" +- `timeout`: Timeout for the sandbox in **seconds**, default to 300 seconds. The maximum time a sandbox can be kept alive is 24 hours (86_400 seconds) for Pro users and 1 hour (3_600 seconds) for Hobby users. +- `metadata`: Custom metadata for the sandbox +- `envs`: Custom environment variables for the sandbox +- `secure`: Envd is secured with access token and cannot be used without it +- `allow_internet_access`: Allow sandbox to access the internet, defaults to `True`. + +**Returns**: + +A Sandbox instance for the new sandbox +Use this method instead of using the constructor to create a new sandbox. + + + +### beta\_create + +```python +@classmethod +def beta_create(cls, + template: Optional[str] = None, + resolution: Optional[Tuple[int, int]] = None, + dpi: Optional[int] = None, + display: Optional[str] = None, + timeout: Optional[int] = None, + auto_pause: Optional[bool] = False, + metadata: Optional[Dict[str, str]] = None, + envs: Optional[Dict[str, str]] = None, + secure: bool = True, + allow_internet_access: bool = True, + **opts: Unpack[ApiParams]) -> Self +``` + +[BETA] This feature is in beta and may change in the future. + +Create a new sandbox. + +By default, the sandbox is created from the default `desktop` sandbox template. + +**Arguments**: + +- `template`: Sandbox template name or ID +- `resolution`: Startup the desktop with custom screen resolution. Defaults to (1024, 768) +- `dpi`: Startup the desktop with custom DPI. Defaults to 96 +- `display`: Startup the desktop with custom display. Defaults to ":0" +- `timeout`: Timeout for the sandbox in **seconds**, default to 300 seconds. The maximum time a sandbox can be kept alive is 24 hours (86_400 seconds) for Pro users and 1 hour (3_600 seconds) for Hobby users. +- `auto_pause`: Automatically pause the sandbox after the timeout expires. Defaults to `False`. +- `metadata`: Custom metadata for the sandbox +- `envs`: Custom environment variables for the sandbox +- `secure`: Envd is secured with access token and cannot be used without it +- `allow_internet_access`: Allow sandbox to access the internet, defaults to `True`. + +**Returns**: + +A Sandbox instance for the new sandbox +Use this method instead of using the constructor to create a new sandbox. + + + +### screenshot + +```python +@overload +def screenshot(format: Literal["stream"]) -> Iterator[bytes] +``` + +Take a screenshot and return it as a stream of bytes. + + + +### screenshot + +```python +@overload +def screenshot(format: Literal["bytes"]) -> bytearray +``` + +Take a screenshot and return it as a bytearray. + + + +### screenshot + +```python +def screenshot(format: Literal["bytes", "stream"] = "bytes") +``` + +Take a screenshot and return it in the specified format. + +**Arguments**: + +- `format`: The format of the screenshot. Can be 'bytes', 'blob', or 'stream'. + +**Returns**: + +The screenshot in the specified format. + + + +### left\_click + +```python +def left_click(x: Optional[int] = None, y: Optional[int] = None) +``` + +Left click on the mouse position. + + + +### double\_click + +```python +def double_click(x: Optional[int] = None, y: Optional[int] = None) +``` + +Double left click on the mouse position. + + + +### middle\_click + +```python +def middle_click(x: Optional[int] = None, y: Optional[int] = None) +``` + +Middle click on the mouse position. + + + +### scroll + +```python +def scroll(direction: Literal["up", "down"] = "down", amount: int = 1) +``` + +Scroll the mouse wheel by the given amount. + +**Arguments**: + +- `direction`: The direction to scroll. Can be "up" or "down". +- `amount`: The amount to scroll. + + + +### move\_mouse + +```python +def move_mouse(x: int, y: int) +``` + +Move the mouse to the given coordinates. + +**Arguments**: + +- `x`: The x coordinate. +- `y`: The y coordinate. + + + +### mouse\_press + +```python +def mouse_press(button: Literal["left", "right", "middle"] = "left") +``` + +Press the mouse button. + + + +### mouse\_release + +```python +def mouse_release(button: Literal["left", "right", "middle"] = "left") +``` + +Release the mouse button. + + + +### get\_cursor\_position + +```python +def get_cursor_position() -> tuple[int, int] +``` + +Get the current cursor position. + +**Raises**: + +- `RuntimeError`: If the cursor position cannot be determined + +**Returns**: + +A tuple with the x and y coordinates + + + +### get\_screen\_size + +```python +def get_screen_size() -> tuple[int, int] +``` + +Get the current screen size. + +**Raises**: + +- `RuntimeError`: If the screen size cannot be determined + +**Returns**: + +A tuple with the width and height + + + +### write + +```python +def write(text: str, *, chunk_size: int = 25, delay_in_ms: int = 75) -> None +``` + +Write the given text at the current cursor position. + +**Arguments**: + +- `text`: The text to write. +- `chunk_size`: The size of each chunk of text to write. +- `delay_in_ms`: The delay between each chunk of text. + + + +### press + +```python +def press(key: Union[str, list[str]]) +``` + +Press a key. + +**Arguments**: + +- `key`: The key to press (e.g. "enter", "space", "backspace", etc.). + + + +### drag + +```python +def drag(fr: tuple[int, int], to: tuple[int, int]) +``` + +Drag the mouse from the given position to the given position. + +**Arguments**: + +- `from`: The starting position. +- `to`: The ending position. + + + +### wait + +```python +def wait(ms: int) +``` + +Wait for the given amount of time. + +**Arguments**: + +- `ms`: The amount of time to wait in milliseconds. + + + +### open + +```python +def open(file_or_url: str) +``` + +Open a file or a URL in the default application. + +**Arguments**: + +- `file_or_url`: The file or URL to open. + + + +### get\_current\_window\_id + +```python +def get_current_window_id() -> str +``` + +Get the current window ID. + + + +### get\_application\_windows + +```python +def get_application_windows(application: str) -> list[str] +``` + +Get the window IDs of all windows for the given application. + + + +### get\_window\_title + +```python +def get_window_title(window_id: str) -> str +``` + +Get the title of the window with the given ID. + + + +### launch + +```python +def launch(application: str, uri: Optional[str] = None) +``` + +Launch an application. diff --git a/docs/sdk-reference/desktop-python-sdk/v2.2.0/desktop.mdx b/docs/sdk-reference/desktop-python-sdk/v2.2.0/desktop.mdx new file mode 100644 index 0000000..391f449 --- /dev/null +++ b/docs/sdk-reference/desktop-python-sdk/v2.2.0/desktop.mdx @@ -0,0 +1,371 @@ +--- +sidebarTitle: "Desktop" +mode: "center" +--- + + + + + + + + + +## Sandbox + +```python +class Sandbox(SandboxBase) +``` + + + +### create + +```python +@classmethod +def create(cls, + template: Optional[str] = None, + resolution: Optional[Tuple[int, int]] = None, + dpi: Optional[int] = None, + display: Optional[str] = None, + timeout: Optional[int] = None, + metadata: Optional[Dict[str, str]] = None, + envs: Optional[Dict[str, str]] = None, + secure: bool = True, + allow_internet_access: bool = True, + **opts: Unpack[ApiParams]) -> Self +``` + +Create a new sandbox. + +By default, the sandbox is created from the default `desktop` sandbox template. + +**Arguments**: + +- `template`: Sandbox template name or ID +- `resolution`: Startup the desktop with custom screen resolution. Defaults to (1024, 768) +- `dpi`: Startup the desktop with custom DPI. Defaults to 96 +- `display`: Startup the desktop with custom display. Defaults to ":0" +- `timeout`: Timeout for the sandbox in **seconds**, default to 300 seconds. The maximum time a sandbox can be kept alive is 24 hours (86_400 seconds) for Pro users and 1 hour (3_600 seconds) for Hobby users. +- `metadata`: Custom metadata for the sandbox +- `envs`: Custom environment variables for the sandbox +- `secure`: Envd is secured with access token and cannot be used without it +- `allow_internet_access`: Allow sandbox to access the internet, defaults to `True`. + +**Returns**: + +A Sandbox instance for the new sandbox +Use this method instead of using the constructor to create a new sandbox. + + + +### beta\_create + +```python +@classmethod +def beta_create(cls, + template: Optional[str] = None, + resolution: Optional[Tuple[int, int]] = None, + dpi: Optional[int] = None, + display: Optional[str] = None, + timeout: Optional[int] = None, + auto_pause: Optional[bool] = False, + metadata: Optional[Dict[str, str]] = None, + envs: Optional[Dict[str, str]] = None, + secure: bool = True, + allow_internet_access: bool = True, + **opts: Unpack[ApiParams]) -> Self +``` + +[BETA] This feature is in beta and may change in the future. + +Create a new sandbox. + +By default, the sandbox is created from the default `desktop` sandbox template. + +**Arguments**: + +- `template`: Sandbox template name or ID +- `resolution`: Startup the desktop with custom screen resolution. Defaults to (1024, 768) +- `dpi`: Startup the desktop with custom DPI. Defaults to 96 +- `display`: Startup the desktop with custom display. Defaults to ":0" +- `timeout`: Timeout for the sandbox in **seconds**, default to 300 seconds. The maximum time a sandbox can be kept alive is 24 hours (86_400 seconds) for Pro users and 1 hour (3_600 seconds) for Hobby users. +- `auto_pause`: Automatically pause the sandbox after the timeout expires. Defaults to `False`. +- `metadata`: Custom metadata for the sandbox +- `envs`: Custom environment variables for the sandbox +- `secure`: Envd is secured with access token and cannot be used without it +- `allow_internet_access`: Allow sandbox to access the internet, defaults to `True`. + +**Returns**: + +A Sandbox instance for the new sandbox +Use this method instead of using the constructor to create a new sandbox. + + + +### screenshot + +```python +@overload +def screenshot(format: Literal["stream"]) -> Iterator[bytes] +``` + +Take a screenshot and return it as a stream of bytes. + + + +### screenshot + +```python +@overload +def screenshot(format: Literal["bytes"]) -> bytearray +``` + +Take a screenshot and return it as a bytearray. + + + +### screenshot + +```python +def screenshot(format: Literal["bytes", "stream"] = "bytes") +``` + +Take a screenshot and return it in the specified format. + +**Arguments**: + +- `format`: The format of the screenshot. Can be 'bytes', 'blob', or 'stream'. + +**Returns**: + +The screenshot in the specified format. + + + +### left\_click + +```python +def left_click(x: Optional[int] = None, y: Optional[int] = None) +``` + +Left click on the mouse position. + + + +### double\_click + +```python +def double_click(x: Optional[int] = None, y: Optional[int] = None) +``` + +Double left click on the mouse position. + + + +### middle\_click + +```python +def middle_click(x: Optional[int] = None, y: Optional[int] = None) +``` + +Middle click on the mouse position. + + + +### scroll + +```python +def scroll(direction: Literal["up", "down"] = "down", amount: int = 1) +``` + +Scroll the mouse wheel by the given amount. + +**Arguments**: + +- `direction`: The direction to scroll. Can be "up" or "down". +- `amount`: The amount to scroll. + + + +### move\_mouse + +```python +def move_mouse(x: int, y: int) +``` + +Move the mouse to the given coordinates. + +**Arguments**: + +- `x`: The x coordinate. +- `y`: The y coordinate. + + + +### mouse\_press + +```python +def mouse_press(button: Literal["left", "right", "middle"] = "left") +``` + +Press the mouse button. + + + +### mouse\_release + +```python +def mouse_release(button: Literal["left", "right", "middle"] = "left") +``` + +Release the mouse button. + + + +### get\_cursor\_position + +```python +def get_cursor_position() -> tuple[int, int] +``` + +Get the current cursor position. + +**Raises**: + +- `RuntimeError`: If the cursor position cannot be determined + +**Returns**: + +A tuple with the x and y coordinates + + + +### get\_screen\_size + +```python +def get_screen_size() -> tuple[int, int] +``` + +Get the current screen size. + +**Raises**: + +- `RuntimeError`: If the screen size cannot be determined + +**Returns**: + +A tuple with the width and height + + + +### write + +```python +def write(text: str, *, chunk_size: int = 25, delay_in_ms: int = 75) -> None +``` + +Write the given text at the current cursor position. + +**Arguments**: + +- `text`: The text to write. +- `chunk_size`: The size of each chunk of text to write. +- `delay_in_ms`: The delay between each chunk of text. + + + +### press + +```python +def press(key: Union[str, list[str]]) +``` + +Press a key. + +**Arguments**: + +- `key`: The key to press (e.g. "enter", "space", "backspace", etc.). + + + +### drag + +```python +def drag(fr: tuple[int, int], to: tuple[int, int]) +``` + +Drag the mouse from the given position to the given position. + +**Arguments**: + +- `from`: The starting position. +- `to`: The ending position. + + + +### wait + +```python +def wait(ms: int) +``` + +Wait for the given amount of time. + +**Arguments**: + +- `ms`: The amount of time to wait in milliseconds. + + + +### open + +```python +def open(file_or_url: str) +``` + +Open a file or a URL in the default application. + +**Arguments**: + +- `file_or_url`: The file or URL to open. + + + +### get\_current\_window\_id + +```python +def get_current_window_id() -> str +``` + +Get the current window ID. + + + +### get\_application\_windows + +```python +def get_application_windows(application: str) -> list[str] +``` + +Get the window IDs of all windows for the given application. + + + +### get\_window\_title + +```python +def get_window_title(window_id: str) -> str +``` + +Get the title of the window with the given ID. + + + +### launch + +```python +def launch(application: str, uri: Optional[str] = None) +``` + +Launch an application. diff --git a/docs/sdk-reference/js-sdk/1.0.0/errors.mdx b/docs/sdk-reference/js-sdk/1.0.0/errors.mdx new file mode 100644 index 0000000..1e56924 --- /dev/null +++ b/docs/sdk-reference/js-sdk/1.0.0/errors.mdx @@ -0,0 +1,197 @@ +--- +sidebarTitle: "Errors" +mode: "center" +--- + +# errors + +## Classes + +### AuthenticationError + +Thrown when authentication fails. + +#### Constructors + +> **new AuthenticationError**(`message`): `AuthenticationError` + +###### Parameters + +• **message**: `any` + +###### Returns + +`AuthenticationError` + +###### Defined in + +errors.ts:72 + +*** + +### InvalidArgumentError + +Thrown when an invalid argument is provided. + +#### Constructors + +> **new InvalidArgumentError**(`message`): `InvalidArgumentError` + +###### Parameters + +• **message**: `string` + +###### Returns + +`InvalidArgumentError` + +###### Defined in + +errors.ts:42 + +*** + +### NotEnoughSpaceError + +Thrown when there is not enough disk space. + +#### Constructors + +> **new NotEnoughSpaceError**(`message`): `NotEnoughSpaceError` + +###### Parameters + +• **message**: `string` + +###### Returns + +`NotEnoughSpaceError` + +###### Defined in + +errors.ts:52 + +*** + +### NotFoundError + +Thrown when a resource is not found. + +#### Constructors + +> **new NotFoundError**(`message`): `NotFoundError` + +###### Parameters + +• **message**: `string` + +###### Returns + +`NotFoundError` + +###### Defined in + +errors.ts:62 + +*** + +### SandboxError + +Base class for all sandbox errors. + +Thrown when general sandbox errors occur. + +#### Extended by + +- `TimeoutError` +- `InvalidArgumentError` +- `NotEnoughSpaceError` +- `NotFoundError` +- `AuthenticationError` +- `TemplateError` + +#### Constructors + +> **new SandboxError**(`message`): `SandboxError` + +###### Parameters + +• **message**: `any` + +###### Returns + +`SandboxError` + +###### Defined in + +errors.ts:14 + +*** + +### TemplateError + +Thrown when the template uses old envd version. It isn't compatible with the new SDK. + +#### Constructors + +> **new TemplateError**(`message`): `TemplateError` + +###### Parameters + +• **message**: `string` + +###### Returns + +`TemplateError` + +###### Defined in + +errors.ts:82 + +*** + +### TimeoutError + +Thrown when a timeout error occurs. + +The [unavailable] error type is caused by sandbox timeout. + +The [canceled] error type is caused by exceeding request timeout. + +The [deadline_exceeded] error type is caused by exceeding the timeout for command execution, watch, etc. + +The [unknown] error type is sometimes caused by the sandbox timeout when the request is not processed correctly. + +#### Constructors + +> **new TimeoutError**(`message`): `TimeoutError` + +###### Parameters + +• **message**: `string` + +###### Returns + +`TimeoutError` + +###### Defined in + +errors.ts:32 + +## Functions + +### formatSandboxTimeoutError() + +> **formatSandboxTimeoutError**(`message`): `TimeoutError` + +#### Parameters + +• **message**: `string` + +#### Returns + +`TimeoutError` + +#### Defined in + +errors.ts:2 diff --git a/docs/sdk-reference/js-sdk/1.0.0/sandbox-filesystem.mdx b/docs/sdk-reference/js-sdk/1.0.0/sandbox-filesystem.mdx new file mode 100644 index 0000000..32481ec --- /dev/null +++ b/docs/sdk-reference/js-sdk/1.0.0/sandbox-filesystem.mdx @@ -0,0 +1,521 @@ +--- +sidebarTitle: "Filesystem" +mode: "center" +--- + +# sandbox/filesystem + +## Enumerations + +### FileType + +Sandbox filesystem object type. + +#### Enumeration Members + +### DIR + +> **DIR**: `"dir"` + +Filesystem object is a directory. + +###### Defined in + +sandbox/filesystem/index.ts:55 + +### FILE + +> **FILE**: `"file"` + +Filesystem object is a file. + +###### Defined in + +sandbox/filesystem/index.ts:51 + +## Classes + +### Filesystem + +Module for interacting with the sandbox filesystem. + +#### Constructors + +> **new Filesystem**(`transport`, `envdApi`, `connectionConfig`): `Filesystem` + +###### Parameters + +• **transport**: `Transport` + +• **envdApi**: `EnvdApiClient` + +• **connectionConfig**: `ConnectionConfig` + +###### Returns + +`Filesystem` + +###### Defined in + +sandbox/filesystem/index.ts:104 + +#### Methods + +### exists() + +> **exists**(`path`, `opts`?): `Promise`\<`boolean`\> + +Check if a file or a directory exists. + +###### Parameters + +• **path**: `string` + +path to a file or a directory + +• **opts?**: `FilesystemRequestOpts` + +connection options. + +###### Returns + +`Promise`\<`boolean`\> + +`true` if the file or directory exists, `false` otherwise + +###### Defined in + +sandbox/filesystem/index.ts:399 + +### list() + +> **list**(`path`, `opts`?): `Promise`\<`EntryInfo`[]\> + +List entries in a directory. + +###### Parameters + +• **path**: `string` + +path to the directory. + +• **opts?**: `FilesystemRequestOpts` + +connection options. + +###### Returns + +`Promise`\<`EntryInfo`[]\> + +list of entries in the sandbox filesystem directory. + +###### Defined in + +sandbox/filesystem/index.ts:270 + +### makeDir() + +> **makeDir**(`path`, `opts`?): `Promise`\<`boolean`\> + +Create a new directory and all directories along the way if needed on the specified path. + +###### Parameters + +• **path**: `string` + +path to a new directory. For example '/dirA/dirB' when creating 'dirB'. + +• **opts?**: `FilesystemRequestOpts` + +connection options. + +###### Returns + +`Promise`\<`boolean`\> + +`true` if the directory was created, `false` if it already exists. + +###### Defined in + +sandbox/filesystem/index.ts:308 + +### read() + +###### read(path, opts) + +> **read**(`path`, `opts`?): `Promise`\<`string`\> + +Read file content as a `string`. + +You can pass `text`, `bytes`, `blob`, or `stream` to `opts.format` to change the return type. + +###### Parameters + +• **path**: `string` + +path to the file. + +• **opts?**: `FilesystemRequestOpts` & `object` + +connection options. + +###### Returns + +`Promise`\<`string`\> + +file content as string + +###### Defined in + +sandbox/filesystem/index.ts:123 + +###### read(path, opts) + +> **read**(`path`, `opts`?): `Promise`\<`Uint8Array`\> + +Read file content as a `Uint8Array`. + +You can pass `text`, `bytes`, `blob`, or `stream` to `opts.format` to change the return type. + +###### Parameters + +• **path**: `string` + +path to the file. + +• **opts?**: `FilesystemRequestOpts` & `object` + +connection options. + +###### Returns + +`Promise`\<`Uint8Array`\> + +file content as `Uint8Array` + +###### Defined in + +sandbox/filesystem/index.ts:138 + +###### read(path, opts) + +> **read**(`path`, `opts`?): `Promise`\<`Blob`\> + +Read file content as a `Blob`. + +You can pass `text`, `bytes`, `blob`, or `stream` to `opts.format` to change the return type. + +###### Parameters + +• **path**: `string` + +path to the file. + +• **opts?**: `FilesystemRequestOpts` & `object` + +connection options. + +###### Returns + +`Promise`\<`Blob`\> + +file content as `Blob` + +###### Defined in + +sandbox/filesystem/index.ts:153 + +###### read(path, opts) + +> **read**(`path`, `opts`?): `Promise`\<`ReadableStream`\<`Uint8Array`\>\> + +Read file content as a `ReadableStream`. + +You can pass `text`, `bytes`, `blob`, or `stream` to `opts.format` to change the return type. + +###### Parameters + +• **path**: `string` + +path to the file. + +• **opts?**: `FilesystemRequestOpts` & `object` + +connection options. + +###### Returns + +`Promise`\<`ReadableStream`\<`Uint8Array`\>\> + +file content as `ReadableStream` + +###### Defined in + +sandbox/filesystem/index.ts:168 + +### remove() + +> **remove**(`path`, `opts`?): `Promise`\<`void`\> + +Remove a file or directory. + +###### Parameters + +• **path**: `string` + +path to a file or directory. + +• **opts?**: `FilesystemRequestOpts` + +connection options. + +###### Returns + +`Promise`\<`void`\> + +###### Defined in + +sandbox/filesystem/index.ts:377 + +### rename() + +> **rename**(`oldPath`, `newPath`, `opts`?): `Promise`\<`EntryInfo`\> + +Rename a file or directory. + +###### Parameters + +• **oldPath**: `string` + +path to the file or directory to rename. + +• **newPath**: `string` + +new path for the file or directory. + +• **opts?**: `FilesystemRequestOpts` + +connection options. + +###### Returns + +`Promise`\<`EntryInfo`\> + +information about renamed file or directory. + +###### Defined in + +sandbox/filesystem/index.ts:339 + +### watchDir() + +> **watchDir**(`path`, `onEvent`, `opts`?): `Promise`\<`WatchHandle`\> + +Start watching a directory for filesystem events. + +###### Parameters + +• **path**: `string` + +path to directory to watch. + +• **onEvent** + +callback to call when an event in the directory occurs. + +• **opts?**: `WatchOpts` + +connection options. + +###### Returns + +`Promise`\<`WatchHandle`\> + +`WatchHandle` object for stopping watching directory. + +###### Defined in + +sandbox/filesystem/index.ts:430 + +### write() + +> **write**(`path`, `data`, `opts`?): `Promise`\<`EntryInfo`\> + +Write content to a file. + +Writing to a file that doesn't exist creates the file. + +Writing to a file that already exists overwrites the file. + +Writing to a file at path that doesn't exist creates the necessary directories. + +###### Parameters + +• **path**: `string` + +path to file. + +• **data**: `string` \| `ArrayBuffer` \| `Blob` \| `ReadableStream`\<`any`\> + +data to write to the file. Data can be a string, `ArrayBuffer`, `Blob`, or `ReadableStream`. + +• **opts?**: `FilesystemRequestOpts` + +connection options. + +###### Returns + +`Promise`\<`EntryInfo`\> + +information about the written file + +###### Defined in + +sandbox/filesystem/index.ts:224 + +## Interfaces + +### EntryInfo + +Sandbox filesystem object information. + +#### Properties + +### name + +> **name**: `string` + +Name of the filesystem object. + +###### Defined in + +sandbox/filesystem/index.ts:33 + +### path + +> **path**: `string` + +Path to the filesystem object. + +###### Defined in + +sandbox/filesystem/index.ts:41 + +### type? + +> `optional` **type**: `FileType` + +Type of the filesystem object. + +###### Defined in + +sandbox/filesystem/index.ts:37 + +*** + +### FilesystemRequestOpts + +Options for the sandbox filesystem operations. + +#### Extended by + +- `WatchOpts` + +#### Properties + +### requestTimeoutMs? + +> `optional` **requestTimeoutMs**: `number` + +Timeout for requests to the API in **milliseconds**. + +###### Default + +```ts +30_000 // 30 seconds +``` + +###### Defined in + +connectionConfig.ts:42 + +### user? + +> `optional` **user**: `Username` + +User to use for the operation in the sandbox. +This affects the resolution of relative paths and ownership of the created filesystem objects. + +###### Defined in + +sandbox/filesystem/index.ts:76 + +*** + +### WatchOpts + +Options for watching a directory. + +#### Properties + +### onExit()? + +> `optional` **onExit**: (`err`?) => `void` \| `Promise`\<`void`\> + +Callback to call when the watch operation stops. + +###### Parameters + +• **err?**: `Error` + +###### Returns + +`void` \| `Promise`\<`void`\> + +###### Defined in + +sandbox/filesystem/index.ts:93 + +### requestTimeoutMs? + +> `optional` **requestTimeoutMs**: `number` + +Timeout for requests to the API in **milliseconds**. + +###### Default + +```ts +30_000 // 30 seconds +``` + +###### Defined in + +connectionConfig.ts:42 + +### timeoutMs? + +> `optional` **timeoutMs**: `number` + +Timeout for the watch operation in **milliseconds**. +You can pass `0` to disable the timeout. + +###### Default + +```ts +60_000 // 60 seconds +``` + +###### Defined in + +sandbox/filesystem/index.ts:89 + +### user? + +> `optional` **user**: `Username` + +User to use for the operation in the sandbox. +This affects the resolution of relative paths and ownership of the created filesystem objects. + +###### Defined in + +sandbox/filesystem/index.ts:76 diff --git a/docs/sdk-reference/js-sdk/1.0.0/sandbox.mdx b/docs/sdk-reference/js-sdk/1.0.0/sandbox.mdx new file mode 100644 index 0000000..388c4d2 --- /dev/null +++ b/docs/sdk-reference/js-sdk/1.0.0/sandbox.mdx @@ -0,0 +1,586 @@ +--- +sidebarTitle: "Sandbox" +mode: "center" +--- + +# sandbox + +## Classes + +### Sandbox + +E2B cloud sandbox is a secure and isolated cloud environment. + +The sandbox allows you to: +- Access Linux OS +- Create, list, and delete files and directories +- Run commands +- Run isolated code +- Access the internet + +Check docs here. + +Use Sandbox.create to create a new sandbox. + +#### Example + +```ts +import { Sandbox } from 'e2b' + +const sandbox = await Sandbox.create() +``` + +#### Properties + +### commands + +> `readonly` **commands**: `Commands` + +Module for running commands in the sandbox + +###### Defined in + +sandbox/index.ts:74 + +### files + +> `readonly` **files**: `Filesystem` + +Module for interacting with the sandbox filesystem + +###### Defined in + +sandbox/index.ts:70 + +### pty + +> `readonly` **pty**: `Pty` + +Module for interacting with the sandbox pseudo-terminals + +###### Defined in + +sandbox/index.ts:78 + +### sandboxId + +> `readonly` **sandboxId**: `string` + +Unique identifier of the sandbox. + +###### Defined in + +sandbox/index.ts:83 + +#### Methods + +### downloadUrl() + +> **downloadUrl**(`path`): `string` + +Get the URL to download a file from the sandbox. + +###### Parameters + +• **path**: `string` + +path to the file to download. + +###### Returns + +`string` + +URL for downloading file. + +###### Defined in + +sandbox/index.ts:339 + +### getHost() + +> **getHost**(`port`): `string` + +Get the host address for the specified sandbox port. +You can then use this address to connect to the sandbox port from outside the sandbox via HTTP or WebSocket. + +###### Parameters + +• **port**: `number` + +number of the port in the sandbox. + +###### Returns + +`string` + +host address of the sandbox port. + +###### Example + +```ts +const sandbox = await Sandbox.create() +// Start an HTTP server +await sandbox.commands.exec('python3 -m http.server 3000') +// Get the hostname of the HTTP server +const serverURL = sandbox.getHost(3000) +`` + +###### Defined in + +sandbox/index.ts:237 + +### isRunning() + +> **isRunning**(`opts`?): `Promise`\<`boolean`\> + +Check if the sandbox is running. + +###### Parameters + +• **opts?**: `Pick`\<`ConnectionOpts`, `"requestTimeoutMs"`\> + +###### Returns + +`Promise`\<`boolean`\> + +`true` if the sandbox is running, `false` otherwise. + +###### Example + +```ts +const sandbox = await Sandbox.create() +await sandbox.isRunning() // Returns true + +await sandbox.kill() +await sandbox.isRunning() // Returns false +``` + +###### Defined in + +sandbox/index.ts:259 + +### kill() + +> **kill**(`opts`?): `Promise`\<`void`\> + +Kill the sandbox. + +###### Parameters + +• **opts?**: `Pick`\<`SandboxOpts`, `"requestTimeoutMs"`\> + +connection options. + +###### Returns + +`Promise`\<`void`\> + +###### Defined in + +sandbox/index.ts:310 + +### setTimeout() + +> **setTimeout**(`timeoutMs`, `opts`?): `Promise`\<`void`\> + +Set the timeout of the sandbox. +After the timeout expires the sandbox will be automatically killed. + +This method can extend or reduce the sandbox timeout set when creating the sandbox or from the last call to `.setTimeout`. +Maximum time a sandbox can be kept alive is 24 hours (86_400_000 milliseconds) for Pro users and 1 hour (3_600_000 milliseconds) for Hobby users. + +###### Parameters + +• **timeoutMs**: `number` + +timeout in **milliseconds**. + +• **opts?**: `Pick`\<`SandboxOpts`, `"requestTimeoutMs"`\> + +connection options. + +###### Returns + +`Promise`\<`void`\> + +###### Defined in + +sandbox/index.ts:290 + +### uploadUrl() + +> **uploadUrl**(`path`?): `string` + +Get the URL to upload a file to the sandbox. + +You have to send a POST request to this URL with the file as multipart/form-data. + +###### Parameters + +• **path?**: `string` + +the directory where to upload the file, defaults to user's home directory. + +###### Returns + +`string` + +URL for uploading file. + +###### Defined in + +sandbox/index.ts:328 + +### connect() + +> `static` **connect**\<`S`\>(`this`, `sandboxId`, `opts`?): `Promise`\<`InstanceType`\<`S`\>\> + +Connect to an existing sandbox. +With sandbox ID you can connect to the same sandbox from different places or environments (serverless functions, etc). + +###### Type Parameters + +• **S** *extends* *typeof* `Sandbox` + +###### Parameters + +• **this**: `S` + +• **sandboxId**: `string` + +sandbox ID. + +• **opts?**: `Omit`\<`SandboxOpts`, `"timeoutMs"` \| `"metadata"` \| `"envs"`\> + +connection options. + +###### Returns + +`Promise`\<`InstanceType`\<`S`\>\> + +sandbox instance for the existing sandbox. + +###### Example + +```ts +const sandbox = await Sandbox.create() +const sandboxId = sandbox.sandboxId + +// Connect to the same sandbox. +const sameSandbox = await Sandbox.connect(sandboxId) +``` + +###### Defined in + +sandbox/index.ts:209 + +### create() + +###### create(this, opts) + +> `static` **create**\<`S`\>(`this`, `opts`?): `Promise`\<`InstanceType`\<`S`\>\> + +Create a new sandbox from the default `base` sandbox template. + +###### Type Parameters + +• **S** *extends* *typeof* `Sandbox` + +###### Parameters + +• **this**: `S` + +• **opts?**: `SandboxOpts` + +connection options. + +###### Returns + +`Promise`\<`InstanceType`\<`S`\>\> + +sandbox instance for the new sandbox. + +###### Example + +```ts +const sandbox = await Sandbox.create() +``` + +###### Constructs + +Sandbox + +###### Defined in + +sandbox/index.ts:143 + +###### create(this, template, opts) + +> `static` **create**\<`S`\>(`this`, `template`, `opts`?): `Promise`\<`InstanceType`\<`S`\>\> + +Create a new sandbox from the specified sandbox template. + +###### Type Parameters + +• **S** *extends* *typeof* `Sandbox` + +###### Parameters + +• **this**: `S` + +• **template**: `string` + +sandbox template name or ID. + +• **opts?**: `SandboxOpts` + +connection options. + +###### Returns + +`Promise`\<`InstanceType`\<`S`\>\> + +sandbox instance for the new sandbox. + +###### Example + +```ts +const sandbox = await Sandbox.create('') +``` + +###### Constructs + +Sandbox + +###### Defined in + +sandbox/index.ts:162 + +### kill() + +> `static` **kill**(`sandboxId`, `opts`?): `Promise`\<`boolean`\> + +Kill the sandbox specified by sandbox ID. + +###### Parameters + +• **sandboxId**: `string` + +sandbox ID. + +• **opts?**: `SandboxApiOpts` + +connection options. + +###### Returns + +`Promise`\<`boolean`\> + +`true` if the sandbox was found and killed, `false` otherwise. + +###### Defined in + +sandbox/sandboxApi.ts:55 + +### list() + +> `static` **list**(`opts`?): `Promise`\<`SandboxInfo`[]\> + +List all running sandboxes. + +###### Parameters + +• **opts?**: `SandboxApiOpts` + +connection options. + +###### Returns + +`Promise`\<`SandboxInfo`[]\> + +list of running sandboxes. + +###### Defined in + +sandbox/sandboxApi.ts:90 + +### setTimeout() + +> `static` **setTimeout**(`sandboxId`, `timeoutMs`, `opts`?): `Promise`\<`void`\> + +Set the timeout of the specified sandbox. +After the timeout expires the sandbox will be automatically killed. + +This method can extend or reduce the sandbox timeout set when creating the sandbox or from the last call to Sandbox.setTimeout. + +Maximum time a sandbox can be kept alive is 24 hours (86_400_000 milliseconds) for Pro users and 1 hour (3_600_000 milliseconds) for Hobby users. + +###### Parameters + +• **sandboxId**: `string` + +sandbox ID. + +• **timeoutMs**: `number` + +timeout in **milliseconds**. + +• **opts?**: `SandboxApiOpts` + +connection options. + +###### Returns + +`Promise`\<`void`\> + +###### Defined in + +sandbox/sandboxApi.ts:129 + +## Interfaces + +### SandboxOpts + +Options for creating a new Sandbox. + +#### Properties + +### accessToken? + +> `optional` **accessToken**: `string` + +E2B access token to use for authentication. + +###### Default + +```ts +E2B_ACCESS_TOKEN // environment variable +``` + +###### Defined in + +connectionConfig.ts:24 + +### apiKey? + +> `optional` **apiKey**: `string` + +E2B API key to use for authentication. + +###### Default + +```ts +E2B_API_KEY // environment variable +``` + +###### Defined in + +connectionConfig.ts:18 + +### debug? + +> `optional` **debug**: `boolean` + +**`Internal`** + +If true the SDK starts in the debug mode and connects to the local envd API server. + +###### Default + +E2B_DEBUG // environment variable or `false` + +###### Defined in + +connectionConfig.ts:36 + +### domain? + +> `optional` **domain**: `string` + +Domain to use for the API. + +###### Default + +E2B_DOMAIN // environment variable or `e2b.dev` + +###### Defined in + +connectionConfig.ts:30 + +### envs? + +> `optional` **envs**: `Record`\<`string`, `string`\> + +Custom environment variables for the sandbox. + +Used when executing commands and code in the sandbox. +Can be overridden with the `envs` argument when executing commands or code. + +###### Default + +```ts +{} +``` + +###### Defined in + +sandbox/index.ts:32 + +### logger? + +> `optional` **logger**: `Logger` + +Logger to use for logging messages. It can accept any object that implements `Logger` interface—for example, console. + +###### Defined in + +connectionConfig.ts:46 + +### metadata? + +> `optional` **metadata**: `Record`\<`string`, `string`\> + +Custom metadata for the sandbox. + +###### Default + +```ts +{} +``` + +###### Defined in + +sandbox/index.ts:23 + +### requestTimeoutMs? + +> `optional` **requestTimeoutMs**: `number` + +Timeout for requests to the API in **milliseconds**. + +###### Default + +```ts +30_000 // 30 seconds +``` + +###### Defined in + +connectionConfig.ts:42 + +### timeoutMs? + +> `optional` **timeoutMs**: `number` + +Timeout for the sandbox in **milliseconds**. +Maximum time a sandbox can be kept alive is 24 hours (86_400_000 milliseconds) for Pro users and 1 hour (3_600_000 milliseconds) for Hobby users. + +###### Default + +```ts +300_000 // 5 minutes +``` + +###### Defined in + +sandbox/index.ts:39 diff --git a/docs/sdk-reference/js-sdk/v2.8.2/errors.mdx b/docs/sdk-reference/js-sdk/v2.8.2/errors.mdx new file mode 100644 index 0000000..bfe0deb --- /dev/null +++ b/docs/sdk-reference/js-sdk/v2.8.2/errors.mdx @@ -0,0 +1,271 @@ +--- +sidebarTitle: "Errors" +mode: "center" +--- + +### AuthenticationError + +Thrown when authentication fails. + +#### Constructors + +```ts +new AuthenticationError(message: string): AuthenticationError +``` + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `message` | `string` | + +###### Returns + +`AuthenticationError` + +*** + +### BuildError + +Thrown when the build fails. + +#### Extended by + +- `FileUploadError` + +#### Constructors + +```ts +new BuildError(message: string, stackTrace?: string): BuildError +``` + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `message` | `string` | +| `stackTrace`? | `string` | + +###### Returns + +`BuildError` + +*** + +### FileUploadError + +Thrown when the file upload fails. + +#### Constructors + +```ts +new FileUploadError(message: string, stackTrace?: string): FileUploadError +``` + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `message` | `string` | +| `stackTrace`? | `string` | + +###### Returns + +`FileUploadError` + +*** + +### InvalidArgumentError + +Thrown when an invalid argument is provided. + +#### Constructors + +```ts +new InvalidArgumentError(message: string, stackTrace?: string): InvalidArgumentError +``` + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `message` | `string` | +| `stackTrace`? | `string` | + +###### Returns + +`InvalidArgumentError` + +*** + +### NotEnoughSpaceError + +Thrown when there is not enough disk space. + +#### Constructors + +```ts +new NotEnoughSpaceError(message: string, stackTrace?: string): NotEnoughSpaceError +``` + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `message` | `string` | +| `stackTrace`? | `string` | + +###### Returns + +`NotEnoughSpaceError` + +*** + +### NotFoundError + +Thrown when a resource is not found. + +#### Constructors + +```ts +new NotFoundError(message: string, stackTrace?: string): NotFoundError +``` + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `message` | `string` | +| `stackTrace`? | `string` | + +###### Returns + +`NotFoundError` + +*** + +### RateLimitError + +Thrown when the API rate limit is exceeded. + +#### Constructors + +```ts +new RateLimitError(message: string): RateLimitError +``` + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `message` | `string` | + +###### Returns + +`RateLimitError` + +*** + +### SandboxError + +Base class for all sandbox errors. + +Thrown when general sandbox errors occur. + +#### Extended by + +- `TimeoutError` +- `InvalidArgumentError` +- `NotEnoughSpaceError` +- `NotFoundError` +- `TemplateError` +- `RateLimitError` + +#### Constructors + +```ts +new SandboxError(message?: string, stackTrace?: string): SandboxError +``` + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `message`? | `string` | +| `stackTrace`? | `string` | + +###### Returns + +`SandboxError` + +*** + +### TemplateError + +Thrown when the template uses old envd version. It isn't compatible with the new SDK. + +#### Constructors + +```ts +new TemplateError(message: string, stackTrace?: string): TemplateError +``` + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `message` | `string` | +| `stackTrace`? | `string` | + +###### Returns + +`TemplateError` + +*** + +### TimeoutError + +Thrown when a timeout error occurs. + +The [unavailable] error type is caused by sandbox timeout. + +The [canceled] error type is caused by exceeding request timeout. + +The [deadline_exceeded] error type is caused by exceeding the timeout for command execution, watch, etc. + +The [unknown] error type is sometimes caused by the sandbox timeout when the request is not processed correctly. + +#### Constructors + +```ts +new TimeoutError(message: string, stackTrace?: string): TimeoutError +``` + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `message` | `string` | +| `stackTrace`? | `string` | + +###### Returns + +`TimeoutError` + +## Functions + +### formatSandboxTimeoutError() + +```ts +function formatSandboxTimeoutError(message: string): TimeoutError +``` + +#### Parameters + +| Parameter | Type | +| ------ | ------ | +| `message` | `string` | + +#### Returns + +`TimeoutError` diff --git a/docs/sdk-reference/js-sdk/v2.8.2/sandbox-commands.mdx b/docs/sdk-reference/js-sdk/v2.8.2/sandbox-commands.mdx new file mode 100644 index 0000000..16d736c --- /dev/null +++ b/docs/sdk-reference/js-sdk/v2.8.2/sandbox-commands.mdx @@ -0,0 +1,533 @@ +--- +sidebarTitle: "Commands" +mode: "center" +--- + +### Commands + +Module for starting and interacting with commands in the sandbox. + +#### Constructors + +```ts +new Commands( + transport: Transport, + connectionConfig: ConnectionConfig, + metadata: object): Commands +``` + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `transport` | `Transport` | +| `connectionConfig` | `ConnectionConfig` | +| `metadata` | `object` | +| `metadata.version` | `string` | + +###### Returns + +`Commands` + +#### Methods + +### connect() + +```ts +connect(pid: number, opts?: CommandConnectOpts): Promise +``` + +Connect to a running command. +You can use CommandHandle.wait to wait for the command to finish and get execution results. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `pid` | `number` | process ID of the command to connect to. You can get the list of running commands using Commands.list. | +| `opts`? | `CommandConnectOpts` | connection options. | + +###### Returns + +`Promise`\<`CommandHandle`\> + +`CommandHandle` handle to interact with the running command. + +### kill() + +```ts +kill(pid: number, opts?: CommandRequestOpts): Promise +``` + +Kill a running command specified by its process ID. +It uses `SIGKILL` signal to kill the command. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `pid` | `number` | process ID of the command. You can get the list of running commands using Commands.list. | +| `opts`? | `CommandRequestOpts` | connection options. | + +###### Returns + +`Promise`\<`boolean`\> + +`true` if the command was killed, `false` if the command was not found. + +### list() + +```ts +list(opts?: CommandRequestOpts): Promise +``` + +List all running commands and PTY sessions. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `opts`? | `CommandRequestOpts` | connection options. | + +###### Returns + +`Promise`\<`ProcessInfo`[]\> + +list of running commands and PTY sessions. + +### run() + +###### run(cmd, opts) + +```ts +run(cmd: string, opts?: CommandStartOpts & object): Promise +``` + +Start a new command and wait until it finishes executing. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `cmd` | `string` | command to execute. | +| `opts`? | `CommandStartOpts` & `object` | options for starting the command. | + +###### Returns + +`Promise`\<`CommandResult`\> + +`CommandResult` result of the command execution. + +###### run(cmd, opts) + +```ts +run(cmd: string, opts: CommandStartOpts & object): Promise +``` + +Start a new command in the background. +You can use CommandHandle.wait to wait for the command to finish and get its result. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `cmd` | `string` | command to execute. | +| `opts` | `CommandStartOpts` & `object` | options for starting the command | + +###### Returns + +`Promise`\<`CommandHandle`\> + +`CommandHandle` handle to interact with the running command. + +###### run(cmd, opts) + +```ts +run(cmd: string, opts?: CommandStartOpts & object): Promise +``` + +Start a new command. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `cmd` | `string` | command to execute. | +| `opts`? | `CommandStartOpts` & `object` | options for starting the command. - `opts.background: true` - runs in background, returns `CommandHandle` - `opts.background: false | undefined` - waits for completion, returns `CommandResult` | + +###### Returns + +`Promise`\<`CommandResult` \| `CommandHandle`\> + +Either a `CommandHandle` or a `CommandResult` (depending on `opts.background`). + +### sendStdin() + +```ts +sendStdin( + pid: number, + data: string, +opts?: CommandRequestOpts): Promise +``` + +Send data to command stdin. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `pid` | `number` | process ID of the command. You can get the list of running commands using Commands.list. | +| `data` | `string` | data to send to the command. | +| `opts`? | `CommandRequestOpts` | connection options. | + +###### Returns + +`Promise`\<`void`\> + +*** + +### Pty + +Module for interacting with PTYs (pseudo-terminals) in the sandbox. + +#### Constructors + +```ts +new Pty( + transport: Transport, + connectionConfig: ConnectionConfig, + metadata: object): Pty +``` + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `transport` | `Transport` | +| `connectionConfig` | `ConnectionConfig` | +| `metadata` | `object` | +| `metadata.version` | `string` | + +###### Returns + +`Pty` + +#### Methods + +### create() + +```ts +create(opts: PtyCreateOpts): Promise +``` + +Create a new PTY (pseudo-terminal). + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `opts` | `PtyCreateOpts` | options for creating the PTY. | + +###### Returns + +`Promise`\<`CommandHandle`\> + +handle to interact with the PTY. + +### kill() + +```ts +kill(pid: number, opts?: Pick): Promise +``` + +Kill a running PTY specified by process ID. +It uses `SIGKILL` signal to kill the PTY. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `pid` | `number` | process ID of the PTY. | +| `opts`? | `Pick`\<`ConnectionOpts`, `"requestTimeoutMs"`\> | connection options. | + +###### Returns + +`Promise`\<`boolean`\> + +`true` if the PTY was killed, `false` if the PTY was not found. + +### resize() + +```ts +resize( + pid: number, + size: object, +opts?: Pick): Promise +``` + +Resize PTY. +Call this when the terminal window is resized and the number of columns and rows has changed. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `pid` | `number` | process ID of the PTY. | +| `size` | `object` | new size of the PTY. | +| `size.cols` | `number` | - | +| `size.rows`? | `number` | - | +| `opts`? | `Pick`\<`ConnectionOpts`, `"requestTimeoutMs"`\> | connection options. | + +###### Returns + +`Promise`\<`void`\> + +### sendInput() + +```ts +sendInput( + pid: number, + data: Uint8Array, +opts?: Pick): Promise +``` + +Send input to a PTY. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `pid` | `number` | process ID of the PTY. | +| `data` | `Uint8Array` | input data to send to the PTY. | +| `opts`? | `Pick`\<`ConnectionOpts`, `"requestTimeoutMs"`\> | connection options. | + +###### Returns + +`Promise`\<`void`\> + +## Interfaces + +### CommandRequestOpts + +Options for sending a command request. + +#### Extended by + +- `CommandStartOpts` + +#### Properties + +### requestTimeoutMs? + +```ts +optional requestTimeoutMs: number; +``` + +Timeout for requests to the API in **milliseconds**. + +###### Default + +```ts +60_000 // 60 seconds +``` + +*** + +### CommandStartOpts + +Options for starting a new command. + +#### Properties + +### background? + +```ts +optional background: boolean; +``` + +If true, starts command in the background and the method returns immediately. +You can use CommandHandle.wait to wait for the command to finish. + +### cwd? + +```ts +optional cwd: string; +``` + +Working directory for the command. + +###### Default + +```ts +// home directory of the user used to start the command +``` + +### envs? + +```ts +optional envs: Record; +``` + +Environment variables used for the command. + +This overrides the default environment variables from `Sandbox` constructor. + +###### Default + +`{}` + +### onStderr()? + +```ts +optional onStderr: (data: string) => void | Promise; +``` + +Callback for command stderr output. + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `data` | `string` | + +###### Returns + +`void` \| `Promise`\<`void`\> + +### onStdout()? + +```ts +optional onStdout: (data: string) => void | Promise; +``` + +Callback for command stdout output. + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `data` | `string` | + +###### Returns + +`void` \| `Promise`\<`void`\> + +### requestTimeoutMs? + +```ts +optional requestTimeoutMs: number; +``` + +Timeout for requests to the API in **milliseconds**. + +###### Default + +```ts +60_000 // 60 seconds +``` + +### stdin? + +```ts +optional stdin: boolean; +``` + +If true, command stdin is kept open and you can send data to it using Commands.sendStdin or CommandHandle.sendStdin. + +###### Default + +```ts +false +``` + +### timeoutMs? + +```ts +optional timeoutMs: number; +``` + +Timeout for the command in **milliseconds**. + +###### Default + +```ts +60_000 // 60 seconds +``` + +### user? + +```ts +optional user: string; +``` + +User to run the command as. + +###### Default + +`default Sandbox user (as specified in the template)` + +*** + +### ProcessInfo + +Information about a command, PTY session or start command running in the sandbox as process. + +#### Properties + +### args + +```ts +args: string[]; +``` + +Command arguments. + +### cmd + +```ts +cmd: string; +``` + +Command that was executed. + +### cwd? + +```ts +optional cwd: string; +``` + +Executed command working directory. + +### envs + +```ts +envs: Record; +``` + +Environment variables used for the command. + +### pid + +```ts +pid: number; +``` + +Process ID. + +### tag? + +```ts +optional tag: string; +``` + +Custom tag used for identifying special commands like start command in the custom template. + +## Type Aliases + +### CommandConnectOpts + +```ts +type CommandConnectOpts: Pick & CommandRequestOpts; +``` + +Options for connecting to a command. diff --git a/docs/sdk-reference/js-sdk/v2.8.2/sandbox-filesystem.mdx b/docs/sdk-reference/js-sdk/v2.8.2/sandbox-filesystem.mdx new file mode 100644 index 0000000..c43ac2f --- /dev/null +++ b/docs/sdk-reference/js-sdk/v2.8.2/sandbox-filesystem.mdx @@ -0,0 +1,627 @@ +--- +sidebarTitle: "Filesystem" +mode: "center" +--- + +### FileType + +Sandbox filesystem object type. + +#### Enumeration Members + +| Enumeration Member | Value | Description | +| ------ | ------ | ------ | +| `DIR` | `"dir"` | Filesystem object is a directory. | +| `FILE` | `"file"` | Filesystem object is a file. | + +## Classes + +### Filesystem + +Module for interacting with the sandbox filesystem. + +#### Constructors + +```ts +new Filesystem( + transport: Transport, + envdApi: EnvdApiClient, + connectionConfig: ConnectionConfig): Filesystem +``` + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `transport` | `Transport` | +| `envdApi` | `EnvdApiClient` | +| `connectionConfig` | `ConnectionConfig` | + +###### Returns + +`Filesystem` + +#### Methods + +### exists() + +```ts +exists(path: string, opts?: FilesystemRequestOpts): Promise +``` + +Check if a file or a directory exists. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `path` | `string` | path to a file or a directory | +| `opts`? | `FilesystemRequestOpts` | connection options. | + +###### Returns + +`Promise`\<`boolean`\> + +`true` if the file or directory exists, `false` otherwise + +### getInfo() + +```ts +getInfo(path: string, opts?: FilesystemRequestOpts): Promise +``` + +Get information about a file or directory. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `path` | `string` | path to a file or directory. | +| `opts`? | `FilesystemRequestOpts` | connection options. | + +###### Returns + +`Promise`\<`EntryInfo`\> + +information about the file or directory like name, type, and path. + +### list() + +```ts +list(path: string, opts?: FilesystemListOpts): Promise +``` + +List entries in a directory. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `path` | `string` | path to the directory. | +| `opts`? | `FilesystemListOpts` | connection options. | + +###### Returns + +`Promise`\<`EntryInfo`[]\> + +list of entries in the sandbox filesystem directory. + +### makeDir() + +```ts +makeDir(path: string, opts?: FilesystemRequestOpts): Promise +``` + +Create a new directory and all directories along the way if needed on the specified path. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `path` | `string` | path to a new directory. For example '/dirA/dirB' when creating 'dirB'. | +| `opts`? | `FilesystemRequestOpts` | connection options. | + +###### Returns + +`Promise`\<`boolean`\> + +`true` if the directory was created, `false` if it already exists. + +### read() + +###### read(path, opts) + +```ts +read(path: string, opts?: FilesystemRequestOpts & object): Promise +``` + +Read file content as a `string`. + +You can pass `text`, `bytes`, `blob`, or `stream` to `opts.format` to change the return type. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `path` | `string` | path to the file. | +| `opts`? | `FilesystemRequestOpts` & `object` | connection options. | + +###### Returns + +`Promise`\<`string`\> + +file content as string + +###### read(path, opts) + +```ts +read(path: string, opts?: FilesystemRequestOpts & object): Promise +``` + +Read file content as a `Uint8Array`. + +You can pass `text`, `bytes`, `blob`, or `stream` to `opts.format` to change the return type. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `path` | `string` | path to the file. | +| `opts`? | `FilesystemRequestOpts` & `object` | connection options. | + +###### Returns + +`Promise`\<`Uint8Array`\> + +file content as `Uint8Array` + +###### read(path, opts) + +```ts +read(path: string, opts?: FilesystemRequestOpts & object): Promise +``` + +Read file content as a `Blob`. + +You can pass `text`, `bytes`, `blob`, or `stream` to `opts.format` to change the return type. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `path` | `string` | path to the file. | +| `opts`? | `FilesystemRequestOpts` & `object` | connection options. | + +###### Returns + +`Promise`\<`Blob`\> + +file content as `Blob` + +###### read(path, opts) + +```ts +read(path: string, opts?: FilesystemRequestOpts & object): Promise> +``` + +Read file content as a `ReadableStream`. + +You can pass `text`, `bytes`, `blob`, or `stream` to `opts.format` to change the return type. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `path` | `string` | path to the file. | +| `opts`? | `FilesystemRequestOpts` & `object` | connection options. | + +###### Returns + +`Promise`\<`ReadableStream`\<`Uint8Array`\>\> + +file content as `ReadableStream` + +### remove() + +```ts +remove(path: string, opts?: FilesystemRequestOpts): Promise +``` + +Remove a file or directory. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `path` | `string` | path to a file or directory. | +| `opts`? | `FilesystemRequestOpts` | connection options. | + +###### Returns + +`Promise`\<`void`\> + +### rename() + +```ts +rename( + oldPath: string, + newPath: string, +opts?: FilesystemRequestOpts): Promise +``` + +Rename a file or directory. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `oldPath` | `string` | path to the file or directory to rename. | +| `newPath` | `string` | new path for the file or directory. | +| `opts`? | `FilesystemRequestOpts` | connection options. | + +###### Returns + +`Promise`\<`EntryInfo`\> + +information about renamed file or directory. + +### watchDir() + +```ts +watchDir( + path: string, + onEvent: (event: FilesystemEvent) => void | Promise, +opts?: WatchOpts & object): Promise +``` + +Start watching a directory for filesystem events. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `path` | `string` | path to directory to watch. | +| `onEvent` | (`event`: `FilesystemEvent`) => `void` \| `Promise`\<`void`\> | callback to call when an event in the directory occurs. | +| `opts`? | `WatchOpts` & `object` | connection options. | + +###### Returns + +`Promise`\<`WatchHandle`\> + +`WatchHandle` object for stopping watching directory. + +### write() + +###### write(path, data, opts) + +```ts +write( + path: string, + data: string | ArrayBuffer | Blob | ReadableStream, +opts?: FilesystemRequestOpts): Promise +``` + +Write content to a file. + +Writing to a file that doesn't exist creates the file. + +Writing to a file that already exists overwrites the file. + +Writing to a file at path that doesn't exist creates the necessary directories. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `path` | `string` | path to file. | +| `data` | `string` \| `ArrayBuffer` \| `Blob` \| `ReadableStream`\<`any`\> | data to write to the file. Data can be a string, `ArrayBuffer`, `Blob`, or `ReadableStream`. | +| `opts`? | `FilesystemRequestOpts` | connection options. | + +###### Returns + +`Promise`\<`WriteInfo`\> + +information about the written file + +###### write(files, opts) + +```ts +write(files: WriteEntry[], opts?: FilesystemRequestOpts): Promise +``` + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `files` | `WriteEntry`[] | +| `opts`? | `FilesystemRequestOpts` | + +###### Returns + +`Promise`\<`WriteInfo`[]\> + +## Interfaces + +### EntryInfo + +Sandbox filesystem object information. + +#### Properties + +### group + +```ts +group: string; +``` + +Group owner of the filesystem object. + +### mode + +```ts +mode: number; +``` + +File mode and permission bits. + +### modifiedTime? + +```ts +optional modifiedTime: Date; +``` + +Last modification time of the filesystem object. + +### name + +```ts +name: string; +``` + +Name of the filesystem object. + +### owner + +```ts +owner: string; +``` + +Owner of the filesystem object. + +### path + +```ts +path: string; +``` + +Path to the filesystem object. + +### permissions + +```ts +permissions: string; +``` + +String representation of file permissions (e.g. 'rwxr-xr-x'). + +### size + +```ts +size: number; +``` + +Size of the filesystem object in bytes. + +### symlinkTarget? + +```ts +optional symlinkTarget: string; +``` + +If the filesystem object is a symlink, this is the target of the symlink. + +### type? + +```ts +optional type: FileType; +``` + +Type of the filesystem object. + +*** + +### FilesystemListOpts + +Options for the sandbox filesystem operations. + +#### Properties + +### depth? + +```ts +optional depth: number; +``` + +Depth of the directory to list. + +### requestTimeoutMs? + +```ts +optional requestTimeoutMs: number; +``` + +Timeout for requests to the API in **milliseconds**. + +###### Default + +```ts +60_000 // 60 seconds +``` + +### user? + +```ts +optional user: string; +``` + +User to use for the operation in the sandbox. +This affects the resolution of relative paths and ownership of the created filesystem objects. + +*** + +### FilesystemRequestOpts + +Options for the sandbox filesystem operations. + +#### Extended by + +- `FilesystemListOpts` +- `WatchOpts` + +#### Properties + +### requestTimeoutMs? + +```ts +optional requestTimeoutMs: number; +``` + +Timeout for requests to the API in **milliseconds**. + +###### Default + +```ts +60_000 // 60 seconds +``` + +### user? + +```ts +optional user: string; +``` + +User to use for the operation in the sandbox. +This affects the resolution of relative paths and ownership of the created filesystem objects. + +*** + +### WatchOpts + +Options for watching a directory. + +#### Properties + +### onExit()? + +```ts +optional onExit: (err?: Error) => void | Promise; +``` + +Callback to call when the watch operation stops. + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `err`? | `Error` | + +###### Returns + +`void` \| `Promise`\<`void`\> + +### recursive? + +```ts +optional recursive: boolean; +``` + +Watch the directory recursively + +### requestTimeoutMs? + +```ts +optional requestTimeoutMs: number; +``` + +Timeout for requests to the API in **milliseconds**. + +###### Default + +```ts +60_000 // 60 seconds +``` + +### timeoutMs? + +```ts +optional timeoutMs: number; +``` + +Timeout for the watch operation in **milliseconds**. +You can pass `0` to disable the timeout. + +###### Default + +```ts +60_000 // 60 seconds +``` + +### user? + +```ts +optional user: string; +``` + +User to use for the operation in the sandbox. +This affects the resolution of relative paths and ownership of the created filesystem objects. + +*** + +### WriteInfo + +Sandbox filesystem object information. + +#### Extended by + +- `EntryInfo` + +#### Properties + +### name + +```ts +name: string; +``` + +Name of the filesystem object. + +### path + +```ts +path: string; +``` + +Path to the filesystem object. + +### type? + +```ts +optional type: FileType; +``` + +Type of the filesystem object. + +## Type Aliases + +### WriteEntry + +```ts +type WriteEntry: object; +``` + +#### Type declaration + +| Name | Type | +| ------ | ------ | +| `data` | `string` \| `ArrayBuffer` \| `Blob` \| `ReadableStream` | +| `path` | `string` | diff --git a/docs/sdk-reference/js-sdk/v2.8.2/sandbox.mdx b/docs/sdk-reference/js-sdk/v2.8.2/sandbox.mdx new file mode 100644 index 0000000..e430744 --- /dev/null +++ b/docs/sdk-reference/js-sdk/v2.8.2/sandbox.mdx @@ -0,0 +1,712 @@ +--- +sidebarTitle: "Sandbox" +mode: "center" +--- + +### Sandbox + +E2B cloud sandbox is a secure and isolated cloud environment. + +The sandbox allows you to: +- Access Linux OS +- Create, list, and delete files and directories +- Run commands +- Run isolated code +- Access the internet + +Check docs here. + +Use Sandbox.create to create a new sandbox. + +#### Example + +```ts +import { Sandbox } from 'e2b' + +const sandbox = await Sandbox.create() +``` + +#### Properties + +| Property | Modifier | Type | Description | +| ------ | ------ | ------ | ------ | +| `commands` | `readonly` | `Commands` | Module for running commands in the sandbox | +| `files` | `readonly` | `Filesystem` | Module for interacting with the sandbox filesystem | +| `pty` | `readonly` | `Pty` | Module for interacting with the sandbox pseudo-terminals | +| `sandboxDomain` | `readonly` | `string` | Domain where the sandbox is hosted. | +| `sandboxId` | `readonly` | `string` | Unique identifier of the sandbox. | +| `trafficAccessToken?` | `readonly` | `string` | Traffic access token for accessing sandbox services with restricted public traffic. | + +#### Methods + +### betaPause() + +```ts +betaPause(opts?: ConnectionOpts): Promise +``` + +**`Beta`** + +This feature is in beta and may change in the future. + +Pause a sandbox by its ID. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `opts`? | `ConnectionOpts` | connection options. | + +###### Returns + +`Promise`\<`boolean`\> + +sandbox ID that can be used to resume the sandbox. + +### connect() + +```ts +connect(opts?: SandboxBetaCreateOpts): Promise +``` + +Connect to a sandbox. If the sandbox is paused, it will be automatically resumed. +Sandbox must be either running or be paused. + +With sandbox ID you can connect to the same sandbox from different places or environments (serverless functions, etc). + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `opts`? | `SandboxBetaCreateOpts` | connection options. | + +###### Returns + +`Promise`\<`Sandbox`\> + +A running sandbox instance + +###### Example + +```ts +const sandbox = await Sandbox.create() +await sandbox.betaPause() + +// Connect to the same sandbox. +const sameSandbox = await sandbox.connect() +``` + +### downloadUrl() + +```ts +downloadUrl(path: string, opts?: SandboxUrlOpts): Promise +``` + +Get the URL to download a file from the sandbox. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `path` | `string` | path to the file in the sandbox. | +| `opts`? | `SandboxUrlOpts` | download url options. | + +###### Returns + +`Promise`\<`string`\> + +URL for downloading file. + +### getHost() + +```ts +getHost(port: number): string +``` + +Get the host address for the specified sandbox port. +You can then use this address to connect to the sandbox port from outside the sandbox via HTTP or WebSocket. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `port` | `number` | number of the port in the sandbox. | + +###### Returns + +`string` + +host address of the sandbox port. + +###### Example + +```ts +const sandbox = await Sandbox.create() +// Start an HTTP server +await sandbox.commands.exec('python3 -m http.server 3000') +// Get the hostname of the HTTP server +const serverURL = sandbox.getHost(3000) +``` + +### getInfo() + +```ts +getInfo(opts?: Pick): Promise +``` + +Get sandbox information like sandbox ID, template, metadata, started at/end at date. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `opts`? | `Pick`\<`SandboxOpts`, `"requestTimeoutMs"`\> | connection options. | + +###### Returns + +`Promise`\<`SandboxInfo`\> + +information about the sandbox + +### getMcpToken() + +```ts +getMcpToken(): Promise +``` + +Get the MCP token for the sandbox. + +###### Returns + +`Promise`\<`undefined` \| `string`\> + +MCP token for the sandbox, or undefined if MCP is not enabled. + +### getMcpUrl() + +```ts +getMcpUrl(): string +``` + +Get the MCP URL for the sandbox. + +###### Returns + +`string` + +MCP URL for the sandbox. + +### getMetrics() + +```ts +getMetrics(opts?: SandboxMetricsOpts): Promise +``` + +Get the metrics of the sandbox. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `opts`? | `SandboxMetricsOpts` | connection options. | + +###### Returns + +`Promise`\<`SandboxMetrics`[]\> + +List of sandbox metrics containing CPU, memory and disk usage information. + +### isRunning() + +```ts +isRunning(opts?: Pick): Promise +``` + +Check if the sandbox is running. + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `opts`? | `Pick`\<`ConnectionOpts`, `"requestTimeoutMs"`\> | + +###### Returns + +`Promise`\<`boolean`\> + +`true` if the sandbox is running, `false` otherwise. + +###### Example + +```ts +const sandbox = await Sandbox.create() +await sandbox.isRunning() // Returns true + +await sandbox.kill() +await sandbox.isRunning() // Returns false +``` + +### kill() + +```ts +kill(opts?: Pick): Promise +``` + +Kill the sandbox. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `opts`? | `Pick`\<`SandboxOpts`, `"requestTimeoutMs"`\> | connection options. | + +###### Returns + +`Promise`\<`void`\> + +### setTimeout() + +```ts +setTimeout(timeoutMs: number, opts?: Pick): Promise +``` + +Set the timeout of the sandbox. +After the timeout expires the sandbox will be automatically killed. + +This method can extend or reduce the sandbox timeout set when creating the sandbox or from the last call to `.setTimeout`. +Maximum time a sandbox can be kept alive is 24 hours (86_400_000 milliseconds) for Pro users and 1 hour (3_600_000 milliseconds) for Hobby users. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `timeoutMs` | `number` | timeout in **milliseconds**. | +| `opts`? | `Pick`\<`SandboxOpts`, `"requestTimeoutMs"`\> | connection options. | + +###### Returns + +`Promise`\<`void`\> + +### uploadUrl() + +```ts +uploadUrl(path?: string, opts?: SandboxUrlOpts): Promise +``` + +Get the URL to upload a file to the sandbox. + +You have to send a POST request to this URL with the file as multipart/form-data. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `path`? | `string` | path to the file in the sandbox. | +| `opts`? | `SandboxUrlOpts` | download url options. | + +###### Returns + +`Promise`\<`string`\> + +URL for uploading file. + +### betaCreate() + +###### betaCreate(this, opts) + +```ts +static betaCreate(this: S, opts?: SandboxBetaCreateOpts): Promise> +``` + +**`Beta`** + +This feature is in beta and may change in the future. + +Create a new sandbox from the default `base` sandbox template. + +###### Type Parameters + +| Type Parameter | +| ------ | +| `S` *extends* *typeof* `Sandbox` | + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `this` | `S` | - | +| `opts`? | `SandboxBetaCreateOpts` | connection options. | + +###### Returns + +`Promise`\<`InstanceType`\<`S`\>\> + +sandbox instance for the new sandbox. + +###### Example + +```ts +const sandbox = await Sandbox.betaCreate() +``` + +###### Constructs + +Sandbox + +###### betaCreate(this, template, opts) + +```ts +static betaCreate( + this: S, + template: string, +opts?: SandboxBetaCreateOpts): Promise> +``` + +**`Beta`** + +This feature is in beta and may change in the future. + +Create a new sandbox from the specified sandbox template. + +###### Type Parameters + +| Type Parameter | +| ------ | +| `S` *extends* *typeof* `Sandbox` | + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `this` | `S` | - | +| `template` | `string` | sandbox template name or ID. | +| `opts`? | `SandboxBetaCreateOpts` | connection options. | + +###### Returns + +`Promise`\<`InstanceType`\<`S`\>\> + +sandbox instance for the new sandbox. + +###### Example + +```ts +const sandbox = await Sandbox.betaCreate('') +``` + +###### Constructs + +Sandbox + +### betaPause() + +```ts +static betaPause(sandboxId: string, opts?: SandboxApiOpts): Promise +``` + +Pause the sandbox specified by sandbox ID. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `sandboxId` | `string` | sandbox ID. | +| `opts`? | `SandboxApiOpts` | connection options. | + +###### Returns + +`Promise`\<`boolean`\> + +`true` if the sandbox got paused, `false` if the sandbox was already paused. + +### connect() + +```ts +static connect( + this: S, + sandboxId: string, +opts?: SandboxConnectOpts): Promise> +``` + +Connect to a sandbox. If the sandbox is paused, it will be automatically resumed. +Sandbox must be either running or be paused. + +With sandbox ID you can connect to the same sandbox from different places or environments (serverless functions, etc). + +###### Type Parameters + +| Type Parameter | +| ------ | +| `S` *extends* *typeof* `Sandbox` | + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `this` | `S` | - | +| `sandboxId` | `string` | sandbox ID. | +| `opts`? | `SandboxConnectOpts` | connection options. | + +###### Returns + +`Promise`\<`InstanceType`\<`S`\>\> + +A running sandbox instance + +###### Example + +```ts +const sandbox = await Sandbox.create() +const sandboxId = sandbox.sandboxId + +// Connect to the same sandbox. +const sameSandbox = await Sandbox.connect(sandboxId) +``` + +### create() + +###### create(this, opts) + +```ts +static create(this: S, opts?: SandboxOpts): Promise> +``` + +Create a new sandbox from the default `base` sandbox template. + +###### Type Parameters + +| Type Parameter | +| ------ | +| `S` *extends* *typeof* `Sandbox` | + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `this` | `S` | - | +| `opts`? | `SandboxOpts` | connection options. | + +###### Returns + +`Promise`\<`InstanceType`\<`S`\>\> + +sandbox instance for the new sandbox. + +###### Example + +```ts +const sandbox = await Sandbox.create() +``` + +###### Constructs + +Sandbox + +###### create(this, template, opts) + +```ts +static create( + this: S, + template: string, +opts?: SandboxOpts): Promise> +``` + +Create a new sandbox from the specified sandbox template. + +###### Type Parameters + +| Type Parameter | +| ------ | +| `S` *extends* *typeof* `Sandbox` | + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `this` | `S` | - | +| `template` | `string` | sandbox template name or ID. | +| `opts`? | `SandboxOpts` | connection options. | + +###### Returns + +`Promise`\<`InstanceType`\<`S`\>\> + +sandbox instance for the new sandbox. + +###### Example + +```ts +const sandbox = await Sandbox.create('') +``` + +###### Constructs + +Sandbox + +### getFullInfo() + +```ts +static getFullInfo(sandboxId: string, opts?: SandboxApiOpts): Promise +``` + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `sandboxId` | `string` | +| `opts`? | `SandboxApiOpts` | + +###### Returns + +`Promise`\<`object`\> + +| Name | Type | Default value | +| ------ | ------ | ------ | +| `cpuCount` | `number` | res.data.cpuCount | +| `endAt` | `Date` | - | +| `envdAccessToken` | `undefined` \| `string` | res.data.envdAccessToken | +| `envdVersion` | `string` | res.data.envdVersion | +| `memoryMB` | `number` | res.data.memoryMB | +| `metadata` | `object` | - | +| `name`? | `string` | res.data.alias | +| `sandboxDomain` | `undefined` \| `string` | - | +| `sandboxId` | `string` | res.data.sandboxID | +| `startedAt` | `Date` | - | +| `state` | `"running"` \| `"paused"` | res.data.state | +| `templateId` | `string` | res.data.templateID | + +### getInfo() + +```ts +static getInfo(sandboxId: string, opts?: SandboxApiOpts): Promise +``` + +Get sandbox information like sandbox ID, template, metadata, started at/end at date. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `sandboxId` | `string` | sandbox ID. | +| `opts`? | `SandboxApiOpts` | connection options. | + +###### Returns + +`Promise`\<`SandboxInfo`\> + +sandbox information. + +### getMetrics() + +```ts +static getMetrics(sandboxId: string, opts?: SandboxMetricsOpts): Promise +``` + +Get the metrics of the sandbox. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `sandboxId` | `string` | sandbox ID. | +| `opts`? | `SandboxMetricsOpts` | sandbox metrics options. | + +###### Returns + +`Promise`\<`SandboxMetrics`[]\> + +List of sandbox metrics containing CPU, memory and disk usage information. + +### kill() + +```ts +static kill(sandboxId: string, opts?: SandboxApiOpts): Promise +``` + +Kill the sandbox specified by sandbox ID. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `sandboxId` | `string` | sandbox ID. | +| `opts`? | `SandboxApiOpts` | connection options. | + +###### Returns + +`Promise`\<`boolean`\> + +`true` if the sandbox was found and killed, `false` otherwise. + +### list() + +```ts +static list(opts?: SandboxListOpts): SandboxPaginator +``` + +List all sandboxes. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `opts`? | `SandboxListOpts` | connection options. | + +###### Returns + +`SandboxPaginator` + +paginator for listing sandboxes. + +### setTimeout() + +```ts +static setTimeout( + sandboxId: string, + timeoutMs: number, +opts?: SandboxApiOpts): Promise +``` + +Set the timeout of the specified sandbox. +After the timeout expires the sandbox will be automatically killed. + +This method can extend or reduce the sandbox timeout set when creating the sandbox or from the last call to Sandbox.setTimeout. + +Maximum time a sandbox can be kept alive is 24 hours (86_400_000 milliseconds) for Pro users and 1 hour (3_600_000 milliseconds) for Hobby users. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `sandboxId` | `string` | sandbox ID. | +| `timeoutMs` | `number` | timeout in **milliseconds**. | +| `opts`? | `SandboxApiOpts` | connection options. | + +###### Returns + +`Promise`\<`void`\> + +## Interfaces + +### SandboxUrlOpts + +Options for sandbox upload/download URL generation. + +#### Properties + +### user? + +```ts +optional user: string; +``` + +User that will be used to access the file. + +### useSignatureExpiration? + +```ts +optional useSignatureExpiration: number; +``` + +Use signature expiration for the URL. +Optional parameter to set the expiration time for the signature in seconds. diff --git a/docs/sdk-reference/js-sdk/v2.8.2/template-logger.mdx b/docs/sdk-reference/js-sdk/v2.8.2/template-logger.mdx new file mode 100644 index 0000000..fdebde3 --- /dev/null +++ b/docs/sdk-reference/js-sdk/v2.8.2/template-logger.mdx @@ -0,0 +1,196 @@ +--- +sidebarTitle: "Logger" +mode: "center" +--- + +### LogEntry + +Represents a single log entry from the template build process. + +#### Extended by + +- `LogEntryStart` +- `LogEntryEnd` + +#### Constructors + +```ts +new LogEntry( + timestamp: Date, + level: LogEntryLevel, + message: string): LogEntry +``` + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `timestamp` | `Date` | +| `level` | `LogEntryLevel` | +| `message` | `string` | + +###### Returns + +`LogEntry` + +#### Properties + +| Property | Modifier | Type | +| ------ | ------ | ------ | +| `level` | `readonly` | `LogEntryLevel` | +| `message` | `readonly` | `string` | +| `timestamp` | `readonly` | `Date` | + +#### Methods + +### toString() + +```ts +toString(): string +``` + +###### Returns + +`string` + +*** + +### LogEntryEnd + +Special log entry indicating the end of a build process. + +#### Constructors + +```ts +new LogEntryEnd(timestamp: Date, message: string): LogEntryEnd +``` + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `timestamp` | `Date` | +| `message` | `string` | + +###### Returns + +`LogEntryEnd` + +#### Properties + +| Property | Modifier | Type | Inherited from | +| ------ | ------ | ------ | ------ | +| `level` | `readonly` | `LogEntryLevel` | `LogEntry`.`level` | +| `message` | `readonly` | `string` | `LogEntry`.`message` | +| `timestamp` | `readonly` | `Date` | `LogEntry`.`timestamp` | + +#### Methods + +### toString() + +```ts +toString(): string +``` + +###### Returns + +`string` + +*** + +### LogEntryStart + +Special log entry indicating the start of a build process. + +#### Constructors + +```ts +new LogEntryStart(timestamp: Date, message: string): LogEntryStart +``` + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `timestamp` | `Date` | +| `message` | `string` | + +###### Returns + +`LogEntryStart` + +#### Properties + +| Property | Modifier | Type | Inherited from | +| ------ | ------ | ------ | ------ | +| `level` | `readonly` | `LogEntryLevel` | `LogEntry`.`level` | +| `message` | `readonly` | `string` | `LogEntry`.`message` | +| `timestamp` | `readonly` | `Date` | `LogEntry`.`timestamp` | + +#### Methods + +### toString() + +```ts +toString(): string +``` + +###### Returns + +`string` + +## Type Aliases + +### LogEntryLevel + +```ts +type LogEntryLevel: "debug" | "info" | "warn" | "error"; +``` + +Log entry severity levels. + +## Functions + +### defaultBuildLogger() + +```ts +function defaultBuildLogger(options?: object): (logEntry: LogEntry) => void +``` + +Create a default build logger with animated timer display. + +#### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `options`? | `object` | Logger configuration options | +| `options.minLevel`? | `LogEntryLevel` | Minimum log level to display (default: 'info') | + +#### Returns + +`Function` + +Logger function that accepts LogEntry instances + +### Parameters + +| Parameter | Type | +| ------ | ------ | +| `logEntry` | `LogEntry` | + +### Returns + +`void` + +#### Example + +```ts +import { Template, defaultBuildLogger } from 'e2b' + +const template = Template().fromPythonImage() + +await Template.build(template, { + alias: 'my-template', + onBuildLogs: defaultBuildLogger({ minLevel: 'debug' }) +}) +``` diff --git a/docs/sdk-reference/js-sdk/v2.8.2/template-readycmd.mdx b/docs/sdk-reference/js-sdk/v2.8.2/template-readycmd.mdx new file mode 100644 index 0000000..56fb0b7 --- /dev/null +++ b/docs/sdk-reference/js-sdk/v2.8.2/template-readycmd.mdx @@ -0,0 +1,202 @@ +--- +sidebarTitle: "Readycmd" +mode: "center" +--- + +### ReadyCmd + +Class for ready check commands. + +#### Constructors + +```ts +new ReadyCmd(cmd: string): ReadyCmd +``` + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `cmd` | `string` | + +###### Returns + +`ReadyCmd` + +#### Methods + +### getCmd() + +```ts +getCmd(): string +``` + +###### Returns + +`string` + +## Functions + +### waitForFile() + +```ts +function waitForFile(filename: string): ReadyCmd +``` + +Wait for a file to exist. +Uses shell test command to check file existence. + +#### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `filename` | `string` | Path to the file to wait for | + +#### Returns + +`ReadyCmd` + +ReadyCmd that checks for the file + +#### Example + +```ts +import { Template, waitForFile } from 'e2b' + +const template = Template() + .fromBaseImage() + .setStartCmd('./init.sh', waitForFile('/tmp/ready')) +``` + +*** + +### waitForPort() + +```ts +function waitForPort(port: number): ReadyCmd +``` + +Wait for a port to be listening. +Uses `ss` command to check if a port is open and listening. + +#### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `port` | `number` | Port number to wait for | + +#### Returns + +`ReadyCmd` + +ReadyCmd that checks for the port + +#### Example + +```ts +import { Template, waitForPort } from 'e2b' + +const template = Template() + .fromPythonImage() + .setStartCmd('python -m http.server 8000', waitForPort(8000)) +``` + +*** + +### waitForProcess() + +```ts +function waitForProcess(processName: string): ReadyCmd +``` + +Wait for a process with a specific name to be running. +Uses `pgrep` to check if a process exists. + +#### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `processName` | `string` | Name of the process to wait for | + +#### Returns + +`ReadyCmd` + +ReadyCmd that checks for the process + +#### Example + +```ts +import { Template, waitForProcess } from 'e2b' + +const template = Template() + .fromBaseImage() + .setStartCmd('./my-daemon', waitForProcess('my-daemon')) +``` + +*** + +### waitForTimeout() + +```ts +function waitForTimeout(timeout: number): ReadyCmd +``` + +Wait for a specified timeout before considering the sandbox ready. +Uses `sleep` command to wait for a fixed duration. + +#### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `timeout` | `number` | Time to wait in milliseconds (minimum: 1000ms / 1 second) | + +#### Returns + +`ReadyCmd` + +ReadyCmd that waits for the specified duration + +#### Example + +```ts +import { Template, waitForTimeout } from 'e2b' + +const template = Template() + .fromNodeImage() + .setStartCmd('npm start', waitForTimeout(5000)) // Wait 5 seconds +``` + +*** + +### waitForURL() + +```ts +function waitForURL(url: string, statusCode: number): ReadyCmd +``` + +Wait for a URL to return a specific HTTP status code. +Uses `curl` to make HTTP requests and check the response status. + +#### Parameters + +| Parameter | Type | Default value | Description | +| ------ | ------ | ------ | ------ | +| `url` | `string` | `undefined` | URL to check (e.g., 'http://localhost:3000/health') | +| `statusCode` | `number` | `200` | Expected HTTP status code (default: 200) | + +#### Returns + +`ReadyCmd` + +ReadyCmd that checks the URL + +#### Example + +```ts +import { Template, waitForURL } from 'e2b' + +const template = Template() + .fromNodeImage() + .setStartCmd('npm start', waitForURL('http://localhost:3000/health')) +``` diff --git a/docs/sdk-reference/js-sdk/v2.8.2/template.mdx b/docs/sdk-reference/js-sdk/v2.8.2/template.mdx new file mode 100644 index 0000000..c644e02 --- /dev/null +++ b/docs/sdk-reference/js-sdk/v2.8.2/template.mdx @@ -0,0 +1,2042 @@ +--- +sidebarTitle: "Template" +mode: "center" +--- + +### TemplateBase + +Base class for building E2B sandbox templates. + +#### Implements + +- `TemplateFromImage` +- `TemplateBuilder` +- `TemplateFinal` + +#### Constructors + +```ts +new TemplateBase(options?: TemplateOptions): TemplateBase +``` + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `options`? | `TemplateOptions` | + +###### Returns + +`TemplateBase` + +#### Methods + +### addMcpServer() + +```ts +addMcpServer(servers: keyof McpServer | keyof McpServer[]): TemplateBuilder +``` + +Install MCP servers using mcp-gateway. +Note: Requires a base image with mcp-gateway pre-installed (e.g., mcp-gateway). + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `servers` | keyof McpServer \| keyof McpServer[] | MCP server name(s) | + +###### Returns + +`TemplateBuilder` + +###### Throws + +If the base template is not mcp-gateway + +###### Example + +```ts +template.addMcpServer('exa') +template.addMcpServer(['brave', 'firecrawl', 'duckduckgo']) +``` + +###### Implementation of + +`TemplateBuilder`.`addMcpServer` + +### aptInstall() + +```ts +aptInstall(packages: string | string[], options?: object): TemplateBuilder +``` + +Install Debian/Ubuntu packages using apt-get. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `packages` | `string` \| `string`[] | Package name(s) | +| `options`? | `object` | - | +| `options.noInstallRecommends`? | `boolean` | - | + +###### Returns + +`TemplateBuilder` + +###### Example + +```ts +template.aptInstall('vim') +template.aptInstall(['git', 'curl', 'wget']) +template.aptInstall(['vim'], { noInstallRecommends: true }) +``` + +###### Implementation of + +`TemplateBuilder`.`aptInstall` + +### betaDevContainerPrebuild() + +```ts +betaDevContainerPrebuild(devcontainerDirectory: string): TemplateBuilder +``` + +Prebuild a devcontainer from the specified directory. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `devcontainerDirectory` | `string` | Path to the devcontainer directory | + +###### Returns + +`TemplateBuilder` + +###### Example + +```ts +template + .gitClone('https://myrepo.com/project.git', '/my-devcontainer') + .betaDevContainerPrebuild('/my-devcontainer') +``` + +###### Implementation of + +`TemplateBuilder`.`betaDevContainerPrebuild` + +### betaSetDevContainerStart() + +```ts +betaSetDevContainerStart(devcontainerDirectory: string): TemplateFinal +``` + +Start a devcontainer from the specified directory. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `devcontainerDirectory` | `string` | Path to the devcontainer directory | + +###### Returns + +`TemplateFinal` + +###### Example + +```ts +template + .gitClone('https://myrepo.com/project.git', '/my-devcontainer') + .startDevcontainer('/my-devcontainer') + +// Prebuild and start +template + .gitClone('https://myrepo.com/project.git', '/my-devcontainer') + .betaDevContainerPrebuild('/my-devcontainer') + // Other instructions... + .betaSetDevContainerStart('/my-devcontainer') +``` + +###### Implementation of + +`TemplateBuilder`.`betaSetDevContainerStart` + +### bunInstall() + +```ts +bunInstall(packages?: string | string[], options?: object): TemplateBuilder +``` + +Install Bun packages using bun. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `packages`? | `string` \| `string`[] | Package name(s) or undefined for package.json | +| `options`? | `object` | Install options | +| `options.dev`? | `boolean` | - | +| `options.g`? | `boolean` | - | + +###### Returns + +`TemplateBuilder` + +###### Example + +```ts +template.bunInstall('express') +template.bunInstall(['lodash', 'axios']) +template.bunInstall('tsx', { g: true }) +template.bunInstall('typescript', { dev: true }) +template.bunInstall() // Installs from package.json +``` + +###### Implementation of + +`TemplateBuilder`.`bunInstall` + +### copy() + +```ts +copy( + src: PathLike | PathLike[], + dest: PathLike, + options?: object): TemplateBuilder +``` + +Copy files or directories into the template. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `src` | `PathLike` \| `PathLike`[] | Source path(s) | +| `dest` | `PathLike` | Destination path | +| `options`? | `object` | Copy options | +| `options.forceUpload`? | `true` | - | +| `options.mode`? | `number` | - | +| `options.resolveSymlinks`? | `boolean` | - | +| `options.user`? | `string` | - | + +###### Returns + +`TemplateBuilder` + +###### Example + +```ts +template.copy('requirements.txt', '/home/user/') +template.copy(['app.ts', 'config.ts'], '/app/', { mode: 0o755 }) +``` + +###### Implementation of + +`TemplateBuilder`.`copy` + +### copyItems() + +```ts +copyItems(items: CopyItem[]): TemplateBuilder +``` + +Copy multiple items with individual options. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `items` | `CopyItem`[] | Array of copy items | + +###### Returns + +`TemplateBuilder` + +###### Example + +```ts +template.copyItems([ + { src: 'app.ts', dest: '/app/' }, + { src: 'config.ts', dest: '/app/', mode: 0o644 } +]) +``` + +###### Implementation of + +`TemplateBuilder`.`copyItems` + +### fromAWSRegistry() + +```ts +fromAWSRegistry(image: string, credentials: object): TemplateBuilder +``` + +Start from a Docker image in AWS ECR. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `image` | `string` | Full ECR image path | +| `credentials` | `object` | AWS credentials | +| `credentials.accessKeyId` | `string` | - | +| `credentials.region` | `string` | - | +| `credentials.secretAccessKey` | `string` | - | + +###### Returns + +`TemplateBuilder` + +###### Example + +```ts +Template().fromAWSRegistry( + '123456789.dkr.ecr.us-west-2.amazonaws.com/myimage:latest', + { + accessKeyId: 'AKIA...', + secretAccessKey: '...', + region: 'us-west-2' + } +) +``` + +###### Implementation of + +`TemplateFromImage.fromAWSRegistry` + +### fromBaseImage() + +```ts +fromBaseImage(): TemplateBuilder +``` + +Start from E2B's default base image (e2bdev/base:latest). + +###### Returns + +`TemplateBuilder` + +###### Example + +```ts +Template().fromBaseImage() +``` + +###### Implementation of + +`TemplateFromImage.fromBaseImage` + +### fromBunImage() + +```ts +fromBunImage(variant: string): TemplateBuilder +``` + +Start from a Bun-based Docker image. + +###### Parameters + +| Parameter | Type | Default value | Description | +| ------ | ------ | ------ | ------ | +| `variant` | `string` | `'latest'` | Bun variant (default: 'latest') | + +###### Returns + +`TemplateBuilder` + +###### Example + +```ts +Template().fromBunImage('1.3') +``` + +###### Implementation of + +`TemplateFromImage.fromBunImage` + +### fromDebianImage() + +```ts +fromDebianImage(variant: string): TemplateBuilder +``` + +Start from a Debian-based Docker image. + +###### Parameters + +| Parameter | Type | Default value | Description | +| ------ | ------ | ------ | ------ | +| `variant` | `string` | `'stable'` | Debian variant (default: 'stable') | + +###### Returns + +`TemplateBuilder` + +###### Example + +```ts +Template().fromDebianImage('bookworm') +``` + +###### Implementation of + +`TemplateFromImage.fromDebianImage` + +### fromDockerfile() + +```ts +fromDockerfile(dockerfileContentOrPath: string): TemplateBuilder +``` + +Parse a Dockerfile and convert it to Template SDK format. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `dockerfileContentOrPath` | `string` | Dockerfile content or path | + +###### Returns + +`TemplateBuilder` + +###### Example + +```ts +Template().fromDockerfile('Dockerfile') +Template().fromDockerfile('FROM python:3\nRUN pip install numpy') +``` + +###### Implementation of + +`TemplateFromImage.fromDockerfile` + +### fromGCPRegistry() + +```ts +fromGCPRegistry(image: string, credentials: object): TemplateBuilder +``` + +Start from a Docker image in Google Container Registry. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `image` | `string` | Full GCR/GAR image path | +| `credentials` | `object` | GCP service account credentials | +| `credentials.serviceAccountJSON` | `string` \| `object` | - | + +###### Returns + +`TemplateBuilder` + +###### Example + +```ts +Template().fromGCPRegistry( + 'gcr.io/myproject/myimage:latest', + { serviceAccountJSON: 'path/to/service-account.json' } +) +``` + +###### Implementation of + +`TemplateFromImage.fromGCPRegistry` + +### fromImage() + +```ts +fromImage(baseImage: string, credentials?: object): TemplateBuilder +``` + +Start from a custom Docker image. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `baseImage` | `string` | Docker image name | +| `credentials`? | `object` | Optional credentials for private registries | +| `credentials.password`? | `string` | - | +| `credentials.username`? | `string` | - | + +###### Returns + +`TemplateBuilder` + +###### Example + +```ts +Template().fromImage('python:3') + +// With credentials (optional) +Template().fromImage('myregistry.com/myimage:latest', { + username: 'user', + password: 'pass' +}) +``` + +###### Implementation of + +`TemplateFromImage.fromImage` + +### fromNodeImage() + +```ts +fromNodeImage(variant: string): TemplateBuilder +``` + +Start from a Node.js-based Docker image. + +###### Parameters + +| Parameter | Type | Default value | Description | +| ------ | ------ | ------ | ------ | +| `variant` | `string` | `'lts'` | Node.js variant (default: 'lts') | + +###### Returns + +`TemplateBuilder` + +###### Example + +```ts +Template().fromNodeImage('24') +``` + +###### Implementation of + +`TemplateFromImage.fromNodeImage` + +### fromPythonImage() + +```ts +fromPythonImage(version: string): TemplateBuilder +``` + +Start from a Python-based Docker image. + +###### Parameters + +| Parameter | Type | Default value | Description | +| ------ | ------ | ------ | ------ | +| `version` | `string` | `'3'` | Python version (default: '3') | + +###### Returns + +`TemplateBuilder` + +###### Example + +```ts +Template().fromPythonImage('3') +``` + +###### Implementation of + +`TemplateFromImage.fromPythonImage` + +### fromTemplate() + +```ts +fromTemplate(template: string): TemplateBuilder +``` + +Start from an existing E2B template. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `template` | `string` | E2B template ID or alias | + +###### Returns + +`TemplateBuilder` + +###### Example + +```ts +Template().fromTemplate('my-base-template') +``` + +###### Implementation of + +`TemplateFromImage.fromTemplate` + +### fromUbuntuImage() + +```ts +fromUbuntuImage(variant: string): TemplateBuilder +``` + +Start from an Ubuntu-based Docker image. + +###### Parameters + +| Parameter | Type | Default value | Description | +| ------ | ------ | ------ | ------ | +| `variant` | `string` | `'latest'` | Ubuntu variant (default: 'latest') | + +###### Returns + +`TemplateBuilder` + +###### Example + +```ts +Template().fromUbuntuImage('24.04') +``` + +###### Implementation of + +`TemplateFromImage.fromUbuntuImage` + +### gitClone() + +```ts +gitClone( + url: string, + path?: PathLike, + options?: object): TemplateBuilder +``` + +Clone a Git repository. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `url` | `string` | Repository URL | +| `path`? | `PathLike` | Optional destination path | +| `options`? | `object` | Clone options | +| `options.branch`? | `string` | - | +| `options.depth`? | `number` | - | +| `options.user`? | `string` | - | + +###### Returns + +`TemplateBuilder` + +###### Example + +```ts +template.gitClone('https://github.com/user/repo.git', '/app/repo') +template.gitClone('https://github.com/user/repo.git', undefined, { + branch: 'main', + depth: 1 +}) +template.gitClone('https://github.com/user/repo.git', '/app/repo', { + user: 'root' +}) +``` + +###### Implementation of + +`TemplateBuilder`.`gitClone` + +### makeDir() + +```ts +makeDir(path: PathLike | PathLike[], options?: object): TemplateBuilder +``` + +Create directories. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `path` | `PathLike` \| `PathLike`[] | Directory path(s) | +| `options`? | `object` | Directory options | +| `options.mode`? | `number` | - | +| `options.user`? | `string` | - | + +###### Returns + +`TemplateBuilder` + +###### Example + +```ts +template.makeDir('/app/data', { mode: 0o755 }) +template.makeDir(['/app/logs', '/app/cache']) +template.makeDir('/app/data', { mode: 0o755, user: 'root' }) +``` + +###### Implementation of + +`TemplateBuilder`.`makeDir` + +### makeSymlink() + +```ts +makeSymlink( + src: PathLike, + dest: PathLike, + options?: object): TemplateBuilder +``` + +Create a symbolic link. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `src` | `PathLike` | Source path (target) | +| `dest` | `PathLike` | Destination path (symlink location) | +| `options`? | `object` | Symlink options | +| `options.force`? | `boolean` | - | +| `options.user`? | `string` | - | + +###### Returns + +`TemplateBuilder` + +###### Example + +```ts +template.makeSymlink('/usr/bin/python3', '/usr/bin/python') +template.makeSymlink('/usr/bin/python3', '/usr/bin/python', { user: 'root' }) +template.makeSymlink('/usr/bin/python3', '/usr/bin/python', { force: true }) +``` + +###### Implementation of + +`TemplateBuilder`.`makeSymlink` + +### npmInstall() + +```ts +npmInstall(packages?: string | string[], options?: object): TemplateBuilder +``` + +Install Node.js packages using npm. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `packages`? | `string` \| `string`[] | Package name(s) or undefined for package.json | +| `options`? | `object` | Install options | +| `options.dev`? | `boolean` | - | +| `options.g`? | `boolean` | - | + +###### Returns + +`TemplateBuilder` + +###### Example + +```ts +template.npmInstall('express') +template.npmInstall(['lodash', 'axios']) +template.npmInstall('tsx', { g: true }) +template.npmInstall('typescript', { dev: true }) +template.npmInstall() // Installs from package.json +``` + +###### Implementation of + +`TemplateBuilder`.`npmInstall` + +### pipInstall() + +```ts +pipInstall(packages?: string | string[], options?: object): TemplateBuilder +``` + +Install Python packages using pip. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `packages`? | `string` \| `string`[] | Package name(s) or undefined for current directory | +| `options`? | `object` | Install options | +| `options.g`? | `boolean` | Install globally as root (default: true). Set to false for user-only installation with --user flag | + +###### Returns + +`TemplateBuilder` + +###### Example + +```ts +template.pipInstall('numpy') // Installs globally (default) +template.pipInstall(['pandas', 'scikit-learn']) +template.pipInstall('numpy', { g: false }) // Install for user only +template.pipInstall() // Installs from current directory +``` + +###### Implementation of + +`TemplateBuilder`.`pipInstall` + +### remove() + +```ts +remove(path: PathLike | PathLike[], options?: object): TemplateBuilder +``` + +Remove files or directories. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `path` | `PathLike` \| `PathLike`[] | Path(s) to remove | +| `options`? | `object` | Remove options | +| `options.force`? | `boolean` | - | +| `options.recursive`? | `boolean` | - | +| `options.user`? | `string` | - | + +###### Returns + +`TemplateBuilder` + +###### Example + +```ts +template.remove('/tmp/cache', { recursive: true, force: true }) +template.remove('/tmp/cache', { recursive: true, force: true, user: 'root' }) +``` + +###### Implementation of + +`TemplateBuilder`.`remove` + +### rename() + +```ts +rename( + src: PathLike, + dest: PathLike, + options?: object): TemplateBuilder +``` + +Rename or move a file or directory. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `src` | `PathLike` | Source path | +| `dest` | `PathLike` | Destination path | +| `options`? | `object` | Rename options | +| `options.force`? | `boolean` | - | +| `options.user`? | `string` | - | + +###### Returns + +`TemplateBuilder` + +###### Example + +```ts +template.rename('/tmp/old.txt', '/tmp/new.txt') +template.rename('/tmp/old.txt', '/tmp/new.txt', { user: 'root' }) +``` + +###### Implementation of + +`TemplateBuilder`.`rename` + +### runCmd() + +###### runCmd(command, options) + +```ts +runCmd(command: string, options?: object): TemplateBuilder +``` + +Run a shell command. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `command` | `string` | Command string | +| `options`? | `object` | Command options | +| `options.user`? | `string` | - | + +###### Returns + +`TemplateBuilder` + +###### Example + +```ts +template.runCmd('apt-get update') +template.runCmd(['pip install numpy', 'pip install pandas']) +template.runCmd('apt-get install vim', { user: 'root' }) +``` + +###### Implementation of + +`TemplateBuilder`.`runCmd` + +###### runCmd(commands, options) + +```ts +runCmd(commands: string[], options?: object): TemplateBuilder +``` + +Run a shell command. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `commands` | `string`[] | - | +| `options`? | `object` | Command options | +| `options.user`? | `string` | - | + +###### Returns + +`TemplateBuilder` + +###### Example + +```ts +template.runCmd('apt-get update') +template.runCmd(['pip install numpy', 'pip install pandas']) +template.runCmd('apt-get install vim', { user: 'root' }) +``` + +###### Implementation of + +`TemplateBuilder`.`runCmd` + +### setEnvs() + +```ts +setEnvs(envs: Record): TemplateBuilder +``` + +Set environment variables. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `envs` | `Record`\<`string`, `string`\> | Environment variables | + +###### Returns + +`TemplateBuilder` + +###### Example + +```ts +template.setEnvs({ NODE_ENV: 'production', PORT: '8080' }) +``` + +###### Implementation of + +`TemplateBuilder`.`setEnvs` + +### setReadyCmd() + +```ts +setReadyCmd(readyCommand: string | ReadyCmd): TemplateFinal +``` + +Set or update the ready check command. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `readyCommand` | `string` \| `ReadyCmd` | Command to check readiness | + +###### Returns + +`TemplateFinal` + +###### Example + +```ts +// Using a string command +template.setReadyCmd('curl http://localhost:8000/health') + +// Using ReadyCmd helpers +import { waitForPort, waitForFile, waitForProcess } from 'e2b' + +template.setReadyCmd(waitForPort(3000)) + +template.setReadyCmd(waitForFile('/tmp/ready')) + +template.setReadyCmd(waitForProcess('nginx')) +``` + +###### Implementation of + +`TemplateBuilder`.`setReadyCmd` + +### setStartCmd() + +```ts +setStartCmd(startCommand: string, readyCommand: string | ReadyCmd): TemplateFinal +``` + +Set the start command and ready check. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `startCommand` | `string` | Command to run on startup | +| `readyCommand` | `string` \| `ReadyCmd` | Command to check readiness | + +###### Returns + +`TemplateFinal` + +###### Example + +```ts +// Using a string command +template.setStartCmd( + 'node app.js', + 'curl http://localhost:8000/health' +) + +// Using ReadyCmd helpers +import { waitForPort, waitForURL } from 'e2b' + +template.setStartCmd( + 'python -m http.server 8000', + waitForPort(8000) +) + +template.setStartCmd( + 'npm start', + waitForURL('http://localhost:3000/health', 200) +) +``` + +###### Implementation of + +`TemplateBuilder`.`setStartCmd` + +### setUser() + +```ts +setUser(user: string): TemplateBuilder +``` + +Set the user for subsequent commands. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `user` | `string` | Username | + +###### Returns + +`TemplateBuilder` + +###### Example + +```ts +template.setUser('root') +``` + +###### Implementation of + +`TemplateBuilder`.`setUser` + +### setWorkdir() + +```ts +setWorkdir(workdir: PathLike): TemplateBuilder +``` + +Set the working directory. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `workdir` | `PathLike` | Working directory path | + +###### Returns + +`TemplateBuilder` + +###### Example + +```ts +template.setWorkdir('/app') +``` + +###### Implementation of + +`TemplateBuilder`.`setWorkdir` + +### skipCache() + +```ts +skipCache(): this +``` + +Skip cache for all subsequent build instructions from this point. + +###### Returns + +`this` + +###### Example + +```ts +Template().skipCache().fromPythonImage('3') +``` + +###### Implementation of + +`TemplateBuilder`.`skipCache` + +### build() + +```ts +static build(template: TemplateClass, options: BuildOptions): Promise +``` + +Build and deploy a template to E2B infrastructure. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `template` | `TemplateClass` | The template to build | +| `options` | `BuildOptions` | Build configuration options | + +###### Returns + +`Promise`\<`BuildInfo`\> + +###### Example + +```ts +const template = Template().fromPythonImage('3') +await Template.build(template, { + alias: 'my-python-env', + cpuCount: 2, + memoryMB: 1024 +}) +``` + +### buildInBackground() + +```ts +static buildInBackground(template: TemplateClass, options: BuildOptions): Promise +``` + +Build and deploy a template to E2B infrastructure. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `template` | `TemplateClass` | The template to build | +| `options` | `BuildOptions` | Build configuration options | + +###### Returns + +`Promise`\<`BuildInfo`\> + +###### Example + +```ts +const template = Template().fromPythonImage('3') +const data = await Template.buildInBackground(template, { + alias: 'my-python-env', + cpuCount: 2, + memoryMB: 1024 +}) +``` + +### getBuildStatus() + +```ts +static getBuildStatus(data: Pick, options?: GetBuildStatusOptions): Promise +``` + +Get the status of a build. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `data` | `Pick`\<`BuildInfo`, `"templateId"` \| `"buildId"`\> | Build identifiers | +| `options`? | `GetBuildStatusOptions` | Authentication options | + +###### Returns + +`Promise`\<`object`\> + +| Name | Type | Description | +| ------ | ------ | ------ | +| `buildID` | `string` | **Description** Identifier of the build | +| `logEntries` | `object`[] | **Description** Build logs structured **Default** `[]` | +| `logs` | `string`[] | **Description** Build logs **Default** `[]` | +| `reason`? | `object` | - | +| `reason.logEntries`? | `object`[] | **Description** Log entries related to the status reason **Default** `[]` | +| `reason.message` | `string` | **Description** Message with the status reason, currently reporting only for error status | +| `reason.step`? | `string` | **Description** Step that failed | +| `status` | `"error"` \| `"ready"` \| `"building"` \| `"waiting"` | - | +| `templateID` | `string` | **Description** Identifier of the template | + +###### Example + +```ts +const status = await Template.getBuildStatus(data, { logsOffset: 0 }) +``` + +### toDockerfile() + +```ts +static toDockerfile(template: TemplateClass): string +``` + +Convert a template to Dockerfile format. +Note: Templates based on other E2B templates cannot be converted to Dockerfile. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `template` | `TemplateClass` | The template to convert | + +###### Returns + +`string` + +Dockerfile string representation + +###### Throws + +Error if the template is based on another E2B template + +### toJSON() + +```ts +static toJSON(template: TemplateClass, computeHashes: boolean): Promise +``` + +Convert a template to JSON representation. + +###### Parameters + +| Parameter | Type | Default value | Description | +| ------ | ------ | ------ | ------ | +| `template` | `TemplateClass` | `undefined` | The template to convert | +| `computeHashes` | `boolean` | `true` | Whether to compute file hashes for cache invalidation | + +###### Returns + +`Promise`\<`string`\> + +JSON string representation of the template + +## Interfaces + +### TemplateBuilder + +Main builder state for constructing templates. +Provides methods for customizing the template environment. + +#### Methods + +### addMcpServer() + +```ts +addMcpServer(servers: keyof McpServer | keyof McpServer[]): TemplateBuilder +``` + +Install MCP servers using mcp-gateway. +Note: Requires a base image with mcp-gateway pre-installed (e.g., mcp-gateway). + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `servers` | keyof McpServer \| keyof McpServer[] | MCP server name(s) | + +###### Returns + +`TemplateBuilder` + +###### Throws + +If the base template is not mcp-gateway + +###### Example + +```ts +template.addMcpServer('exa') +template.addMcpServer(['brave', 'firecrawl', 'duckduckgo']) +``` + +### aptInstall() + +```ts +aptInstall(packages: string | string[], options?: object): TemplateBuilder +``` + +Install Debian/Ubuntu packages using apt-get. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `packages` | `string` \| `string`[] | Package name(s) | +| `options`? | `object` | - | +| `options.noInstallRecommends`? | `boolean` | - | + +###### Returns + +`TemplateBuilder` + +###### Example + +```ts +template.aptInstall('vim') +template.aptInstall(['git', 'curl', 'wget']) +template.aptInstall(['vim'], { noInstallRecommends: true }) +``` + +### betaDevContainerPrebuild() + +```ts +betaDevContainerPrebuild(devcontainerDirectory: string): TemplateBuilder +``` + +Prebuild a devcontainer from the specified directory. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `devcontainerDirectory` | `string` | Path to the devcontainer directory | + +###### Returns + +`TemplateBuilder` + +###### Example + +```ts +template + .gitClone('https://myrepo.com/project.git', '/my-devcontainer') + .betaDevContainerPrebuild('/my-devcontainer') +``` + +### betaSetDevContainerStart() + +```ts +betaSetDevContainerStart(devcontainerDirectory: string): TemplateFinal +``` + +Start a devcontainer from the specified directory. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `devcontainerDirectory` | `string` | Path to the devcontainer directory | + +###### Returns + +`TemplateFinal` + +###### Example + +```ts +template + .gitClone('https://myrepo.com/project.git', '/my-devcontainer') + .startDevcontainer('/my-devcontainer') + +// Prebuild and start +template + .gitClone('https://myrepo.com/project.git', '/my-devcontainer') + .betaDevContainerPrebuild('/my-devcontainer') + // Other instructions... + .betaSetDevContainerStart('/my-devcontainer') +``` + +### bunInstall() + +```ts +bunInstall(packages?: string | string[], options?: object): TemplateBuilder +``` + +Install Bun packages using bun. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `packages`? | `string` \| `string`[] | Package name(s) or undefined for package.json | +| `options`? | `object` | Install options | +| `options.dev`? | `boolean` | - | +| `options.g`? | `boolean` | - | + +###### Returns + +`TemplateBuilder` + +###### Example + +```ts +template.bunInstall('express') +template.bunInstall(['lodash', 'axios']) +template.bunInstall('tsx', { g: true }) +template.bunInstall('typescript', { dev: true }) +template.bunInstall() // Installs from package.json +``` + +### copy() + +```ts +copy( + src: PathLike | PathLike[], + dest: PathLike, + options?: object): TemplateBuilder +``` + +Copy files or directories into the template. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `src` | `PathLike` \| `PathLike`[] | Source path(s) | +| `dest` | `PathLike` | Destination path | +| `options`? | `object` | Copy options | +| `options.forceUpload`? | `true` | - | +| `options.mode`? | `number` | - | +| `options.resolveSymlinks`? | `boolean` | - | +| `options.user`? | `string` | - | + +###### Returns + +`TemplateBuilder` + +###### Example + +```ts +template.copy('requirements.txt', '/home/user/') +template.copy(['app.ts', 'config.ts'], '/app/', { mode: 0o755 }) +``` + +### copyItems() + +```ts +copyItems(items: CopyItem[]): TemplateBuilder +``` + +Copy multiple items with individual options. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `items` | `CopyItem`[] | Array of copy items | + +###### Returns + +`TemplateBuilder` + +###### Example + +```ts +template.copyItems([ + { src: 'app.ts', dest: '/app/' }, + { src: 'config.ts', dest: '/app/', mode: 0o644 } +]) +``` + +### gitClone() + +```ts +gitClone( + url: string, + path?: PathLike, + options?: object): TemplateBuilder +``` + +Clone a Git repository. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `url` | `string` | Repository URL | +| `path`? | `PathLike` | Optional destination path | +| `options`? | `object` | Clone options | +| `options.branch`? | `string` | - | +| `options.depth`? | `number` | - | +| `options.user`? | `string` | - | + +###### Returns + +`TemplateBuilder` + +###### Example + +```ts +template.gitClone('https://github.com/user/repo.git', '/app/repo') +template.gitClone('https://github.com/user/repo.git', undefined, { + branch: 'main', + depth: 1 +}) +template.gitClone('https://github.com/user/repo.git', '/app/repo', { + user: 'root' +}) +``` + +### makeDir() + +```ts +makeDir(path: PathLike | PathLike[], options?: object): TemplateBuilder +``` + +Create directories. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `path` | `PathLike` \| `PathLike`[] | Directory path(s) | +| `options`? | `object` | Directory options | +| `options.mode`? | `number` | - | +| `options.user`? | `string` | - | + +###### Returns + +`TemplateBuilder` + +###### Example + +```ts +template.makeDir('/app/data', { mode: 0o755 }) +template.makeDir(['/app/logs', '/app/cache']) +template.makeDir('/app/data', { mode: 0o755, user: 'root' }) +``` + +### makeSymlink() + +```ts +makeSymlink( + src: PathLike, + dest: PathLike, + options?: object): TemplateBuilder +``` + +Create a symbolic link. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `src` | `PathLike` | Source path (target) | +| `dest` | `PathLike` | Destination path (symlink location) | +| `options`? | `object` | Symlink options | +| `options.force`? | `boolean` | - | +| `options.user`? | `string` | - | + +###### Returns + +`TemplateBuilder` + +###### Example + +```ts +template.makeSymlink('/usr/bin/python3', '/usr/bin/python') +template.makeSymlink('/usr/bin/python3', '/usr/bin/python', { user: 'root' }) +template.makeSymlink('/usr/bin/python3', '/usr/bin/python', { force: true }) +``` + +### npmInstall() + +```ts +npmInstall(packages?: string | string[], options?: object): TemplateBuilder +``` + +Install Node.js packages using npm. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `packages`? | `string` \| `string`[] | Package name(s) or undefined for package.json | +| `options`? | `object` | Install options | +| `options.dev`? | `boolean` | - | +| `options.g`? | `boolean` | - | + +###### Returns + +`TemplateBuilder` + +###### Example + +```ts +template.npmInstall('express') +template.npmInstall(['lodash', 'axios']) +template.npmInstall('tsx', { g: true }) +template.npmInstall('typescript', { dev: true }) +template.npmInstall() // Installs from package.json +``` + +### pipInstall() + +```ts +pipInstall(packages?: string | string[], options?: object): TemplateBuilder +``` + +Install Python packages using pip. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `packages`? | `string` \| `string`[] | Package name(s) or undefined for current directory | +| `options`? | `object` | Install options | +| `options.g`? | `boolean` | Install globally as root (default: true). Set to false for user-only installation with --user flag | + +###### Returns + +`TemplateBuilder` + +###### Example + +```ts +template.pipInstall('numpy') // Installs globally (default) +template.pipInstall(['pandas', 'scikit-learn']) +template.pipInstall('numpy', { g: false }) // Install for user only +template.pipInstall() // Installs from current directory +``` + +### remove() + +```ts +remove(path: PathLike | PathLike[], options?: object): TemplateBuilder +``` + +Remove files or directories. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `path` | `PathLike` \| `PathLike`[] | Path(s) to remove | +| `options`? | `object` | Remove options | +| `options.force`? | `boolean` | - | +| `options.recursive`? | `boolean` | - | +| `options.user`? | `string` | - | + +###### Returns + +`TemplateBuilder` + +###### Example + +```ts +template.remove('/tmp/cache', { recursive: true, force: true }) +template.remove('/tmp/cache', { recursive: true, force: true, user: 'root' }) +``` + +### rename() + +```ts +rename( + src: PathLike, + dest: PathLike, + options?: object): TemplateBuilder +``` + +Rename or move a file or directory. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `src` | `PathLike` | Source path | +| `dest` | `PathLike` | Destination path | +| `options`? | `object` | Rename options | +| `options.force`? | `boolean` | - | +| `options.user`? | `string` | - | + +###### Returns + +`TemplateBuilder` + +###### Example + +```ts +template.rename('/tmp/old.txt', '/tmp/new.txt') +template.rename('/tmp/old.txt', '/tmp/new.txt', { user: 'root' }) +``` + +### runCmd() + +###### runCmd(command, options) + +```ts +runCmd(command: string, options?: object): TemplateBuilder +``` + +Run a shell command. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `command` | `string` | Command string | +| `options`? | `object` | Command options | +| `options.user`? | `string` | - | + +###### Returns + +`TemplateBuilder` + +###### Example + +```ts +template.runCmd('apt-get update') +template.runCmd(['pip install numpy', 'pip install pandas']) +template.runCmd('apt-get install vim', { user: 'root' }) +``` + +###### runCmd(commands, options) + +```ts +runCmd(commands: string[], options?: object): TemplateBuilder +``` + +Run multiple shell commands. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `commands` | `string`[] | Array of command strings | +| `options`? | `object` | Command options | +| `options.user`? | `string` | - | + +###### Returns + +`TemplateBuilder` + +###### runCmd(commandOrCommands, options) + +```ts +runCmd(commandOrCommands: string | string[], options?: object): TemplateBuilder +``` + +Run command(s). + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `commandOrCommands` | `string` \| `string`[] | Command or commands | +| `options`? | `object` | Command options | +| `options.user`? | `string` | - | + +###### Returns + +`TemplateBuilder` + +### setEnvs() + +```ts +setEnvs(envs: Record): TemplateBuilder +``` + +Set environment variables. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `envs` | `Record`\<`string`, `string`\> | Environment variables | + +###### Returns + +`TemplateBuilder` + +###### Example + +```ts +template.setEnvs({ NODE_ENV: 'production', PORT: '8080' }) +``` + +### setReadyCmd() + +```ts +setReadyCmd(readyCommand: string | ReadyCmd): TemplateFinal +``` + +Set or update the ready check command. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `readyCommand` | `string` \| `ReadyCmd` | Command to check readiness | + +###### Returns + +`TemplateFinal` + +###### Example + +```ts +// Using a string command +template.setReadyCmd('curl http://localhost:8000/health') + +// Using ReadyCmd helpers +import { waitForPort, waitForFile, waitForProcess } from 'e2b' + +template.setReadyCmd(waitForPort(3000)) + +template.setReadyCmd(waitForFile('/tmp/ready')) + +template.setReadyCmd(waitForProcess('nginx')) +``` + +### setStartCmd() + +```ts +setStartCmd(startCommand: string, readyCommand: string | ReadyCmd): TemplateFinal +``` + +Set the start command and ready check. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `startCommand` | `string` | Command to run on startup | +| `readyCommand` | `string` \| `ReadyCmd` | Command to check readiness | + +###### Returns + +`TemplateFinal` + +###### Example + +```ts +// Using a string command +template.setStartCmd( + 'node app.js', + 'curl http://localhost:8000/health' +) + +// Using ReadyCmd helpers +import { waitForPort, waitForURL } from 'e2b' + +template.setStartCmd( + 'python -m http.server 8000', + waitForPort(8000) +) + +template.setStartCmd( + 'npm start', + waitForURL('http://localhost:3000/health', 200) +) +``` + +### setUser() + +```ts +setUser(user: string): TemplateBuilder +``` + +Set the user for subsequent commands. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `user` | `string` | Username | + +###### Returns + +`TemplateBuilder` + +###### Example + +```ts +template.setUser('root') +``` + +### setWorkdir() + +```ts +setWorkdir(workdir: PathLike): TemplateBuilder +``` + +Set the working directory. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `workdir` | `PathLike` | Working directory path | + +###### Returns + +`TemplateBuilder` + +###### Example + +```ts +template.setWorkdir('/app') +``` + +### skipCache() + +```ts +skipCache(): this +``` + +Skip cache for all subsequent build instructions from this point. + +###### Returns + +`this` + +###### Example + +```ts +template.skipCache().runCmd('apt-get update') +``` + +## Type Aliases + +### BuildInfo + +```ts +type BuildInfo: object; +``` + +Information about a built template. + +#### Type declaration + +| Name | Type | +| ------ | ------ | +| `alias` | `string` | +| `buildId` | `string` | +| `templateId` | `string` | + +*** + +### BuildOptions + +```ts +type BuildOptions: AuthOptions & BasicBuildOptions; +``` + +Options for building a template with authentication. + +*** + +### CopyItem + +```ts +type CopyItem: object; +``` + +Configuration for a single file/directory copy operation. + +#### Type declaration + +| Name | Type | +| ------ | ------ | +| `dest` | `PathLike` | +| `forceUpload`? | `true` | +| `mode`? | `number` | +| `resolveSymlinks`? | `boolean` | +| `src` | `PathLike` \| `PathLike`[] | +| `user`? | `string` | + +*** + +### GetBuildStatusOptions + +```ts +type GetBuildStatusOptions: AuthOptions & object; +``` + +Response from getting build status. + +#### Type declaration + +| Name | Type | +| ------ | ------ | +| `logsOffset`? | `number` | + +*** + +### McpServerName + +```ts +type McpServerName: keyof McpServer; +``` + +MCP server names that can be installed. + +*** + +### TemplateClass + +```ts +type TemplateClass: TemplateBuilder | TemplateFinal; +``` + +Type representing a template in any state (builder or final). + +## Functions + +### Template() + +```ts +function Template(options?: TemplateOptions): TemplateFromImage +``` + +Create a new E2B template builder instance. + +#### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `options`? | `TemplateOptions` | Optional configuration for the template builder | + +#### Returns + +`TemplateFromImage` + +A new template builder instance + +#### Example + +```ts +import { Template } from 'e2b' + +const template = Template() + .fromPythonImage('3') + .copy('requirements.txt', '/app/') + .pipInstall() + +await Template.build(template, { alias: 'my-python-app' }) +``` diff --git a/docs/sdk-reference/js-sdk/v2.8.3/errors.mdx b/docs/sdk-reference/js-sdk/v2.8.3/errors.mdx new file mode 100644 index 0000000..bfe0deb --- /dev/null +++ b/docs/sdk-reference/js-sdk/v2.8.3/errors.mdx @@ -0,0 +1,271 @@ +--- +sidebarTitle: "Errors" +mode: "center" +--- + +### AuthenticationError + +Thrown when authentication fails. + +#### Constructors + +```ts +new AuthenticationError(message: string): AuthenticationError +``` + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `message` | `string` | + +###### Returns + +`AuthenticationError` + +*** + +### BuildError + +Thrown when the build fails. + +#### Extended by + +- `FileUploadError` + +#### Constructors + +```ts +new BuildError(message: string, stackTrace?: string): BuildError +``` + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `message` | `string` | +| `stackTrace`? | `string` | + +###### Returns + +`BuildError` + +*** + +### FileUploadError + +Thrown when the file upload fails. + +#### Constructors + +```ts +new FileUploadError(message: string, stackTrace?: string): FileUploadError +``` + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `message` | `string` | +| `stackTrace`? | `string` | + +###### Returns + +`FileUploadError` + +*** + +### InvalidArgumentError + +Thrown when an invalid argument is provided. + +#### Constructors + +```ts +new InvalidArgumentError(message: string, stackTrace?: string): InvalidArgumentError +``` + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `message` | `string` | +| `stackTrace`? | `string` | + +###### Returns + +`InvalidArgumentError` + +*** + +### NotEnoughSpaceError + +Thrown when there is not enough disk space. + +#### Constructors + +```ts +new NotEnoughSpaceError(message: string, stackTrace?: string): NotEnoughSpaceError +``` + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `message` | `string` | +| `stackTrace`? | `string` | + +###### Returns + +`NotEnoughSpaceError` + +*** + +### NotFoundError + +Thrown when a resource is not found. + +#### Constructors + +```ts +new NotFoundError(message: string, stackTrace?: string): NotFoundError +``` + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `message` | `string` | +| `stackTrace`? | `string` | + +###### Returns + +`NotFoundError` + +*** + +### RateLimitError + +Thrown when the API rate limit is exceeded. + +#### Constructors + +```ts +new RateLimitError(message: string): RateLimitError +``` + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `message` | `string` | + +###### Returns + +`RateLimitError` + +*** + +### SandboxError + +Base class for all sandbox errors. + +Thrown when general sandbox errors occur. + +#### Extended by + +- `TimeoutError` +- `InvalidArgumentError` +- `NotEnoughSpaceError` +- `NotFoundError` +- `TemplateError` +- `RateLimitError` + +#### Constructors + +```ts +new SandboxError(message?: string, stackTrace?: string): SandboxError +``` + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `message`? | `string` | +| `stackTrace`? | `string` | + +###### Returns + +`SandboxError` + +*** + +### TemplateError + +Thrown when the template uses old envd version. It isn't compatible with the new SDK. + +#### Constructors + +```ts +new TemplateError(message: string, stackTrace?: string): TemplateError +``` + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `message` | `string` | +| `stackTrace`? | `string` | + +###### Returns + +`TemplateError` + +*** + +### TimeoutError + +Thrown when a timeout error occurs. + +The [unavailable] error type is caused by sandbox timeout. + +The [canceled] error type is caused by exceeding request timeout. + +The [deadline_exceeded] error type is caused by exceeding the timeout for command execution, watch, etc. + +The [unknown] error type is sometimes caused by the sandbox timeout when the request is not processed correctly. + +#### Constructors + +```ts +new TimeoutError(message: string, stackTrace?: string): TimeoutError +``` + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `message` | `string` | +| `stackTrace`? | `string` | + +###### Returns + +`TimeoutError` + +## Functions + +### formatSandboxTimeoutError() + +```ts +function formatSandboxTimeoutError(message: string): TimeoutError +``` + +#### Parameters + +| Parameter | Type | +| ------ | ------ | +| `message` | `string` | + +#### Returns + +`TimeoutError` diff --git a/docs/sdk-reference/js-sdk/v2.8.3/sandbox-commands.mdx b/docs/sdk-reference/js-sdk/v2.8.3/sandbox-commands.mdx new file mode 100644 index 0000000..16d736c --- /dev/null +++ b/docs/sdk-reference/js-sdk/v2.8.3/sandbox-commands.mdx @@ -0,0 +1,533 @@ +--- +sidebarTitle: "Commands" +mode: "center" +--- + +### Commands + +Module for starting and interacting with commands in the sandbox. + +#### Constructors + +```ts +new Commands( + transport: Transport, + connectionConfig: ConnectionConfig, + metadata: object): Commands +``` + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `transport` | `Transport` | +| `connectionConfig` | `ConnectionConfig` | +| `metadata` | `object` | +| `metadata.version` | `string` | + +###### Returns + +`Commands` + +#### Methods + +### connect() + +```ts +connect(pid: number, opts?: CommandConnectOpts): Promise +``` + +Connect to a running command. +You can use CommandHandle.wait to wait for the command to finish and get execution results. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `pid` | `number` | process ID of the command to connect to. You can get the list of running commands using Commands.list. | +| `opts`? | `CommandConnectOpts` | connection options. | + +###### Returns + +`Promise`\<`CommandHandle`\> + +`CommandHandle` handle to interact with the running command. + +### kill() + +```ts +kill(pid: number, opts?: CommandRequestOpts): Promise +``` + +Kill a running command specified by its process ID. +It uses `SIGKILL` signal to kill the command. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `pid` | `number` | process ID of the command. You can get the list of running commands using Commands.list. | +| `opts`? | `CommandRequestOpts` | connection options. | + +###### Returns + +`Promise`\<`boolean`\> + +`true` if the command was killed, `false` if the command was not found. + +### list() + +```ts +list(opts?: CommandRequestOpts): Promise +``` + +List all running commands and PTY sessions. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `opts`? | `CommandRequestOpts` | connection options. | + +###### Returns + +`Promise`\<`ProcessInfo`[]\> + +list of running commands and PTY sessions. + +### run() + +###### run(cmd, opts) + +```ts +run(cmd: string, opts?: CommandStartOpts & object): Promise +``` + +Start a new command and wait until it finishes executing. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `cmd` | `string` | command to execute. | +| `opts`? | `CommandStartOpts` & `object` | options for starting the command. | + +###### Returns + +`Promise`\<`CommandResult`\> + +`CommandResult` result of the command execution. + +###### run(cmd, opts) + +```ts +run(cmd: string, opts: CommandStartOpts & object): Promise +``` + +Start a new command in the background. +You can use CommandHandle.wait to wait for the command to finish and get its result. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `cmd` | `string` | command to execute. | +| `opts` | `CommandStartOpts` & `object` | options for starting the command | + +###### Returns + +`Promise`\<`CommandHandle`\> + +`CommandHandle` handle to interact with the running command. + +###### run(cmd, opts) + +```ts +run(cmd: string, opts?: CommandStartOpts & object): Promise +``` + +Start a new command. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `cmd` | `string` | command to execute. | +| `opts`? | `CommandStartOpts` & `object` | options for starting the command. - `opts.background: true` - runs in background, returns `CommandHandle` - `opts.background: false | undefined` - waits for completion, returns `CommandResult` | + +###### Returns + +`Promise`\<`CommandResult` \| `CommandHandle`\> + +Either a `CommandHandle` or a `CommandResult` (depending on `opts.background`). + +### sendStdin() + +```ts +sendStdin( + pid: number, + data: string, +opts?: CommandRequestOpts): Promise +``` + +Send data to command stdin. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `pid` | `number` | process ID of the command. You can get the list of running commands using Commands.list. | +| `data` | `string` | data to send to the command. | +| `opts`? | `CommandRequestOpts` | connection options. | + +###### Returns + +`Promise`\<`void`\> + +*** + +### Pty + +Module for interacting with PTYs (pseudo-terminals) in the sandbox. + +#### Constructors + +```ts +new Pty( + transport: Transport, + connectionConfig: ConnectionConfig, + metadata: object): Pty +``` + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `transport` | `Transport` | +| `connectionConfig` | `ConnectionConfig` | +| `metadata` | `object` | +| `metadata.version` | `string` | + +###### Returns + +`Pty` + +#### Methods + +### create() + +```ts +create(opts: PtyCreateOpts): Promise +``` + +Create a new PTY (pseudo-terminal). + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `opts` | `PtyCreateOpts` | options for creating the PTY. | + +###### Returns + +`Promise`\<`CommandHandle`\> + +handle to interact with the PTY. + +### kill() + +```ts +kill(pid: number, opts?: Pick): Promise +``` + +Kill a running PTY specified by process ID. +It uses `SIGKILL` signal to kill the PTY. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `pid` | `number` | process ID of the PTY. | +| `opts`? | `Pick`\<`ConnectionOpts`, `"requestTimeoutMs"`\> | connection options. | + +###### Returns + +`Promise`\<`boolean`\> + +`true` if the PTY was killed, `false` if the PTY was not found. + +### resize() + +```ts +resize( + pid: number, + size: object, +opts?: Pick): Promise +``` + +Resize PTY. +Call this when the terminal window is resized and the number of columns and rows has changed. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `pid` | `number` | process ID of the PTY. | +| `size` | `object` | new size of the PTY. | +| `size.cols` | `number` | - | +| `size.rows`? | `number` | - | +| `opts`? | `Pick`\<`ConnectionOpts`, `"requestTimeoutMs"`\> | connection options. | + +###### Returns + +`Promise`\<`void`\> + +### sendInput() + +```ts +sendInput( + pid: number, + data: Uint8Array, +opts?: Pick): Promise +``` + +Send input to a PTY. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `pid` | `number` | process ID of the PTY. | +| `data` | `Uint8Array` | input data to send to the PTY. | +| `opts`? | `Pick`\<`ConnectionOpts`, `"requestTimeoutMs"`\> | connection options. | + +###### Returns + +`Promise`\<`void`\> + +## Interfaces + +### CommandRequestOpts + +Options for sending a command request. + +#### Extended by + +- `CommandStartOpts` + +#### Properties + +### requestTimeoutMs? + +```ts +optional requestTimeoutMs: number; +``` + +Timeout for requests to the API in **milliseconds**. + +###### Default + +```ts +60_000 // 60 seconds +``` + +*** + +### CommandStartOpts + +Options for starting a new command. + +#### Properties + +### background? + +```ts +optional background: boolean; +``` + +If true, starts command in the background and the method returns immediately. +You can use CommandHandle.wait to wait for the command to finish. + +### cwd? + +```ts +optional cwd: string; +``` + +Working directory for the command. + +###### Default + +```ts +// home directory of the user used to start the command +``` + +### envs? + +```ts +optional envs: Record; +``` + +Environment variables used for the command. + +This overrides the default environment variables from `Sandbox` constructor. + +###### Default + +`{}` + +### onStderr()? + +```ts +optional onStderr: (data: string) => void | Promise; +``` + +Callback for command stderr output. + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `data` | `string` | + +###### Returns + +`void` \| `Promise`\<`void`\> + +### onStdout()? + +```ts +optional onStdout: (data: string) => void | Promise; +``` + +Callback for command stdout output. + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `data` | `string` | + +###### Returns + +`void` \| `Promise`\<`void`\> + +### requestTimeoutMs? + +```ts +optional requestTimeoutMs: number; +``` + +Timeout for requests to the API in **milliseconds**. + +###### Default + +```ts +60_000 // 60 seconds +``` + +### stdin? + +```ts +optional stdin: boolean; +``` + +If true, command stdin is kept open and you can send data to it using Commands.sendStdin or CommandHandle.sendStdin. + +###### Default + +```ts +false +``` + +### timeoutMs? + +```ts +optional timeoutMs: number; +``` + +Timeout for the command in **milliseconds**. + +###### Default + +```ts +60_000 // 60 seconds +``` + +### user? + +```ts +optional user: string; +``` + +User to run the command as. + +###### Default + +`default Sandbox user (as specified in the template)` + +*** + +### ProcessInfo + +Information about a command, PTY session or start command running in the sandbox as process. + +#### Properties + +### args + +```ts +args: string[]; +``` + +Command arguments. + +### cmd + +```ts +cmd: string; +``` + +Command that was executed. + +### cwd? + +```ts +optional cwd: string; +``` + +Executed command working directory. + +### envs + +```ts +envs: Record; +``` + +Environment variables used for the command. + +### pid + +```ts +pid: number; +``` + +Process ID. + +### tag? + +```ts +optional tag: string; +``` + +Custom tag used for identifying special commands like start command in the custom template. + +## Type Aliases + +### CommandConnectOpts + +```ts +type CommandConnectOpts: Pick & CommandRequestOpts; +``` + +Options for connecting to a command. diff --git a/docs/sdk-reference/js-sdk/v2.8.3/sandbox-filesystem.mdx b/docs/sdk-reference/js-sdk/v2.8.3/sandbox-filesystem.mdx new file mode 100644 index 0000000..c43ac2f --- /dev/null +++ b/docs/sdk-reference/js-sdk/v2.8.3/sandbox-filesystem.mdx @@ -0,0 +1,627 @@ +--- +sidebarTitle: "Filesystem" +mode: "center" +--- + +### FileType + +Sandbox filesystem object type. + +#### Enumeration Members + +| Enumeration Member | Value | Description | +| ------ | ------ | ------ | +| `DIR` | `"dir"` | Filesystem object is a directory. | +| `FILE` | `"file"` | Filesystem object is a file. | + +## Classes + +### Filesystem + +Module for interacting with the sandbox filesystem. + +#### Constructors + +```ts +new Filesystem( + transport: Transport, + envdApi: EnvdApiClient, + connectionConfig: ConnectionConfig): Filesystem +``` + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `transport` | `Transport` | +| `envdApi` | `EnvdApiClient` | +| `connectionConfig` | `ConnectionConfig` | + +###### Returns + +`Filesystem` + +#### Methods + +### exists() + +```ts +exists(path: string, opts?: FilesystemRequestOpts): Promise +``` + +Check if a file or a directory exists. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `path` | `string` | path to a file or a directory | +| `opts`? | `FilesystemRequestOpts` | connection options. | + +###### Returns + +`Promise`\<`boolean`\> + +`true` if the file or directory exists, `false` otherwise + +### getInfo() + +```ts +getInfo(path: string, opts?: FilesystemRequestOpts): Promise +``` + +Get information about a file or directory. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `path` | `string` | path to a file or directory. | +| `opts`? | `FilesystemRequestOpts` | connection options. | + +###### Returns + +`Promise`\<`EntryInfo`\> + +information about the file or directory like name, type, and path. + +### list() + +```ts +list(path: string, opts?: FilesystemListOpts): Promise +``` + +List entries in a directory. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `path` | `string` | path to the directory. | +| `opts`? | `FilesystemListOpts` | connection options. | + +###### Returns + +`Promise`\<`EntryInfo`[]\> + +list of entries in the sandbox filesystem directory. + +### makeDir() + +```ts +makeDir(path: string, opts?: FilesystemRequestOpts): Promise +``` + +Create a new directory and all directories along the way if needed on the specified path. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `path` | `string` | path to a new directory. For example '/dirA/dirB' when creating 'dirB'. | +| `opts`? | `FilesystemRequestOpts` | connection options. | + +###### Returns + +`Promise`\<`boolean`\> + +`true` if the directory was created, `false` if it already exists. + +### read() + +###### read(path, opts) + +```ts +read(path: string, opts?: FilesystemRequestOpts & object): Promise +``` + +Read file content as a `string`. + +You can pass `text`, `bytes`, `blob`, or `stream` to `opts.format` to change the return type. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `path` | `string` | path to the file. | +| `opts`? | `FilesystemRequestOpts` & `object` | connection options. | + +###### Returns + +`Promise`\<`string`\> + +file content as string + +###### read(path, opts) + +```ts +read(path: string, opts?: FilesystemRequestOpts & object): Promise +``` + +Read file content as a `Uint8Array`. + +You can pass `text`, `bytes`, `blob`, or `stream` to `opts.format` to change the return type. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `path` | `string` | path to the file. | +| `opts`? | `FilesystemRequestOpts` & `object` | connection options. | + +###### Returns + +`Promise`\<`Uint8Array`\> + +file content as `Uint8Array` + +###### read(path, opts) + +```ts +read(path: string, opts?: FilesystemRequestOpts & object): Promise +``` + +Read file content as a `Blob`. + +You can pass `text`, `bytes`, `blob`, or `stream` to `opts.format` to change the return type. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `path` | `string` | path to the file. | +| `opts`? | `FilesystemRequestOpts` & `object` | connection options. | + +###### Returns + +`Promise`\<`Blob`\> + +file content as `Blob` + +###### read(path, opts) + +```ts +read(path: string, opts?: FilesystemRequestOpts & object): Promise> +``` + +Read file content as a `ReadableStream`. + +You can pass `text`, `bytes`, `blob`, or `stream` to `opts.format` to change the return type. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `path` | `string` | path to the file. | +| `opts`? | `FilesystemRequestOpts` & `object` | connection options. | + +###### Returns + +`Promise`\<`ReadableStream`\<`Uint8Array`\>\> + +file content as `ReadableStream` + +### remove() + +```ts +remove(path: string, opts?: FilesystemRequestOpts): Promise +``` + +Remove a file or directory. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `path` | `string` | path to a file or directory. | +| `opts`? | `FilesystemRequestOpts` | connection options. | + +###### Returns + +`Promise`\<`void`\> + +### rename() + +```ts +rename( + oldPath: string, + newPath: string, +opts?: FilesystemRequestOpts): Promise +``` + +Rename a file or directory. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `oldPath` | `string` | path to the file or directory to rename. | +| `newPath` | `string` | new path for the file or directory. | +| `opts`? | `FilesystemRequestOpts` | connection options. | + +###### Returns + +`Promise`\<`EntryInfo`\> + +information about renamed file or directory. + +### watchDir() + +```ts +watchDir( + path: string, + onEvent: (event: FilesystemEvent) => void | Promise, +opts?: WatchOpts & object): Promise +``` + +Start watching a directory for filesystem events. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `path` | `string` | path to directory to watch. | +| `onEvent` | (`event`: `FilesystemEvent`) => `void` \| `Promise`\<`void`\> | callback to call when an event in the directory occurs. | +| `opts`? | `WatchOpts` & `object` | connection options. | + +###### Returns + +`Promise`\<`WatchHandle`\> + +`WatchHandle` object for stopping watching directory. + +### write() + +###### write(path, data, opts) + +```ts +write( + path: string, + data: string | ArrayBuffer | Blob | ReadableStream, +opts?: FilesystemRequestOpts): Promise +``` + +Write content to a file. + +Writing to a file that doesn't exist creates the file. + +Writing to a file that already exists overwrites the file. + +Writing to a file at path that doesn't exist creates the necessary directories. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `path` | `string` | path to file. | +| `data` | `string` \| `ArrayBuffer` \| `Blob` \| `ReadableStream`\<`any`\> | data to write to the file. Data can be a string, `ArrayBuffer`, `Blob`, or `ReadableStream`. | +| `opts`? | `FilesystemRequestOpts` | connection options. | + +###### Returns + +`Promise`\<`WriteInfo`\> + +information about the written file + +###### write(files, opts) + +```ts +write(files: WriteEntry[], opts?: FilesystemRequestOpts): Promise +``` + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `files` | `WriteEntry`[] | +| `opts`? | `FilesystemRequestOpts` | + +###### Returns + +`Promise`\<`WriteInfo`[]\> + +## Interfaces + +### EntryInfo + +Sandbox filesystem object information. + +#### Properties + +### group + +```ts +group: string; +``` + +Group owner of the filesystem object. + +### mode + +```ts +mode: number; +``` + +File mode and permission bits. + +### modifiedTime? + +```ts +optional modifiedTime: Date; +``` + +Last modification time of the filesystem object. + +### name + +```ts +name: string; +``` + +Name of the filesystem object. + +### owner + +```ts +owner: string; +``` + +Owner of the filesystem object. + +### path + +```ts +path: string; +``` + +Path to the filesystem object. + +### permissions + +```ts +permissions: string; +``` + +String representation of file permissions (e.g. 'rwxr-xr-x'). + +### size + +```ts +size: number; +``` + +Size of the filesystem object in bytes. + +### symlinkTarget? + +```ts +optional symlinkTarget: string; +``` + +If the filesystem object is a symlink, this is the target of the symlink. + +### type? + +```ts +optional type: FileType; +``` + +Type of the filesystem object. + +*** + +### FilesystemListOpts + +Options for the sandbox filesystem operations. + +#### Properties + +### depth? + +```ts +optional depth: number; +``` + +Depth of the directory to list. + +### requestTimeoutMs? + +```ts +optional requestTimeoutMs: number; +``` + +Timeout for requests to the API in **milliseconds**. + +###### Default + +```ts +60_000 // 60 seconds +``` + +### user? + +```ts +optional user: string; +``` + +User to use for the operation in the sandbox. +This affects the resolution of relative paths and ownership of the created filesystem objects. + +*** + +### FilesystemRequestOpts + +Options for the sandbox filesystem operations. + +#### Extended by + +- `FilesystemListOpts` +- `WatchOpts` + +#### Properties + +### requestTimeoutMs? + +```ts +optional requestTimeoutMs: number; +``` + +Timeout for requests to the API in **milliseconds**. + +###### Default + +```ts +60_000 // 60 seconds +``` + +### user? + +```ts +optional user: string; +``` + +User to use for the operation in the sandbox. +This affects the resolution of relative paths and ownership of the created filesystem objects. + +*** + +### WatchOpts + +Options for watching a directory. + +#### Properties + +### onExit()? + +```ts +optional onExit: (err?: Error) => void | Promise; +``` + +Callback to call when the watch operation stops. + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `err`? | `Error` | + +###### Returns + +`void` \| `Promise`\<`void`\> + +### recursive? + +```ts +optional recursive: boolean; +``` + +Watch the directory recursively + +### requestTimeoutMs? + +```ts +optional requestTimeoutMs: number; +``` + +Timeout for requests to the API in **milliseconds**. + +###### Default + +```ts +60_000 // 60 seconds +``` + +### timeoutMs? + +```ts +optional timeoutMs: number; +``` + +Timeout for the watch operation in **milliseconds**. +You can pass `0` to disable the timeout. + +###### Default + +```ts +60_000 // 60 seconds +``` + +### user? + +```ts +optional user: string; +``` + +User to use for the operation in the sandbox. +This affects the resolution of relative paths and ownership of the created filesystem objects. + +*** + +### WriteInfo + +Sandbox filesystem object information. + +#### Extended by + +- `EntryInfo` + +#### Properties + +### name + +```ts +name: string; +``` + +Name of the filesystem object. + +### path + +```ts +path: string; +``` + +Path to the filesystem object. + +### type? + +```ts +optional type: FileType; +``` + +Type of the filesystem object. + +## Type Aliases + +### WriteEntry + +```ts +type WriteEntry: object; +``` + +#### Type declaration + +| Name | Type | +| ------ | ------ | +| `data` | `string` \| `ArrayBuffer` \| `Blob` \| `ReadableStream` | +| `path` | `string` | diff --git a/docs/sdk-reference/js-sdk/v2.8.3/sandbox.mdx b/docs/sdk-reference/js-sdk/v2.8.3/sandbox.mdx new file mode 100644 index 0000000..e430744 --- /dev/null +++ b/docs/sdk-reference/js-sdk/v2.8.3/sandbox.mdx @@ -0,0 +1,712 @@ +--- +sidebarTitle: "Sandbox" +mode: "center" +--- + +### Sandbox + +E2B cloud sandbox is a secure and isolated cloud environment. + +The sandbox allows you to: +- Access Linux OS +- Create, list, and delete files and directories +- Run commands +- Run isolated code +- Access the internet + +Check docs here. + +Use Sandbox.create to create a new sandbox. + +#### Example + +```ts +import { Sandbox } from 'e2b' + +const sandbox = await Sandbox.create() +``` + +#### Properties + +| Property | Modifier | Type | Description | +| ------ | ------ | ------ | ------ | +| `commands` | `readonly` | `Commands` | Module for running commands in the sandbox | +| `files` | `readonly` | `Filesystem` | Module for interacting with the sandbox filesystem | +| `pty` | `readonly` | `Pty` | Module for interacting with the sandbox pseudo-terminals | +| `sandboxDomain` | `readonly` | `string` | Domain where the sandbox is hosted. | +| `sandboxId` | `readonly` | `string` | Unique identifier of the sandbox. | +| `trafficAccessToken?` | `readonly` | `string` | Traffic access token for accessing sandbox services with restricted public traffic. | + +#### Methods + +### betaPause() + +```ts +betaPause(opts?: ConnectionOpts): Promise +``` + +**`Beta`** + +This feature is in beta and may change in the future. + +Pause a sandbox by its ID. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `opts`? | `ConnectionOpts` | connection options. | + +###### Returns + +`Promise`\<`boolean`\> + +sandbox ID that can be used to resume the sandbox. + +### connect() + +```ts +connect(opts?: SandboxBetaCreateOpts): Promise +``` + +Connect to a sandbox. If the sandbox is paused, it will be automatically resumed. +Sandbox must be either running or be paused. + +With sandbox ID you can connect to the same sandbox from different places or environments (serverless functions, etc). + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `opts`? | `SandboxBetaCreateOpts` | connection options. | + +###### Returns + +`Promise`\<`Sandbox`\> + +A running sandbox instance + +###### Example + +```ts +const sandbox = await Sandbox.create() +await sandbox.betaPause() + +// Connect to the same sandbox. +const sameSandbox = await sandbox.connect() +``` + +### downloadUrl() + +```ts +downloadUrl(path: string, opts?: SandboxUrlOpts): Promise +``` + +Get the URL to download a file from the sandbox. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `path` | `string` | path to the file in the sandbox. | +| `opts`? | `SandboxUrlOpts` | download url options. | + +###### Returns + +`Promise`\<`string`\> + +URL for downloading file. + +### getHost() + +```ts +getHost(port: number): string +``` + +Get the host address for the specified sandbox port. +You can then use this address to connect to the sandbox port from outside the sandbox via HTTP or WebSocket. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `port` | `number` | number of the port in the sandbox. | + +###### Returns + +`string` + +host address of the sandbox port. + +###### Example + +```ts +const sandbox = await Sandbox.create() +// Start an HTTP server +await sandbox.commands.exec('python3 -m http.server 3000') +// Get the hostname of the HTTP server +const serverURL = sandbox.getHost(3000) +``` + +### getInfo() + +```ts +getInfo(opts?: Pick): Promise +``` + +Get sandbox information like sandbox ID, template, metadata, started at/end at date. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `opts`? | `Pick`\<`SandboxOpts`, `"requestTimeoutMs"`\> | connection options. | + +###### Returns + +`Promise`\<`SandboxInfo`\> + +information about the sandbox + +### getMcpToken() + +```ts +getMcpToken(): Promise +``` + +Get the MCP token for the sandbox. + +###### Returns + +`Promise`\<`undefined` \| `string`\> + +MCP token for the sandbox, or undefined if MCP is not enabled. + +### getMcpUrl() + +```ts +getMcpUrl(): string +``` + +Get the MCP URL for the sandbox. + +###### Returns + +`string` + +MCP URL for the sandbox. + +### getMetrics() + +```ts +getMetrics(opts?: SandboxMetricsOpts): Promise +``` + +Get the metrics of the sandbox. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `opts`? | `SandboxMetricsOpts` | connection options. | + +###### Returns + +`Promise`\<`SandboxMetrics`[]\> + +List of sandbox metrics containing CPU, memory and disk usage information. + +### isRunning() + +```ts +isRunning(opts?: Pick): Promise +``` + +Check if the sandbox is running. + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `opts`? | `Pick`\<`ConnectionOpts`, `"requestTimeoutMs"`\> | + +###### Returns + +`Promise`\<`boolean`\> + +`true` if the sandbox is running, `false` otherwise. + +###### Example + +```ts +const sandbox = await Sandbox.create() +await sandbox.isRunning() // Returns true + +await sandbox.kill() +await sandbox.isRunning() // Returns false +``` + +### kill() + +```ts +kill(opts?: Pick): Promise +``` + +Kill the sandbox. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `opts`? | `Pick`\<`SandboxOpts`, `"requestTimeoutMs"`\> | connection options. | + +###### Returns + +`Promise`\<`void`\> + +### setTimeout() + +```ts +setTimeout(timeoutMs: number, opts?: Pick): Promise +``` + +Set the timeout of the sandbox. +After the timeout expires the sandbox will be automatically killed. + +This method can extend or reduce the sandbox timeout set when creating the sandbox or from the last call to `.setTimeout`. +Maximum time a sandbox can be kept alive is 24 hours (86_400_000 milliseconds) for Pro users and 1 hour (3_600_000 milliseconds) for Hobby users. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `timeoutMs` | `number` | timeout in **milliseconds**. | +| `opts`? | `Pick`\<`SandboxOpts`, `"requestTimeoutMs"`\> | connection options. | + +###### Returns + +`Promise`\<`void`\> + +### uploadUrl() + +```ts +uploadUrl(path?: string, opts?: SandboxUrlOpts): Promise +``` + +Get the URL to upload a file to the sandbox. + +You have to send a POST request to this URL with the file as multipart/form-data. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `path`? | `string` | path to the file in the sandbox. | +| `opts`? | `SandboxUrlOpts` | download url options. | + +###### Returns + +`Promise`\<`string`\> + +URL for uploading file. + +### betaCreate() + +###### betaCreate(this, opts) + +```ts +static betaCreate(this: S, opts?: SandboxBetaCreateOpts): Promise> +``` + +**`Beta`** + +This feature is in beta and may change in the future. + +Create a new sandbox from the default `base` sandbox template. + +###### Type Parameters + +| Type Parameter | +| ------ | +| `S` *extends* *typeof* `Sandbox` | + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `this` | `S` | - | +| `opts`? | `SandboxBetaCreateOpts` | connection options. | + +###### Returns + +`Promise`\<`InstanceType`\<`S`\>\> + +sandbox instance for the new sandbox. + +###### Example + +```ts +const sandbox = await Sandbox.betaCreate() +``` + +###### Constructs + +Sandbox + +###### betaCreate(this, template, opts) + +```ts +static betaCreate( + this: S, + template: string, +opts?: SandboxBetaCreateOpts): Promise> +``` + +**`Beta`** + +This feature is in beta and may change in the future. + +Create a new sandbox from the specified sandbox template. + +###### Type Parameters + +| Type Parameter | +| ------ | +| `S` *extends* *typeof* `Sandbox` | + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `this` | `S` | - | +| `template` | `string` | sandbox template name or ID. | +| `opts`? | `SandboxBetaCreateOpts` | connection options. | + +###### Returns + +`Promise`\<`InstanceType`\<`S`\>\> + +sandbox instance for the new sandbox. + +###### Example + +```ts +const sandbox = await Sandbox.betaCreate('') +``` + +###### Constructs + +Sandbox + +### betaPause() + +```ts +static betaPause(sandboxId: string, opts?: SandboxApiOpts): Promise +``` + +Pause the sandbox specified by sandbox ID. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `sandboxId` | `string` | sandbox ID. | +| `opts`? | `SandboxApiOpts` | connection options. | + +###### Returns + +`Promise`\<`boolean`\> + +`true` if the sandbox got paused, `false` if the sandbox was already paused. + +### connect() + +```ts +static connect( + this: S, + sandboxId: string, +opts?: SandboxConnectOpts): Promise> +``` + +Connect to a sandbox. If the sandbox is paused, it will be automatically resumed. +Sandbox must be either running or be paused. + +With sandbox ID you can connect to the same sandbox from different places or environments (serverless functions, etc). + +###### Type Parameters + +| Type Parameter | +| ------ | +| `S` *extends* *typeof* `Sandbox` | + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `this` | `S` | - | +| `sandboxId` | `string` | sandbox ID. | +| `opts`? | `SandboxConnectOpts` | connection options. | + +###### Returns + +`Promise`\<`InstanceType`\<`S`\>\> + +A running sandbox instance + +###### Example + +```ts +const sandbox = await Sandbox.create() +const sandboxId = sandbox.sandboxId + +// Connect to the same sandbox. +const sameSandbox = await Sandbox.connect(sandboxId) +``` + +### create() + +###### create(this, opts) + +```ts +static create(this: S, opts?: SandboxOpts): Promise> +``` + +Create a new sandbox from the default `base` sandbox template. + +###### Type Parameters + +| Type Parameter | +| ------ | +| `S` *extends* *typeof* `Sandbox` | + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `this` | `S` | - | +| `opts`? | `SandboxOpts` | connection options. | + +###### Returns + +`Promise`\<`InstanceType`\<`S`\>\> + +sandbox instance for the new sandbox. + +###### Example + +```ts +const sandbox = await Sandbox.create() +``` + +###### Constructs + +Sandbox + +###### create(this, template, opts) + +```ts +static create( + this: S, + template: string, +opts?: SandboxOpts): Promise> +``` + +Create a new sandbox from the specified sandbox template. + +###### Type Parameters + +| Type Parameter | +| ------ | +| `S` *extends* *typeof* `Sandbox` | + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `this` | `S` | - | +| `template` | `string` | sandbox template name or ID. | +| `opts`? | `SandboxOpts` | connection options. | + +###### Returns + +`Promise`\<`InstanceType`\<`S`\>\> + +sandbox instance for the new sandbox. + +###### Example + +```ts +const sandbox = await Sandbox.create('') +``` + +###### Constructs + +Sandbox + +### getFullInfo() + +```ts +static getFullInfo(sandboxId: string, opts?: SandboxApiOpts): Promise +``` + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `sandboxId` | `string` | +| `opts`? | `SandboxApiOpts` | + +###### Returns + +`Promise`\<`object`\> + +| Name | Type | Default value | +| ------ | ------ | ------ | +| `cpuCount` | `number` | res.data.cpuCount | +| `endAt` | `Date` | - | +| `envdAccessToken` | `undefined` \| `string` | res.data.envdAccessToken | +| `envdVersion` | `string` | res.data.envdVersion | +| `memoryMB` | `number` | res.data.memoryMB | +| `metadata` | `object` | - | +| `name`? | `string` | res.data.alias | +| `sandboxDomain` | `undefined` \| `string` | - | +| `sandboxId` | `string` | res.data.sandboxID | +| `startedAt` | `Date` | - | +| `state` | `"running"` \| `"paused"` | res.data.state | +| `templateId` | `string` | res.data.templateID | + +### getInfo() + +```ts +static getInfo(sandboxId: string, opts?: SandboxApiOpts): Promise +``` + +Get sandbox information like sandbox ID, template, metadata, started at/end at date. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `sandboxId` | `string` | sandbox ID. | +| `opts`? | `SandboxApiOpts` | connection options. | + +###### Returns + +`Promise`\<`SandboxInfo`\> + +sandbox information. + +### getMetrics() + +```ts +static getMetrics(sandboxId: string, opts?: SandboxMetricsOpts): Promise +``` + +Get the metrics of the sandbox. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `sandboxId` | `string` | sandbox ID. | +| `opts`? | `SandboxMetricsOpts` | sandbox metrics options. | + +###### Returns + +`Promise`\<`SandboxMetrics`[]\> + +List of sandbox metrics containing CPU, memory and disk usage information. + +### kill() + +```ts +static kill(sandboxId: string, opts?: SandboxApiOpts): Promise +``` + +Kill the sandbox specified by sandbox ID. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `sandboxId` | `string` | sandbox ID. | +| `opts`? | `SandboxApiOpts` | connection options. | + +###### Returns + +`Promise`\<`boolean`\> + +`true` if the sandbox was found and killed, `false` otherwise. + +### list() + +```ts +static list(opts?: SandboxListOpts): SandboxPaginator +``` + +List all sandboxes. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `opts`? | `SandboxListOpts` | connection options. | + +###### Returns + +`SandboxPaginator` + +paginator for listing sandboxes. + +### setTimeout() + +```ts +static setTimeout( + sandboxId: string, + timeoutMs: number, +opts?: SandboxApiOpts): Promise +``` + +Set the timeout of the specified sandbox. +After the timeout expires the sandbox will be automatically killed. + +This method can extend or reduce the sandbox timeout set when creating the sandbox or from the last call to Sandbox.setTimeout. + +Maximum time a sandbox can be kept alive is 24 hours (86_400_000 milliseconds) for Pro users and 1 hour (3_600_000 milliseconds) for Hobby users. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `sandboxId` | `string` | sandbox ID. | +| `timeoutMs` | `number` | timeout in **milliseconds**. | +| `opts`? | `SandboxApiOpts` | connection options. | + +###### Returns + +`Promise`\<`void`\> + +## Interfaces + +### SandboxUrlOpts + +Options for sandbox upload/download URL generation. + +#### Properties + +### user? + +```ts +optional user: string; +``` + +User that will be used to access the file. + +### useSignatureExpiration? + +```ts +optional useSignatureExpiration: number; +``` + +Use signature expiration for the URL. +Optional parameter to set the expiration time for the signature in seconds. diff --git a/docs/sdk-reference/js-sdk/v2.8.3/template-logger.mdx b/docs/sdk-reference/js-sdk/v2.8.3/template-logger.mdx new file mode 100644 index 0000000..fdebde3 --- /dev/null +++ b/docs/sdk-reference/js-sdk/v2.8.3/template-logger.mdx @@ -0,0 +1,196 @@ +--- +sidebarTitle: "Logger" +mode: "center" +--- + +### LogEntry + +Represents a single log entry from the template build process. + +#### Extended by + +- `LogEntryStart` +- `LogEntryEnd` + +#### Constructors + +```ts +new LogEntry( + timestamp: Date, + level: LogEntryLevel, + message: string): LogEntry +``` + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `timestamp` | `Date` | +| `level` | `LogEntryLevel` | +| `message` | `string` | + +###### Returns + +`LogEntry` + +#### Properties + +| Property | Modifier | Type | +| ------ | ------ | ------ | +| `level` | `readonly` | `LogEntryLevel` | +| `message` | `readonly` | `string` | +| `timestamp` | `readonly` | `Date` | + +#### Methods + +### toString() + +```ts +toString(): string +``` + +###### Returns + +`string` + +*** + +### LogEntryEnd + +Special log entry indicating the end of a build process. + +#### Constructors + +```ts +new LogEntryEnd(timestamp: Date, message: string): LogEntryEnd +``` + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `timestamp` | `Date` | +| `message` | `string` | + +###### Returns + +`LogEntryEnd` + +#### Properties + +| Property | Modifier | Type | Inherited from | +| ------ | ------ | ------ | ------ | +| `level` | `readonly` | `LogEntryLevel` | `LogEntry`.`level` | +| `message` | `readonly` | `string` | `LogEntry`.`message` | +| `timestamp` | `readonly` | `Date` | `LogEntry`.`timestamp` | + +#### Methods + +### toString() + +```ts +toString(): string +``` + +###### Returns + +`string` + +*** + +### LogEntryStart + +Special log entry indicating the start of a build process. + +#### Constructors + +```ts +new LogEntryStart(timestamp: Date, message: string): LogEntryStart +``` + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `timestamp` | `Date` | +| `message` | `string` | + +###### Returns + +`LogEntryStart` + +#### Properties + +| Property | Modifier | Type | Inherited from | +| ------ | ------ | ------ | ------ | +| `level` | `readonly` | `LogEntryLevel` | `LogEntry`.`level` | +| `message` | `readonly` | `string` | `LogEntry`.`message` | +| `timestamp` | `readonly` | `Date` | `LogEntry`.`timestamp` | + +#### Methods + +### toString() + +```ts +toString(): string +``` + +###### Returns + +`string` + +## Type Aliases + +### LogEntryLevel + +```ts +type LogEntryLevel: "debug" | "info" | "warn" | "error"; +``` + +Log entry severity levels. + +## Functions + +### defaultBuildLogger() + +```ts +function defaultBuildLogger(options?: object): (logEntry: LogEntry) => void +``` + +Create a default build logger with animated timer display. + +#### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `options`? | `object` | Logger configuration options | +| `options.minLevel`? | `LogEntryLevel` | Minimum log level to display (default: 'info') | + +#### Returns + +`Function` + +Logger function that accepts LogEntry instances + +### Parameters + +| Parameter | Type | +| ------ | ------ | +| `logEntry` | `LogEntry` | + +### Returns + +`void` + +#### Example + +```ts +import { Template, defaultBuildLogger } from 'e2b' + +const template = Template().fromPythonImage() + +await Template.build(template, { + alias: 'my-template', + onBuildLogs: defaultBuildLogger({ minLevel: 'debug' }) +}) +``` diff --git a/docs/sdk-reference/js-sdk/v2.8.3/template-readycmd.mdx b/docs/sdk-reference/js-sdk/v2.8.3/template-readycmd.mdx new file mode 100644 index 0000000..56fb0b7 --- /dev/null +++ b/docs/sdk-reference/js-sdk/v2.8.3/template-readycmd.mdx @@ -0,0 +1,202 @@ +--- +sidebarTitle: "Readycmd" +mode: "center" +--- + +### ReadyCmd + +Class for ready check commands. + +#### Constructors + +```ts +new ReadyCmd(cmd: string): ReadyCmd +``` + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `cmd` | `string` | + +###### Returns + +`ReadyCmd` + +#### Methods + +### getCmd() + +```ts +getCmd(): string +``` + +###### Returns + +`string` + +## Functions + +### waitForFile() + +```ts +function waitForFile(filename: string): ReadyCmd +``` + +Wait for a file to exist. +Uses shell test command to check file existence. + +#### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `filename` | `string` | Path to the file to wait for | + +#### Returns + +`ReadyCmd` + +ReadyCmd that checks for the file + +#### Example + +```ts +import { Template, waitForFile } from 'e2b' + +const template = Template() + .fromBaseImage() + .setStartCmd('./init.sh', waitForFile('/tmp/ready')) +``` + +*** + +### waitForPort() + +```ts +function waitForPort(port: number): ReadyCmd +``` + +Wait for a port to be listening. +Uses `ss` command to check if a port is open and listening. + +#### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `port` | `number` | Port number to wait for | + +#### Returns + +`ReadyCmd` + +ReadyCmd that checks for the port + +#### Example + +```ts +import { Template, waitForPort } from 'e2b' + +const template = Template() + .fromPythonImage() + .setStartCmd('python -m http.server 8000', waitForPort(8000)) +``` + +*** + +### waitForProcess() + +```ts +function waitForProcess(processName: string): ReadyCmd +``` + +Wait for a process with a specific name to be running. +Uses `pgrep` to check if a process exists. + +#### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `processName` | `string` | Name of the process to wait for | + +#### Returns + +`ReadyCmd` + +ReadyCmd that checks for the process + +#### Example + +```ts +import { Template, waitForProcess } from 'e2b' + +const template = Template() + .fromBaseImage() + .setStartCmd('./my-daemon', waitForProcess('my-daemon')) +``` + +*** + +### waitForTimeout() + +```ts +function waitForTimeout(timeout: number): ReadyCmd +``` + +Wait for a specified timeout before considering the sandbox ready. +Uses `sleep` command to wait for a fixed duration. + +#### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `timeout` | `number` | Time to wait in milliseconds (minimum: 1000ms / 1 second) | + +#### Returns + +`ReadyCmd` + +ReadyCmd that waits for the specified duration + +#### Example + +```ts +import { Template, waitForTimeout } from 'e2b' + +const template = Template() + .fromNodeImage() + .setStartCmd('npm start', waitForTimeout(5000)) // Wait 5 seconds +``` + +*** + +### waitForURL() + +```ts +function waitForURL(url: string, statusCode: number): ReadyCmd +``` + +Wait for a URL to return a specific HTTP status code. +Uses `curl` to make HTTP requests and check the response status. + +#### Parameters + +| Parameter | Type | Default value | Description | +| ------ | ------ | ------ | ------ | +| `url` | `string` | `undefined` | URL to check (e.g., 'http://localhost:3000/health') | +| `statusCode` | `number` | `200` | Expected HTTP status code (default: 200) | + +#### Returns + +`ReadyCmd` + +ReadyCmd that checks the URL + +#### Example + +```ts +import { Template, waitForURL } from 'e2b' + +const template = Template() + .fromNodeImage() + .setStartCmd('npm start', waitForURL('http://localhost:3000/health')) +``` diff --git a/docs/sdk-reference/js-sdk/v2.8.3/template.mdx b/docs/sdk-reference/js-sdk/v2.8.3/template.mdx new file mode 100644 index 0000000..c644e02 --- /dev/null +++ b/docs/sdk-reference/js-sdk/v2.8.3/template.mdx @@ -0,0 +1,2042 @@ +--- +sidebarTitle: "Template" +mode: "center" +--- + +### TemplateBase + +Base class for building E2B sandbox templates. + +#### Implements + +- `TemplateFromImage` +- `TemplateBuilder` +- `TemplateFinal` + +#### Constructors + +```ts +new TemplateBase(options?: TemplateOptions): TemplateBase +``` + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `options`? | `TemplateOptions` | + +###### Returns + +`TemplateBase` + +#### Methods + +### addMcpServer() + +```ts +addMcpServer(servers: keyof McpServer | keyof McpServer[]): TemplateBuilder +``` + +Install MCP servers using mcp-gateway. +Note: Requires a base image with mcp-gateway pre-installed (e.g., mcp-gateway). + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `servers` | keyof McpServer \| keyof McpServer[] | MCP server name(s) | + +###### Returns + +`TemplateBuilder` + +###### Throws + +If the base template is not mcp-gateway + +###### Example + +```ts +template.addMcpServer('exa') +template.addMcpServer(['brave', 'firecrawl', 'duckduckgo']) +``` + +###### Implementation of + +`TemplateBuilder`.`addMcpServer` + +### aptInstall() + +```ts +aptInstall(packages: string | string[], options?: object): TemplateBuilder +``` + +Install Debian/Ubuntu packages using apt-get. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `packages` | `string` \| `string`[] | Package name(s) | +| `options`? | `object` | - | +| `options.noInstallRecommends`? | `boolean` | - | + +###### Returns + +`TemplateBuilder` + +###### Example + +```ts +template.aptInstall('vim') +template.aptInstall(['git', 'curl', 'wget']) +template.aptInstall(['vim'], { noInstallRecommends: true }) +``` + +###### Implementation of + +`TemplateBuilder`.`aptInstall` + +### betaDevContainerPrebuild() + +```ts +betaDevContainerPrebuild(devcontainerDirectory: string): TemplateBuilder +``` + +Prebuild a devcontainer from the specified directory. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `devcontainerDirectory` | `string` | Path to the devcontainer directory | + +###### Returns + +`TemplateBuilder` + +###### Example + +```ts +template + .gitClone('https://myrepo.com/project.git', '/my-devcontainer') + .betaDevContainerPrebuild('/my-devcontainer') +``` + +###### Implementation of + +`TemplateBuilder`.`betaDevContainerPrebuild` + +### betaSetDevContainerStart() + +```ts +betaSetDevContainerStart(devcontainerDirectory: string): TemplateFinal +``` + +Start a devcontainer from the specified directory. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `devcontainerDirectory` | `string` | Path to the devcontainer directory | + +###### Returns + +`TemplateFinal` + +###### Example + +```ts +template + .gitClone('https://myrepo.com/project.git', '/my-devcontainer') + .startDevcontainer('/my-devcontainer') + +// Prebuild and start +template + .gitClone('https://myrepo.com/project.git', '/my-devcontainer') + .betaDevContainerPrebuild('/my-devcontainer') + // Other instructions... + .betaSetDevContainerStart('/my-devcontainer') +``` + +###### Implementation of + +`TemplateBuilder`.`betaSetDevContainerStart` + +### bunInstall() + +```ts +bunInstall(packages?: string | string[], options?: object): TemplateBuilder +``` + +Install Bun packages using bun. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `packages`? | `string` \| `string`[] | Package name(s) or undefined for package.json | +| `options`? | `object` | Install options | +| `options.dev`? | `boolean` | - | +| `options.g`? | `boolean` | - | + +###### Returns + +`TemplateBuilder` + +###### Example + +```ts +template.bunInstall('express') +template.bunInstall(['lodash', 'axios']) +template.bunInstall('tsx', { g: true }) +template.bunInstall('typescript', { dev: true }) +template.bunInstall() // Installs from package.json +``` + +###### Implementation of + +`TemplateBuilder`.`bunInstall` + +### copy() + +```ts +copy( + src: PathLike | PathLike[], + dest: PathLike, + options?: object): TemplateBuilder +``` + +Copy files or directories into the template. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `src` | `PathLike` \| `PathLike`[] | Source path(s) | +| `dest` | `PathLike` | Destination path | +| `options`? | `object` | Copy options | +| `options.forceUpload`? | `true` | - | +| `options.mode`? | `number` | - | +| `options.resolveSymlinks`? | `boolean` | - | +| `options.user`? | `string` | - | + +###### Returns + +`TemplateBuilder` + +###### Example + +```ts +template.copy('requirements.txt', '/home/user/') +template.copy(['app.ts', 'config.ts'], '/app/', { mode: 0o755 }) +``` + +###### Implementation of + +`TemplateBuilder`.`copy` + +### copyItems() + +```ts +copyItems(items: CopyItem[]): TemplateBuilder +``` + +Copy multiple items with individual options. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `items` | `CopyItem`[] | Array of copy items | + +###### Returns + +`TemplateBuilder` + +###### Example + +```ts +template.copyItems([ + { src: 'app.ts', dest: '/app/' }, + { src: 'config.ts', dest: '/app/', mode: 0o644 } +]) +``` + +###### Implementation of + +`TemplateBuilder`.`copyItems` + +### fromAWSRegistry() + +```ts +fromAWSRegistry(image: string, credentials: object): TemplateBuilder +``` + +Start from a Docker image in AWS ECR. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `image` | `string` | Full ECR image path | +| `credentials` | `object` | AWS credentials | +| `credentials.accessKeyId` | `string` | - | +| `credentials.region` | `string` | - | +| `credentials.secretAccessKey` | `string` | - | + +###### Returns + +`TemplateBuilder` + +###### Example + +```ts +Template().fromAWSRegistry( + '123456789.dkr.ecr.us-west-2.amazonaws.com/myimage:latest', + { + accessKeyId: 'AKIA...', + secretAccessKey: '...', + region: 'us-west-2' + } +) +``` + +###### Implementation of + +`TemplateFromImage.fromAWSRegistry` + +### fromBaseImage() + +```ts +fromBaseImage(): TemplateBuilder +``` + +Start from E2B's default base image (e2bdev/base:latest). + +###### Returns + +`TemplateBuilder` + +###### Example + +```ts +Template().fromBaseImage() +``` + +###### Implementation of + +`TemplateFromImage.fromBaseImage` + +### fromBunImage() + +```ts +fromBunImage(variant: string): TemplateBuilder +``` + +Start from a Bun-based Docker image. + +###### Parameters + +| Parameter | Type | Default value | Description | +| ------ | ------ | ------ | ------ | +| `variant` | `string` | `'latest'` | Bun variant (default: 'latest') | + +###### Returns + +`TemplateBuilder` + +###### Example + +```ts +Template().fromBunImage('1.3') +``` + +###### Implementation of + +`TemplateFromImage.fromBunImage` + +### fromDebianImage() + +```ts +fromDebianImage(variant: string): TemplateBuilder +``` + +Start from a Debian-based Docker image. + +###### Parameters + +| Parameter | Type | Default value | Description | +| ------ | ------ | ------ | ------ | +| `variant` | `string` | `'stable'` | Debian variant (default: 'stable') | + +###### Returns + +`TemplateBuilder` + +###### Example + +```ts +Template().fromDebianImage('bookworm') +``` + +###### Implementation of + +`TemplateFromImage.fromDebianImage` + +### fromDockerfile() + +```ts +fromDockerfile(dockerfileContentOrPath: string): TemplateBuilder +``` + +Parse a Dockerfile and convert it to Template SDK format. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `dockerfileContentOrPath` | `string` | Dockerfile content or path | + +###### Returns + +`TemplateBuilder` + +###### Example + +```ts +Template().fromDockerfile('Dockerfile') +Template().fromDockerfile('FROM python:3\nRUN pip install numpy') +``` + +###### Implementation of + +`TemplateFromImage.fromDockerfile` + +### fromGCPRegistry() + +```ts +fromGCPRegistry(image: string, credentials: object): TemplateBuilder +``` + +Start from a Docker image in Google Container Registry. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `image` | `string` | Full GCR/GAR image path | +| `credentials` | `object` | GCP service account credentials | +| `credentials.serviceAccountJSON` | `string` \| `object` | - | + +###### Returns + +`TemplateBuilder` + +###### Example + +```ts +Template().fromGCPRegistry( + 'gcr.io/myproject/myimage:latest', + { serviceAccountJSON: 'path/to/service-account.json' } +) +``` + +###### Implementation of + +`TemplateFromImage.fromGCPRegistry` + +### fromImage() + +```ts +fromImage(baseImage: string, credentials?: object): TemplateBuilder +``` + +Start from a custom Docker image. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `baseImage` | `string` | Docker image name | +| `credentials`? | `object` | Optional credentials for private registries | +| `credentials.password`? | `string` | - | +| `credentials.username`? | `string` | - | + +###### Returns + +`TemplateBuilder` + +###### Example + +```ts +Template().fromImage('python:3') + +// With credentials (optional) +Template().fromImage('myregistry.com/myimage:latest', { + username: 'user', + password: 'pass' +}) +``` + +###### Implementation of + +`TemplateFromImage.fromImage` + +### fromNodeImage() + +```ts +fromNodeImage(variant: string): TemplateBuilder +``` + +Start from a Node.js-based Docker image. + +###### Parameters + +| Parameter | Type | Default value | Description | +| ------ | ------ | ------ | ------ | +| `variant` | `string` | `'lts'` | Node.js variant (default: 'lts') | + +###### Returns + +`TemplateBuilder` + +###### Example + +```ts +Template().fromNodeImage('24') +``` + +###### Implementation of + +`TemplateFromImage.fromNodeImage` + +### fromPythonImage() + +```ts +fromPythonImage(version: string): TemplateBuilder +``` + +Start from a Python-based Docker image. + +###### Parameters + +| Parameter | Type | Default value | Description | +| ------ | ------ | ------ | ------ | +| `version` | `string` | `'3'` | Python version (default: '3') | + +###### Returns + +`TemplateBuilder` + +###### Example + +```ts +Template().fromPythonImage('3') +``` + +###### Implementation of + +`TemplateFromImage.fromPythonImage` + +### fromTemplate() + +```ts +fromTemplate(template: string): TemplateBuilder +``` + +Start from an existing E2B template. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `template` | `string` | E2B template ID or alias | + +###### Returns + +`TemplateBuilder` + +###### Example + +```ts +Template().fromTemplate('my-base-template') +``` + +###### Implementation of + +`TemplateFromImage.fromTemplate` + +### fromUbuntuImage() + +```ts +fromUbuntuImage(variant: string): TemplateBuilder +``` + +Start from an Ubuntu-based Docker image. + +###### Parameters + +| Parameter | Type | Default value | Description | +| ------ | ------ | ------ | ------ | +| `variant` | `string` | `'latest'` | Ubuntu variant (default: 'latest') | + +###### Returns + +`TemplateBuilder` + +###### Example + +```ts +Template().fromUbuntuImage('24.04') +``` + +###### Implementation of + +`TemplateFromImage.fromUbuntuImage` + +### gitClone() + +```ts +gitClone( + url: string, + path?: PathLike, + options?: object): TemplateBuilder +``` + +Clone a Git repository. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `url` | `string` | Repository URL | +| `path`? | `PathLike` | Optional destination path | +| `options`? | `object` | Clone options | +| `options.branch`? | `string` | - | +| `options.depth`? | `number` | - | +| `options.user`? | `string` | - | + +###### Returns + +`TemplateBuilder` + +###### Example + +```ts +template.gitClone('https://github.com/user/repo.git', '/app/repo') +template.gitClone('https://github.com/user/repo.git', undefined, { + branch: 'main', + depth: 1 +}) +template.gitClone('https://github.com/user/repo.git', '/app/repo', { + user: 'root' +}) +``` + +###### Implementation of + +`TemplateBuilder`.`gitClone` + +### makeDir() + +```ts +makeDir(path: PathLike | PathLike[], options?: object): TemplateBuilder +``` + +Create directories. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `path` | `PathLike` \| `PathLike`[] | Directory path(s) | +| `options`? | `object` | Directory options | +| `options.mode`? | `number` | - | +| `options.user`? | `string` | - | + +###### Returns + +`TemplateBuilder` + +###### Example + +```ts +template.makeDir('/app/data', { mode: 0o755 }) +template.makeDir(['/app/logs', '/app/cache']) +template.makeDir('/app/data', { mode: 0o755, user: 'root' }) +``` + +###### Implementation of + +`TemplateBuilder`.`makeDir` + +### makeSymlink() + +```ts +makeSymlink( + src: PathLike, + dest: PathLike, + options?: object): TemplateBuilder +``` + +Create a symbolic link. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `src` | `PathLike` | Source path (target) | +| `dest` | `PathLike` | Destination path (symlink location) | +| `options`? | `object` | Symlink options | +| `options.force`? | `boolean` | - | +| `options.user`? | `string` | - | + +###### Returns + +`TemplateBuilder` + +###### Example + +```ts +template.makeSymlink('/usr/bin/python3', '/usr/bin/python') +template.makeSymlink('/usr/bin/python3', '/usr/bin/python', { user: 'root' }) +template.makeSymlink('/usr/bin/python3', '/usr/bin/python', { force: true }) +``` + +###### Implementation of + +`TemplateBuilder`.`makeSymlink` + +### npmInstall() + +```ts +npmInstall(packages?: string | string[], options?: object): TemplateBuilder +``` + +Install Node.js packages using npm. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `packages`? | `string` \| `string`[] | Package name(s) or undefined for package.json | +| `options`? | `object` | Install options | +| `options.dev`? | `boolean` | - | +| `options.g`? | `boolean` | - | + +###### Returns + +`TemplateBuilder` + +###### Example + +```ts +template.npmInstall('express') +template.npmInstall(['lodash', 'axios']) +template.npmInstall('tsx', { g: true }) +template.npmInstall('typescript', { dev: true }) +template.npmInstall() // Installs from package.json +``` + +###### Implementation of + +`TemplateBuilder`.`npmInstall` + +### pipInstall() + +```ts +pipInstall(packages?: string | string[], options?: object): TemplateBuilder +``` + +Install Python packages using pip. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `packages`? | `string` \| `string`[] | Package name(s) or undefined for current directory | +| `options`? | `object` | Install options | +| `options.g`? | `boolean` | Install globally as root (default: true). Set to false for user-only installation with --user flag | + +###### Returns + +`TemplateBuilder` + +###### Example + +```ts +template.pipInstall('numpy') // Installs globally (default) +template.pipInstall(['pandas', 'scikit-learn']) +template.pipInstall('numpy', { g: false }) // Install for user only +template.pipInstall() // Installs from current directory +``` + +###### Implementation of + +`TemplateBuilder`.`pipInstall` + +### remove() + +```ts +remove(path: PathLike | PathLike[], options?: object): TemplateBuilder +``` + +Remove files or directories. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `path` | `PathLike` \| `PathLike`[] | Path(s) to remove | +| `options`? | `object` | Remove options | +| `options.force`? | `boolean` | - | +| `options.recursive`? | `boolean` | - | +| `options.user`? | `string` | - | + +###### Returns + +`TemplateBuilder` + +###### Example + +```ts +template.remove('/tmp/cache', { recursive: true, force: true }) +template.remove('/tmp/cache', { recursive: true, force: true, user: 'root' }) +``` + +###### Implementation of + +`TemplateBuilder`.`remove` + +### rename() + +```ts +rename( + src: PathLike, + dest: PathLike, + options?: object): TemplateBuilder +``` + +Rename or move a file or directory. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `src` | `PathLike` | Source path | +| `dest` | `PathLike` | Destination path | +| `options`? | `object` | Rename options | +| `options.force`? | `boolean` | - | +| `options.user`? | `string` | - | + +###### Returns + +`TemplateBuilder` + +###### Example + +```ts +template.rename('/tmp/old.txt', '/tmp/new.txt') +template.rename('/tmp/old.txt', '/tmp/new.txt', { user: 'root' }) +``` + +###### Implementation of + +`TemplateBuilder`.`rename` + +### runCmd() + +###### runCmd(command, options) + +```ts +runCmd(command: string, options?: object): TemplateBuilder +``` + +Run a shell command. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `command` | `string` | Command string | +| `options`? | `object` | Command options | +| `options.user`? | `string` | - | + +###### Returns + +`TemplateBuilder` + +###### Example + +```ts +template.runCmd('apt-get update') +template.runCmd(['pip install numpy', 'pip install pandas']) +template.runCmd('apt-get install vim', { user: 'root' }) +``` + +###### Implementation of + +`TemplateBuilder`.`runCmd` + +###### runCmd(commands, options) + +```ts +runCmd(commands: string[], options?: object): TemplateBuilder +``` + +Run a shell command. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `commands` | `string`[] | - | +| `options`? | `object` | Command options | +| `options.user`? | `string` | - | + +###### Returns + +`TemplateBuilder` + +###### Example + +```ts +template.runCmd('apt-get update') +template.runCmd(['pip install numpy', 'pip install pandas']) +template.runCmd('apt-get install vim', { user: 'root' }) +``` + +###### Implementation of + +`TemplateBuilder`.`runCmd` + +### setEnvs() + +```ts +setEnvs(envs: Record): TemplateBuilder +``` + +Set environment variables. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `envs` | `Record`\<`string`, `string`\> | Environment variables | + +###### Returns + +`TemplateBuilder` + +###### Example + +```ts +template.setEnvs({ NODE_ENV: 'production', PORT: '8080' }) +``` + +###### Implementation of + +`TemplateBuilder`.`setEnvs` + +### setReadyCmd() + +```ts +setReadyCmd(readyCommand: string | ReadyCmd): TemplateFinal +``` + +Set or update the ready check command. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `readyCommand` | `string` \| `ReadyCmd` | Command to check readiness | + +###### Returns + +`TemplateFinal` + +###### Example + +```ts +// Using a string command +template.setReadyCmd('curl http://localhost:8000/health') + +// Using ReadyCmd helpers +import { waitForPort, waitForFile, waitForProcess } from 'e2b' + +template.setReadyCmd(waitForPort(3000)) + +template.setReadyCmd(waitForFile('/tmp/ready')) + +template.setReadyCmd(waitForProcess('nginx')) +``` + +###### Implementation of + +`TemplateBuilder`.`setReadyCmd` + +### setStartCmd() + +```ts +setStartCmd(startCommand: string, readyCommand: string | ReadyCmd): TemplateFinal +``` + +Set the start command and ready check. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `startCommand` | `string` | Command to run on startup | +| `readyCommand` | `string` \| `ReadyCmd` | Command to check readiness | + +###### Returns + +`TemplateFinal` + +###### Example + +```ts +// Using a string command +template.setStartCmd( + 'node app.js', + 'curl http://localhost:8000/health' +) + +// Using ReadyCmd helpers +import { waitForPort, waitForURL } from 'e2b' + +template.setStartCmd( + 'python -m http.server 8000', + waitForPort(8000) +) + +template.setStartCmd( + 'npm start', + waitForURL('http://localhost:3000/health', 200) +) +``` + +###### Implementation of + +`TemplateBuilder`.`setStartCmd` + +### setUser() + +```ts +setUser(user: string): TemplateBuilder +``` + +Set the user for subsequent commands. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `user` | `string` | Username | + +###### Returns + +`TemplateBuilder` + +###### Example + +```ts +template.setUser('root') +``` + +###### Implementation of + +`TemplateBuilder`.`setUser` + +### setWorkdir() + +```ts +setWorkdir(workdir: PathLike): TemplateBuilder +``` + +Set the working directory. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `workdir` | `PathLike` | Working directory path | + +###### Returns + +`TemplateBuilder` + +###### Example + +```ts +template.setWorkdir('/app') +``` + +###### Implementation of + +`TemplateBuilder`.`setWorkdir` + +### skipCache() + +```ts +skipCache(): this +``` + +Skip cache for all subsequent build instructions from this point. + +###### Returns + +`this` + +###### Example + +```ts +Template().skipCache().fromPythonImage('3') +``` + +###### Implementation of + +`TemplateBuilder`.`skipCache` + +### build() + +```ts +static build(template: TemplateClass, options: BuildOptions): Promise +``` + +Build and deploy a template to E2B infrastructure. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `template` | `TemplateClass` | The template to build | +| `options` | `BuildOptions` | Build configuration options | + +###### Returns + +`Promise`\<`BuildInfo`\> + +###### Example + +```ts +const template = Template().fromPythonImage('3') +await Template.build(template, { + alias: 'my-python-env', + cpuCount: 2, + memoryMB: 1024 +}) +``` + +### buildInBackground() + +```ts +static buildInBackground(template: TemplateClass, options: BuildOptions): Promise +``` + +Build and deploy a template to E2B infrastructure. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `template` | `TemplateClass` | The template to build | +| `options` | `BuildOptions` | Build configuration options | + +###### Returns + +`Promise`\<`BuildInfo`\> + +###### Example + +```ts +const template = Template().fromPythonImage('3') +const data = await Template.buildInBackground(template, { + alias: 'my-python-env', + cpuCount: 2, + memoryMB: 1024 +}) +``` + +### getBuildStatus() + +```ts +static getBuildStatus(data: Pick, options?: GetBuildStatusOptions): Promise +``` + +Get the status of a build. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `data` | `Pick`\<`BuildInfo`, `"templateId"` \| `"buildId"`\> | Build identifiers | +| `options`? | `GetBuildStatusOptions` | Authentication options | + +###### Returns + +`Promise`\<`object`\> + +| Name | Type | Description | +| ------ | ------ | ------ | +| `buildID` | `string` | **Description** Identifier of the build | +| `logEntries` | `object`[] | **Description** Build logs structured **Default** `[]` | +| `logs` | `string`[] | **Description** Build logs **Default** `[]` | +| `reason`? | `object` | - | +| `reason.logEntries`? | `object`[] | **Description** Log entries related to the status reason **Default** `[]` | +| `reason.message` | `string` | **Description** Message with the status reason, currently reporting only for error status | +| `reason.step`? | `string` | **Description** Step that failed | +| `status` | `"error"` \| `"ready"` \| `"building"` \| `"waiting"` | - | +| `templateID` | `string` | **Description** Identifier of the template | + +###### Example + +```ts +const status = await Template.getBuildStatus(data, { logsOffset: 0 }) +``` + +### toDockerfile() + +```ts +static toDockerfile(template: TemplateClass): string +``` + +Convert a template to Dockerfile format. +Note: Templates based on other E2B templates cannot be converted to Dockerfile. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `template` | `TemplateClass` | The template to convert | + +###### Returns + +`string` + +Dockerfile string representation + +###### Throws + +Error if the template is based on another E2B template + +### toJSON() + +```ts +static toJSON(template: TemplateClass, computeHashes: boolean): Promise +``` + +Convert a template to JSON representation. + +###### Parameters + +| Parameter | Type | Default value | Description | +| ------ | ------ | ------ | ------ | +| `template` | `TemplateClass` | `undefined` | The template to convert | +| `computeHashes` | `boolean` | `true` | Whether to compute file hashes for cache invalidation | + +###### Returns + +`Promise`\<`string`\> + +JSON string representation of the template + +## Interfaces + +### TemplateBuilder + +Main builder state for constructing templates. +Provides methods for customizing the template environment. + +#### Methods + +### addMcpServer() + +```ts +addMcpServer(servers: keyof McpServer | keyof McpServer[]): TemplateBuilder +``` + +Install MCP servers using mcp-gateway. +Note: Requires a base image with mcp-gateway pre-installed (e.g., mcp-gateway). + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `servers` | keyof McpServer \| keyof McpServer[] | MCP server name(s) | + +###### Returns + +`TemplateBuilder` + +###### Throws + +If the base template is not mcp-gateway + +###### Example + +```ts +template.addMcpServer('exa') +template.addMcpServer(['brave', 'firecrawl', 'duckduckgo']) +``` + +### aptInstall() + +```ts +aptInstall(packages: string | string[], options?: object): TemplateBuilder +``` + +Install Debian/Ubuntu packages using apt-get. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `packages` | `string` \| `string`[] | Package name(s) | +| `options`? | `object` | - | +| `options.noInstallRecommends`? | `boolean` | - | + +###### Returns + +`TemplateBuilder` + +###### Example + +```ts +template.aptInstall('vim') +template.aptInstall(['git', 'curl', 'wget']) +template.aptInstall(['vim'], { noInstallRecommends: true }) +``` + +### betaDevContainerPrebuild() + +```ts +betaDevContainerPrebuild(devcontainerDirectory: string): TemplateBuilder +``` + +Prebuild a devcontainer from the specified directory. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `devcontainerDirectory` | `string` | Path to the devcontainer directory | + +###### Returns + +`TemplateBuilder` + +###### Example + +```ts +template + .gitClone('https://myrepo.com/project.git', '/my-devcontainer') + .betaDevContainerPrebuild('/my-devcontainer') +``` + +### betaSetDevContainerStart() + +```ts +betaSetDevContainerStart(devcontainerDirectory: string): TemplateFinal +``` + +Start a devcontainer from the specified directory. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `devcontainerDirectory` | `string` | Path to the devcontainer directory | + +###### Returns + +`TemplateFinal` + +###### Example + +```ts +template + .gitClone('https://myrepo.com/project.git', '/my-devcontainer') + .startDevcontainer('/my-devcontainer') + +// Prebuild and start +template + .gitClone('https://myrepo.com/project.git', '/my-devcontainer') + .betaDevContainerPrebuild('/my-devcontainer') + // Other instructions... + .betaSetDevContainerStart('/my-devcontainer') +``` + +### bunInstall() + +```ts +bunInstall(packages?: string | string[], options?: object): TemplateBuilder +``` + +Install Bun packages using bun. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `packages`? | `string` \| `string`[] | Package name(s) or undefined for package.json | +| `options`? | `object` | Install options | +| `options.dev`? | `boolean` | - | +| `options.g`? | `boolean` | - | + +###### Returns + +`TemplateBuilder` + +###### Example + +```ts +template.bunInstall('express') +template.bunInstall(['lodash', 'axios']) +template.bunInstall('tsx', { g: true }) +template.bunInstall('typescript', { dev: true }) +template.bunInstall() // Installs from package.json +``` + +### copy() + +```ts +copy( + src: PathLike | PathLike[], + dest: PathLike, + options?: object): TemplateBuilder +``` + +Copy files or directories into the template. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `src` | `PathLike` \| `PathLike`[] | Source path(s) | +| `dest` | `PathLike` | Destination path | +| `options`? | `object` | Copy options | +| `options.forceUpload`? | `true` | - | +| `options.mode`? | `number` | - | +| `options.resolveSymlinks`? | `boolean` | - | +| `options.user`? | `string` | - | + +###### Returns + +`TemplateBuilder` + +###### Example + +```ts +template.copy('requirements.txt', '/home/user/') +template.copy(['app.ts', 'config.ts'], '/app/', { mode: 0o755 }) +``` + +### copyItems() + +```ts +copyItems(items: CopyItem[]): TemplateBuilder +``` + +Copy multiple items with individual options. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `items` | `CopyItem`[] | Array of copy items | + +###### Returns + +`TemplateBuilder` + +###### Example + +```ts +template.copyItems([ + { src: 'app.ts', dest: '/app/' }, + { src: 'config.ts', dest: '/app/', mode: 0o644 } +]) +``` + +### gitClone() + +```ts +gitClone( + url: string, + path?: PathLike, + options?: object): TemplateBuilder +``` + +Clone a Git repository. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `url` | `string` | Repository URL | +| `path`? | `PathLike` | Optional destination path | +| `options`? | `object` | Clone options | +| `options.branch`? | `string` | - | +| `options.depth`? | `number` | - | +| `options.user`? | `string` | - | + +###### Returns + +`TemplateBuilder` + +###### Example + +```ts +template.gitClone('https://github.com/user/repo.git', '/app/repo') +template.gitClone('https://github.com/user/repo.git', undefined, { + branch: 'main', + depth: 1 +}) +template.gitClone('https://github.com/user/repo.git', '/app/repo', { + user: 'root' +}) +``` + +### makeDir() + +```ts +makeDir(path: PathLike | PathLike[], options?: object): TemplateBuilder +``` + +Create directories. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `path` | `PathLike` \| `PathLike`[] | Directory path(s) | +| `options`? | `object` | Directory options | +| `options.mode`? | `number` | - | +| `options.user`? | `string` | - | + +###### Returns + +`TemplateBuilder` + +###### Example + +```ts +template.makeDir('/app/data', { mode: 0o755 }) +template.makeDir(['/app/logs', '/app/cache']) +template.makeDir('/app/data', { mode: 0o755, user: 'root' }) +``` + +### makeSymlink() + +```ts +makeSymlink( + src: PathLike, + dest: PathLike, + options?: object): TemplateBuilder +``` + +Create a symbolic link. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `src` | `PathLike` | Source path (target) | +| `dest` | `PathLike` | Destination path (symlink location) | +| `options`? | `object` | Symlink options | +| `options.force`? | `boolean` | - | +| `options.user`? | `string` | - | + +###### Returns + +`TemplateBuilder` + +###### Example + +```ts +template.makeSymlink('/usr/bin/python3', '/usr/bin/python') +template.makeSymlink('/usr/bin/python3', '/usr/bin/python', { user: 'root' }) +template.makeSymlink('/usr/bin/python3', '/usr/bin/python', { force: true }) +``` + +### npmInstall() + +```ts +npmInstall(packages?: string | string[], options?: object): TemplateBuilder +``` + +Install Node.js packages using npm. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `packages`? | `string` \| `string`[] | Package name(s) or undefined for package.json | +| `options`? | `object` | Install options | +| `options.dev`? | `boolean` | - | +| `options.g`? | `boolean` | - | + +###### Returns + +`TemplateBuilder` + +###### Example + +```ts +template.npmInstall('express') +template.npmInstall(['lodash', 'axios']) +template.npmInstall('tsx', { g: true }) +template.npmInstall('typescript', { dev: true }) +template.npmInstall() // Installs from package.json +``` + +### pipInstall() + +```ts +pipInstall(packages?: string | string[], options?: object): TemplateBuilder +``` + +Install Python packages using pip. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `packages`? | `string` \| `string`[] | Package name(s) or undefined for current directory | +| `options`? | `object` | Install options | +| `options.g`? | `boolean` | Install globally as root (default: true). Set to false for user-only installation with --user flag | + +###### Returns + +`TemplateBuilder` + +###### Example + +```ts +template.pipInstall('numpy') // Installs globally (default) +template.pipInstall(['pandas', 'scikit-learn']) +template.pipInstall('numpy', { g: false }) // Install for user only +template.pipInstall() // Installs from current directory +``` + +### remove() + +```ts +remove(path: PathLike | PathLike[], options?: object): TemplateBuilder +``` + +Remove files or directories. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `path` | `PathLike` \| `PathLike`[] | Path(s) to remove | +| `options`? | `object` | Remove options | +| `options.force`? | `boolean` | - | +| `options.recursive`? | `boolean` | - | +| `options.user`? | `string` | - | + +###### Returns + +`TemplateBuilder` + +###### Example + +```ts +template.remove('/tmp/cache', { recursive: true, force: true }) +template.remove('/tmp/cache', { recursive: true, force: true, user: 'root' }) +``` + +### rename() + +```ts +rename( + src: PathLike, + dest: PathLike, + options?: object): TemplateBuilder +``` + +Rename or move a file or directory. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `src` | `PathLike` | Source path | +| `dest` | `PathLike` | Destination path | +| `options`? | `object` | Rename options | +| `options.force`? | `boolean` | - | +| `options.user`? | `string` | - | + +###### Returns + +`TemplateBuilder` + +###### Example + +```ts +template.rename('/tmp/old.txt', '/tmp/new.txt') +template.rename('/tmp/old.txt', '/tmp/new.txt', { user: 'root' }) +``` + +### runCmd() + +###### runCmd(command, options) + +```ts +runCmd(command: string, options?: object): TemplateBuilder +``` + +Run a shell command. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `command` | `string` | Command string | +| `options`? | `object` | Command options | +| `options.user`? | `string` | - | + +###### Returns + +`TemplateBuilder` + +###### Example + +```ts +template.runCmd('apt-get update') +template.runCmd(['pip install numpy', 'pip install pandas']) +template.runCmd('apt-get install vim', { user: 'root' }) +``` + +###### runCmd(commands, options) + +```ts +runCmd(commands: string[], options?: object): TemplateBuilder +``` + +Run multiple shell commands. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `commands` | `string`[] | Array of command strings | +| `options`? | `object` | Command options | +| `options.user`? | `string` | - | + +###### Returns + +`TemplateBuilder` + +###### runCmd(commandOrCommands, options) + +```ts +runCmd(commandOrCommands: string | string[], options?: object): TemplateBuilder +``` + +Run command(s). + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `commandOrCommands` | `string` \| `string`[] | Command or commands | +| `options`? | `object` | Command options | +| `options.user`? | `string` | - | + +###### Returns + +`TemplateBuilder` + +### setEnvs() + +```ts +setEnvs(envs: Record): TemplateBuilder +``` + +Set environment variables. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `envs` | `Record`\<`string`, `string`\> | Environment variables | + +###### Returns + +`TemplateBuilder` + +###### Example + +```ts +template.setEnvs({ NODE_ENV: 'production', PORT: '8080' }) +``` + +### setReadyCmd() + +```ts +setReadyCmd(readyCommand: string | ReadyCmd): TemplateFinal +``` + +Set or update the ready check command. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `readyCommand` | `string` \| `ReadyCmd` | Command to check readiness | + +###### Returns + +`TemplateFinal` + +###### Example + +```ts +// Using a string command +template.setReadyCmd('curl http://localhost:8000/health') + +// Using ReadyCmd helpers +import { waitForPort, waitForFile, waitForProcess } from 'e2b' + +template.setReadyCmd(waitForPort(3000)) + +template.setReadyCmd(waitForFile('/tmp/ready')) + +template.setReadyCmd(waitForProcess('nginx')) +``` + +### setStartCmd() + +```ts +setStartCmd(startCommand: string, readyCommand: string | ReadyCmd): TemplateFinal +``` + +Set the start command and ready check. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `startCommand` | `string` | Command to run on startup | +| `readyCommand` | `string` \| `ReadyCmd` | Command to check readiness | + +###### Returns + +`TemplateFinal` + +###### Example + +```ts +// Using a string command +template.setStartCmd( + 'node app.js', + 'curl http://localhost:8000/health' +) + +// Using ReadyCmd helpers +import { waitForPort, waitForURL } from 'e2b' + +template.setStartCmd( + 'python -m http.server 8000', + waitForPort(8000) +) + +template.setStartCmd( + 'npm start', + waitForURL('http://localhost:3000/health', 200) +) +``` + +### setUser() + +```ts +setUser(user: string): TemplateBuilder +``` + +Set the user for subsequent commands. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `user` | `string` | Username | + +###### Returns + +`TemplateBuilder` + +###### Example + +```ts +template.setUser('root') +``` + +### setWorkdir() + +```ts +setWorkdir(workdir: PathLike): TemplateBuilder +``` + +Set the working directory. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `workdir` | `PathLike` | Working directory path | + +###### Returns + +`TemplateBuilder` + +###### Example + +```ts +template.setWorkdir('/app') +``` + +### skipCache() + +```ts +skipCache(): this +``` + +Skip cache for all subsequent build instructions from this point. + +###### Returns + +`this` + +###### Example + +```ts +template.skipCache().runCmd('apt-get update') +``` + +## Type Aliases + +### BuildInfo + +```ts +type BuildInfo: object; +``` + +Information about a built template. + +#### Type declaration + +| Name | Type | +| ------ | ------ | +| `alias` | `string` | +| `buildId` | `string` | +| `templateId` | `string` | + +*** + +### BuildOptions + +```ts +type BuildOptions: AuthOptions & BasicBuildOptions; +``` + +Options for building a template with authentication. + +*** + +### CopyItem + +```ts +type CopyItem: object; +``` + +Configuration for a single file/directory copy operation. + +#### Type declaration + +| Name | Type | +| ------ | ------ | +| `dest` | `PathLike` | +| `forceUpload`? | `true` | +| `mode`? | `number` | +| `resolveSymlinks`? | `boolean` | +| `src` | `PathLike` \| `PathLike`[] | +| `user`? | `string` | + +*** + +### GetBuildStatusOptions + +```ts +type GetBuildStatusOptions: AuthOptions & object; +``` + +Response from getting build status. + +#### Type declaration + +| Name | Type | +| ------ | ------ | +| `logsOffset`? | `number` | + +*** + +### McpServerName + +```ts +type McpServerName: keyof McpServer; +``` + +MCP server names that can be installed. + +*** + +### TemplateClass + +```ts +type TemplateClass: TemplateBuilder | TemplateFinal; +``` + +Type representing a template in any state (builder or final). + +## Functions + +### Template() + +```ts +function Template(options?: TemplateOptions): TemplateFromImage +``` + +Create a new E2B template builder instance. + +#### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `options`? | `TemplateOptions` | Optional configuration for the template builder | + +#### Returns + +`TemplateFromImage` + +A new template builder instance + +#### Example + +```ts +import { Template } from 'e2b' + +const template = Template() + .fromPythonImage('3') + .copy('requirements.txt', '/app/') + .pipInstall() + +await Template.build(template, { alias: 'my-python-app' }) +``` diff --git a/docs/sdk-reference/js-sdk/v2.8.4/errors.mdx b/docs/sdk-reference/js-sdk/v2.8.4/errors.mdx new file mode 100644 index 0000000..bfe0deb --- /dev/null +++ b/docs/sdk-reference/js-sdk/v2.8.4/errors.mdx @@ -0,0 +1,271 @@ +--- +sidebarTitle: "Errors" +mode: "center" +--- + +### AuthenticationError + +Thrown when authentication fails. + +#### Constructors + +```ts +new AuthenticationError(message: string): AuthenticationError +``` + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `message` | `string` | + +###### Returns + +`AuthenticationError` + +*** + +### BuildError + +Thrown when the build fails. + +#### Extended by + +- `FileUploadError` + +#### Constructors + +```ts +new BuildError(message: string, stackTrace?: string): BuildError +``` + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `message` | `string` | +| `stackTrace`? | `string` | + +###### Returns + +`BuildError` + +*** + +### FileUploadError + +Thrown when the file upload fails. + +#### Constructors + +```ts +new FileUploadError(message: string, stackTrace?: string): FileUploadError +``` + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `message` | `string` | +| `stackTrace`? | `string` | + +###### Returns + +`FileUploadError` + +*** + +### InvalidArgumentError + +Thrown when an invalid argument is provided. + +#### Constructors + +```ts +new InvalidArgumentError(message: string, stackTrace?: string): InvalidArgumentError +``` + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `message` | `string` | +| `stackTrace`? | `string` | + +###### Returns + +`InvalidArgumentError` + +*** + +### NotEnoughSpaceError + +Thrown when there is not enough disk space. + +#### Constructors + +```ts +new NotEnoughSpaceError(message: string, stackTrace?: string): NotEnoughSpaceError +``` + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `message` | `string` | +| `stackTrace`? | `string` | + +###### Returns + +`NotEnoughSpaceError` + +*** + +### NotFoundError + +Thrown when a resource is not found. + +#### Constructors + +```ts +new NotFoundError(message: string, stackTrace?: string): NotFoundError +``` + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `message` | `string` | +| `stackTrace`? | `string` | + +###### Returns + +`NotFoundError` + +*** + +### RateLimitError + +Thrown when the API rate limit is exceeded. + +#### Constructors + +```ts +new RateLimitError(message: string): RateLimitError +``` + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `message` | `string` | + +###### Returns + +`RateLimitError` + +*** + +### SandboxError + +Base class for all sandbox errors. + +Thrown when general sandbox errors occur. + +#### Extended by + +- `TimeoutError` +- `InvalidArgumentError` +- `NotEnoughSpaceError` +- `NotFoundError` +- `TemplateError` +- `RateLimitError` + +#### Constructors + +```ts +new SandboxError(message?: string, stackTrace?: string): SandboxError +``` + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `message`? | `string` | +| `stackTrace`? | `string` | + +###### Returns + +`SandboxError` + +*** + +### TemplateError + +Thrown when the template uses old envd version. It isn't compatible with the new SDK. + +#### Constructors + +```ts +new TemplateError(message: string, stackTrace?: string): TemplateError +``` + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `message` | `string` | +| `stackTrace`? | `string` | + +###### Returns + +`TemplateError` + +*** + +### TimeoutError + +Thrown when a timeout error occurs. + +The [unavailable] error type is caused by sandbox timeout. + +The [canceled] error type is caused by exceeding request timeout. + +The [deadline_exceeded] error type is caused by exceeding the timeout for command execution, watch, etc. + +The [unknown] error type is sometimes caused by the sandbox timeout when the request is not processed correctly. + +#### Constructors + +```ts +new TimeoutError(message: string, stackTrace?: string): TimeoutError +``` + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `message` | `string` | +| `stackTrace`? | `string` | + +###### Returns + +`TimeoutError` + +## Functions + +### formatSandboxTimeoutError() + +```ts +function formatSandboxTimeoutError(message: string): TimeoutError +``` + +#### Parameters + +| Parameter | Type | +| ------ | ------ | +| `message` | `string` | + +#### Returns + +`TimeoutError` diff --git a/docs/sdk-reference/js-sdk/v2.8.4/sandbox-commands.mdx b/docs/sdk-reference/js-sdk/v2.8.4/sandbox-commands.mdx new file mode 100644 index 0000000..16d736c --- /dev/null +++ b/docs/sdk-reference/js-sdk/v2.8.4/sandbox-commands.mdx @@ -0,0 +1,533 @@ +--- +sidebarTitle: "Commands" +mode: "center" +--- + +### Commands + +Module for starting and interacting with commands in the sandbox. + +#### Constructors + +```ts +new Commands( + transport: Transport, + connectionConfig: ConnectionConfig, + metadata: object): Commands +``` + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `transport` | `Transport` | +| `connectionConfig` | `ConnectionConfig` | +| `metadata` | `object` | +| `metadata.version` | `string` | + +###### Returns + +`Commands` + +#### Methods + +### connect() + +```ts +connect(pid: number, opts?: CommandConnectOpts): Promise +``` + +Connect to a running command. +You can use CommandHandle.wait to wait for the command to finish and get execution results. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `pid` | `number` | process ID of the command to connect to. You can get the list of running commands using Commands.list. | +| `opts`? | `CommandConnectOpts` | connection options. | + +###### Returns + +`Promise`\<`CommandHandle`\> + +`CommandHandle` handle to interact with the running command. + +### kill() + +```ts +kill(pid: number, opts?: CommandRequestOpts): Promise +``` + +Kill a running command specified by its process ID. +It uses `SIGKILL` signal to kill the command. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `pid` | `number` | process ID of the command. You can get the list of running commands using Commands.list. | +| `opts`? | `CommandRequestOpts` | connection options. | + +###### Returns + +`Promise`\<`boolean`\> + +`true` if the command was killed, `false` if the command was not found. + +### list() + +```ts +list(opts?: CommandRequestOpts): Promise +``` + +List all running commands and PTY sessions. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `opts`? | `CommandRequestOpts` | connection options. | + +###### Returns + +`Promise`\<`ProcessInfo`[]\> + +list of running commands and PTY sessions. + +### run() + +###### run(cmd, opts) + +```ts +run(cmd: string, opts?: CommandStartOpts & object): Promise +``` + +Start a new command and wait until it finishes executing. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `cmd` | `string` | command to execute. | +| `opts`? | `CommandStartOpts` & `object` | options for starting the command. | + +###### Returns + +`Promise`\<`CommandResult`\> + +`CommandResult` result of the command execution. + +###### run(cmd, opts) + +```ts +run(cmd: string, opts: CommandStartOpts & object): Promise +``` + +Start a new command in the background. +You can use CommandHandle.wait to wait for the command to finish and get its result. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `cmd` | `string` | command to execute. | +| `opts` | `CommandStartOpts` & `object` | options for starting the command | + +###### Returns + +`Promise`\<`CommandHandle`\> + +`CommandHandle` handle to interact with the running command. + +###### run(cmd, opts) + +```ts +run(cmd: string, opts?: CommandStartOpts & object): Promise +``` + +Start a new command. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `cmd` | `string` | command to execute. | +| `opts`? | `CommandStartOpts` & `object` | options for starting the command. - `opts.background: true` - runs in background, returns `CommandHandle` - `opts.background: false | undefined` - waits for completion, returns `CommandResult` | + +###### Returns + +`Promise`\<`CommandResult` \| `CommandHandle`\> + +Either a `CommandHandle` or a `CommandResult` (depending on `opts.background`). + +### sendStdin() + +```ts +sendStdin( + pid: number, + data: string, +opts?: CommandRequestOpts): Promise +``` + +Send data to command stdin. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `pid` | `number` | process ID of the command. You can get the list of running commands using Commands.list. | +| `data` | `string` | data to send to the command. | +| `opts`? | `CommandRequestOpts` | connection options. | + +###### Returns + +`Promise`\<`void`\> + +*** + +### Pty + +Module for interacting with PTYs (pseudo-terminals) in the sandbox. + +#### Constructors + +```ts +new Pty( + transport: Transport, + connectionConfig: ConnectionConfig, + metadata: object): Pty +``` + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `transport` | `Transport` | +| `connectionConfig` | `ConnectionConfig` | +| `metadata` | `object` | +| `metadata.version` | `string` | + +###### Returns + +`Pty` + +#### Methods + +### create() + +```ts +create(opts: PtyCreateOpts): Promise +``` + +Create a new PTY (pseudo-terminal). + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `opts` | `PtyCreateOpts` | options for creating the PTY. | + +###### Returns + +`Promise`\<`CommandHandle`\> + +handle to interact with the PTY. + +### kill() + +```ts +kill(pid: number, opts?: Pick): Promise +``` + +Kill a running PTY specified by process ID. +It uses `SIGKILL` signal to kill the PTY. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `pid` | `number` | process ID of the PTY. | +| `opts`? | `Pick`\<`ConnectionOpts`, `"requestTimeoutMs"`\> | connection options. | + +###### Returns + +`Promise`\<`boolean`\> + +`true` if the PTY was killed, `false` if the PTY was not found. + +### resize() + +```ts +resize( + pid: number, + size: object, +opts?: Pick): Promise +``` + +Resize PTY. +Call this when the terminal window is resized and the number of columns and rows has changed. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `pid` | `number` | process ID of the PTY. | +| `size` | `object` | new size of the PTY. | +| `size.cols` | `number` | - | +| `size.rows`? | `number` | - | +| `opts`? | `Pick`\<`ConnectionOpts`, `"requestTimeoutMs"`\> | connection options. | + +###### Returns + +`Promise`\<`void`\> + +### sendInput() + +```ts +sendInput( + pid: number, + data: Uint8Array, +opts?: Pick): Promise +``` + +Send input to a PTY. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `pid` | `number` | process ID of the PTY. | +| `data` | `Uint8Array` | input data to send to the PTY. | +| `opts`? | `Pick`\<`ConnectionOpts`, `"requestTimeoutMs"`\> | connection options. | + +###### Returns + +`Promise`\<`void`\> + +## Interfaces + +### CommandRequestOpts + +Options for sending a command request. + +#### Extended by + +- `CommandStartOpts` + +#### Properties + +### requestTimeoutMs? + +```ts +optional requestTimeoutMs: number; +``` + +Timeout for requests to the API in **milliseconds**. + +###### Default + +```ts +60_000 // 60 seconds +``` + +*** + +### CommandStartOpts + +Options for starting a new command. + +#### Properties + +### background? + +```ts +optional background: boolean; +``` + +If true, starts command in the background and the method returns immediately. +You can use CommandHandle.wait to wait for the command to finish. + +### cwd? + +```ts +optional cwd: string; +``` + +Working directory for the command. + +###### Default + +```ts +// home directory of the user used to start the command +``` + +### envs? + +```ts +optional envs: Record; +``` + +Environment variables used for the command. + +This overrides the default environment variables from `Sandbox` constructor. + +###### Default + +`{}` + +### onStderr()? + +```ts +optional onStderr: (data: string) => void | Promise; +``` + +Callback for command stderr output. + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `data` | `string` | + +###### Returns + +`void` \| `Promise`\<`void`\> + +### onStdout()? + +```ts +optional onStdout: (data: string) => void | Promise; +``` + +Callback for command stdout output. + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `data` | `string` | + +###### Returns + +`void` \| `Promise`\<`void`\> + +### requestTimeoutMs? + +```ts +optional requestTimeoutMs: number; +``` + +Timeout for requests to the API in **milliseconds**. + +###### Default + +```ts +60_000 // 60 seconds +``` + +### stdin? + +```ts +optional stdin: boolean; +``` + +If true, command stdin is kept open and you can send data to it using Commands.sendStdin or CommandHandle.sendStdin. + +###### Default + +```ts +false +``` + +### timeoutMs? + +```ts +optional timeoutMs: number; +``` + +Timeout for the command in **milliseconds**. + +###### Default + +```ts +60_000 // 60 seconds +``` + +### user? + +```ts +optional user: string; +``` + +User to run the command as. + +###### Default + +`default Sandbox user (as specified in the template)` + +*** + +### ProcessInfo + +Information about a command, PTY session or start command running in the sandbox as process. + +#### Properties + +### args + +```ts +args: string[]; +``` + +Command arguments. + +### cmd + +```ts +cmd: string; +``` + +Command that was executed. + +### cwd? + +```ts +optional cwd: string; +``` + +Executed command working directory. + +### envs + +```ts +envs: Record; +``` + +Environment variables used for the command. + +### pid + +```ts +pid: number; +``` + +Process ID. + +### tag? + +```ts +optional tag: string; +``` + +Custom tag used for identifying special commands like start command in the custom template. + +## Type Aliases + +### CommandConnectOpts + +```ts +type CommandConnectOpts: Pick & CommandRequestOpts; +``` + +Options for connecting to a command. diff --git a/docs/sdk-reference/js-sdk/v2.8.4/sandbox-filesystem.mdx b/docs/sdk-reference/js-sdk/v2.8.4/sandbox-filesystem.mdx new file mode 100644 index 0000000..c43ac2f --- /dev/null +++ b/docs/sdk-reference/js-sdk/v2.8.4/sandbox-filesystem.mdx @@ -0,0 +1,627 @@ +--- +sidebarTitle: "Filesystem" +mode: "center" +--- + +### FileType + +Sandbox filesystem object type. + +#### Enumeration Members + +| Enumeration Member | Value | Description | +| ------ | ------ | ------ | +| `DIR` | `"dir"` | Filesystem object is a directory. | +| `FILE` | `"file"` | Filesystem object is a file. | + +## Classes + +### Filesystem + +Module for interacting with the sandbox filesystem. + +#### Constructors + +```ts +new Filesystem( + transport: Transport, + envdApi: EnvdApiClient, + connectionConfig: ConnectionConfig): Filesystem +``` + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `transport` | `Transport` | +| `envdApi` | `EnvdApiClient` | +| `connectionConfig` | `ConnectionConfig` | + +###### Returns + +`Filesystem` + +#### Methods + +### exists() + +```ts +exists(path: string, opts?: FilesystemRequestOpts): Promise +``` + +Check if a file or a directory exists. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `path` | `string` | path to a file or a directory | +| `opts`? | `FilesystemRequestOpts` | connection options. | + +###### Returns + +`Promise`\<`boolean`\> + +`true` if the file or directory exists, `false` otherwise + +### getInfo() + +```ts +getInfo(path: string, opts?: FilesystemRequestOpts): Promise +``` + +Get information about a file or directory. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `path` | `string` | path to a file or directory. | +| `opts`? | `FilesystemRequestOpts` | connection options. | + +###### Returns + +`Promise`\<`EntryInfo`\> + +information about the file or directory like name, type, and path. + +### list() + +```ts +list(path: string, opts?: FilesystemListOpts): Promise +``` + +List entries in a directory. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `path` | `string` | path to the directory. | +| `opts`? | `FilesystemListOpts` | connection options. | + +###### Returns + +`Promise`\<`EntryInfo`[]\> + +list of entries in the sandbox filesystem directory. + +### makeDir() + +```ts +makeDir(path: string, opts?: FilesystemRequestOpts): Promise +``` + +Create a new directory and all directories along the way if needed on the specified path. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `path` | `string` | path to a new directory. For example '/dirA/dirB' when creating 'dirB'. | +| `opts`? | `FilesystemRequestOpts` | connection options. | + +###### Returns + +`Promise`\<`boolean`\> + +`true` if the directory was created, `false` if it already exists. + +### read() + +###### read(path, opts) + +```ts +read(path: string, opts?: FilesystemRequestOpts & object): Promise +``` + +Read file content as a `string`. + +You can pass `text`, `bytes`, `blob`, or `stream` to `opts.format` to change the return type. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `path` | `string` | path to the file. | +| `opts`? | `FilesystemRequestOpts` & `object` | connection options. | + +###### Returns + +`Promise`\<`string`\> + +file content as string + +###### read(path, opts) + +```ts +read(path: string, opts?: FilesystemRequestOpts & object): Promise +``` + +Read file content as a `Uint8Array`. + +You can pass `text`, `bytes`, `blob`, or `stream` to `opts.format` to change the return type. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `path` | `string` | path to the file. | +| `opts`? | `FilesystemRequestOpts` & `object` | connection options. | + +###### Returns + +`Promise`\<`Uint8Array`\> + +file content as `Uint8Array` + +###### read(path, opts) + +```ts +read(path: string, opts?: FilesystemRequestOpts & object): Promise +``` + +Read file content as a `Blob`. + +You can pass `text`, `bytes`, `blob`, or `stream` to `opts.format` to change the return type. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `path` | `string` | path to the file. | +| `opts`? | `FilesystemRequestOpts` & `object` | connection options. | + +###### Returns + +`Promise`\<`Blob`\> + +file content as `Blob` + +###### read(path, opts) + +```ts +read(path: string, opts?: FilesystemRequestOpts & object): Promise> +``` + +Read file content as a `ReadableStream`. + +You can pass `text`, `bytes`, `blob`, or `stream` to `opts.format` to change the return type. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `path` | `string` | path to the file. | +| `opts`? | `FilesystemRequestOpts` & `object` | connection options. | + +###### Returns + +`Promise`\<`ReadableStream`\<`Uint8Array`\>\> + +file content as `ReadableStream` + +### remove() + +```ts +remove(path: string, opts?: FilesystemRequestOpts): Promise +``` + +Remove a file or directory. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `path` | `string` | path to a file or directory. | +| `opts`? | `FilesystemRequestOpts` | connection options. | + +###### Returns + +`Promise`\<`void`\> + +### rename() + +```ts +rename( + oldPath: string, + newPath: string, +opts?: FilesystemRequestOpts): Promise +``` + +Rename a file or directory. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `oldPath` | `string` | path to the file or directory to rename. | +| `newPath` | `string` | new path for the file or directory. | +| `opts`? | `FilesystemRequestOpts` | connection options. | + +###### Returns + +`Promise`\<`EntryInfo`\> + +information about renamed file or directory. + +### watchDir() + +```ts +watchDir( + path: string, + onEvent: (event: FilesystemEvent) => void | Promise, +opts?: WatchOpts & object): Promise +``` + +Start watching a directory for filesystem events. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `path` | `string` | path to directory to watch. | +| `onEvent` | (`event`: `FilesystemEvent`) => `void` \| `Promise`\<`void`\> | callback to call when an event in the directory occurs. | +| `opts`? | `WatchOpts` & `object` | connection options. | + +###### Returns + +`Promise`\<`WatchHandle`\> + +`WatchHandle` object for stopping watching directory. + +### write() + +###### write(path, data, opts) + +```ts +write( + path: string, + data: string | ArrayBuffer | Blob | ReadableStream, +opts?: FilesystemRequestOpts): Promise +``` + +Write content to a file. + +Writing to a file that doesn't exist creates the file. + +Writing to a file that already exists overwrites the file. + +Writing to a file at path that doesn't exist creates the necessary directories. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `path` | `string` | path to file. | +| `data` | `string` \| `ArrayBuffer` \| `Blob` \| `ReadableStream`\<`any`\> | data to write to the file. Data can be a string, `ArrayBuffer`, `Blob`, or `ReadableStream`. | +| `opts`? | `FilesystemRequestOpts` | connection options. | + +###### Returns + +`Promise`\<`WriteInfo`\> + +information about the written file + +###### write(files, opts) + +```ts +write(files: WriteEntry[], opts?: FilesystemRequestOpts): Promise +``` + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `files` | `WriteEntry`[] | +| `opts`? | `FilesystemRequestOpts` | + +###### Returns + +`Promise`\<`WriteInfo`[]\> + +## Interfaces + +### EntryInfo + +Sandbox filesystem object information. + +#### Properties + +### group + +```ts +group: string; +``` + +Group owner of the filesystem object. + +### mode + +```ts +mode: number; +``` + +File mode and permission bits. + +### modifiedTime? + +```ts +optional modifiedTime: Date; +``` + +Last modification time of the filesystem object. + +### name + +```ts +name: string; +``` + +Name of the filesystem object. + +### owner + +```ts +owner: string; +``` + +Owner of the filesystem object. + +### path + +```ts +path: string; +``` + +Path to the filesystem object. + +### permissions + +```ts +permissions: string; +``` + +String representation of file permissions (e.g. 'rwxr-xr-x'). + +### size + +```ts +size: number; +``` + +Size of the filesystem object in bytes. + +### symlinkTarget? + +```ts +optional symlinkTarget: string; +``` + +If the filesystem object is a symlink, this is the target of the symlink. + +### type? + +```ts +optional type: FileType; +``` + +Type of the filesystem object. + +*** + +### FilesystemListOpts + +Options for the sandbox filesystem operations. + +#### Properties + +### depth? + +```ts +optional depth: number; +``` + +Depth of the directory to list. + +### requestTimeoutMs? + +```ts +optional requestTimeoutMs: number; +``` + +Timeout for requests to the API in **milliseconds**. + +###### Default + +```ts +60_000 // 60 seconds +``` + +### user? + +```ts +optional user: string; +``` + +User to use for the operation in the sandbox. +This affects the resolution of relative paths and ownership of the created filesystem objects. + +*** + +### FilesystemRequestOpts + +Options for the sandbox filesystem operations. + +#### Extended by + +- `FilesystemListOpts` +- `WatchOpts` + +#### Properties + +### requestTimeoutMs? + +```ts +optional requestTimeoutMs: number; +``` + +Timeout for requests to the API in **milliseconds**. + +###### Default + +```ts +60_000 // 60 seconds +``` + +### user? + +```ts +optional user: string; +``` + +User to use for the operation in the sandbox. +This affects the resolution of relative paths and ownership of the created filesystem objects. + +*** + +### WatchOpts + +Options for watching a directory. + +#### Properties + +### onExit()? + +```ts +optional onExit: (err?: Error) => void | Promise; +``` + +Callback to call when the watch operation stops. + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `err`? | `Error` | + +###### Returns + +`void` \| `Promise`\<`void`\> + +### recursive? + +```ts +optional recursive: boolean; +``` + +Watch the directory recursively + +### requestTimeoutMs? + +```ts +optional requestTimeoutMs: number; +``` + +Timeout for requests to the API in **milliseconds**. + +###### Default + +```ts +60_000 // 60 seconds +``` + +### timeoutMs? + +```ts +optional timeoutMs: number; +``` + +Timeout for the watch operation in **milliseconds**. +You can pass `0` to disable the timeout. + +###### Default + +```ts +60_000 // 60 seconds +``` + +### user? + +```ts +optional user: string; +``` + +User to use for the operation in the sandbox. +This affects the resolution of relative paths and ownership of the created filesystem objects. + +*** + +### WriteInfo + +Sandbox filesystem object information. + +#### Extended by + +- `EntryInfo` + +#### Properties + +### name + +```ts +name: string; +``` + +Name of the filesystem object. + +### path + +```ts +path: string; +``` + +Path to the filesystem object. + +### type? + +```ts +optional type: FileType; +``` + +Type of the filesystem object. + +## Type Aliases + +### WriteEntry + +```ts +type WriteEntry: object; +``` + +#### Type declaration + +| Name | Type | +| ------ | ------ | +| `data` | `string` \| `ArrayBuffer` \| `Blob` \| `ReadableStream` | +| `path` | `string` | diff --git a/docs/sdk-reference/js-sdk/v2.8.4/sandbox.mdx b/docs/sdk-reference/js-sdk/v2.8.4/sandbox.mdx new file mode 100644 index 0000000..e430744 --- /dev/null +++ b/docs/sdk-reference/js-sdk/v2.8.4/sandbox.mdx @@ -0,0 +1,712 @@ +--- +sidebarTitle: "Sandbox" +mode: "center" +--- + +### Sandbox + +E2B cloud sandbox is a secure and isolated cloud environment. + +The sandbox allows you to: +- Access Linux OS +- Create, list, and delete files and directories +- Run commands +- Run isolated code +- Access the internet + +Check docs here. + +Use Sandbox.create to create a new sandbox. + +#### Example + +```ts +import { Sandbox } from 'e2b' + +const sandbox = await Sandbox.create() +``` + +#### Properties + +| Property | Modifier | Type | Description | +| ------ | ------ | ------ | ------ | +| `commands` | `readonly` | `Commands` | Module for running commands in the sandbox | +| `files` | `readonly` | `Filesystem` | Module for interacting with the sandbox filesystem | +| `pty` | `readonly` | `Pty` | Module for interacting with the sandbox pseudo-terminals | +| `sandboxDomain` | `readonly` | `string` | Domain where the sandbox is hosted. | +| `sandboxId` | `readonly` | `string` | Unique identifier of the sandbox. | +| `trafficAccessToken?` | `readonly` | `string` | Traffic access token for accessing sandbox services with restricted public traffic. | + +#### Methods + +### betaPause() + +```ts +betaPause(opts?: ConnectionOpts): Promise +``` + +**`Beta`** + +This feature is in beta and may change in the future. + +Pause a sandbox by its ID. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `opts`? | `ConnectionOpts` | connection options. | + +###### Returns + +`Promise`\<`boolean`\> + +sandbox ID that can be used to resume the sandbox. + +### connect() + +```ts +connect(opts?: SandboxBetaCreateOpts): Promise +``` + +Connect to a sandbox. If the sandbox is paused, it will be automatically resumed. +Sandbox must be either running or be paused. + +With sandbox ID you can connect to the same sandbox from different places or environments (serverless functions, etc). + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `opts`? | `SandboxBetaCreateOpts` | connection options. | + +###### Returns + +`Promise`\<`Sandbox`\> + +A running sandbox instance + +###### Example + +```ts +const sandbox = await Sandbox.create() +await sandbox.betaPause() + +// Connect to the same sandbox. +const sameSandbox = await sandbox.connect() +``` + +### downloadUrl() + +```ts +downloadUrl(path: string, opts?: SandboxUrlOpts): Promise +``` + +Get the URL to download a file from the sandbox. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `path` | `string` | path to the file in the sandbox. | +| `opts`? | `SandboxUrlOpts` | download url options. | + +###### Returns + +`Promise`\<`string`\> + +URL for downloading file. + +### getHost() + +```ts +getHost(port: number): string +``` + +Get the host address for the specified sandbox port. +You can then use this address to connect to the sandbox port from outside the sandbox via HTTP or WebSocket. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `port` | `number` | number of the port in the sandbox. | + +###### Returns + +`string` + +host address of the sandbox port. + +###### Example + +```ts +const sandbox = await Sandbox.create() +// Start an HTTP server +await sandbox.commands.exec('python3 -m http.server 3000') +// Get the hostname of the HTTP server +const serverURL = sandbox.getHost(3000) +``` + +### getInfo() + +```ts +getInfo(opts?: Pick): Promise +``` + +Get sandbox information like sandbox ID, template, metadata, started at/end at date. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `opts`? | `Pick`\<`SandboxOpts`, `"requestTimeoutMs"`\> | connection options. | + +###### Returns + +`Promise`\<`SandboxInfo`\> + +information about the sandbox + +### getMcpToken() + +```ts +getMcpToken(): Promise +``` + +Get the MCP token for the sandbox. + +###### Returns + +`Promise`\<`undefined` \| `string`\> + +MCP token for the sandbox, or undefined if MCP is not enabled. + +### getMcpUrl() + +```ts +getMcpUrl(): string +``` + +Get the MCP URL for the sandbox. + +###### Returns + +`string` + +MCP URL for the sandbox. + +### getMetrics() + +```ts +getMetrics(opts?: SandboxMetricsOpts): Promise +``` + +Get the metrics of the sandbox. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `opts`? | `SandboxMetricsOpts` | connection options. | + +###### Returns + +`Promise`\<`SandboxMetrics`[]\> + +List of sandbox metrics containing CPU, memory and disk usage information. + +### isRunning() + +```ts +isRunning(opts?: Pick): Promise +``` + +Check if the sandbox is running. + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `opts`? | `Pick`\<`ConnectionOpts`, `"requestTimeoutMs"`\> | + +###### Returns + +`Promise`\<`boolean`\> + +`true` if the sandbox is running, `false` otherwise. + +###### Example + +```ts +const sandbox = await Sandbox.create() +await sandbox.isRunning() // Returns true + +await sandbox.kill() +await sandbox.isRunning() // Returns false +``` + +### kill() + +```ts +kill(opts?: Pick): Promise +``` + +Kill the sandbox. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `opts`? | `Pick`\<`SandboxOpts`, `"requestTimeoutMs"`\> | connection options. | + +###### Returns + +`Promise`\<`void`\> + +### setTimeout() + +```ts +setTimeout(timeoutMs: number, opts?: Pick): Promise +``` + +Set the timeout of the sandbox. +After the timeout expires the sandbox will be automatically killed. + +This method can extend or reduce the sandbox timeout set when creating the sandbox or from the last call to `.setTimeout`. +Maximum time a sandbox can be kept alive is 24 hours (86_400_000 milliseconds) for Pro users and 1 hour (3_600_000 milliseconds) for Hobby users. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `timeoutMs` | `number` | timeout in **milliseconds**. | +| `opts`? | `Pick`\<`SandboxOpts`, `"requestTimeoutMs"`\> | connection options. | + +###### Returns + +`Promise`\<`void`\> + +### uploadUrl() + +```ts +uploadUrl(path?: string, opts?: SandboxUrlOpts): Promise +``` + +Get the URL to upload a file to the sandbox. + +You have to send a POST request to this URL with the file as multipart/form-data. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `path`? | `string` | path to the file in the sandbox. | +| `opts`? | `SandboxUrlOpts` | download url options. | + +###### Returns + +`Promise`\<`string`\> + +URL for uploading file. + +### betaCreate() + +###### betaCreate(this, opts) + +```ts +static betaCreate(this: S, opts?: SandboxBetaCreateOpts): Promise> +``` + +**`Beta`** + +This feature is in beta and may change in the future. + +Create a new sandbox from the default `base` sandbox template. + +###### Type Parameters + +| Type Parameter | +| ------ | +| `S` *extends* *typeof* `Sandbox` | + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `this` | `S` | - | +| `opts`? | `SandboxBetaCreateOpts` | connection options. | + +###### Returns + +`Promise`\<`InstanceType`\<`S`\>\> + +sandbox instance for the new sandbox. + +###### Example + +```ts +const sandbox = await Sandbox.betaCreate() +``` + +###### Constructs + +Sandbox + +###### betaCreate(this, template, opts) + +```ts +static betaCreate( + this: S, + template: string, +opts?: SandboxBetaCreateOpts): Promise> +``` + +**`Beta`** + +This feature is in beta and may change in the future. + +Create a new sandbox from the specified sandbox template. + +###### Type Parameters + +| Type Parameter | +| ------ | +| `S` *extends* *typeof* `Sandbox` | + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `this` | `S` | - | +| `template` | `string` | sandbox template name or ID. | +| `opts`? | `SandboxBetaCreateOpts` | connection options. | + +###### Returns + +`Promise`\<`InstanceType`\<`S`\>\> + +sandbox instance for the new sandbox. + +###### Example + +```ts +const sandbox = await Sandbox.betaCreate('') +``` + +###### Constructs + +Sandbox + +### betaPause() + +```ts +static betaPause(sandboxId: string, opts?: SandboxApiOpts): Promise +``` + +Pause the sandbox specified by sandbox ID. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `sandboxId` | `string` | sandbox ID. | +| `opts`? | `SandboxApiOpts` | connection options. | + +###### Returns + +`Promise`\<`boolean`\> + +`true` if the sandbox got paused, `false` if the sandbox was already paused. + +### connect() + +```ts +static connect( + this: S, + sandboxId: string, +opts?: SandboxConnectOpts): Promise> +``` + +Connect to a sandbox. If the sandbox is paused, it will be automatically resumed. +Sandbox must be either running or be paused. + +With sandbox ID you can connect to the same sandbox from different places or environments (serverless functions, etc). + +###### Type Parameters + +| Type Parameter | +| ------ | +| `S` *extends* *typeof* `Sandbox` | + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `this` | `S` | - | +| `sandboxId` | `string` | sandbox ID. | +| `opts`? | `SandboxConnectOpts` | connection options. | + +###### Returns + +`Promise`\<`InstanceType`\<`S`\>\> + +A running sandbox instance + +###### Example + +```ts +const sandbox = await Sandbox.create() +const sandboxId = sandbox.sandboxId + +// Connect to the same sandbox. +const sameSandbox = await Sandbox.connect(sandboxId) +``` + +### create() + +###### create(this, opts) + +```ts +static create(this: S, opts?: SandboxOpts): Promise> +``` + +Create a new sandbox from the default `base` sandbox template. + +###### Type Parameters + +| Type Parameter | +| ------ | +| `S` *extends* *typeof* `Sandbox` | + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `this` | `S` | - | +| `opts`? | `SandboxOpts` | connection options. | + +###### Returns + +`Promise`\<`InstanceType`\<`S`\>\> + +sandbox instance for the new sandbox. + +###### Example + +```ts +const sandbox = await Sandbox.create() +``` + +###### Constructs + +Sandbox + +###### create(this, template, opts) + +```ts +static create( + this: S, + template: string, +opts?: SandboxOpts): Promise> +``` + +Create a new sandbox from the specified sandbox template. + +###### Type Parameters + +| Type Parameter | +| ------ | +| `S` *extends* *typeof* `Sandbox` | + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `this` | `S` | - | +| `template` | `string` | sandbox template name or ID. | +| `opts`? | `SandboxOpts` | connection options. | + +###### Returns + +`Promise`\<`InstanceType`\<`S`\>\> + +sandbox instance for the new sandbox. + +###### Example + +```ts +const sandbox = await Sandbox.create('') +``` + +###### Constructs + +Sandbox + +### getFullInfo() + +```ts +static getFullInfo(sandboxId: string, opts?: SandboxApiOpts): Promise +``` + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `sandboxId` | `string` | +| `opts`? | `SandboxApiOpts` | + +###### Returns + +`Promise`\<`object`\> + +| Name | Type | Default value | +| ------ | ------ | ------ | +| `cpuCount` | `number` | res.data.cpuCount | +| `endAt` | `Date` | - | +| `envdAccessToken` | `undefined` \| `string` | res.data.envdAccessToken | +| `envdVersion` | `string` | res.data.envdVersion | +| `memoryMB` | `number` | res.data.memoryMB | +| `metadata` | `object` | - | +| `name`? | `string` | res.data.alias | +| `sandboxDomain` | `undefined` \| `string` | - | +| `sandboxId` | `string` | res.data.sandboxID | +| `startedAt` | `Date` | - | +| `state` | `"running"` \| `"paused"` | res.data.state | +| `templateId` | `string` | res.data.templateID | + +### getInfo() + +```ts +static getInfo(sandboxId: string, opts?: SandboxApiOpts): Promise +``` + +Get sandbox information like sandbox ID, template, metadata, started at/end at date. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `sandboxId` | `string` | sandbox ID. | +| `opts`? | `SandboxApiOpts` | connection options. | + +###### Returns + +`Promise`\<`SandboxInfo`\> + +sandbox information. + +### getMetrics() + +```ts +static getMetrics(sandboxId: string, opts?: SandboxMetricsOpts): Promise +``` + +Get the metrics of the sandbox. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `sandboxId` | `string` | sandbox ID. | +| `opts`? | `SandboxMetricsOpts` | sandbox metrics options. | + +###### Returns + +`Promise`\<`SandboxMetrics`[]\> + +List of sandbox metrics containing CPU, memory and disk usage information. + +### kill() + +```ts +static kill(sandboxId: string, opts?: SandboxApiOpts): Promise +``` + +Kill the sandbox specified by sandbox ID. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `sandboxId` | `string` | sandbox ID. | +| `opts`? | `SandboxApiOpts` | connection options. | + +###### Returns + +`Promise`\<`boolean`\> + +`true` if the sandbox was found and killed, `false` otherwise. + +### list() + +```ts +static list(opts?: SandboxListOpts): SandboxPaginator +``` + +List all sandboxes. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `opts`? | `SandboxListOpts` | connection options. | + +###### Returns + +`SandboxPaginator` + +paginator for listing sandboxes. + +### setTimeout() + +```ts +static setTimeout( + sandboxId: string, + timeoutMs: number, +opts?: SandboxApiOpts): Promise +``` + +Set the timeout of the specified sandbox. +After the timeout expires the sandbox will be automatically killed. + +This method can extend or reduce the sandbox timeout set when creating the sandbox or from the last call to Sandbox.setTimeout. + +Maximum time a sandbox can be kept alive is 24 hours (86_400_000 milliseconds) for Pro users and 1 hour (3_600_000 milliseconds) for Hobby users. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `sandboxId` | `string` | sandbox ID. | +| `timeoutMs` | `number` | timeout in **milliseconds**. | +| `opts`? | `SandboxApiOpts` | connection options. | + +###### Returns + +`Promise`\<`void`\> + +## Interfaces + +### SandboxUrlOpts + +Options for sandbox upload/download URL generation. + +#### Properties + +### user? + +```ts +optional user: string; +``` + +User that will be used to access the file. + +### useSignatureExpiration? + +```ts +optional useSignatureExpiration: number; +``` + +Use signature expiration for the URL. +Optional parameter to set the expiration time for the signature in seconds. diff --git a/docs/sdk-reference/js-sdk/v2.8.4/template-logger.mdx b/docs/sdk-reference/js-sdk/v2.8.4/template-logger.mdx new file mode 100644 index 0000000..fdebde3 --- /dev/null +++ b/docs/sdk-reference/js-sdk/v2.8.4/template-logger.mdx @@ -0,0 +1,196 @@ +--- +sidebarTitle: "Logger" +mode: "center" +--- + +### LogEntry + +Represents a single log entry from the template build process. + +#### Extended by + +- `LogEntryStart` +- `LogEntryEnd` + +#### Constructors + +```ts +new LogEntry( + timestamp: Date, + level: LogEntryLevel, + message: string): LogEntry +``` + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `timestamp` | `Date` | +| `level` | `LogEntryLevel` | +| `message` | `string` | + +###### Returns + +`LogEntry` + +#### Properties + +| Property | Modifier | Type | +| ------ | ------ | ------ | +| `level` | `readonly` | `LogEntryLevel` | +| `message` | `readonly` | `string` | +| `timestamp` | `readonly` | `Date` | + +#### Methods + +### toString() + +```ts +toString(): string +``` + +###### Returns + +`string` + +*** + +### LogEntryEnd + +Special log entry indicating the end of a build process. + +#### Constructors + +```ts +new LogEntryEnd(timestamp: Date, message: string): LogEntryEnd +``` + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `timestamp` | `Date` | +| `message` | `string` | + +###### Returns + +`LogEntryEnd` + +#### Properties + +| Property | Modifier | Type | Inherited from | +| ------ | ------ | ------ | ------ | +| `level` | `readonly` | `LogEntryLevel` | `LogEntry`.`level` | +| `message` | `readonly` | `string` | `LogEntry`.`message` | +| `timestamp` | `readonly` | `Date` | `LogEntry`.`timestamp` | + +#### Methods + +### toString() + +```ts +toString(): string +``` + +###### Returns + +`string` + +*** + +### LogEntryStart + +Special log entry indicating the start of a build process. + +#### Constructors + +```ts +new LogEntryStart(timestamp: Date, message: string): LogEntryStart +``` + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `timestamp` | `Date` | +| `message` | `string` | + +###### Returns + +`LogEntryStart` + +#### Properties + +| Property | Modifier | Type | Inherited from | +| ------ | ------ | ------ | ------ | +| `level` | `readonly` | `LogEntryLevel` | `LogEntry`.`level` | +| `message` | `readonly` | `string` | `LogEntry`.`message` | +| `timestamp` | `readonly` | `Date` | `LogEntry`.`timestamp` | + +#### Methods + +### toString() + +```ts +toString(): string +``` + +###### Returns + +`string` + +## Type Aliases + +### LogEntryLevel + +```ts +type LogEntryLevel: "debug" | "info" | "warn" | "error"; +``` + +Log entry severity levels. + +## Functions + +### defaultBuildLogger() + +```ts +function defaultBuildLogger(options?: object): (logEntry: LogEntry) => void +``` + +Create a default build logger with animated timer display. + +#### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `options`? | `object` | Logger configuration options | +| `options.minLevel`? | `LogEntryLevel` | Minimum log level to display (default: 'info') | + +#### Returns + +`Function` + +Logger function that accepts LogEntry instances + +### Parameters + +| Parameter | Type | +| ------ | ------ | +| `logEntry` | `LogEntry` | + +### Returns + +`void` + +#### Example + +```ts +import { Template, defaultBuildLogger } from 'e2b' + +const template = Template().fromPythonImage() + +await Template.build(template, { + alias: 'my-template', + onBuildLogs: defaultBuildLogger({ minLevel: 'debug' }) +}) +``` diff --git a/docs/sdk-reference/js-sdk/v2.8.4/template-readycmd.mdx b/docs/sdk-reference/js-sdk/v2.8.4/template-readycmd.mdx new file mode 100644 index 0000000..56fb0b7 --- /dev/null +++ b/docs/sdk-reference/js-sdk/v2.8.4/template-readycmd.mdx @@ -0,0 +1,202 @@ +--- +sidebarTitle: "Readycmd" +mode: "center" +--- + +### ReadyCmd + +Class for ready check commands. + +#### Constructors + +```ts +new ReadyCmd(cmd: string): ReadyCmd +``` + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `cmd` | `string` | + +###### Returns + +`ReadyCmd` + +#### Methods + +### getCmd() + +```ts +getCmd(): string +``` + +###### Returns + +`string` + +## Functions + +### waitForFile() + +```ts +function waitForFile(filename: string): ReadyCmd +``` + +Wait for a file to exist. +Uses shell test command to check file existence. + +#### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `filename` | `string` | Path to the file to wait for | + +#### Returns + +`ReadyCmd` + +ReadyCmd that checks for the file + +#### Example + +```ts +import { Template, waitForFile } from 'e2b' + +const template = Template() + .fromBaseImage() + .setStartCmd('./init.sh', waitForFile('/tmp/ready')) +``` + +*** + +### waitForPort() + +```ts +function waitForPort(port: number): ReadyCmd +``` + +Wait for a port to be listening. +Uses `ss` command to check if a port is open and listening. + +#### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `port` | `number` | Port number to wait for | + +#### Returns + +`ReadyCmd` + +ReadyCmd that checks for the port + +#### Example + +```ts +import { Template, waitForPort } from 'e2b' + +const template = Template() + .fromPythonImage() + .setStartCmd('python -m http.server 8000', waitForPort(8000)) +``` + +*** + +### waitForProcess() + +```ts +function waitForProcess(processName: string): ReadyCmd +``` + +Wait for a process with a specific name to be running. +Uses `pgrep` to check if a process exists. + +#### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `processName` | `string` | Name of the process to wait for | + +#### Returns + +`ReadyCmd` + +ReadyCmd that checks for the process + +#### Example + +```ts +import { Template, waitForProcess } from 'e2b' + +const template = Template() + .fromBaseImage() + .setStartCmd('./my-daemon', waitForProcess('my-daemon')) +``` + +*** + +### waitForTimeout() + +```ts +function waitForTimeout(timeout: number): ReadyCmd +``` + +Wait for a specified timeout before considering the sandbox ready. +Uses `sleep` command to wait for a fixed duration. + +#### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `timeout` | `number` | Time to wait in milliseconds (minimum: 1000ms / 1 second) | + +#### Returns + +`ReadyCmd` + +ReadyCmd that waits for the specified duration + +#### Example + +```ts +import { Template, waitForTimeout } from 'e2b' + +const template = Template() + .fromNodeImage() + .setStartCmd('npm start', waitForTimeout(5000)) // Wait 5 seconds +``` + +*** + +### waitForURL() + +```ts +function waitForURL(url: string, statusCode: number): ReadyCmd +``` + +Wait for a URL to return a specific HTTP status code. +Uses `curl` to make HTTP requests and check the response status. + +#### Parameters + +| Parameter | Type | Default value | Description | +| ------ | ------ | ------ | ------ | +| `url` | `string` | `undefined` | URL to check (e.g., 'http://localhost:3000/health') | +| `statusCode` | `number` | `200` | Expected HTTP status code (default: 200) | + +#### Returns + +`ReadyCmd` + +ReadyCmd that checks the URL + +#### Example + +```ts +import { Template, waitForURL } from 'e2b' + +const template = Template() + .fromNodeImage() + .setStartCmd('npm start', waitForURL('http://localhost:3000/health')) +``` diff --git a/docs/sdk-reference/js-sdk/v2.8.4/template.mdx b/docs/sdk-reference/js-sdk/v2.8.4/template.mdx new file mode 100644 index 0000000..c644e02 --- /dev/null +++ b/docs/sdk-reference/js-sdk/v2.8.4/template.mdx @@ -0,0 +1,2042 @@ +--- +sidebarTitle: "Template" +mode: "center" +--- + +### TemplateBase + +Base class for building E2B sandbox templates. + +#### Implements + +- `TemplateFromImage` +- `TemplateBuilder` +- `TemplateFinal` + +#### Constructors + +```ts +new TemplateBase(options?: TemplateOptions): TemplateBase +``` + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `options`? | `TemplateOptions` | + +###### Returns + +`TemplateBase` + +#### Methods + +### addMcpServer() + +```ts +addMcpServer(servers: keyof McpServer | keyof McpServer[]): TemplateBuilder +``` + +Install MCP servers using mcp-gateway. +Note: Requires a base image with mcp-gateway pre-installed (e.g., mcp-gateway). + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `servers` | keyof McpServer \| keyof McpServer[] | MCP server name(s) | + +###### Returns + +`TemplateBuilder` + +###### Throws + +If the base template is not mcp-gateway + +###### Example + +```ts +template.addMcpServer('exa') +template.addMcpServer(['brave', 'firecrawl', 'duckduckgo']) +``` + +###### Implementation of + +`TemplateBuilder`.`addMcpServer` + +### aptInstall() + +```ts +aptInstall(packages: string | string[], options?: object): TemplateBuilder +``` + +Install Debian/Ubuntu packages using apt-get. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `packages` | `string` \| `string`[] | Package name(s) | +| `options`? | `object` | - | +| `options.noInstallRecommends`? | `boolean` | - | + +###### Returns + +`TemplateBuilder` + +###### Example + +```ts +template.aptInstall('vim') +template.aptInstall(['git', 'curl', 'wget']) +template.aptInstall(['vim'], { noInstallRecommends: true }) +``` + +###### Implementation of + +`TemplateBuilder`.`aptInstall` + +### betaDevContainerPrebuild() + +```ts +betaDevContainerPrebuild(devcontainerDirectory: string): TemplateBuilder +``` + +Prebuild a devcontainer from the specified directory. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `devcontainerDirectory` | `string` | Path to the devcontainer directory | + +###### Returns + +`TemplateBuilder` + +###### Example + +```ts +template + .gitClone('https://myrepo.com/project.git', '/my-devcontainer') + .betaDevContainerPrebuild('/my-devcontainer') +``` + +###### Implementation of + +`TemplateBuilder`.`betaDevContainerPrebuild` + +### betaSetDevContainerStart() + +```ts +betaSetDevContainerStart(devcontainerDirectory: string): TemplateFinal +``` + +Start a devcontainer from the specified directory. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `devcontainerDirectory` | `string` | Path to the devcontainer directory | + +###### Returns + +`TemplateFinal` + +###### Example + +```ts +template + .gitClone('https://myrepo.com/project.git', '/my-devcontainer') + .startDevcontainer('/my-devcontainer') + +// Prebuild and start +template + .gitClone('https://myrepo.com/project.git', '/my-devcontainer') + .betaDevContainerPrebuild('/my-devcontainer') + // Other instructions... + .betaSetDevContainerStart('/my-devcontainer') +``` + +###### Implementation of + +`TemplateBuilder`.`betaSetDevContainerStart` + +### bunInstall() + +```ts +bunInstall(packages?: string | string[], options?: object): TemplateBuilder +``` + +Install Bun packages using bun. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `packages`? | `string` \| `string`[] | Package name(s) or undefined for package.json | +| `options`? | `object` | Install options | +| `options.dev`? | `boolean` | - | +| `options.g`? | `boolean` | - | + +###### Returns + +`TemplateBuilder` + +###### Example + +```ts +template.bunInstall('express') +template.bunInstall(['lodash', 'axios']) +template.bunInstall('tsx', { g: true }) +template.bunInstall('typescript', { dev: true }) +template.bunInstall() // Installs from package.json +``` + +###### Implementation of + +`TemplateBuilder`.`bunInstall` + +### copy() + +```ts +copy( + src: PathLike | PathLike[], + dest: PathLike, + options?: object): TemplateBuilder +``` + +Copy files or directories into the template. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `src` | `PathLike` \| `PathLike`[] | Source path(s) | +| `dest` | `PathLike` | Destination path | +| `options`? | `object` | Copy options | +| `options.forceUpload`? | `true` | - | +| `options.mode`? | `number` | - | +| `options.resolveSymlinks`? | `boolean` | - | +| `options.user`? | `string` | - | + +###### Returns + +`TemplateBuilder` + +###### Example + +```ts +template.copy('requirements.txt', '/home/user/') +template.copy(['app.ts', 'config.ts'], '/app/', { mode: 0o755 }) +``` + +###### Implementation of + +`TemplateBuilder`.`copy` + +### copyItems() + +```ts +copyItems(items: CopyItem[]): TemplateBuilder +``` + +Copy multiple items with individual options. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `items` | `CopyItem`[] | Array of copy items | + +###### Returns + +`TemplateBuilder` + +###### Example + +```ts +template.copyItems([ + { src: 'app.ts', dest: '/app/' }, + { src: 'config.ts', dest: '/app/', mode: 0o644 } +]) +``` + +###### Implementation of + +`TemplateBuilder`.`copyItems` + +### fromAWSRegistry() + +```ts +fromAWSRegistry(image: string, credentials: object): TemplateBuilder +``` + +Start from a Docker image in AWS ECR. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `image` | `string` | Full ECR image path | +| `credentials` | `object` | AWS credentials | +| `credentials.accessKeyId` | `string` | - | +| `credentials.region` | `string` | - | +| `credentials.secretAccessKey` | `string` | - | + +###### Returns + +`TemplateBuilder` + +###### Example + +```ts +Template().fromAWSRegistry( + '123456789.dkr.ecr.us-west-2.amazonaws.com/myimage:latest', + { + accessKeyId: 'AKIA...', + secretAccessKey: '...', + region: 'us-west-2' + } +) +``` + +###### Implementation of + +`TemplateFromImage.fromAWSRegistry` + +### fromBaseImage() + +```ts +fromBaseImage(): TemplateBuilder +``` + +Start from E2B's default base image (e2bdev/base:latest). + +###### Returns + +`TemplateBuilder` + +###### Example + +```ts +Template().fromBaseImage() +``` + +###### Implementation of + +`TemplateFromImage.fromBaseImage` + +### fromBunImage() + +```ts +fromBunImage(variant: string): TemplateBuilder +``` + +Start from a Bun-based Docker image. + +###### Parameters + +| Parameter | Type | Default value | Description | +| ------ | ------ | ------ | ------ | +| `variant` | `string` | `'latest'` | Bun variant (default: 'latest') | + +###### Returns + +`TemplateBuilder` + +###### Example + +```ts +Template().fromBunImage('1.3') +``` + +###### Implementation of + +`TemplateFromImage.fromBunImage` + +### fromDebianImage() + +```ts +fromDebianImage(variant: string): TemplateBuilder +``` + +Start from a Debian-based Docker image. + +###### Parameters + +| Parameter | Type | Default value | Description | +| ------ | ------ | ------ | ------ | +| `variant` | `string` | `'stable'` | Debian variant (default: 'stable') | + +###### Returns + +`TemplateBuilder` + +###### Example + +```ts +Template().fromDebianImage('bookworm') +``` + +###### Implementation of + +`TemplateFromImage.fromDebianImage` + +### fromDockerfile() + +```ts +fromDockerfile(dockerfileContentOrPath: string): TemplateBuilder +``` + +Parse a Dockerfile and convert it to Template SDK format. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `dockerfileContentOrPath` | `string` | Dockerfile content or path | + +###### Returns + +`TemplateBuilder` + +###### Example + +```ts +Template().fromDockerfile('Dockerfile') +Template().fromDockerfile('FROM python:3\nRUN pip install numpy') +``` + +###### Implementation of + +`TemplateFromImage.fromDockerfile` + +### fromGCPRegistry() + +```ts +fromGCPRegistry(image: string, credentials: object): TemplateBuilder +``` + +Start from a Docker image in Google Container Registry. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `image` | `string` | Full GCR/GAR image path | +| `credentials` | `object` | GCP service account credentials | +| `credentials.serviceAccountJSON` | `string` \| `object` | - | + +###### Returns + +`TemplateBuilder` + +###### Example + +```ts +Template().fromGCPRegistry( + 'gcr.io/myproject/myimage:latest', + { serviceAccountJSON: 'path/to/service-account.json' } +) +``` + +###### Implementation of + +`TemplateFromImage.fromGCPRegistry` + +### fromImage() + +```ts +fromImage(baseImage: string, credentials?: object): TemplateBuilder +``` + +Start from a custom Docker image. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `baseImage` | `string` | Docker image name | +| `credentials`? | `object` | Optional credentials for private registries | +| `credentials.password`? | `string` | - | +| `credentials.username`? | `string` | - | + +###### Returns + +`TemplateBuilder` + +###### Example + +```ts +Template().fromImage('python:3') + +// With credentials (optional) +Template().fromImage('myregistry.com/myimage:latest', { + username: 'user', + password: 'pass' +}) +``` + +###### Implementation of + +`TemplateFromImage.fromImage` + +### fromNodeImage() + +```ts +fromNodeImage(variant: string): TemplateBuilder +``` + +Start from a Node.js-based Docker image. + +###### Parameters + +| Parameter | Type | Default value | Description | +| ------ | ------ | ------ | ------ | +| `variant` | `string` | `'lts'` | Node.js variant (default: 'lts') | + +###### Returns + +`TemplateBuilder` + +###### Example + +```ts +Template().fromNodeImage('24') +``` + +###### Implementation of + +`TemplateFromImage.fromNodeImage` + +### fromPythonImage() + +```ts +fromPythonImage(version: string): TemplateBuilder +``` + +Start from a Python-based Docker image. + +###### Parameters + +| Parameter | Type | Default value | Description | +| ------ | ------ | ------ | ------ | +| `version` | `string` | `'3'` | Python version (default: '3') | + +###### Returns + +`TemplateBuilder` + +###### Example + +```ts +Template().fromPythonImage('3') +``` + +###### Implementation of + +`TemplateFromImage.fromPythonImage` + +### fromTemplate() + +```ts +fromTemplate(template: string): TemplateBuilder +``` + +Start from an existing E2B template. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `template` | `string` | E2B template ID or alias | + +###### Returns + +`TemplateBuilder` + +###### Example + +```ts +Template().fromTemplate('my-base-template') +``` + +###### Implementation of + +`TemplateFromImage.fromTemplate` + +### fromUbuntuImage() + +```ts +fromUbuntuImage(variant: string): TemplateBuilder +``` + +Start from an Ubuntu-based Docker image. + +###### Parameters + +| Parameter | Type | Default value | Description | +| ------ | ------ | ------ | ------ | +| `variant` | `string` | `'latest'` | Ubuntu variant (default: 'latest') | + +###### Returns + +`TemplateBuilder` + +###### Example + +```ts +Template().fromUbuntuImage('24.04') +``` + +###### Implementation of + +`TemplateFromImage.fromUbuntuImage` + +### gitClone() + +```ts +gitClone( + url: string, + path?: PathLike, + options?: object): TemplateBuilder +``` + +Clone a Git repository. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `url` | `string` | Repository URL | +| `path`? | `PathLike` | Optional destination path | +| `options`? | `object` | Clone options | +| `options.branch`? | `string` | - | +| `options.depth`? | `number` | - | +| `options.user`? | `string` | - | + +###### Returns + +`TemplateBuilder` + +###### Example + +```ts +template.gitClone('https://github.com/user/repo.git', '/app/repo') +template.gitClone('https://github.com/user/repo.git', undefined, { + branch: 'main', + depth: 1 +}) +template.gitClone('https://github.com/user/repo.git', '/app/repo', { + user: 'root' +}) +``` + +###### Implementation of + +`TemplateBuilder`.`gitClone` + +### makeDir() + +```ts +makeDir(path: PathLike | PathLike[], options?: object): TemplateBuilder +``` + +Create directories. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `path` | `PathLike` \| `PathLike`[] | Directory path(s) | +| `options`? | `object` | Directory options | +| `options.mode`? | `number` | - | +| `options.user`? | `string` | - | + +###### Returns + +`TemplateBuilder` + +###### Example + +```ts +template.makeDir('/app/data', { mode: 0o755 }) +template.makeDir(['/app/logs', '/app/cache']) +template.makeDir('/app/data', { mode: 0o755, user: 'root' }) +``` + +###### Implementation of + +`TemplateBuilder`.`makeDir` + +### makeSymlink() + +```ts +makeSymlink( + src: PathLike, + dest: PathLike, + options?: object): TemplateBuilder +``` + +Create a symbolic link. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `src` | `PathLike` | Source path (target) | +| `dest` | `PathLike` | Destination path (symlink location) | +| `options`? | `object` | Symlink options | +| `options.force`? | `boolean` | - | +| `options.user`? | `string` | - | + +###### Returns + +`TemplateBuilder` + +###### Example + +```ts +template.makeSymlink('/usr/bin/python3', '/usr/bin/python') +template.makeSymlink('/usr/bin/python3', '/usr/bin/python', { user: 'root' }) +template.makeSymlink('/usr/bin/python3', '/usr/bin/python', { force: true }) +``` + +###### Implementation of + +`TemplateBuilder`.`makeSymlink` + +### npmInstall() + +```ts +npmInstall(packages?: string | string[], options?: object): TemplateBuilder +``` + +Install Node.js packages using npm. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `packages`? | `string` \| `string`[] | Package name(s) or undefined for package.json | +| `options`? | `object` | Install options | +| `options.dev`? | `boolean` | - | +| `options.g`? | `boolean` | - | + +###### Returns + +`TemplateBuilder` + +###### Example + +```ts +template.npmInstall('express') +template.npmInstall(['lodash', 'axios']) +template.npmInstall('tsx', { g: true }) +template.npmInstall('typescript', { dev: true }) +template.npmInstall() // Installs from package.json +``` + +###### Implementation of + +`TemplateBuilder`.`npmInstall` + +### pipInstall() + +```ts +pipInstall(packages?: string | string[], options?: object): TemplateBuilder +``` + +Install Python packages using pip. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `packages`? | `string` \| `string`[] | Package name(s) or undefined for current directory | +| `options`? | `object` | Install options | +| `options.g`? | `boolean` | Install globally as root (default: true). Set to false for user-only installation with --user flag | + +###### Returns + +`TemplateBuilder` + +###### Example + +```ts +template.pipInstall('numpy') // Installs globally (default) +template.pipInstall(['pandas', 'scikit-learn']) +template.pipInstall('numpy', { g: false }) // Install for user only +template.pipInstall() // Installs from current directory +``` + +###### Implementation of + +`TemplateBuilder`.`pipInstall` + +### remove() + +```ts +remove(path: PathLike | PathLike[], options?: object): TemplateBuilder +``` + +Remove files or directories. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `path` | `PathLike` \| `PathLike`[] | Path(s) to remove | +| `options`? | `object` | Remove options | +| `options.force`? | `boolean` | - | +| `options.recursive`? | `boolean` | - | +| `options.user`? | `string` | - | + +###### Returns + +`TemplateBuilder` + +###### Example + +```ts +template.remove('/tmp/cache', { recursive: true, force: true }) +template.remove('/tmp/cache', { recursive: true, force: true, user: 'root' }) +``` + +###### Implementation of + +`TemplateBuilder`.`remove` + +### rename() + +```ts +rename( + src: PathLike, + dest: PathLike, + options?: object): TemplateBuilder +``` + +Rename or move a file or directory. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `src` | `PathLike` | Source path | +| `dest` | `PathLike` | Destination path | +| `options`? | `object` | Rename options | +| `options.force`? | `boolean` | - | +| `options.user`? | `string` | - | + +###### Returns + +`TemplateBuilder` + +###### Example + +```ts +template.rename('/tmp/old.txt', '/tmp/new.txt') +template.rename('/tmp/old.txt', '/tmp/new.txt', { user: 'root' }) +``` + +###### Implementation of + +`TemplateBuilder`.`rename` + +### runCmd() + +###### runCmd(command, options) + +```ts +runCmd(command: string, options?: object): TemplateBuilder +``` + +Run a shell command. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `command` | `string` | Command string | +| `options`? | `object` | Command options | +| `options.user`? | `string` | - | + +###### Returns + +`TemplateBuilder` + +###### Example + +```ts +template.runCmd('apt-get update') +template.runCmd(['pip install numpy', 'pip install pandas']) +template.runCmd('apt-get install vim', { user: 'root' }) +``` + +###### Implementation of + +`TemplateBuilder`.`runCmd` + +###### runCmd(commands, options) + +```ts +runCmd(commands: string[], options?: object): TemplateBuilder +``` + +Run a shell command. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `commands` | `string`[] | - | +| `options`? | `object` | Command options | +| `options.user`? | `string` | - | + +###### Returns + +`TemplateBuilder` + +###### Example + +```ts +template.runCmd('apt-get update') +template.runCmd(['pip install numpy', 'pip install pandas']) +template.runCmd('apt-get install vim', { user: 'root' }) +``` + +###### Implementation of + +`TemplateBuilder`.`runCmd` + +### setEnvs() + +```ts +setEnvs(envs: Record): TemplateBuilder +``` + +Set environment variables. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `envs` | `Record`\<`string`, `string`\> | Environment variables | + +###### Returns + +`TemplateBuilder` + +###### Example + +```ts +template.setEnvs({ NODE_ENV: 'production', PORT: '8080' }) +``` + +###### Implementation of + +`TemplateBuilder`.`setEnvs` + +### setReadyCmd() + +```ts +setReadyCmd(readyCommand: string | ReadyCmd): TemplateFinal +``` + +Set or update the ready check command. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `readyCommand` | `string` \| `ReadyCmd` | Command to check readiness | + +###### Returns + +`TemplateFinal` + +###### Example + +```ts +// Using a string command +template.setReadyCmd('curl http://localhost:8000/health') + +// Using ReadyCmd helpers +import { waitForPort, waitForFile, waitForProcess } from 'e2b' + +template.setReadyCmd(waitForPort(3000)) + +template.setReadyCmd(waitForFile('/tmp/ready')) + +template.setReadyCmd(waitForProcess('nginx')) +``` + +###### Implementation of + +`TemplateBuilder`.`setReadyCmd` + +### setStartCmd() + +```ts +setStartCmd(startCommand: string, readyCommand: string | ReadyCmd): TemplateFinal +``` + +Set the start command and ready check. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `startCommand` | `string` | Command to run on startup | +| `readyCommand` | `string` \| `ReadyCmd` | Command to check readiness | + +###### Returns + +`TemplateFinal` + +###### Example + +```ts +// Using a string command +template.setStartCmd( + 'node app.js', + 'curl http://localhost:8000/health' +) + +// Using ReadyCmd helpers +import { waitForPort, waitForURL } from 'e2b' + +template.setStartCmd( + 'python -m http.server 8000', + waitForPort(8000) +) + +template.setStartCmd( + 'npm start', + waitForURL('http://localhost:3000/health', 200) +) +``` + +###### Implementation of + +`TemplateBuilder`.`setStartCmd` + +### setUser() + +```ts +setUser(user: string): TemplateBuilder +``` + +Set the user for subsequent commands. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `user` | `string` | Username | + +###### Returns + +`TemplateBuilder` + +###### Example + +```ts +template.setUser('root') +``` + +###### Implementation of + +`TemplateBuilder`.`setUser` + +### setWorkdir() + +```ts +setWorkdir(workdir: PathLike): TemplateBuilder +``` + +Set the working directory. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `workdir` | `PathLike` | Working directory path | + +###### Returns + +`TemplateBuilder` + +###### Example + +```ts +template.setWorkdir('/app') +``` + +###### Implementation of + +`TemplateBuilder`.`setWorkdir` + +### skipCache() + +```ts +skipCache(): this +``` + +Skip cache for all subsequent build instructions from this point. + +###### Returns + +`this` + +###### Example + +```ts +Template().skipCache().fromPythonImage('3') +``` + +###### Implementation of + +`TemplateBuilder`.`skipCache` + +### build() + +```ts +static build(template: TemplateClass, options: BuildOptions): Promise +``` + +Build and deploy a template to E2B infrastructure. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `template` | `TemplateClass` | The template to build | +| `options` | `BuildOptions` | Build configuration options | + +###### Returns + +`Promise`\<`BuildInfo`\> + +###### Example + +```ts +const template = Template().fromPythonImage('3') +await Template.build(template, { + alias: 'my-python-env', + cpuCount: 2, + memoryMB: 1024 +}) +``` + +### buildInBackground() + +```ts +static buildInBackground(template: TemplateClass, options: BuildOptions): Promise +``` + +Build and deploy a template to E2B infrastructure. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `template` | `TemplateClass` | The template to build | +| `options` | `BuildOptions` | Build configuration options | + +###### Returns + +`Promise`\<`BuildInfo`\> + +###### Example + +```ts +const template = Template().fromPythonImage('3') +const data = await Template.buildInBackground(template, { + alias: 'my-python-env', + cpuCount: 2, + memoryMB: 1024 +}) +``` + +### getBuildStatus() + +```ts +static getBuildStatus(data: Pick, options?: GetBuildStatusOptions): Promise +``` + +Get the status of a build. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `data` | `Pick`\<`BuildInfo`, `"templateId"` \| `"buildId"`\> | Build identifiers | +| `options`? | `GetBuildStatusOptions` | Authentication options | + +###### Returns + +`Promise`\<`object`\> + +| Name | Type | Description | +| ------ | ------ | ------ | +| `buildID` | `string` | **Description** Identifier of the build | +| `logEntries` | `object`[] | **Description** Build logs structured **Default** `[]` | +| `logs` | `string`[] | **Description** Build logs **Default** `[]` | +| `reason`? | `object` | - | +| `reason.logEntries`? | `object`[] | **Description** Log entries related to the status reason **Default** `[]` | +| `reason.message` | `string` | **Description** Message with the status reason, currently reporting only for error status | +| `reason.step`? | `string` | **Description** Step that failed | +| `status` | `"error"` \| `"ready"` \| `"building"` \| `"waiting"` | - | +| `templateID` | `string` | **Description** Identifier of the template | + +###### Example + +```ts +const status = await Template.getBuildStatus(data, { logsOffset: 0 }) +``` + +### toDockerfile() + +```ts +static toDockerfile(template: TemplateClass): string +``` + +Convert a template to Dockerfile format. +Note: Templates based on other E2B templates cannot be converted to Dockerfile. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `template` | `TemplateClass` | The template to convert | + +###### Returns + +`string` + +Dockerfile string representation + +###### Throws + +Error if the template is based on another E2B template + +### toJSON() + +```ts +static toJSON(template: TemplateClass, computeHashes: boolean): Promise +``` + +Convert a template to JSON representation. + +###### Parameters + +| Parameter | Type | Default value | Description | +| ------ | ------ | ------ | ------ | +| `template` | `TemplateClass` | `undefined` | The template to convert | +| `computeHashes` | `boolean` | `true` | Whether to compute file hashes for cache invalidation | + +###### Returns + +`Promise`\<`string`\> + +JSON string representation of the template + +## Interfaces + +### TemplateBuilder + +Main builder state for constructing templates. +Provides methods for customizing the template environment. + +#### Methods + +### addMcpServer() + +```ts +addMcpServer(servers: keyof McpServer | keyof McpServer[]): TemplateBuilder +``` + +Install MCP servers using mcp-gateway. +Note: Requires a base image with mcp-gateway pre-installed (e.g., mcp-gateway). + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `servers` | keyof McpServer \| keyof McpServer[] | MCP server name(s) | + +###### Returns + +`TemplateBuilder` + +###### Throws + +If the base template is not mcp-gateway + +###### Example + +```ts +template.addMcpServer('exa') +template.addMcpServer(['brave', 'firecrawl', 'duckduckgo']) +``` + +### aptInstall() + +```ts +aptInstall(packages: string | string[], options?: object): TemplateBuilder +``` + +Install Debian/Ubuntu packages using apt-get. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `packages` | `string` \| `string`[] | Package name(s) | +| `options`? | `object` | - | +| `options.noInstallRecommends`? | `boolean` | - | + +###### Returns + +`TemplateBuilder` + +###### Example + +```ts +template.aptInstall('vim') +template.aptInstall(['git', 'curl', 'wget']) +template.aptInstall(['vim'], { noInstallRecommends: true }) +``` + +### betaDevContainerPrebuild() + +```ts +betaDevContainerPrebuild(devcontainerDirectory: string): TemplateBuilder +``` + +Prebuild a devcontainer from the specified directory. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `devcontainerDirectory` | `string` | Path to the devcontainer directory | + +###### Returns + +`TemplateBuilder` + +###### Example + +```ts +template + .gitClone('https://myrepo.com/project.git', '/my-devcontainer') + .betaDevContainerPrebuild('/my-devcontainer') +``` + +### betaSetDevContainerStart() + +```ts +betaSetDevContainerStart(devcontainerDirectory: string): TemplateFinal +``` + +Start a devcontainer from the specified directory. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `devcontainerDirectory` | `string` | Path to the devcontainer directory | + +###### Returns + +`TemplateFinal` + +###### Example + +```ts +template + .gitClone('https://myrepo.com/project.git', '/my-devcontainer') + .startDevcontainer('/my-devcontainer') + +// Prebuild and start +template + .gitClone('https://myrepo.com/project.git', '/my-devcontainer') + .betaDevContainerPrebuild('/my-devcontainer') + // Other instructions... + .betaSetDevContainerStart('/my-devcontainer') +``` + +### bunInstall() + +```ts +bunInstall(packages?: string | string[], options?: object): TemplateBuilder +``` + +Install Bun packages using bun. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `packages`? | `string` \| `string`[] | Package name(s) or undefined for package.json | +| `options`? | `object` | Install options | +| `options.dev`? | `boolean` | - | +| `options.g`? | `boolean` | - | + +###### Returns + +`TemplateBuilder` + +###### Example + +```ts +template.bunInstall('express') +template.bunInstall(['lodash', 'axios']) +template.bunInstall('tsx', { g: true }) +template.bunInstall('typescript', { dev: true }) +template.bunInstall() // Installs from package.json +``` + +### copy() + +```ts +copy( + src: PathLike | PathLike[], + dest: PathLike, + options?: object): TemplateBuilder +``` + +Copy files or directories into the template. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `src` | `PathLike` \| `PathLike`[] | Source path(s) | +| `dest` | `PathLike` | Destination path | +| `options`? | `object` | Copy options | +| `options.forceUpload`? | `true` | - | +| `options.mode`? | `number` | - | +| `options.resolveSymlinks`? | `boolean` | - | +| `options.user`? | `string` | - | + +###### Returns + +`TemplateBuilder` + +###### Example + +```ts +template.copy('requirements.txt', '/home/user/') +template.copy(['app.ts', 'config.ts'], '/app/', { mode: 0o755 }) +``` + +### copyItems() + +```ts +copyItems(items: CopyItem[]): TemplateBuilder +``` + +Copy multiple items with individual options. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `items` | `CopyItem`[] | Array of copy items | + +###### Returns + +`TemplateBuilder` + +###### Example + +```ts +template.copyItems([ + { src: 'app.ts', dest: '/app/' }, + { src: 'config.ts', dest: '/app/', mode: 0o644 } +]) +``` + +### gitClone() + +```ts +gitClone( + url: string, + path?: PathLike, + options?: object): TemplateBuilder +``` + +Clone a Git repository. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `url` | `string` | Repository URL | +| `path`? | `PathLike` | Optional destination path | +| `options`? | `object` | Clone options | +| `options.branch`? | `string` | - | +| `options.depth`? | `number` | - | +| `options.user`? | `string` | - | + +###### Returns + +`TemplateBuilder` + +###### Example + +```ts +template.gitClone('https://github.com/user/repo.git', '/app/repo') +template.gitClone('https://github.com/user/repo.git', undefined, { + branch: 'main', + depth: 1 +}) +template.gitClone('https://github.com/user/repo.git', '/app/repo', { + user: 'root' +}) +``` + +### makeDir() + +```ts +makeDir(path: PathLike | PathLike[], options?: object): TemplateBuilder +``` + +Create directories. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `path` | `PathLike` \| `PathLike`[] | Directory path(s) | +| `options`? | `object` | Directory options | +| `options.mode`? | `number` | - | +| `options.user`? | `string` | - | + +###### Returns + +`TemplateBuilder` + +###### Example + +```ts +template.makeDir('/app/data', { mode: 0o755 }) +template.makeDir(['/app/logs', '/app/cache']) +template.makeDir('/app/data', { mode: 0o755, user: 'root' }) +``` + +### makeSymlink() + +```ts +makeSymlink( + src: PathLike, + dest: PathLike, + options?: object): TemplateBuilder +``` + +Create a symbolic link. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `src` | `PathLike` | Source path (target) | +| `dest` | `PathLike` | Destination path (symlink location) | +| `options`? | `object` | Symlink options | +| `options.force`? | `boolean` | - | +| `options.user`? | `string` | - | + +###### Returns + +`TemplateBuilder` + +###### Example + +```ts +template.makeSymlink('/usr/bin/python3', '/usr/bin/python') +template.makeSymlink('/usr/bin/python3', '/usr/bin/python', { user: 'root' }) +template.makeSymlink('/usr/bin/python3', '/usr/bin/python', { force: true }) +``` + +### npmInstall() + +```ts +npmInstall(packages?: string | string[], options?: object): TemplateBuilder +``` + +Install Node.js packages using npm. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `packages`? | `string` \| `string`[] | Package name(s) or undefined for package.json | +| `options`? | `object` | Install options | +| `options.dev`? | `boolean` | - | +| `options.g`? | `boolean` | - | + +###### Returns + +`TemplateBuilder` + +###### Example + +```ts +template.npmInstall('express') +template.npmInstall(['lodash', 'axios']) +template.npmInstall('tsx', { g: true }) +template.npmInstall('typescript', { dev: true }) +template.npmInstall() // Installs from package.json +``` + +### pipInstall() + +```ts +pipInstall(packages?: string | string[], options?: object): TemplateBuilder +``` + +Install Python packages using pip. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `packages`? | `string` \| `string`[] | Package name(s) or undefined for current directory | +| `options`? | `object` | Install options | +| `options.g`? | `boolean` | Install globally as root (default: true). Set to false for user-only installation with --user flag | + +###### Returns + +`TemplateBuilder` + +###### Example + +```ts +template.pipInstall('numpy') // Installs globally (default) +template.pipInstall(['pandas', 'scikit-learn']) +template.pipInstall('numpy', { g: false }) // Install for user only +template.pipInstall() // Installs from current directory +``` + +### remove() + +```ts +remove(path: PathLike | PathLike[], options?: object): TemplateBuilder +``` + +Remove files or directories. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `path` | `PathLike` \| `PathLike`[] | Path(s) to remove | +| `options`? | `object` | Remove options | +| `options.force`? | `boolean` | - | +| `options.recursive`? | `boolean` | - | +| `options.user`? | `string` | - | + +###### Returns + +`TemplateBuilder` + +###### Example + +```ts +template.remove('/tmp/cache', { recursive: true, force: true }) +template.remove('/tmp/cache', { recursive: true, force: true, user: 'root' }) +``` + +### rename() + +```ts +rename( + src: PathLike, + dest: PathLike, + options?: object): TemplateBuilder +``` + +Rename or move a file or directory. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `src` | `PathLike` | Source path | +| `dest` | `PathLike` | Destination path | +| `options`? | `object` | Rename options | +| `options.force`? | `boolean` | - | +| `options.user`? | `string` | - | + +###### Returns + +`TemplateBuilder` + +###### Example + +```ts +template.rename('/tmp/old.txt', '/tmp/new.txt') +template.rename('/tmp/old.txt', '/tmp/new.txt', { user: 'root' }) +``` + +### runCmd() + +###### runCmd(command, options) + +```ts +runCmd(command: string, options?: object): TemplateBuilder +``` + +Run a shell command. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `command` | `string` | Command string | +| `options`? | `object` | Command options | +| `options.user`? | `string` | - | + +###### Returns + +`TemplateBuilder` + +###### Example + +```ts +template.runCmd('apt-get update') +template.runCmd(['pip install numpy', 'pip install pandas']) +template.runCmd('apt-get install vim', { user: 'root' }) +``` + +###### runCmd(commands, options) + +```ts +runCmd(commands: string[], options?: object): TemplateBuilder +``` + +Run multiple shell commands. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `commands` | `string`[] | Array of command strings | +| `options`? | `object` | Command options | +| `options.user`? | `string` | - | + +###### Returns + +`TemplateBuilder` + +###### runCmd(commandOrCommands, options) + +```ts +runCmd(commandOrCommands: string | string[], options?: object): TemplateBuilder +``` + +Run command(s). + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `commandOrCommands` | `string` \| `string`[] | Command or commands | +| `options`? | `object` | Command options | +| `options.user`? | `string` | - | + +###### Returns + +`TemplateBuilder` + +### setEnvs() + +```ts +setEnvs(envs: Record): TemplateBuilder +``` + +Set environment variables. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `envs` | `Record`\<`string`, `string`\> | Environment variables | + +###### Returns + +`TemplateBuilder` + +###### Example + +```ts +template.setEnvs({ NODE_ENV: 'production', PORT: '8080' }) +``` + +### setReadyCmd() + +```ts +setReadyCmd(readyCommand: string | ReadyCmd): TemplateFinal +``` + +Set or update the ready check command. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `readyCommand` | `string` \| `ReadyCmd` | Command to check readiness | + +###### Returns + +`TemplateFinal` + +###### Example + +```ts +// Using a string command +template.setReadyCmd('curl http://localhost:8000/health') + +// Using ReadyCmd helpers +import { waitForPort, waitForFile, waitForProcess } from 'e2b' + +template.setReadyCmd(waitForPort(3000)) + +template.setReadyCmd(waitForFile('/tmp/ready')) + +template.setReadyCmd(waitForProcess('nginx')) +``` + +### setStartCmd() + +```ts +setStartCmd(startCommand: string, readyCommand: string | ReadyCmd): TemplateFinal +``` + +Set the start command and ready check. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `startCommand` | `string` | Command to run on startup | +| `readyCommand` | `string` \| `ReadyCmd` | Command to check readiness | + +###### Returns + +`TemplateFinal` + +###### Example + +```ts +// Using a string command +template.setStartCmd( + 'node app.js', + 'curl http://localhost:8000/health' +) + +// Using ReadyCmd helpers +import { waitForPort, waitForURL } from 'e2b' + +template.setStartCmd( + 'python -m http.server 8000', + waitForPort(8000) +) + +template.setStartCmd( + 'npm start', + waitForURL('http://localhost:3000/health', 200) +) +``` + +### setUser() + +```ts +setUser(user: string): TemplateBuilder +``` + +Set the user for subsequent commands. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `user` | `string` | Username | + +###### Returns + +`TemplateBuilder` + +###### Example + +```ts +template.setUser('root') +``` + +### setWorkdir() + +```ts +setWorkdir(workdir: PathLike): TemplateBuilder +``` + +Set the working directory. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `workdir` | `PathLike` | Working directory path | + +###### Returns + +`TemplateBuilder` + +###### Example + +```ts +template.setWorkdir('/app') +``` + +### skipCache() + +```ts +skipCache(): this +``` + +Skip cache for all subsequent build instructions from this point. + +###### Returns + +`this` + +###### Example + +```ts +template.skipCache().runCmd('apt-get update') +``` + +## Type Aliases + +### BuildInfo + +```ts +type BuildInfo: object; +``` + +Information about a built template. + +#### Type declaration + +| Name | Type | +| ------ | ------ | +| `alias` | `string` | +| `buildId` | `string` | +| `templateId` | `string` | + +*** + +### BuildOptions + +```ts +type BuildOptions: AuthOptions & BasicBuildOptions; +``` + +Options for building a template with authentication. + +*** + +### CopyItem + +```ts +type CopyItem: object; +``` + +Configuration for a single file/directory copy operation. + +#### Type declaration + +| Name | Type | +| ------ | ------ | +| `dest` | `PathLike` | +| `forceUpload`? | `true` | +| `mode`? | `number` | +| `resolveSymlinks`? | `boolean` | +| `src` | `PathLike` \| `PathLike`[] | +| `user`? | `string` | + +*** + +### GetBuildStatusOptions + +```ts +type GetBuildStatusOptions: AuthOptions & object; +``` + +Response from getting build status. + +#### Type declaration + +| Name | Type | +| ------ | ------ | +| `logsOffset`? | `number` | + +*** + +### McpServerName + +```ts +type McpServerName: keyof McpServer; +``` + +MCP server names that can be installed. + +*** + +### TemplateClass + +```ts +type TemplateClass: TemplateBuilder | TemplateFinal; +``` + +Type representing a template in any state (builder or final). + +## Functions + +### Template() + +```ts +function Template(options?: TemplateOptions): TemplateFromImage +``` + +Create a new E2B template builder instance. + +#### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `options`? | `TemplateOptions` | Optional configuration for the template builder | + +#### Returns + +`TemplateFromImage` + +A new template builder instance + +#### Example + +```ts +import { Template } from 'e2b' + +const template = Template() + .fromPythonImage('3') + .copy('requirements.txt', '/app/') + .pipInstall() + +await Template.build(template, { alias: 'my-python-app' }) +``` diff --git a/docs/sdk-reference/js-sdk/v2.9.0/errors.mdx b/docs/sdk-reference/js-sdk/v2.9.0/errors.mdx new file mode 100644 index 0000000..bfe0deb --- /dev/null +++ b/docs/sdk-reference/js-sdk/v2.9.0/errors.mdx @@ -0,0 +1,271 @@ +--- +sidebarTitle: "Errors" +mode: "center" +--- + +### AuthenticationError + +Thrown when authentication fails. + +#### Constructors + +```ts +new AuthenticationError(message: string): AuthenticationError +``` + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `message` | `string` | + +###### Returns + +`AuthenticationError` + +*** + +### BuildError + +Thrown when the build fails. + +#### Extended by + +- `FileUploadError` + +#### Constructors + +```ts +new BuildError(message: string, stackTrace?: string): BuildError +``` + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `message` | `string` | +| `stackTrace`? | `string` | + +###### Returns + +`BuildError` + +*** + +### FileUploadError + +Thrown when the file upload fails. + +#### Constructors + +```ts +new FileUploadError(message: string, stackTrace?: string): FileUploadError +``` + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `message` | `string` | +| `stackTrace`? | `string` | + +###### Returns + +`FileUploadError` + +*** + +### InvalidArgumentError + +Thrown when an invalid argument is provided. + +#### Constructors + +```ts +new InvalidArgumentError(message: string, stackTrace?: string): InvalidArgumentError +``` + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `message` | `string` | +| `stackTrace`? | `string` | + +###### Returns + +`InvalidArgumentError` + +*** + +### NotEnoughSpaceError + +Thrown when there is not enough disk space. + +#### Constructors + +```ts +new NotEnoughSpaceError(message: string, stackTrace?: string): NotEnoughSpaceError +``` + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `message` | `string` | +| `stackTrace`? | `string` | + +###### Returns + +`NotEnoughSpaceError` + +*** + +### NotFoundError + +Thrown when a resource is not found. + +#### Constructors + +```ts +new NotFoundError(message: string, stackTrace?: string): NotFoundError +``` + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `message` | `string` | +| `stackTrace`? | `string` | + +###### Returns + +`NotFoundError` + +*** + +### RateLimitError + +Thrown when the API rate limit is exceeded. + +#### Constructors + +```ts +new RateLimitError(message: string): RateLimitError +``` + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `message` | `string` | + +###### Returns + +`RateLimitError` + +*** + +### SandboxError + +Base class for all sandbox errors. + +Thrown when general sandbox errors occur. + +#### Extended by + +- `TimeoutError` +- `InvalidArgumentError` +- `NotEnoughSpaceError` +- `NotFoundError` +- `TemplateError` +- `RateLimitError` + +#### Constructors + +```ts +new SandboxError(message?: string, stackTrace?: string): SandboxError +``` + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `message`? | `string` | +| `stackTrace`? | `string` | + +###### Returns + +`SandboxError` + +*** + +### TemplateError + +Thrown when the template uses old envd version. It isn't compatible with the new SDK. + +#### Constructors + +```ts +new TemplateError(message: string, stackTrace?: string): TemplateError +``` + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `message` | `string` | +| `stackTrace`? | `string` | + +###### Returns + +`TemplateError` + +*** + +### TimeoutError + +Thrown when a timeout error occurs. + +The [unavailable] error type is caused by sandbox timeout. + +The [canceled] error type is caused by exceeding request timeout. + +The [deadline_exceeded] error type is caused by exceeding the timeout for command execution, watch, etc. + +The [unknown] error type is sometimes caused by the sandbox timeout when the request is not processed correctly. + +#### Constructors + +```ts +new TimeoutError(message: string, stackTrace?: string): TimeoutError +``` + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `message` | `string` | +| `stackTrace`? | `string` | + +###### Returns + +`TimeoutError` + +## Functions + +### formatSandboxTimeoutError() + +```ts +function formatSandboxTimeoutError(message: string): TimeoutError +``` + +#### Parameters + +| Parameter | Type | +| ------ | ------ | +| `message` | `string` | + +#### Returns + +`TimeoutError` diff --git a/docs/sdk-reference/js-sdk/v2.9.0/sandbox-commands.mdx b/docs/sdk-reference/js-sdk/v2.9.0/sandbox-commands.mdx new file mode 100644 index 0000000..bebbd9a --- /dev/null +++ b/docs/sdk-reference/js-sdk/v2.9.0/sandbox-commands.mdx @@ -0,0 +1,554 @@ +--- +sidebarTitle: "Commands" +mode: "center" +--- + +### Commands + +Module for starting and interacting with commands in the sandbox. + +#### Constructors + +```ts +new Commands( + transport: Transport, + connectionConfig: ConnectionConfig, + metadata: object): Commands +``` + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `transport` | `Transport` | +| `connectionConfig` | `ConnectionConfig` | +| `metadata` | `object` | +| `metadata.version` | `string` | + +###### Returns + +`Commands` + +#### Methods + +### connect() + +```ts +connect(pid: number, opts?: CommandConnectOpts): Promise +``` + +Connect to a running command. +You can use CommandHandle.wait to wait for the command to finish and get execution results. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `pid` | `number` | process ID of the command to connect to. You can get the list of running commands using Commands.list. | +| `opts`? | `CommandConnectOpts` | connection options. | + +###### Returns + +`Promise`\<`CommandHandle`\> + +`CommandHandle` handle to interact with the running command. + +### kill() + +```ts +kill(pid: number, opts?: CommandRequestOpts): Promise +``` + +Kill a running command specified by its process ID. +It uses `SIGKILL` signal to kill the command. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `pid` | `number` | process ID of the command. You can get the list of running commands using Commands.list. | +| `opts`? | `CommandRequestOpts` | connection options. | + +###### Returns + +`Promise`\<`boolean`\> + +`true` if the command was killed, `false` if the command was not found. + +### list() + +```ts +list(opts?: CommandRequestOpts): Promise +``` + +List all running commands and PTY sessions. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `opts`? | `CommandRequestOpts` | connection options. | + +###### Returns + +`Promise`\<`ProcessInfo`[]\> + +list of running commands and PTY sessions. + +### run() + +###### run(cmd, opts) + +```ts +run(cmd: string, opts?: CommandStartOpts & object): Promise +``` + +Start a new command and wait until it finishes executing. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `cmd` | `string` | command to execute. | +| `opts`? | `CommandStartOpts` & `object` | options for starting the command. | + +###### Returns + +`Promise`\<`CommandResult`\> + +`CommandResult` result of the command execution. + +###### run(cmd, opts) + +```ts +run(cmd: string, opts: CommandStartOpts & object): Promise +``` + +Start a new command in the background. +You can use CommandHandle.wait to wait for the command to finish and get its result. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `cmd` | `string` | command to execute. | +| `opts` | `CommandStartOpts` & `object` | options for starting the command | + +###### Returns + +`Promise`\<`CommandHandle`\> + +`CommandHandle` handle to interact with the running command. + +###### run(cmd, opts) + +```ts +run(cmd: string, opts?: CommandStartOpts & object): Promise +``` + +Start a new command. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `cmd` | `string` | command to execute. | +| `opts`? | `CommandStartOpts` & `object` | options for starting the command. - `opts.background: true` - runs in background, returns `CommandHandle` - `opts.background: false | undefined` - waits for completion, returns `CommandResult` | + +###### Returns + +`Promise`\<`CommandResult` \| `CommandHandle`\> + +Either a `CommandHandle` or a `CommandResult` (depending on `opts.background`). + +### sendStdin() + +```ts +sendStdin( + pid: number, + data: string, +opts?: CommandRequestOpts): Promise +``` + +Send data to command stdin. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `pid` | `number` | process ID of the command. You can get the list of running commands using Commands.list. | +| `data` | `string` | data to send to the command. | +| `opts`? | `CommandRequestOpts` | connection options. | + +###### Returns + +`Promise`\<`void`\> + +*** + +### Pty + +Module for interacting with PTYs (pseudo-terminals) in the sandbox. + +#### Constructors + +```ts +new Pty( + transport: Transport, + connectionConfig: ConnectionConfig, + metadata: object): Pty +``` + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `transport` | `Transport` | +| `connectionConfig` | `ConnectionConfig` | +| `metadata` | `object` | +| `metadata.version` | `string` | + +###### Returns + +`Pty` + +#### Methods + +### connect() + +```ts +connect(pid: number, opts?: PtyConnectOpts): Promise +``` + +Connect to a running PTY. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `pid` | `number` | process ID of the PTY to connect to. You can get the list of running PTYs using Commands.list. | +| `opts`? | `PtyConnectOpts` | connection options. | + +###### Returns + +`Promise`\<`CommandHandle`\> + +handle to interact with the PTY. + +### create() + +```ts +create(opts: PtyCreateOpts): Promise +``` + +Create a new PTY (pseudo-terminal). + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `opts` | `PtyCreateOpts` | options for creating the PTY. | + +###### Returns + +`Promise`\<`CommandHandle`\> + +handle to interact with the PTY. + +### kill() + +```ts +kill(pid: number, opts?: Pick): Promise +``` + +Kill a running PTY specified by process ID. +It uses `SIGKILL` signal to kill the PTY. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `pid` | `number` | process ID of the PTY. | +| `opts`? | `Pick`\<`ConnectionOpts`, `"requestTimeoutMs"`\> | connection options. | + +###### Returns + +`Promise`\<`boolean`\> + +`true` if the PTY was killed, `false` if the PTY was not found. + +### resize() + +```ts +resize( + pid: number, + size: object, +opts?: Pick): Promise +``` + +Resize PTY. +Call this when the terminal window is resized and the number of columns and rows has changed. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `pid` | `number` | process ID of the PTY. | +| `size` | `object` | new size of the PTY. | +| `size.cols` | `number` | - | +| `size.rows`? | `number` | - | +| `opts`? | `Pick`\<`ConnectionOpts`, `"requestTimeoutMs"`\> | connection options. | + +###### Returns + +`Promise`\<`void`\> + +### sendInput() + +```ts +sendInput( + pid: number, + data: Uint8Array, +opts?: Pick): Promise +``` + +Send input to a PTY. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `pid` | `number` | process ID of the PTY. | +| `data` | `Uint8Array` | input data to send to the PTY. | +| `opts`? | `Pick`\<`ConnectionOpts`, `"requestTimeoutMs"`\> | connection options. | + +###### Returns + +`Promise`\<`void`\> + +## Interfaces + +### CommandRequestOpts + +Options for sending a command request. + +#### Extended by + +- `CommandStartOpts` + +#### Properties + +### requestTimeoutMs? + +```ts +optional requestTimeoutMs: number; +``` + +Timeout for requests to the API in **milliseconds**. + +###### Default + +```ts +60_000 // 60 seconds +``` + +*** + +### CommandStartOpts + +Options for starting a new command. + +#### Properties + +### background? + +```ts +optional background: boolean; +``` + +If true, starts command in the background and the method returns immediately. +You can use CommandHandle.wait to wait for the command to finish. + +### cwd? + +```ts +optional cwd: string; +``` + +Working directory for the command. + +###### Default + +```ts +// home directory of the user used to start the command +``` + +### envs? + +```ts +optional envs: Record; +``` + +Environment variables used for the command. + +This overrides the default environment variables from `Sandbox` constructor. + +###### Default + +`{}` + +### onStderr()? + +```ts +optional onStderr: (data: string) => void | Promise; +``` + +Callback for command stderr output. + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `data` | `string` | + +###### Returns + +`void` \| `Promise`\<`void`\> + +### onStdout()? + +```ts +optional onStdout: (data: string) => void | Promise; +``` + +Callback for command stdout output. + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `data` | `string` | + +###### Returns + +`void` \| `Promise`\<`void`\> + +### requestTimeoutMs? + +```ts +optional requestTimeoutMs: number; +``` + +Timeout for requests to the API in **milliseconds**. + +###### Default + +```ts +60_000 // 60 seconds +``` + +### stdin? + +```ts +optional stdin: boolean; +``` + +If true, command stdin is kept open and you can send data to it using Commands.sendStdin or CommandHandle.sendStdin. + +###### Default + +```ts +false +``` + +### timeoutMs? + +```ts +optional timeoutMs: number; +``` + +Timeout for the command in **milliseconds**. + +###### Default + +```ts +60_000 // 60 seconds +``` + +### user? + +```ts +optional user: string; +``` + +User to run the command as. + +###### Default + +`default Sandbox user (as specified in the template)` + +*** + +### ProcessInfo + +Information about a command, PTY session or start command running in the sandbox as process. + +#### Properties + +### args + +```ts +args: string[]; +``` + +Command arguments. + +### cmd + +```ts +cmd: string; +``` + +Command that was executed. + +### cwd? + +```ts +optional cwd: string; +``` + +Executed command working directory. + +### envs + +```ts +envs: Record; +``` + +Environment variables used for the command. + +### pid + +```ts +pid: number; +``` + +Process ID. + +### tag? + +```ts +optional tag: string; +``` + +Custom tag used for identifying special commands like start command in the custom template. + +## Type Aliases + +### CommandConnectOpts + +```ts +type CommandConnectOpts: Pick & CommandRequestOpts; +``` + +Options for connecting to a command. diff --git a/docs/sdk-reference/js-sdk/v2.9.0/sandbox-filesystem.mdx b/docs/sdk-reference/js-sdk/v2.9.0/sandbox-filesystem.mdx new file mode 100644 index 0000000..c43ac2f --- /dev/null +++ b/docs/sdk-reference/js-sdk/v2.9.0/sandbox-filesystem.mdx @@ -0,0 +1,627 @@ +--- +sidebarTitle: "Filesystem" +mode: "center" +--- + +### FileType + +Sandbox filesystem object type. + +#### Enumeration Members + +| Enumeration Member | Value | Description | +| ------ | ------ | ------ | +| `DIR` | `"dir"` | Filesystem object is a directory. | +| `FILE` | `"file"` | Filesystem object is a file. | + +## Classes + +### Filesystem + +Module for interacting with the sandbox filesystem. + +#### Constructors + +```ts +new Filesystem( + transport: Transport, + envdApi: EnvdApiClient, + connectionConfig: ConnectionConfig): Filesystem +``` + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `transport` | `Transport` | +| `envdApi` | `EnvdApiClient` | +| `connectionConfig` | `ConnectionConfig` | + +###### Returns + +`Filesystem` + +#### Methods + +### exists() + +```ts +exists(path: string, opts?: FilesystemRequestOpts): Promise +``` + +Check if a file or a directory exists. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `path` | `string` | path to a file or a directory | +| `opts`? | `FilesystemRequestOpts` | connection options. | + +###### Returns + +`Promise`\<`boolean`\> + +`true` if the file or directory exists, `false` otherwise + +### getInfo() + +```ts +getInfo(path: string, opts?: FilesystemRequestOpts): Promise +``` + +Get information about a file or directory. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `path` | `string` | path to a file or directory. | +| `opts`? | `FilesystemRequestOpts` | connection options. | + +###### Returns + +`Promise`\<`EntryInfo`\> + +information about the file or directory like name, type, and path. + +### list() + +```ts +list(path: string, opts?: FilesystemListOpts): Promise +``` + +List entries in a directory. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `path` | `string` | path to the directory. | +| `opts`? | `FilesystemListOpts` | connection options. | + +###### Returns + +`Promise`\<`EntryInfo`[]\> + +list of entries in the sandbox filesystem directory. + +### makeDir() + +```ts +makeDir(path: string, opts?: FilesystemRequestOpts): Promise +``` + +Create a new directory and all directories along the way if needed on the specified path. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `path` | `string` | path to a new directory. For example '/dirA/dirB' when creating 'dirB'. | +| `opts`? | `FilesystemRequestOpts` | connection options. | + +###### Returns + +`Promise`\<`boolean`\> + +`true` if the directory was created, `false` if it already exists. + +### read() + +###### read(path, opts) + +```ts +read(path: string, opts?: FilesystemRequestOpts & object): Promise +``` + +Read file content as a `string`. + +You can pass `text`, `bytes`, `blob`, or `stream` to `opts.format` to change the return type. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `path` | `string` | path to the file. | +| `opts`? | `FilesystemRequestOpts` & `object` | connection options. | + +###### Returns + +`Promise`\<`string`\> + +file content as string + +###### read(path, opts) + +```ts +read(path: string, opts?: FilesystemRequestOpts & object): Promise +``` + +Read file content as a `Uint8Array`. + +You can pass `text`, `bytes`, `blob`, or `stream` to `opts.format` to change the return type. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `path` | `string` | path to the file. | +| `opts`? | `FilesystemRequestOpts` & `object` | connection options. | + +###### Returns + +`Promise`\<`Uint8Array`\> + +file content as `Uint8Array` + +###### read(path, opts) + +```ts +read(path: string, opts?: FilesystemRequestOpts & object): Promise +``` + +Read file content as a `Blob`. + +You can pass `text`, `bytes`, `blob`, or `stream` to `opts.format` to change the return type. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `path` | `string` | path to the file. | +| `opts`? | `FilesystemRequestOpts` & `object` | connection options. | + +###### Returns + +`Promise`\<`Blob`\> + +file content as `Blob` + +###### read(path, opts) + +```ts +read(path: string, opts?: FilesystemRequestOpts & object): Promise> +``` + +Read file content as a `ReadableStream`. + +You can pass `text`, `bytes`, `blob`, or `stream` to `opts.format` to change the return type. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `path` | `string` | path to the file. | +| `opts`? | `FilesystemRequestOpts` & `object` | connection options. | + +###### Returns + +`Promise`\<`ReadableStream`\<`Uint8Array`\>\> + +file content as `ReadableStream` + +### remove() + +```ts +remove(path: string, opts?: FilesystemRequestOpts): Promise +``` + +Remove a file or directory. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `path` | `string` | path to a file or directory. | +| `opts`? | `FilesystemRequestOpts` | connection options. | + +###### Returns + +`Promise`\<`void`\> + +### rename() + +```ts +rename( + oldPath: string, + newPath: string, +opts?: FilesystemRequestOpts): Promise +``` + +Rename a file or directory. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `oldPath` | `string` | path to the file or directory to rename. | +| `newPath` | `string` | new path for the file or directory. | +| `opts`? | `FilesystemRequestOpts` | connection options. | + +###### Returns + +`Promise`\<`EntryInfo`\> + +information about renamed file or directory. + +### watchDir() + +```ts +watchDir( + path: string, + onEvent: (event: FilesystemEvent) => void | Promise, +opts?: WatchOpts & object): Promise +``` + +Start watching a directory for filesystem events. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `path` | `string` | path to directory to watch. | +| `onEvent` | (`event`: `FilesystemEvent`) => `void` \| `Promise`\<`void`\> | callback to call when an event in the directory occurs. | +| `opts`? | `WatchOpts` & `object` | connection options. | + +###### Returns + +`Promise`\<`WatchHandle`\> + +`WatchHandle` object for stopping watching directory. + +### write() + +###### write(path, data, opts) + +```ts +write( + path: string, + data: string | ArrayBuffer | Blob | ReadableStream, +opts?: FilesystemRequestOpts): Promise +``` + +Write content to a file. + +Writing to a file that doesn't exist creates the file. + +Writing to a file that already exists overwrites the file. + +Writing to a file at path that doesn't exist creates the necessary directories. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `path` | `string` | path to file. | +| `data` | `string` \| `ArrayBuffer` \| `Blob` \| `ReadableStream`\<`any`\> | data to write to the file. Data can be a string, `ArrayBuffer`, `Blob`, or `ReadableStream`. | +| `opts`? | `FilesystemRequestOpts` | connection options. | + +###### Returns + +`Promise`\<`WriteInfo`\> + +information about the written file + +###### write(files, opts) + +```ts +write(files: WriteEntry[], opts?: FilesystemRequestOpts): Promise +``` + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `files` | `WriteEntry`[] | +| `opts`? | `FilesystemRequestOpts` | + +###### Returns + +`Promise`\<`WriteInfo`[]\> + +## Interfaces + +### EntryInfo + +Sandbox filesystem object information. + +#### Properties + +### group + +```ts +group: string; +``` + +Group owner of the filesystem object. + +### mode + +```ts +mode: number; +``` + +File mode and permission bits. + +### modifiedTime? + +```ts +optional modifiedTime: Date; +``` + +Last modification time of the filesystem object. + +### name + +```ts +name: string; +``` + +Name of the filesystem object. + +### owner + +```ts +owner: string; +``` + +Owner of the filesystem object. + +### path + +```ts +path: string; +``` + +Path to the filesystem object. + +### permissions + +```ts +permissions: string; +``` + +String representation of file permissions (e.g. 'rwxr-xr-x'). + +### size + +```ts +size: number; +``` + +Size of the filesystem object in bytes. + +### symlinkTarget? + +```ts +optional symlinkTarget: string; +``` + +If the filesystem object is a symlink, this is the target of the symlink. + +### type? + +```ts +optional type: FileType; +``` + +Type of the filesystem object. + +*** + +### FilesystemListOpts + +Options for the sandbox filesystem operations. + +#### Properties + +### depth? + +```ts +optional depth: number; +``` + +Depth of the directory to list. + +### requestTimeoutMs? + +```ts +optional requestTimeoutMs: number; +``` + +Timeout for requests to the API in **milliseconds**. + +###### Default + +```ts +60_000 // 60 seconds +``` + +### user? + +```ts +optional user: string; +``` + +User to use for the operation in the sandbox. +This affects the resolution of relative paths and ownership of the created filesystem objects. + +*** + +### FilesystemRequestOpts + +Options for the sandbox filesystem operations. + +#### Extended by + +- `FilesystemListOpts` +- `WatchOpts` + +#### Properties + +### requestTimeoutMs? + +```ts +optional requestTimeoutMs: number; +``` + +Timeout for requests to the API in **milliseconds**. + +###### Default + +```ts +60_000 // 60 seconds +``` + +### user? + +```ts +optional user: string; +``` + +User to use for the operation in the sandbox. +This affects the resolution of relative paths and ownership of the created filesystem objects. + +*** + +### WatchOpts + +Options for watching a directory. + +#### Properties + +### onExit()? + +```ts +optional onExit: (err?: Error) => void | Promise; +``` + +Callback to call when the watch operation stops. + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `err`? | `Error` | + +###### Returns + +`void` \| `Promise`\<`void`\> + +### recursive? + +```ts +optional recursive: boolean; +``` + +Watch the directory recursively + +### requestTimeoutMs? + +```ts +optional requestTimeoutMs: number; +``` + +Timeout for requests to the API in **milliseconds**. + +###### Default + +```ts +60_000 // 60 seconds +``` + +### timeoutMs? + +```ts +optional timeoutMs: number; +``` + +Timeout for the watch operation in **milliseconds**. +You can pass `0` to disable the timeout. + +###### Default + +```ts +60_000 // 60 seconds +``` + +### user? + +```ts +optional user: string; +``` + +User to use for the operation in the sandbox. +This affects the resolution of relative paths and ownership of the created filesystem objects. + +*** + +### WriteInfo + +Sandbox filesystem object information. + +#### Extended by + +- `EntryInfo` + +#### Properties + +### name + +```ts +name: string; +``` + +Name of the filesystem object. + +### path + +```ts +path: string; +``` + +Path to the filesystem object. + +### type? + +```ts +optional type: FileType; +``` + +Type of the filesystem object. + +## Type Aliases + +### WriteEntry + +```ts +type WriteEntry: object; +``` + +#### Type declaration + +| Name | Type | +| ------ | ------ | +| `data` | `string` \| `ArrayBuffer` \| `Blob` \| `ReadableStream` | +| `path` | `string` | diff --git a/docs/sdk-reference/js-sdk/v2.9.0/sandbox.mdx b/docs/sdk-reference/js-sdk/v2.9.0/sandbox.mdx new file mode 100644 index 0000000..e430744 --- /dev/null +++ b/docs/sdk-reference/js-sdk/v2.9.0/sandbox.mdx @@ -0,0 +1,712 @@ +--- +sidebarTitle: "Sandbox" +mode: "center" +--- + +### Sandbox + +E2B cloud sandbox is a secure and isolated cloud environment. + +The sandbox allows you to: +- Access Linux OS +- Create, list, and delete files and directories +- Run commands +- Run isolated code +- Access the internet + +Check docs here. + +Use Sandbox.create to create a new sandbox. + +#### Example + +```ts +import { Sandbox } from 'e2b' + +const sandbox = await Sandbox.create() +``` + +#### Properties + +| Property | Modifier | Type | Description | +| ------ | ------ | ------ | ------ | +| `commands` | `readonly` | `Commands` | Module for running commands in the sandbox | +| `files` | `readonly` | `Filesystem` | Module for interacting with the sandbox filesystem | +| `pty` | `readonly` | `Pty` | Module for interacting with the sandbox pseudo-terminals | +| `sandboxDomain` | `readonly` | `string` | Domain where the sandbox is hosted. | +| `sandboxId` | `readonly` | `string` | Unique identifier of the sandbox. | +| `trafficAccessToken?` | `readonly` | `string` | Traffic access token for accessing sandbox services with restricted public traffic. | + +#### Methods + +### betaPause() + +```ts +betaPause(opts?: ConnectionOpts): Promise +``` + +**`Beta`** + +This feature is in beta and may change in the future. + +Pause a sandbox by its ID. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `opts`? | `ConnectionOpts` | connection options. | + +###### Returns + +`Promise`\<`boolean`\> + +sandbox ID that can be used to resume the sandbox. + +### connect() + +```ts +connect(opts?: SandboxBetaCreateOpts): Promise +``` + +Connect to a sandbox. If the sandbox is paused, it will be automatically resumed. +Sandbox must be either running or be paused. + +With sandbox ID you can connect to the same sandbox from different places or environments (serverless functions, etc). + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `opts`? | `SandboxBetaCreateOpts` | connection options. | + +###### Returns + +`Promise`\<`Sandbox`\> + +A running sandbox instance + +###### Example + +```ts +const sandbox = await Sandbox.create() +await sandbox.betaPause() + +// Connect to the same sandbox. +const sameSandbox = await sandbox.connect() +``` + +### downloadUrl() + +```ts +downloadUrl(path: string, opts?: SandboxUrlOpts): Promise +``` + +Get the URL to download a file from the sandbox. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `path` | `string` | path to the file in the sandbox. | +| `opts`? | `SandboxUrlOpts` | download url options. | + +###### Returns + +`Promise`\<`string`\> + +URL for downloading file. + +### getHost() + +```ts +getHost(port: number): string +``` + +Get the host address for the specified sandbox port. +You can then use this address to connect to the sandbox port from outside the sandbox via HTTP or WebSocket. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `port` | `number` | number of the port in the sandbox. | + +###### Returns + +`string` + +host address of the sandbox port. + +###### Example + +```ts +const sandbox = await Sandbox.create() +// Start an HTTP server +await sandbox.commands.exec('python3 -m http.server 3000') +// Get the hostname of the HTTP server +const serverURL = sandbox.getHost(3000) +``` + +### getInfo() + +```ts +getInfo(opts?: Pick): Promise +``` + +Get sandbox information like sandbox ID, template, metadata, started at/end at date. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `opts`? | `Pick`\<`SandboxOpts`, `"requestTimeoutMs"`\> | connection options. | + +###### Returns + +`Promise`\<`SandboxInfo`\> + +information about the sandbox + +### getMcpToken() + +```ts +getMcpToken(): Promise +``` + +Get the MCP token for the sandbox. + +###### Returns + +`Promise`\<`undefined` \| `string`\> + +MCP token for the sandbox, or undefined if MCP is not enabled. + +### getMcpUrl() + +```ts +getMcpUrl(): string +``` + +Get the MCP URL for the sandbox. + +###### Returns + +`string` + +MCP URL for the sandbox. + +### getMetrics() + +```ts +getMetrics(opts?: SandboxMetricsOpts): Promise +``` + +Get the metrics of the sandbox. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `opts`? | `SandboxMetricsOpts` | connection options. | + +###### Returns + +`Promise`\<`SandboxMetrics`[]\> + +List of sandbox metrics containing CPU, memory and disk usage information. + +### isRunning() + +```ts +isRunning(opts?: Pick): Promise +``` + +Check if the sandbox is running. + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `opts`? | `Pick`\<`ConnectionOpts`, `"requestTimeoutMs"`\> | + +###### Returns + +`Promise`\<`boolean`\> + +`true` if the sandbox is running, `false` otherwise. + +###### Example + +```ts +const sandbox = await Sandbox.create() +await sandbox.isRunning() // Returns true + +await sandbox.kill() +await sandbox.isRunning() // Returns false +``` + +### kill() + +```ts +kill(opts?: Pick): Promise +``` + +Kill the sandbox. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `opts`? | `Pick`\<`SandboxOpts`, `"requestTimeoutMs"`\> | connection options. | + +###### Returns + +`Promise`\<`void`\> + +### setTimeout() + +```ts +setTimeout(timeoutMs: number, opts?: Pick): Promise +``` + +Set the timeout of the sandbox. +After the timeout expires the sandbox will be automatically killed. + +This method can extend or reduce the sandbox timeout set when creating the sandbox or from the last call to `.setTimeout`. +Maximum time a sandbox can be kept alive is 24 hours (86_400_000 milliseconds) for Pro users and 1 hour (3_600_000 milliseconds) for Hobby users. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `timeoutMs` | `number` | timeout in **milliseconds**. | +| `opts`? | `Pick`\<`SandboxOpts`, `"requestTimeoutMs"`\> | connection options. | + +###### Returns + +`Promise`\<`void`\> + +### uploadUrl() + +```ts +uploadUrl(path?: string, opts?: SandboxUrlOpts): Promise +``` + +Get the URL to upload a file to the sandbox. + +You have to send a POST request to this URL with the file as multipart/form-data. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `path`? | `string` | path to the file in the sandbox. | +| `opts`? | `SandboxUrlOpts` | download url options. | + +###### Returns + +`Promise`\<`string`\> + +URL for uploading file. + +### betaCreate() + +###### betaCreate(this, opts) + +```ts +static betaCreate(this: S, opts?: SandboxBetaCreateOpts): Promise> +``` + +**`Beta`** + +This feature is in beta and may change in the future. + +Create a new sandbox from the default `base` sandbox template. + +###### Type Parameters + +| Type Parameter | +| ------ | +| `S` *extends* *typeof* `Sandbox` | + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `this` | `S` | - | +| `opts`? | `SandboxBetaCreateOpts` | connection options. | + +###### Returns + +`Promise`\<`InstanceType`\<`S`\>\> + +sandbox instance for the new sandbox. + +###### Example + +```ts +const sandbox = await Sandbox.betaCreate() +``` + +###### Constructs + +Sandbox + +###### betaCreate(this, template, opts) + +```ts +static betaCreate( + this: S, + template: string, +opts?: SandboxBetaCreateOpts): Promise> +``` + +**`Beta`** + +This feature is in beta and may change in the future. + +Create a new sandbox from the specified sandbox template. + +###### Type Parameters + +| Type Parameter | +| ------ | +| `S` *extends* *typeof* `Sandbox` | + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `this` | `S` | - | +| `template` | `string` | sandbox template name or ID. | +| `opts`? | `SandboxBetaCreateOpts` | connection options. | + +###### Returns + +`Promise`\<`InstanceType`\<`S`\>\> + +sandbox instance for the new sandbox. + +###### Example + +```ts +const sandbox = await Sandbox.betaCreate('') +``` + +###### Constructs + +Sandbox + +### betaPause() + +```ts +static betaPause(sandboxId: string, opts?: SandboxApiOpts): Promise +``` + +Pause the sandbox specified by sandbox ID. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `sandboxId` | `string` | sandbox ID. | +| `opts`? | `SandboxApiOpts` | connection options. | + +###### Returns + +`Promise`\<`boolean`\> + +`true` if the sandbox got paused, `false` if the sandbox was already paused. + +### connect() + +```ts +static connect( + this: S, + sandboxId: string, +opts?: SandboxConnectOpts): Promise> +``` + +Connect to a sandbox. If the sandbox is paused, it will be automatically resumed. +Sandbox must be either running or be paused. + +With sandbox ID you can connect to the same sandbox from different places or environments (serverless functions, etc). + +###### Type Parameters + +| Type Parameter | +| ------ | +| `S` *extends* *typeof* `Sandbox` | + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `this` | `S` | - | +| `sandboxId` | `string` | sandbox ID. | +| `opts`? | `SandboxConnectOpts` | connection options. | + +###### Returns + +`Promise`\<`InstanceType`\<`S`\>\> + +A running sandbox instance + +###### Example + +```ts +const sandbox = await Sandbox.create() +const sandboxId = sandbox.sandboxId + +// Connect to the same sandbox. +const sameSandbox = await Sandbox.connect(sandboxId) +``` + +### create() + +###### create(this, opts) + +```ts +static create(this: S, opts?: SandboxOpts): Promise> +``` + +Create a new sandbox from the default `base` sandbox template. + +###### Type Parameters + +| Type Parameter | +| ------ | +| `S` *extends* *typeof* `Sandbox` | + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `this` | `S` | - | +| `opts`? | `SandboxOpts` | connection options. | + +###### Returns + +`Promise`\<`InstanceType`\<`S`\>\> + +sandbox instance for the new sandbox. + +###### Example + +```ts +const sandbox = await Sandbox.create() +``` + +###### Constructs + +Sandbox + +###### create(this, template, opts) + +```ts +static create( + this: S, + template: string, +opts?: SandboxOpts): Promise> +``` + +Create a new sandbox from the specified sandbox template. + +###### Type Parameters + +| Type Parameter | +| ------ | +| `S` *extends* *typeof* `Sandbox` | + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `this` | `S` | - | +| `template` | `string` | sandbox template name or ID. | +| `opts`? | `SandboxOpts` | connection options. | + +###### Returns + +`Promise`\<`InstanceType`\<`S`\>\> + +sandbox instance for the new sandbox. + +###### Example + +```ts +const sandbox = await Sandbox.create('') +``` + +###### Constructs + +Sandbox + +### getFullInfo() + +```ts +static getFullInfo(sandboxId: string, opts?: SandboxApiOpts): Promise +``` + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `sandboxId` | `string` | +| `opts`? | `SandboxApiOpts` | + +###### Returns + +`Promise`\<`object`\> + +| Name | Type | Default value | +| ------ | ------ | ------ | +| `cpuCount` | `number` | res.data.cpuCount | +| `endAt` | `Date` | - | +| `envdAccessToken` | `undefined` \| `string` | res.data.envdAccessToken | +| `envdVersion` | `string` | res.data.envdVersion | +| `memoryMB` | `number` | res.data.memoryMB | +| `metadata` | `object` | - | +| `name`? | `string` | res.data.alias | +| `sandboxDomain` | `undefined` \| `string` | - | +| `sandboxId` | `string` | res.data.sandboxID | +| `startedAt` | `Date` | - | +| `state` | `"running"` \| `"paused"` | res.data.state | +| `templateId` | `string` | res.data.templateID | + +### getInfo() + +```ts +static getInfo(sandboxId: string, opts?: SandboxApiOpts): Promise +``` + +Get sandbox information like sandbox ID, template, metadata, started at/end at date. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `sandboxId` | `string` | sandbox ID. | +| `opts`? | `SandboxApiOpts` | connection options. | + +###### Returns + +`Promise`\<`SandboxInfo`\> + +sandbox information. + +### getMetrics() + +```ts +static getMetrics(sandboxId: string, opts?: SandboxMetricsOpts): Promise +``` + +Get the metrics of the sandbox. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `sandboxId` | `string` | sandbox ID. | +| `opts`? | `SandboxMetricsOpts` | sandbox metrics options. | + +###### Returns + +`Promise`\<`SandboxMetrics`[]\> + +List of sandbox metrics containing CPU, memory and disk usage information. + +### kill() + +```ts +static kill(sandboxId: string, opts?: SandboxApiOpts): Promise +``` + +Kill the sandbox specified by sandbox ID. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `sandboxId` | `string` | sandbox ID. | +| `opts`? | `SandboxApiOpts` | connection options. | + +###### Returns + +`Promise`\<`boolean`\> + +`true` if the sandbox was found and killed, `false` otherwise. + +### list() + +```ts +static list(opts?: SandboxListOpts): SandboxPaginator +``` + +List all sandboxes. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `opts`? | `SandboxListOpts` | connection options. | + +###### Returns + +`SandboxPaginator` + +paginator for listing sandboxes. + +### setTimeout() + +```ts +static setTimeout( + sandboxId: string, + timeoutMs: number, +opts?: SandboxApiOpts): Promise +``` + +Set the timeout of the specified sandbox. +After the timeout expires the sandbox will be automatically killed. + +This method can extend or reduce the sandbox timeout set when creating the sandbox or from the last call to Sandbox.setTimeout. + +Maximum time a sandbox can be kept alive is 24 hours (86_400_000 milliseconds) for Pro users and 1 hour (3_600_000 milliseconds) for Hobby users. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `sandboxId` | `string` | sandbox ID. | +| `timeoutMs` | `number` | timeout in **milliseconds**. | +| `opts`? | `SandboxApiOpts` | connection options. | + +###### Returns + +`Promise`\<`void`\> + +## Interfaces + +### SandboxUrlOpts + +Options for sandbox upload/download URL generation. + +#### Properties + +### user? + +```ts +optional user: string; +``` + +User that will be used to access the file. + +### useSignatureExpiration? + +```ts +optional useSignatureExpiration: number; +``` + +Use signature expiration for the URL. +Optional parameter to set the expiration time for the signature in seconds. diff --git a/docs/sdk-reference/js-sdk/v2.9.0/template-logger.mdx b/docs/sdk-reference/js-sdk/v2.9.0/template-logger.mdx new file mode 100644 index 0000000..fdebde3 --- /dev/null +++ b/docs/sdk-reference/js-sdk/v2.9.0/template-logger.mdx @@ -0,0 +1,196 @@ +--- +sidebarTitle: "Logger" +mode: "center" +--- + +### LogEntry + +Represents a single log entry from the template build process. + +#### Extended by + +- `LogEntryStart` +- `LogEntryEnd` + +#### Constructors + +```ts +new LogEntry( + timestamp: Date, + level: LogEntryLevel, + message: string): LogEntry +``` + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `timestamp` | `Date` | +| `level` | `LogEntryLevel` | +| `message` | `string` | + +###### Returns + +`LogEntry` + +#### Properties + +| Property | Modifier | Type | +| ------ | ------ | ------ | +| `level` | `readonly` | `LogEntryLevel` | +| `message` | `readonly` | `string` | +| `timestamp` | `readonly` | `Date` | + +#### Methods + +### toString() + +```ts +toString(): string +``` + +###### Returns + +`string` + +*** + +### LogEntryEnd + +Special log entry indicating the end of a build process. + +#### Constructors + +```ts +new LogEntryEnd(timestamp: Date, message: string): LogEntryEnd +``` + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `timestamp` | `Date` | +| `message` | `string` | + +###### Returns + +`LogEntryEnd` + +#### Properties + +| Property | Modifier | Type | Inherited from | +| ------ | ------ | ------ | ------ | +| `level` | `readonly` | `LogEntryLevel` | `LogEntry`.`level` | +| `message` | `readonly` | `string` | `LogEntry`.`message` | +| `timestamp` | `readonly` | `Date` | `LogEntry`.`timestamp` | + +#### Methods + +### toString() + +```ts +toString(): string +``` + +###### Returns + +`string` + +*** + +### LogEntryStart + +Special log entry indicating the start of a build process. + +#### Constructors + +```ts +new LogEntryStart(timestamp: Date, message: string): LogEntryStart +``` + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `timestamp` | `Date` | +| `message` | `string` | + +###### Returns + +`LogEntryStart` + +#### Properties + +| Property | Modifier | Type | Inherited from | +| ------ | ------ | ------ | ------ | +| `level` | `readonly` | `LogEntryLevel` | `LogEntry`.`level` | +| `message` | `readonly` | `string` | `LogEntry`.`message` | +| `timestamp` | `readonly` | `Date` | `LogEntry`.`timestamp` | + +#### Methods + +### toString() + +```ts +toString(): string +``` + +###### Returns + +`string` + +## Type Aliases + +### LogEntryLevel + +```ts +type LogEntryLevel: "debug" | "info" | "warn" | "error"; +``` + +Log entry severity levels. + +## Functions + +### defaultBuildLogger() + +```ts +function defaultBuildLogger(options?: object): (logEntry: LogEntry) => void +``` + +Create a default build logger with animated timer display. + +#### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `options`? | `object` | Logger configuration options | +| `options.minLevel`? | `LogEntryLevel` | Minimum log level to display (default: 'info') | + +#### Returns + +`Function` + +Logger function that accepts LogEntry instances + +### Parameters + +| Parameter | Type | +| ------ | ------ | +| `logEntry` | `LogEntry` | + +### Returns + +`void` + +#### Example + +```ts +import { Template, defaultBuildLogger } from 'e2b' + +const template = Template().fromPythonImage() + +await Template.build(template, { + alias: 'my-template', + onBuildLogs: defaultBuildLogger({ minLevel: 'debug' }) +}) +``` diff --git a/docs/sdk-reference/js-sdk/v2.9.0/template-readycmd.mdx b/docs/sdk-reference/js-sdk/v2.9.0/template-readycmd.mdx new file mode 100644 index 0000000..56fb0b7 --- /dev/null +++ b/docs/sdk-reference/js-sdk/v2.9.0/template-readycmd.mdx @@ -0,0 +1,202 @@ +--- +sidebarTitle: "Readycmd" +mode: "center" +--- + +### ReadyCmd + +Class for ready check commands. + +#### Constructors + +```ts +new ReadyCmd(cmd: string): ReadyCmd +``` + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `cmd` | `string` | + +###### Returns + +`ReadyCmd` + +#### Methods + +### getCmd() + +```ts +getCmd(): string +``` + +###### Returns + +`string` + +## Functions + +### waitForFile() + +```ts +function waitForFile(filename: string): ReadyCmd +``` + +Wait for a file to exist. +Uses shell test command to check file existence. + +#### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `filename` | `string` | Path to the file to wait for | + +#### Returns + +`ReadyCmd` + +ReadyCmd that checks for the file + +#### Example + +```ts +import { Template, waitForFile } from 'e2b' + +const template = Template() + .fromBaseImage() + .setStartCmd('./init.sh', waitForFile('/tmp/ready')) +``` + +*** + +### waitForPort() + +```ts +function waitForPort(port: number): ReadyCmd +``` + +Wait for a port to be listening. +Uses `ss` command to check if a port is open and listening. + +#### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `port` | `number` | Port number to wait for | + +#### Returns + +`ReadyCmd` + +ReadyCmd that checks for the port + +#### Example + +```ts +import { Template, waitForPort } from 'e2b' + +const template = Template() + .fromPythonImage() + .setStartCmd('python -m http.server 8000', waitForPort(8000)) +``` + +*** + +### waitForProcess() + +```ts +function waitForProcess(processName: string): ReadyCmd +``` + +Wait for a process with a specific name to be running. +Uses `pgrep` to check if a process exists. + +#### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `processName` | `string` | Name of the process to wait for | + +#### Returns + +`ReadyCmd` + +ReadyCmd that checks for the process + +#### Example + +```ts +import { Template, waitForProcess } from 'e2b' + +const template = Template() + .fromBaseImage() + .setStartCmd('./my-daemon', waitForProcess('my-daemon')) +``` + +*** + +### waitForTimeout() + +```ts +function waitForTimeout(timeout: number): ReadyCmd +``` + +Wait for a specified timeout before considering the sandbox ready. +Uses `sleep` command to wait for a fixed duration. + +#### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `timeout` | `number` | Time to wait in milliseconds (minimum: 1000ms / 1 second) | + +#### Returns + +`ReadyCmd` + +ReadyCmd that waits for the specified duration + +#### Example + +```ts +import { Template, waitForTimeout } from 'e2b' + +const template = Template() + .fromNodeImage() + .setStartCmd('npm start', waitForTimeout(5000)) // Wait 5 seconds +``` + +*** + +### waitForURL() + +```ts +function waitForURL(url: string, statusCode: number): ReadyCmd +``` + +Wait for a URL to return a specific HTTP status code. +Uses `curl` to make HTTP requests and check the response status. + +#### Parameters + +| Parameter | Type | Default value | Description | +| ------ | ------ | ------ | ------ | +| `url` | `string` | `undefined` | URL to check (e.g., 'http://localhost:3000/health') | +| `statusCode` | `number` | `200` | Expected HTTP status code (default: 200) | + +#### Returns + +`ReadyCmd` + +ReadyCmd that checks the URL + +#### Example + +```ts +import { Template, waitForURL } from 'e2b' + +const template = Template() + .fromNodeImage() + .setStartCmd('npm start', waitForURL('http://localhost:3000/health')) +``` diff --git a/docs/sdk-reference/js-sdk/v2.9.0/template.mdx b/docs/sdk-reference/js-sdk/v2.9.0/template.mdx new file mode 100644 index 0000000..5f1eccd --- /dev/null +++ b/docs/sdk-reference/js-sdk/v2.9.0/template.mdx @@ -0,0 +1,2044 @@ +--- +sidebarTitle: "Template" +mode: "center" +--- + +### TemplateBase + +Base class for building E2B sandbox templates. + +#### Implements + +- `TemplateFromImage` +- `TemplateBuilder` +- `TemplateFinal` + +#### Constructors + +```ts +new TemplateBase(options?: TemplateOptions): TemplateBase +``` + +###### Parameters + +| Parameter | Type | +| ------ | ------ | +| `options`? | `TemplateOptions` | + +###### Returns + +`TemplateBase` + +#### Methods + +### addMcpServer() + +```ts +addMcpServer(servers: keyof McpServer | keyof McpServer[]): TemplateBuilder +``` + +Install MCP servers using mcp-gateway. +Note: Requires a base image with mcp-gateway pre-installed (e.g., mcp-gateway). + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `servers` | keyof McpServer \| keyof McpServer[] | MCP server name(s) | + +###### Returns + +`TemplateBuilder` + +###### Throws + +If the base template is not mcp-gateway + +###### Example + +```ts +template.addMcpServer('exa') +template.addMcpServer(['brave', 'firecrawl', 'duckduckgo']) +``` + +###### Implementation of + +`TemplateBuilder`.`addMcpServer` + +### aptInstall() + +```ts +aptInstall(packages: string | string[], options?: object): TemplateBuilder +``` + +Install Debian/Ubuntu packages using apt-get. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `packages` | `string` \| `string`[] | Package name(s) | +| `options`? | `object` | - | +| `options.noInstallRecommends`? | `boolean` | - | + +###### Returns + +`TemplateBuilder` + +###### Example + +```ts +template.aptInstall('vim') +template.aptInstall(['git', 'curl', 'wget']) +template.aptInstall(['vim'], { noInstallRecommends: true }) +``` + +###### Implementation of + +`TemplateBuilder`.`aptInstall` + +### betaDevContainerPrebuild() + +```ts +betaDevContainerPrebuild(devcontainerDirectory: string): TemplateBuilder +``` + +Prebuild a devcontainer from the specified directory. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `devcontainerDirectory` | `string` | Path to the devcontainer directory | + +###### Returns + +`TemplateBuilder` + +###### Example + +```ts +template + .gitClone('https://myrepo.com/project.git', '/my-devcontainer') + .betaDevContainerPrebuild('/my-devcontainer') +``` + +###### Implementation of + +`TemplateBuilder`.`betaDevContainerPrebuild` + +### betaSetDevContainerStart() + +```ts +betaSetDevContainerStart(devcontainerDirectory: string): TemplateFinal +``` + +Start a devcontainer from the specified directory. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `devcontainerDirectory` | `string` | Path to the devcontainer directory | + +###### Returns + +`TemplateFinal` + +###### Example + +```ts +template + .gitClone('https://myrepo.com/project.git', '/my-devcontainer') + .startDevcontainer('/my-devcontainer') + +// Prebuild and start +template + .gitClone('https://myrepo.com/project.git', '/my-devcontainer') + .betaDevContainerPrebuild('/my-devcontainer') + // Other instructions... + .betaSetDevContainerStart('/my-devcontainer') +``` + +###### Implementation of + +`TemplateBuilder`.`betaSetDevContainerStart` + +### bunInstall() + +```ts +bunInstall(packages?: string | string[], options?: object): TemplateBuilder +``` + +Install Bun packages using bun. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `packages`? | `string` \| `string`[] | Package name(s) or undefined for package.json | +| `options`? | `object` | Install options | +| `options.dev`? | `boolean` | - | +| `options.g`? | `boolean` | - | + +###### Returns + +`TemplateBuilder` + +###### Example + +```ts +template.bunInstall('express') +template.bunInstall(['lodash', 'axios']) +template.bunInstall('tsx', { g: true }) +template.bunInstall('typescript', { dev: true }) +template.bunInstall() // Installs from package.json +``` + +###### Implementation of + +`TemplateBuilder`.`bunInstall` + +### copy() + +```ts +copy( + src: PathLike | PathLike[], + dest: PathLike, + options?: object): TemplateBuilder +``` + +Copy files or directories into the template. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `src` | `PathLike` \| `PathLike`[] | Source path(s) | +| `dest` | `PathLike` | Destination path | +| `options`? | `object` | Copy options | +| `options.forceUpload`? | `true` | - | +| `options.mode`? | `number` | - | +| `options.resolveSymlinks`? | `boolean` | - | +| `options.user`? | `string` | - | + +###### Returns + +`TemplateBuilder` + +###### Example + +```ts +template.copy('requirements.txt', '/home/user/') +template.copy(['app.ts', 'config.ts'], '/app/', { mode: 0o755 }) +``` + +###### Implementation of + +`TemplateBuilder`.`copy` + +### copyItems() + +```ts +copyItems(items: CopyItem[]): TemplateBuilder +``` + +Copy multiple items with individual options. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `items` | `CopyItem`[] | Array of copy items | + +###### Returns + +`TemplateBuilder` + +###### Example + +```ts +template.copyItems([ + { src: 'app.ts', dest: '/app/' }, + { src: 'config.ts', dest: '/app/', mode: 0o644 } +]) +``` + +###### Implementation of + +`TemplateBuilder`.`copyItems` + +### fromAWSRegistry() + +```ts +fromAWSRegistry(image: string, credentials: object): TemplateBuilder +``` + +Start from a Docker image in AWS ECR. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `image` | `string` | Full ECR image path | +| `credentials` | `object` | AWS credentials | +| `credentials.accessKeyId` | `string` | - | +| `credentials.region` | `string` | - | +| `credentials.secretAccessKey` | `string` | - | + +###### Returns + +`TemplateBuilder` + +###### Example + +```ts +Template().fromAWSRegistry( + '123456789.dkr.ecr.us-west-2.amazonaws.com/myimage:latest', + { + accessKeyId: 'AKIA...', + secretAccessKey: '...', + region: 'us-west-2' + } +) +``` + +###### Implementation of + +`TemplateFromImage.fromAWSRegistry` + +### fromBaseImage() + +```ts +fromBaseImage(): TemplateBuilder +``` + +Start from E2B's default base image (e2bdev/base:latest). + +###### Returns + +`TemplateBuilder` + +###### Example + +```ts +Template().fromBaseImage() +``` + +###### Implementation of + +`TemplateFromImage.fromBaseImage` + +### fromBunImage() + +```ts +fromBunImage(variant: string): TemplateBuilder +``` + +Start from a Bun-based Docker image. + +###### Parameters + +| Parameter | Type | Default value | Description | +| ------ | ------ | ------ | ------ | +| `variant` | `string` | `'latest'` | Bun variant (default: 'latest') | + +###### Returns + +`TemplateBuilder` + +###### Example + +```ts +Template().fromBunImage('1.3') +``` + +###### Implementation of + +`TemplateFromImage.fromBunImage` + +### fromDebianImage() + +```ts +fromDebianImage(variant: string): TemplateBuilder +``` + +Start from a Debian-based Docker image. + +###### Parameters + +| Parameter | Type | Default value | Description | +| ------ | ------ | ------ | ------ | +| `variant` | `string` | `'stable'` | Debian variant (default: 'stable') | + +###### Returns + +`TemplateBuilder` + +###### Example + +```ts +Template().fromDebianImage('bookworm') +``` + +###### Implementation of + +`TemplateFromImage.fromDebianImage` + +### fromDockerfile() + +```ts +fromDockerfile(dockerfileContentOrPath: string): TemplateBuilder +``` + +Parse a Dockerfile and convert it to Template SDK format. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `dockerfileContentOrPath` | `string` | Dockerfile content or path | + +###### Returns + +`TemplateBuilder` + +###### Example + +```ts +Template().fromDockerfile('Dockerfile') +Template().fromDockerfile('FROM python:3\nRUN pip install numpy') +``` + +###### Implementation of + +`TemplateFromImage.fromDockerfile` + +### fromGCPRegistry() + +```ts +fromGCPRegistry(image: string, credentials: object): TemplateBuilder +``` + +Start from a Docker image in Google Container Registry. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `image` | `string` | Full GCR/GAR image path | +| `credentials` | `object` | GCP service account credentials | +| `credentials.serviceAccountJSON` | `string` \| `object` | - | + +###### Returns + +`TemplateBuilder` + +###### Example + +```ts +Template().fromGCPRegistry( + 'gcr.io/myproject/myimage:latest', + { serviceAccountJSON: 'path/to/service-account.json' } +) +``` + +###### Implementation of + +`TemplateFromImage.fromGCPRegistry` + +### fromImage() + +```ts +fromImage(baseImage: string, credentials?: object): TemplateBuilder +``` + +Start from a custom Docker image. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `baseImage` | `string` | Docker image name | +| `credentials`? | `object` | Optional credentials for private registries | +| `credentials.password`? | `string` | - | +| `credentials.username`? | `string` | - | + +###### Returns + +`TemplateBuilder` + +###### Example + +```ts +Template().fromImage('python:3') + +// With credentials (optional) +Template().fromImage('myregistry.com/myimage:latest', { + username: 'user', + password: 'pass' +}) +``` + +###### Implementation of + +`TemplateFromImage.fromImage` + +### fromNodeImage() + +```ts +fromNodeImage(variant: string): TemplateBuilder +``` + +Start from a Node.js-based Docker image. + +###### Parameters + +| Parameter | Type | Default value | Description | +| ------ | ------ | ------ | ------ | +| `variant` | `string` | `'lts'` | Node.js variant (default: 'lts') | + +###### Returns + +`TemplateBuilder` + +###### Example + +```ts +Template().fromNodeImage('24') +``` + +###### Implementation of + +`TemplateFromImage.fromNodeImage` + +### fromPythonImage() + +```ts +fromPythonImage(version: string): TemplateBuilder +``` + +Start from a Python-based Docker image. + +###### Parameters + +| Parameter | Type | Default value | Description | +| ------ | ------ | ------ | ------ | +| `version` | `string` | `'3'` | Python version (default: '3') | + +###### Returns + +`TemplateBuilder` + +###### Example + +```ts +Template().fromPythonImage('3') +``` + +###### Implementation of + +`TemplateFromImage.fromPythonImage` + +### fromTemplate() + +```ts +fromTemplate(template: string): TemplateBuilder +``` + +Start from an existing E2B template. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `template` | `string` | E2B template ID or alias | + +###### Returns + +`TemplateBuilder` + +###### Example + +```ts +Template().fromTemplate('my-base-template') +``` + +###### Implementation of + +`TemplateFromImage.fromTemplate` + +### fromUbuntuImage() + +```ts +fromUbuntuImage(variant: string): TemplateBuilder +``` + +Start from an Ubuntu-based Docker image. + +###### Parameters + +| Parameter | Type | Default value | Description | +| ------ | ------ | ------ | ------ | +| `variant` | `string` | `'latest'` | Ubuntu variant (default: 'latest') | + +###### Returns + +`TemplateBuilder` + +###### Example + +```ts +Template().fromUbuntuImage('24.04') +``` + +###### Implementation of + +`TemplateFromImage.fromUbuntuImage` + +### gitClone() + +```ts +gitClone( + url: string, + path?: PathLike, + options?: object): TemplateBuilder +``` + +Clone a Git repository. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `url` | `string` | Repository URL | +| `path`? | `PathLike` | Optional destination path | +| `options`? | `object` | Clone options | +| `options.branch`? | `string` | - | +| `options.depth`? | `number` | - | +| `options.user`? | `string` | - | + +###### Returns + +`TemplateBuilder` + +###### Example + +```ts +template.gitClone('https://github.com/user/repo.git', '/app/repo') +template.gitClone('https://github.com/user/repo.git', undefined, { + branch: 'main', + depth: 1 +}) +template.gitClone('https://github.com/user/repo.git', '/app/repo', { + user: 'root' +}) +``` + +###### Implementation of + +`TemplateBuilder`.`gitClone` + +### makeDir() + +```ts +makeDir(path: PathLike | PathLike[], options?: object): TemplateBuilder +``` + +Create directories. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `path` | `PathLike` \| `PathLike`[] | Directory path(s) | +| `options`? | `object` | Directory options | +| `options.mode`? | `number` | - | +| `options.user`? | `string` | - | + +###### Returns + +`TemplateBuilder` + +###### Example + +```ts +template.makeDir('/app/data', { mode: 0o755 }) +template.makeDir(['/app/logs', '/app/cache']) +template.makeDir('/app/data', { mode: 0o755, user: 'root' }) +``` + +###### Implementation of + +`TemplateBuilder`.`makeDir` + +### makeSymlink() + +```ts +makeSymlink( + src: PathLike, + dest: PathLike, + options?: object): TemplateBuilder +``` + +Create a symbolic link. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `src` | `PathLike` | Source path (target) | +| `dest` | `PathLike` | Destination path (symlink location) | +| `options`? | `object` | Symlink options | +| `options.force`? | `boolean` | - | +| `options.user`? | `string` | - | + +###### Returns + +`TemplateBuilder` + +###### Example + +```ts +template.makeSymlink('/usr/bin/python3', '/usr/bin/python') +template.makeSymlink('/usr/bin/python3', '/usr/bin/python', { user: 'root' }) +template.makeSymlink('/usr/bin/python3', '/usr/bin/python', { force: true }) +``` + +###### Implementation of + +`TemplateBuilder`.`makeSymlink` + +### npmInstall() + +```ts +npmInstall(packages?: string | string[], options?: object): TemplateBuilder +``` + +Install Node.js packages using npm. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `packages`? | `string` \| `string`[] | Package name(s) or undefined for package.json | +| `options`? | `object` | Install options | +| `options.dev`? | `boolean` | - | +| `options.g`? | `boolean` | - | + +###### Returns + +`TemplateBuilder` + +###### Example + +```ts +template.npmInstall('express') +template.npmInstall(['lodash', 'axios']) +template.npmInstall('tsx', { g: true }) +template.npmInstall('typescript', { dev: true }) +template.npmInstall() // Installs from package.json +``` + +###### Implementation of + +`TemplateBuilder`.`npmInstall` + +### pipInstall() + +```ts +pipInstall(packages?: string | string[], options?: object): TemplateBuilder +``` + +Install Python packages using pip. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `packages`? | `string` \| `string`[] | Package name(s) or undefined for current directory | +| `options`? | `object` | Install options | +| `options.g`? | `boolean` | Install globally as root (default: true). Set to false for user-only installation with --user flag | + +###### Returns + +`TemplateBuilder` + +###### Example + +```ts +template.pipInstall('numpy') // Installs globally (default) +template.pipInstall(['pandas', 'scikit-learn']) +template.pipInstall('numpy', { g: false }) // Install for user only +template.pipInstall() // Installs from current directory +``` + +###### Implementation of + +`TemplateBuilder`.`pipInstall` + +### remove() + +```ts +remove(path: PathLike | PathLike[], options?: object): TemplateBuilder +``` + +Remove files or directories. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `path` | `PathLike` \| `PathLike`[] | Path(s) to remove | +| `options`? | `object` | Remove options | +| `options.force`? | `boolean` | - | +| `options.recursive`? | `boolean` | - | +| `options.user`? | `string` | - | + +###### Returns + +`TemplateBuilder` + +###### Example + +```ts +template.remove('/tmp/cache', { recursive: true, force: true }) +template.remove('/tmp/cache', { recursive: true, force: true, user: 'root' }) +``` + +###### Implementation of + +`TemplateBuilder`.`remove` + +### rename() + +```ts +rename( + src: PathLike, + dest: PathLike, + options?: object): TemplateBuilder +``` + +Rename or move a file or directory. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `src` | `PathLike` | Source path | +| `dest` | `PathLike` | Destination path | +| `options`? | `object` | Rename options | +| `options.force`? | `boolean` | - | +| `options.user`? | `string` | - | + +###### Returns + +`TemplateBuilder` + +###### Example + +```ts +template.rename('/tmp/old.txt', '/tmp/new.txt') +template.rename('/tmp/old.txt', '/tmp/new.txt', { user: 'root' }) +``` + +###### Implementation of + +`TemplateBuilder`.`rename` + +### runCmd() + +###### runCmd(command, options) + +```ts +runCmd(command: string, options?: object): TemplateBuilder +``` + +Run a shell command. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `command` | `string` | Command string | +| `options`? | `object` | Command options | +| `options.user`? | `string` | - | + +###### Returns + +`TemplateBuilder` + +###### Example + +```ts +template.runCmd('apt-get update') +template.runCmd(['pip install numpy', 'pip install pandas']) +template.runCmd('apt-get install vim', { user: 'root' }) +``` + +###### Implementation of + +`TemplateBuilder`.`runCmd` + +###### runCmd(commands, options) + +```ts +runCmd(commands: string[], options?: object): TemplateBuilder +``` + +Run a shell command. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `commands` | `string`[] | - | +| `options`? | `object` | Command options | +| `options.user`? | `string` | - | + +###### Returns + +`TemplateBuilder` + +###### Example + +```ts +template.runCmd('apt-get update') +template.runCmd(['pip install numpy', 'pip install pandas']) +template.runCmd('apt-get install vim', { user: 'root' }) +``` + +###### Implementation of + +`TemplateBuilder`.`runCmd` + +### setEnvs() + +```ts +setEnvs(envs: Record): TemplateBuilder +``` + +Set environment variables. +Note: Environment variables defined here are available only during template build. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `envs` | `Record`\<`string`, `string`\> | Environment variables | + +###### Returns + +`TemplateBuilder` + +###### Example + +```ts +template.setEnvs({ NODE_ENV: 'production', PORT: '8080' }) +``` + +###### Implementation of + +`TemplateBuilder`.`setEnvs` + +### setReadyCmd() + +```ts +setReadyCmd(readyCommand: string | ReadyCmd): TemplateFinal +``` + +Set or update the ready check command. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `readyCommand` | `string` \| `ReadyCmd` | Command to check readiness | + +###### Returns + +`TemplateFinal` + +###### Example + +```ts +// Using a string command +template.setReadyCmd('curl http://localhost:8000/health') + +// Using ReadyCmd helpers +import { waitForPort, waitForFile, waitForProcess } from 'e2b' + +template.setReadyCmd(waitForPort(3000)) + +template.setReadyCmd(waitForFile('/tmp/ready')) + +template.setReadyCmd(waitForProcess('nginx')) +``` + +###### Implementation of + +`TemplateBuilder`.`setReadyCmd` + +### setStartCmd() + +```ts +setStartCmd(startCommand: string, readyCommand: string | ReadyCmd): TemplateFinal +``` + +Set the start command and ready check. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `startCommand` | `string` | Command to run on startup | +| `readyCommand` | `string` \| `ReadyCmd` | Command to check readiness | + +###### Returns + +`TemplateFinal` + +###### Example + +```ts +// Using a string command +template.setStartCmd( + 'node app.js', + 'curl http://localhost:8000/health' +) + +// Using ReadyCmd helpers +import { waitForPort, waitForURL } from 'e2b' + +template.setStartCmd( + 'python -m http.server 8000', + waitForPort(8000) +) + +template.setStartCmd( + 'npm start', + waitForURL('http://localhost:3000/health', 200) +) +``` + +###### Implementation of + +`TemplateBuilder`.`setStartCmd` + +### setUser() + +```ts +setUser(user: string): TemplateBuilder +``` + +Set the user for subsequent commands. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `user` | `string` | Username | + +###### Returns + +`TemplateBuilder` + +###### Example + +```ts +template.setUser('root') +``` + +###### Implementation of + +`TemplateBuilder`.`setUser` + +### setWorkdir() + +```ts +setWorkdir(workdir: PathLike): TemplateBuilder +``` + +Set the working directory. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `workdir` | `PathLike` | Working directory path | + +###### Returns + +`TemplateBuilder` + +###### Example + +```ts +template.setWorkdir('/app') +``` + +###### Implementation of + +`TemplateBuilder`.`setWorkdir` + +### skipCache() + +```ts +skipCache(): this +``` + +Skip cache for all subsequent build instructions from this point. + +###### Returns + +`this` + +###### Example + +```ts +Template().skipCache().fromPythonImage('3') +``` + +###### Implementation of + +`TemplateBuilder`.`skipCache` + +### build() + +```ts +static build(template: TemplateClass, options: BuildOptions): Promise +``` + +Build and deploy a template to E2B infrastructure. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `template` | `TemplateClass` | The template to build | +| `options` | `BuildOptions` | Build configuration options | + +###### Returns + +`Promise`\<`BuildInfo`\> + +###### Example + +```ts +const template = Template().fromPythonImage('3') +await Template.build(template, { + alias: 'my-python-env', + cpuCount: 2, + memoryMB: 1024 +}) +``` + +### buildInBackground() + +```ts +static buildInBackground(template: TemplateClass, options: BuildOptions): Promise +``` + +Build and deploy a template to E2B infrastructure. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `template` | `TemplateClass` | The template to build | +| `options` | `BuildOptions` | Build configuration options | + +###### Returns + +`Promise`\<`BuildInfo`\> + +###### Example + +```ts +const template = Template().fromPythonImage('3') +const data = await Template.buildInBackground(template, { + alias: 'my-python-env', + cpuCount: 2, + memoryMB: 1024 +}) +``` + +### getBuildStatus() + +```ts +static getBuildStatus(data: Pick, options?: GetBuildStatusOptions): Promise +``` + +Get the status of a build. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `data` | `Pick`\<`BuildInfo`, `"templateId"` \| `"buildId"`\> | Build identifiers | +| `options`? | `GetBuildStatusOptions` | Authentication options | + +###### Returns + +`Promise`\<`object`\> + +| Name | Type | Description | +| ------ | ------ | ------ | +| `buildID` | `string` | **Description** Identifier of the build | +| `logEntries` | `object`[] | **Description** Build logs structured **Default** `[]` | +| `logs` | `string`[] | **Description** Build logs **Default** `[]` | +| `reason`? | `object` | - | +| `reason.logEntries`? | `object`[] | **Description** Log entries related to the status reason **Default** `[]` | +| `reason.message` | `string` | **Description** Message with the status reason, currently reporting only for error status | +| `reason.step`? | `string` | **Description** Step that failed | +| `status` | `"error"` \| `"ready"` \| `"building"` \| `"waiting"` | - | +| `templateID` | `string` | **Description** Identifier of the template | + +###### Example + +```ts +const status = await Template.getBuildStatus(data, { logsOffset: 0 }) +``` + +### toDockerfile() + +```ts +static toDockerfile(template: TemplateClass): string +``` + +Convert a template to Dockerfile format. +Note: Templates based on other E2B templates cannot be converted to Dockerfile. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `template` | `TemplateClass` | The template to convert | + +###### Returns + +`string` + +Dockerfile string representation + +###### Throws + +Error if the template is based on another E2B template + +### toJSON() + +```ts +static toJSON(template: TemplateClass, computeHashes: boolean): Promise +``` + +Convert a template to JSON representation. + +###### Parameters + +| Parameter | Type | Default value | Description | +| ------ | ------ | ------ | ------ | +| `template` | `TemplateClass` | `undefined` | The template to convert | +| `computeHashes` | `boolean` | `true` | Whether to compute file hashes for cache invalidation | + +###### Returns + +`Promise`\<`string`\> + +JSON string representation of the template + +## Interfaces + +### TemplateBuilder + +Main builder state for constructing templates. +Provides methods for customizing the template environment. + +#### Methods + +### addMcpServer() + +```ts +addMcpServer(servers: keyof McpServer | keyof McpServer[]): TemplateBuilder +``` + +Install MCP servers using mcp-gateway. +Note: Requires a base image with mcp-gateway pre-installed (e.g., mcp-gateway). + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `servers` | keyof McpServer \| keyof McpServer[] | MCP server name(s) | + +###### Returns + +`TemplateBuilder` + +###### Throws + +If the base template is not mcp-gateway + +###### Example + +```ts +template.addMcpServer('exa') +template.addMcpServer(['brave', 'firecrawl', 'duckduckgo']) +``` + +### aptInstall() + +```ts +aptInstall(packages: string | string[], options?: object): TemplateBuilder +``` + +Install Debian/Ubuntu packages using apt-get. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `packages` | `string` \| `string`[] | Package name(s) | +| `options`? | `object` | - | +| `options.noInstallRecommends`? | `boolean` | - | + +###### Returns + +`TemplateBuilder` + +###### Example + +```ts +template.aptInstall('vim') +template.aptInstall(['git', 'curl', 'wget']) +template.aptInstall(['vim'], { noInstallRecommends: true }) +``` + +### betaDevContainerPrebuild() + +```ts +betaDevContainerPrebuild(devcontainerDirectory: string): TemplateBuilder +``` + +Prebuild a devcontainer from the specified directory. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `devcontainerDirectory` | `string` | Path to the devcontainer directory | + +###### Returns + +`TemplateBuilder` + +###### Example + +```ts +template + .gitClone('https://myrepo.com/project.git', '/my-devcontainer') + .betaDevContainerPrebuild('/my-devcontainer') +``` + +### betaSetDevContainerStart() + +```ts +betaSetDevContainerStart(devcontainerDirectory: string): TemplateFinal +``` + +Start a devcontainer from the specified directory. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `devcontainerDirectory` | `string` | Path to the devcontainer directory | + +###### Returns + +`TemplateFinal` + +###### Example + +```ts +template + .gitClone('https://myrepo.com/project.git', '/my-devcontainer') + .startDevcontainer('/my-devcontainer') + +// Prebuild and start +template + .gitClone('https://myrepo.com/project.git', '/my-devcontainer') + .betaDevContainerPrebuild('/my-devcontainer') + // Other instructions... + .betaSetDevContainerStart('/my-devcontainer') +``` + +### bunInstall() + +```ts +bunInstall(packages?: string | string[], options?: object): TemplateBuilder +``` + +Install Bun packages using bun. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `packages`? | `string` \| `string`[] | Package name(s) or undefined for package.json | +| `options`? | `object` | Install options | +| `options.dev`? | `boolean` | - | +| `options.g`? | `boolean` | - | + +###### Returns + +`TemplateBuilder` + +###### Example + +```ts +template.bunInstall('express') +template.bunInstall(['lodash', 'axios']) +template.bunInstall('tsx', { g: true }) +template.bunInstall('typescript', { dev: true }) +template.bunInstall() // Installs from package.json +``` + +### copy() + +```ts +copy( + src: PathLike | PathLike[], + dest: PathLike, + options?: object): TemplateBuilder +``` + +Copy files or directories into the template. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `src` | `PathLike` \| `PathLike`[] | Source path(s) | +| `dest` | `PathLike` | Destination path | +| `options`? | `object` | Copy options | +| `options.forceUpload`? | `true` | - | +| `options.mode`? | `number` | - | +| `options.resolveSymlinks`? | `boolean` | - | +| `options.user`? | `string` | - | + +###### Returns + +`TemplateBuilder` + +###### Example + +```ts +template.copy('requirements.txt', '/home/user/') +template.copy(['app.ts', 'config.ts'], '/app/', { mode: 0o755 }) +``` + +### copyItems() + +```ts +copyItems(items: CopyItem[]): TemplateBuilder +``` + +Copy multiple items with individual options. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `items` | `CopyItem`[] | Array of copy items | + +###### Returns + +`TemplateBuilder` + +###### Example + +```ts +template.copyItems([ + { src: 'app.ts', dest: '/app/' }, + { src: 'config.ts', dest: '/app/', mode: 0o644 } +]) +``` + +### gitClone() + +```ts +gitClone( + url: string, + path?: PathLike, + options?: object): TemplateBuilder +``` + +Clone a Git repository. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `url` | `string` | Repository URL | +| `path`? | `PathLike` | Optional destination path | +| `options`? | `object` | Clone options | +| `options.branch`? | `string` | - | +| `options.depth`? | `number` | - | +| `options.user`? | `string` | - | + +###### Returns + +`TemplateBuilder` + +###### Example + +```ts +template.gitClone('https://github.com/user/repo.git', '/app/repo') +template.gitClone('https://github.com/user/repo.git', undefined, { + branch: 'main', + depth: 1 +}) +template.gitClone('https://github.com/user/repo.git', '/app/repo', { + user: 'root' +}) +``` + +### makeDir() + +```ts +makeDir(path: PathLike | PathLike[], options?: object): TemplateBuilder +``` + +Create directories. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `path` | `PathLike` \| `PathLike`[] | Directory path(s) | +| `options`? | `object` | Directory options | +| `options.mode`? | `number` | - | +| `options.user`? | `string` | - | + +###### Returns + +`TemplateBuilder` + +###### Example + +```ts +template.makeDir('/app/data', { mode: 0o755 }) +template.makeDir(['/app/logs', '/app/cache']) +template.makeDir('/app/data', { mode: 0o755, user: 'root' }) +``` + +### makeSymlink() + +```ts +makeSymlink( + src: PathLike, + dest: PathLike, + options?: object): TemplateBuilder +``` + +Create a symbolic link. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `src` | `PathLike` | Source path (target) | +| `dest` | `PathLike` | Destination path (symlink location) | +| `options`? | `object` | Symlink options | +| `options.force`? | `boolean` | - | +| `options.user`? | `string` | - | + +###### Returns + +`TemplateBuilder` + +###### Example + +```ts +template.makeSymlink('/usr/bin/python3', '/usr/bin/python') +template.makeSymlink('/usr/bin/python3', '/usr/bin/python', { user: 'root' }) +template.makeSymlink('/usr/bin/python3', '/usr/bin/python', { force: true }) +``` + +### npmInstall() + +```ts +npmInstall(packages?: string | string[], options?: object): TemplateBuilder +``` + +Install Node.js packages using npm. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `packages`? | `string` \| `string`[] | Package name(s) or undefined for package.json | +| `options`? | `object` | Install options | +| `options.dev`? | `boolean` | - | +| `options.g`? | `boolean` | - | + +###### Returns + +`TemplateBuilder` + +###### Example + +```ts +template.npmInstall('express') +template.npmInstall(['lodash', 'axios']) +template.npmInstall('tsx', { g: true }) +template.npmInstall('typescript', { dev: true }) +template.npmInstall() // Installs from package.json +``` + +### pipInstall() + +```ts +pipInstall(packages?: string | string[], options?: object): TemplateBuilder +``` + +Install Python packages using pip. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `packages`? | `string` \| `string`[] | Package name(s) or undefined for current directory | +| `options`? | `object` | Install options | +| `options.g`? | `boolean` | Install globally as root (default: true). Set to false for user-only installation with --user flag | + +###### Returns + +`TemplateBuilder` + +###### Example + +```ts +template.pipInstall('numpy') // Installs globally (default) +template.pipInstall(['pandas', 'scikit-learn']) +template.pipInstall('numpy', { g: false }) // Install for user only +template.pipInstall() // Installs from current directory +``` + +### remove() + +```ts +remove(path: PathLike | PathLike[], options?: object): TemplateBuilder +``` + +Remove files or directories. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `path` | `PathLike` \| `PathLike`[] | Path(s) to remove | +| `options`? | `object` | Remove options | +| `options.force`? | `boolean` | - | +| `options.recursive`? | `boolean` | - | +| `options.user`? | `string` | - | + +###### Returns + +`TemplateBuilder` + +###### Example + +```ts +template.remove('/tmp/cache', { recursive: true, force: true }) +template.remove('/tmp/cache', { recursive: true, force: true, user: 'root' }) +``` + +### rename() + +```ts +rename( + src: PathLike, + dest: PathLike, + options?: object): TemplateBuilder +``` + +Rename or move a file or directory. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `src` | `PathLike` | Source path | +| `dest` | `PathLike` | Destination path | +| `options`? | `object` | Rename options | +| `options.force`? | `boolean` | - | +| `options.user`? | `string` | - | + +###### Returns + +`TemplateBuilder` + +###### Example + +```ts +template.rename('/tmp/old.txt', '/tmp/new.txt') +template.rename('/tmp/old.txt', '/tmp/new.txt', { user: 'root' }) +``` + +### runCmd() + +###### runCmd(command, options) + +```ts +runCmd(command: string, options?: object): TemplateBuilder +``` + +Run a shell command. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `command` | `string` | Command string | +| `options`? | `object` | Command options | +| `options.user`? | `string` | - | + +###### Returns + +`TemplateBuilder` + +###### Example + +```ts +template.runCmd('apt-get update') +template.runCmd(['pip install numpy', 'pip install pandas']) +template.runCmd('apt-get install vim', { user: 'root' }) +``` + +###### runCmd(commands, options) + +```ts +runCmd(commands: string[], options?: object): TemplateBuilder +``` + +Run multiple shell commands. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `commands` | `string`[] | Array of command strings | +| `options`? | `object` | Command options | +| `options.user`? | `string` | - | + +###### Returns + +`TemplateBuilder` + +###### runCmd(commandOrCommands, options) + +```ts +runCmd(commandOrCommands: string | string[], options?: object): TemplateBuilder +``` + +Run command(s). + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `commandOrCommands` | `string` \| `string`[] | Command or commands | +| `options`? | `object` | Command options | +| `options.user`? | `string` | - | + +###### Returns + +`TemplateBuilder` + +### setEnvs() + +```ts +setEnvs(envs: Record): TemplateBuilder +``` + +Set environment variables. +Note: Environment variables defined here are available only during template build. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `envs` | `Record`\<`string`, `string`\> | Environment variables | + +###### Returns + +`TemplateBuilder` + +###### Example + +```ts +template.setEnvs({ NODE_ENV: 'production', PORT: '8080' }) +``` + +### setReadyCmd() + +```ts +setReadyCmd(readyCommand: string | ReadyCmd): TemplateFinal +``` + +Set or update the ready check command. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `readyCommand` | `string` \| `ReadyCmd` | Command to check readiness | + +###### Returns + +`TemplateFinal` + +###### Example + +```ts +// Using a string command +template.setReadyCmd('curl http://localhost:8000/health') + +// Using ReadyCmd helpers +import { waitForPort, waitForFile, waitForProcess } from 'e2b' + +template.setReadyCmd(waitForPort(3000)) + +template.setReadyCmd(waitForFile('/tmp/ready')) + +template.setReadyCmd(waitForProcess('nginx')) +``` + +### setStartCmd() + +```ts +setStartCmd(startCommand: string, readyCommand: string | ReadyCmd): TemplateFinal +``` + +Set the start command and ready check. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `startCommand` | `string` | Command to run on startup | +| `readyCommand` | `string` \| `ReadyCmd` | Command to check readiness | + +###### Returns + +`TemplateFinal` + +###### Example + +```ts +// Using a string command +template.setStartCmd( + 'node app.js', + 'curl http://localhost:8000/health' +) + +// Using ReadyCmd helpers +import { waitForPort, waitForURL } from 'e2b' + +template.setStartCmd( + 'python -m http.server 8000', + waitForPort(8000) +) + +template.setStartCmd( + 'npm start', + waitForURL('http://localhost:3000/health', 200) +) +``` + +### setUser() + +```ts +setUser(user: string): TemplateBuilder +``` + +Set the user for subsequent commands. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `user` | `string` | Username | + +###### Returns + +`TemplateBuilder` + +###### Example + +```ts +template.setUser('root') +``` + +### setWorkdir() + +```ts +setWorkdir(workdir: PathLike): TemplateBuilder +``` + +Set the working directory. + +###### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `workdir` | `PathLike` | Working directory path | + +###### Returns + +`TemplateBuilder` + +###### Example + +```ts +template.setWorkdir('/app') +``` + +### skipCache() + +```ts +skipCache(): this +``` + +Skip cache for all subsequent build instructions from this point. + +###### Returns + +`this` + +###### Example + +```ts +template.skipCache().runCmd('apt-get update') +``` + +## Type Aliases + +### BuildInfo + +```ts +type BuildInfo: object; +``` + +Information about a built template. + +#### Type declaration + +| Name | Type | +| ------ | ------ | +| `alias` | `string` | +| `buildId` | `string` | +| `templateId` | `string` | + +*** + +### BuildOptions + +```ts +type BuildOptions: AuthOptions & BasicBuildOptions; +``` + +Options for building a template with authentication. + +*** + +### CopyItem + +```ts +type CopyItem: object; +``` + +Configuration for a single file/directory copy operation. + +#### Type declaration + +| Name | Type | +| ------ | ------ | +| `dest` | `PathLike` | +| `forceUpload`? | `true` | +| `mode`? | `number` | +| `resolveSymlinks`? | `boolean` | +| `src` | `PathLike` \| `PathLike`[] | +| `user`? | `string` | + +*** + +### GetBuildStatusOptions + +```ts +type GetBuildStatusOptions: AuthOptions & object; +``` + +Response from getting build status. + +#### Type declaration + +| Name | Type | +| ------ | ------ | +| `logsOffset`? | `number` | + +*** + +### McpServerName + +```ts +type McpServerName: keyof McpServer; +``` + +MCP server names that can be installed. + +*** + +### TemplateClass + +```ts +type TemplateClass: TemplateBuilder | TemplateFinal; +``` + +Type representing a template in any state (builder or final). + +## Functions + +### Template() + +```ts +function Template(options?: TemplateOptions): TemplateFromImage +``` + +Create a new E2B template builder instance. + +#### Parameters + +| Parameter | Type | Description | +| ------ | ------ | ------ | +| `options`? | `TemplateOptions` | Optional configuration for the template builder | + +#### Returns + +`TemplateFromImage` + +A new template builder instance + +#### Example + +```ts +import { Template } from 'e2b' + +const template = Template() + .fromPythonImage('3') + .copy('requirements.txt', '/app/') + .pipInstall() + +await Template.build(template, { alias: 'my-python-app' }) +``` diff --git a/docs/sdk-reference/python-sdk/1.0.0/exceptions.mdx b/docs/sdk-reference/python-sdk/1.0.0/exceptions.mdx new file mode 100644 index 0000000..fa9912e --- /dev/null +++ b/docs/sdk-reference/python-sdk/1.0.0/exceptions.mdx @@ -0,0 +1,87 @@ +--- +sidebarTitle: "Exceptions" +mode: "center" +--- + + + + + + +## SandboxException + +```python +class SandboxException(Exception) +``` + +Base class for all sandbox errors. + +Raised when a general sandbox exception occurs. + + + +## TimeoutException + +```python +class TimeoutException(SandboxException) +``` + +Raised when a timeout occurs. + +The [unavailable] exception type is caused by sandbox timeout. + +The [canceled] exception type is caused by exceeding request timeout. + +The [deadline_exceeded] exception type is caused by exceeding the timeout for process, watch, etc. + +The [unknown] exception type is sometimes caused by the sandbox timeout when the request is not processed correctly. + + + +## InvalidArgumentException + +```python +class InvalidArgumentException(SandboxException) +``` + +Raised when an invalid argument is provided. + + + +## NotEnoughSpaceException + +```python +class NotEnoughSpaceException(SandboxException) +``` + +Raised when there is not enough disk space. + + + +## NotFoundException + +```python +class NotFoundException(SandboxException) +``` + +Raised when a resource is not found. + + + +## AuthenticationException + +```python +class AuthenticationException(SandboxException) +``` + +Raised when authentication fails. + + + +## TemplateException + +```python +class TemplateException(SandboxException) +``` + +Exception raised when the template uses old envd version. It isn't compatible with the new SDK. diff --git a/docs/sdk-reference/python-sdk/1.0.0/sandbox_async.mdx b/docs/sdk-reference/python-sdk/1.0.0/sandbox_async.mdx new file mode 100644 index 0000000..b0bf4ab --- /dev/null +++ b/docs/sdk-reference/python-sdk/1.0.0/sandbox_async.mdx @@ -0,0 +1,985 @@ +--- +sidebarTitle: "Sandbox Async" +mode: "center" +--- + + + + + + +## AsyncWatchHandle + +```python +class AsyncWatchHandle() +``` + +Handle for watching a directory in the sandbox filesystem. + +Use `.stop()` to stop watching the directory. + + + +### stop + +```python +async def stop() +``` + +Stop watching the directory. + + + + + + +## Filesystem + +```python +class Filesystem() +``` + +Module for interacting with the filesystem in the sandbox. + + + +### read + +```python +@overload +async def read(path: str, + format: Literal["text"] = "text", + user: Username = "user", + request_timeout: Optional[float] = None) -> str +``` + +Read file content as a `str`. + +**Arguments**: + +- `path`: Path to the file +- `user`: Run the operation as this user +- `format`: Format of the file content—`text` by default +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +File content as a `str` + + + +### read + +```python +@overload +async def read(path: str, + format: Literal["bytes"], + user: Username = "user", + request_timeout: Optional[float] = None) -> bytearray +``` + +Read file content as a `bytearray`. + +**Arguments**: + +- `path`: Path to the file +- `user`: Run the operation as this user +- `format`: Format of the file content—`bytes` +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +File content as a `bytearray` + + + +### read + +```python +@overload +async def read( + path: str, + format: Literal["stream"], + user: Username = "user", + request_timeout: Optional[float] = None) -> AsyncIterator[bytes] +``` + +Read file content as a `AsyncIterator[bytes]`. + +**Arguments**: + +- `path`: Path to the file +- `user`: Run the operation as this user +- `format`: Format of the file content—`stream` +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +File content as an `AsyncIterator[bytes]` + + + +### write + +```python +async def write(path: str, + data: Union[str, bytes, IO], + user: Username = "user", + request_timeout: Optional[float] = None) -> EntryInfo +``` + +Write content to a file on the path. + +Writing to a file that doesn't exist creates the file. + +Writing to a file that already exists overwrites the file. + +Writing to a file at path that doesn't exist creates the necessary directories. + +**Arguments**: + +- `path`: Path to the file +- `data`: Data to write to the file, can be a `str`, `bytes`, or `IO`. +- `user`: Run the operation as this user +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +Information about the written file + + + +### list + +```python +async def list(path: str, + user: Username = "user", + request_timeout: Optional[float] = None) -> List[EntryInfo] +``` + +List entries in a directory. + +**Arguments**: + +- `path`: Path to the directory +- `user`: Run the operation as this user +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +List of entries in the directory + + + +### exists + +```python +async def exists(path: str, + user: Username = "user", + request_timeout: Optional[float] = None) -> bool +``` + +Check if a file or a directory exists. + +**Arguments**: + +- `path`: Path to a file or a directory +- `user`: Run the operation as this user +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`True` if the file or directory exists, `False` otherwise + + + +### remove + +```python +async def remove(path: str, + user: Username = "user", + request_timeout: Optional[float] = None) -> None +``` + +Remove a file or a directory. + +**Arguments**: + +- `path`: Path to a file or a directory +- `user`: Run the operation as this user +- `request_timeout`: Timeout for the request in **seconds** + + + +### rename + +```python +async def rename(old_path: str, + new_path: str, + user: Username = "user", + request_timeout: Optional[float] = None) -> EntryInfo +``` + +Rename a file or directory. + +**Arguments**: + +- `old_path`: Path to the file or directory to rename +- `new_path`: New path to the file or directory +- `user`: Run the operation as this user +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +Information about the renamed file or directory + + + +### make\_dir + +```python +async def make_dir(path: str, + user: Username = "user", + request_timeout: Optional[float] = None) -> bool +``` + +Create a new directory and all directories along the way if needed on the specified path. + +**Arguments**: + +- `path`: Path to a new directory. For example '/dirA/dirB' when creating 'dirB'. +- `user`: Run the operation as this user +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`True` if the directory was created, `False` if the directory already exists + + + +### watch\_dir + +```python +async def watch_dir(path: str, + on_event: OutputHandler[FilesystemEvent], + on_exit: Optional[OutputHandler[Exception]] = None, + user: Username = "user", + request_timeout: Optional[float] = None, + timeout: Optional[float] = 60) -> AsyncWatchHandle +``` + +Watch directory for filesystem events. + +**Arguments**: + +- `path`: Path to a directory to watch +- `on_event`: Callback to call on each event in the directory +- `on_exit`: Callback to call when the watching ends +- `user`: Run the operation as this user +- `request_timeout`: Timeout for the request in **seconds** +- `timeout`: Timeout for the watch operation in **seconds**. Using `0` will not limit the watch time + +**Returns**: + +`AsyncWatchHandle` object for stopping watching directory + + + + + + + + + +## SandboxApi + +```python +class SandboxApi(SandboxApiBase) +``` + + + +### list + +```python +@classmethod +async def list(cls, + api_key: Optional[str] = None, + domain: Optional[str] = None, + debug: Optional[bool] = None, + request_timeout: Optional[float] = None) -> List[SandboxInfo] +``` + +List all running sandboxes. + +**Arguments**: + +- `api_key`: API key to use for authentication, defaults to `E2B_API_KEY` environment variable +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +List of running sandboxes + + + + + + +## Commands + +```python +class Commands() +``` + +Module for executing commands in the sandbox. + + + +### list + +```python +async def list(request_timeout: Optional[float] = None) -> List[ProcessInfo] +``` + +Lists all running commands and PTY sessions. + +**Arguments**: + +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +List of running commands and PTY sessions + + + +### kill + +```python +async def kill(pid: int, request_timeout: Optional[float] = None) -> bool +``` + +Kill a running command specified by its process ID. + +It uses `SIGKILL` signal to kill the command. + +**Arguments**: + +- `pid`: Process ID of the command. You can get the list of processes using `sandbox.commands.list()` +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`True` if the command was killed, `False` if the command was not found + + + +### send\_stdin + +```python +async def send_stdin(pid: int, + data: str, + request_timeout: Optional[float] = None) -> None +``` + +Send data to command stdin. + +:param pid Process ID of the command. You can get the list of processes using `sandbox.commands.list()`. +:param data: Data to send to the command +:param request_timeout: Timeout for the request in **seconds** + + + + +### run + +```python +@overload +async def run(cmd: str, + background: Union[Literal[False], None] = None, + envs: Optional[Dict[str, str]] = None, + user: Username = "user", + cwd: Optional[str] = None, + on_stdout: Optional[OutputHandler[Stdout]] = None, + on_stderr: Optional[OutputHandler[Stderr]] = None, + timeout: Optional[float] = 60, + request_timeout: Optional[float] = None) -> CommandResult +``` + +Start a new command and wait until it finishes executing. + +**Arguments**: + +- `cmd`: Command to execute +- `background`: **`False` if the command should be executed in the foreground**, `True` if the command should be executed in the background +- `envs`: Environment variables used for the command +- `user`: User to run the command as +- `cwd`: Working directory to run the command +- `on_stdout`: Callback for command stdout output +- `on_stderr`: Callback for command stderr output +- `timeout`: Timeout for the command connection in **seconds**. Using `0` will not limit the command connection time +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`CommandResult` result of the command execution + + + +### run + +```python +@overload +async def run(cmd: str, + background: Literal[True], + envs: Optional[Dict[str, str]] = None, + user: Username = "user", + cwd: Optional[str] = None, + on_stdout: Optional[OutputHandler[Stdout]] = None, + on_stderr: Optional[OutputHandler[Stderr]] = None, + timeout: Optional[float] = 60, + request_timeout: Optional[float] = None) -> AsyncCommandHandle +``` + +Start a new command and return a handle to interact with it. + +**Arguments**: + +- `cmd`: Command to execute +- `background`: `False` if the command should be executed in the foreground, **`True` if the command should be executed in the background** +- `envs`: Environment variables used for the command +- `user`: User to run the command as +- `cwd`: Working directory to run the command +- `on_stdout`: Callback for command stdout output +- `on_stderr`: Callback for command stderr output +- `timeout`: Timeout for the command connection in **seconds**. Using `0` will not limit the command connection time +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`AsyncCommandHandle` handle to interact with the running command + + + +### connect + +```python +async def connect( + pid: int, + timeout: Optional[float] = 60, + request_timeout: Optional[float] = None, + on_stdout: Optional[OutputHandler[Stdout]] = None, + on_stderr: Optional[OutputHandler[Stderr]] = None +) -> AsyncCommandHandle +``` + +Connects to a running command. + +You can use `AsyncCommandHandle.wait()` to wait for the command to finish and get execution results. + +**Arguments**: + +- `pid`: Process ID of the command to connect to. You can get the list of processes using `sandbox.commands.list()` +- `request_timeout`: Request timeout in **seconds** +- `timeout`: Timeout for the command connection in **seconds**. Using `0` will not limit the command connection time +- `on_stdout`: Callback for command stdout output +- `on_stderr`: Callback for command stderr output + +**Returns**: + +`AsyncCommandHandle` handle to interact with the running command + + + + + + +## AsyncCommandHandle + +```python +class AsyncCommandHandle() +``` + +Command execution handle. + +It provides methods for waiting for the command to finish, retrieving stdout/stderr, and killing the command. + + + +### pid + +```python +@property +def pid() +``` + +Command process ID. + + + +### stdout + +```python +@property +def stdout() +``` + +Command stdout output. + + + +### stderr + +```python +@property +def stderr() +``` + +Command stderr output. + + + +### error + +```python +@property +def error() +``` + +Command execution error message. + + + +### exit\_code + +```python +@property +def exit_code() +``` + +Command execution exit code. + +`0` if the command finished successfully. + +It is `None` if the command is still running. + + + +### disconnect + +```python +async def disconnect() -> None +``` + +Disconnects from the command. + +The command is not killed, but SDK stops receiving events from the command. +You can reconnect to the command using `sandbox.commands.connect` method. + + + +### wait + +```python +async def wait() -> CommandResult +``` + +Wait for the command to finish and return the result. + +If the command exits with a non-zero exit code, it throws a `CommandExitException`. + +**Returns**: + +`CommandResult` result of command execution + + + +### kill + +```python +async def kill() -> bool +``` + +Kills the command. + +It uses `SIGKILL` signal to kill the command + +**Returns**: + +`True` if the command was killed successfully, `False` if the command was not found + + + + + + +## Pty + +```python +class Pty() +``` + +Module for interacting with PTYs (pseudo-terminals) in the sandbox. + + + +### kill + +```python +async def kill(pid: int, request_timeout: Optional[float] = None) -> bool +``` + +Kill PTY. + +**Arguments**: + +- `pid`: Process ID of the PTY +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`true` if the PTY was killed, `false` if the PTY was not found + + + +### send\_stdin + +```python +async def send_stdin(pid: int, + data: bytes, + request_timeout: Optional[float] = None) -> None +``` + +Send input to a PTY. + +**Arguments**: + +- `pid`: Process ID of the PTY +- `data`: Input data to send +- `request_timeout`: Timeout for the request in **seconds** + + + +### create + +```python +async def create( + size: PtySize, + on_data: OutputHandler[PtyOutput], + user: Username = "user", + cwd: Optional[str] = None, + envs: Optional[Dict[str, str]] = None, + timeout: Optional[float] = 60, + request_timeout: Optional[float] = None) -> AsyncCommandHandle +``` + +Start a new PTY (pseudo-terminal). + +**Arguments**: + +- `size`: Size of the PTY +- `on_data`: Callback to handle PTY data +- `user`: User to use for the PTY +- `cwd`: Working directory for the PTY +- `envs`: Environment variables for the PTY +- `timeout`: Timeout for the PTY in **seconds** +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +Handle to interact with the PTY + + + +### resize + +```python +async def resize(pid: int, + size: PtySize, + request_timeout: Optional[float] = None) +``` + +Resize PTY. + +Call this when the terminal window is resized and the number of columns and rows has changed. + +**Arguments**: + +- `pid`: Process ID of the PTY +- `size`: New size of the PTY +- `request_timeout`: Timeout for the request in **seconds** + + + + + + +## AsyncSandbox + +```python +class AsyncSandbox(SandboxSetup, SandboxApi) +``` + +E2B cloud sandbox is a secure and isolated cloud environment. + +The sandbox allows you to: +- Access Linux OS +- Create, list, and delete files and directories +- Run commands +- Run isolated code +- Access the internet + +Check docs [here](https://e2b.dev/docs). + +Use the `AsyncSandbox.create()` to create a new sandbox. + +**Example**: + +```python +from e2b import AsyncSandbox + +sandbox = await AsyncSandbox.create() +``` + + + +### files + +```python +@property +def files() -> Filesystem +``` + +Module for interacting with the sandbox filesystem. + + + +### commands + +```python +@property +def commands() -> Commands +``` + +Module for running commands in the sandbox. + + + +### pty + +```python +@property +def pty() -> Pty +``` + +Module for interacting with the sandbox pseudo-terminal. + + + +### sandbox\_id + +```python +@property +def sandbox_id() -> str +``` + +Unique identifier of the sandbox. + + + +### \_\_init\_\_ + +```python +def __init__(**opts: Unpack[AsyncSandboxOpts]) +``` + +Use `AsyncSandbox.create()` to create a new sandbox instead. + + + +### is\_running + +```python +async def is_running(request_timeout: Optional[float] = None) -> bool +``` + +Check if the sandbox is running. + +**Arguments**: + +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`True` if the sandbox is running, `False` otherwise +Example +```python +sandbox = await AsyncSandbox.create() +await sandbox.is_running() # Returns True + +await sandbox.kill() +await sandbox.is_running() # Returns False +``` + + + +### create + +```python +@classmethod +async def create(cls, + template: Optional[str] = None, + timeout: Optional[int] = None, + metadata: Optional[Dict[str, str]] = None, + envs: Optional[Dict[str, str]] = None, + api_key: Optional[str] = None, + domain: Optional[str] = None, + debug: Optional[bool] = None, + request_timeout: Optional[float] = None) +``` + +Create a new sandbox. + +By default, the sandbox is created from the default `base` sandbox template. + +**Arguments**: + +- `template`: Sandbox template name or ID +- `timeout`: Timeout for the sandbox in **seconds**, default to 300 seconds. Maximum time a sandbox can be kept alive is 24 hours (86_400 seconds) for Pro users and 1 hour (3_600 seconds) for Hobby users. +- `metadata`: Custom metadata for the sandbox +- `envs`: Custom environment variables for the sandbox +- `api_key`: E2B API Key to use for authentication, defaults to `E2B_API_KEY` environment variable +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +sandbox instance for the new sandbox +Use this method instead of using the constructor to create a new sandbox. + + + +### connect + +```python +@classmethod +async def connect(cls, + sandbox_id: str, + api_key: Optional[str] = None, + domain: Optional[str] = None, + debug: Optional[bool] = None) +``` + +Connect to an existing sandbox. + +With sandbox ID you can connect to the same sandbox from different places or environments (serverless functions, etc). + +**Arguments**: + +- `sandbox_id`: Sandbox ID +- `api_key`: E2B API Key to use for authentication, defaults to `E2B_API_KEY` environment variable + +**Returns**: + +sandbox instance for the existing sandbox +@example +```python +sandbox = await AsyncSandbox.create() +sandbox_id = sandbox.sandbox_id + +same_sandbox = await AsyncSandbox.connect(sandbox_id) + + + +### kill + +```python +@overload +async def kill(request_timeout: Optional[float] = None) -> bool +``` + +Kill the sandbox. + +**Arguments**: + +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`True` if the sandbox was killed, `False` if the sandbox was not found + + + +### kill + +```python +@overload +@staticmethod +async def kill(sandbox_id: str, + api_key: Optional[str] = None, + domain: Optional[str] = None, + debug: Optional[bool] = None, + request_timeout: Optional[float] = None) -> bool +``` + +Kill the sandbox specified by sandbox ID. + +**Arguments**: + +- `sandbox_id`: Sandbox ID +- `api_key`: E2B API Key to use for authentication, defaults to `E2B_API_KEY` environment variable +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`True` if the sandbox was killed, `False` if the sandbox was not found + + + +### set\_timeout + +```python +@overload +async def set_timeout(timeout: int, + request_timeout: Optional[float] = None) -> None +``` + +Set the timeout of the sandbox. + +After the timeout expires the sandbox will be automatically killed. +This method can extend or reduce the sandbox timeout set when creating the sandbox or from the last call to `.set_timeout`. + +Maximum time a sandbox can be kept alive is 24 hours (86_400 seconds) for Pro users and 1 hour (3_600 seconds) for Hobby users. + +**Arguments**: + +- `timeout`: Timeout for the sandbox in **seconds** +- `request_timeout`: Timeout for the request in **seconds** + + + +### set\_timeout + +```python +@overload +@staticmethod +async def set_timeout(sandbox_id: str, + timeout: int, + api_key: Optional[str] = None, + domain: Optional[str] = None, + debug: Optional[bool] = None, + request_timeout: Optional[float] = None) -> None +``` + +Set the timeout of the specified sandbox. + +After the timeout expires the sandbox will be automatically killed. +This method can extend or reduce the sandbox timeout set when creating the sandbox or from the last call to `.set_timeout`. + +Maximum time a sandbox can be kept alive is 24 hours (86_400 seconds) for Pro users and 1 hour (3_600 seconds) for Hobby users. + +**Arguments**: + +- `sandbox_id`: Sandbox ID +- `timeout`: Timeout for the sandbox in **seconds** +- `request_timeout`: Timeout for the request in **seconds** diff --git a/docs/sdk-reference/python-sdk/1.0.0/sandbox_sync.mdx b/docs/sdk-reference/python-sdk/1.0.0/sandbox_sync.mdx new file mode 100644 index 0000000..c94bb48 --- /dev/null +++ b/docs/sdk-reference/python-sdk/1.0.0/sandbox_sync.mdx @@ -0,0 +1,959 @@ +--- +sidebarTitle: "Sandbox Sync" +mode: "center" +--- + + + + + + +## WatchHandle + +```python +class WatchHandle() +``` + +Handle for watching filesystem events. +It is used to get the latest events that have occurred in the watched directory. + +Use `.stop()` to stop watching the directory. + + + +### stop + +```python +def stop() +``` + +Stop watching the directory. +After you stop the watcher you won't be able to get the events anymore. + + + +### get\_new\_events + +```python +def get_new_events() -> List[FilesystemEvent] +``` + +Get the latest events that have occurred in the watched directory since the last call, or from the beginning of the watching, up until now. + +**Returns**: + +List of filesystem events + + + + + + +## Filesystem + +```python +class Filesystem() +``` + +Module for interacting with the filesystem in the sandbox. + + + +### read + +```python +@overload +def read(path: str, + format: Literal["text"] = "text", + user: Username = "user", + request_timeout: Optional[float] = None) -> str +``` + +Read file content as a `str`. + +**Arguments**: + +- `path`: Path to the file +- `user`: Run the operation as this user +- `format`: Format of the file content—`text` by default +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +File content as a `str` + + + +### read + +```python +@overload +def read(path: str, + format: Literal["bytes"], + user: Username = "user", + request_timeout: Optional[float] = None) -> bytearray +``` + +Read file content as a `bytearray`. + +**Arguments**: + +- `path`: Path to the file +- `user`: Run the operation as this user +- `format`: Format of the file content—`bytes` +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +File content as a `bytearray` + + + +### read + +```python +@overload +def read(path: str, + format: Literal["stream"], + user: Username = "user", + request_timeout: Optional[float] = None) -> Iterator[bytes] +``` + +Read file content as a `Iterator[bytes]`. + +**Arguments**: + +- `path`: Path to the file +- `user`: Run the operation as this user +- `format`: Format of the file content—`stream` +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +File content as an `Iterator[bytes]` + + + +### write + +```python +def write(path: str, + data: Union[str, bytes, IO], + user: Username = "user", + request_timeout: Optional[float] = None) -> EntryInfo +``` + +Write content to a file on the path. + +Writing to a file that doesn't exist creates the file. + +Writing to a file that already exists overwrites the file. + +Writing to a file at path that doesn't exist creates the necessary directories. + +**Arguments**: + +- `path`: Path to the file +- `data`: Data to write to the file, can be a `str`, `bytes`, or `IO`. +- `user`: Run the operation as this user +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +Information about the written file + + + +### list + +```python +def list(path: str, + user: Username = "user", + request_timeout: Optional[float] = None) -> List[EntryInfo] +``` + +List entries in a directory. + +**Arguments**: + +- `path`: Path to the directory +- `user`: Run the operation as this user +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +List of entries in the directory + + + +### exists + +```python +def exists(path: str, + user: Username = "user", + request_timeout: Optional[float] = None) -> bool +``` + +Check if a file or a directory exists. + +**Arguments**: + +- `path`: Path to a file or a directory +- `user`: Run the operation as this user +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`True` if the file or directory exists, `False` otherwise + + + +### remove + +```python +def remove(path: str, + user: Username = "user", + request_timeout: Optional[float] = None) -> None +``` + +Remove a file or a directory. + +**Arguments**: + +- `path`: Path to a file or a directory +- `user`: Run the operation as this user +- `request_timeout`: Timeout for the request in **seconds** + + + +### rename + +```python +def rename(old_path: str, + new_path: str, + user: Username = "user", + request_timeout: Optional[float] = None) -> EntryInfo +``` + +Rename a file or directory. + +**Arguments**: + +- `old_path`: Path to the file or directory to rename +- `new_path`: New path to the file or directory +- `user`: Run the operation as this user +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +Information about the renamed file or directory + + + +### make\_dir + +```python +def make_dir(path: str, + user: Username = "user", + request_timeout: Optional[float] = None) -> bool +``` + +Create a new directory and all directories along the way if needed on the specified path. + +**Arguments**: + +- `path`: Path to a new directory. For example '/dirA/dirB' when creating 'dirB'. +- `user`: Run the operation as this user +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`True` if the directory was created, `False` if the directory already exists + + + +### watch\_dir + +```python +def watch_dir(path: str, + user: Username = "user", + request_timeout: Optional[float] = None) -> WatchHandle +``` + +Watch directory for filesystem events. + +**Arguments**: + +- `path`: Path to a directory to watch +- `user`: Run the operation as this user +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`WatchHandle` object for stopping watching directory + + + + + + +## SandboxApi + +```python +class SandboxApi(SandboxApiBase) +``` + + + +### list + +```python +@classmethod +def list(cls, + api_key: Optional[str] = None, + domain: Optional[str] = None, + debug: Optional[bool] = None, + request_timeout: Optional[float] = None) -> List[SandboxInfo] +``` + +List all running sandboxes. + +**Arguments**: + +- `api_key`: API key to use for authentication, defaults to `E2B_API_KEY` environment variable +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +List of sandbox info + + + + + + +## Commands + +```python +class Commands() +``` + +Module for executing commands in the sandbox. + + + +### list + +```python +def list(request_timeout: Optional[float] = None) -> List[ProcessInfo] +``` + +Lists all running commands and PTY sessions. + +**Arguments**: + +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +List of running commands and PTY sessions + + + +### kill + +```python +def kill(pid: int, request_timeout: Optional[float] = None) -> bool +``` + +Kills a running command specified by its process ID. + +It uses `SIGKILL` signal to kill the command. + +**Arguments**: + +- `pid`: Process ID of the command. You can get the list of processes using `sandbox.commands.list()` +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`True` if the command was killed, `False` if the command was not found + + + +### send\_stdin + +```python +def send_stdin(pid: int, data: str, request_timeout: Optional[float] = None) +``` + +Send data to command stdin. + +:param pid Process ID of the command. You can get the list of processes using `sandbox.commands.list()`. +:param data: Data to send to the command +:param request_timeout: Timeout for the request in **seconds** + + + + +### run + +```python +@overload +def run(cmd: str, + background: Union[Literal[False], None] = None, + envs: Optional[Dict[str, str]] = None, + user: Username = "user", + cwd: Optional[str] = None, + on_stdout: Optional[Callable[[str], None]] = None, + on_stderr: Optional[Callable[[str], None]] = None, + timeout: Optional[float] = 60, + request_timeout: Optional[float] = None) -> CommandResult +``` + +Start a new command and wait until it finishes executing. + +**Arguments**: + +- `cmd`: Command to execute +- `background`: **`False` if the command should be executed in the foreground**, `True` if the command should be executed in the background +- `envs`: Environment variables used for the command +- `user`: User to run the command as +- `cwd`: Working directory to run the command +- `on_stdout`: Callback for command stdout output +- `on_stderr`: Callback for command stderr output +- `timeout`: Timeout for the command connection in **seconds**. Using `0` will not limit the command connection time +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`CommandResult` result of the command execution + + + +### run + +```python +@overload +def run(cmd: str, + background: Literal[True], + envs: Optional[Dict[str, str]] = None, + user: Username = "user", + cwd: Optional[str] = None, + on_stdout: None = None, + on_stderr: None = None, + timeout: Optional[float] = 60, + request_timeout: Optional[float] = None) -> CommandHandle +``` + +Start a new command and return a handle to interact with it. + +**Arguments**: + +- `cmd`: Command to execute +- `background`: `False` if the command should be executed in the foreground, **`True` if the command should be executed in the background** +- `envs`: Environment variables used for the command +- `user`: User to run the command as +- `cwd`: Working directory to run the command +- `timeout`: Timeout for the command connection in **seconds**. Using `0` will not limit the command connection time +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`CommandHandle` handle to interact with the running command + + + +### connect + +```python +def connect(pid: int, + timeout: Optional[float] = 60, + request_timeout: Optional[float] = None) +``` + +Connects to a running command. + +You can use `CommandHandle.wait()` to wait for the command to finish and get execution results. + +**Arguments**: + +- `pid`: Process ID of the command to connect to. You can get the list of processes using `sandbox.commands.list()` +- `timeout`: Timeout for the connection in **seconds**. Using `0` will not limit the connection time +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`CommandHandle` handle to interact with the running command + + + + + + +## CommandHandle + +```python +class CommandHandle() +``` + +Command execution handle. + +It provides methods for waiting for the command to finish, retrieving stdout/stderr, and killing the command. + + + +### pid + +```python +@property +def pid() +``` + +Command process ID. + + + +### \_\_iter\_\_ + +```python +def __iter__() +``` + +Iterate over the command output. + +**Returns**: + +Generator of command outputs + + + +### disconnect + +```python +def disconnect() -> None +``` + +Disconnect from the command. + +The command is not killed, but SDK stops receiving events from the command. +You can reconnect to the command using `sandbox.commands.connect` method. + + + +### wait + +```python +def wait(on_pty: Optional[Callable[[PtyOutput], None]] = None, + on_stdout: Optional[Callable[[str], None]] = None, + on_stderr: Optional[Callable[[str], None]] = None) -> CommandResult +``` + +Wait for the command to finish and returns the result. + +If the command exits with a non-zero exit code, it throws a `CommandExitException`. + +**Arguments**: + +- `on_pty`: Callback for pty output +- `on_stdout`: Callback for stdout output +- `on_stderr`: Callback for stderr output + +**Returns**: + +`CommandResult` result of command execution + + + +### kill + +```python +def kill() -> bool +``` + +Kills the command. + +It uses `SIGKILL` signal to kill the command. + +**Returns**: + +Whether the command was killed successfully + + + + + + +## Pty + +```python +class Pty() +``` + +Module for interacting with PTYs (pseudo-terminals) in the sandbox. + + + +### kill + +```python +def kill(pid: int, request_timeout: Optional[float] = None) -> bool +``` + +Kill PTY. + +**Arguments**: + +- `pid`: Process ID of the PTY +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`true` if the PTY was killed, `false` if the PTY was not found + + + +### send\_stdin + +```python +def send_stdin(pid: int, + data: bytes, + request_timeout: Optional[float] = None) -> None +``` + +Send input to a PTY. + +**Arguments**: + +- `pid`: Process ID of the PTY +- `data`: Input data to send +- `request_timeout`: Timeout for the request in **seconds** + + + +### create + +```python +def create(size: PtySize, + user: Username = "user", + cwd: Optional[str] = None, + envs: Optional[Dict[str, str]] = None, + timeout: Optional[float] = 60, + request_timeout: Optional[float] = None) -> CommandHandle +``` + +Start a new PTY (pseudo-terminal). + +**Arguments**: + +- `size`: Size of the PTY +- `user`: User to use for the PTY +- `cwd`: Working directory for the PTY +- `envs`: Environment variables for the PTY +- `timeout`: Timeout for the PTY in **seconds** +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +Handle to interact with the PTY + + + +### resize + +```python +def resize(pid: int, + size: PtySize, + request_timeout: Optional[float] = None) -> None +``` + +Resize PTY. + +Call this when the terminal window is resized and the number of columns and rows has changed. + +**Arguments**: + +- `pid`: Process ID of the PTY +- `size`: New size of the PTY +- `request_timeout`: Timeout for the request in **seconds**s + + + + + + +## Sandbox + +```python +class Sandbox(SandboxSetup, SandboxApi) +``` + +E2B cloud sandbox is a secure and isolated cloud environment. + +The sandbox allows you to: +- Access Linux OS +- Create, list, and delete files and directories +- Run commands +- Run isolated code +- Access the internet + +Check docs [here](https://e2b.dev/docs). + +Use the `Sandbox()` to create a new sandbox. + +**Example**: + +```python +from e2b import Sandbox + +sandbox = Sandbox() +``` + + + +### files + +```python +@property +def files() -> Filesystem +``` + +Module for interacting with the sandbox filesystem. + + + +### commands + +```python +@property +def commands() -> Commands +``` + +Module for running commands in the sandbox. + + + +### pty + +```python +@property +def pty() -> Pty +``` + +Module for interacting with the sandbox pseudo-terminal. + + + +### sandbox\_id + +```python +@property +def sandbox_id() -> str +``` + +Unique identifier of the sandbox + + + +### \_\_init\_\_ + +```python +def __init__(template: Optional[str] = None, + timeout: Optional[int] = None, + metadata: Optional[Dict[str, str]] = None, + envs: Optional[Dict[str, str]] = None, + api_key: Optional[str] = None, + domain: Optional[str] = None, + debug: Optional[bool] = None, + sandbox_id: Optional[str] = None, + request_timeout: Optional[float] = None) +``` + +Create a new sandbox. + +By default, the sandbox is created from the default `base` sandbox template. + +**Arguments**: + +- `template`: Sandbox template name or ID +- `timeout`: Timeout for the sandbox in **seconds**, default to 300 seconds. Maximum time a sandbox can be kept alive is 24 hours (86_400 seconds) for Pro users and 1 hour (3_600 seconds) for Hobby users +- `metadata`: Custom metadata for the sandbox +- `envs`: Custom environment variables for the sandbox +- `api_key`: E2B API Key to use for authentication, defaults to `E2B_API_KEY` environment variable +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +sandbox instance for the new sandbox + + + +### is\_running + +```python +def is_running(request_timeout: Optional[float] = None) -> bool +``` + +Check if the sandbox is running. + +**Arguments**: + +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`True` if the sandbox is running, `False` otherwise +Example +```python +sandbox = Sandbox() +sandbox.is_running() # Returns True + +sandbox.kill() +sandbox.is_running() # Returns False +``` + + + +### connect + +```python +@classmethod +def connect(cls, + sandbox_id: str, + api_key: Optional[str] = None, + domain: Optional[str] = None, + debug: Optional[bool] = None) +``` + +Connects to an existing Sandbox. + +With sandbox ID you can connect to the same sandbox from different places or environments (serverless functions, etc). + +**Arguments**: + +- `sandbox_id`: Sandbox ID +- `api_key`: E2B API Key to use for authentication, defaults to `E2B_API_KEY` environment variable + +**Returns**: + +sandbox instance for the existing sandbox +@example +```python +sandbox = Sandbox() +sandbox_id = sandbox.sandbox_id + +same_sandbox = Sandbox.connect(sandbox_id) + + + +### kill + +```python +@overload +def kill(request_timeout: Optional[float] = None) -> bool +``` + +Kill the sandbox. + +**Arguments**: + +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`True` if the sandbox was killed, `False` if the sandbox was not found + + + +### kill + +```python +@overload +@staticmethod +def kill(sandbox_id: str, + api_key: Optional[str] = None, + domain: Optional[str] = None, + debug: Optional[bool] = None, + request_timeout: Optional[float] = None) -> bool +``` + +Kill the sandbox specified by sandbox ID. + +**Arguments**: + +- `sandbox_id`: Sandbox ID +- `api_key`: E2B API Key to use for authentication, defaults to `E2B_API_KEY` environment variable +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`True` if the sandbox was killed, `False` if the sandbox was not found + + + +### kill + +```python +@class_method_variant("_cls_kill") +def kill(request_timeout: Optional[float] = None) -> bool +``` + +Kill the sandbox. + +**Arguments**: + +- `request_timeout`: Timeout for the request + +**Returns**: + +`True` if the sandbox was killed, `False` if the sandbox was not found + + + +### set\_timeout + +```python +@overload +def set_timeout(timeout: int, request_timeout: Optional[float] = None) -> None +``` + +Set the timeout of the sandbox. + +After the timeout expires the sandbox will be automatically killed. +This method can extend or reduce the sandbox timeout set when creating the sandbox or from the last call to `.set_timeout`. + +Maximum time a sandbox can be kept alive is 24 hours (86_400 seconds) for Pro users and 1 hour (3_600 seconds) for Hobby users. + +**Arguments**: + +- `timeout`: Timeout for the sandbox in **seconds** +- `request_timeout`: Timeout for the request in **seconds** + + + +### set\_timeout + +```python +@overload +@staticmethod +def set_timeout(sandbox_id: str, + timeout: int, + api_key: Optional[str] = None, + domain: Optional[str] = None, + debug: Optional[bool] = None, + request_timeout: Optional[float] = None) -> None +``` + +Set the timeout of the sandbox specified by sandbox ID. + +After the timeout expires the sandbox will be automatically killed. +This method can extend or reduce the sandbox timeout set when creating the sandbox or from the last call to `.set_timeout`. + +Maximum time a sandbox can be kept alive is 24 hours (86_400 seconds) for Pro users and 1 hour (3_600 seconds) for Hobby users. + +**Arguments**: + +- `sandbox_id`: Sandbox ID +- `timeout`: Timeout for the sandbox in **seconds** +- `api_key`: E2B API Key to use for authentication, defaults to `E2B_API_KEY` environment variable +- `request_timeout`: Timeout for the request in **seconds** diff --git a/docs/sdk-reference/python-sdk/v2.7.0/exceptions.mdx b/docs/sdk-reference/python-sdk/v2.7.0/exceptions.mdx new file mode 100644 index 0000000..d66f786 --- /dev/null +++ b/docs/sdk-reference/python-sdk/v2.7.0/exceptions.mdx @@ -0,0 +1,117 @@ +--- +sidebarTitle: "Exceptions" +mode: "center" +--- + + + + + + +## SandboxException + +```python +class SandboxException(Exception) +``` + +Base class for all sandbox errors. + +Raised when a general sandbox exception occurs. + + + +## TimeoutException + +```python +class TimeoutException(SandboxException) +``` + +Raised when a timeout occurs. + +The `unavailable` exception type is caused by sandbox timeout. + +The `canceled` exception type is caused by exceeding request timeout. + +The `deadline_exceeded` exception type is caused by exceeding the timeout for process, watch, etc. + +The `unknown` exception type is sometimes caused by the sandbox timeout when the request is not processed correctly. + + + +## InvalidArgumentException + +```python +class InvalidArgumentException(SandboxException) +``` + +Raised when an invalid argument is provided. + + + +## NotEnoughSpaceException + +```python +class NotEnoughSpaceException(SandboxException) +``` + +Raised when there is not enough disk space. + + + +## NotFoundException + +```python +class NotFoundException(SandboxException) +``` + +Raised when a resource is not found. + + + +## AuthenticationException + +```python +class AuthenticationException(Exception) +``` + +Raised when authentication fails. + + + +## TemplateException + +```python +class TemplateException(SandboxException) +``` + +Exception raised when the template uses old envd version. It isn't compatible with the new SDK. + + + +## RateLimitException + +```python +class RateLimitException(SandboxException) +``` + +Raised when the API rate limit is exceeded. + + + +## BuildException + +```python +class BuildException(Exception) +``` + +Raised when the build fails. + + + +## FileUploadException + +```python +class FileUploadException(BuildException) +``` + +Raised when the file upload fails. diff --git a/docs/sdk-reference/python-sdk/v2.7.0/logger.mdx b/docs/sdk-reference/python-sdk/v2.7.0/logger.mdx new file mode 100644 index 0000000..9fa3b18 --- /dev/null +++ b/docs/sdk-reference/python-sdk/v2.7.0/logger.mdx @@ -0,0 +1,106 @@ +--- +sidebarTitle: "Logger" +mode: "center" +--- + + + + + + +## LogEntry + +```python +@dataclass +class LogEntry() +``` + +Represents a single log entry from the template build process. + + + +## LogEntryStart + +```python +@dataclass +class LogEntryStart(LogEntry) +``` + +Special log entry indicating the start of a build process. + + + +## LogEntryEnd + +```python +@dataclass +class LogEntryEnd(LogEntry) +``` + +Special log entry indicating the end of a build process. + + + +### TIMER\_UPDATE\_INTERVAL\_MS + +Default minimum log level to display. + + + +### DEFAULT\_LEVEL + +Colored labels for each log level. + + + +### levels + +Numeric ordering of log levels for comparison (lower = less severe). + + + +### set\_interval + +```python +def set_interval(func, interval) +``` + +Returns a stop function that can be called to cancel the interval. + +Similar to JavaScript's setInterval. + +**Arguments**: + +- `func`: Function to execute at each interval +- `interval`: Interval duration in **seconds** + +**Returns**: + +Stop function that can be called to cancel the interval + + + +### default\_build\_logger + +```python +def default_build_logger( + min_level: Optional[LogEntryLevel] = None +) -> Callable[[LogEntry], None] +``` + +Create a default build logger with animated timer display. + +**Arguments**: + +- `min_level`: Minimum log level to display (default: 'info') + +**Returns**: + +Logger function that accepts LogEntry instances +Example +```python +from e2b import Template, default_build_logger + +template = Template().from_python_image() + +``` diff --git a/docs/sdk-reference/python-sdk/v2.7.0/readycmd.mdx b/docs/sdk-reference/python-sdk/v2.7.0/readycmd.mdx new file mode 100644 index 0000000..8eabda6 --- /dev/null +++ b/docs/sdk-reference/python-sdk/v2.7.0/readycmd.mdx @@ -0,0 +1,168 @@ +--- +sidebarTitle: "Readycmd" +mode: "center" +--- + + + + + + +## ReadyCmd + +```python +class ReadyCmd() +``` + +Wrapper class for ready check commands. + + + +### wait\_for\_port + +```python +def wait_for_port(port: int) +``` + +Wait for a port to be listening. + +Uses `ss` command to check if a port is open and listening. + +**Arguments**: + +- `port`: Port number to wait for + +**Returns**: + +ReadyCmd that checks for the port +Example +```python +from e2b import Template, wait_for_port + +template = ( + Template() + .from_python_image() + .set_start_cmd('python -m http.server 8000', wait_for_port(8000)) +) +``` + + + +### wait\_for\_url + +```python +def wait_for_url(url: str, status_code: int = 200) +``` + +Wait for a URL to return a specific HTTP status code. + +Uses `curl` to make HTTP requests and check the response status. + +**Arguments**: + +- `url`: URL to check (e.g., 'http://localhost:3000/health') +- `status_code`: Expected HTTP status code (default: 200) + +**Returns**: + +ReadyCmd that checks the URL +Example +```python +from e2b import Template, wait_for_url + +template = ( + Template() + .from_node_image() + .set_start_cmd('npm start', wait_for_url('http://localhost:3000/health')) +) +``` + + + +### wait\_for\_process + +```python +def wait_for_process(process_name: str) +``` + +Wait for a process with a specific name to be running. + +Uses `pgrep` to check if a process exists. + +**Arguments**: + +- `process_name`: Name of the process to wait for + +**Returns**: + +ReadyCmd that checks for the process +Example +```python +from e2b import Template, wait_for_process + +template = ( + Template() + .from_base_image() + .set_start_cmd('./my-daemon', wait_for_process('my-daemon')) +) +``` + + + +### wait\_for\_file + +```python +def wait_for_file(filename: str) +``` + +Wait for a file to exist. + +Uses shell test command to check file existence. + +**Arguments**: + +- `filename`: Path to the file to wait for + +**Returns**: + +ReadyCmd that checks for the file +Example +```python +from e2b import Template, wait_for_file + +template = ( + Template() + .from_base_image() + .set_start_cmd('./init.sh', wait_for_file('/tmp/ready')) +) +``` + + + +### wait\_for\_timeout + +```python +def wait_for_timeout(timeout: int) +``` + +Wait for a specified timeout before considering the sandbox ready. + +Uses `sleep` command to wait for a fixed duration. + +**Arguments**: + +- `timeout`: Time to wait in **milliseconds** (minimum: 1000ms / 1 second) + +**Returns**: + +ReadyCmd that waits for the specified duration +Example +```python +from e2b import Template, wait_for_timeout + +template = ( + Template() + .from_node_image() + .set_start_cmd('npm start', wait_for_timeout(5000)) # Wait 5 seconds +) +``` diff --git a/docs/sdk-reference/python-sdk/v2.7.0/sandbox_async.mdx b/docs/sdk-reference/python-sdk/v2.7.0/sandbox_async.mdx new file mode 100644 index 0000000..b636b1a --- /dev/null +++ b/docs/sdk-reference/python-sdk/v2.7.0/sandbox_async.mdx @@ -0,0 +1,1387 @@ +--- +sidebarTitle: "Sandbox Async" +mode: "center" +--- + + + + + + +## AsyncWatchHandle + +```python +class AsyncWatchHandle() +``` + +Handle for watching a directory in the sandbox filesystem. + +Use `.stop()` to stop watching the directory. + + + +### stop + +```python +async def stop() +``` + +Stop watching the directory. + + + + + + +## Filesystem + +```python +class Filesystem() +``` + +Module for interacting with the filesystem in the sandbox. + + + +### read + +```python +@overload +async def read(path: str, + format: Literal["text"] = "text", + user: Optional[Username] = None, + request_timeout: Optional[float] = None) -> str +``` + +Read file content as a `str`. + +**Arguments**: + +- `path`: Path to the file +- `user`: Run the operation as this user +- `format`: Format of the file content—`text` by default +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +File content as a `str` + + + +### read + +```python +@overload +async def read(path: str, + format: Literal["bytes"], + user: Optional[Username] = None, + request_timeout: Optional[float] = None) -> bytearray +``` + +Read file content as a `bytearray`. + +**Arguments**: + +- `path`: Path to the file +- `user`: Run the operation as this user +- `format`: Format of the file content—`bytes` +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +File content as a `bytearray` + + + +### read + +```python +@overload +async def read( + path: str, + format: Literal["stream"], + user: Optional[Username] = None, + request_timeout: Optional[float] = None) -> AsyncIterator[bytes] +``` + +Read file content as a `AsyncIterator[bytes]`. + +**Arguments**: + +- `path`: Path to the file +- `user`: Run the operation as this user +- `format`: Format of the file content—`stream` +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +File content as an `AsyncIterator[bytes]` + + + +### write + +```python +async def write(path: str, + data: Union[str, bytes, IO], + user: Optional[Username] = None, + request_timeout: Optional[float] = None) -> WriteInfo +``` + +Write content to a file on the path. + +Writing to a file that doesn't exist creates the file. +Writing to a file that already exists overwrites the file. +Writing to a file at path that doesn't exist creates the necessary directories. + +**Arguments**: + +- `path`: Path to the file +- `data`: Data to write to the file, can be a `str`, `bytes`, or `IO`. +- `user`: Run the operation as this user +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +Information about the written file + + + +### write\_files + +```python +async def write_files( + files: List[WriteEntry], + user: Optional[Username] = None, + request_timeout: Optional[float] = None) -> List[WriteInfo] +``` + +Writes multiple files. + +Writes a list of files to the filesystem. +When writing to a file that doesn't exist, the file will get created. +When writing to a file that already exists, the file will get overwritten. +When writing to a file that's in a directory that doesn't exist, you'll get an error. + +**Arguments**: + +- `files`: list of files to write as `WriteEntry` objects, each containing `path` and `data` +- `user`: Run the operation as this user +- `request_timeout`: Timeout for the request + +**Returns**: + +Information about the written files + + + +### list + +```python +async def list(path: str, + depth: Optional[int] = 1, + user: Optional[Username] = None, + request_timeout: Optional[float] = None) -> List[EntryInfo] +``` + +List entries in a directory. + +**Arguments**: + +- `path`: Path to the directory +- `depth`: Depth of the directory to list +- `user`: Run the operation as this user +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +List of entries in the directory + + + +### exists + +```python +async def exists(path: str, + user: Optional[Username] = None, + request_timeout: Optional[float] = None) -> bool +``` + +Check if a file or a directory exists. + +**Arguments**: + +- `path`: Path to a file or a directory +- `user`: Run the operation as this user +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`True` if the file or directory exists, `False` otherwise + + + +### get\_info + +```python +async def get_info(path: str, + user: Optional[Username] = None, + request_timeout: Optional[float] = None) -> EntryInfo +``` + +Get information about a file or directory. + +**Arguments**: + +- `path`: Path to a file or a directory +- `user`: Run the operation as this user +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +Information about the file or directory like name, type, and path + + + +### remove + +```python +async def remove(path: str, + user: Optional[Username] = None, + request_timeout: Optional[float] = None) -> None +``` + +Remove a file or a directory. + +**Arguments**: + +- `path`: Path to a file or a directory +- `user`: Run the operation as this user +- `request_timeout`: Timeout for the request in **seconds** + + + +### rename + +```python +async def rename(old_path: str, + new_path: str, + user: Optional[Username] = None, + request_timeout: Optional[float] = None) -> EntryInfo +``` + +Rename a file or directory. + +**Arguments**: + +- `old_path`: Path to the file or directory to rename +- `new_path`: New path to the file or directory +- `user`: Run the operation as this user +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +Information about the renamed file or directory + + + +### make\_dir + +```python +async def make_dir(path: str, + user: Optional[Username] = None, + request_timeout: Optional[float] = None) -> bool +``` + +Create a new directory and all directories along the way if needed on the specified path. + +**Arguments**: + +- `path`: Path to a new directory. For example '/dirA/dirB' when creating 'dirB'. +- `user`: Run the operation as this user +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`True` if the directory was created, `False` if the directory already exists + + + +### watch\_dir + +```python +async def watch_dir(path: str, + on_event: OutputHandler[FilesystemEvent], + on_exit: Optional[OutputHandler[Exception]] = None, + user: Optional[Username] = None, + request_timeout: Optional[float] = None, + timeout: Optional[float] = 60, + recursive: bool = False) -> AsyncWatchHandle +``` + +Watch directory for filesystem events. + +**Arguments**: + +- `path`: Path to a directory to watch +- `on_event`: Callback to call on each event in the directory +- `on_exit`: Callback to call when the watching ends +- `user`: Run the operation as this user +- `request_timeout`: Timeout for the request in **seconds** +- `timeout`: Timeout for the watch operation in **seconds**. Using `0` will not limit the watch time +- `recursive`: Watch directory recursively + +**Returns**: + +`AsyncWatchHandle` object for stopping watching directory + + + + + + +## AsyncSandboxPaginator + +```python +class AsyncSandboxPaginator(SandboxPaginatorBase) +``` + +Paginator for listing sandboxes. + +**Example**: + +```python +paginator = AsyncSandbox.list() + +while paginator.has_next: + sandboxes = await paginator.next_items() + print(sandboxes) +``` + + + +### next\_items + +```python +async def next_items() -> List[SandboxInfo] +``` + +Returns the next page of sandboxes. + +Call this method only if `has_next` is `True`, otherwise it will raise an exception. + +**Returns**: + +List of sandboxes + + + + + + + + + +## SandboxApi + +```python +class SandboxApi(SandboxBase) +``` + + + +### list + +```python +@staticmethod +def list(query: Optional[SandboxQuery] = None, + limit: Optional[int] = None, + next_token: Optional[str] = None, + **opts: Unpack[ApiParams]) -> AsyncSandboxPaginator +``` + +List all running sandboxes. + +**Arguments**: + +- `query`: Filter the list of sandboxes by metadata or state, e.g. `SandboxListQuery(metadata={"key": "value"})` or `SandboxListQuery(state=[SandboxState.RUNNING])` +- `limit`: Maximum number of sandboxes to return per page +- `next_token`: Token for pagination + +**Returns**: + +List of running sandboxes + + + + + + +## Commands + +```python +class Commands() +``` + +Module for executing commands in the sandbox. + + + +### list + +```python +async def list(request_timeout: Optional[float] = None) -> List[ProcessInfo] +``` + +Lists all running commands and PTY sessions. + +**Arguments**: + +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +List of running commands and PTY sessions + + + +### kill + +```python +async def kill(pid: int, request_timeout: Optional[float] = None) -> bool +``` + +Kill a running command specified by its process ID. + +It uses `SIGKILL` signal to kill the command. + +**Arguments**: + +- `pid`: Process ID of the command. You can get the list of processes using `sandbox.commands.list()` +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`True` if the command was killed, `False` if the command was not found + + + +### send\_stdin + +```python +async def send_stdin(pid: int, + data: str, + request_timeout: Optional[float] = None) -> None +``` + +Send data to command stdin. + +:param pid Process ID of the command. You can get the list of processes using `sandbox.commands.list()`. +:param data: Data to send to the command +:param request_timeout: Timeout for the request in **seconds** + + + + +### run + +```python +@overload +async def run(cmd: str, + background: Union[Literal[False], None] = None, + envs: Optional[Dict[str, str]] = None, + user: Optional[Username] = None, + cwd: Optional[str] = None, + on_stdout: Optional[OutputHandler[Stdout]] = None, + on_stderr: Optional[OutputHandler[Stderr]] = None, + stdin: Optional[bool] = None, + timeout: Optional[float] = 60, + request_timeout: Optional[float] = None) -> CommandResult +``` + +Start a new command and wait until it finishes executing. + +**Arguments**: + +- `cmd`: Command to execute +- `background`: **`False` if the command should be executed in the foreground**, `True` if the command should be executed in the background +- `envs`: Environment variables used for the command +- `user`: User to run the command as +- `cwd`: Working directory to run the command +- `on_stdout`: Callback for command stdout output +- `on_stderr`: Callback for command stderr output +- `stdin`: If `True`, the command will have a stdin stream that you can send data to using `sandbox.commands.send_stdin()` +- `timeout`: Timeout for the command connection in **seconds**. Using `0` will not limit the command connection time +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`CommandResult` result of the command execution + + + +### run + +```python +@overload +async def run(cmd: str, + background: Literal[True], + envs: Optional[Dict[str, str]] = None, + user: Optional[Username] = None, + cwd: Optional[str] = None, + on_stdout: Optional[OutputHandler[Stdout]] = None, + on_stderr: Optional[OutputHandler[Stderr]] = None, + stdin: Optional[bool] = None, + timeout: Optional[float] = 60, + request_timeout: Optional[float] = None) -> AsyncCommandHandle +``` + +Start a new command and return a handle to interact with it. + +**Arguments**: + +- `cmd`: Command to execute +- `background`: `False` if the command should be executed in the foreground, **`True` if the command should be executed in the background** +- `envs`: Environment variables used for the command +- `user`: User to run the command as +- `cwd`: Working directory to run the command +- `on_stdout`: Callback for command stdout output +- `on_stderr`: Callback for command stderr output +- `stdin`: If `True`, the command will have a stdin stream that you can send data to using `sandbox.commands.send_stdin()` +- `timeout`: Timeout for the command connection in **seconds**. Using `0` will not limit the command connection time +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`AsyncCommandHandle` handle to interact with the running command + + + +### connect + +```python +async def connect( + pid: int, + timeout: Optional[float] = 60, + request_timeout: Optional[float] = None, + on_stdout: Optional[OutputHandler[Stdout]] = None, + on_stderr: Optional[OutputHandler[Stderr]] = None +) -> AsyncCommandHandle +``` + +Connects to a running command. + +You can use `AsyncCommandHandle.wait()` to wait for the command to finish and get execution results. + +**Arguments**: + +- `pid`: Process ID of the command to connect to. You can get the list of processes using `sandbox.commands.list()` +- `request_timeout`: Request timeout in **seconds** +- `timeout`: Timeout for the command connection in **seconds**. Using `0` will not limit the command connection time +- `on_stdout`: Callback for command stdout output +- `on_stderr`: Callback for command stderr output + +**Returns**: + +`AsyncCommandHandle` handle to interact with the running command + + + + + + +## AsyncCommandHandle + +```python +class AsyncCommandHandle() +``` + +Command execution handle. + +It provides methods for waiting for the command to finish, retrieving stdout/stderr, and killing the command. + + + +### pid + +```python +@property +def pid() +``` + +Command process ID. + + + +### stdout + +```python +@property +def stdout() +``` + +Command stdout output. + + + +### stderr + +```python +@property +def stderr() +``` + +Command stderr output. + + + +### error + +```python +@property +def error() +``` + +Command execution error message. + + + +### exit\_code + +```python +@property +def exit_code() +``` + +Command execution exit code. + +`0` if the command finished successfully. + +It is `None` if the command is still running. + + + +### disconnect + +```python +async def disconnect() -> None +``` + +Disconnects from the command. + +The command is not killed, but SDK stops receiving events from the command. +You can reconnect to the command using `sandbox.commands.connect` method. + + + +### wait + +```python +async def wait() -> CommandResult +``` + +Wait for the command to finish and return the result. + +If the command exits with a non-zero exit code, it throws a `CommandExitException`. + +**Returns**: + +`CommandResult` result of command execution + + + +### kill + +```python +async def kill() -> bool +``` + +Kills the command. + +It uses `SIGKILL` signal to kill the command + +**Returns**: + +`True` if the command was killed successfully, `False` if the command was not found + + + + + + +## Pty + +```python +class Pty() +``` + +Module for interacting with PTYs (pseudo-terminals) in the sandbox. + + + +### kill + +```python +async def kill(pid: int, request_timeout: Optional[float] = None) -> bool +``` + +Kill PTY. + +**Arguments**: + +- `pid`: Process ID of the PTY +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`true` if the PTY was killed, `false` if the PTY was not found + + + +### send\_stdin + +```python +async def send_stdin(pid: int, + data: bytes, + request_timeout: Optional[float] = None) -> None +``` + +Send input to a PTY. + +**Arguments**: + +- `pid`: Process ID of the PTY +- `data`: Input data to send +- `request_timeout`: Timeout for the request in **seconds** + + + +### create + +```python +async def create( + size: PtySize, + on_data: OutputHandler[PtyOutput], + user: Optional[Username] = None, + cwd: Optional[str] = None, + envs: Optional[Dict[str, str]] = None, + timeout: Optional[float] = 60, + request_timeout: Optional[float] = None) -> AsyncCommandHandle +``` + +Start a new PTY (pseudo-terminal). + +**Arguments**: + +- `size`: Size of the PTY +- `on_data`: Callback to handle PTY data +- `user`: User to use for the PTY +- `cwd`: Working directory for the PTY +- `envs`: Environment variables for the PTY +- `timeout`: Timeout for the PTY in **seconds** +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +Handle to interact with the PTY + + + +### resize + +```python +async def resize(pid: int, + size: PtySize, + request_timeout: Optional[float] = None) +``` + +Resize PTY. + +Call this when the terminal window is resized and the number of columns and rows has changed. + +**Arguments**: + +- `pid`: Process ID of the PTY +- `size`: New size of the PTY +- `request_timeout`: Timeout for the request in **seconds** + + + + + + +## AsyncSandbox + +```python +class AsyncSandbox(SandboxApi) +``` + +E2B cloud sandbox is a secure and isolated cloud environment. + +The sandbox allows you to: +- Access Linux OS +- Create, list, and delete files and directories +- Run commands +- Run isolated code +- Access the internet + +Check docs [here](https://e2b.dev/docs). + +Use the `AsyncSandbox.create()` to create a new sandbox. + +**Example**: + +```python +from e2b import AsyncSandbox + +sandbox = await AsyncSandbox.create() +``` + + + +### files + +```python +@property +def files() -> Filesystem +``` + +Module for interacting with the sandbox filesystem. + + + +### commands + +```python +@property +def commands() -> Commands +``` + +Module for running commands in the sandbox. + + + +### pty + +```python +@property +def pty() -> Pty +``` + +Module for interacting with the sandbox pseudo-terminal. + + + +### \_\_init\_\_ + +```python +def __init__(**opts: Unpack[SandboxOpts]) +``` + +Use `AsyncSandbox.create()` to create a new sandbox instead. + + + +### is\_running + +```python +async def is_running(request_timeout: Optional[float] = None) -> bool +``` + +Check if the sandbox is running. + +**Arguments**: + +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`True` if the sandbox is running, `False` otherwise +Example +```python +sandbox = await AsyncSandbox.create() +await sandbox.is_running() # Returns True + +await sandbox.kill() +await sandbox.is_running() # Returns False +``` + + + +### create + +```python +@classmethod +async def create(cls, + template: Optional[str] = None, + timeout: Optional[int] = None, + metadata: Optional[Dict[str, str]] = None, + envs: Optional[Dict[str, str]] = None, + secure: bool = True, + allow_internet_access: bool = True, + mcp: Optional[McpServer] = None, + network: Optional[SandboxNetworkOpts] = None, + **opts: Unpack[ApiParams]) -> Self +``` + +Create a new sandbox. + +By default, the sandbox is created from the default `base` sandbox template. + +**Arguments**: + +- `template`: Sandbox template name or ID +- `timeout`: Timeout for the sandbox in **seconds**, default to 300 seconds. The maximum time a sandbox can be kept alive is 24 hours (86_400 seconds) for Pro users and 1 hour (3_600 seconds) for Hobby users. +- `metadata`: Custom metadata for the sandbox +- `envs`: Custom environment variables for the sandbox +- `secure`: Envd is secured with access token and cannot be used without it, defaults to `True`. +- `allow_internet_access`: Allow sandbox to access the internet, defaults to `True`. If set to `False`, it works the same as setting network `deny_out` to `[0.0.0.0/0]`. +- `mcp`: MCP server to enable in the sandbox +- `network`: Sandbox network configuration + +**Returns**: + +A Sandbox instance for the new sandbox +Use this method instead of using the constructor to create a new sandbox. + + + +### connect + +```python +@overload +async def connect(timeout: Optional[int] = None, + **opts: Unpack[ApiParams]) -> Self +``` + +Connect to a sandbox. If the sandbox is paused, it will be automatically resumed. + +Sandbox must be either running or be paused. + +With sandbox ID you can connect to the same sandbox from different places or environments (serverless functions, etc). + +**Arguments**: + +- `timeout`: Timeout for the sandbox in **seconds** +For running sandboxes, the timeout will update only if the new timeout is longer than the existing one. + +**Returns**: + +A running sandbox instance +@example +```python +sandbox = await AsyncSandbox.create() +await sandbox.beta_pause() + +same_sandbox = await sandbox.connect() +``` + + + +### connect + +```python +@overload +@classmethod +async def connect(cls, + sandbox_id: str, + timeout: Optional[int] = None, + **opts: Unpack[ApiParams]) -> Self +``` + +Connect to a sandbox. If the sandbox is paused, it will be automatically resumed. + +Sandbox must be either running or be paused. + +With sandbox ID you can connect to the same sandbox from different places or environments (serverless functions, etc). + +**Arguments**: + +- `sandbox_id`: Sandbox ID +- `timeout`: Timeout for the sandbox in **seconds** +For running sandboxes, the timeout will update only if the new timeout is longer than the existing one. + +**Returns**: + +A running sandbox instance +@example +```python +sandbox = await AsyncSandbox.create() +await AsyncSandbox.beta_pause(sandbox.sandbox_id) + +same_sandbox = await AsyncSandbox.connect(sandbox.sandbox_id)) +``` + + + +### connect + +```python +@class_method_variant("_cls_connect") +async def connect(timeout: Optional[int] = None, + **opts: Unpack[ApiParams]) -> Self +``` + +Connect to a sandbox. If the sandbox is paused, it will be automatically resumed. + +Sandbox must be either running or be paused. + +With sandbox ID you can connect to the same sandbox from different places or environments (serverless functions, etc). + +**Arguments**: + +- `timeout`: Timeout for the sandbox in **seconds** +For running sandboxes, the timeout will update only if the new timeout is longer than the existing one. + +**Returns**: + +A running sandbox instance +@example +```python +sandbox = await AsyncSandbox.create() +await sandbox.beta_pause() + +same_sandbox = await sandbox.connect() +``` + + + +### kill + +```python +@overload +async def kill(**opts: Unpack[ApiParams]) -> bool +``` + +Kill the sandbox. + +**Returns**: + +`True` if the sandbox was killed, `False` if the sandbox was not found + + + +### kill + +```python +@overload +@staticmethod +async def kill(sandbox_id: str, **opts: Unpack[ApiParams]) -> bool +``` + +Kill the sandbox specified by sandbox ID. + +**Arguments**: + +- `sandbox_id`: Sandbox ID + +**Returns**: + +`True` if the sandbox was killed, `False` if the sandbox was not found + + + +### kill + +```python +@class_method_variant("_cls_kill") +async def kill(**opts: Unpack[ApiParams]) -> bool +``` + +Kill the sandbox specified by sandbox ID. + +**Returns**: + +`True` if the sandbox was killed, `False` if the sandbox was not found + + + +### set\_timeout + +```python +@overload +async def set_timeout(timeout: int, **opts: Unpack[ApiParams]) -> None +``` + +Set the timeout of the sandbox. + +After the timeout expires, the sandbox will be automatically killed. +This method can extend or reduce the sandbox timeout set when creating the sandbox or from the last call to `.set_timeout`. + +The maximum time a sandbox can be kept alive is 24 hours (86_400 seconds) for Pro users and 1 hour (3_600 seconds) for Hobby users. + +**Arguments**: + +- `timeout`: Timeout for the sandbox in **seconds** + + + +### set\_timeout + +```python +@overload +@staticmethod +async def set_timeout(sandbox_id: str, timeout: int, + **opts: Unpack[ApiParams]) -> None +``` + +Set the timeout of the specified sandbox. + +After the timeout expires, the sandbox will be automatically killed. +This method can extend or reduce the sandbox timeout set when creating the sandbox or from the last call to `.set_timeout`. + +The maximum time a sandbox can be kept alive is 24 hours (86_400 seconds) for Pro users and 1 hour (3_600 seconds) for Hobby users. + +**Arguments**: + +- `sandbox_id`: Sandbox ID +- `timeout`: Timeout for the sandbox in **seconds** + + + +### set\_timeout + +```python +@class_method_variant("_cls_set_timeout") +async def set_timeout(timeout: int, **opts: Unpack[ApiParams]) -> None +``` + +Set the timeout of the specified sandbox. + +After the timeout expires, the sandbox will be automatically killed. +This method can extend or reduce the sandbox timeout set when creating the sandbox or from the last call to `.set_timeout`. + +The maximum time a sandbox can be kept alive is 24 hours (86_400 seconds) for Pro users and 1 hour (3_600 seconds) for Hobby users. + +**Arguments**: + +- `timeout`: Timeout for the sandbox in **seconds** + + + +### get\_info + +```python +@overload +async def get_info(**opts: Unpack[ApiParams]) -> SandboxInfo +``` + +Get sandbox information like sandbox ID, template, metadata, started at/end at date. + +**Returns**: + +Sandbox info + + + +### get\_info + +```python +@overload +@staticmethod +async def get_info(sandbox_id: str, **opts: Unpack[ApiParams]) -> SandboxInfo +``` + +Get sandbox information like sandbox ID, template, metadata, started at/end at date. + +**Arguments**: + +- `sandbox_id`: Sandbox ID + +**Returns**: + +Sandbox info + + + +### get\_info + +```python +@class_method_variant("_cls_get_info") +async def get_info(**opts: Unpack[ApiParams]) -> SandboxInfo +``` + +Get sandbox information like sandbox ID, template, metadata, started at/end at date. + +**Returns**: + +Sandbox info + + + +### get\_metrics + +```python +@overload +async def get_metrics(start: Optional[datetime.datetime] = None, + end: Optional[datetime.datetime] = None, + **opts: Unpack[ApiParams]) -> List[SandboxMetrics] +``` + +Get the metrics of the current sandbox. + +**Arguments**: + +- `start`: Start time for the metrics, defaults to the start of the sandbox +- `end`: End time for the metrics, defaults to the current time + +**Returns**: + +List of sandbox metrics containing CPU, memory and disk usage information + + + +### get\_metrics + +```python +@overload +@staticmethod +async def get_metrics(sandbox_id: str, + start: Optional[datetime.datetime] = None, + end: Optional[datetime.datetime] = None, + **opts: Unpack[ApiParams]) -> List[SandboxMetrics] +``` + +Get the metrics of the sandbox specified by sandbox ID. + +**Arguments**: + +- `sandbox_id`: Sandbox ID +- `start`: Start time for the metrics, defaults to the start of the sandbox +- `end`: End time for the metrics, defaults to the current time + +**Returns**: + +List of sandbox metrics containing CPU, memory and disk usage information + + + +### get\_metrics + +```python +@class_method_variant("_cls_get_metrics") +async def get_metrics(start: Optional[datetime.datetime] = None, + end: Optional[datetime.datetime] = None, + **opts: Unpack[ApiParams]) -> List[SandboxMetrics] +``` + +Get the metrics of the current sandbox. + +**Arguments**: + +- `start`: Start time for the metrics, defaults to the start of the sandbox +- `end`: End time for the metrics, defaults to the current time + +**Returns**: + +List of sandbox metrics containing CPU, memory and disk usage information + + + +### beta\_create + +```python +@classmethod +async def beta_create(cls, + template: Optional[str] = None, + timeout: Optional[int] = None, + auto_pause: bool = False, + metadata: Optional[Dict[str, str]] = None, + envs: Optional[Dict[str, str]] = None, + secure: bool = True, + allow_internet_access: bool = True, + mcp: Optional[McpServer] = None, + **opts: Unpack[ApiParams]) -> Self +``` + +[BETA] This feature is in beta and may change in the future. + +Create a new sandbox. + +By default, the sandbox is created from the default `base` sandbox template. + +**Arguments**: + +- `template`: Sandbox template name or ID +- `timeout`: Timeout for the sandbox in **seconds**, default to 300 seconds. The maximum time a sandbox can be kept alive is 24 hours (86_400 seconds) for Pro users and 1 hour (3_600 seconds) for Hobby users. +- `auto_pause`: Automatically pause the sandbox after the timeout expires. Defaults to `False`. +- `metadata`: Custom metadata for the sandbox +- `envs`: Custom environment variables for the sandbox +- `secure`: Envd is secured with access token and cannot be used without it, defaults to `True`. +- `allow_internet_access`: Allow sandbox to access the internet, defaults to `True`. +- `mcp`: MCP server to enable in the sandbox + +**Returns**: + +A Sandbox instance for the new sandbox +Use this method instead of using the constructor to create a new sandbox. + + + +### beta\_pause + +```python +@overload +async def beta_pause(**opts: Unpack[ApiParams]) -> None +``` + +[BETA] This feature is in beta and may change in the future. + +Pause the sandbox. + +**Returns**: + +Sandbox ID that can be used to resume the sandbox + + + +### beta\_pause + +```python +@overload +@staticmethod +async def beta_pause(sandbox_id: str, **opts: Unpack[ApiParams]) -> None +``` + +[BETA] This feature is in beta and may change in the future. + +Pause the sandbox specified by sandbox ID. + +**Arguments**: + +- `sandbox_id`: Sandbox ID + +**Returns**: + +Sandbox ID that can be used to resume the sandbox + + + +### beta\_pause + +```python +@class_method_variant("_cls_pause") +async def beta_pause(**opts: Unpack[ApiParams]) -> None +``` + +[BETA] This feature is in beta and may change in the future. + +Pause the sandbox. + +**Returns**: + +Sandbox ID that can be used to resume the sandbox + + + +### get\_mcp\_token + +```python +async def get_mcp_token() -> Optional[str] +``` + +Get the MCP token for the sandbox. + +**Returns**: + +MCP token for the sandbox, or None if MCP is not enabled. diff --git a/docs/sdk-reference/python-sdk/v2.7.0/sandbox_sync.mdx b/docs/sdk-reference/python-sdk/v2.7.0/sandbox_sync.mdx new file mode 100644 index 0000000..04927a8 --- /dev/null +++ b/docs/sdk-reference/python-sdk/v2.7.0/sandbox_sync.mdx @@ -0,0 +1,1343 @@ +--- +sidebarTitle: "Sandbox Sync" +mode: "center" +--- + + + + + + +## WatchHandle + +```python +class WatchHandle() +``` + +Handle for watching filesystem events. +It is used to get the latest events that have occurred in the watched directory. + +Use `.stop()` to stop watching the directory. + + + +### stop + +```python +def stop() +``` + +Stop watching the directory. +After you stop the watcher you won't be able to get the events anymore. + + + +### get\_new\_events + +```python +def get_new_events() -> List[FilesystemEvent] +``` + +Get the latest events that have occurred in the watched directory since the last call, or from the beginning of the watching, up until now. + +**Returns**: + +List of filesystem events + + + + + + +## Filesystem + +```python +class Filesystem() +``` + +Module for interacting with the filesystem in the sandbox. + + + +### read + +```python +@overload +def read(path: str, + format: Literal["text"] = "text", + user: Optional[Username] = None, + request_timeout: Optional[float] = None) -> str +``` + +Read file content as a `str`. + +**Arguments**: + +- `path`: Path to the file +- `user`: Run the operation as this user +- `format`: Format of the file content—`text` by default +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +File content as a `str` + + + +### read + +```python +@overload +def read(path: str, + format: Literal["bytes"], + user: Optional[Username] = None, + request_timeout: Optional[float] = None) -> bytearray +``` + +Read file content as a `bytearray`. + +**Arguments**: + +- `path`: Path to the file +- `user`: Run the operation as this user +- `format`: Format of the file content—`bytes` +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +File content as a `bytearray` + + + +### read + +```python +@overload +def read(path: str, + format: Literal["stream"], + user: Optional[Username] = None, + request_timeout: Optional[float] = None) -> Iterator[bytes] +``` + +Read file content as a `Iterator[bytes]`. + +**Arguments**: + +- `path`: Path to the file +- `user`: Run the operation as this user +- `format`: Format of the file content—`stream` +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +File content as an `Iterator[bytes]` + + + +### write + +```python +def write(path: str, + data: Union[str, bytes, IO], + user: Optional[Username] = None, + request_timeout: Optional[float] = None) -> WriteInfo +``` + +Write content to a file on the path. + +Writing to a file that doesn't exist creates the file. +Writing to a file that already exists overwrites the file. +Writing to a file at path that doesn't exist creates the necessary directories. + +**Arguments**: + +- `path`: Path to the file +- `data`: Data to write to the file, can be a `str`, `bytes`, or `IO`. +- `user`: Run the operation as this user +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +Information about the written file + + + +### write\_files + +```python +def write_files(files: List[WriteEntry], + user: Optional[Username] = None, + request_timeout: Optional[float] = None) -> List[WriteInfo] +``` + +Writes a list of files to the filesystem. + +When writing to a file that doesn't exist, the file will get created. +When writing to a file that already exists, the file will get overwritten. +When writing to a file that's in a directory that doesn't exist, you'll get an error. + +**Arguments**: + +- `files`: list of files to write as `WriteEntry` objects, each containing `path` and `data` +- `user`: Run the operation as this user +- `request_timeout`: Timeout for the request + +**Returns**: + +Information about the written files + + + +### list + +```python +def list(path: str, + depth: Optional[int] = 1, + user: Optional[Username] = None, + request_timeout: Optional[float] = None) -> List[EntryInfo] +``` + +List entries in a directory. + +**Arguments**: + +- `path`: Path to the directory +- `depth`: Depth of the directory to list +- `user`: Run the operation as this user +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +List of entries in the directory + + + +### exists + +```python +def exists(path: str, + user: Optional[Username] = None, + request_timeout: Optional[float] = None) -> bool +``` + +Check if a file or a directory exists. + +**Arguments**: + +- `path`: Path to a file or a directory +- `user`: Run the operation as this user +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`True` if the file or directory exists, `False` otherwise + + + +### get\_info + +```python +def get_info(path: str, + user: Optional[Username] = None, + request_timeout: Optional[float] = None) -> EntryInfo +``` + +Get information about a file or directory. + +**Arguments**: + +- `path`: Path to a file or a directory +- `user`: Run the operation as this user +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +Information about the file or directory like name, type, and path + + + +### remove + +```python +def remove(path: str, + user: Optional[Username] = None, + request_timeout: Optional[float] = None) -> None +``` + +Remove a file or a directory. + +**Arguments**: + +- `path`: Path to a file or a directory +- `user`: Run the operation as this user +- `request_timeout`: Timeout for the request in **seconds** + + + +### rename + +```python +def rename(old_path: str, + new_path: str, + user: Optional[Username] = None, + request_timeout: Optional[float] = None) -> EntryInfo +``` + +Rename a file or directory. + +**Arguments**: + +- `old_path`: Path to the file or directory to rename +- `new_path`: New path to the file or directory +- `user`: Run the operation as this user +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +Information about the renamed file or directory + + + +### make\_dir + +```python +def make_dir(path: str, + user: Optional[Username] = None, + request_timeout: Optional[float] = None) -> bool +``` + +Create a new directory and all directories along the way if needed on the specified path. + +**Arguments**: + +- `path`: Path to a new directory. For example '/dirA/dirB' when creating 'dirB'. +- `user`: Run the operation as this user +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`True` if the directory was created, `False` if the directory already exists + + + +### watch\_dir + +```python +def watch_dir(path: str, + user: Optional[Username] = None, + request_timeout: Optional[float] = None, + recursive: bool = False) -> WatchHandle +``` + +Watch directory for filesystem events. + +**Arguments**: + +- `path`: Path to a directory to watch +- `user`: Run the operation as this user +- `request_timeout`: Timeout for the request in **seconds** +- `recursive`: Watch directory recursively + +**Returns**: + +`WatchHandle` object for stopping watching directory + + + + + + +## SandboxPaginator + +```python +class SandboxPaginator(SandboxPaginatorBase) +``` + +Paginator for listing sandboxes. + +**Example**: + +```python +paginator = Sandbox.list() + +while paginator.has_next: + sandboxes = paginator.next_items() + print(sandboxes) +``` + + + +### next\_items + +```python +def next_items() -> List[SandboxInfo] +``` + +Returns the next page of sandboxes. + +Call this method only if `has_next` is `True`, otherwise it will raise an exception. + +**Returns**: + +List of sandboxes + + + + + + +## SandboxApi + +```python +class SandboxApi(SandboxBase) +``` + + + +### list + +```python +@staticmethod +def list(query: Optional[SandboxQuery] = None, + limit: Optional[int] = None, + next_token: Optional[str] = None, + **opts: Unpack[ApiParams]) -> SandboxPaginator +``` + +List all running sandboxes. + +**Arguments**: + +- `query`: Filter the list of sandboxes by metadata or state, e.g. `SandboxListQuery(metadata={"key": "value"})` or `SandboxListQuery(state=[SandboxState.RUNNING])` +- `limit`: Maximum number of sandboxes to return per page +- `next_token`: Token for pagination + +**Returns**: + +List of running sandboxes + + + + + + +## Commands + +```python +class Commands() +``` + +Module for executing commands in the sandbox. + + + +### list + +```python +def list(request_timeout: Optional[float] = None) -> List[ProcessInfo] +``` + +Lists all running commands and PTY sessions. + +**Arguments**: + +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +List of running commands and PTY sessions + + + +### kill + +```python +def kill(pid: int, request_timeout: Optional[float] = None) -> bool +``` + +Kills a running command specified by its process ID. + +It uses `SIGKILL` signal to kill the command. + +**Arguments**: + +- `pid`: Process ID of the command. You can get the list of processes using `sandbox.commands.list()` +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`True` if the command was killed, `False` if the command was not found + + + +### send\_stdin + +```python +def send_stdin(pid: int, data: str, request_timeout: Optional[float] = None) +``` + +Send data to command stdin. + +:param pid Process ID of the command. You can get the list of processes using `sandbox.commands.list()`. +:param data: Data to send to the command +:param request_timeout: Timeout for the request in **seconds** + + + + +### run + +```python +@overload +def run(cmd: str, + background: Union[Literal[False], None] = None, + envs: Optional[Dict[str, str]] = None, + user: Optional[Username] = None, + cwd: Optional[str] = None, + on_stdout: Optional[Callable[[str], None]] = None, + on_stderr: Optional[Callable[[str], None]] = None, + stdin: Optional[bool] = None, + timeout: Optional[float] = 60, + request_timeout: Optional[float] = None) -> CommandResult +``` + +Start a new command and wait until it finishes executing. + +**Arguments**: + +- `cmd`: Command to execute +- `background`: **`False` if the command should be executed in the foreground**, `True` if the command should be executed in the background +- `envs`: Environment variables used for the command +- `user`: User to run the command as +- `cwd`: Working directory to run the command +- `on_stdout`: Callback for command stdout output +- `on_stderr`: Callback for command stderr output +- `stdin`: If `True`, the command will have a stdin stream that you can send data to using `sandbox.commands.send_stdin()` +- `timeout`: Timeout for the command connection in **seconds**. Using `0` will not limit the command connection time +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`CommandResult` result of the command execution + + + +### run + +```python +@overload +def run(cmd: str, + background: Literal[True], + envs: Optional[Dict[str, str]] = None, + user: Optional[Username] = None, + cwd: Optional[str] = None, + on_stdout: None = None, + on_stderr: None = None, + stdin: Optional[bool] = None, + timeout: Optional[float] = 60, + request_timeout: Optional[float] = None) -> CommandHandle +``` + +Start a new command and return a handle to interact with it. + +**Arguments**: + +- `cmd`: Command to execute +- `background`: `False` if the command should be executed in the foreground, **`True` if the command should be executed in the background** +- `envs`: Environment variables used for the command +- `user`: User to run the command as +- `cwd`: Working directory to run the command +- `stdin`: If `True`, the command will have a stdin stream that you can send data to using `sandbox.commands.send_stdin()` +- `timeout`: Timeout for the command connection in **seconds**. Using `0` will not limit the command connection time +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`CommandHandle` handle to interact with the running command + + + +### connect + +```python +def connect(pid: int, + timeout: Optional[float] = 60, + request_timeout: Optional[float] = None) +``` + +Connects to a running command. + +You can use `CommandHandle.wait()` to wait for the command to finish and get execution results. + +**Arguments**: + +- `pid`: Process ID of the command to connect to. You can get the list of processes using `sandbox.commands.list()` +- `timeout`: Timeout for the connection in **seconds**. Using `0` will not limit the connection time +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`CommandHandle` handle to interact with the running command + + + + + + +## CommandHandle + +```python +class CommandHandle() +``` + +Command execution handle. + +It provides methods for waiting for the command to finish, retrieving stdout/stderr, and killing the command. + + + +### pid + +```python +@property +def pid() +``` + +Command process ID. + + + +### \_\_iter\_\_ + +```python +def __iter__() +``` + +Iterate over the command output. + +**Returns**: + +Generator of command outputs + + + +### disconnect + +```python +def disconnect() -> None +``` + +Disconnect from the command. + +The command is not killed, but SDK stops receiving events from the command. +You can reconnect to the command using `sandbox.commands.connect` method. + + + +### wait + +```python +def wait(on_pty: Optional[Callable[[PtyOutput], None]] = None, + on_stdout: Optional[Callable[[str], None]] = None, + on_stderr: Optional[Callable[[str], None]] = None) -> CommandResult +``` + +Wait for the command to finish and returns the result. + +If the command exits with a non-zero exit code, it throws a `CommandExitException`. + +**Arguments**: + +- `on_pty`: Callback for pty output +- `on_stdout`: Callback for stdout output +- `on_stderr`: Callback for stderr output + +**Returns**: + +`CommandResult` result of command execution + + + +### kill + +```python +def kill() -> bool +``` + +Kills the command. + +It uses `SIGKILL` signal to kill the command. + +**Returns**: + +Whether the command was killed successfully + + + + + + +## Pty + +```python +class Pty() +``` + +Module for interacting with PTYs (pseudo-terminals) in the sandbox. + + + +### kill + +```python +def kill(pid: int, request_timeout: Optional[float] = None) -> bool +``` + +Kill PTY. + +**Arguments**: + +- `pid`: Process ID of the PTY +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`true` if the PTY was killed, `false` if the PTY was not found + + + +### send\_stdin + +```python +def send_stdin(pid: int, + data: bytes, + request_timeout: Optional[float] = None) -> None +``` + +Send input to a PTY. + +**Arguments**: + +- `pid`: Process ID of the PTY +- `data`: Input data to send +- `request_timeout`: Timeout for the request in **seconds** + + + +### create + +```python +def create(size: PtySize, + user: Optional[Username] = None, + cwd: Optional[str] = None, + envs: Optional[Dict[str, str]] = None, + timeout: Optional[float] = 60, + request_timeout: Optional[float] = None) -> CommandHandle +``` + +Start a new PTY (pseudo-terminal). + +**Arguments**: + +- `size`: Size of the PTY +- `user`: User to use for the PTY +- `cwd`: Working directory for the PTY +- `envs`: Environment variables for the PTY +- `timeout`: Timeout for the PTY in **seconds** +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +Handle to interact with the PTY + + + +### resize + +```python +def resize(pid: int, + size: PtySize, + request_timeout: Optional[float] = None) -> None +``` + +Resize PTY. + +Call this when the terminal window is resized and the number of columns and rows has changed. + +**Arguments**: + +- `pid`: Process ID of the PTY +- `size`: New size of the PTY +- `request_timeout`: Timeout for the request in **seconds**s + + + + + + +## Sandbox + +```python +class Sandbox(SandboxApi) +``` + +E2B cloud sandbox is a secure and isolated cloud environment. + +The sandbox allows you to: +- Access Linux OS +- Create, list, and delete files and directories +- Run commands +- Run isolated code +- Access the internet + +Check docs [here](https://e2b.dev/docs). + +Use the `Sandbox.create()` to create a new sandbox. + +**Example**: + +```python +from e2b import Sandbox + +sandbox = Sandbox.create() +``` + + + +### files + +```python +@property +def files() -> Filesystem +``` + +Module for interacting with the sandbox filesystem. + + + +### commands + +```python +@property +def commands() -> Commands +``` + +Module for running commands in the sandbox. + + + +### pty + +```python +@property +def pty() -> Pty +``` + +Module for interacting with the sandbox pseudo-terminal. + + + +### \_\_init\_\_ + +```python +def __init__(**opts: Unpack[SandboxOpts]) +``` + +:deprecated: This constructor is deprecated + +Use `Sandbox.create()` to create a new sandbox instead. + + + +### is\_running + +```python +def is_running(request_timeout: Optional[float] = None) -> bool +``` + +Check if the sandbox is running. + +**Arguments**: + +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`True` if the sandbox is running, `False` otherwise +Example +```python +sandbox = Sandbox.create() +sandbox.is_running() # Returns True + +sandbox.kill() +sandbox.is_running() # Returns False +``` + + + +### create + +```python +@classmethod +def create(cls, + template: Optional[str] = None, + timeout: Optional[int] = None, + metadata: Optional[Dict[str, str]] = None, + envs: Optional[Dict[str, str]] = None, + secure: bool = True, + allow_internet_access: bool = True, + mcp: Optional[McpServer] = None, + network: Optional[SandboxNetworkOpts] = None, + **opts: Unpack[ApiParams]) -> Self +``` + +Create a new sandbox. + +By default, the sandbox is created from the default `base` sandbox template. + +**Arguments**: + +- `template`: Sandbox template name or ID +- `timeout`: Timeout for the sandbox in **seconds**, default to 300 seconds. The maximum time a sandbox can be kept alive is 24 hours (86_400 seconds) for Pro users and 1 hour (3_600 seconds) for Hobby users. +- `metadata`: Custom metadata for the sandbox +- `envs`: Custom environment variables for the sandbox +- `secure`: Envd is secured with access token and cannot be used without it, defaults to `True`. +- `allow_internet_access`: Allow sandbox to access the internet, defaults to `True`. If set to `False`, it works the same as setting network `deny_out` to `[0.0.0.0/0]`. +- `mcp`: MCP server to enable in the sandbox +- `network`: Sandbox network configuration + +**Returns**: + +A Sandbox instance for the new sandbox +Use this method instead of using the constructor to create a new sandbox. + + + +### connect + +```python +@overload +def connect(timeout: Optional[int] = None, **opts: Unpack[ApiParams]) -> Self +``` + +Connect to a sandbox. If the sandbox is paused, it will be automatically resumed. + +Sandbox must be either running or be paused. + +With sandbox ID you can connect to the same sandbox from different places or environments (serverless functions, etc). + +**Arguments**: + +- `timeout`: Timeout for the sandbox in **seconds** +For running sandboxes, the timeout will update only if the new timeout is longer than the existing one. + +**Returns**: + +A running sandbox instance +@example +```python +sandbox = Sandbox.create() +sandbox.beta_pause() + +same_sandbox = sandbox.connect() + + + +### connect + +```python +@overload +@classmethod +def connect(cls, + sandbox_id: str, + timeout: Optional[int] = None, + **opts: Unpack[ApiParams]) -> Self +``` + +Connect to a sandbox. If the sandbox is paused, it will be automatically resumed. + +Sandbox must be either running or be paused. + +With sandbox ID you can connect to the same sandbox from different places or environments (serverless functions, etc). + +**Arguments**: + +- `sandbox_id`: Sandbox ID +- `timeout`: Timeout for the sandbox in **seconds**. +For running sandboxes, the timeout will update only if the new timeout is longer than the existing one. + +**Returns**: + +A running sandbox instance +@example +```python +sandbox = Sandbox.create() +Sandbox.beta_pause(sandbox.sandbox_id) + +same_sandbox = Sandbox.connect(sandbox.sandbox_id) +``` + + + +### connect + +```python +@class_method_variant("_cls_connect") +def connect(timeout: Optional[int] = None, **opts: Unpack[ApiParams]) -> Self +``` + +Connect to a sandbox. If the sandbox is paused, it will be automatically resumed. + +Sandbox must be either running or be paused. + +With sandbox ID you can connect to the same sandbox from different places or environments (serverless functions, etc). + +**Arguments**: + +- `timeout`: Timeout for the sandbox in **seconds**. +For running sandboxes, the timeout will update only if the new timeout is longer than the existing one. + +**Returns**: + +A running sandbox instance +@example +```python +sandbox = Sandbox.create() +sandbox.beta_pause() + +same_sandbox = sandbox.connect() +``` + + + +### kill + +```python +@overload +def kill(**opts: Unpack[ApiParams]) -> bool +``` + +Kill the sandbox. + +**Returns**: + +`True` if the sandbox was killed, `False` if the sandbox was not found + + + +### kill + +```python +@overload +@staticmethod +def kill(sandbox_id: str, **opts: Unpack[ApiParams]) -> bool +``` + +Kill the sandbox specified by sandbox ID. + +**Arguments**: + +- `sandbox_id`: Sandbox ID + +**Returns**: + +`True` if the sandbox was killed, `False` if the sandbox was not found + + + +### kill + +```python +@class_method_variant("_cls_kill") +def kill(**opts: Unpack[ApiParams]) -> bool +``` + +Kill the sandbox specified by sandbox ID. + +**Returns**: + +`True` if the sandbox was killed, `False` if the sandbox was not found + + + +### set\_timeout + +```python +@overload +def set_timeout(timeout: int, **opts: Unpack[ApiParams]) -> None +``` + +Set the timeout of the sandbox. + +After the timeout expires, the sandbox will be automatically killed. +This method can extend or reduce the sandbox timeout set when creating the sandbox or from the last call to `.set_timeout`. + +The maximum time a sandbox can be kept alive is 24 hours (86_400 seconds) for Pro users and 1 hour (3_600 seconds) for Hobby users. + +**Arguments**: + +- `timeout`: Timeout for the sandbox in **seconds** + + + +### set\_timeout + +```python +@overload +@staticmethod +def set_timeout(sandbox_id: str, timeout: int, + **opts: Unpack[ApiParams]) -> None +``` + +Set the timeout of the sandbox specified by sandbox ID. + +After the timeout expires, the sandbox will be automatically killed. +This method can extend or reduce the sandbox timeout set when creating the sandbox or from the last call to `.set_timeout`. + +The maximum time a sandbox can be kept alive is 24 hours (86_400 seconds) for Pro users and 1 hour (3_600 seconds) for Hobby users. + +**Arguments**: + +- `sandbox_id`: Sandbox ID +- `timeout`: Timeout for the sandbox in **seconds** + + + +### set\_timeout + +```python +@class_method_variant("_cls_set_timeout") +def set_timeout(timeout: int, **opts: Unpack[ApiParams]) -> None +``` + +Set the timeout of the sandbox. + +After the timeout expires, the sandbox will be automatically killed. +This method can extend or reduce the sandbox timeout set when creating the sandbox or from the last call to `.set_timeout`. + +The maximum time a sandbox can be kept alive is 24 hours (86_400 seconds) for Pro users and 1 hour (3_600 seconds) for Hobby users. + +**Arguments**: + +- `timeout`: Timeout for the sandbox in **seconds** + + + +### get\_info + +```python +@overload +def get_info(**opts: Unpack[ApiParams]) -> SandboxInfo +``` + +Get sandbox information like sandbox ID, template, metadata, started at/end at date. + +**Returns**: + +Sandbox info + + + +### get\_info + +```python +@overload +@staticmethod +def get_info(sandbox_id: str, **opts: Unpack[ApiParams]) -> SandboxInfo +``` + +Get sandbox information like sandbox ID, template, metadata, started at/end at date. + +**Arguments**: + +- `sandbox_id`: Sandbox ID + +**Returns**: + +Sandbox info + + + +### get\_info + +```python +@class_method_variant("_cls_get_info") +def get_info(**opts: Unpack[ApiParams]) -> SandboxInfo +``` + +Get sandbox information like sandbox ID, template, metadata, started at/end at date. + +**Returns**: + +Sandbox info + + + +### get\_metrics + +```python +@overload +def get_metrics(start: Optional[datetime.datetime] = None, + end: Optional[datetime.datetime] = None, + **opts: Unpack[ApiParams]) -> List[SandboxMetrics] +``` + +Get the metrics of the current sandbox. + +**Arguments**: + +- `start`: Start time for the metrics, defaults to the start of the sandbox +- `end`: End time for the metrics, defaults to the current time + +**Returns**: + +List of sandbox metrics containing CPU, memory and disk usage information + + + +### get\_metrics + +```python +@overload +@staticmethod +def get_metrics(sandbox_id: str, + start: Optional[datetime.datetime] = None, + end: Optional[datetime.datetime] = None, + **opts: Unpack[ApiParams]) -> List[SandboxMetrics] +``` + +Get the metrics of the sandbox specified by sandbox ID. + +**Arguments**: + +- `sandbox_id`: Sandbox ID +- `start`: Start time for the metrics, defaults to the start of the sandbox +- `end`: End time for the metrics, defaults to the current time + +**Returns**: + +List of sandbox metrics containing CPU, memory and disk usage information + + + +### get\_metrics + +```python +@class_method_variant("_cls_get_metrics") +def get_metrics(start: Optional[datetime.datetime] = None, + end: Optional[datetime.datetime] = None, + **opts: Unpack[ApiParams]) -> List[SandboxMetrics] +``` + +Get the metrics of the sandbox specified by sandbox ID. + +**Arguments**: + +- `start`: Start time for the metrics, defaults to the start of the sandbox +- `end`: End time for the metrics, defaults to the current time + +**Returns**: + +List of sandbox metrics containing CPU, memory and disk usage information + + + +### beta\_create + +```python +@classmethod +def beta_create(cls, + template: Optional[str] = None, + timeout: Optional[int] = None, + auto_pause: bool = False, + metadata: Optional[Dict[str, str]] = None, + envs: Optional[Dict[str, str]] = None, + secure: bool = True, + allow_internet_access: bool = True, + mcp: Optional[McpServer] = None, + **opts: Unpack[ApiParams]) -> Self +``` + +[BETA] This feature is in beta and may change in the future. + +Create a new sandbox. + +By default, the sandbox is created from the default `base` sandbox template. + +**Arguments**: + +- `template`: Sandbox template name or ID +- `timeout`: Timeout for the sandbox in **seconds**, default to 300 seconds. The maximum time a sandbox can be kept alive is 24 hours (86_400 seconds) for Pro users and 1 hour (3_600 seconds) for Hobby users. +- `auto_pause`: Automatically pause the sandbox after the timeout expires. Defaults to `False`. +- `metadata`: Custom metadata for the sandbox +- `envs`: Custom environment variables for the sandbox +- `secure`: Envd is secured with access token and cannot be used without it, defaults to `True`. +- `allow_internet_access`: Allow sandbox to access the internet, defaults to `True`. +- `mcp`: MCP server to enable in the sandbox + +**Returns**: + +A Sandbox instance for the new sandbox +Use this method instead of using the constructor to create a new sandbox. + + + +### beta\_pause + +```python +@overload +def beta_pause(**opts: Unpack[ApiParams]) -> None +``` + +[BETA] This feature is in beta and may change in the future. + +Pause the sandbox. + + + +### beta\_pause + +```python +@overload +@classmethod +def beta_pause(cls, sandbox_id: str, **opts: Unpack[ApiParams]) -> None +``` + +[BETA] This feature is in beta and may change in the future. + +Pause the sandbox specified by sandbox ID. + +**Arguments**: + +- `sandbox_id`: Sandbox ID + + + +### beta\_pause + +```python +@class_method_variant("_cls_pause") +def beta_pause(**opts: Unpack[ApiParams]) -> None +``` + +[BETA] This feature is in beta and may change in the future. + +Pause the sandbox. + +**Returns**: + +Sandbox ID that can be used to resume the sandbox + + + +### get\_mcp\_token + +```python +def get_mcp_token() -> Optional[str] +``` + +Get the MCP token for the sandbox. + +**Returns**: + +MCP token for the sandbox, or None if MCP is not enabled. diff --git a/docs/sdk-reference/python-sdk/v2.7.0/template.mdx b/docs/sdk-reference/python-sdk/v2.7.0/template.mdx new file mode 100644 index 0000000..9ac3cc8 --- /dev/null +++ b/docs/sdk-reference/python-sdk/v2.7.0/template.mdx @@ -0,0 +1,1686 @@ +--- +sidebarTitle: "Template" +mode: "center" +--- + + + + + + +## DockerfFileFinalParserInterface + +```python +class DockerfFileFinalParserInterface(Protocol) +``` + +Protocol defining the final interface for Dockerfile parsing callbacks. + + + +## DockerfileParserInterface + +```python +class DockerfileParserInterface(Protocol) +``` + +Protocol defining the interface for Dockerfile parsing callbacks. + + + +### run\_cmd + +```python +def run_cmd(command: Union[str, List[str]], + user: Optional[str] = None) -> "DockerfileParserInterface" +``` + +Handle RUN instruction. + + + +### copy + +```python +def copy(src: Union[str, List[CopyItem]], + dest: Optional[str] = None, + force_upload: Optional[Literal[True]] = None, + resolve_symlinks: Optional[bool] = None, + user: Optional[str] = None, + mode: Optional[int] = None) -> "DockerfileParserInterface" +``` + +Handle COPY instruction. + + + +### set\_workdir + +```python +def set_workdir(workdir: str) -> "DockerfileParserInterface" +``` + +Handle WORKDIR instruction. + + + +### set\_user + +```python +def set_user(user: str) -> "DockerfileParserInterface" +``` + +Handle USER instruction. + + + +### set\_envs + +```python +def set_envs(envs: Dict[str, str]) -> "DockerfileParserInterface" +``` + +Handle ENV instruction. + + + +### set\_start\_cmd + +```python +def set_start_cmd(start_cmd: str, + ready_cmd: str) -> "DockerfFileFinalParserInterface" +``` + +Handle CMD/ENTRYPOINT instruction. + + + +### parse\_dockerfile + +```python +def parse_dockerfile(dockerfile_content_or_path: str, + template_builder: DockerfileParserInterface) -> str +``` + +Parse a Dockerfile and convert it to Template SDK format. + +**Arguments**: + +- `dockerfile_content_or_path`: Either the Dockerfile content as a string, or a path to a Dockerfile file +- `template_builder`: Interface providing template builder methods + +**Raises**: + +- `ValueError`: If the Dockerfile is invalid or unsupported + +**Returns**: + +The base image from the Dockerfile + + + + + + +## InstructionType + +```python +class InstructionType(str, Enum) +``` + +Types of instructions that can be used in a template. + + + +## CopyItem + +```python +class CopyItem(TypedDict) +``` + +Configuration for a single file/directory copy operation. + + + +## Instruction + +```python +class Instruction(TypedDict) +``` + +Represents a single instruction in the template build process. + + + +## GenericDockerRegistry + +```python +class GenericDockerRegistry(TypedDict) +``` + +Configuration for a generic Docker registry with basic authentication. + + + +## AWSRegistry + +```python +class AWSRegistry(TypedDict) +``` + +Configuration for AWS Elastic Container Registry (ECR). + + + +## GCPRegistry + +```python +class GCPRegistry(TypedDict) +``` + +Configuration for Google Container Registry (GCR) or Artifact Registry. + + + +## TemplateType + +```python +class TemplateType(TypedDict) +``` + +Internal representation of a template for the E2B build API. + + + +## BuildInfo + +```python +@dataclass +class BuildInfo() +``` + +Information about a built template. + + + + + + +## LogEntry + +```python +@dataclass +class LogEntry() +``` + +Represents a single log entry from the template build process. + + + +## LogEntryStart + +```python +@dataclass +class LogEntryStart(LogEntry) +``` + +Special log entry indicating the start of a build process. + + + +## LogEntryEnd + +```python +@dataclass +class LogEntryEnd(LogEntry) +``` + +Special log entry indicating the end of a build process. + + + +### TIMER\_UPDATE\_INTERVAL\_MS + +Default minimum log level to display. + + + +### DEFAULT\_LEVEL + +Colored labels for each log level. + + + +### levels + +Numeric ordering of log levels for comparison (lower = less severe). + + + +### set\_interval + +```python +def set_interval(func, interval) +``` + +Returns a stop function that can be called to cancel the interval. + +Similar to JavaScript's setInterval. + +**Arguments**: + +- `func`: Function to execute at each interval +- `interval`: Interval duration in **seconds** + +**Returns**: + +Stop function that can be called to cancel the interval + + + +### default\_build\_logger + +```python +def default_build_logger( + min_level: Optional[LogEntryLevel] = None +) -> Callable[[LogEntry], None] +``` + +Create a default build logger with animated timer display. + +**Arguments**: + +- `min_level`: Minimum log level to display (default: 'info') + +**Returns**: + +Logger function that accepts LogEntry instances +Example +```python +from e2b import Template, default_build_logger + +template = Template().from_python_image() + +``` + + + + +Special step name for the finalization phase of template building. +This is the last step that runs after all user-defined instructions. + + + +### FINALIZE\_STEP\_NAME + +Special step name for the base image phase of template building. +This is the first step that sets up the base image. + + + +### BASE\_STEP\_NAME + +Stack trace depth for capturing caller information. + +Depth levels: +1. TemplateClass +2. Caller method (e.g., copy(), from_image(), etc.) + +This depth is used to determine the original caller's location +for stack traces. + + + +### STACK\_TRACE\_DEPTH + +Default setting for whether to resolve symbolic links when copying files. +When False, symlinks are copied as symlinks rather than following them. + + + + + + +## ReadyCmd + +```python +class ReadyCmd() +``` + +Wrapper class for ready check commands. + + + +### wait\_for\_port + +```python +def wait_for_port(port: int) +``` + +Wait for a port to be listening. + +Uses `ss` command to check if a port is open and listening. + +**Arguments**: + +- `port`: Port number to wait for + +**Returns**: + +ReadyCmd that checks for the port +Example +```python +from e2b import Template, wait_for_port + +template = ( + Template() + .from_python_image() + .set_start_cmd('python -m http.server 8000', wait_for_port(8000)) +) +``` + + + +### wait\_for\_url + +```python +def wait_for_url(url: str, status_code: int = 200) +``` + +Wait for a URL to return a specific HTTP status code. + +Uses `curl` to make HTTP requests and check the response status. + +**Arguments**: + +- `url`: URL to check (e.g., 'http://localhost:3000/health') +- `status_code`: Expected HTTP status code (default: 200) + +**Returns**: + +ReadyCmd that checks the URL +Example +```python +from e2b import Template, wait_for_url + +template = ( + Template() + .from_node_image() + .set_start_cmd('npm start', wait_for_url('http://localhost:3000/health')) +) +``` + + + +### wait\_for\_process + +```python +def wait_for_process(process_name: str) +``` + +Wait for a process with a specific name to be running. + +Uses `pgrep` to check if a process exists. + +**Arguments**: + +- `process_name`: Name of the process to wait for + +**Returns**: + +ReadyCmd that checks for the process +Example +```python +from e2b import Template, wait_for_process + +template = ( + Template() + .from_base_image() + .set_start_cmd('./my-daemon', wait_for_process('my-daemon')) +) +``` + + + +### wait\_for\_file + +```python +def wait_for_file(filename: str) +``` + +Wait for a file to exist. + +Uses shell test command to check file existence. + +**Arguments**: + +- `filename`: Path to the file to wait for + +**Returns**: + +ReadyCmd that checks for the file +Example +```python +from e2b import Template, wait_for_file + +template = ( + Template() + .from_base_image() + .set_start_cmd('./init.sh', wait_for_file('/tmp/ready')) +) +``` + + + +### wait\_for\_timeout + +```python +def wait_for_timeout(timeout: int) +``` + +Wait for a specified timeout before considering the sandbox ready. + +Uses `sleep` command to wait for a fixed duration. + +**Arguments**: + +- `timeout`: Time to wait in **milliseconds** (minimum: 1000ms / 1 second) + +**Returns**: + +ReadyCmd that waits for the specified duration +Example +```python +from e2b import Template, wait_for_timeout + +template = ( + Template() + .from_node_image() + .set_start_cmd('npm start', wait_for_timeout(5000)) # Wait 5 seconds +) +``` + + + + + + +### read\_dockerignore + +```python +def read_dockerignore(context_path: str) -> List[str] +``` + +Read and parse a .dockerignore file. + +**Arguments**: + +- `context_path`: Directory path containing the .dockerignore file + +**Returns**: + +Array of ignore patterns (empty lines and comments are filtered out) + + + +### get\_all\_files\_in\_path + +```python +def get_all_files_in_path(src: str, + context_path: str, + ignore_patterns: List[str], + include_directories: bool = True) -> List[str] +``` + +Get all files for a given path and ignore patterns. + +**Arguments**: + +- `src`: Path to the source directory +- `context_path`: Base directory for resolving relative paths +- `ignore_patterns`: Ignore patterns +- `include_directories`: Whether to include directories + +**Returns**: + +Array of files + + + +### calculate\_files\_hash + +```python +def calculate_files_hash(src: str, dest: str, context_path: str, + ignore_patterns: List[str], resolve_symlinks: bool, + stack_trace: Optional[TracebackType]) -> str +``` + +Calculate a hash of files being copied to detect changes for cache invalidation. + +The hash includes file content, metadata (mode, size), and relative paths. +Note: uid, gid, and mtime are excluded to ensure stable hashes across environments. + +**Arguments**: + +- `src`: Source path pattern for files to copy +- `dest`: Destination path where files will be copied +- `context_path`: Base directory for resolving relative paths +- `ignore_patterns`: Glob patterns to ignore +- `resolve_symlinks`: Whether to resolve symbolic links when hashing +- `stack_trace`: Optional stack trace for error reporting + +**Raises**: + +- `ValueError`: If no files match the source pattern + +**Returns**: + +Hex string hash of all files + + + +### tar\_file\_stream + +```python +def tar_file_stream(file_name: str, file_context_path: str, + ignore_patterns: List[str], + resolve_symlinks: bool) -> io.BytesIO +``` + +Create a tar stream of files matching a pattern. + +**Arguments**: + +- `file_name`: Glob pattern for files to include +- `file_context_path`: Base directory for resolving file paths +- `ignore_patterns`: Ignore patterns +- `resolve_symlinks`: Whether to resolve symbolic links + +**Returns**: + +Tar stream + + + +### strip\_ansi\_escape\_codes + +```python +def strip_ansi_escape_codes(text: str) -> str +``` + +Strip ANSI escape codes from a string. + +Source: https://github.com/chalk/ansi-regex/blob/main/index.js + +**Arguments**: + +- `text`: String with ANSI escape codes + +**Returns**: + +String without ANSI escape codes + + + +### get\_caller\_frame + +```python +def get_caller_frame(depth: int) -> Optional[FrameType] +``` + +Get the caller's stack frame at a specific depth. + +This is used to provide better error messages and debugging information +by tracking where template methods were called from in user code. + +**Arguments**: + +- `depth`: The depth of the stack trace to retrieve + +**Returns**: + +The caller frame, or None if not available + + + +### get\_caller\_directory + +```python +def get_caller_directory(depth: int) -> Optional[str] +``` + +Get the directory of the caller at a specific stack depth. + +This is used to determine the file_context_path when creating a template, +so file paths are resolved relative to the user's template file location. + +**Arguments**: + +- `depth`: The depth of the stack trace + +**Returns**: + +The caller's directory path, or None if not available + + + +### pad\_octal + +```python +def pad_octal(mode: int) -> str +``` + +Convert a numeric file mode to a zero-padded octal string. + +**Arguments**: + +- `mode`: File mode as a number (e.g., 493 for 0o755) + +**Returns**: + +Zero-padded 4-digit octal string (e.g., "0755") +Example +```python +pad_octal(0o755) # Returns "0755" +pad_octal(0o644) # Returns "0644" +``` + + + +### get\_build\_step\_index + +```python +def get_build_step_index(step: str, stack_traces_length: int) -> int +``` + +Get the array index for a build step based on its name. + +Special steps: +- BASE_STEP_NAME: Returns 0 (first step) +- FINALIZE_STEP_NAME: Returns the last index +- Numeric strings: Converted to number + +**Arguments**: + +- `step`: Build step name or number as string +- `stack_traces_length`: Total number of stack traces (used for FINALIZE_STEP_NAME) + +**Returns**: + +Index for the build step + + + +### read\_gcp\_service\_account\_json + +```python +def read_gcp_service_account_json(context_path: str, + path_or_content: Union[str, dict]) -> str +``` + +Read GCP service account JSON from a file or object. + +**Arguments**: + +- `context_path`: Base directory for resolving relative file paths +- `path_or_content`: Either a path to a JSON file or a service account object + +**Returns**: + +Service account JSON as a string + + + + + + +## TemplateBuilder + +```python +class TemplateBuilder() +``` + +Builder class for adding instructions to an E2B template. + +All methods return self to allow method chaining. + + + +### copy + +```python +def copy(src: Union[Union[str, Path], List[Union[str, Path]]], + dest: Union[str, Path], + force_upload: Optional[Literal[True]] = None, + user: Optional[str] = None, + mode: Optional[int] = None, + resolve_symlinks: Optional[bool] = None) -> "TemplateBuilder" +``` + +Copy files or directories from the local filesystem into the template. + +**Arguments**: + +- `src`: Source file(s) or directory path(s) to copy +- `dest`: Destination path in the template +- `force_upload`: Force upload even if files are cached +- `user`: User and optionally group (user:group) to own the files +- `mode`: File permissions in octal format (e.g., 0o755) +- `resolve_symlinks`: Whether to resolve symlinks + +**Returns**: + +`TemplateBuilder` class +Example +```python +template.copy('requirements.txt', '/home/user/') +template.copy(['app.py', 'config.py'], '/app/', mode=0o755) +``` + + + +### copy\_items + +```python +def copy_items(items: List[CopyItem]) -> "TemplateBuilder" +``` + +Copy multiple files or directories using a list of copy items. + +**Arguments**: + +- `items`: List of CopyItem dictionaries with src, dest, and optional parameters + +**Returns**: + +`TemplateBuilder` class +Example +```python +template.copy_items([ + {'src': 'app.py', 'dest': '/app/'}, + {'src': 'config.py', 'dest': '/app/', 'mode': 0o644} +]) +``` + + + +### remove + +```python +def remove(path: Union[Union[str, Path], List[Union[str, Path]]], + force: bool = False, + recursive: bool = False, + user: Optional[str] = None) -> "TemplateBuilder" +``` + +Remove files or directories in the template. + +**Arguments**: + +- `path`: File(s) or directory path(s) to remove +- `force`: Force removal without prompting +- `recursive`: Remove directories recursively +- `user`: User to run the command as + +**Returns**: + +`TemplateBuilder` class +Example +```python +template.remove('/tmp/cache', recursive=True, force=True) +template.remove('/tmp/cache', recursive=True, force=True, user='root') +``` + + + +### rename + +```python +def rename(src: Union[str, Path], + dest: Union[str, Path], + force: bool = False, + user: Optional[str] = None) -> "TemplateBuilder" +``` + +Rename or move a file or directory in the template. + +**Arguments**: + +- `src`: Source path +- `dest`: Destination path +- `force`: Force rename without prompting +- `user`: User to run the command as + +**Returns**: + +`TemplateBuilder` class +Example +```python +template.rename('/tmp/old.txt', '/tmp/new.txt') +template.rename('/tmp/old.txt', '/tmp/new.txt', user='root') +``` + + + +### make\_dir + +```python +def make_dir(path: Union[Union[str, Path], List[Union[str, Path]]], + mode: Optional[int] = None, + user: Optional[str] = None) -> "TemplateBuilder" +``` + +Create directory(ies) in the template. + +**Arguments**: + +- `path`: Directory path(s) to create +- `mode`: Directory permissions in octal format (e.g., 0o755) +- `user`: User to run the command as + +**Returns**: + +`TemplateBuilder` class +Example +```python +template.make_dir('/app/data', mode=0o755) +template.make_dir(['/app/logs', '/app/cache']) +template.make_dir('/app/data', mode=0o755, user='root') +``` + + + +### make\_symlink + +```python +def make_symlink(src: Union[str, Path], + dest: Union[str, Path], + user: Optional[str] = None, + force: bool = False) -> "TemplateBuilder" +``` + +Create a symbolic link in the template. + +**Arguments**: + +- `src`: Source path (target of the symlink) +- `dest`: Destination path (location of the symlink) +- `user`: User to run the command as +- `force`: Force symlink without prompting + +**Returns**: + +`TemplateBuilder` class +Example +```python +template.make_symlink('/usr/bin/python3', '/usr/bin/python') +template.make_symlink('/usr/bin/python3', '/usr/bin/python', user='root') +template.make_symlink('/usr/bin/python3', '/usr/bin/python', force=True) +``` + + + +### run\_cmd + +```python +def run_cmd(command: Union[str, List[str]], + user: Optional[str] = None) -> "TemplateBuilder" +``` + +Run a shell command during template build. + +**Arguments**: + +- `command`: Command string or list of commands to run (joined with &&) +- `user`: User to run the command as + +**Returns**: + +`TemplateBuilder` class +Example +```python +template.run_cmd('apt-get update') +template.run_cmd(['pip install numpy', 'pip install pandas']) +template.run_cmd('apt-get install vim', user='root') +``` + + + +### set\_workdir + +```python +def set_workdir(workdir: Union[str, Path]) -> "TemplateBuilder" +``` + +Set the working directory for subsequent commands in the template. + +**Arguments**: + +- `workdir`: Path to set as the working directory + +**Returns**: + +`TemplateBuilder` class +Example +```python +template.set_workdir('/app') +``` + + + +### set\_user + +```python +def set_user(user: str) -> "TemplateBuilder" +``` + +Set the user for subsequent commands in the template. + +**Arguments**: + +- `user`: Username to set + +**Returns**: + +`TemplateBuilder` class +Example +```python +template.set_user('root') +``` + + + +### pip\_install + +```python +def pip_install(packages: Optional[Union[str, List[str]]] = None, + g: bool = True) -> "TemplateBuilder" +``` + +Install Python packages using pip. + +**Arguments**: + +- `packages`: Package name(s) to install. If None, runs 'pip install .' in the current directory +- `g`: Install packages globally (default: True). If False, installs for user only + +**Returns**: + +`TemplateBuilder` class +Example +```python +template.pip_install('numpy') +template.pip_install(['pandas', 'scikit-learn']) +template.pip_install('numpy', g=False) # Install for user only +template.pip_install() # Installs from current directory +``` + + + +### npm\_install + +```python +def npm_install(packages: Optional[Union[str, List[str]]] = None, + g: Optional[bool] = False, + dev: Optional[bool] = False) -> "TemplateBuilder" +``` + +Install Node.js packages using npm. + +**Arguments**: + +- `packages`: Package name(s) to install. If None, installs from package.json +- `g`: Install packages globally +- `dev`: Install packages as dev dependencies + +**Returns**: + +`TemplateBuilder` class +Example +```python +template.npm_install('express') +template.npm_install(['lodash', 'axios']) +template.npm_install('typescript', g=True) +template.npm_install() # Installs from package.json +``` + + + +### bun\_install + +```python +def bun_install(packages: Optional[Union[str, List[str]]] = None, + g: Optional[bool] = False, + dev: Optional[bool] = False) -> "TemplateBuilder" +``` + +Install Bun packages using bun. + +**Arguments**: + +- `packages`: Package name(s) to install. If None, installs from package.json +- `g`: Install packages globally +- `dev`: Install packages as dev dependencies + +**Returns**: + +`TemplateBuilder` class +Example +```python +template.bun_install('express') +template.bun_install(['lodash', 'axios']) +template.bun_install('tsx', g=True) +template.bun_install('typescript', dev=True) +template.bun_install() // Installs from package.json +``` + + + +### apt\_install + +```python +def apt_install(packages: Union[str, List[str]], + no_install_recommends: bool = False) -> "TemplateBuilder" +``` + +Install system packages using apt-get. + +**Arguments**: + +- `packages`: Package name(s) to install +- `no_install_recommends`: Whether to install recommended packages + +**Returns**: + +`TemplateBuilder` class +Example +```python +template.apt_install('vim') +template.apt_install(['git', 'curl', 'wget']) +``` + + + +### add\_mcp\_server + +```python +def add_mcp_server(servers: Union[str, List[str]]) -> "TemplateBuilder" +``` + +Install MCP servers using mcp-gateway. + +Note: Requires a base image with mcp-gateway pre-installed (e.g., mcp-gateway). + +**Arguments**: + +- `servers`: MCP server name(s) + +**Returns**: + +`TemplateBuilder` class +Example +```python +template.add_mcp_server('exa') +template.add_mcp_server(['brave', 'firecrawl', 'duckduckgo']) +``` + + + +### git\_clone + +```python +def git_clone(url: str, + path: Optional[Union[str, Path]] = None, + branch: Optional[str] = None, + depth: Optional[int] = None, + user: Optional[str] = None) -> "TemplateBuilder" +``` + +Clone a git repository into the template. + +**Arguments**: + +- `url`: Git repository URL +- `path`: Destination path for the clone +- `branch`: Branch to clone +- `depth`: Clone depth for shallow clones +- `user`: User to run the command as + +**Returns**: + +`TemplateBuilder` class +Example +```python +template.git_clone('https://github.com/user/repo.git', '/app/repo') +template.git_clone('https://github.com/user/repo.git', branch='main', depth=1) +template.git_clone('https://github.com/user/repo.git', '/app/repo', user='root') +``` + + + +### beta\_dev\_container\_prebuild + +```python +def beta_dev_container_prebuild( + devcontainer_directory: Union[str, Path]) -> "TemplateBuilder" +``` + +Prebuild a devcontainer from the specified directory during the build process. + +**Arguments**: + +- `devcontainer_directory`: Path to the devcontainer directory + +**Returns**: + +`TemplateBuilder` class +Example +```python +template.git_clone('https://myrepo.com/project.git', '/my-devcontainer') +template.beta_dev_container_prebuild('/my-devcontainer') +``` + + + +### beta\_set\_dev\_container\_start + +```python +def beta_set_dev_container_start( + devcontainer_directory: Union[str, Path]) -> "TemplateFinal" +``` + +Start a devcontainer from the specified directory and set it as the start command. + +This method returns `TemplateFinal`, which means it must be the last method in the chain. + +**Arguments**: + +- `devcontainer_directory`: Path to the devcontainer directory + +**Returns**: + +`TemplateFinal` class +Example +```python +template.git_clone('https://myrepo.com/project.git', '/my-devcontainer') +template.beta_set_devcontainer_start('/my-devcontainer') + +template.git_clone('https://myrepo.com/project.git', '/my-devcontainer') +template.beta_dev_container_prebuild('/my-devcontainer') +template.beta_set_dev_container_start('/my-devcontainer') +``` + + + +### set\_envs + +```python +def set_envs(envs: Dict[str, str]) -> "TemplateBuilder" +``` + +Set environment variables in the template. + +**Arguments**: + +- `envs`: Dictionary of environment variable names and values + +**Returns**: + +`TemplateBuilder` class +Example +```python +template.set_envs({'NODE_ENV': 'production', 'PORT': '8080'}) +``` + + + +### skip\_cache + +```python +def skip_cache() -> "TemplateBuilder" +``` + +Skip cache for all subsequent build instructions from this point. + +Call this before any instruction to force it and all following layers +to be rebuilt, ignoring any cached layers. + +**Returns**: + +`TemplateBuilder` class +Example +```python +template.skip_cache().run_cmd('apt-get update') +``` + + + +### set\_start\_cmd + +```python +def set_start_cmd(start_cmd: str, + ready_cmd: Union[str, ReadyCmd]) -> "TemplateFinal" +``` + +Set the command to start when the sandbox launches and the ready check command. + +**Arguments**: + +- `start_cmd`: Command to run when the sandbox starts +- `ready_cmd`: Command or ReadyCmd to check if the sandbox is ready + +**Returns**: + +`TemplateFinal` class +Example +```python +template.set_start_cmd( + 'python app.py', + 'curl http://localhost:8000/health' +) + +from e2b import wait_for_port, wait_for_url + +template.set_start_cmd( + 'python -m http.server 8000', + wait_for_port(8000) +) + +template.set_start_cmd( + 'npm start', + wait_for_url('http://localhost:3000/health', 200) +) +``` + + + +### set\_ready\_cmd + +```python +def set_ready_cmd(ready_cmd: Union[str, ReadyCmd]) -> "TemplateFinal" +``` + +Set the command to check if the sandbox is ready. + +**Arguments**: + +- `ready_cmd`: Command or ReadyCmd to check if the sandbox is ready + +**Returns**: + +`TemplateFinal` class +Example +```python +template.set_ready_cmd('curl http://localhost:8000/health') + +from e2b import wait_for_port, wait_for_file, wait_for_process + +template.set_ready_cmd(wait_for_port(3000)) + +template.set_ready_cmd(wait_for_file('/tmp/ready')) + +template.set_ready_cmd(wait_for_process('nginx')) +``` + + + +## TemplateFinal + +```python +class TemplateFinal() +``` + +Final template state after start/ready commands are set. + + + +## TemplateBase + +```python +class TemplateBase() +``` + +Base class for building E2B sandbox templates. + + + +### \_\_init\_\_ + +```python +def __init__(file_context_path: Optional[Union[str, Path]] = None, + file_ignore_patterns: Optional[List[str]] = None) +``` + +Create a new template builder instance. + +**Arguments**: + +- `file_context_path`: Base path for resolving relative file paths in copy operations +- `file_ignore_patterns`: List of glob patterns to ignore when copying files + + + +### skip\_cache + +```python +def skip_cache() -> "TemplateBase" +``` + +Skip cache for all subsequent build instructions from this point. + +**Returns**: + +`TemplateBase` class +Example +```python +template.skip_cache().from_python_image('3.11') +``` + + + +### from\_debian\_image + +```python +def from_debian_image(variant: str = "stable") -> TemplateBuilder +``` + +Start template from a Debian base image. + +**Arguments**: + +- `variant`: Debian image variant + +**Returns**: + +`TemplateBuilder` class +Example +```python +Template().from_debian_image('bookworm') +``` + + + +### from\_ubuntu\_image + +```python +def from_ubuntu_image(variant: str = "latest") -> TemplateBuilder +``` + +Start template from an Ubuntu base image. + +**Arguments**: + +- `variant`: Ubuntu image variant (default: 'latest') + +**Returns**: + +`TemplateBuilder` class +Example +```python +Template().from_ubuntu_image('24.04') +``` + + + +### from\_python\_image + +```python +def from_python_image(version: str = "3") -> TemplateBuilder +``` + +Start template from a Python base image. + +**Arguments**: + +- `version`: Python version (default: '3') + +**Returns**: + +`TemplateBuilder` class +Example +```python +Template().from_python_image('3') +``` + + + +### from\_node\_image + +```python +def from_node_image(variant: str = "lts") -> TemplateBuilder +``` + +Start template from a Node.js base image. + +**Arguments**: + +- `variant`: Node.js image variant (default: 'lts') + +**Returns**: + +`TemplateBuilder` class +Example +```python +Template().from_node_image('24') +``` + + + +### from\_bun\_image + +```python +def from_bun_image(variant: str = "latest") -> TemplateBuilder +``` + +Start template from a Bun base image. + +**Arguments**: + +- `variant`: Bun image variant (default: 'latest') + +**Returns**: + +`TemplateBuilder` class + + + +### from\_base\_image + +```python +def from_base_image() -> TemplateBuilder +``` + +Start template from the E2B base image (e2bdev/base:latest). + +**Returns**: + +`TemplateBuilder` class +Example +```python +Template().from_base_image() +``` + + + +### from\_image + +```python +def from_image(image: str, + username: Optional[str] = None, + password: Optional[str] = None) -> TemplateBuilder +``` + +Start template from a Docker image. + +**Arguments**: + +- `image`: Docker image name (e.g., 'ubuntu:24.04') +- `username`: Username for private registry authentication +- `password`: Password for private registry authentication + +**Returns**: + +`TemplateBuilder` class +Example +```python +Template().from_image('python:3') + +Template().from_image('myregistry.com/myimage:latest', username='user', password='pass') +``` + + + +### from\_template + +```python +def from_template(template: str) -> TemplateBuilder +``` + +Start template from an existing E2B template. + +**Arguments**: + +- `template`: E2B template ID or alias + +**Returns**: + +`TemplateBuilder` class +Example +```python +Template().from_template('my-base-template') +``` + + + +### from\_dockerfile + +```python +def from_dockerfile(dockerfile_content_or_path: str) -> TemplateBuilder +``` + +Parse a Dockerfile and convert it to Template SDK format. + +**Arguments**: + +- `dockerfile_content_or_path`: Either the Dockerfile content as a string, or a path to a Dockerfile file + +**Returns**: + +`TemplateBuilder` class +Example +```python +Template().from_dockerfile('Dockerfile') +Template().from_dockerfile('FROM python:3\nRUN pip install numpy') +``` + + + +### from\_aws\_registry + +```python +def from_aws_registry(image: str, access_key_id: str, secret_access_key: str, + region: str) -> TemplateBuilder +``` + +Start template from an AWS ECR registry image. + +**Arguments**: + +- `image`: Docker image name from AWS ECR +- `access_key_id`: AWS access key ID +- `secret_access_key`: AWS secret access key +- `region`: AWS region + +**Returns**: + +`TemplateBuilder` class +Example +```python +Template().from_aws_registry( + '123456789.dkr.ecr.us-west-2.amazonaws.com/myimage:latest', + access_key_id='AKIA...', + secret_access_key='...', + region='us-west-2' +) +``` + + + +### from\_gcp\_registry + +```python +def from_gcp_registry( + image: str, service_account_json: Union[str, dict]) -> TemplateBuilder +``` + +Start template from a GCP Artifact Registry or Container Registry image. + +**Arguments**: + +- `image`: Docker image name from GCP registry +- `service_account_json`: Service account JSON string, dict, or path to JSON file + +**Returns**: + +`TemplateBuilder` class +Example +```python +Template().from_gcp_registry( + 'gcr.io/myproject/myimage:latest', + service_account_json='path/to/service-account.json' +) +``` + + + +### to\_json + +```python +@staticmethod +def to_json(template: "TemplateClass") -> str +``` + +Convert a template to JSON representation. + +**Arguments**: + +- `template`: The template to convert (TemplateBuilder or TemplateFinal instance) + +**Returns**: + +JSON string representation of the template +Example +```python +template = Template().from_python_image('3').copy('app.py', '/app/') +json_str = TemplateBase.to_json(template) +``` + + + +### to\_dockerfile + +```python +@staticmethod +def to_dockerfile(template: "TemplateClass") -> str +``` + +Convert a template to Dockerfile format. + +Note: Templates based on other E2B templates cannot be converted to Dockerfile. + +**Arguments**: + +- `template`: The template to convert (TemplateBuilder or TemplateFinal instance) + +**Raises**: + +- `ValueError`: If the template is based on another E2B template or has no base image +Example +```python +template = Template().from_python_image('3').copy('app.py', '/app/') +dockerfile = TemplateBase.to_dockerfile(template) +``` + +**Returns**: + +Dockerfile string representation diff --git a/docs/sdk-reference/python-sdk/v2.7.0/template_async.mdx b/docs/sdk-reference/python-sdk/v2.7.0/template_async.mdx new file mode 100644 index 0000000..950d066 --- /dev/null +++ b/docs/sdk-reference/python-sdk/v2.7.0/template_async.mdx @@ -0,0 +1,150 @@ +--- +sidebarTitle: "Template Async" +mode: "center" +--- + + + + + + + + + +## AsyncTemplate + +```python +class AsyncTemplate(TemplateBase) +``` + +Asynchronous template builder for E2B sandboxes. + + + +### build + +```python +@staticmethod +async def build(template: TemplateClass, + alias: str, + cpu_count: int = 2, + memory_mb: int = 1024, + skip_cache: bool = False, + on_build_logs: Optional[Callable[[LogEntry], None]] = None, + api_key: Optional[str] = None, + domain: Optional[str] = None) -> BuildInfo +``` + +Build and deploy a template to E2B infrastructure. + +**Arguments**: + +- `template`: The template to build +- `alias`: Alias name for the template +- `cpu_count`: Number of CPUs allocated to the sandbox +- `memory_mb`: Amount of memory in MB allocated to the sandbox +- `skip_cache`: If True, forces a complete rebuild ignoring cache +- `on_build_logs`: Callback function to receive build logs during the build process +- `api_key`: E2B API key for authentication +- `domain`: Domain of the E2B API +Example +```python +from e2b import AsyncTemplate + +template = ( + AsyncTemplate() + .from_python_image('3') + .copy('requirements.txt', '/home/user/') + .run_cmd('pip install -r /home/user/requirements.txt') +) + +await AsyncTemplate.build( + template, + alias='my-python-env', + cpu_count=2, + memory_mb=1024 +) +``` + + + +### build\_in\_background + +```python +@staticmethod +async def build_in_background(template: TemplateClass, + alias: str, + cpu_count: int = 2, + memory_mb: int = 1024, + skip_cache: bool = False, + on_build_logs: Optional[Callable[[LogEntry], + None]] = None, + api_key: Optional[str] = None, + domain: Optional[str] = None) -> BuildInfo +``` + +Build and deploy a template to E2B infrastructure without waiting for completion. + +**Arguments**: + +- `template`: The template to build +- `alias`: Alias name for the template +- `cpu_count`: Number of CPUs allocated to the sandbox +- `memory_mb`: Amount of memory in MB allocated to the sandbox +- `skip_cache`: If True, forces a complete rebuild ignoring cache +- `api_key`: E2B API key for authentication +- `domain`: Domain of the E2B API + +**Returns**: + +BuildInfo containing the template ID and build ID +Example +```python +from e2b import AsyncTemplate + +template = ( + AsyncTemplate() + .from_python_image('3') + .run_cmd('echo "test"') + .set_start_cmd('echo "Hello"', 'sleep 1') +) + +build_info = await AsyncTemplate.build_in_background( + template, + alias='my-python-env', + cpu_count=2, + memory_mb=1024 +) +``` + + + +### get\_build\_status + +```python +@staticmethod +async def get_build_status(build_info: BuildInfo, + logs_offset: int = 0, + api_key: Optional[str] = None, + domain: Optional[str] = None) +``` + +Get the status of a build. + +**Arguments**: + +- `build_info`: Build identifiers returned from build_in_background +- `logs_offset`: Offset for fetching logs +- `api_key`: E2B API key for authentication +- `domain`: Domain of the E2B API + +**Returns**: + +TemplateBuild containing the build status and logs +Example +```python +from e2b import AsyncTemplate + +build_info = await AsyncTemplate.build_in_background(template, alias='my-template') +status = await AsyncTemplate.get_build_status(build_info, logs_offset=0) +``` diff --git a/docs/sdk-reference/python-sdk/v2.7.0/template_sync.mdx b/docs/sdk-reference/python-sdk/v2.7.0/template_sync.mdx new file mode 100644 index 0000000..6387438 --- /dev/null +++ b/docs/sdk-reference/python-sdk/v2.7.0/template_sync.mdx @@ -0,0 +1,150 @@ +--- +sidebarTitle: "Template Sync" +mode: "center" +--- + + + + + + + + + +## Template + +```python +class Template(TemplateBase) +``` + +Synchronous template builder for E2B sandboxes. + + + +### build + +```python +@staticmethod +def build(template: TemplateClass, + alias: str, + cpu_count: int = 2, + memory_mb: int = 1024, + skip_cache: bool = False, + on_build_logs: Optional[Callable[[LogEntry], None]] = None, + api_key: Optional[str] = None, + domain: Optional[str] = None) -> BuildInfo +``` + +Build and deploy a template to E2B infrastructure. + +**Arguments**: + +- `template`: The template to build +- `alias`: Alias name for the template +- `cpu_count`: Number of CPUs allocated to the sandbox +- `memory_mb`: Amount of memory in MB allocated to the sandbox +- `skip_cache`: If True, forces a complete rebuild ignoring cache +- `on_build_logs`: Callback function to receive build logs during the build process +- `api_key`: E2B API key for authentication +- `domain`: Domain of the E2B API +Example +```python +from e2b import Template + +template = ( + Template() + .from_python_image('3') + .copy('requirements.txt', '/home/user/') + .run_cmd('pip install -r /home/user/requirements.txt') +) + +Template.build( + template, + alias='my-python-env', + cpu_count=2, + memory_mb=1024 +) +``` + + + +### build\_in\_background + +```python +@staticmethod +def build_in_background(template: TemplateClass, + alias: str, + cpu_count: int = 2, + memory_mb: int = 1024, + skip_cache: bool = False, + on_build_logs: Optional[Callable[[LogEntry], + None]] = None, + api_key: Optional[str] = None, + domain: Optional[str] = None) -> BuildInfo +``` + +Build and deploy a template to E2B infrastructure without waiting for completion. + +**Arguments**: + +- `template`: The template to build +- `alias`: Alias name for the template +- `cpu_count`: Number of CPUs allocated to the sandbox +- `memory_mb`: Amount of memory in MB allocated to the sandbox +- `skip_cache`: If True, forces a complete rebuild ignoring cache +- `api_key`: E2B API key for authentication +- `domain`: Domain of the E2B API + +**Returns**: + +BuildInfo containing the template ID and build ID +Example +```python +from e2b import Template + +template = ( + Template() + .from_python_image('3') + .run_cmd('echo "test"') + .set_start_cmd('echo "Hello"', 'sleep 1') +) + +build_info = Template.build_in_background( + template, + alias='my-python-env', + cpu_count=2, + memory_mb=1024 +) +``` + + + +### get\_build\_status + +```python +@staticmethod +def get_build_status(build_info: BuildInfo, + logs_offset: int = 0, + api_key: Optional[str] = None, + domain: Optional[str] = None) +``` + +Get the status of a build. + +**Arguments**: + +- `build_info`: Build identifiers returned from build_in_background +- `logs_offset`: Offset for fetching logs +- `api_key`: E2B API key for authentication +- `domain`: Domain of the E2B API + +**Returns**: + +TemplateBuild containing the build status and logs +Example +```python +from e2b import Template + +build_info = Template.build_in_background(template, alias='my-template') +status = Template.get_build_status(build_info, logs_offset=0) +``` diff --git a/docs/sdk-reference/python-sdk/v2.8.0/exceptions.mdx b/docs/sdk-reference/python-sdk/v2.8.0/exceptions.mdx new file mode 100644 index 0000000..d66f786 --- /dev/null +++ b/docs/sdk-reference/python-sdk/v2.8.0/exceptions.mdx @@ -0,0 +1,117 @@ +--- +sidebarTitle: "Exceptions" +mode: "center" +--- + + + + + + +## SandboxException + +```python +class SandboxException(Exception) +``` + +Base class for all sandbox errors. + +Raised when a general sandbox exception occurs. + + + +## TimeoutException + +```python +class TimeoutException(SandboxException) +``` + +Raised when a timeout occurs. + +The `unavailable` exception type is caused by sandbox timeout. + +The `canceled` exception type is caused by exceeding request timeout. + +The `deadline_exceeded` exception type is caused by exceeding the timeout for process, watch, etc. + +The `unknown` exception type is sometimes caused by the sandbox timeout when the request is not processed correctly. + + + +## InvalidArgumentException + +```python +class InvalidArgumentException(SandboxException) +``` + +Raised when an invalid argument is provided. + + + +## NotEnoughSpaceException + +```python +class NotEnoughSpaceException(SandboxException) +``` + +Raised when there is not enough disk space. + + + +## NotFoundException + +```python +class NotFoundException(SandboxException) +``` + +Raised when a resource is not found. + + + +## AuthenticationException + +```python +class AuthenticationException(Exception) +``` + +Raised when authentication fails. + + + +## TemplateException + +```python +class TemplateException(SandboxException) +``` + +Exception raised when the template uses old envd version. It isn't compatible with the new SDK. + + + +## RateLimitException + +```python +class RateLimitException(SandboxException) +``` + +Raised when the API rate limit is exceeded. + + + +## BuildException + +```python +class BuildException(Exception) +``` + +Raised when the build fails. + + + +## FileUploadException + +```python +class FileUploadException(BuildException) +``` + +Raised when the file upload fails. diff --git a/docs/sdk-reference/python-sdk/v2.8.0/logger.mdx b/docs/sdk-reference/python-sdk/v2.8.0/logger.mdx new file mode 100644 index 0000000..9fa3b18 --- /dev/null +++ b/docs/sdk-reference/python-sdk/v2.8.0/logger.mdx @@ -0,0 +1,106 @@ +--- +sidebarTitle: "Logger" +mode: "center" +--- + + + + + + +## LogEntry + +```python +@dataclass +class LogEntry() +``` + +Represents a single log entry from the template build process. + + + +## LogEntryStart + +```python +@dataclass +class LogEntryStart(LogEntry) +``` + +Special log entry indicating the start of a build process. + + + +## LogEntryEnd + +```python +@dataclass +class LogEntryEnd(LogEntry) +``` + +Special log entry indicating the end of a build process. + + + +### TIMER\_UPDATE\_INTERVAL\_MS + +Default minimum log level to display. + + + +### DEFAULT\_LEVEL + +Colored labels for each log level. + + + +### levels + +Numeric ordering of log levels for comparison (lower = less severe). + + + +### set\_interval + +```python +def set_interval(func, interval) +``` + +Returns a stop function that can be called to cancel the interval. + +Similar to JavaScript's setInterval. + +**Arguments**: + +- `func`: Function to execute at each interval +- `interval`: Interval duration in **seconds** + +**Returns**: + +Stop function that can be called to cancel the interval + + + +### default\_build\_logger + +```python +def default_build_logger( + min_level: Optional[LogEntryLevel] = None +) -> Callable[[LogEntry], None] +``` + +Create a default build logger with animated timer display. + +**Arguments**: + +- `min_level`: Minimum log level to display (default: 'info') + +**Returns**: + +Logger function that accepts LogEntry instances +Example +```python +from e2b import Template, default_build_logger + +template = Template().from_python_image() + +``` diff --git a/docs/sdk-reference/python-sdk/v2.8.0/readycmd.mdx b/docs/sdk-reference/python-sdk/v2.8.0/readycmd.mdx new file mode 100644 index 0000000..8eabda6 --- /dev/null +++ b/docs/sdk-reference/python-sdk/v2.8.0/readycmd.mdx @@ -0,0 +1,168 @@ +--- +sidebarTitle: "Readycmd" +mode: "center" +--- + + + + + + +## ReadyCmd + +```python +class ReadyCmd() +``` + +Wrapper class for ready check commands. + + + +### wait\_for\_port + +```python +def wait_for_port(port: int) +``` + +Wait for a port to be listening. + +Uses `ss` command to check if a port is open and listening. + +**Arguments**: + +- `port`: Port number to wait for + +**Returns**: + +ReadyCmd that checks for the port +Example +```python +from e2b import Template, wait_for_port + +template = ( + Template() + .from_python_image() + .set_start_cmd('python -m http.server 8000', wait_for_port(8000)) +) +``` + + + +### wait\_for\_url + +```python +def wait_for_url(url: str, status_code: int = 200) +``` + +Wait for a URL to return a specific HTTP status code. + +Uses `curl` to make HTTP requests and check the response status. + +**Arguments**: + +- `url`: URL to check (e.g., 'http://localhost:3000/health') +- `status_code`: Expected HTTP status code (default: 200) + +**Returns**: + +ReadyCmd that checks the URL +Example +```python +from e2b import Template, wait_for_url + +template = ( + Template() + .from_node_image() + .set_start_cmd('npm start', wait_for_url('http://localhost:3000/health')) +) +``` + + + +### wait\_for\_process + +```python +def wait_for_process(process_name: str) +``` + +Wait for a process with a specific name to be running. + +Uses `pgrep` to check if a process exists. + +**Arguments**: + +- `process_name`: Name of the process to wait for + +**Returns**: + +ReadyCmd that checks for the process +Example +```python +from e2b import Template, wait_for_process + +template = ( + Template() + .from_base_image() + .set_start_cmd('./my-daemon', wait_for_process('my-daemon')) +) +``` + + + +### wait\_for\_file + +```python +def wait_for_file(filename: str) +``` + +Wait for a file to exist. + +Uses shell test command to check file existence. + +**Arguments**: + +- `filename`: Path to the file to wait for + +**Returns**: + +ReadyCmd that checks for the file +Example +```python +from e2b import Template, wait_for_file + +template = ( + Template() + .from_base_image() + .set_start_cmd('./init.sh', wait_for_file('/tmp/ready')) +) +``` + + + +### wait\_for\_timeout + +```python +def wait_for_timeout(timeout: int) +``` + +Wait for a specified timeout before considering the sandbox ready. + +Uses `sleep` command to wait for a fixed duration. + +**Arguments**: + +- `timeout`: Time to wait in **milliseconds** (minimum: 1000ms / 1 second) + +**Returns**: + +ReadyCmd that waits for the specified duration +Example +```python +from e2b import Template, wait_for_timeout + +template = ( + Template() + .from_node_image() + .set_start_cmd('npm start', wait_for_timeout(5000)) # Wait 5 seconds +) +``` diff --git a/docs/sdk-reference/python-sdk/v2.8.0/sandbox_async.mdx b/docs/sdk-reference/python-sdk/v2.8.0/sandbox_async.mdx new file mode 100644 index 0000000..b636b1a --- /dev/null +++ b/docs/sdk-reference/python-sdk/v2.8.0/sandbox_async.mdx @@ -0,0 +1,1387 @@ +--- +sidebarTitle: "Sandbox Async" +mode: "center" +--- + + + + + + +## AsyncWatchHandle + +```python +class AsyncWatchHandle() +``` + +Handle for watching a directory in the sandbox filesystem. + +Use `.stop()` to stop watching the directory. + + + +### stop + +```python +async def stop() +``` + +Stop watching the directory. + + + + + + +## Filesystem + +```python +class Filesystem() +``` + +Module for interacting with the filesystem in the sandbox. + + + +### read + +```python +@overload +async def read(path: str, + format: Literal["text"] = "text", + user: Optional[Username] = None, + request_timeout: Optional[float] = None) -> str +``` + +Read file content as a `str`. + +**Arguments**: + +- `path`: Path to the file +- `user`: Run the operation as this user +- `format`: Format of the file content—`text` by default +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +File content as a `str` + + + +### read + +```python +@overload +async def read(path: str, + format: Literal["bytes"], + user: Optional[Username] = None, + request_timeout: Optional[float] = None) -> bytearray +``` + +Read file content as a `bytearray`. + +**Arguments**: + +- `path`: Path to the file +- `user`: Run the operation as this user +- `format`: Format of the file content—`bytes` +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +File content as a `bytearray` + + + +### read + +```python +@overload +async def read( + path: str, + format: Literal["stream"], + user: Optional[Username] = None, + request_timeout: Optional[float] = None) -> AsyncIterator[bytes] +``` + +Read file content as a `AsyncIterator[bytes]`. + +**Arguments**: + +- `path`: Path to the file +- `user`: Run the operation as this user +- `format`: Format of the file content—`stream` +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +File content as an `AsyncIterator[bytes]` + + + +### write + +```python +async def write(path: str, + data: Union[str, bytes, IO], + user: Optional[Username] = None, + request_timeout: Optional[float] = None) -> WriteInfo +``` + +Write content to a file on the path. + +Writing to a file that doesn't exist creates the file. +Writing to a file that already exists overwrites the file. +Writing to a file at path that doesn't exist creates the necessary directories. + +**Arguments**: + +- `path`: Path to the file +- `data`: Data to write to the file, can be a `str`, `bytes`, or `IO`. +- `user`: Run the operation as this user +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +Information about the written file + + + +### write\_files + +```python +async def write_files( + files: List[WriteEntry], + user: Optional[Username] = None, + request_timeout: Optional[float] = None) -> List[WriteInfo] +``` + +Writes multiple files. + +Writes a list of files to the filesystem. +When writing to a file that doesn't exist, the file will get created. +When writing to a file that already exists, the file will get overwritten. +When writing to a file that's in a directory that doesn't exist, you'll get an error. + +**Arguments**: + +- `files`: list of files to write as `WriteEntry` objects, each containing `path` and `data` +- `user`: Run the operation as this user +- `request_timeout`: Timeout for the request + +**Returns**: + +Information about the written files + + + +### list + +```python +async def list(path: str, + depth: Optional[int] = 1, + user: Optional[Username] = None, + request_timeout: Optional[float] = None) -> List[EntryInfo] +``` + +List entries in a directory. + +**Arguments**: + +- `path`: Path to the directory +- `depth`: Depth of the directory to list +- `user`: Run the operation as this user +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +List of entries in the directory + + + +### exists + +```python +async def exists(path: str, + user: Optional[Username] = None, + request_timeout: Optional[float] = None) -> bool +``` + +Check if a file or a directory exists. + +**Arguments**: + +- `path`: Path to a file or a directory +- `user`: Run the operation as this user +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`True` if the file or directory exists, `False` otherwise + + + +### get\_info + +```python +async def get_info(path: str, + user: Optional[Username] = None, + request_timeout: Optional[float] = None) -> EntryInfo +``` + +Get information about a file or directory. + +**Arguments**: + +- `path`: Path to a file or a directory +- `user`: Run the operation as this user +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +Information about the file or directory like name, type, and path + + + +### remove + +```python +async def remove(path: str, + user: Optional[Username] = None, + request_timeout: Optional[float] = None) -> None +``` + +Remove a file or a directory. + +**Arguments**: + +- `path`: Path to a file or a directory +- `user`: Run the operation as this user +- `request_timeout`: Timeout for the request in **seconds** + + + +### rename + +```python +async def rename(old_path: str, + new_path: str, + user: Optional[Username] = None, + request_timeout: Optional[float] = None) -> EntryInfo +``` + +Rename a file or directory. + +**Arguments**: + +- `old_path`: Path to the file or directory to rename +- `new_path`: New path to the file or directory +- `user`: Run the operation as this user +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +Information about the renamed file or directory + + + +### make\_dir + +```python +async def make_dir(path: str, + user: Optional[Username] = None, + request_timeout: Optional[float] = None) -> bool +``` + +Create a new directory and all directories along the way if needed on the specified path. + +**Arguments**: + +- `path`: Path to a new directory. For example '/dirA/dirB' when creating 'dirB'. +- `user`: Run the operation as this user +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`True` if the directory was created, `False` if the directory already exists + + + +### watch\_dir + +```python +async def watch_dir(path: str, + on_event: OutputHandler[FilesystemEvent], + on_exit: Optional[OutputHandler[Exception]] = None, + user: Optional[Username] = None, + request_timeout: Optional[float] = None, + timeout: Optional[float] = 60, + recursive: bool = False) -> AsyncWatchHandle +``` + +Watch directory for filesystem events. + +**Arguments**: + +- `path`: Path to a directory to watch +- `on_event`: Callback to call on each event in the directory +- `on_exit`: Callback to call when the watching ends +- `user`: Run the operation as this user +- `request_timeout`: Timeout for the request in **seconds** +- `timeout`: Timeout for the watch operation in **seconds**. Using `0` will not limit the watch time +- `recursive`: Watch directory recursively + +**Returns**: + +`AsyncWatchHandle` object for stopping watching directory + + + + + + +## AsyncSandboxPaginator + +```python +class AsyncSandboxPaginator(SandboxPaginatorBase) +``` + +Paginator for listing sandboxes. + +**Example**: + +```python +paginator = AsyncSandbox.list() + +while paginator.has_next: + sandboxes = await paginator.next_items() + print(sandboxes) +``` + + + +### next\_items + +```python +async def next_items() -> List[SandboxInfo] +``` + +Returns the next page of sandboxes. + +Call this method only if `has_next` is `True`, otherwise it will raise an exception. + +**Returns**: + +List of sandboxes + + + + + + + + + +## SandboxApi + +```python +class SandboxApi(SandboxBase) +``` + + + +### list + +```python +@staticmethod +def list(query: Optional[SandboxQuery] = None, + limit: Optional[int] = None, + next_token: Optional[str] = None, + **opts: Unpack[ApiParams]) -> AsyncSandboxPaginator +``` + +List all running sandboxes. + +**Arguments**: + +- `query`: Filter the list of sandboxes by metadata or state, e.g. `SandboxListQuery(metadata={"key": "value"})` or `SandboxListQuery(state=[SandboxState.RUNNING])` +- `limit`: Maximum number of sandboxes to return per page +- `next_token`: Token for pagination + +**Returns**: + +List of running sandboxes + + + + + + +## Commands + +```python +class Commands() +``` + +Module for executing commands in the sandbox. + + + +### list + +```python +async def list(request_timeout: Optional[float] = None) -> List[ProcessInfo] +``` + +Lists all running commands and PTY sessions. + +**Arguments**: + +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +List of running commands and PTY sessions + + + +### kill + +```python +async def kill(pid: int, request_timeout: Optional[float] = None) -> bool +``` + +Kill a running command specified by its process ID. + +It uses `SIGKILL` signal to kill the command. + +**Arguments**: + +- `pid`: Process ID of the command. You can get the list of processes using `sandbox.commands.list()` +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`True` if the command was killed, `False` if the command was not found + + + +### send\_stdin + +```python +async def send_stdin(pid: int, + data: str, + request_timeout: Optional[float] = None) -> None +``` + +Send data to command stdin. + +:param pid Process ID of the command. You can get the list of processes using `sandbox.commands.list()`. +:param data: Data to send to the command +:param request_timeout: Timeout for the request in **seconds** + + + + +### run + +```python +@overload +async def run(cmd: str, + background: Union[Literal[False], None] = None, + envs: Optional[Dict[str, str]] = None, + user: Optional[Username] = None, + cwd: Optional[str] = None, + on_stdout: Optional[OutputHandler[Stdout]] = None, + on_stderr: Optional[OutputHandler[Stderr]] = None, + stdin: Optional[bool] = None, + timeout: Optional[float] = 60, + request_timeout: Optional[float] = None) -> CommandResult +``` + +Start a new command and wait until it finishes executing. + +**Arguments**: + +- `cmd`: Command to execute +- `background`: **`False` if the command should be executed in the foreground**, `True` if the command should be executed in the background +- `envs`: Environment variables used for the command +- `user`: User to run the command as +- `cwd`: Working directory to run the command +- `on_stdout`: Callback for command stdout output +- `on_stderr`: Callback for command stderr output +- `stdin`: If `True`, the command will have a stdin stream that you can send data to using `sandbox.commands.send_stdin()` +- `timeout`: Timeout for the command connection in **seconds**. Using `0` will not limit the command connection time +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`CommandResult` result of the command execution + + + +### run + +```python +@overload +async def run(cmd: str, + background: Literal[True], + envs: Optional[Dict[str, str]] = None, + user: Optional[Username] = None, + cwd: Optional[str] = None, + on_stdout: Optional[OutputHandler[Stdout]] = None, + on_stderr: Optional[OutputHandler[Stderr]] = None, + stdin: Optional[bool] = None, + timeout: Optional[float] = 60, + request_timeout: Optional[float] = None) -> AsyncCommandHandle +``` + +Start a new command and return a handle to interact with it. + +**Arguments**: + +- `cmd`: Command to execute +- `background`: `False` if the command should be executed in the foreground, **`True` if the command should be executed in the background** +- `envs`: Environment variables used for the command +- `user`: User to run the command as +- `cwd`: Working directory to run the command +- `on_stdout`: Callback for command stdout output +- `on_stderr`: Callback for command stderr output +- `stdin`: If `True`, the command will have a stdin stream that you can send data to using `sandbox.commands.send_stdin()` +- `timeout`: Timeout for the command connection in **seconds**. Using `0` will not limit the command connection time +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`AsyncCommandHandle` handle to interact with the running command + + + +### connect + +```python +async def connect( + pid: int, + timeout: Optional[float] = 60, + request_timeout: Optional[float] = None, + on_stdout: Optional[OutputHandler[Stdout]] = None, + on_stderr: Optional[OutputHandler[Stderr]] = None +) -> AsyncCommandHandle +``` + +Connects to a running command. + +You can use `AsyncCommandHandle.wait()` to wait for the command to finish and get execution results. + +**Arguments**: + +- `pid`: Process ID of the command to connect to. You can get the list of processes using `sandbox.commands.list()` +- `request_timeout`: Request timeout in **seconds** +- `timeout`: Timeout for the command connection in **seconds**. Using `0` will not limit the command connection time +- `on_stdout`: Callback for command stdout output +- `on_stderr`: Callback for command stderr output + +**Returns**: + +`AsyncCommandHandle` handle to interact with the running command + + + + + + +## AsyncCommandHandle + +```python +class AsyncCommandHandle() +``` + +Command execution handle. + +It provides methods for waiting for the command to finish, retrieving stdout/stderr, and killing the command. + + + +### pid + +```python +@property +def pid() +``` + +Command process ID. + + + +### stdout + +```python +@property +def stdout() +``` + +Command stdout output. + + + +### stderr + +```python +@property +def stderr() +``` + +Command stderr output. + + + +### error + +```python +@property +def error() +``` + +Command execution error message. + + + +### exit\_code + +```python +@property +def exit_code() +``` + +Command execution exit code. + +`0` if the command finished successfully. + +It is `None` if the command is still running. + + + +### disconnect + +```python +async def disconnect() -> None +``` + +Disconnects from the command. + +The command is not killed, but SDK stops receiving events from the command. +You can reconnect to the command using `sandbox.commands.connect` method. + + + +### wait + +```python +async def wait() -> CommandResult +``` + +Wait for the command to finish and return the result. + +If the command exits with a non-zero exit code, it throws a `CommandExitException`. + +**Returns**: + +`CommandResult` result of command execution + + + +### kill + +```python +async def kill() -> bool +``` + +Kills the command. + +It uses `SIGKILL` signal to kill the command + +**Returns**: + +`True` if the command was killed successfully, `False` if the command was not found + + + + + + +## Pty + +```python +class Pty() +``` + +Module for interacting with PTYs (pseudo-terminals) in the sandbox. + + + +### kill + +```python +async def kill(pid: int, request_timeout: Optional[float] = None) -> bool +``` + +Kill PTY. + +**Arguments**: + +- `pid`: Process ID of the PTY +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`true` if the PTY was killed, `false` if the PTY was not found + + + +### send\_stdin + +```python +async def send_stdin(pid: int, + data: bytes, + request_timeout: Optional[float] = None) -> None +``` + +Send input to a PTY. + +**Arguments**: + +- `pid`: Process ID of the PTY +- `data`: Input data to send +- `request_timeout`: Timeout for the request in **seconds** + + + +### create + +```python +async def create( + size: PtySize, + on_data: OutputHandler[PtyOutput], + user: Optional[Username] = None, + cwd: Optional[str] = None, + envs: Optional[Dict[str, str]] = None, + timeout: Optional[float] = 60, + request_timeout: Optional[float] = None) -> AsyncCommandHandle +``` + +Start a new PTY (pseudo-terminal). + +**Arguments**: + +- `size`: Size of the PTY +- `on_data`: Callback to handle PTY data +- `user`: User to use for the PTY +- `cwd`: Working directory for the PTY +- `envs`: Environment variables for the PTY +- `timeout`: Timeout for the PTY in **seconds** +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +Handle to interact with the PTY + + + +### resize + +```python +async def resize(pid: int, + size: PtySize, + request_timeout: Optional[float] = None) +``` + +Resize PTY. + +Call this when the terminal window is resized and the number of columns and rows has changed. + +**Arguments**: + +- `pid`: Process ID of the PTY +- `size`: New size of the PTY +- `request_timeout`: Timeout for the request in **seconds** + + + + + + +## AsyncSandbox + +```python +class AsyncSandbox(SandboxApi) +``` + +E2B cloud sandbox is a secure and isolated cloud environment. + +The sandbox allows you to: +- Access Linux OS +- Create, list, and delete files and directories +- Run commands +- Run isolated code +- Access the internet + +Check docs [here](https://e2b.dev/docs). + +Use the `AsyncSandbox.create()` to create a new sandbox. + +**Example**: + +```python +from e2b import AsyncSandbox + +sandbox = await AsyncSandbox.create() +``` + + + +### files + +```python +@property +def files() -> Filesystem +``` + +Module for interacting with the sandbox filesystem. + + + +### commands + +```python +@property +def commands() -> Commands +``` + +Module for running commands in the sandbox. + + + +### pty + +```python +@property +def pty() -> Pty +``` + +Module for interacting with the sandbox pseudo-terminal. + + + +### \_\_init\_\_ + +```python +def __init__(**opts: Unpack[SandboxOpts]) +``` + +Use `AsyncSandbox.create()` to create a new sandbox instead. + + + +### is\_running + +```python +async def is_running(request_timeout: Optional[float] = None) -> bool +``` + +Check if the sandbox is running. + +**Arguments**: + +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`True` if the sandbox is running, `False` otherwise +Example +```python +sandbox = await AsyncSandbox.create() +await sandbox.is_running() # Returns True + +await sandbox.kill() +await sandbox.is_running() # Returns False +``` + + + +### create + +```python +@classmethod +async def create(cls, + template: Optional[str] = None, + timeout: Optional[int] = None, + metadata: Optional[Dict[str, str]] = None, + envs: Optional[Dict[str, str]] = None, + secure: bool = True, + allow_internet_access: bool = True, + mcp: Optional[McpServer] = None, + network: Optional[SandboxNetworkOpts] = None, + **opts: Unpack[ApiParams]) -> Self +``` + +Create a new sandbox. + +By default, the sandbox is created from the default `base` sandbox template. + +**Arguments**: + +- `template`: Sandbox template name or ID +- `timeout`: Timeout for the sandbox in **seconds**, default to 300 seconds. The maximum time a sandbox can be kept alive is 24 hours (86_400 seconds) for Pro users and 1 hour (3_600 seconds) for Hobby users. +- `metadata`: Custom metadata for the sandbox +- `envs`: Custom environment variables for the sandbox +- `secure`: Envd is secured with access token and cannot be used without it, defaults to `True`. +- `allow_internet_access`: Allow sandbox to access the internet, defaults to `True`. If set to `False`, it works the same as setting network `deny_out` to `[0.0.0.0/0]`. +- `mcp`: MCP server to enable in the sandbox +- `network`: Sandbox network configuration + +**Returns**: + +A Sandbox instance for the new sandbox +Use this method instead of using the constructor to create a new sandbox. + + + +### connect + +```python +@overload +async def connect(timeout: Optional[int] = None, + **opts: Unpack[ApiParams]) -> Self +``` + +Connect to a sandbox. If the sandbox is paused, it will be automatically resumed. + +Sandbox must be either running or be paused. + +With sandbox ID you can connect to the same sandbox from different places or environments (serverless functions, etc). + +**Arguments**: + +- `timeout`: Timeout for the sandbox in **seconds** +For running sandboxes, the timeout will update only if the new timeout is longer than the existing one. + +**Returns**: + +A running sandbox instance +@example +```python +sandbox = await AsyncSandbox.create() +await sandbox.beta_pause() + +same_sandbox = await sandbox.connect() +``` + + + +### connect + +```python +@overload +@classmethod +async def connect(cls, + sandbox_id: str, + timeout: Optional[int] = None, + **opts: Unpack[ApiParams]) -> Self +``` + +Connect to a sandbox. If the sandbox is paused, it will be automatically resumed. + +Sandbox must be either running or be paused. + +With sandbox ID you can connect to the same sandbox from different places or environments (serverless functions, etc). + +**Arguments**: + +- `sandbox_id`: Sandbox ID +- `timeout`: Timeout for the sandbox in **seconds** +For running sandboxes, the timeout will update only if the new timeout is longer than the existing one. + +**Returns**: + +A running sandbox instance +@example +```python +sandbox = await AsyncSandbox.create() +await AsyncSandbox.beta_pause(sandbox.sandbox_id) + +same_sandbox = await AsyncSandbox.connect(sandbox.sandbox_id)) +``` + + + +### connect + +```python +@class_method_variant("_cls_connect") +async def connect(timeout: Optional[int] = None, + **opts: Unpack[ApiParams]) -> Self +``` + +Connect to a sandbox. If the sandbox is paused, it will be automatically resumed. + +Sandbox must be either running or be paused. + +With sandbox ID you can connect to the same sandbox from different places or environments (serverless functions, etc). + +**Arguments**: + +- `timeout`: Timeout for the sandbox in **seconds** +For running sandboxes, the timeout will update only if the new timeout is longer than the existing one. + +**Returns**: + +A running sandbox instance +@example +```python +sandbox = await AsyncSandbox.create() +await sandbox.beta_pause() + +same_sandbox = await sandbox.connect() +``` + + + +### kill + +```python +@overload +async def kill(**opts: Unpack[ApiParams]) -> bool +``` + +Kill the sandbox. + +**Returns**: + +`True` if the sandbox was killed, `False` if the sandbox was not found + + + +### kill + +```python +@overload +@staticmethod +async def kill(sandbox_id: str, **opts: Unpack[ApiParams]) -> bool +``` + +Kill the sandbox specified by sandbox ID. + +**Arguments**: + +- `sandbox_id`: Sandbox ID + +**Returns**: + +`True` if the sandbox was killed, `False` if the sandbox was not found + + + +### kill + +```python +@class_method_variant("_cls_kill") +async def kill(**opts: Unpack[ApiParams]) -> bool +``` + +Kill the sandbox specified by sandbox ID. + +**Returns**: + +`True` if the sandbox was killed, `False` if the sandbox was not found + + + +### set\_timeout + +```python +@overload +async def set_timeout(timeout: int, **opts: Unpack[ApiParams]) -> None +``` + +Set the timeout of the sandbox. + +After the timeout expires, the sandbox will be automatically killed. +This method can extend or reduce the sandbox timeout set when creating the sandbox or from the last call to `.set_timeout`. + +The maximum time a sandbox can be kept alive is 24 hours (86_400 seconds) for Pro users and 1 hour (3_600 seconds) for Hobby users. + +**Arguments**: + +- `timeout`: Timeout for the sandbox in **seconds** + + + +### set\_timeout + +```python +@overload +@staticmethod +async def set_timeout(sandbox_id: str, timeout: int, + **opts: Unpack[ApiParams]) -> None +``` + +Set the timeout of the specified sandbox. + +After the timeout expires, the sandbox will be automatically killed. +This method can extend or reduce the sandbox timeout set when creating the sandbox or from the last call to `.set_timeout`. + +The maximum time a sandbox can be kept alive is 24 hours (86_400 seconds) for Pro users and 1 hour (3_600 seconds) for Hobby users. + +**Arguments**: + +- `sandbox_id`: Sandbox ID +- `timeout`: Timeout for the sandbox in **seconds** + + + +### set\_timeout + +```python +@class_method_variant("_cls_set_timeout") +async def set_timeout(timeout: int, **opts: Unpack[ApiParams]) -> None +``` + +Set the timeout of the specified sandbox. + +After the timeout expires, the sandbox will be automatically killed. +This method can extend or reduce the sandbox timeout set when creating the sandbox or from the last call to `.set_timeout`. + +The maximum time a sandbox can be kept alive is 24 hours (86_400 seconds) for Pro users and 1 hour (3_600 seconds) for Hobby users. + +**Arguments**: + +- `timeout`: Timeout for the sandbox in **seconds** + + + +### get\_info + +```python +@overload +async def get_info(**opts: Unpack[ApiParams]) -> SandboxInfo +``` + +Get sandbox information like sandbox ID, template, metadata, started at/end at date. + +**Returns**: + +Sandbox info + + + +### get\_info + +```python +@overload +@staticmethod +async def get_info(sandbox_id: str, **opts: Unpack[ApiParams]) -> SandboxInfo +``` + +Get sandbox information like sandbox ID, template, metadata, started at/end at date. + +**Arguments**: + +- `sandbox_id`: Sandbox ID + +**Returns**: + +Sandbox info + + + +### get\_info + +```python +@class_method_variant("_cls_get_info") +async def get_info(**opts: Unpack[ApiParams]) -> SandboxInfo +``` + +Get sandbox information like sandbox ID, template, metadata, started at/end at date. + +**Returns**: + +Sandbox info + + + +### get\_metrics + +```python +@overload +async def get_metrics(start: Optional[datetime.datetime] = None, + end: Optional[datetime.datetime] = None, + **opts: Unpack[ApiParams]) -> List[SandboxMetrics] +``` + +Get the metrics of the current sandbox. + +**Arguments**: + +- `start`: Start time for the metrics, defaults to the start of the sandbox +- `end`: End time for the metrics, defaults to the current time + +**Returns**: + +List of sandbox metrics containing CPU, memory and disk usage information + + + +### get\_metrics + +```python +@overload +@staticmethod +async def get_metrics(sandbox_id: str, + start: Optional[datetime.datetime] = None, + end: Optional[datetime.datetime] = None, + **opts: Unpack[ApiParams]) -> List[SandboxMetrics] +``` + +Get the metrics of the sandbox specified by sandbox ID. + +**Arguments**: + +- `sandbox_id`: Sandbox ID +- `start`: Start time for the metrics, defaults to the start of the sandbox +- `end`: End time for the metrics, defaults to the current time + +**Returns**: + +List of sandbox metrics containing CPU, memory and disk usage information + + + +### get\_metrics + +```python +@class_method_variant("_cls_get_metrics") +async def get_metrics(start: Optional[datetime.datetime] = None, + end: Optional[datetime.datetime] = None, + **opts: Unpack[ApiParams]) -> List[SandboxMetrics] +``` + +Get the metrics of the current sandbox. + +**Arguments**: + +- `start`: Start time for the metrics, defaults to the start of the sandbox +- `end`: End time for the metrics, defaults to the current time + +**Returns**: + +List of sandbox metrics containing CPU, memory and disk usage information + + + +### beta\_create + +```python +@classmethod +async def beta_create(cls, + template: Optional[str] = None, + timeout: Optional[int] = None, + auto_pause: bool = False, + metadata: Optional[Dict[str, str]] = None, + envs: Optional[Dict[str, str]] = None, + secure: bool = True, + allow_internet_access: bool = True, + mcp: Optional[McpServer] = None, + **opts: Unpack[ApiParams]) -> Self +``` + +[BETA] This feature is in beta and may change in the future. + +Create a new sandbox. + +By default, the sandbox is created from the default `base` sandbox template. + +**Arguments**: + +- `template`: Sandbox template name or ID +- `timeout`: Timeout for the sandbox in **seconds**, default to 300 seconds. The maximum time a sandbox can be kept alive is 24 hours (86_400 seconds) for Pro users and 1 hour (3_600 seconds) for Hobby users. +- `auto_pause`: Automatically pause the sandbox after the timeout expires. Defaults to `False`. +- `metadata`: Custom metadata for the sandbox +- `envs`: Custom environment variables for the sandbox +- `secure`: Envd is secured with access token and cannot be used without it, defaults to `True`. +- `allow_internet_access`: Allow sandbox to access the internet, defaults to `True`. +- `mcp`: MCP server to enable in the sandbox + +**Returns**: + +A Sandbox instance for the new sandbox +Use this method instead of using the constructor to create a new sandbox. + + + +### beta\_pause + +```python +@overload +async def beta_pause(**opts: Unpack[ApiParams]) -> None +``` + +[BETA] This feature is in beta and may change in the future. + +Pause the sandbox. + +**Returns**: + +Sandbox ID that can be used to resume the sandbox + + + +### beta\_pause + +```python +@overload +@staticmethod +async def beta_pause(sandbox_id: str, **opts: Unpack[ApiParams]) -> None +``` + +[BETA] This feature is in beta and may change in the future. + +Pause the sandbox specified by sandbox ID. + +**Arguments**: + +- `sandbox_id`: Sandbox ID + +**Returns**: + +Sandbox ID that can be used to resume the sandbox + + + +### beta\_pause + +```python +@class_method_variant("_cls_pause") +async def beta_pause(**opts: Unpack[ApiParams]) -> None +``` + +[BETA] This feature is in beta and may change in the future. + +Pause the sandbox. + +**Returns**: + +Sandbox ID that can be used to resume the sandbox + + + +### get\_mcp\_token + +```python +async def get_mcp_token() -> Optional[str] +``` + +Get the MCP token for the sandbox. + +**Returns**: + +MCP token for the sandbox, or None if MCP is not enabled. diff --git a/docs/sdk-reference/python-sdk/v2.8.0/sandbox_sync.mdx b/docs/sdk-reference/python-sdk/v2.8.0/sandbox_sync.mdx new file mode 100644 index 0000000..04927a8 --- /dev/null +++ b/docs/sdk-reference/python-sdk/v2.8.0/sandbox_sync.mdx @@ -0,0 +1,1343 @@ +--- +sidebarTitle: "Sandbox Sync" +mode: "center" +--- + + + + + + +## WatchHandle + +```python +class WatchHandle() +``` + +Handle for watching filesystem events. +It is used to get the latest events that have occurred in the watched directory. + +Use `.stop()` to stop watching the directory. + + + +### stop + +```python +def stop() +``` + +Stop watching the directory. +After you stop the watcher you won't be able to get the events anymore. + + + +### get\_new\_events + +```python +def get_new_events() -> List[FilesystemEvent] +``` + +Get the latest events that have occurred in the watched directory since the last call, or from the beginning of the watching, up until now. + +**Returns**: + +List of filesystem events + + + + + + +## Filesystem + +```python +class Filesystem() +``` + +Module for interacting with the filesystem in the sandbox. + + + +### read + +```python +@overload +def read(path: str, + format: Literal["text"] = "text", + user: Optional[Username] = None, + request_timeout: Optional[float] = None) -> str +``` + +Read file content as a `str`. + +**Arguments**: + +- `path`: Path to the file +- `user`: Run the operation as this user +- `format`: Format of the file content—`text` by default +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +File content as a `str` + + + +### read + +```python +@overload +def read(path: str, + format: Literal["bytes"], + user: Optional[Username] = None, + request_timeout: Optional[float] = None) -> bytearray +``` + +Read file content as a `bytearray`. + +**Arguments**: + +- `path`: Path to the file +- `user`: Run the operation as this user +- `format`: Format of the file content—`bytes` +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +File content as a `bytearray` + + + +### read + +```python +@overload +def read(path: str, + format: Literal["stream"], + user: Optional[Username] = None, + request_timeout: Optional[float] = None) -> Iterator[bytes] +``` + +Read file content as a `Iterator[bytes]`. + +**Arguments**: + +- `path`: Path to the file +- `user`: Run the operation as this user +- `format`: Format of the file content—`stream` +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +File content as an `Iterator[bytes]` + + + +### write + +```python +def write(path: str, + data: Union[str, bytes, IO], + user: Optional[Username] = None, + request_timeout: Optional[float] = None) -> WriteInfo +``` + +Write content to a file on the path. + +Writing to a file that doesn't exist creates the file. +Writing to a file that already exists overwrites the file. +Writing to a file at path that doesn't exist creates the necessary directories. + +**Arguments**: + +- `path`: Path to the file +- `data`: Data to write to the file, can be a `str`, `bytes`, or `IO`. +- `user`: Run the operation as this user +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +Information about the written file + + + +### write\_files + +```python +def write_files(files: List[WriteEntry], + user: Optional[Username] = None, + request_timeout: Optional[float] = None) -> List[WriteInfo] +``` + +Writes a list of files to the filesystem. + +When writing to a file that doesn't exist, the file will get created. +When writing to a file that already exists, the file will get overwritten. +When writing to a file that's in a directory that doesn't exist, you'll get an error. + +**Arguments**: + +- `files`: list of files to write as `WriteEntry` objects, each containing `path` and `data` +- `user`: Run the operation as this user +- `request_timeout`: Timeout for the request + +**Returns**: + +Information about the written files + + + +### list + +```python +def list(path: str, + depth: Optional[int] = 1, + user: Optional[Username] = None, + request_timeout: Optional[float] = None) -> List[EntryInfo] +``` + +List entries in a directory. + +**Arguments**: + +- `path`: Path to the directory +- `depth`: Depth of the directory to list +- `user`: Run the operation as this user +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +List of entries in the directory + + + +### exists + +```python +def exists(path: str, + user: Optional[Username] = None, + request_timeout: Optional[float] = None) -> bool +``` + +Check if a file or a directory exists. + +**Arguments**: + +- `path`: Path to a file or a directory +- `user`: Run the operation as this user +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`True` if the file or directory exists, `False` otherwise + + + +### get\_info + +```python +def get_info(path: str, + user: Optional[Username] = None, + request_timeout: Optional[float] = None) -> EntryInfo +``` + +Get information about a file or directory. + +**Arguments**: + +- `path`: Path to a file or a directory +- `user`: Run the operation as this user +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +Information about the file or directory like name, type, and path + + + +### remove + +```python +def remove(path: str, + user: Optional[Username] = None, + request_timeout: Optional[float] = None) -> None +``` + +Remove a file or a directory. + +**Arguments**: + +- `path`: Path to a file or a directory +- `user`: Run the operation as this user +- `request_timeout`: Timeout for the request in **seconds** + + + +### rename + +```python +def rename(old_path: str, + new_path: str, + user: Optional[Username] = None, + request_timeout: Optional[float] = None) -> EntryInfo +``` + +Rename a file or directory. + +**Arguments**: + +- `old_path`: Path to the file or directory to rename +- `new_path`: New path to the file or directory +- `user`: Run the operation as this user +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +Information about the renamed file or directory + + + +### make\_dir + +```python +def make_dir(path: str, + user: Optional[Username] = None, + request_timeout: Optional[float] = None) -> bool +``` + +Create a new directory and all directories along the way if needed on the specified path. + +**Arguments**: + +- `path`: Path to a new directory. For example '/dirA/dirB' when creating 'dirB'. +- `user`: Run the operation as this user +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`True` if the directory was created, `False` if the directory already exists + + + +### watch\_dir + +```python +def watch_dir(path: str, + user: Optional[Username] = None, + request_timeout: Optional[float] = None, + recursive: bool = False) -> WatchHandle +``` + +Watch directory for filesystem events. + +**Arguments**: + +- `path`: Path to a directory to watch +- `user`: Run the operation as this user +- `request_timeout`: Timeout for the request in **seconds** +- `recursive`: Watch directory recursively + +**Returns**: + +`WatchHandle` object for stopping watching directory + + + + + + +## SandboxPaginator + +```python +class SandboxPaginator(SandboxPaginatorBase) +``` + +Paginator for listing sandboxes. + +**Example**: + +```python +paginator = Sandbox.list() + +while paginator.has_next: + sandboxes = paginator.next_items() + print(sandboxes) +``` + + + +### next\_items + +```python +def next_items() -> List[SandboxInfo] +``` + +Returns the next page of sandboxes. + +Call this method only if `has_next` is `True`, otherwise it will raise an exception. + +**Returns**: + +List of sandboxes + + + + + + +## SandboxApi + +```python +class SandboxApi(SandboxBase) +``` + + + +### list + +```python +@staticmethod +def list(query: Optional[SandboxQuery] = None, + limit: Optional[int] = None, + next_token: Optional[str] = None, + **opts: Unpack[ApiParams]) -> SandboxPaginator +``` + +List all running sandboxes. + +**Arguments**: + +- `query`: Filter the list of sandboxes by metadata or state, e.g. `SandboxListQuery(metadata={"key": "value"})` or `SandboxListQuery(state=[SandboxState.RUNNING])` +- `limit`: Maximum number of sandboxes to return per page +- `next_token`: Token for pagination + +**Returns**: + +List of running sandboxes + + + + + + +## Commands + +```python +class Commands() +``` + +Module for executing commands in the sandbox. + + + +### list + +```python +def list(request_timeout: Optional[float] = None) -> List[ProcessInfo] +``` + +Lists all running commands and PTY sessions. + +**Arguments**: + +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +List of running commands and PTY sessions + + + +### kill + +```python +def kill(pid: int, request_timeout: Optional[float] = None) -> bool +``` + +Kills a running command specified by its process ID. + +It uses `SIGKILL` signal to kill the command. + +**Arguments**: + +- `pid`: Process ID of the command. You can get the list of processes using `sandbox.commands.list()` +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`True` if the command was killed, `False` if the command was not found + + + +### send\_stdin + +```python +def send_stdin(pid: int, data: str, request_timeout: Optional[float] = None) +``` + +Send data to command stdin. + +:param pid Process ID of the command. You can get the list of processes using `sandbox.commands.list()`. +:param data: Data to send to the command +:param request_timeout: Timeout for the request in **seconds** + + + + +### run + +```python +@overload +def run(cmd: str, + background: Union[Literal[False], None] = None, + envs: Optional[Dict[str, str]] = None, + user: Optional[Username] = None, + cwd: Optional[str] = None, + on_stdout: Optional[Callable[[str], None]] = None, + on_stderr: Optional[Callable[[str], None]] = None, + stdin: Optional[bool] = None, + timeout: Optional[float] = 60, + request_timeout: Optional[float] = None) -> CommandResult +``` + +Start a new command and wait until it finishes executing. + +**Arguments**: + +- `cmd`: Command to execute +- `background`: **`False` if the command should be executed in the foreground**, `True` if the command should be executed in the background +- `envs`: Environment variables used for the command +- `user`: User to run the command as +- `cwd`: Working directory to run the command +- `on_stdout`: Callback for command stdout output +- `on_stderr`: Callback for command stderr output +- `stdin`: If `True`, the command will have a stdin stream that you can send data to using `sandbox.commands.send_stdin()` +- `timeout`: Timeout for the command connection in **seconds**. Using `0` will not limit the command connection time +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`CommandResult` result of the command execution + + + +### run + +```python +@overload +def run(cmd: str, + background: Literal[True], + envs: Optional[Dict[str, str]] = None, + user: Optional[Username] = None, + cwd: Optional[str] = None, + on_stdout: None = None, + on_stderr: None = None, + stdin: Optional[bool] = None, + timeout: Optional[float] = 60, + request_timeout: Optional[float] = None) -> CommandHandle +``` + +Start a new command and return a handle to interact with it. + +**Arguments**: + +- `cmd`: Command to execute +- `background`: `False` if the command should be executed in the foreground, **`True` if the command should be executed in the background** +- `envs`: Environment variables used for the command +- `user`: User to run the command as +- `cwd`: Working directory to run the command +- `stdin`: If `True`, the command will have a stdin stream that you can send data to using `sandbox.commands.send_stdin()` +- `timeout`: Timeout for the command connection in **seconds**. Using `0` will not limit the command connection time +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`CommandHandle` handle to interact with the running command + + + +### connect + +```python +def connect(pid: int, + timeout: Optional[float] = 60, + request_timeout: Optional[float] = None) +``` + +Connects to a running command. + +You can use `CommandHandle.wait()` to wait for the command to finish and get execution results. + +**Arguments**: + +- `pid`: Process ID of the command to connect to. You can get the list of processes using `sandbox.commands.list()` +- `timeout`: Timeout for the connection in **seconds**. Using `0` will not limit the connection time +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`CommandHandle` handle to interact with the running command + + + + + + +## CommandHandle + +```python +class CommandHandle() +``` + +Command execution handle. + +It provides methods for waiting for the command to finish, retrieving stdout/stderr, and killing the command. + + + +### pid + +```python +@property +def pid() +``` + +Command process ID. + + + +### \_\_iter\_\_ + +```python +def __iter__() +``` + +Iterate over the command output. + +**Returns**: + +Generator of command outputs + + + +### disconnect + +```python +def disconnect() -> None +``` + +Disconnect from the command. + +The command is not killed, but SDK stops receiving events from the command. +You can reconnect to the command using `sandbox.commands.connect` method. + + + +### wait + +```python +def wait(on_pty: Optional[Callable[[PtyOutput], None]] = None, + on_stdout: Optional[Callable[[str], None]] = None, + on_stderr: Optional[Callable[[str], None]] = None) -> CommandResult +``` + +Wait for the command to finish and returns the result. + +If the command exits with a non-zero exit code, it throws a `CommandExitException`. + +**Arguments**: + +- `on_pty`: Callback for pty output +- `on_stdout`: Callback for stdout output +- `on_stderr`: Callback for stderr output + +**Returns**: + +`CommandResult` result of command execution + + + +### kill + +```python +def kill() -> bool +``` + +Kills the command. + +It uses `SIGKILL` signal to kill the command. + +**Returns**: + +Whether the command was killed successfully + + + + + + +## Pty + +```python +class Pty() +``` + +Module for interacting with PTYs (pseudo-terminals) in the sandbox. + + + +### kill + +```python +def kill(pid: int, request_timeout: Optional[float] = None) -> bool +``` + +Kill PTY. + +**Arguments**: + +- `pid`: Process ID of the PTY +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`true` if the PTY was killed, `false` if the PTY was not found + + + +### send\_stdin + +```python +def send_stdin(pid: int, + data: bytes, + request_timeout: Optional[float] = None) -> None +``` + +Send input to a PTY. + +**Arguments**: + +- `pid`: Process ID of the PTY +- `data`: Input data to send +- `request_timeout`: Timeout for the request in **seconds** + + + +### create + +```python +def create(size: PtySize, + user: Optional[Username] = None, + cwd: Optional[str] = None, + envs: Optional[Dict[str, str]] = None, + timeout: Optional[float] = 60, + request_timeout: Optional[float] = None) -> CommandHandle +``` + +Start a new PTY (pseudo-terminal). + +**Arguments**: + +- `size`: Size of the PTY +- `user`: User to use for the PTY +- `cwd`: Working directory for the PTY +- `envs`: Environment variables for the PTY +- `timeout`: Timeout for the PTY in **seconds** +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +Handle to interact with the PTY + + + +### resize + +```python +def resize(pid: int, + size: PtySize, + request_timeout: Optional[float] = None) -> None +``` + +Resize PTY. + +Call this when the terminal window is resized and the number of columns and rows has changed. + +**Arguments**: + +- `pid`: Process ID of the PTY +- `size`: New size of the PTY +- `request_timeout`: Timeout for the request in **seconds**s + + + + + + +## Sandbox + +```python +class Sandbox(SandboxApi) +``` + +E2B cloud sandbox is a secure and isolated cloud environment. + +The sandbox allows you to: +- Access Linux OS +- Create, list, and delete files and directories +- Run commands +- Run isolated code +- Access the internet + +Check docs [here](https://e2b.dev/docs). + +Use the `Sandbox.create()` to create a new sandbox. + +**Example**: + +```python +from e2b import Sandbox + +sandbox = Sandbox.create() +``` + + + +### files + +```python +@property +def files() -> Filesystem +``` + +Module for interacting with the sandbox filesystem. + + + +### commands + +```python +@property +def commands() -> Commands +``` + +Module for running commands in the sandbox. + + + +### pty + +```python +@property +def pty() -> Pty +``` + +Module for interacting with the sandbox pseudo-terminal. + + + +### \_\_init\_\_ + +```python +def __init__(**opts: Unpack[SandboxOpts]) +``` + +:deprecated: This constructor is deprecated + +Use `Sandbox.create()` to create a new sandbox instead. + + + +### is\_running + +```python +def is_running(request_timeout: Optional[float] = None) -> bool +``` + +Check if the sandbox is running. + +**Arguments**: + +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`True` if the sandbox is running, `False` otherwise +Example +```python +sandbox = Sandbox.create() +sandbox.is_running() # Returns True + +sandbox.kill() +sandbox.is_running() # Returns False +``` + + + +### create + +```python +@classmethod +def create(cls, + template: Optional[str] = None, + timeout: Optional[int] = None, + metadata: Optional[Dict[str, str]] = None, + envs: Optional[Dict[str, str]] = None, + secure: bool = True, + allow_internet_access: bool = True, + mcp: Optional[McpServer] = None, + network: Optional[SandboxNetworkOpts] = None, + **opts: Unpack[ApiParams]) -> Self +``` + +Create a new sandbox. + +By default, the sandbox is created from the default `base` sandbox template. + +**Arguments**: + +- `template`: Sandbox template name or ID +- `timeout`: Timeout for the sandbox in **seconds**, default to 300 seconds. The maximum time a sandbox can be kept alive is 24 hours (86_400 seconds) for Pro users and 1 hour (3_600 seconds) for Hobby users. +- `metadata`: Custom metadata for the sandbox +- `envs`: Custom environment variables for the sandbox +- `secure`: Envd is secured with access token and cannot be used without it, defaults to `True`. +- `allow_internet_access`: Allow sandbox to access the internet, defaults to `True`. If set to `False`, it works the same as setting network `deny_out` to `[0.0.0.0/0]`. +- `mcp`: MCP server to enable in the sandbox +- `network`: Sandbox network configuration + +**Returns**: + +A Sandbox instance for the new sandbox +Use this method instead of using the constructor to create a new sandbox. + + + +### connect + +```python +@overload +def connect(timeout: Optional[int] = None, **opts: Unpack[ApiParams]) -> Self +``` + +Connect to a sandbox. If the sandbox is paused, it will be automatically resumed. + +Sandbox must be either running or be paused. + +With sandbox ID you can connect to the same sandbox from different places or environments (serverless functions, etc). + +**Arguments**: + +- `timeout`: Timeout for the sandbox in **seconds** +For running sandboxes, the timeout will update only if the new timeout is longer than the existing one. + +**Returns**: + +A running sandbox instance +@example +```python +sandbox = Sandbox.create() +sandbox.beta_pause() + +same_sandbox = sandbox.connect() + + + +### connect + +```python +@overload +@classmethod +def connect(cls, + sandbox_id: str, + timeout: Optional[int] = None, + **opts: Unpack[ApiParams]) -> Self +``` + +Connect to a sandbox. If the sandbox is paused, it will be automatically resumed. + +Sandbox must be either running or be paused. + +With sandbox ID you can connect to the same sandbox from different places or environments (serverless functions, etc). + +**Arguments**: + +- `sandbox_id`: Sandbox ID +- `timeout`: Timeout for the sandbox in **seconds**. +For running sandboxes, the timeout will update only if the new timeout is longer than the existing one. + +**Returns**: + +A running sandbox instance +@example +```python +sandbox = Sandbox.create() +Sandbox.beta_pause(sandbox.sandbox_id) + +same_sandbox = Sandbox.connect(sandbox.sandbox_id) +``` + + + +### connect + +```python +@class_method_variant("_cls_connect") +def connect(timeout: Optional[int] = None, **opts: Unpack[ApiParams]) -> Self +``` + +Connect to a sandbox. If the sandbox is paused, it will be automatically resumed. + +Sandbox must be either running or be paused. + +With sandbox ID you can connect to the same sandbox from different places or environments (serverless functions, etc). + +**Arguments**: + +- `timeout`: Timeout for the sandbox in **seconds**. +For running sandboxes, the timeout will update only if the new timeout is longer than the existing one. + +**Returns**: + +A running sandbox instance +@example +```python +sandbox = Sandbox.create() +sandbox.beta_pause() + +same_sandbox = sandbox.connect() +``` + + + +### kill + +```python +@overload +def kill(**opts: Unpack[ApiParams]) -> bool +``` + +Kill the sandbox. + +**Returns**: + +`True` if the sandbox was killed, `False` if the sandbox was not found + + + +### kill + +```python +@overload +@staticmethod +def kill(sandbox_id: str, **opts: Unpack[ApiParams]) -> bool +``` + +Kill the sandbox specified by sandbox ID. + +**Arguments**: + +- `sandbox_id`: Sandbox ID + +**Returns**: + +`True` if the sandbox was killed, `False` if the sandbox was not found + + + +### kill + +```python +@class_method_variant("_cls_kill") +def kill(**opts: Unpack[ApiParams]) -> bool +``` + +Kill the sandbox specified by sandbox ID. + +**Returns**: + +`True` if the sandbox was killed, `False` if the sandbox was not found + + + +### set\_timeout + +```python +@overload +def set_timeout(timeout: int, **opts: Unpack[ApiParams]) -> None +``` + +Set the timeout of the sandbox. + +After the timeout expires, the sandbox will be automatically killed. +This method can extend or reduce the sandbox timeout set when creating the sandbox or from the last call to `.set_timeout`. + +The maximum time a sandbox can be kept alive is 24 hours (86_400 seconds) for Pro users and 1 hour (3_600 seconds) for Hobby users. + +**Arguments**: + +- `timeout`: Timeout for the sandbox in **seconds** + + + +### set\_timeout + +```python +@overload +@staticmethod +def set_timeout(sandbox_id: str, timeout: int, + **opts: Unpack[ApiParams]) -> None +``` + +Set the timeout of the sandbox specified by sandbox ID. + +After the timeout expires, the sandbox will be automatically killed. +This method can extend or reduce the sandbox timeout set when creating the sandbox or from the last call to `.set_timeout`. + +The maximum time a sandbox can be kept alive is 24 hours (86_400 seconds) for Pro users and 1 hour (3_600 seconds) for Hobby users. + +**Arguments**: + +- `sandbox_id`: Sandbox ID +- `timeout`: Timeout for the sandbox in **seconds** + + + +### set\_timeout + +```python +@class_method_variant("_cls_set_timeout") +def set_timeout(timeout: int, **opts: Unpack[ApiParams]) -> None +``` + +Set the timeout of the sandbox. + +After the timeout expires, the sandbox will be automatically killed. +This method can extend or reduce the sandbox timeout set when creating the sandbox or from the last call to `.set_timeout`. + +The maximum time a sandbox can be kept alive is 24 hours (86_400 seconds) for Pro users and 1 hour (3_600 seconds) for Hobby users. + +**Arguments**: + +- `timeout`: Timeout for the sandbox in **seconds** + + + +### get\_info + +```python +@overload +def get_info(**opts: Unpack[ApiParams]) -> SandboxInfo +``` + +Get sandbox information like sandbox ID, template, metadata, started at/end at date. + +**Returns**: + +Sandbox info + + + +### get\_info + +```python +@overload +@staticmethod +def get_info(sandbox_id: str, **opts: Unpack[ApiParams]) -> SandboxInfo +``` + +Get sandbox information like sandbox ID, template, metadata, started at/end at date. + +**Arguments**: + +- `sandbox_id`: Sandbox ID + +**Returns**: + +Sandbox info + + + +### get\_info + +```python +@class_method_variant("_cls_get_info") +def get_info(**opts: Unpack[ApiParams]) -> SandboxInfo +``` + +Get sandbox information like sandbox ID, template, metadata, started at/end at date. + +**Returns**: + +Sandbox info + + + +### get\_metrics + +```python +@overload +def get_metrics(start: Optional[datetime.datetime] = None, + end: Optional[datetime.datetime] = None, + **opts: Unpack[ApiParams]) -> List[SandboxMetrics] +``` + +Get the metrics of the current sandbox. + +**Arguments**: + +- `start`: Start time for the metrics, defaults to the start of the sandbox +- `end`: End time for the metrics, defaults to the current time + +**Returns**: + +List of sandbox metrics containing CPU, memory and disk usage information + + + +### get\_metrics + +```python +@overload +@staticmethod +def get_metrics(sandbox_id: str, + start: Optional[datetime.datetime] = None, + end: Optional[datetime.datetime] = None, + **opts: Unpack[ApiParams]) -> List[SandboxMetrics] +``` + +Get the metrics of the sandbox specified by sandbox ID. + +**Arguments**: + +- `sandbox_id`: Sandbox ID +- `start`: Start time for the metrics, defaults to the start of the sandbox +- `end`: End time for the metrics, defaults to the current time + +**Returns**: + +List of sandbox metrics containing CPU, memory and disk usage information + + + +### get\_metrics + +```python +@class_method_variant("_cls_get_metrics") +def get_metrics(start: Optional[datetime.datetime] = None, + end: Optional[datetime.datetime] = None, + **opts: Unpack[ApiParams]) -> List[SandboxMetrics] +``` + +Get the metrics of the sandbox specified by sandbox ID. + +**Arguments**: + +- `start`: Start time for the metrics, defaults to the start of the sandbox +- `end`: End time for the metrics, defaults to the current time + +**Returns**: + +List of sandbox metrics containing CPU, memory and disk usage information + + + +### beta\_create + +```python +@classmethod +def beta_create(cls, + template: Optional[str] = None, + timeout: Optional[int] = None, + auto_pause: bool = False, + metadata: Optional[Dict[str, str]] = None, + envs: Optional[Dict[str, str]] = None, + secure: bool = True, + allow_internet_access: bool = True, + mcp: Optional[McpServer] = None, + **opts: Unpack[ApiParams]) -> Self +``` + +[BETA] This feature is in beta and may change in the future. + +Create a new sandbox. + +By default, the sandbox is created from the default `base` sandbox template. + +**Arguments**: + +- `template`: Sandbox template name or ID +- `timeout`: Timeout for the sandbox in **seconds**, default to 300 seconds. The maximum time a sandbox can be kept alive is 24 hours (86_400 seconds) for Pro users and 1 hour (3_600 seconds) for Hobby users. +- `auto_pause`: Automatically pause the sandbox after the timeout expires. Defaults to `False`. +- `metadata`: Custom metadata for the sandbox +- `envs`: Custom environment variables for the sandbox +- `secure`: Envd is secured with access token and cannot be used without it, defaults to `True`. +- `allow_internet_access`: Allow sandbox to access the internet, defaults to `True`. +- `mcp`: MCP server to enable in the sandbox + +**Returns**: + +A Sandbox instance for the new sandbox +Use this method instead of using the constructor to create a new sandbox. + + + +### beta\_pause + +```python +@overload +def beta_pause(**opts: Unpack[ApiParams]) -> None +``` + +[BETA] This feature is in beta and may change in the future. + +Pause the sandbox. + + + +### beta\_pause + +```python +@overload +@classmethod +def beta_pause(cls, sandbox_id: str, **opts: Unpack[ApiParams]) -> None +``` + +[BETA] This feature is in beta and may change in the future. + +Pause the sandbox specified by sandbox ID. + +**Arguments**: + +- `sandbox_id`: Sandbox ID + + + +### beta\_pause + +```python +@class_method_variant("_cls_pause") +def beta_pause(**opts: Unpack[ApiParams]) -> None +``` + +[BETA] This feature is in beta and may change in the future. + +Pause the sandbox. + +**Returns**: + +Sandbox ID that can be used to resume the sandbox + + + +### get\_mcp\_token + +```python +def get_mcp_token() -> Optional[str] +``` + +Get the MCP token for the sandbox. + +**Returns**: + +MCP token for the sandbox, or None if MCP is not enabled. diff --git a/docs/sdk-reference/python-sdk/v2.8.0/template.mdx b/docs/sdk-reference/python-sdk/v2.8.0/template.mdx new file mode 100644 index 0000000..9ac3cc8 --- /dev/null +++ b/docs/sdk-reference/python-sdk/v2.8.0/template.mdx @@ -0,0 +1,1686 @@ +--- +sidebarTitle: "Template" +mode: "center" +--- + + + + + + +## DockerfFileFinalParserInterface + +```python +class DockerfFileFinalParserInterface(Protocol) +``` + +Protocol defining the final interface for Dockerfile parsing callbacks. + + + +## DockerfileParserInterface + +```python +class DockerfileParserInterface(Protocol) +``` + +Protocol defining the interface for Dockerfile parsing callbacks. + + + +### run\_cmd + +```python +def run_cmd(command: Union[str, List[str]], + user: Optional[str] = None) -> "DockerfileParserInterface" +``` + +Handle RUN instruction. + + + +### copy + +```python +def copy(src: Union[str, List[CopyItem]], + dest: Optional[str] = None, + force_upload: Optional[Literal[True]] = None, + resolve_symlinks: Optional[bool] = None, + user: Optional[str] = None, + mode: Optional[int] = None) -> "DockerfileParserInterface" +``` + +Handle COPY instruction. + + + +### set\_workdir + +```python +def set_workdir(workdir: str) -> "DockerfileParserInterface" +``` + +Handle WORKDIR instruction. + + + +### set\_user + +```python +def set_user(user: str) -> "DockerfileParserInterface" +``` + +Handle USER instruction. + + + +### set\_envs + +```python +def set_envs(envs: Dict[str, str]) -> "DockerfileParserInterface" +``` + +Handle ENV instruction. + + + +### set\_start\_cmd + +```python +def set_start_cmd(start_cmd: str, + ready_cmd: str) -> "DockerfFileFinalParserInterface" +``` + +Handle CMD/ENTRYPOINT instruction. + + + +### parse\_dockerfile + +```python +def parse_dockerfile(dockerfile_content_or_path: str, + template_builder: DockerfileParserInterface) -> str +``` + +Parse a Dockerfile and convert it to Template SDK format. + +**Arguments**: + +- `dockerfile_content_or_path`: Either the Dockerfile content as a string, or a path to a Dockerfile file +- `template_builder`: Interface providing template builder methods + +**Raises**: + +- `ValueError`: If the Dockerfile is invalid or unsupported + +**Returns**: + +The base image from the Dockerfile + + + + + + +## InstructionType + +```python +class InstructionType(str, Enum) +``` + +Types of instructions that can be used in a template. + + + +## CopyItem + +```python +class CopyItem(TypedDict) +``` + +Configuration for a single file/directory copy operation. + + + +## Instruction + +```python +class Instruction(TypedDict) +``` + +Represents a single instruction in the template build process. + + + +## GenericDockerRegistry + +```python +class GenericDockerRegistry(TypedDict) +``` + +Configuration for a generic Docker registry with basic authentication. + + + +## AWSRegistry + +```python +class AWSRegistry(TypedDict) +``` + +Configuration for AWS Elastic Container Registry (ECR). + + + +## GCPRegistry + +```python +class GCPRegistry(TypedDict) +``` + +Configuration for Google Container Registry (GCR) or Artifact Registry. + + + +## TemplateType + +```python +class TemplateType(TypedDict) +``` + +Internal representation of a template for the E2B build API. + + + +## BuildInfo + +```python +@dataclass +class BuildInfo() +``` + +Information about a built template. + + + + + + +## LogEntry + +```python +@dataclass +class LogEntry() +``` + +Represents a single log entry from the template build process. + + + +## LogEntryStart + +```python +@dataclass +class LogEntryStart(LogEntry) +``` + +Special log entry indicating the start of a build process. + + + +## LogEntryEnd + +```python +@dataclass +class LogEntryEnd(LogEntry) +``` + +Special log entry indicating the end of a build process. + + + +### TIMER\_UPDATE\_INTERVAL\_MS + +Default minimum log level to display. + + + +### DEFAULT\_LEVEL + +Colored labels for each log level. + + + +### levels + +Numeric ordering of log levels for comparison (lower = less severe). + + + +### set\_interval + +```python +def set_interval(func, interval) +``` + +Returns a stop function that can be called to cancel the interval. + +Similar to JavaScript's setInterval. + +**Arguments**: + +- `func`: Function to execute at each interval +- `interval`: Interval duration in **seconds** + +**Returns**: + +Stop function that can be called to cancel the interval + + + +### default\_build\_logger + +```python +def default_build_logger( + min_level: Optional[LogEntryLevel] = None +) -> Callable[[LogEntry], None] +``` + +Create a default build logger with animated timer display. + +**Arguments**: + +- `min_level`: Minimum log level to display (default: 'info') + +**Returns**: + +Logger function that accepts LogEntry instances +Example +```python +from e2b import Template, default_build_logger + +template = Template().from_python_image() + +``` + + + + +Special step name for the finalization phase of template building. +This is the last step that runs after all user-defined instructions. + + + +### FINALIZE\_STEP\_NAME + +Special step name for the base image phase of template building. +This is the first step that sets up the base image. + + + +### BASE\_STEP\_NAME + +Stack trace depth for capturing caller information. + +Depth levels: +1. TemplateClass +2. Caller method (e.g., copy(), from_image(), etc.) + +This depth is used to determine the original caller's location +for stack traces. + + + +### STACK\_TRACE\_DEPTH + +Default setting for whether to resolve symbolic links when copying files. +When False, symlinks are copied as symlinks rather than following them. + + + + + + +## ReadyCmd + +```python +class ReadyCmd() +``` + +Wrapper class for ready check commands. + + + +### wait\_for\_port + +```python +def wait_for_port(port: int) +``` + +Wait for a port to be listening. + +Uses `ss` command to check if a port is open and listening. + +**Arguments**: + +- `port`: Port number to wait for + +**Returns**: + +ReadyCmd that checks for the port +Example +```python +from e2b import Template, wait_for_port + +template = ( + Template() + .from_python_image() + .set_start_cmd('python -m http.server 8000', wait_for_port(8000)) +) +``` + + + +### wait\_for\_url + +```python +def wait_for_url(url: str, status_code: int = 200) +``` + +Wait for a URL to return a specific HTTP status code. + +Uses `curl` to make HTTP requests and check the response status. + +**Arguments**: + +- `url`: URL to check (e.g., 'http://localhost:3000/health') +- `status_code`: Expected HTTP status code (default: 200) + +**Returns**: + +ReadyCmd that checks the URL +Example +```python +from e2b import Template, wait_for_url + +template = ( + Template() + .from_node_image() + .set_start_cmd('npm start', wait_for_url('http://localhost:3000/health')) +) +``` + + + +### wait\_for\_process + +```python +def wait_for_process(process_name: str) +``` + +Wait for a process with a specific name to be running. + +Uses `pgrep` to check if a process exists. + +**Arguments**: + +- `process_name`: Name of the process to wait for + +**Returns**: + +ReadyCmd that checks for the process +Example +```python +from e2b import Template, wait_for_process + +template = ( + Template() + .from_base_image() + .set_start_cmd('./my-daemon', wait_for_process('my-daemon')) +) +``` + + + +### wait\_for\_file + +```python +def wait_for_file(filename: str) +``` + +Wait for a file to exist. + +Uses shell test command to check file existence. + +**Arguments**: + +- `filename`: Path to the file to wait for + +**Returns**: + +ReadyCmd that checks for the file +Example +```python +from e2b import Template, wait_for_file + +template = ( + Template() + .from_base_image() + .set_start_cmd('./init.sh', wait_for_file('/tmp/ready')) +) +``` + + + +### wait\_for\_timeout + +```python +def wait_for_timeout(timeout: int) +``` + +Wait for a specified timeout before considering the sandbox ready. + +Uses `sleep` command to wait for a fixed duration. + +**Arguments**: + +- `timeout`: Time to wait in **milliseconds** (minimum: 1000ms / 1 second) + +**Returns**: + +ReadyCmd that waits for the specified duration +Example +```python +from e2b import Template, wait_for_timeout + +template = ( + Template() + .from_node_image() + .set_start_cmd('npm start', wait_for_timeout(5000)) # Wait 5 seconds +) +``` + + + + + + +### read\_dockerignore + +```python +def read_dockerignore(context_path: str) -> List[str] +``` + +Read and parse a .dockerignore file. + +**Arguments**: + +- `context_path`: Directory path containing the .dockerignore file + +**Returns**: + +Array of ignore patterns (empty lines and comments are filtered out) + + + +### get\_all\_files\_in\_path + +```python +def get_all_files_in_path(src: str, + context_path: str, + ignore_patterns: List[str], + include_directories: bool = True) -> List[str] +``` + +Get all files for a given path and ignore patterns. + +**Arguments**: + +- `src`: Path to the source directory +- `context_path`: Base directory for resolving relative paths +- `ignore_patterns`: Ignore patterns +- `include_directories`: Whether to include directories + +**Returns**: + +Array of files + + + +### calculate\_files\_hash + +```python +def calculate_files_hash(src: str, dest: str, context_path: str, + ignore_patterns: List[str], resolve_symlinks: bool, + stack_trace: Optional[TracebackType]) -> str +``` + +Calculate a hash of files being copied to detect changes for cache invalidation. + +The hash includes file content, metadata (mode, size), and relative paths. +Note: uid, gid, and mtime are excluded to ensure stable hashes across environments. + +**Arguments**: + +- `src`: Source path pattern for files to copy +- `dest`: Destination path where files will be copied +- `context_path`: Base directory for resolving relative paths +- `ignore_patterns`: Glob patterns to ignore +- `resolve_symlinks`: Whether to resolve symbolic links when hashing +- `stack_trace`: Optional stack trace for error reporting + +**Raises**: + +- `ValueError`: If no files match the source pattern + +**Returns**: + +Hex string hash of all files + + + +### tar\_file\_stream + +```python +def tar_file_stream(file_name: str, file_context_path: str, + ignore_patterns: List[str], + resolve_symlinks: bool) -> io.BytesIO +``` + +Create a tar stream of files matching a pattern. + +**Arguments**: + +- `file_name`: Glob pattern for files to include +- `file_context_path`: Base directory for resolving file paths +- `ignore_patterns`: Ignore patterns +- `resolve_symlinks`: Whether to resolve symbolic links + +**Returns**: + +Tar stream + + + +### strip\_ansi\_escape\_codes + +```python +def strip_ansi_escape_codes(text: str) -> str +``` + +Strip ANSI escape codes from a string. + +Source: https://github.com/chalk/ansi-regex/blob/main/index.js + +**Arguments**: + +- `text`: String with ANSI escape codes + +**Returns**: + +String without ANSI escape codes + + + +### get\_caller\_frame + +```python +def get_caller_frame(depth: int) -> Optional[FrameType] +``` + +Get the caller's stack frame at a specific depth. + +This is used to provide better error messages and debugging information +by tracking where template methods were called from in user code. + +**Arguments**: + +- `depth`: The depth of the stack trace to retrieve + +**Returns**: + +The caller frame, or None if not available + + + +### get\_caller\_directory + +```python +def get_caller_directory(depth: int) -> Optional[str] +``` + +Get the directory of the caller at a specific stack depth. + +This is used to determine the file_context_path when creating a template, +so file paths are resolved relative to the user's template file location. + +**Arguments**: + +- `depth`: The depth of the stack trace + +**Returns**: + +The caller's directory path, or None if not available + + + +### pad\_octal + +```python +def pad_octal(mode: int) -> str +``` + +Convert a numeric file mode to a zero-padded octal string. + +**Arguments**: + +- `mode`: File mode as a number (e.g., 493 for 0o755) + +**Returns**: + +Zero-padded 4-digit octal string (e.g., "0755") +Example +```python +pad_octal(0o755) # Returns "0755" +pad_octal(0o644) # Returns "0644" +``` + + + +### get\_build\_step\_index + +```python +def get_build_step_index(step: str, stack_traces_length: int) -> int +``` + +Get the array index for a build step based on its name. + +Special steps: +- BASE_STEP_NAME: Returns 0 (first step) +- FINALIZE_STEP_NAME: Returns the last index +- Numeric strings: Converted to number + +**Arguments**: + +- `step`: Build step name or number as string +- `stack_traces_length`: Total number of stack traces (used for FINALIZE_STEP_NAME) + +**Returns**: + +Index for the build step + + + +### read\_gcp\_service\_account\_json + +```python +def read_gcp_service_account_json(context_path: str, + path_or_content: Union[str, dict]) -> str +``` + +Read GCP service account JSON from a file or object. + +**Arguments**: + +- `context_path`: Base directory for resolving relative file paths +- `path_or_content`: Either a path to a JSON file or a service account object + +**Returns**: + +Service account JSON as a string + + + + + + +## TemplateBuilder + +```python +class TemplateBuilder() +``` + +Builder class for adding instructions to an E2B template. + +All methods return self to allow method chaining. + + + +### copy + +```python +def copy(src: Union[Union[str, Path], List[Union[str, Path]]], + dest: Union[str, Path], + force_upload: Optional[Literal[True]] = None, + user: Optional[str] = None, + mode: Optional[int] = None, + resolve_symlinks: Optional[bool] = None) -> "TemplateBuilder" +``` + +Copy files or directories from the local filesystem into the template. + +**Arguments**: + +- `src`: Source file(s) or directory path(s) to copy +- `dest`: Destination path in the template +- `force_upload`: Force upload even if files are cached +- `user`: User and optionally group (user:group) to own the files +- `mode`: File permissions in octal format (e.g., 0o755) +- `resolve_symlinks`: Whether to resolve symlinks + +**Returns**: + +`TemplateBuilder` class +Example +```python +template.copy('requirements.txt', '/home/user/') +template.copy(['app.py', 'config.py'], '/app/', mode=0o755) +``` + + + +### copy\_items + +```python +def copy_items(items: List[CopyItem]) -> "TemplateBuilder" +``` + +Copy multiple files or directories using a list of copy items. + +**Arguments**: + +- `items`: List of CopyItem dictionaries with src, dest, and optional parameters + +**Returns**: + +`TemplateBuilder` class +Example +```python +template.copy_items([ + {'src': 'app.py', 'dest': '/app/'}, + {'src': 'config.py', 'dest': '/app/', 'mode': 0o644} +]) +``` + + + +### remove + +```python +def remove(path: Union[Union[str, Path], List[Union[str, Path]]], + force: bool = False, + recursive: bool = False, + user: Optional[str] = None) -> "TemplateBuilder" +``` + +Remove files or directories in the template. + +**Arguments**: + +- `path`: File(s) or directory path(s) to remove +- `force`: Force removal without prompting +- `recursive`: Remove directories recursively +- `user`: User to run the command as + +**Returns**: + +`TemplateBuilder` class +Example +```python +template.remove('/tmp/cache', recursive=True, force=True) +template.remove('/tmp/cache', recursive=True, force=True, user='root') +``` + + + +### rename + +```python +def rename(src: Union[str, Path], + dest: Union[str, Path], + force: bool = False, + user: Optional[str] = None) -> "TemplateBuilder" +``` + +Rename or move a file or directory in the template. + +**Arguments**: + +- `src`: Source path +- `dest`: Destination path +- `force`: Force rename without prompting +- `user`: User to run the command as + +**Returns**: + +`TemplateBuilder` class +Example +```python +template.rename('/tmp/old.txt', '/tmp/new.txt') +template.rename('/tmp/old.txt', '/tmp/new.txt', user='root') +``` + + + +### make\_dir + +```python +def make_dir(path: Union[Union[str, Path], List[Union[str, Path]]], + mode: Optional[int] = None, + user: Optional[str] = None) -> "TemplateBuilder" +``` + +Create directory(ies) in the template. + +**Arguments**: + +- `path`: Directory path(s) to create +- `mode`: Directory permissions in octal format (e.g., 0o755) +- `user`: User to run the command as + +**Returns**: + +`TemplateBuilder` class +Example +```python +template.make_dir('/app/data', mode=0o755) +template.make_dir(['/app/logs', '/app/cache']) +template.make_dir('/app/data', mode=0o755, user='root') +``` + + + +### make\_symlink + +```python +def make_symlink(src: Union[str, Path], + dest: Union[str, Path], + user: Optional[str] = None, + force: bool = False) -> "TemplateBuilder" +``` + +Create a symbolic link in the template. + +**Arguments**: + +- `src`: Source path (target of the symlink) +- `dest`: Destination path (location of the symlink) +- `user`: User to run the command as +- `force`: Force symlink without prompting + +**Returns**: + +`TemplateBuilder` class +Example +```python +template.make_symlink('/usr/bin/python3', '/usr/bin/python') +template.make_symlink('/usr/bin/python3', '/usr/bin/python', user='root') +template.make_symlink('/usr/bin/python3', '/usr/bin/python', force=True) +``` + + + +### run\_cmd + +```python +def run_cmd(command: Union[str, List[str]], + user: Optional[str] = None) -> "TemplateBuilder" +``` + +Run a shell command during template build. + +**Arguments**: + +- `command`: Command string or list of commands to run (joined with &&) +- `user`: User to run the command as + +**Returns**: + +`TemplateBuilder` class +Example +```python +template.run_cmd('apt-get update') +template.run_cmd(['pip install numpy', 'pip install pandas']) +template.run_cmd('apt-get install vim', user='root') +``` + + + +### set\_workdir + +```python +def set_workdir(workdir: Union[str, Path]) -> "TemplateBuilder" +``` + +Set the working directory for subsequent commands in the template. + +**Arguments**: + +- `workdir`: Path to set as the working directory + +**Returns**: + +`TemplateBuilder` class +Example +```python +template.set_workdir('/app') +``` + + + +### set\_user + +```python +def set_user(user: str) -> "TemplateBuilder" +``` + +Set the user for subsequent commands in the template. + +**Arguments**: + +- `user`: Username to set + +**Returns**: + +`TemplateBuilder` class +Example +```python +template.set_user('root') +``` + + + +### pip\_install + +```python +def pip_install(packages: Optional[Union[str, List[str]]] = None, + g: bool = True) -> "TemplateBuilder" +``` + +Install Python packages using pip. + +**Arguments**: + +- `packages`: Package name(s) to install. If None, runs 'pip install .' in the current directory +- `g`: Install packages globally (default: True). If False, installs for user only + +**Returns**: + +`TemplateBuilder` class +Example +```python +template.pip_install('numpy') +template.pip_install(['pandas', 'scikit-learn']) +template.pip_install('numpy', g=False) # Install for user only +template.pip_install() # Installs from current directory +``` + + + +### npm\_install + +```python +def npm_install(packages: Optional[Union[str, List[str]]] = None, + g: Optional[bool] = False, + dev: Optional[bool] = False) -> "TemplateBuilder" +``` + +Install Node.js packages using npm. + +**Arguments**: + +- `packages`: Package name(s) to install. If None, installs from package.json +- `g`: Install packages globally +- `dev`: Install packages as dev dependencies + +**Returns**: + +`TemplateBuilder` class +Example +```python +template.npm_install('express') +template.npm_install(['lodash', 'axios']) +template.npm_install('typescript', g=True) +template.npm_install() # Installs from package.json +``` + + + +### bun\_install + +```python +def bun_install(packages: Optional[Union[str, List[str]]] = None, + g: Optional[bool] = False, + dev: Optional[bool] = False) -> "TemplateBuilder" +``` + +Install Bun packages using bun. + +**Arguments**: + +- `packages`: Package name(s) to install. If None, installs from package.json +- `g`: Install packages globally +- `dev`: Install packages as dev dependencies + +**Returns**: + +`TemplateBuilder` class +Example +```python +template.bun_install('express') +template.bun_install(['lodash', 'axios']) +template.bun_install('tsx', g=True) +template.bun_install('typescript', dev=True) +template.bun_install() // Installs from package.json +``` + + + +### apt\_install + +```python +def apt_install(packages: Union[str, List[str]], + no_install_recommends: bool = False) -> "TemplateBuilder" +``` + +Install system packages using apt-get. + +**Arguments**: + +- `packages`: Package name(s) to install +- `no_install_recommends`: Whether to install recommended packages + +**Returns**: + +`TemplateBuilder` class +Example +```python +template.apt_install('vim') +template.apt_install(['git', 'curl', 'wget']) +``` + + + +### add\_mcp\_server + +```python +def add_mcp_server(servers: Union[str, List[str]]) -> "TemplateBuilder" +``` + +Install MCP servers using mcp-gateway. + +Note: Requires a base image with mcp-gateway pre-installed (e.g., mcp-gateway). + +**Arguments**: + +- `servers`: MCP server name(s) + +**Returns**: + +`TemplateBuilder` class +Example +```python +template.add_mcp_server('exa') +template.add_mcp_server(['brave', 'firecrawl', 'duckduckgo']) +``` + + + +### git\_clone + +```python +def git_clone(url: str, + path: Optional[Union[str, Path]] = None, + branch: Optional[str] = None, + depth: Optional[int] = None, + user: Optional[str] = None) -> "TemplateBuilder" +``` + +Clone a git repository into the template. + +**Arguments**: + +- `url`: Git repository URL +- `path`: Destination path for the clone +- `branch`: Branch to clone +- `depth`: Clone depth for shallow clones +- `user`: User to run the command as + +**Returns**: + +`TemplateBuilder` class +Example +```python +template.git_clone('https://github.com/user/repo.git', '/app/repo') +template.git_clone('https://github.com/user/repo.git', branch='main', depth=1) +template.git_clone('https://github.com/user/repo.git', '/app/repo', user='root') +``` + + + +### beta\_dev\_container\_prebuild + +```python +def beta_dev_container_prebuild( + devcontainer_directory: Union[str, Path]) -> "TemplateBuilder" +``` + +Prebuild a devcontainer from the specified directory during the build process. + +**Arguments**: + +- `devcontainer_directory`: Path to the devcontainer directory + +**Returns**: + +`TemplateBuilder` class +Example +```python +template.git_clone('https://myrepo.com/project.git', '/my-devcontainer') +template.beta_dev_container_prebuild('/my-devcontainer') +``` + + + +### beta\_set\_dev\_container\_start + +```python +def beta_set_dev_container_start( + devcontainer_directory: Union[str, Path]) -> "TemplateFinal" +``` + +Start a devcontainer from the specified directory and set it as the start command. + +This method returns `TemplateFinal`, which means it must be the last method in the chain. + +**Arguments**: + +- `devcontainer_directory`: Path to the devcontainer directory + +**Returns**: + +`TemplateFinal` class +Example +```python +template.git_clone('https://myrepo.com/project.git', '/my-devcontainer') +template.beta_set_devcontainer_start('/my-devcontainer') + +template.git_clone('https://myrepo.com/project.git', '/my-devcontainer') +template.beta_dev_container_prebuild('/my-devcontainer') +template.beta_set_dev_container_start('/my-devcontainer') +``` + + + +### set\_envs + +```python +def set_envs(envs: Dict[str, str]) -> "TemplateBuilder" +``` + +Set environment variables in the template. + +**Arguments**: + +- `envs`: Dictionary of environment variable names and values + +**Returns**: + +`TemplateBuilder` class +Example +```python +template.set_envs({'NODE_ENV': 'production', 'PORT': '8080'}) +``` + + + +### skip\_cache + +```python +def skip_cache() -> "TemplateBuilder" +``` + +Skip cache for all subsequent build instructions from this point. + +Call this before any instruction to force it and all following layers +to be rebuilt, ignoring any cached layers. + +**Returns**: + +`TemplateBuilder` class +Example +```python +template.skip_cache().run_cmd('apt-get update') +``` + + + +### set\_start\_cmd + +```python +def set_start_cmd(start_cmd: str, + ready_cmd: Union[str, ReadyCmd]) -> "TemplateFinal" +``` + +Set the command to start when the sandbox launches and the ready check command. + +**Arguments**: + +- `start_cmd`: Command to run when the sandbox starts +- `ready_cmd`: Command or ReadyCmd to check if the sandbox is ready + +**Returns**: + +`TemplateFinal` class +Example +```python +template.set_start_cmd( + 'python app.py', + 'curl http://localhost:8000/health' +) + +from e2b import wait_for_port, wait_for_url + +template.set_start_cmd( + 'python -m http.server 8000', + wait_for_port(8000) +) + +template.set_start_cmd( + 'npm start', + wait_for_url('http://localhost:3000/health', 200) +) +``` + + + +### set\_ready\_cmd + +```python +def set_ready_cmd(ready_cmd: Union[str, ReadyCmd]) -> "TemplateFinal" +``` + +Set the command to check if the sandbox is ready. + +**Arguments**: + +- `ready_cmd`: Command or ReadyCmd to check if the sandbox is ready + +**Returns**: + +`TemplateFinal` class +Example +```python +template.set_ready_cmd('curl http://localhost:8000/health') + +from e2b import wait_for_port, wait_for_file, wait_for_process + +template.set_ready_cmd(wait_for_port(3000)) + +template.set_ready_cmd(wait_for_file('/tmp/ready')) + +template.set_ready_cmd(wait_for_process('nginx')) +``` + + + +## TemplateFinal + +```python +class TemplateFinal() +``` + +Final template state after start/ready commands are set. + + + +## TemplateBase + +```python +class TemplateBase() +``` + +Base class for building E2B sandbox templates. + + + +### \_\_init\_\_ + +```python +def __init__(file_context_path: Optional[Union[str, Path]] = None, + file_ignore_patterns: Optional[List[str]] = None) +``` + +Create a new template builder instance. + +**Arguments**: + +- `file_context_path`: Base path for resolving relative file paths in copy operations +- `file_ignore_patterns`: List of glob patterns to ignore when copying files + + + +### skip\_cache + +```python +def skip_cache() -> "TemplateBase" +``` + +Skip cache for all subsequent build instructions from this point. + +**Returns**: + +`TemplateBase` class +Example +```python +template.skip_cache().from_python_image('3.11') +``` + + + +### from\_debian\_image + +```python +def from_debian_image(variant: str = "stable") -> TemplateBuilder +``` + +Start template from a Debian base image. + +**Arguments**: + +- `variant`: Debian image variant + +**Returns**: + +`TemplateBuilder` class +Example +```python +Template().from_debian_image('bookworm') +``` + + + +### from\_ubuntu\_image + +```python +def from_ubuntu_image(variant: str = "latest") -> TemplateBuilder +``` + +Start template from an Ubuntu base image. + +**Arguments**: + +- `variant`: Ubuntu image variant (default: 'latest') + +**Returns**: + +`TemplateBuilder` class +Example +```python +Template().from_ubuntu_image('24.04') +``` + + + +### from\_python\_image + +```python +def from_python_image(version: str = "3") -> TemplateBuilder +``` + +Start template from a Python base image. + +**Arguments**: + +- `version`: Python version (default: '3') + +**Returns**: + +`TemplateBuilder` class +Example +```python +Template().from_python_image('3') +``` + + + +### from\_node\_image + +```python +def from_node_image(variant: str = "lts") -> TemplateBuilder +``` + +Start template from a Node.js base image. + +**Arguments**: + +- `variant`: Node.js image variant (default: 'lts') + +**Returns**: + +`TemplateBuilder` class +Example +```python +Template().from_node_image('24') +``` + + + +### from\_bun\_image + +```python +def from_bun_image(variant: str = "latest") -> TemplateBuilder +``` + +Start template from a Bun base image. + +**Arguments**: + +- `variant`: Bun image variant (default: 'latest') + +**Returns**: + +`TemplateBuilder` class + + + +### from\_base\_image + +```python +def from_base_image() -> TemplateBuilder +``` + +Start template from the E2B base image (e2bdev/base:latest). + +**Returns**: + +`TemplateBuilder` class +Example +```python +Template().from_base_image() +``` + + + +### from\_image + +```python +def from_image(image: str, + username: Optional[str] = None, + password: Optional[str] = None) -> TemplateBuilder +``` + +Start template from a Docker image. + +**Arguments**: + +- `image`: Docker image name (e.g., 'ubuntu:24.04') +- `username`: Username for private registry authentication +- `password`: Password for private registry authentication + +**Returns**: + +`TemplateBuilder` class +Example +```python +Template().from_image('python:3') + +Template().from_image('myregistry.com/myimage:latest', username='user', password='pass') +``` + + + +### from\_template + +```python +def from_template(template: str) -> TemplateBuilder +``` + +Start template from an existing E2B template. + +**Arguments**: + +- `template`: E2B template ID or alias + +**Returns**: + +`TemplateBuilder` class +Example +```python +Template().from_template('my-base-template') +``` + + + +### from\_dockerfile + +```python +def from_dockerfile(dockerfile_content_or_path: str) -> TemplateBuilder +``` + +Parse a Dockerfile and convert it to Template SDK format. + +**Arguments**: + +- `dockerfile_content_or_path`: Either the Dockerfile content as a string, or a path to a Dockerfile file + +**Returns**: + +`TemplateBuilder` class +Example +```python +Template().from_dockerfile('Dockerfile') +Template().from_dockerfile('FROM python:3\nRUN pip install numpy') +``` + + + +### from\_aws\_registry + +```python +def from_aws_registry(image: str, access_key_id: str, secret_access_key: str, + region: str) -> TemplateBuilder +``` + +Start template from an AWS ECR registry image. + +**Arguments**: + +- `image`: Docker image name from AWS ECR +- `access_key_id`: AWS access key ID +- `secret_access_key`: AWS secret access key +- `region`: AWS region + +**Returns**: + +`TemplateBuilder` class +Example +```python +Template().from_aws_registry( + '123456789.dkr.ecr.us-west-2.amazonaws.com/myimage:latest', + access_key_id='AKIA...', + secret_access_key='...', + region='us-west-2' +) +``` + + + +### from\_gcp\_registry + +```python +def from_gcp_registry( + image: str, service_account_json: Union[str, dict]) -> TemplateBuilder +``` + +Start template from a GCP Artifact Registry or Container Registry image. + +**Arguments**: + +- `image`: Docker image name from GCP registry +- `service_account_json`: Service account JSON string, dict, or path to JSON file + +**Returns**: + +`TemplateBuilder` class +Example +```python +Template().from_gcp_registry( + 'gcr.io/myproject/myimage:latest', + service_account_json='path/to/service-account.json' +) +``` + + + +### to\_json + +```python +@staticmethod +def to_json(template: "TemplateClass") -> str +``` + +Convert a template to JSON representation. + +**Arguments**: + +- `template`: The template to convert (TemplateBuilder or TemplateFinal instance) + +**Returns**: + +JSON string representation of the template +Example +```python +template = Template().from_python_image('3').copy('app.py', '/app/') +json_str = TemplateBase.to_json(template) +``` + + + +### to\_dockerfile + +```python +@staticmethod +def to_dockerfile(template: "TemplateClass") -> str +``` + +Convert a template to Dockerfile format. + +Note: Templates based on other E2B templates cannot be converted to Dockerfile. + +**Arguments**: + +- `template`: The template to convert (TemplateBuilder or TemplateFinal instance) + +**Raises**: + +- `ValueError`: If the template is based on another E2B template or has no base image +Example +```python +template = Template().from_python_image('3').copy('app.py', '/app/') +dockerfile = TemplateBase.to_dockerfile(template) +``` + +**Returns**: + +Dockerfile string representation diff --git a/docs/sdk-reference/python-sdk/v2.8.0/template_async.mdx b/docs/sdk-reference/python-sdk/v2.8.0/template_async.mdx new file mode 100644 index 0000000..950d066 --- /dev/null +++ b/docs/sdk-reference/python-sdk/v2.8.0/template_async.mdx @@ -0,0 +1,150 @@ +--- +sidebarTitle: "Template Async" +mode: "center" +--- + + + + + + + + + +## AsyncTemplate + +```python +class AsyncTemplate(TemplateBase) +``` + +Asynchronous template builder for E2B sandboxes. + + + +### build + +```python +@staticmethod +async def build(template: TemplateClass, + alias: str, + cpu_count: int = 2, + memory_mb: int = 1024, + skip_cache: bool = False, + on_build_logs: Optional[Callable[[LogEntry], None]] = None, + api_key: Optional[str] = None, + domain: Optional[str] = None) -> BuildInfo +``` + +Build and deploy a template to E2B infrastructure. + +**Arguments**: + +- `template`: The template to build +- `alias`: Alias name for the template +- `cpu_count`: Number of CPUs allocated to the sandbox +- `memory_mb`: Amount of memory in MB allocated to the sandbox +- `skip_cache`: If True, forces a complete rebuild ignoring cache +- `on_build_logs`: Callback function to receive build logs during the build process +- `api_key`: E2B API key for authentication +- `domain`: Domain of the E2B API +Example +```python +from e2b import AsyncTemplate + +template = ( + AsyncTemplate() + .from_python_image('3') + .copy('requirements.txt', '/home/user/') + .run_cmd('pip install -r /home/user/requirements.txt') +) + +await AsyncTemplate.build( + template, + alias='my-python-env', + cpu_count=2, + memory_mb=1024 +) +``` + + + +### build\_in\_background + +```python +@staticmethod +async def build_in_background(template: TemplateClass, + alias: str, + cpu_count: int = 2, + memory_mb: int = 1024, + skip_cache: bool = False, + on_build_logs: Optional[Callable[[LogEntry], + None]] = None, + api_key: Optional[str] = None, + domain: Optional[str] = None) -> BuildInfo +``` + +Build and deploy a template to E2B infrastructure without waiting for completion. + +**Arguments**: + +- `template`: The template to build +- `alias`: Alias name for the template +- `cpu_count`: Number of CPUs allocated to the sandbox +- `memory_mb`: Amount of memory in MB allocated to the sandbox +- `skip_cache`: If True, forces a complete rebuild ignoring cache +- `api_key`: E2B API key for authentication +- `domain`: Domain of the E2B API + +**Returns**: + +BuildInfo containing the template ID and build ID +Example +```python +from e2b import AsyncTemplate + +template = ( + AsyncTemplate() + .from_python_image('3') + .run_cmd('echo "test"') + .set_start_cmd('echo "Hello"', 'sleep 1') +) + +build_info = await AsyncTemplate.build_in_background( + template, + alias='my-python-env', + cpu_count=2, + memory_mb=1024 +) +``` + + + +### get\_build\_status + +```python +@staticmethod +async def get_build_status(build_info: BuildInfo, + logs_offset: int = 0, + api_key: Optional[str] = None, + domain: Optional[str] = None) +``` + +Get the status of a build. + +**Arguments**: + +- `build_info`: Build identifiers returned from build_in_background +- `logs_offset`: Offset for fetching logs +- `api_key`: E2B API key for authentication +- `domain`: Domain of the E2B API + +**Returns**: + +TemplateBuild containing the build status and logs +Example +```python +from e2b import AsyncTemplate + +build_info = await AsyncTemplate.build_in_background(template, alias='my-template') +status = await AsyncTemplate.get_build_status(build_info, logs_offset=0) +``` diff --git a/docs/sdk-reference/python-sdk/v2.8.0/template_sync.mdx b/docs/sdk-reference/python-sdk/v2.8.0/template_sync.mdx new file mode 100644 index 0000000..6387438 --- /dev/null +++ b/docs/sdk-reference/python-sdk/v2.8.0/template_sync.mdx @@ -0,0 +1,150 @@ +--- +sidebarTitle: "Template Sync" +mode: "center" +--- + + + + + + + + + +## Template + +```python +class Template(TemplateBase) +``` + +Synchronous template builder for E2B sandboxes. + + + +### build + +```python +@staticmethod +def build(template: TemplateClass, + alias: str, + cpu_count: int = 2, + memory_mb: int = 1024, + skip_cache: bool = False, + on_build_logs: Optional[Callable[[LogEntry], None]] = None, + api_key: Optional[str] = None, + domain: Optional[str] = None) -> BuildInfo +``` + +Build and deploy a template to E2B infrastructure. + +**Arguments**: + +- `template`: The template to build +- `alias`: Alias name for the template +- `cpu_count`: Number of CPUs allocated to the sandbox +- `memory_mb`: Amount of memory in MB allocated to the sandbox +- `skip_cache`: If True, forces a complete rebuild ignoring cache +- `on_build_logs`: Callback function to receive build logs during the build process +- `api_key`: E2B API key for authentication +- `domain`: Domain of the E2B API +Example +```python +from e2b import Template + +template = ( + Template() + .from_python_image('3') + .copy('requirements.txt', '/home/user/') + .run_cmd('pip install -r /home/user/requirements.txt') +) + +Template.build( + template, + alias='my-python-env', + cpu_count=2, + memory_mb=1024 +) +``` + + + +### build\_in\_background + +```python +@staticmethod +def build_in_background(template: TemplateClass, + alias: str, + cpu_count: int = 2, + memory_mb: int = 1024, + skip_cache: bool = False, + on_build_logs: Optional[Callable[[LogEntry], + None]] = None, + api_key: Optional[str] = None, + domain: Optional[str] = None) -> BuildInfo +``` + +Build and deploy a template to E2B infrastructure without waiting for completion. + +**Arguments**: + +- `template`: The template to build +- `alias`: Alias name for the template +- `cpu_count`: Number of CPUs allocated to the sandbox +- `memory_mb`: Amount of memory in MB allocated to the sandbox +- `skip_cache`: If True, forces a complete rebuild ignoring cache +- `api_key`: E2B API key for authentication +- `domain`: Domain of the E2B API + +**Returns**: + +BuildInfo containing the template ID and build ID +Example +```python +from e2b import Template + +template = ( + Template() + .from_python_image('3') + .run_cmd('echo "test"') + .set_start_cmd('echo "Hello"', 'sleep 1') +) + +build_info = Template.build_in_background( + template, + alias='my-python-env', + cpu_count=2, + memory_mb=1024 +) +``` + + + +### get\_build\_status + +```python +@staticmethod +def get_build_status(build_info: BuildInfo, + logs_offset: int = 0, + api_key: Optional[str] = None, + domain: Optional[str] = None) +``` + +Get the status of a build. + +**Arguments**: + +- `build_info`: Build identifiers returned from build_in_background +- `logs_offset`: Offset for fetching logs +- `api_key`: E2B API key for authentication +- `domain`: Domain of the E2B API + +**Returns**: + +TemplateBuild containing the build status and logs +Example +```python +from e2b import Template + +build_info = Template.build_in_background(template, alias='my-template') +status = Template.get_build_status(build_info, logs_offset=0) +``` diff --git a/docs/sdk-reference/python-sdk/v2.8.1/exceptions.mdx b/docs/sdk-reference/python-sdk/v2.8.1/exceptions.mdx new file mode 100644 index 0000000..d66f786 --- /dev/null +++ b/docs/sdk-reference/python-sdk/v2.8.1/exceptions.mdx @@ -0,0 +1,117 @@ +--- +sidebarTitle: "Exceptions" +mode: "center" +--- + + + + + + +## SandboxException + +```python +class SandboxException(Exception) +``` + +Base class for all sandbox errors. + +Raised when a general sandbox exception occurs. + + + +## TimeoutException + +```python +class TimeoutException(SandboxException) +``` + +Raised when a timeout occurs. + +The `unavailable` exception type is caused by sandbox timeout. + +The `canceled` exception type is caused by exceeding request timeout. + +The `deadline_exceeded` exception type is caused by exceeding the timeout for process, watch, etc. + +The `unknown` exception type is sometimes caused by the sandbox timeout when the request is not processed correctly. + + + +## InvalidArgumentException + +```python +class InvalidArgumentException(SandboxException) +``` + +Raised when an invalid argument is provided. + + + +## NotEnoughSpaceException + +```python +class NotEnoughSpaceException(SandboxException) +``` + +Raised when there is not enough disk space. + + + +## NotFoundException + +```python +class NotFoundException(SandboxException) +``` + +Raised when a resource is not found. + + + +## AuthenticationException + +```python +class AuthenticationException(Exception) +``` + +Raised when authentication fails. + + + +## TemplateException + +```python +class TemplateException(SandboxException) +``` + +Exception raised when the template uses old envd version. It isn't compatible with the new SDK. + + + +## RateLimitException + +```python +class RateLimitException(SandboxException) +``` + +Raised when the API rate limit is exceeded. + + + +## BuildException + +```python +class BuildException(Exception) +``` + +Raised when the build fails. + + + +## FileUploadException + +```python +class FileUploadException(BuildException) +``` + +Raised when the file upload fails. diff --git a/docs/sdk-reference/python-sdk/v2.8.1/logger.mdx b/docs/sdk-reference/python-sdk/v2.8.1/logger.mdx new file mode 100644 index 0000000..9fa3b18 --- /dev/null +++ b/docs/sdk-reference/python-sdk/v2.8.1/logger.mdx @@ -0,0 +1,106 @@ +--- +sidebarTitle: "Logger" +mode: "center" +--- + + + + + + +## LogEntry + +```python +@dataclass +class LogEntry() +``` + +Represents a single log entry from the template build process. + + + +## LogEntryStart + +```python +@dataclass +class LogEntryStart(LogEntry) +``` + +Special log entry indicating the start of a build process. + + + +## LogEntryEnd + +```python +@dataclass +class LogEntryEnd(LogEntry) +``` + +Special log entry indicating the end of a build process. + + + +### TIMER\_UPDATE\_INTERVAL\_MS + +Default minimum log level to display. + + + +### DEFAULT\_LEVEL + +Colored labels for each log level. + + + +### levels + +Numeric ordering of log levels for comparison (lower = less severe). + + + +### set\_interval + +```python +def set_interval(func, interval) +``` + +Returns a stop function that can be called to cancel the interval. + +Similar to JavaScript's setInterval. + +**Arguments**: + +- `func`: Function to execute at each interval +- `interval`: Interval duration in **seconds** + +**Returns**: + +Stop function that can be called to cancel the interval + + + +### default\_build\_logger + +```python +def default_build_logger( + min_level: Optional[LogEntryLevel] = None +) -> Callable[[LogEntry], None] +``` + +Create a default build logger with animated timer display. + +**Arguments**: + +- `min_level`: Minimum log level to display (default: 'info') + +**Returns**: + +Logger function that accepts LogEntry instances +Example +```python +from e2b import Template, default_build_logger + +template = Template().from_python_image() + +``` diff --git a/docs/sdk-reference/python-sdk/v2.8.1/readycmd.mdx b/docs/sdk-reference/python-sdk/v2.8.1/readycmd.mdx new file mode 100644 index 0000000..8eabda6 --- /dev/null +++ b/docs/sdk-reference/python-sdk/v2.8.1/readycmd.mdx @@ -0,0 +1,168 @@ +--- +sidebarTitle: "Readycmd" +mode: "center" +--- + + + + + + +## ReadyCmd + +```python +class ReadyCmd() +``` + +Wrapper class for ready check commands. + + + +### wait\_for\_port + +```python +def wait_for_port(port: int) +``` + +Wait for a port to be listening. + +Uses `ss` command to check if a port is open and listening. + +**Arguments**: + +- `port`: Port number to wait for + +**Returns**: + +ReadyCmd that checks for the port +Example +```python +from e2b import Template, wait_for_port + +template = ( + Template() + .from_python_image() + .set_start_cmd('python -m http.server 8000', wait_for_port(8000)) +) +``` + + + +### wait\_for\_url + +```python +def wait_for_url(url: str, status_code: int = 200) +``` + +Wait for a URL to return a specific HTTP status code. + +Uses `curl` to make HTTP requests and check the response status. + +**Arguments**: + +- `url`: URL to check (e.g., 'http://localhost:3000/health') +- `status_code`: Expected HTTP status code (default: 200) + +**Returns**: + +ReadyCmd that checks the URL +Example +```python +from e2b import Template, wait_for_url + +template = ( + Template() + .from_node_image() + .set_start_cmd('npm start', wait_for_url('http://localhost:3000/health')) +) +``` + + + +### wait\_for\_process + +```python +def wait_for_process(process_name: str) +``` + +Wait for a process with a specific name to be running. + +Uses `pgrep` to check if a process exists. + +**Arguments**: + +- `process_name`: Name of the process to wait for + +**Returns**: + +ReadyCmd that checks for the process +Example +```python +from e2b import Template, wait_for_process + +template = ( + Template() + .from_base_image() + .set_start_cmd('./my-daemon', wait_for_process('my-daemon')) +) +``` + + + +### wait\_for\_file + +```python +def wait_for_file(filename: str) +``` + +Wait for a file to exist. + +Uses shell test command to check file existence. + +**Arguments**: + +- `filename`: Path to the file to wait for + +**Returns**: + +ReadyCmd that checks for the file +Example +```python +from e2b import Template, wait_for_file + +template = ( + Template() + .from_base_image() + .set_start_cmd('./init.sh', wait_for_file('/tmp/ready')) +) +``` + + + +### wait\_for\_timeout + +```python +def wait_for_timeout(timeout: int) +``` + +Wait for a specified timeout before considering the sandbox ready. + +Uses `sleep` command to wait for a fixed duration. + +**Arguments**: + +- `timeout`: Time to wait in **milliseconds** (minimum: 1000ms / 1 second) + +**Returns**: + +ReadyCmd that waits for the specified duration +Example +```python +from e2b import Template, wait_for_timeout + +template = ( + Template() + .from_node_image() + .set_start_cmd('npm start', wait_for_timeout(5000)) # Wait 5 seconds +) +``` diff --git a/docs/sdk-reference/python-sdk/v2.8.1/sandbox_async.mdx b/docs/sdk-reference/python-sdk/v2.8.1/sandbox_async.mdx new file mode 100644 index 0000000..b636b1a --- /dev/null +++ b/docs/sdk-reference/python-sdk/v2.8.1/sandbox_async.mdx @@ -0,0 +1,1387 @@ +--- +sidebarTitle: "Sandbox Async" +mode: "center" +--- + + + + + + +## AsyncWatchHandle + +```python +class AsyncWatchHandle() +``` + +Handle for watching a directory in the sandbox filesystem. + +Use `.stop()` to stop watching the directory. + + + +### stop + +```python +async def stop() +``` + +Stop watching the directory. + + + + + + +## Filesystem + +```python +class Filesystem() +``` + +Module for interacting with the filesystem in the sandbox. + + + +### read + +```python +@overload +async def read(path: str, + format: Literal["text"] = "text", + user: Optional[Username] = None, + request_timeout: Optional[float] = None) -> str +``` + +Read file content as a `str`. + +**Arguments**: + +- `path`: Path to the file +- `user`: Run the operation as this user +- `format`: Format of the file content—`text` by default +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +File content as a `str` + + + +### read + +```python +@overload +async def read(path: str, + format: Literal["bytes"], + user: Optional[Username] = None, + request_timeout: Optional[float] = None) -> bytearray +``` + +Read file content as a `bytearray`. + +**Arguments**: + +- `path`: Path to the file +- `user`: Run the operation as this user +- `format`: Format of the file content—`bytes` +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +File content as a `bytearray` + + + +### read + +```python +@overload +async def read( + path: str, + format: Literal["stream"], + user: Optional[Username] = None, + request_timeout: Optional[float] = None) -> AsyncIterator[bytes] +``` + +Read file content as a `AsyncIterator[bytes]`. + +**Arguments**: + +- `path`: Path to the file +- `user`: Run the operation as this user +- `format`: Format of the file content—`stream` +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +File content as an `AsyncIterator[bytes]` + + + +### write + +```python +async def write(path: str, + data: Union[str, bytes, IO], + user: Optional[Username] = None, + request_timeout: Optional[float] = None) -> WriteInfo +``` + +Write content to a file on the path. + +Writing to a file that doesn't exist creates the file. +Writing to a file that already exists overwrites the file. +Writing to a file at path that doesn't exist creates the necessary directories. + +**Arguments**: + +- `path`: Path to the file +- `data`: Data to write to the file, can be a `str`, `bytes`, or `IO`. +- `user`: Run the operation as this user +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +Information about the written file + + + +### write\_files + +```python +async def write_files( + files: List[WriteEntry], + user: Optional[Username] = None, + request_timeout: Optional[float] = None) -> List[WriteInfo] +``` + +Writes multiple files. + +Writes a list of files to the filesystem. +When writing to a file that doesn't exist, the file will get created. +When writing to a file that already exists, the file will get overwritten. +When writing to a file that's in a directory that doesn't exist, you'll get an error. + +**Arguments**: + +- `files`: list of files to write as `WriteEntry` objects, each containing `path` and `data` +- `user`: Run the operation as this user +- `request_timeout`: Timeout for the request + +**Returns**: + +Information about the written files + + + +### list + +```python +async def list(path: str, + depth: Optional[int] = 1, + user: Optional[Username] = None, + request_timeout: Optional[float] = None) -> List[EntryInfo] +``` + +List entries in a directory. + +**Arguments**: + +- `path`: Path to the directory +- `depth`: Depth of the directory to list +- `user`: Run the operation as this user +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +List of entries in the directory + + + +### exists + +```python +async def exists(path: str, + user: Optional[Username] = None, + request_timeout: Optional[float] = None) -> bool +``` + +Check if a file or a directory exists. + +**Arguments**: + +- `path`: Path to a file or a directory +- `user`: Run the operation as this user +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`True` if the file or directory exists, `False` otherwise + + + +### get\_info + +```python +async def get_info(path: str, + user: Optional[Username] = None, + request_timeout: Optional[float] = None) -> EntryInfo +``` + +Get information about a file or directory. + +**Arguments**: + +- `path`: Path to a file or a directory +- `user`: Run the operation as this user +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +Information about the file or directory like name, type, and path + + + +### remove + +```python +async def remove(path: str, + user: Optional[Username] = None, + request_timeout: Optional[float] = None) -> None +``` + +Remove a file or a directory. + +**Arguments**: + +- `path`: Path to a file or a directory +- `user`: Run the operation as this user +- `request_timeout`: Timeout for the request in **seconds** + + + +### rename + +```python +async def rename(old_path: str, + new_path: str, + user: Optional[Username] = None, + request_timeout: Optional[float] = None) -> EntryInfo +``` + +Rename a file or directory. + +**Arguments**: + +- `old_path`: Path to the file or directory to rename +- `new_path`: New path to the file or directory +- `user`: Run the operation as this user +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +Information about the renamed file or directory + + + +### make\_dir + +```python +async def make_dir(path: str, + user: Optional[Username] = None, + request_timeout: Optional[float] = None) -> bool +``` + +Create a new directory and all directories along the way if needed on the specified path. + +**Arguments**: + +- `path`: Path to a new directory. For example '/dirA/dirB' when creating 'dirB'. +- `user`: Run the operation as this user +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`True` if the directory was created, `False` if the directory already exists + + + +### watch\_dir + +```python +async def watch_dir(path: str, + on_event: OutputHandler[FilesystemEvent], + on_exit: Optional[OutputHandler[Exception]] = None, + user: Optional[Username] = None, + request_timeout: Optional[float] = None, + timeout: Optional[float] = 60, + recursive: bool = False) -> AsyncWatchHandle +``` + +Watch directory for filesystem events. + +**Arguments**: + +- `path`: Path to a directory to watch +- `on_event`: Callback to call on each event in the directory +- `on_exit`: Callback to call when the watching ends +- `user`: Run the operation as this user +- `request_timeout`: Timeout for the request in **seconds** +- `timeout`: Timeout for the watch operation in **seconds**. Using `0` will not limit the watch time +- `recursive`: Watch directory recursively + +**Returns**: + +`AsyncWatchHandle` object for stopping watching directory + + + + + + +## AsyncSandboxPaginator + +```python +class AsyncSandboxPaginator(SandboxPaginatorBase) +``` + +Paginator for listing sandboxes. + +**Example**: + +```python +paginator = AsyncSandbox.list() + +while paginator.has_next: + sandboxes = await paginator.next_items() + print(sandboxes) +``` + + + +### next\_items + +```python +async def next_items() -> List[SandboxInfo] +``` + +Returns the next page of sandboxes. + +Call this method only if `has_next` is `True`, otherwise it will raise an exception. + +**Returns**: + +List of sandboxes + + + + + + + + + +## SandboxApi + +```python +class SandboxApi(SandboxBase) +``` + + + +### list + +```python +@staticmethod +def list(query: Optional[SandboxQuery] = None, + limit: Optional[int] = None, + next_token: Optional[str] = None, + **opts: Unpack[ApiParams]) -> AsyncSandboxPaginator +``` + +List all running sandboxes. + +**Arguments**: + +- `query`: Filter the list of sandboxes by metadata or state, e.g. `SandboxListQuery(metadata={"key": "value"})` or `SandboxListQuery(state=[SandboxState.RUNNING])` +- `limit`: Maximum number of sandboxes to return per page +- `next_token`: Token for pagination + +**Returns**: + +List of running sandboxes + + + + + + +## Commands + +```python +class Commands() +``` + +Module for executing commands in the sandbox. + + + +### list + +```python +async def list(request_timeout: Optional[float] = None) -> List[ProcessInfo] +``` + +Lists all running commands and PTY sessions. + +**Arguments**: + +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +List of running commands and PTY sessions + + + +### kill + +```python +async def kill(pid: int, request_timeout: Optional[float] = None) -> bool +``` + +Kill a running command specified by its process ID. + +It uses `SIGKILL` signal to kill the command. + +**Arguments**: + +- `pid`: Process ID of the command. You can get the list of processes using `sandbox.commands.list()` +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`True` if the command was killed, `False` if the command was not found + + + +### send\_stdin + +```python +async def send_stdin(pid: int, + data: str, + request_timeout: Optional[float] = None) -> None +``` + +Send data to command stdin. + +:param pid Process ID of the command. You can get the list of processes using `sandbox.commands.list()`. +:param data: Data to send to the command +:param request_timeout: Timeout for the request in **seconds** + + + + +### run + +```python +@overload +async def run(cmd: str, + background: Union[Literal[False], None] = None, + envs: Optional[Dict[str, str]] = None, + user: Optional[Username] = None, + cwd: Optional[str] = None, + on_stdout: Optional[OutputHandler[Stdout]] = None, + on_stderr: Optional[OutputHandler[Stderr]] = None, + stdin: Optional[bool] = None, + timeout: Optional[float] = 60, + request_timeout: Optional[float] = None) -> CommandResult +``` + +Start a new command and wait until it finishes executing. + +**Arguments**: + +- `cmd`: Command to execute +- `background`: **`False` if the command should be executed in the foreground**, `True` if the command should be executed in the background +- `envs`: Environment variables used for the command +- `user`: User to run the command as +- `cwd`: Working directory to run the command +- `on_stdout`: Callback for command stdout output +- `on_stderr`: Callback for command stderr output +- `stdin`: If `True`, the command will have a stdin stream that you can send data to using `sandbox.commands.send_stdin()` +- `timeout`: Timeout for the command connection in **seconds**. Using `0` will not limit the command connection time +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`CommandResult` result of the command execution + + + +### run + +```python +@overload +async def run(cmd: str, + background: Literal[True], + envs: Optional[Dict[str, str]] = None, + user: Optional[Username] = None, + cwd: Optional[str] = None, + on_stdout: Optional[OutputHandler[Stdout]] = None, + on_stderr: Optional[OutputHandler[Stderr]] = None, + stdin: Optional[bool] = None, + timeout: Optional[float] = 60, + request_timeout: Optional[float] = None) -> AsyncCommandHandle +``` + +Start a new command and return a handle to interact with it. + +**Arguments**: + +- `cmd`: Command to execute +- `background`: `False` if the command should be executed in the foreground, **`True` if the command should be executed in the background** +- `envs`: Environment variables used for the command +- `user`: User to run the command as +- `cwd`: Working directory to run the command +- `on_stdout`: Callback for command stdout output +- `on_stderr`: Callback for command stderr output +- `stdin`: If `True`, the command will have a stdin stream that you can send data to using `sandbox.commands.send_stdin()` +- `timeout`: Timeout for the command connection in **seconds**. Using `0` will not limit the command connection time +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`AsyncCommandHandle` handle to interact with the running command + + + +### connect + +```python +async def connect( + pid: int, + timeout: Optional[float] = 60, + request_timeout: Optional[float] = None, + on_stdout: Optional[OutputHandler[Stdout]] = None, + on_stderr: Optional[OutputHandler[Stderr]] = None +) -> AsyncCommandHandle +``` + +Connects to a running command. + +You can use `AsyncCommandHandle.wait()` to wait for the command to finish and get execution results. + +**Arguments**: + +- `pid`: Process ID of the command to connect to. You can get the list of processes using `sandbox.commands.list()` +- `request_timeout`: Request timeout in **seconds** +- `timeout`: Timeout for the command connection in **seconds**. Using `0` will not limit the command connection time +- `on_stdout`: Callback for command stdout output +- `on_stderr`: Callback for command stderr output + +**Returns**: + +`AsyncCommandHandle` handle to interact with the running command + + + + + + +## AsyncCommandHandle + +```python +class AsyncCommandHandle() +``` + +Command execution handle. + +It provides methods for waiting for the command to finish, retrieving stdout/stderr, and killing the command. + + + +### pid + +```python +@property +def pid() +``` + +Command process ID. + + + +### stdout + +```python +@property +def stdout() +``` + +Command stdout output. + + + +### stderr + +```python +@property +def stderr() +``` + +Command stderr output. + + + +### error + +```python +@property +def error() +``` + +Command execution error message. + + + +### exit\_code + +```python +@property +def exit_code() +``` + +Command execution exit code. + +`0` if the command finished successfully. + +It is `None` if the command is still running. + + + +### disconnect + +```python +async def disconnect() -> None +``` + +Disconnects from the command. + +The command is not killed, but SDK stops receiving events from the command. +You can reconnect to the command using `sandbox.commands.connect` method. + + + +### wait + +```python +async def wait() -> CommandResult +``` + +Wait for the command to finish and return the result. + +If the command exits with a non-zero exit code, it throws a `CommandExitException`. + +**Returns**: + +`CommandResult` result of command execution + + + +### kill + +```python +async def kill() -> bool +``` + +Kills the command. + +It uses `SIGKILL` signal to kill the command + +**Returns**: + +`True` if the command was killed successfully, `False` if the command was not found + + + + + + +## Pty + +```python +class Pty() +``` + +Module for interacting with PTYs (pseudo-terminals) in the sandbox. + + + +### kill + +```python +async def kill(pid: int, request_timeout: Optional[float] = None) -> bool +``` + +Kill PTY. + +**Arguments**: + +- `pid`: Process ID of the PTY +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`true` if the PTY was killed, `false` if the PTY was not found + + + +### send\_stdin + +```python +async def send_stdin(pid: int, + data: bytes, + request_timeout: Optional[float] = None) -> None +``` + +Send input to a PTY. + +**Arguments**: + +- `pid`: Process ID of the PTY +- `data`: Input data to send +- `request_timeout`: Timeout for the request in **seconds** + + + +### create + +```python +async def create( + size: PtySize, + on_data: OutputHandler[PtyOutput], + user: Optional[Username] = None, + cwd: Optional[str] = None, + envs: Optional[Dict[str, str]] = None, + timeout: Optional[float] = 60, + request_timeout: Optional[float] = None) -> AsyncCommandHandle +``` + +Start a new PTY (pseudo-terminal). + +**Arguments**: + +- `size`: Size of the PTY +- `on_data`: Callback to handle PTY data +- `user`: User to use for the PTY +- `cwd`: Working directory for the PTY +- `envs`: Environment variables for the PTY +- `timeout`: Timeout for the PTY in **seconds** +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +Handle to interact with the PTY + + + +### resize + +```python +async def resize(pid: int, + size: PtySize, + request_timeout: Optional[float] = None) +``` + +Resize PTY. + +Call this when the terminal window is resized and the number of columns and rows has changed. + +**Arguments**: + +- `pid`: Process ID of the PTY +- `size`: New size of the PTY +- `request_timeout`: Timeout for the request in **seconds** + + + + + + +## AsyncSandbox + +```python +class AsyncSandbox(SandboxApi) +``` + +E2B cloud sandbox is a secure and isolated cloud environment. + +The sandbox allows you to: +- Access Linux OS +- Create, list, and delete files and directories +- Run commands +- Run isolated code +- Access the internet + +Check docs [here](https://e2b.dev/docs). + +Use the `AsyncSandbox.create()` to create a new sandbox. + +**Example**: + +```python +from e2b import AsyncSandbox + +sandbox = await AsyncSandbox.create() +``` + + + +### files + +```python +@property +def files() -> Filesystem +``` + +Module for interacting with the sandbox filesystem. + + + +### commands + +```python +@property +def commands() -> Commands +``` + +Module for running commands in the sandbox. + + + +### pty + +```python +@property +def pty() -> Pty +``` + +Module for interacting with the sandbox pseudo-terminal. + + + +### \_\_init\_\_ + +```python +def __init__(**opts: Unpack[SandboxOpts]) +``` + +Use `AsyncSandbox.create()` to create a new sandbox instead. + + + +### is\_running + +```python +async def is_running(request_timeout: Optional[float] = None) -> bool +``` + +Check if the sandbox is running. + +**Arguments**: + +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`True` if the sandbox is running, `False` otherwise +Example +```python +sandbox = await AsyncSandbox.create() +await sandbox.is_running() # Returns True + +await sandbox.kill() +await sandbox.is_running() # Returns False +``` + + + +### create + +```python +@classmethod +async def create(cls, + template: Optional[str] = None, + timeout: Optional[int] = None, + metadata: Optional[Dict[str, str]] = None, + envs: Optional[Dict[str, str]] = None, + secure: bool = True, + allow_internet_access: bool = True, + mcp: Optional[McpServer] = None, + network: Optional[SandboxNetworkOpts] = None, + **opts: Unpack[ApiParams]) -> Self +``` + +Create a new sandbox. + +By default, the sandbox is created from the default `base` sandbox template. + +**Arguments**: + +- `template`: Sandbox template name or ID +- `timeout`: Timeout for the sandbox in **seconds**, default to 300 seconds. The maximum time a sandbox can be kept alive is 24 hours (86_400 seconds) for Pro users and 1 hour (3_600 seconds) for Hobby users. +- `metadata`: Custom metadata for the sandbox +- `envs`: Custom environment variables for the sandbox +- `secure`: Envd is secured with access token and cannot be used without it, defaults to `True`. +- `allow_internet_access`: Allow sandbox to access the internet, defaults to `True`. If set to `False`, it works the same as setting network `deny_out` to `[0.0.0.0/0]`. +- `mcp`: MCP server to enable in the sandbox +- `network`: Sandbox network configuration + +**Returns**: + +A Sandbox instance for the new sandbox +Use this method instead of using the constructor to create a new sandbox. + + + +### connect + +```python +@overload +async def connect(timeout: Optional[int] = None, + **opts: Unpack[ApiParams]) -> Self +``` + +Connect to a sandbox. If the sandbox is paused, it will be automatically resumed. + +Sandbox must be either running or be paused. + +With sandbox ID you can connect to the same sandbox from different places or environments (serverless functions, etc). + +**Arguments**: + +- `timeout`: Timeout for the sandbox in **seconds** +For running sandboxes, the timeout will update only if the new timeout is longer than the existing one. + +**Returns**: + +A running sandbox instance +@example +```python +sandbox = await AsyncSandbox.create() +await sandbox.beta_pause() + +same_sandbox = await sandbox.connect() +``` + + + +### connect + +```python +@overload +@classmethod +async def connect(cls, + sandbox_id: str, + timeout: Optional[int] = None, + **opts: Unpack[ApiParams]) -> Self +``` + +Connect to a sandbox. If the sandbox is paused, it will be automatically resumed. + +Sandbox must be either running or be paused. + +With sandbox ID you can connect to the same sandbox from different places or environments (serverless functions, etc). + +**Arguments**: + +- `sandbox_id`: Sandbox ID +- `timeout`: Timeout for the sandbox in **seconds** +For running sandboxes, the timeout will update only if the new timeout is longer than the existing one. + +**Returns**: + +A running sandbox instance +@example +```python +sandbox = await AsyncSandbox.create() +await AsyncSandbox.beta_pause(sandbox.sandbox_id) + +same_sandbox = await AsyncSandbox.connect(sandbox.sandbox_id)) +``` + + + +### connect + +```python +@class_method_variant("_cls_connect") +async def connect(timeout: Optional[int] = None, + **opts: Unpack[ApiParams]) -> Self +``` + +Connect to a sandbox. If the sandbox is paused, it will be automatically resumed. + +Sandbox must be either running or be paused. + +With sandbox ID you can connect to the same sandbox from different places or environments (serverless functions, etc). + +**Arguments**: + +- `timeout`: Timeout for the sandbox in **seconds** +For running sandboxes, the timeout will update only if the new timeout is longer than the existing one. + +**Returns**: + +A running sandbox instance +@example +```python +sandbox = await AsyncSandbox.create() +await sandbox.beta_pause() + +same_sandbox = await sandbox.connect() +``` + + + +### kill + +```python +@overload +async def kill(**opts: Unpack[ApiParams]) -> bool +``` + +Kill the sandbox. + +**Returns**: + +`True` if the sandbox was killed, `False` if the sandbox was not found + + + +### kill + +```python +@overload +@staticmethod +async def kill(sandbox_id: str, **opts: Unpack[ApiParams]) -> bool +``` + +Kill the sandbox specified by sandbox ID. + +**Arguments**: + +- `sandbox_id`: Sandbox ID + +**Returns**: + +`True` if the sandbox was killed, `False` if the sandbox was not found + + + +### kill + +```python +@class_method_variant("_cls_kill") +async def kill(**opts: Unpack[ApiParams]) -> bool +``` + +Kill the sandbox specified by sandbox ID. + +**Returns**: + +`True` if the sandbox was killed, `False` if the sandbox was not found + + + +### set\_timeout + +```python +@overload +async def set_timeout(timeout: int, **opts: Unpack[ApiParams]) -> None +``` + +Set the timeout of the sandbox. + +After the timeout expires, the sandbox will be automatically killed. +This method can extend or reduce the sandbox timeout set when creating the sandbox or from the last call to `.set_timeout`. + +The maximum time a sandbox can be kept alive is 24 hours (86_400 seconds) for Pro users and 1 hour (3_600 seconds) for Hobby users. + +**Arguments**: + +- `timeout`: Timeout for the sandbox in **seconds** + + + +### set\_timeout + +```python +@overload +@staticmethod +async def set_timeout(sandbox_id: str, timeout: int, + **opts: Unpack[ApiParams]) -> None +``` + +Set the timeout of the specified sandbox. + +After the timeout expires, the sandbox will be automatically killed. +This method can extend or reduce the sandbox timeout set when creating the sandbox or from the last call to `.set_timeout`. + +The maximum time a sandbox can be kept alive is 24 hours (86_400 seconds) for Pro users and 1 hour (3_600 seconds) for Hobby users. + +**Arguments**: + +- `sandbox_id`: Sandbox ID +- `timeout`: Timeout for the sandbox in **seconds** + + + +### set\_timeout + +```python +@class_method_variant("_cls_set_timeout") +async def set_timeout(timeout: int, **opts: Unpack[ApiParams]) -> None +``` + +Set the timeout of the specified sandbox. + +After the timeout expires, the sandbox will be automatically killed. +This method can extend or reduce the sandbox timeout set when creating the sandbox or from the last call to `.set_timeout`. + +The maximum time a sandbox can be kept alive is 24 hours (86_400 seconds) for Pro users and 1 hour (3_600 seconds) for Hobby users. + +**Arguments**: + +- `timeout`: Timeout for the sandbox in **seconds** + + + +### get\_info + +```python +@overload +async def get_info(**opts: Unpack[ApiParams]) -> SandboxInfo +``` + +Get sandbox information like sandbox ID, template, metadata, started at/end at date. + +**Returns**: + +Sandbox info + + + +### get\_info + +```python +@overload +@staticmethod +async def get_info(sandbox_id: str, **opts: Unpack[ApiParams]) -> SandboxInfo +``` + +Get sandbox information like sandbox ID, template, metadata, started at/end at date. + +**Arguments**: + +- `sandbox_id`: Sandbox ID + +**Returns**: + +Sandbox info + + + +### get\_info + +```python +@class_method_variant("_cls_get_info") +async def get_info(**opts: Unpack[ApiParams]) -> SandboxInfo +``` + +Get sandbox information like sandbox ID, template, metadata, started at/end at date. + +**Returns**: + +Sandbox info + + + +### get\_metrics + +```python +@overload +async def get_metrics(start: Optional[datetime.datetime] = None, + end: Optional[datetime.datetime] = None, + **opts: Unpack[ApiParams]) -> List[SandboxMetrics] +``` + +Get the metrics of the current sandbox. + +**Arguments**: + +- `start`: Start time for the metrics, defaults to the start of the sandbox +- `end`: End time for the metrics, defaults to the current time + +**Returns**: + +List of sandbox metrics containing CPU, memory and disk usage information + + + +### get\_metrics + +```python +@overload +@staticmethod +async def get_metrics(sandbox_id: str, + start: Optional[datetime.datetime] = None, + end: Optional[datetime.datetime] = None, + **opts: Unpack[ApiParams]) -> List[SandboxMetrics] +``` + +Get the metrics of the sandbox specified by sandbox ID. + +**Arguments**: + +- `sandbox_id`: Sandbox ID +- `start`: Start time for the metrics, defaults to the start of the sandbox +- `end`: End time for the metrics, defaults to the current time + +**Returns**: + +List of sandbox metrics containing CPU, memory and disk usage information + + + +### get\_metrics + +```python +@class_method_variant("_cls_get_metrics") +async def get_metrics(start: Optional[datetime.datetime] = None, + end: Optional[datetime.datetime] = None, + **opts: Unpack[ApiParams]) -> List[SandboxMetrics] +``` + +Get the metrics of the current sandbox. + +**Arguments**: + +- `start`: Start time for the metrics, defaults to the start of the sandbox +- `end`: End time for the metrics, defaults to the current time + +**Returns**: + +List of sandbox metrics containing CPU, memory and disk usage information + + + +### beta\_create + +```python +@classmethod +async def beta_create(cls, + template: Optional[str] = None, + timeout: Optional[int] = None, + auto_pause: bool = False, + metadata: Optional[Dict[str, str]] = None, + envs: Optional[Dict[str, str]] = None, + secure: bool = True, + allow_internet_access: bool = True, + mcp: Optional[McpServer] = None, + **opts: Unpack[ApiParams]) -> Self +``` + +[BETA] This feature is in beta and may change in the future. + +Create a new sandbox. + +By default, the sandbox is created from the default `base` sandbox template. + +**Arguments**: + +- `template`: Sandbox template name or ID +- `timeout`: Timeout for the sandbox in **seconds**, default to 300 seconds. The maximum time a sandbox can be kept alive is 24 hours (86_400 seconds) for Pro users and 1 hour (3_600 seconds) for Hobby users. +- `auto_pause`: Automatically pause the sandbox after the timeout expires. Defaults to `False`. +- `metadata`: Custom metadata for the sandbox +- `envs`: Custom environment variables for the sandbox +- `secure`: Envd is secured with access token and cannot be used without it, defaults to `True`. +- `allow_internet_access`: Allow sandbox to access the internet, defaults to `True`. +- `mcp`: MCP server to enable in the sandbox + +**Returns**: + +A Sandbox instance for the new sandbox +Use this method instead of using the constructor to create a new sandbox. + + + +### beta\_pause + +```python +@overload +async def beta_pause(**opts: Unpack[ApiParams]) -> None +``` + +[BETA] This feature is in beta and may change in the future. + +Pause the sandbox. + +**Returns**: + +Sandbox ID that can be used to resume the sandbox + + + +### beta\_pause + +```python +@overload +@staticmethod +async def beta_pause(sandbox_id: str, **opts: Unpack[ApiParams]) -> None +``` + +[BETA] This feature is in beta and may change in the future. + +Pause the sandbox specified by sandbox ID. + +**Arguments**: + +- `sandbox_id`: Sandbox ID + +**Returns**: + +Sandbox ID that can be used to resume the sandbox + + + +### beta\_pause + +```python +@class_method_variant("_cls_pause") +async def beta_pause(**opts: Unpack[ApiParams]) -> None +``` + +[BETA] This feature is in beta and may change in the future. + +Pause the sandbox. + +**Returns**: + +Sandbox ID that can be used to resume the sandbox + + + +### get\_mcp\_token + +```python +async def get_mcp_token() -> Optional[str] +``` + +Get the MCP token for the sandbox. + +**Returns**: + +MCP token for the sandbox, or None if MCP is not enabled. diff --git a/docs/sdk-reference/python-sdk/v2.8.1/sandbox_sync.mdx b/docs/sdk-reference/python-sdk/v2.8.1/sandbox_sync.mdx new file mode 100644 index 0000000..04927a8 --- /dev/null +++ b/docs/sdk-reference/python-sdk/v2.8.1/sandbox_sync.mdx @@ -0,0 +1,1343 @@ +--- +sidebarTitle: "Sandbox Sync" +mode: "center" +--- + + + + + + +## WatchHandle + +```python +class WatchHandle() +``` + +Handle for watching filesystem events. +It is used to get the latest events that have occurred in the watched directory. + +Use `.stop()` to stop watching the directory. + + + +### stop + +```python +def stop() +``` + +Stop watching the directory. +After you stop the watcher you won't be able to get the events anymore. + + + +### get\_new\_events + +```python +def get_new_events() -> List[FilesystemEvent] +``` + +Get the latest events that have occurred in the watched directory since the last call, or from the beginning of the watching, up until now. + +**Returns**: + +List of filesystem events + + + + + + +## Filesystem + +```python +class Filesystem() +``` + +Module for interacting with the filesystem in the sandbox. + + + +### read + +```python +@overload +def read(path: str, + format: Literal["text"] = "text", + user: Optional[Username] = None, + request_timeout: Optional[float] = None) -> str +``` + +Read file content as a `str`. + +**Arguments**: + +- `path`: Path to the file +- `user`: Run the operation as this user +- `format`: Format of the file content—`text` by default +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +File content as a `str` + + + +### read + +```python +@overload +def read(path: str, + format: Literal["bytes"], + user: Optional[Username] = None, + request_timeout: Optional[float] = None) -> bytearray +``` + +Read file content as a `bytearray`. + +**Arguments**: + +- `path`: Path to the file +- `user`: Run the operation as this user +- `format`: Format of the file content—`bytes` +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +File content as a `bytearray` + + + +### read + +```python +@overload +def read(path: str, + format: Literal["stream"], + user: Optional[Username] = None, + request_timeout: Optional[float] = None) -> Iterator[bytes] +``` + +Read file content as a `Iterator[bytes]`. + +**Arguments**: + +- `path`: Path to the file +- `user`: Run the operation as this user +- `format`: Format of the file content—`stream` +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +File content as an `Iterator[bytes]` + + + +### write + +```python +def write(path: str, + data: Union[str, bytes, IO], + user: Optional[Username] = None, + request_timeout: Optional[float] = None) -> WriteInfo +``` + +Write content to a file on the path. + +Writing to a file that doesn't exist creates the file. +Writing to a file that already exists overwrites the file. +Writing to a file at path that doesn't exist creates the necessary directories. + +**Arguments**: + +- `path`: Path to the file +- `data`: Data to write to the file, can be a `str`, `bytes`, or `IO`. +- `user`: Run the operation as this user +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +Information about the written file + + + +### write\_files + +```python +def write_files(files: List[WriteEntry], + user: Optional[Username] = None, + request_timeout: Optional[float] = None) -> List[WriteInfo] +``` + +Writes a list of files to the filesystem. + +When writing to a file that doesn't exist, the file will get created. +When writing to a file that already exists, the file will get overwritten. +When writing to a file that's in a directory that doesn't exist, you'll get an error. + +**Arguments**: + +- `files`: list of files to write as `WriteEntry` objects, each containing `path` and `data` +- `user`: Run the operation as this user +- `request_timeout`: Timeout for the request + +**Returns**: + +Information about the written files + + + +### list + +```python +def list(path: str, + depth: Optional[int] = 1, + user: Optional[Username] = None, + request_timeout: Optional[float] = None) -> List[EntryInfo] +``` + +List entries in a directory. + +**Arguments**: + +- `path`: Path to the directory +- `depth`: Depth of the directory to list +- `user`: Run the operation as this user +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +List of entries in the directory + + + +### exists + +```python +def exists(path: str, + user: Optional[Username] = None, + request_timeout: Optional[float] = None) -> bool +``` + +Check if a file or a directory exists. + +**Arguments**: + +- `path`: Path to a file or a directory +- `user`: Run the operation as this user +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`True` if the file or directory exists, `False` otherwise + + + +### get\_info + +```python +def get_info(path: str, + user: Optional[Username] = None, + request_timeout: Optional[float] = None) -> EntryInfo +``` + +Get information about a file or directory. + +**Arguments**: + +- `path`: Path to a file or a directory +- `user`: Run the operation as this user +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +Information about the file or directory like name, type, and path + + + +### remove + +```python +def remove(path: str, + user: Optional[Username] = None, + request_timeout: Optional[float] = None) -> None +``` + +Remove a file or a directory. + +**Arguments**: + +- `path`: Path to a file or a directory +- `user`: Run the operation as this user +- `request_timeout`: Timeout for the request in **seconds** + + + +### rename + +```python +def rename(old_path: str, + new_path: str, + user: Optional[Username] = None, + request_timeout: Optional[float] = None) -> EntryInfo +``` + +Rename a file or directory. + +**Arguments**: + +- `old_path`: Path to the file or directory to rename +- `new_path`: New path to the file or directory +- `user`: Run the operation as this user +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +Information about the renamed file or directory + + + +### make\_dir + +```python +def make_dir(path: str, + user: Optional[Username] = None, + request_timeout: Optional[float] = None) -> bool +``` + +Create a new directory and all directories along the way if needed on the specified path. + +**Arguments**: + +- `path`: Path to a new directory. For example '/dirA/dirB' when creating 'dirB'. +- `user`: Run the operation as this user +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`True` if the directory was created, `False` if the directory already exists + + + +### watch\_dir + +```python +def watch_dir(path: str, + user: Optional[Username] = None, + request_timeout: Optional[float] = None, + recursive: bool = False) -> WatchHandle +``` + +Watch directory for filesystem events. + +**Arguments**: + +- `path`: Path to a directory to watch +- `user`: Run the operation as this user +- `request_timeout`: Timeout for the request in **seconds** +- `recursive`: Watch directory recursively + +**Returns**: + +`WatchHandle` object for stopping watching directory + + + + + + +## SandboxPaginator + +```python +class SandboxPaginator(SandboxPaginatorBase) +``` + +Paginator for listing sandboxes. + +**Example**: + +```python +paginator = Sandbox.list() + +while paginator.has_next: + sandboxes = paginator.next_items() + print(sandboxes) +``` + + + +### next\_items + +```python +def next_items() -> List[SandboxInfo] +``` + +Returns the next page of sandboxes. + +Call this method only if `has_next` is `True`, otherwise it will raise an exception. + +**Returns**: + +List of sandboxes + + + + + + +## SandboxApi + +```python +class SandboxApi(SandboxBase) +``` + + + +### list + +```python +@staticmethod +def list(query: Optional[SandboxQuery] = None, + limit: Optional[int] = None, + next_token: Optional[str] = None, + **opts: Unpack[ApiParams]) -> SandboxPaginator +``` + +List all running sandboxes. + +**Arguments**: + +- `query`: Filter the list of sandboxes by metadata or state, e.g. `SandboxListQuery(metadata={"key": "value"})` or `SandboxListQuery(state=[SandboxState.RUNNING])` +- `limit`: Maximum number of sandboxes to return per page +- `next_token`: Token for pagination + +**Returns**: + +List of running sandboxes + + + + + + +## Commands + +```python +class Commands() +``` + +Module for executing commands in the sandbox. + + + +### list + +```python +def list(request_timeout: Optional[float] = None) -> List[ProcessInfo] +``` + +Lists all running commands and PTY sessions. + +**Arguments**: + +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +List of running commands and PTY sessions + + + +### kill + +```python +def kill(pid: int, request_timeout: Optional[float] = None) -> bool +``` + +Kills a running command specified by its process ID. + +It uses `SIGKILL` signal to kill the command. + +**Arguments**: + +- `pid`: Process ID of the command. You can get the list of processes using `sandbox.commands.list()` +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`True` if the command was killed, `False` if the command was not found + + + +### send\_stdin + +```python +def send_stdin(pid: int, data: str, request_timeout: Optional[float] = None) +``` + +Send data to command stdin. + +:param pid Process ID of the command. You can get the list of processes using `sandbox.commands.list()`. +:param data: Data to send to the command +:param request_timeout: Timeout for the request in **seconds** + + + + +### run + +```python +@overload +def run(cmd: str, + background: Union[Literal[False], None] = None, + envs: Optional[Dict[str, str]] = None, + user: Optional[Username] = None, + cwd: Optional[str] = None, + on_stdout: Optional[Callable[[str], None]] = None, + on_stderr: Optional[Callable[[str], None]] = None, + stdin: Optional[bool] = None, + timeout: Optional[float] = 60, + request_timeout: Optional[float] = None) -> CommandResult +``` + +Start a new command and wait until it finishes executing. + +**Arguments**: + +- `cmd`: Command to execute +- `background`: **`False` if the command should be executed in the foreground**, `True` if the command should be executed in the background +- `envs`: Environment variables used for the command +- `user`: User to run the command as +- `cwd`: Working directory to run the command +- `on_stdout`: Callback for command stdout output +- `on_stderr`: Callback for command stderr output +- `stdin`: If `True`, the command will have a stdin stream that you can send data to using `sandbox.commands.send_stdin()` +- `timeout`: Timeout for the command connection in **seconds**. Using `0` will not limit the command connection time +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`CommandResult` result of the command execution + + + +### run + +```python +@overload +def run(cmd: str, + background: Literal[True], + envs: Optional[Dict[str, str]] = None, + user: Optional[Username] = None, + cwd: Optional[str] = None, + on_stdout: None = None, + on_stderr: None = None, + stdin: Optional[bool] = None, + timeout: Optional[float] = 60, + request_timeout: Optional[float] = None) -> CommandHandle +``` + +Start a new command and return a handle to interact with it. + +**Arguments**: + +- `cmd`: Command to execute +- `background`: `False` if the command should be executed in the foreground, **`True` if the command should be executed in the background** +- `envs`: Environment variables used for the command +- `user`: User to run the command as +- `cwd`: Working directory to run the command +- `stdin`: If `True`, the command will have a stdin stream that you can send data to using `sandbox.commands.send_stdin()` +- `timeout`: Timeout for the command connection in **seconds**. Using `0` will not limit the command connection time +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`CommandHandle` handle to interact with the running command + + + +### connect + +```python +def connect(pid: int, + timeout: Optional[float] = 60, + request_timeout: Optional[float] = None) +``` + +Connects to a running command. + +You can use `CommandHandle.wait()` to wait for the command to finish and get execution results. + +**Arguments**: + +- `pid`: Process ID of the command to connect to. You can get the list of processes using `sandbox.commands.list()` +- `timeout`: Timeout for the connection in **seconds**. Using `0` will not limit the connection time +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`CommandHandle` handle to interact with the running command + + + + + + +## CommandHandle + +```python +class CommandHandle() +``` + +Command execution handle. + +It provides methods for waiting for the command to finish, retrieving stdout/stderr, and killing the command. + + + +### pid + +```python +@property +def pid() +``` + +Command process ID. + + + +### \_\_iter\_\_ + +```python +def __iter__() +``` + +Iterate over the command output. + +**Returns**: + +Generator of command outputs + + + +### disconnect + +```python +def disconnect() -> None +``` + +Disconnect from the command. + +The command is not killed, but SDK stops receiving events from the command. +You can reconnect to the command using `sandbox.commands.connect` method. + + + +### wait + +```python +def wait(on_pty: Optional[Callable[[PtyOutput], None]] = None, + on_stdout: Optional[Callable[[str], None]] = None, + on_stderr: Optional[Callable[[str], None]] = None) -> CommandResult +``` + +Wait for the command to finish and returns the result. + +If the command exits with a non-zero exit code, it throws a `CommandExitException`. + +**Arguments**: + +- `on_pty`: Callback for pty output +- `on_stdout`: Callback for stdout output +- `on_stderr`: Callback for stderr output + +**Returns**: + +`CommandResult` result of command execution + + + +### kill + +```python +def kill() -> bool +``` + +Kills the command. + +It uses `SIGKILL` signal to kill the command. + +**Returns**: + +Whether the command was killed successfully + + + + + + +## Pty + +```python +class Pty() +``` + +Module for interacting with PTYs (pseudo-terminals) in the sandbox. + + + +### kill + +```python +def kill(pid: int, request_timeout: Optional[float] = None) -> bool +``` + +Kill PTY. + +**Arguments**: + +- `pid`: Process ID of the PTY +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`true` if the PTY was killed, `false` if the PTY was not found + + + +### send\_stdin + +```python +def send_stdin(pid: int, + data: bytes, + request_timeout: Optional[float] = None) -> None +``` + +Send input to a PTY. + +**Arguments**: + +- `pid`: Process ID of the PTY +- `data`: Input data to send +- `request_timeout`: Timeout for the request in **seconds** + + + +### create + +```python +def create(size: PtySize, + user: Optional[Username] = None, + cwd: Optional[str] = None, + envs: Optional[Dict[str, str]] = None, + timeout: Optional[float] = 60, + request_timeout: Optional[float] = None) -> CommandHandle +``` + +Start a new PTY (pseudo-terminal). + +**Arguments**: + +- `size`: Size of the PTY +- `user`: User to use for the PTY +- `cwd`: Working directory for the PTY +- `envs`: Environment variables for the PTY +- `timeout`: Timeout for the PTY in **seconds** +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +Handle to interact with the PTY + + + +### resize + +```python +def resize(pid: int, + size: PtySize, + request_timeout: Optional[float] = None) -> None +``` + +Resize PTY. + +Call this when the terminal window is resized and the number of columns and rows has changed. + +**Arguments**: + +- `pid`: Process ID of the PTY +- `size`: New size of the PTY +- `request_timeout`: Timeout for the request in **seconds**s + + + + + + +## Sandbox + +```python +class Sandbox(SandboxApi) +``` + +E2B cloud sandbox is a secure and isolated cloud environment. + +The sandbox allows you to: +- Access Linux OS +- Create, list, and delete files and directories +- Run commands +- Run isolated code +- Access the internet + +Check docs [here](https://e2b.dev/docs). + +Use the `Sandbox.create()` to create a new sandbox. + +**Example**: + +```python +from e2b import Sandbox + +sandbox = Sandbox.create() +``` + + + +### files + +```python +@property +def files() -> Filesystem +``` + +Module for interacting with the sandbox filesystem. + + + +### commands + +```python +@property +def commands() -> Commands +``` + +Module for running commands in the sandbox. + + + +### pty + +```python +@property +def pty() -> Pty +``` + +Module for interacting with the sandbox pseudo-terminal. + + + +### \_\_init\_\_ + +```python +def __init__(**opts: Unpack[SandboxOpts]) +``` + +:deprecated: This constructor is deprecated + +Use `Sandbox.create()` to create a new sandbox instead. + + + +### is\_running + +```python +def is_running(request_timeout: Optional[float] = None) -> bool +``` + +Check if the sandbox is running. + +**Arguments**: + +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`True` if the sandbox is running, `False` otherwise +Example +```python +sandbox = Sandbox.create() +sandbox.is_running() # Returns True + +sandbox.kill() +sandbox.is_running() # Returns False +``` + + + +### create + +```python +@classmethod +def create(cls, + template: Optional[str] = None, + timeout: Optional[int] = None, + metadata: Optional[Dict[str, str]] = None, + envs: Optional[Dict[str, str]] = None, + secure: bool = True, + allow_internet_access: bool = True, + mcp: Optional[McpServer] = None, + network: Optional[SandboxNetworkOpts] = None, + **opts: Unpack[ApiParams]) -> Self +``` + +Create a new sandbox. + +By default, the sandbox is created from the default `base` sandbox template. + +**Arguments**: + +- `template`: Sandbox template name or ID +- `timeout`: Timeout for the sandbox in **seconds**, default to 300 seconds. The maximum time a sandbox can be kept alive is 24 hours (86_400 seconds) for Pro users and 1 hour (3_600 seconds) for Hobby users. +- `metadata`: Custom metadata for the sandbox +- `envs`: Custom environment variables for the sandbox +- `secure`: Envd is secured with access token and cannot be used without it, defaults to `True`. +- `allow_internet_access`: Allow sandbox to access the internet, defaults to `True`. If set to `False`, it works the same as setting network `deny_out` to `[0.0.0.0/0]`. +- `mcp`: MCP server to enable in the sandbox +- `network`: Sandbox network configuration + +**Returns**: + +A Sandbox instance for the new sandbox +Use this method instead of using the constructor to create a new sandbox. + + + +### connect + +```python +@overload +def connect(timeout: Optional[int] = None, **opts: Unpack[ApiParams]) -> Self +``` + +Connect to a sandbox. If the sandbox is paused, it will be automatically resumed. + +Sandbox must be either running or be paused. + +With sandbox ID you can connect to the same sandbox from different places or environments (serverless functions, etc). + +**Arguments**: + +- `timeout`: Timeout for the sandbox in **seconds** +For running sandboxes, the timeout will update only if the new timeout is longer than the existing one. + +**Returns**: + +A running sandbox instance +@example +```python +sandbox = Sandbox.create() +sandbox.beta_pause() + +same_sandbox = sandbox.connect() + + + +### connect + +```python +@overload +@classmethod +def connect(cls, + sandbox_id: str, + timeout: Optional[int] = None, + **opts: Unpack[ApiParams]) -> Self +``` + +Connect to a sandbox. If the sandbox is paused, it will be automatically resumed. + +Sandbox must be either running or be paused. + +With sandbox ID you can connect to the same sandbox from different places or environments (serverless functions, etc). + +**Arguments**: + +- `sandbox_id`: Sandbox ID +- `timeout`: Timeout for the sandbox in **seconds**. +For running sandboxes, the timeout will update only if the new timeout is longer than the existing one. + +**Returns**: + +A running sandbox instance +@example +```python +sandbox = Sandbox.create() +Sandbox.beta_pause(sandbox.sandbox_id) + +same_sandbox = Sandbox.connect(sandbox.sandbox_id) +``` + + + +### connect + +```python +@class_method_variant("_cls_connect") +def connect(timeout: Optional[int] = None, **opts: Unpack[ApiParams]) -> Self +``` + +Connect to a sandbox. If the sandbox is paused, it will be automatically resumed. + +Sandbox must be either running or be paused. + +With sandbox ID you can connect to the same sandbox from different places or environments (serverless functions, etc). + +**Arguments**: + +- `timeout`: Timeout for the sandbox in **seconds**. +For running sandboxes, the timeout will update only if the new timeout is longer than the existing one. + +**Returns**: + +A running sandbox instance +@example +```python +sandbox = Sandbox.create() +sandbox.beta_pause() + +same_sandbox = sandbox.connect() +``` + + + +### kill + +```python +@overload +def kill(**opts: Unpack[ApiParams]) -> bool +``` + +Kill the sandbox. + +**Returns**: + +`True` if the sandbox was killed, `False` if the sandbox was not found + + + +### kill + +```python +@overload +@staticmethod +def kill(sandbox_id: str, **opts: Unpack[ApiParams]) -> bool +``` + +Kill the sandbox specified by sandbox ID. + +**Arguments**: + +- `sandbox_id`: Sandbox ID + +**Returns**: + +`True` if the sandbox was killed, `False` if the sandbox was not found + + + +### kill + +```python +@class_method_variant("_cls_kill") +def kill(**opts: Unpack[ApiParams]) -> bool +``` + +Kill the sandbox specified by sandbox ID. + +**Returns**: + +`True` if the sandbox was killed, `False` if the sandbox was not found + + + +### set\_timeout + +```python +@overload +def set_timeout(timeout: int, **opts: Unpack[ApiParams]) -> None +``` + +Set the timeout of the sandbox. + +After the timeout expires, the sandbox will be automatically killed. +This method can extend or reduce the sandbox timeout set when creating the sandbox or from the last call to `.set_timeout`. + +The maximum time a sandbox can be kept alive is 24 hours (86_400 seconds) for Pro users and 1 hour (3_600 seconds) for Hobby users. + +**Arguments**: + +- `timeout`: Timeout for the sandbox in **seconds** + + + +### set\_timeout + +```python +@overload +@staticmethod +def set_timeout(sandbox_id: str, timeout: int, + **opts: Unpack[ApiParams]) -> None +``` + +Set the timeout of the sandbox specified by sandbox ID. + +After the timeout expires, the sandbox will be automatically killed. +This method can extend or reduce the sandbox timeout set when creating the sandbox or from the last call to `.set_timeout`. + +The maximum time a sandbox can be kept alive is 24 hours (86_400 seconds) for Pro users and 1 hour (3_600 seconds) for Hobby users. + +**Arguments**: + +- `sandbox_id`: Sandbox ID +- `timeout`: Timeout for the sandbox in **seconds** + + + +### set\_timeout + +```python +@class_method_variant("_cls_set_timeout") +def set_timeout(timeout: int, **opts: Unpack[ApiParams]) -> None +``` + +Set the timeout of the sandbox. + +After the timeout expires, the sandbox will be automatically killed. +This method can extend or reduce the sandbox timeout set when creating the sandbox or from the last call to `.set_timeout`. + +The maximum time a sandbox can be kept alive is 24 hours (86_400 seconds) for Pro users and 1 hour (3_600 seconds) for Hobby users. + +**Arguments**: + +- `timeout`: Timeout for the sandbox in **seconds** + + + +### get\_info + +```python +@overload +def get_info(**opts: Unpack[ApiParams]) -> SandboxInfo +``` + +Get sandbox information like sandbox ID, template, metadata, started at/end at date. + +**Returns**: + +Sandbox info + + + +### get\_info + +```python +@overload +@staticmethod +def get_info(sandbox_id: str, **opts: Unpack[ApiParams]) -> SandboxInfo +``` + +Get sandbox information like sandbox ID, template, metadata, started at/end at date. + +**Arguments**: + +- `sandbox_id`: Sandbox ID + +**Returns**: + +Sandbox info + + + +### get\_info + +```python +@class_method_variant("_cls_get_info") +def get_info(**opts: Unpack[ApiParams]) -> SandboxInfo +``` + +Get sandbox information like sandbox ID, template, metadata, started at/end at date. + +**Returns**: + +Sandbox info + + + +### get\_metrics + +```python +@overload +def get_metrics(start: Optional[datetime.datetime] = None, + end: Optional[datetime.datetime] = None, + **opts: Unpack[ApiParams]) -> List[SandboxMetrics] +``` + +Get the metrics of the current sandbox. + +**Arguments**: + +- `start`: Start time for the metrics, defaults to the start of the sandbox +- `end`: End time for the metrics, defaults to the current time + +**Returns**: + +List of sandbox metrics containing CPU, memory and disk usage information + + + +### get\_metrics + +```python +@overload +@staticmethod +def get_metrics(sandbox_id: str, + start: Optional[datetime.datetime] = None, + end: Optional[datetime.datetime] = None, + **opts: Unpack[ApiParams]) -> List[SandboxMetrics] +``` + +Get the metrics of the sandbox specified by sandbox ID. + +**Arguments**: + +- `sandbox_id`: Sandbox ID +- `start`: Start time for the metrics, defaults to the start of the sandbox +- `end`: End time for the metrics, defaults to the current time + +**Returns**: + +List of sandbox metrics containing CPU, memory and disk usage information + + + +### get\_metrics + +```python +@class_method_variant("_cls_get_metrics") +def get_metrics(start: Optional[datetime.datetime] = None, + end: Optional[datetime.datetime] = None, + **opts: Unpack[ApiParams]) -> List[SandboxMetrics] +``` + +Get the metrics of the sandbox specified by sandbox ID. + +**Arguments**: + +- `start`: Start time for the metrics, defaults to the start of the sandbox +- `end`: End time for the metrics, defaults to the current time + +**Returns**: + +List of sandbox metrics containing CPU, memory and disk usage information + + + +### beta\_create + +```python +@classmethod +def beta_create(cls, + template: Optional[str] = None, + timeout: Optional[int] = None, + auto_pause: bool = False, + metadata: Optional[Dict[str, str]] = None, + envs: Optional[Dict[str, str]] = None, + secure: bool = True, + allow_internet_access: bool = True, + mcp: Optional[McpServer] = None, + **opts: Unpack[ApiParams]) -> Self +``` + +[BETA] This feature is in beta and may change in the future. + +Create a new sandbox. + +By default, the sandbox is created from the default `base` sandbox template. + +**Arguments**: + +- `template`: Sandbox template name or ID +- `timeout`: Timeout for the sandbox in **seconds**, default to 300 seconds. The maximum time a sandbox can be kept alive is 24 hours (86_400 seconds) for Pro users and 1 hour (3_600 seconds) for Hobby users. +- `auto_pause`: Automatically pause the sandbox after the timeout expires. Defaults to `False`. +- `metadata`: Custom metadata for the sandbox +- `envs`: Custom environment variables for the sandbox +- `secure`: Envd is secured with access token and cannot be used without it, defaults to `True`. +- `allow_internet_access`: Allow sandbox to access the internet, defaults to `True`. +- `mcp`: MCP server to enable in the sandbox + +**Returns**: + +A Sandbox instance for the new sandbox +Use this method instead of using the constructor to create a new sandbox. + + + +### beta\_pause + +```python +@overload +def beta_pause(**opts: Unpack[ApiParams]) -> None +``` + +[BETA] This feature is in beta and may change in the future. + +Pause the sandbox. + + + +### beta\_pause + +```python +@overload +@classmethod +def beta_pause(cls, sandbox_id: str, **opts: Unpack[ApiParams]) -> None +``` + +[BETA] This feature is in beta and may change in the future. + +Pause the sandbox specified by sandbox ID. + +**Arguments**: + +- `sandbox_id`: Sandbox ID + + + +### beta\_pause + +```python +@class_method_variant("_cls_pause") +def beta_pause(**opts: Unpack[ApiParams]) -> None +``` + +[BETA] This feature is in beta and may change in the future. + +Pause the sandbox. + +**Returns**: + +Sandbox ID that can be used to resume the sandbox + + + +### get\_mcp\_token + +```python +def get_mcp_token() -> Optional[str] +``` + +Get the MCP token for the sandbox. + +**Returns**: + +MCP token for the sandbox, or None if MCP is not enabled. diff --git a/docs/sdk-reference/python-sdk/v2.8.1/template.mdx b/docs/sdk-reference/python-sdk/v2.8.1/template.mdx new file mode 100644 index 0000000..e93bb10 --- /dev/null +++ b/docs/sdk-reference/python-sdk/v2.8.1/template.mdx @@ -0,0 +1,1704 @@ +--- +sidebarTitle: "Template" +mode: "center" +--- + + + + + + +## DockerfFileFinalParserInterface + +```python +class DockerfFileFinalParserInterface(Protocol) +``` + +Protocol defining the final interface for Dockerfile parsing callbacks. + + + +## DockerfileParserInterface + +```python +class DockerfileParserInterface(Protocol) +``` + +Protocol defining the interface for Dockerfile parsing callbacks. + + + +### run\_cmd + +```python +def run_cmd(command: Union[str, List[str]], + user: Optional[str] = None) -> "DockerfileParserInterface" +``` + +Handle RUN instruction. + + + +### copy + +```python +def copy(src: Union[str, List[CopyItem]], + dest: Optional[str] = None, + force_upload: Optional[Literal[True]] = None, + resolve_symlinks: Optional[bool] = None, + user: Optional[str] = None, + mode: Optional[int] = None) -> "DockerfileParserInterface" +``` + +Handle COPY instruction. + + + +### set\_workdir + +```python +def set_workdir(workdir: str) -> "DockerfileParserInterface" +``` + +Handle WORKDIR instruction. + + + +### set\_user + +```python +def set_user(user: str) -> "DockerfileParserInterface" +``` + +Handle USER instruction. + + + +### set\_envs + +```python +def set_envs(envs: Dict[str, str]) -> "DockerfileParserInterface" +``` + +Handle ENV instruction. + + + +### set\_start\_cmd + +```python +def set_start_cmd(start_cmd: str, + ready_cmd: str) -> "DockerfFileFinalParserInterface" +``` + +Handle CMD/ENTRYPOINT instruction. + + + +### parse\_dockerfile + +```python +def parse_dockerfile(dockerfile_content_or_path: str, + template_builder: DockerfileParserInterface) -> str +``` + +Parse a Dockerfile and convert it to Template SDK format. + +**Arguments**: + +- `dockerfile_content_or_path`: Either the Dockerfile content as a string, or a path to a Dockerfile file +- `template_builder`: Interface providing template builder methods + +**Raises**: + +- `ValueError`: If the Dockerfile is invalid or unsupported + +**Returns**: + +The base image from the Dockerfile + + + + + + +## InstructionType + +```python +class InstructionType(str, Enum) +``` + +Types of instructions that can be used in a template. + + + +## CopyItem + +```python +class CopyItem(TypedDict) +``` + +Configuration for a single file/directory copy operation. + + + +## Instruction + +```python +class Instruction(TypedDict) +``` + +Represents a single instruction in the template build process. + + + +## GenericDockerRegistry + +```python +class GenericDockerRegistry(TypedDict) +``` + +Configuration for a generic Docker registry with basic authentication. + + + +## AWSRegistry + +```python +class AWSRegistry(TypedDict) +``` + +Configuration for AWS Elastic Container Registry (ECR). + + + +## GCPRegistry + +```python +class GCPRegistry(TypedDict) +``` + +Configuration for Google Container Registry (GCR) or Artifact Registry. + + + +## TemplateType + +```python +class TemplateType(TypedDict) +``` + +Internal representation of a template for the E2B build API. + + + +## BuildInfo + +```python +@dataclass +class BuildInfo() +``` + +Information about a built template. + + + + + + +## LogEntry + +```python +@dataclass +class LogEntry() +``` + +Represents a single log entry from the template build process. + + + +## LogEntryStart + +```python +@dataclass +class LogEntryStart(LogEntry) +``` + +Special log entry indicating the start of a build process. + + + +## LogEntryEnd + +```python +@dataclass +class LogEntryEnd(LogEntry) +``` + +Special log entry indicating the end of a build process. + + + +### TIMER\_UPDATE\_INTERVAL\_MS + +Default minimum log level to display. + + + +### DEFAULT\_LEVEL + +Colored labels for each log level. + + + +### levels + +Numeric ordering of log levels for comparison (lower = less severe). + + + +### set\_interval + +```python +def set_interval(func, interval) +``` + +Returns a stop function that can be called to cancel the interval. + +Similar to JavaScript's setInterval. + +**Arguments**: + +- `func`: Function to execute at each interval +- `interval`: Interval duration in **seconds** + +**Returns**: + +Stop function that can be called to cancel the interval + + + +### default\_build\_logger + +```python +def default_build_logger( + min_level: Optional[LogEntryLevel] = None +) -> Callable[[LogEntry], None] +``` + +Create a default build logger with animated timer display. + +**Arguments**: + +- `min_level`: Minimum log level to display (default: 'info') + +**Returns**: + +Logger function that accepts LogEntry instances +Example +```python +from e2b import Template, default_build_logger + +template = Template().from_python_image() + +``` + + + + +Special step name for the finalization phase of template building. +This is the last step that runs after all user-defined instructions. + + + +### FINALIZE\_STEP\_NAME + +Special step name for the base image phase of template building. +This is the first step that sets up the base image. + + + +### BASE\_STEP\_NAME + +Stack trace depth for capturing caller information. + +Depth levels: +1. TemplateClass +2. Caller method (e.g., copy(), from_image(), etc.) + +This depth is used to determine the original caller's location +for stack traces. + + + +### STACK\_TRACE\_DEPTH + +Default setting for whether to resolve symbolic links when copying files. +When False, symlinks are copied as symlinks rather than following them. + + + + + + +## ReadyCmd + +```python +class ReadyCmd() +``` + +Wrapper class for ready check commands. + + + +### wait\_for\_port + +```python +def wait_for_port(port: int) +``` + +Wait for a port to be listening. + +Uses `ss` command to check if a port is open and listening. + +**Arguments**: + +- `port`: Port number to wait for + +**Returns**: + +ReadyCmd that checks for the port +Example +```python +from e2b import Template, wait_for_port + +template = ( + Template() + .from_python_image() + .set_start_cmd('python -m http.server 8000', wait_for_port(8000)) +) +``` + + + +### wait\_for\_url + +```python +def wait_for_url(url: str, status_code: int = 200) +``` + +Wait for a URL to return a specific HTTP status code. + +Uses `curl` to make HTTP requests and check the response status. + +**Arguments**: + +- `url`: URL to check (e.g., 'http://localhost:3000/health') +- `status_code`: Expected HTTP status code (default: 200) + +**Returns**: + +ReadyCmd that checks the URL +Example +```python +from e2b import Template, wait_for_url + +template = ( + Template() + .from_node_image() + .set_start_cmd('npm start', wait_for_url('http://localhost:3000/health')) +) +``` + + + +### wait\_for\_process + +```python +def wait_for_process(process_name: str) +``` + +Wait for a process with a specific name to be running. + +Uses `pgrep` to check if a process exists. + +**Arguments**: + +- `process_name`: Name of the process to wait for + +**Returns**: + +ReadyCmd that checks for the process +Example +```python +from e2b import Template, wait_for_process + +template = ( + Template() + .from_base_image() + .set_start_cmd('./my-daemon', wait_for_process('my-daemon')) +) +``` + + + +### wait\_for\_file + +```python +def wait_for_file(filename: str) +``` + +Wait for a file to exist. + +Uses shell test command to check file existence. + +**Arguments**: + +- `filename`: Path to the file to wait for + +**Returns**: + +ReadyCmd that checks for the file +Example +```python +from e2b import Template, wait_for_file + +template = ( + Template() + .from_base_image() + .set_start_cmd('./init.sh', wait_for_file('/tmp/ready')) +) +``` + + + +### wait\_for\_timeout + +```python +def wait_for_timeout(timeout: int) +``` + +Wait for a specified timeout before considering the sandbox ready. + +Uses `sleep` command to wait for a fixed duration. + +**Arguments**: + +- `timeout`: Time to wait in **milliseconds** (minimum: 1000ms / 1 second) + +**Returns**: + +ReadyCmd that waits for the specified duration +Example +```python +from e2b import Template, wait_for_timeout + +template = ( + Template() + .from_node_image() + .set_start_cmd('npm start', wait_for_timeout(5000)) # Wait 5 seconds +) +``` + + + + + + +### read\_dockerignore + +```python +def read_dockerignore(context_path: str) -> List[str] +``` + +Read and parse a .dockerignore file. + +**Arguments**: + +- `context_path`: Directory path containing the .dockerignore file + +**Returns**: + +Array of ignore patterns (empty lines and comments are filtered out) + + + +### normalize\_path + +```python +def normalize_path(path: str) -> str +``` + +Normalize path separators to forward slashes for glob patterns (glob expects / even on Windows). + +**Arguments**: + +- `path`: The path to normalize + +**Returns**: + +The normalized path + + + +### get\_all\_files\_in\_path + +```python +def get_all_files_in_path(src: str, + context_path: str, + ignore_patterns: List[str], + include_directories: bool = True) -> List[str] +``` + +Get all files for a given path and ignore patterns. + +**Arguments**: + +- `src`: Path to the source directory +- `context_path`: Base directory for resolving relative paths +- `ignore_patterns`: Ignore patterns +- `include_directories`: Whether to include directories + +**Returns**: + +Array of files + + + +### calculate\_files\_hash + +```python +def calculate_files_hash(src: str, dest: str, context_path: str, + ignore_patterns: List[str], resolve_symlinks: bool, + stack_trace: Optional[TracebackType]) -> str +``` + +Calculate a hash of files being copied to detect changes for cache invalidation. + +The hash includes file content, metadata (mode, size), and relative paths. +Note: uid, gid, and mtime are excluded to ensure stable hashes across environments. + +**Arguments**: + +- `src`: Source path pattern for files to copy +- `dest`: Destination path where files will be copied +- `context_path`: Base directory for resolving relative paths +- `ignore_patterns`: Glob patterns to ignore +- `resolve_symlinks`: Whether to resolve symbolic links when hashing +- `stack_trace`: Optional stack trace for error reporting + +**Raises**: + +- `ValueError`: If no files match the source pattern + +**Returns**: + +Hex string hash of all files + + + +### tar\_file\_stream + +```python +def tar_file_stream(file_name: str, file_context_path: str, + ignore_patterns: List[str], + resolve_symlinks: bool) -> io.BytesIO +``` + +Create a tar stream of files matching a pattern. + +**Arguments**: + +- `file_name`: Glob pattern for files to include +- `file_context_path`: Base directory for resolving file paths +- `ignore_patterns`: Ignore patterns +- `resolve_symlinks`: Whether to resolve symbolic links + +**Returns**: + +Tar stream + + + +### strip\_ansi\_escape\_codes + +```python +def strip_ansi_escape_codes(text: str) -> str +``` + +Strip ANSI escape codes from a string. + +Source: https://github.com/chalk/ansi-regex/blob/main/index.js + +**Arguments**: + +- `text`: String with ANSI escape codes + +**Returns**: + +String without ANSI escape codes + + + +### get\_caller\_frame + +```python +def get_caller_frame(depth: int) -> Optional[FrameType] +``` + +Get the caller's stack frame at a specific depth. + +This is used to provide better error messages and debugging information +by tracking where template methods were called from in user code. + +**Arguments**: + +- `depth`: The depth of the stack trace to retrieve + +**Returns**: + +The caller frame, or None if not available + + + +### get\_caller\_directory + +```python +def get_caller_directory(depth: int) -> Optional[str] +``` + +Get the directory of the caller at a specific stack depth. + +This is used to determine the file_context_path when creating a template, +so file paths are resolved relative to the user's template file location. + +**Arguments**: + +- `depth`: The depth of the stack trace + +**Returns**: + +The caller's directory path, or None if not available + + + +### pad\_octal + +```python +def pad_octal(mode: int) -> str +``` + +Convert a numeric file mode to a zero-padded octal string. + +**Arguments**: + +- `mode`: File mode as a number (e.g., 493 for 0o755) + +**Returns**: + +Zero-padded 4-digit octal string (e.g., "0755") +Example +```python +pad_octal(0o755) # Returns "0755" +pad_octal(0o644) # Returns "0644" +``` + + + +### get\_build\_step\_index + +```python +def get_build_step_index(step: str, stack_traces_length: int) -> int +``` + +Get the array index for a build step based on its name. + +Special steps: +- BASE_STEP_NAME: Returns 0 (first step) +- FINALIZE_STEP_NAME: Returns the last index +- Numeric strings: Converted to number + +**Arguments**: + +- `step`: Build step name or number as string +- `stack_traces_length`: Total number of stack traces (used for FINALIZE_STEP_NAME) + +**Returns**: + +Index for the build step + + + +### read\_gcp\_service\_account\_json + +```python +def read_gcp_service_account_json(context_path: str, + path_or_content: Union[str, dict]) -> str +``` + +Read GCP service account JSON from a file or object. + +**Arguments**: + +- `context_path`: Base directory for resolving relative file paths +- `path_or_content`: Either a path to a JSON file or a service account object + +**Returns**: + +Service account JSON as a string + + + + + + +## TemplateBuilder + +```python +class TemplateBuilder() +``` + +Builder class for adding instructions to an E2B template. + +All methods return self to allow method chaining. + + + +### copy + +```python +def copy(src: Union[Union[str, Path], List[Union[str, Path]]], + dest: Union[str, Path], + force_upload: Optional[Literal[True]] = None, + user: Optional[str] = None, + mode: Optional[int] = None, + resolve_symlinks: Optional[bool] = None) -> "TemplateBuilder" +``` + +Copy files or directories from the local filesystem into the template. + +**Arguments**: + +- `src`: Source file(s) or directory path(s) to copy +- `dest`: Destination path in the template +- `force_upload`: Force upload even if files are cached +- `user`: User and optionally group (user:group) to own the files +- `mode`: File permissions in octal format (e.g., 0o755) +- `resolve_symlinks`: Whether to resolve symlinks + +**Returns**: + +`TemplateBuilder` class +Example +```python +template.copy('requirements.txt', '/home/user/') +template.copy(['app.py', 'config.py'], '/app/', mode=0o755) +``` + + + +### copy\_items + +```python +def copy_items(items: List[CopyItem]) -> "TemplateBuilder" +``` + +Copy multiple files or directories using a list of copy items. + +**Arguments**: + +- `items`: List of CopyItem dictionaries with src, dest, and optional parameters + +**Returns**: + +`TemplateBuilder` class +Example +```python +template.copy_items([ + {'src': 'app.py', 'dest': '/app/'}, + {'src': 'config.py', 'dest': '/app/', 'mode': 0o644} +]) +``` + + + +### remove + +```python +def remove(path: Union[Union[str, Path], List[Union[str, Path]]], + force: bool = False, + recursive: bool = False, + user: Optional[str] = None) -> "TemplateBuilder" +``` + +Remove files or directories in the template. + +**Arguments**: + +- `path`: File(s) or directory path(s) to remove +- `force`: Force removal without prompting +- `recursive`: Remove directories recursively +- `user`: User to run the command as + +**Returns**: + +`TemplateBuilder` class +Example +```python +template.remove('/tmp/cache', recursive=True, force=True) +template.remove('/tmp/cache', recursive=True, force=True, user='root') +``` + + + +### rename + +```python +def rename(src: Union[str, Path], + dest: Union[str, Path], + force: bool = False, + user: Optional[str] = None) -> "TemplateBuilder" +``` + +Rename or move a file or directory in the template. + +**Arguments**: + +- `src`: Source path +- `dest`: Destination path +- `force`: Force rename without prompting +- `user`: User to run the command as + +**Returns**: + +`TemplateBuilder` class +Example +```python +template.rename('/tmp/old.txt', '/tmp/new.txt') +template.rename('/tmp/old.txt', '/tmp/new.txt', user='root') +``` + + + +### make\_dir + +```python +def make_dir(path: Union[Union[str, Path], List[Union[str, Path]]], + mode: Optional[int] = None, + user: Optional[str] = None) -> "TemplateBuilder" +``` + +Create directory(ies) in the template. + +**Arguments**: + +- `path`: Directory path(s) to create +- `mode`: Directory permissions in octal format (e.g., 0o755) +- `user`: User to run the command as + +**Returns**: + +`TemplateBuilder` class +Example +```python +template.make_dir('/app/data', mode=0o755) +template.make_dir(['/app/logs', '/app/cache']) +template.make_dir('/app/data', mode=0o755, user='root') +``` + + + +### make\_symlink + +```python +def make_symlink(src: Union[str, Path], + dest: Union[str, Path], + user: Optional[str] = None, + force: bool = False) -> "TemplateBuilder" +``` + +Create a symbolic link in the template. + +**Arguments**: + +- `src`: Source path (target of the symlink) +- `dest`: Destination path (location of the symlink) +- `user`: User to run the command as +- `force`: Force symlink without prompting + +**Returns**: + +`TemplateBuilder` class +Example +```python +template.make_symlink('/usr/bin/python3', '/usr/bin/python') +template.make_symlink('/usr/bin/python3', '/usr/bin/python', user='root') +template.make_symlink('/usr/bin/python3', '/usr/bin/python', force=True) +``` + + + +### run\_cmd + +```python +def run_cmd(command: Union[str, List[str]], + user: Optional[str] = None) -> "TemplateBuilder" +``` + +Run a shell command during template build. + +**Arguments**: + +- `command`: Command string or list of commands to run (joined with &&) +- `user`: User to run the command as + +**Returns**: + +`TemplateBuilder` class +Example +```python +template.run_cmd('apt-get update') +template.run_cmd(['pip install numpy', 'pip install pandas']) +template.run_cmd('apt-get install vim', user='root') +``` + + + +### set\_workdir + +```python +def set_workdir(workdir: Union[str, Path]) -> "TemplateBuilder" +``` + +Set the working directory for subsequent commands in the template. + +**Arguments**: + +- `workdir`: Path to set as the working directory + +**Returns**: + +`TemplateBuilder` class +Example +```python +template.set_workdir('/app') +``` + + + +### set\_user + +```python +def set_user(user: str) -> "TemplateBuilder" +``` + +Set the user for subsequent commands in the template. + +**Arguments**: + +- `user`: Username to set + +**Returns**: + +`TemplateBuilder` class +Example +```python +template.set_user('root') +``` + + + +### pip\_install + +```python +def pip_install(packages: Optional[Union[str, List[str]]] = None, + g: bool = True) -> "TemplateBuilder" +``` + +Install Python packages using pip. + +**Arguments**: + +- `packages`: Package name(s) to install. If None, runs 'pip install .' in the current directory +- `g`: Install packages globally (default: True). If False, installs for user only + +**Returns**: + +`TemplateBuilder` class +Example +```python +template.pip_install('numpy') +template.pip_install(['pandas', 'scikit-learn']) +template.pip_install('numpy', g=False) # Install for user only +template.pip_install() # Installs from current directory +``` + + + +### npm\_install + +```python +def npm_install(packages: Optional[Union[str, List[str]]] = None, + g: Optional[bool] = False, + dev: Optional[bool] = False) -> "TemplateBuilder" +``` + +Install Node.js packages using npm. + +**Arguments**: + +- `packages`: Package name(s) to install. If None, installs from package.json +- `g`: Install packages globally +- `dev`: Install packages as dev dependencies + +**Returns**: + +`TemplateBuilder` class +Example +```python +template.npm_install('express') +template.npm_install(['lodash', 'axios']) +template.npm_install('typescript', g=True) +template.npm_install() # Installs from package.json +``` + + + +### bun\_install + +```python +def bun_install(packages: Optional[Union[str, List[str]]] = None, + g: Optional[bool] = False, + dev: Optional[bool] = False) -> "TemplateBuilder" +``` + +Install Bun packages using bun. + +**Arguments**: + +- `packages`: Package name(s) to install. If None, installs from package.json +- `g`: Install packages globally +- `dev`: Install packages as dev dependencies + +**Returns**: + +`TemplateBuilder` class +Example +```python +template.bun_install('express') +template.bun_install(['lodash', 'axios']) +template.bun_install('tsx', g=True) +template.bun_install('typescript', dev=True) +template.bun_install() // Installs from package.json +``` + + + +### apt\_install + +```python +def apt_install(packages: Union[str, List[str]], + no_install_recommends: bool = False) -> "TemplateBuilder" +``` + +Install system packages using apt-get. + +**Arguments**: + +- `packages`: Package name(s) to install +- `no_install_recommends`: Whether to install recommended packages + +**Returns**: + +`TemplateBuilder` class +Example +```python +template.apt_install('vim') +template.apt_install(['git', 'curl', 'wget']) +``` + + + +### add\_mcp\_server + +```python +def add_mcp_server(servers: Union[str, List[str]]) -> "TemplateBuilder" +``` + +Install MCP servers using mcp-gateway. + +Note: Requires a base image with mcp-gateway pre-installed (e.g., mcp-gateway). + +**Arguments**: + +- `servers`: MCP server name(s) + +**Returns**: + +`TemplateBuilder` class +Example +```python +template.add_mcp_server('exa') +template.add_mcp_server(['brave', 'firecrawl', 'duckduckgo']) +``` + + + +### git\_clone + +```python +def git_clone(url: str, + path: Optional[Union[str, Path]] = None, + branch: Optional[str] = None, + depth: Optional[int] = None, + user: Optional[str] = None) -> "TemplateBuilder" +``` + +Clone a git repository into the template. + +**Arguments**: + +- `url`: Git repository URL +- `path`: Destination path for the clone +- `branch`: Branch to clone +- `depth`: Clone depth for shallow clones +- `user`: User to run the command as + +**Returns**: + +`TemplateBuilder` class +Example +```python +template.git_clone('https://github.com/user/repo.git', '/app/repo') +template.git_clone('https://github.com/user/repo.git', branch='main', depth=1) +template.git_clone('https://github.com/user/repo.git', '/app/repo', user='root') +``` + + + +### beta\_dev\_container\_prebuild + +```python +def beta_dev_container_prebuild( + devcontainer_directory: Union[str, Path]) -> "TemplateBuilder" +``` + +Prebuild a devcontainer from the specified directory during the build process. + +**Arguments**: + +- `devcontainer_directory`: Path to the devcontainer directory + +**Returns**: + +`TemplateBuilder` class +Example +```python +template.git_clone('https://myrepo.com/project.git', '/my-devcontainer') +template.beta_dev_container_prebuild('/my-devcontainer') +``` + + + +### beta\_set\_dev\_container\_start + +```python +def beta_set_dev_container_start( + devcontainer_directory: Union[str, Path]) -> "TemplateFinal" +``` + +Start a devcontainer from the specified directory and set it as the start command. + +This method returns `TemplateFinal`, which means it must be the last method in the chain. + +**Arguments**: + +- `devcontainer_directory`: Path to the devcontainer directory + +**Returns**: + +`TemplateFinal` class +Example +```python +template.git_clone('https://myrepo.com/project.git', '/my-devcontainer') +template.beta_set_devcontainer_start('/my-devcontainer') + +template.git_clone('https://myrepo.com/project.git', '/my-devcontainer') +template.beta_dev_container_prebuild('/my-devcontainer') +template.beta_set_dev_container_start('/my-devcontainer') +``` + + + +### set\_envs + +```python +def set_envs(envs: Dict[str, str]) -> "TemplateBuilder" +``` + +Set environment variables in the template. + +**Arguments**: + +- `envs`: Dictionary of environment variable names and values + +**Returns**: + +`TemplateBuilder` class +Example +```python +template.set_envs({'NODE_ENV': 'production', 'PORT': '8080'}) +``` + + + +### skip\_cache + +```python +def skip_cache() -> "TemplateBuilder" +``` + +Skip cache for all subsequent build instructions from this point. + +Call this before any instruction to force it and all following layers +to be rebuilt, ignoring any cached layers. + +**Returns**: + +`TemplateBuilder` class +Example +```python +template.skip_cache().run_cmd('apt-get update') +``` + + + +### set\_start\_cmd + +```python +def set_start_cmd(start_cmd: str, + ready_cmd: Union[str, ReadyCmd]) -> "TemplateFinal" +``` + +Set the command to start when the sandbox launches and the ready check command. + +**Arguments**: + +- `start_cmd`: Command to run when the sandbox starts +- `ready_cmd`: Command or ReadyCmd to check if the sandbox is ready + +**Returns**: + +`TemplateFinal` class +Example +```python +template.set_start_cmd( + 'python app.py', + 'curl http://localhost:8000/health' +) + +from e2b import wait_for_port, wait_for_url + +template.set_start_cmd( + 'python -m http.server 8000', + wait_for_port(8000) +) + +template.set_start_cmd( + 'npm start', + wait_for_url('http://localhost:3000/health', 200) +) +``` + + + +### set\_ready\_cmd + +```python +def set_ready_cmd(ready_cmd: Union[str, ReadyCmd]) -> "TemplateFinal" +``` + +Set the command to check if the sandbox is ready. + +**Arguments**: + +- `ready_cmd`: Command or ReadyCmd to check if the sandbox is ready + +**Returns**: + +`TemplateFinal` class +Example +```python +template.set_ready_cmd('curl http://localhost:8000/health') + +from e2b import wait_for_port, wait_for_file, wait_for_process + +template.set_ready_cmd(wait_for_port(3000)) + +template.set_ready_cmd(wait_for_file('/tmp/ready')) + +template.set_ready_cmd(wait_for_process('nginx')) +``` + + + +## TemplateFinal + +```python +class TemplateFinal() +``` + +Final template state after start/ready commands are set. + + + +## TemplateBase + +```python +class TemplateBase() +``` + +Base class for building E2B sandbox templates. + + + +### \_\_init\_\_ + +```python +def __init__(file_context_path: Optional[Union[str, Path]] = None, + file_ignore_patterns: Optional[List[str]] = None) +``` + +Create a new template builder instance. + +**Arguments**: + +- `file_context_path`: Base path for resolving relative file paths in copy operations +- `file_ignore_patterns`: List of glob patterns to ignore when copying files + + + +### skip\_cache + +```python +def skip_cache() -> "TemplateBase" +``` + +Skip cache for all subsequent build instructions from this point. + +**Returns**: + +`TemplateBase` class +Example +```python +template.skip_cache().from_python_image('3.11') +``` + + + +### from\_debian\_image + +```python +def from_debian_image(variant: str = "stable") -> TemplateBuilder +``` + +Start template from a Debian base image. + +**Arguments**: + +- `variant`: Debian image variant + +**Returns**: + +`TemplateBuilder` class +Example +```python +Template().from_debian_image('bookworm') +``` + + + +### from\_ubuntu\_image + +```python +def from_ubuntu_image(variant: str = "latest") -> TemplateBuilder +``` + +Start template from an Ubuntu base image. + +**Arguments**: + +- `variant`: Ubuntu image variant (default: 'latest') + +**Returns**: + +`TemplateBuilder` class +Example +```python +Template().from_ubuntu_image('24.04') +``` + + + +### from\_python\_image + +```python +def from_python_image(version: str = "3") -> TemplateBuilder +``` + +Start template from a Python base image. + +**Arguments**: + +- `version`: Python version (default: '3') + +**Returns**: + +`TemplateBuilder` class +Example +```python +Template().from_python_image('3') +``` + + + +### from\_node\_image + +```python +def from_node_image(variant: str = "lts") -> TemplateBuilder +``` + +Start template from a Node.js base image. + +**Arguments**: + +- `variant`: Node.js image variant (default: 'lts') + +**Returns**: + +`TemplateBuilder` class +Example +```python +Template().from_node_image('24') +``` + + + +### from\_bun\_image + +```python +def from_bun_image(variant: str = "latest") -> TemplateBuilder +``` + +Start template from a Bun base image. + +**Arguments**: + +- `variant`: Bun image variant (default: 'latest') + +**Returns**: + +`TemplateBuilder` class + + + +### from\_base\_image + +```python +def from_base_image() -> TemplateBuilder +``` + +Start template from the E2B base image (e2bdev/base:latest). + +**Returns**: + +`TemplateBuilder` class +Example +```python +Template().from_base_image() +``` + + + +### from\_image + +```python +def from_image(image: str, + username: Optional[str] = None, + password: Optional[str] = None) -> TemplateBuilder +``` + +Start template from a Docker image. + +**Arguments**: + +- `image`: Docker image name (e.g., 'ubuntu:24.04') +- `username`: Username for private registry authentication +- `password`: Password for private registry authentication + +**Returns**: + +`TemplateBuilder` class +Example +```python +Template().from_image('python:3') + +Template().from_image('myregistry.com/myimage:latest', username='user', password='pass') +``` + + + +### from\_template + +```python +def from_template(template: str) -> TemplateBuilder +``` + +Start template from an existing E2B template. + +**Arguments**: + +- `template`: E2B template ID or alias + +**Returns**: + +`TemplateBuilder` class +Example +```python +Template().from_template('my-base-template') +``` + + + +### from\_dockerfile + +```python +def from_dockerfile(dockerfile_content_or_path: str) -> TemplateBuilder +``` + +Parse a Dockerfile and convert it to Template SDK format. + +**Arguments**: + +- `dockerfile_content_or_path`: Either the Dockerfile content as a string, or a path to a Dockerfile file + +**Returns**: + +`TemplateBuilder` class +Example +```python +Template().from_dockerfile('Dockerfile') +Template().from_dockerfile('FROM python:3\nRUN pip install numpy') +``` + + + +### from\_aws\_registry + +```python +def from_aws_registry(image: str, access_key_id: str, secret_access_key: str, + region: str) -> TemplateBuilder +``` + +Start template from an AWS ECR registry image. + +**Arguments**: + +- `image`: Docker image name from AWS ECR +- `access_key_id`: AWS access key ID +- `secret_access_key`: AWS secret access key +- `region`: AWS region + +**Returns**: + +`TemplateBuilder` class +Example +```python +Template().from_aws_registry( + '123456789.dkr.ecr.us-west-2.amazonaws.com/myimage:latest', + access_key_id='AKIA...', + secret_access_key='...', + region='us-west-2' +) +``` + + + +### from\_gcp\_registry + +```python +def from_gcp_registry( + image: str, service_account_json: Union[str, dict]) -> TemplateBuilder +``` + +Start template from a GCP Artifact Registry or Container Registry image. + +**Arguments**: + +- `image`: Docker image name from GCP registry +- `service_account_json`: Service account JSON string, dict, or path to JSON file + +**Returns**: + +`TemplateBuilder` class +Example +```python +Template().from_gcp_registry( + 'gcr.io/myproject/myimage:latest', + service_account_json='path/to/service-account.json' +) +``` + + + +### to\_json + +```python +@staticmethod +def to_json(template: "TemplateClass") -> str +``` + +Convert a template to JSON representation. + +**Arguments**: + +- `template`: The template to convert (TemplateBuilder or TemplateFinal instance) + +**Returns**: + +JSON string representation of the template +Example +```python +template = Template().from_python_image('3').copy('app.py', '/app/') +json_str = TemplateBase.to_json(template) +``` + + + +### to\_dockerfile + +```python +@staticmethod +def to_dockerfile(template: "TemplateClass") -> str +``` + +Convert a template to Dockerfile format. + +Note: Templates based on other E2B templates cannot be converted to Dockerfile. + +**Arguments**: + +- `template`: The template to convert (TemplateBuilder or TemplateFinal instance) + +**Raises**: + +- `ValueError`: If the template is based on another E2B template or has no base image +Example +```python +template = Template().from_python_image('3').copy('app.py', '/app/') +dockerfile = TemplateBase.to_dockerfile(template) +``` + +**Returns**: + +Dockerfile string representation diff --git a/docs/sdk-reference/python-sdk/v2.8.1/template_async.mdx b/docs/sdk-reference/python-sdk/v2.8.1/template_async.mdx new file mode 100644 index 0000000..950d066 --- /dev/null +++ b/docs/sdk-reference/python-sdk/v2.8.1/template_async.mdx @@ -0,0 +1,150 @@ +--- +sidebarTitle: "Template Async" +mode: "center" +--- + + + + + + + + + +## AsyncTemplate + +```python +class AsyncTemplate(TemplateBase) +``` + +Asynchronous template builder for E2B sandboxes. + + + +### build + +```python +@staticmethod +async def build(template: TemplateClass, + alias: str, + cpu_count: int = 2, + memory_mb: int = 1024, + skip_cache: bool = False, + on_build_logs: Optional[Callable[[LogEntry], None]] = None, + api_key: Optional[str] = None, + domain: Optional[str] = None) -> BuildInfo +``` + +Build and deploy a template to E2B infrastructure. + +**Arguments**: + +- `template`: The template to build +- `alias`: Alias name for the template +- `cpu_count`: Number of CPUs allocated to the sandbox +- `memory_mb`: Amount of memory in MB allocated to the sandbox +- `skip_cache`: If True, forces a complete rebuild ignoring cache +- `on_build_logs`: Callback function to receive build logs during the build process +- `api_key`: E2B API key for authentication +- `domain`: Domain of the E2B API +Example +```python +from e2b import AsyncTemplate + +template = ( + AsyncTemplate() + .from_python_image('3') + .copy('requirements.txt', '/home/user/') + .run_cmd('pip install -r /home/user/requirements.txt') +) + +await AsyncTemplate.build( + template, + alias='my-python-env', + cpu_count=2, + memory_mb=1024 +) +``` + + + +### build\_in\_background + +```python +@staticmethod +async def build_in_background(template: TemplateClass, + alias: str, + cpu_count: int = 2, + memory_mb: int = 1024, + skip_cache: bool = False, + on_build_logs: Optional[Callable[[LogEntry], + None]] = None, + api_key: Optional[str] = None, + domain: Optional[str] = None) -> BuildInfo +``` + +Build and deploy a template to E2B infrastructure without waiting for completion. + +**Arguments**: + +- `template`: The template to build +- `alias`: Alias name for the template +- `cpu_count`: Number of CPUs allocated to the sandbox +- `memory_mb`: Amount of memory in MB allocated to the sandbox +- `skip_cache`: If True, forces a complete rebuild ignoring cache +- `api_key`: E2B API key for authentication +- `domain`: Domain of the E2B API + +**Returns**: + +BuildInfo containing the template ID and build ID +Example +```python +from e2b import AsyncTemplate + +template = ( + AsyncTemplate() + .from_python_image('3') + .run_cmd('echo "test"') + .set_start_cmd('echo "Hello"', 'sleep 1') +) + +build_info = await AsyncTemplate.build_in_background( + template, + alias='my-python-env', + cpu_count=2, + memory_mb=1024 +) +``` + + + +### get\_build\_status + +```python +@staticmethod +async def get_build_status(build_info: BuildInfo, + logs_offset: int = 0, + api_key: Optional[str] = None, + domain: Optional[str] = None) +``` + +Get the status of a build. + +**Arguments**: + +- `build_info`: Build identifiers returned from build_in_background +- `logs_offset`: Offset for fetching logs +- `api_key`: E2B API key for authentication +- `domain`: Domain of the E2B API + +**Returns**: + +TemplateBuild containing the build status and logs +Example +```python +from e2b import AsyncTemplate + +build_info = await AsyncTemplate.build_in_background(template, alias='my-template') +status = await AsyncTemplate.get_build_status(build_info, logs_offset=0) +``` diff --git a/docs/sdk-reference/python-sdk/v2.8.1/template_sync.mdx b/docs/sdk-reference/python-sdk/v2.8.1/template_sync.mdx new file mode 100644 index 0000000..6387438 --- /dev/null +++ b/docs/sdk-reference/python-sdk/v2.8.1/template_sync.mdx @@ -0,0 +1,150 @@ +--- +sidebarTitle: "Template Sync" +mode: "center" +--- + + + + + + + + + +## Template + +```python +class Template(TemplateBase) +``` + +Synchronous template builder for E2B sandboxes. + + + +### build + +```python +@staticmethod +def build(template: TemplateClass, + alias: str, + cpu_count: int = 2, + memory_mb: int = 1024, + skip_cache: bool = False, + on_build_logs: Optional[Callable[[LogEntry], None]] = None, + api_key: Optional[str] = None, + domain: Optional[str] = None) -> BuildInfo +``` + +Build and deploy a template to E2B infrastructure. + +**Arguments**: + +- `template`: The template to build +- `alias`: Alias name for the template +- `cpu_count`: Number of CPUs allocated to the sandbox +- `memory_mb`: Amount of memory in MB allocated to the sandbox +- `skip_cache`: If True, forces a complete rebuild ignoring cache +- `on_build_logs`: Callback function to receive build logs during the build process +- `api_key`: E2B API key for authentication +- `domain`: Domain of the E2B API +Example +```python +from e2b import Template + +template = ( + Template() + .from_python_image('3') + .copy('requirements.txt', '/home/user/') + .run_cmd('pip install -r /home/user/requirements.txt') +) + +Template.build( + template, + alias='my-python-env', + cpu_count=2, + memory_mb=1024 +) +``` + + + +### build\_in\_background + +```python +@staticmethod +def build_in_background(template: TemplateClass, + alias: str, + cpu_count: int = 2, + memory_mb: int = 1024, + skip_cache: bool = False, + on_build_logs: Optional[Callable[[LogEntry], + None]] = None, + api_key: Optional[str] = None, + domain: Optional[str] = None) -> BuildInfo +``` + +Build and deploy a template to E2B infrastructure without waiting for completion. + +**Arguments**: + +- `template`: The template to build +- `alias`: Alias name for the template +- `cpu_count`: Number of CPUs allocated to the sandbox +- `memory_mb`: Amount of memory in MB allocated to the sandbox +- `skip_cache`: If True, forces a complete rebuild ignoring cache +- `api_key`: E2B API key for authentication +- `domain`: Domain of the E2B API + +**Returns**: + +BuildInfo containing the template ID and build ID +Example +```python +from e2b import Template + +template = ( + Template() + .from_python_image('3') + .run_cmd('echo "test"') + .set_start_cmd('echo "Hello"', 'sleep 1') +) + +build_info = Template.build_in_background( + template, + alias='my-python-env', + cpu_count=2, + memory_mb=1024 +) +``` + + + +### get\_build\_status + +```python +@staticmethod +def get_build_status(build_info: BuildInfo, + logs_offset: int = 0, + api_key: Optional[str] = None, + domain: Optional[str] = None) +``` + +Get the status of a build. + +**Arguments**: + +- `build_info`: Build identifiers returned from build_in_background +- `logs_offset`: Offset for fetching logs +- `api_key`: E2B API key for authentication +- `domain`: Domain of the E2B API + +**Returns**: + +TemplateBuild containing the build status and logs +Example +```python +from e2b import Template + +build_info = Template.build_in_background(template, alias='my-template') +status = Template.get_build_status(build_info, logs_offset=0) +``` diff --git a/docs/sdk-reference/python-sdk/v2.9.0/exceptions.mdx b/docs/sdk-reference/python-sdk/v2.9.0/exceptions.mdx new file mode 100644 index 0000000..d66f786 --- /dev/null +++ b/docs/sdk-reference/python-sdk/v2.9.0/exceptions.mdx @@ -0,0 +1,117 @@ +--- +sidebarTitle: "Exceptions" +mode: "center" +--- + + + + + + +## SandboxException + +```python +class SandboxException(Exception) +``` + +Base class for all sandbox errors. + +Raised when a general sandbox exception occurs. + + + +## TimeoutException + +```python +class TimeoutException(SandboxException) +``` + +Raised when a timeout occurs. + +The `unavailable` exception type is caused by sandbox timeout. + +The `canceled` exception type is caused by exceeding request timeout. + +The `deadline_exceeded` exception type is caused by exceeding the timeout for process, watch, etc. + +The `unknown` exception type is sometimes caused by the sandbox timeout when the request is not processed correctly. + + + +## InvalidArgumentException + +```python +class InvalidArgumentException(SandboxException) +``` + +Raised when an invalid argument is provided. + + + +## NotEnoughSpaceException + +```python +class NotEnoughSpaceException(SandboxException) +``` + +Raised when there is not enough disk space. + + + +## NotFoundException + +```python +class NotFoundException(SandboxException) +``` + +Raised when a resource is not found. + + + +## AuthenticationException + +```python +class AuthenticationException(Exception) +``` + +Raised when authentication fails. + + + +## TemplateException + +```python +class TemplateException(SandboxException) +``` + +Exception raised when the template uses old envd version. It isn't compatible with the new SDK. + + + +## RateLimitException + +```python +class RateLimitException(SandboxException) +``` + +Raised when the API rate limit is exceeded. + + + +## BuildException + +```python +class BuildException(Exception) +``` + +Raised when the build fails. + + + +## FileUploadException + +```python +class FileUploadException(BuildException) +``` + +Raised when the file upload fails. diff --git a/docs/sdk-reference/python-sdk/v2.9.0/logger.mdx b/docs/sdk-reference/python-sdk/v2.9.0/logger.mdx new file mode 100644 index 0000000..9fa3b18 --- /dev/null +++ b/docs/sdk-reference/python-sdk/v2.9.0/logger.mdx @@ -0,0 +1,106 @@ +--- +sidebarTitle: "Logger" +mode: "center" +--- + + + + + + +## LogEntry + +```python +@dataclass +class LogEntry() +``` + +Represents a single log entry from the template build process. + + + +## LogEntryStart + +```python +@dataclass +class LogEntryStart(LogEntry) +``` + +Special log entry indicating the start of a build process. + + + +## LogEntryEnd + +```python +@dataclass +class LogEntryEnd(LogEntry) +``` + +Special log entry indicating the end of a build process. + + + +### TIMER\_UPDATE\_INTERVAL\_MS + +Default minimum log level to display. + + + +### DEFAULT\_LEVEL + +Colored labels for each log level. + + + +### levels + +Numeric ordering of log levels for comparison (lower = less severe). + + + +### set\_interval + +```python +def set_interval(func, interval) +``` + +Returns a stop function that can be called to cancel the interval. + +Similar to JavaScript's setInterval. + +**Arguments**: + +- `func`: Function to execute at each interval +- `interval`: Interval duration in **seconds** + +**Returns**: + +Stop function that can be called to cancel the interval + + + +### default\_build\_logger + +```python +def default_build_logger( + min_level: Optional[LogEntryLevel] = None +) -> Callable[[LogEntry], None] +``` + +Create a default build logger with animated timer display. + +**Arguments**: + +- `min_level`: Minimum log level to display (default: 'info') + +**Returns**: + +Logger function that accepts LogEntry instances +Example +```python +from e2b import Template, default_build_logger + +template = Template().from_python_image() + +``` diff --git a/docs/sdk-reference/python-sdk/v2.9.0/readycmd.mdx b/docs/sdk-reference/python-sdk/v2.9.0/readycmd.mdx new file mode 100644 index 0000000..8eabda6 --- /dev/null +++ b/docs/sdk-reference/python-sdk/v2.9.0/readycmd.mdx @@ -0,0 +1,168 @@ +--- +sidebarTitle: "Readycmd" +mode: "center" +--- + + + + + + +## ReadyCmd + +```python +class ReadyCmd() +``` + +Wrapper class for ready check commands. + + + +### wait\_for\_port + +```python +def wait_for_port(port: int) +``` + +Wait for a port to be listening. + +Uses `ss` command to check if a port is open and listening. + +**Arguments**: + +- `port`: Port number to wait for + +**Returns**: + +ReadyCmd that checks for the port +Example +```python +from e2b import Template, wait_for_port + +template = ( + Template() + .from_python_image() + .set_start_cmd('python -m http.server 8000', wait_for_port(8000)) +) +``` + + + +### wait\_for\_url + +```python +def wait_for_url(url: str, status_code: int = 200) +``` + +Wait for a URL to return a specific HTTP status code. + +Uses `curl` to make HTTP requests and check the response status. + +**Arguments**: + +- `url`: URL to check (e.g., 'http://localhost:3000/health') +- `status_code`: Expected HTTP status code (default: 200) + +**Returns**: + +ReadyCmd that checks the URL +Example +```python +from e2b import Template, wait_for_url + +template = ( + Template() + .from_node_image() + .set_start_cmd('npm start', wait_for_url('http://localhost:3000/health')) +) +``` + + + +### wait\_for\_process + +```python +def wait_for_process(process_name: str) +``` + +Wait for a process with a specific name to be running. + +Uses `pgrep` to check if a process exists. + +**Arguments**: + +- `process_name`: Name of the process to wait for + +**Returns**: + +ReadyCmd that checks for the process +Example +```python +from e2b import Template, wait_for_process + +template = ( + Template() + .from_base_image() + .set_start_cmd('./my-daemon', wait_for_process('my-daemon')) +) +``` + + + +### wait\_for\_file + +```python +def wait_for_file(filename: str) +``` + +Wait for a file to exist. + +Uses shell test command to check file existence. + +**Arguments**: + +- `filename`: Path to the file to wait for + +**Returns**: + +ReadyCmd that checks for the file +Example +```python +from e2b import Template, wait_for_file + +template = ( + Template() + .from_base_image() + .set_start_cmd('./init.sh', wait_for_file('/tmp/ready')) +) +``` + + + +### wait\_for\_timeout + +```python +def wait_for_timeout(timeout: int) +``` + +Wait for a specified timeout before considering the sandbox ready. + +Uses `sleep` command to wait for a fixed duration. + +**Arguments**: + +- `timeout`: Time to wait in **milliseconds** (minimum: 1000ms / 1 second) + +**Returns**: + +ReadyCmd that waits for the specified duration +Example +```python +from e2b import Template, wait_for_timeout + +template = ( + Template() + .from_node_image() + .set_start_cmd('npm start', wait_for_timeout(5000)) # Wait 5 seconds +) +``` diff --git a/docs/sdk-reference/python-sdk/v2.9.0/sandbox_async.mdx b/docs/sdk-reference/python-sdk/v2.9.0/sandbox_async.mdx new file mode 100644 index 0000000..ea19a01 --- /dev/null +++ b/docs/sdk-reference/python-sdk/v2.9.0/sandbox_async.mdx @@ -0,0 +1,1412 @@ +--- +sidebarTitle: "Sandbox Async" +mode: "center" +--- + + + + + + +## AsyncWatchHandle + +```python +class AsyncWatchHandle() +``` + +Handle for watching a directory in the sandbox filesystem. + +Use `.stop()` to stop watching the directory. + + + +### stop + +```python +async def stop() +``` + +Stop watching the directory. + + + + + + +## Filesystem + +```python +class Filesystem() +``` + +Module for interacting with the filesystem in the sandbox. + + + +### read + +```python +@overload +async def read(path: str, + format: Literal["text"] = "text", + user: Optional[Username] = None, + request_timeout: Optional[float] = None) -> str +``` + +Read file content as a `str`. + +**Arguments**: + +- `path`: Path to the file +- `user`: Run the operation as this user +- `format`: Format of the file content—`text` by default +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +File content as a `str` + + + +### read + +```python +@overload +async def read(path: str, + format: Literal["bytes"], + user: Optional[Username] = None, + request_timeout: Optional[float] = None) -> bytearray +``` + +Read file content as a `bytearray`. + +**Arguments**: + +- `path`: Path to the file +- `user`: Run the operation as this user +- `format`: Format of the file content—`bytes` +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +File content as a `bytearray` + + + +### read + +```python +@overload +async def read( + path: str, + format: Literal["stream"], + user: Optional[Username] = None, + request_timeout: Optional[float] = None) -> AsyncIterator[bytes] +``` + +Read file content as a `AsyncIterator[bytes]`. + +**Arguments**: + +- `path`: Path to the file +- `user`: Run the operation as this user +- `format`: Format of the file content—`stream` +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +File content as an `AsyncIterator[bytes]` + + + +### write + +```python +async def write(path: str, + data: Union[str, bytes, IO], + user: Optional[Username] = None, + request_timeout: Optional[float] = None) -> WriteInfo +``` + +Write content to a file on the path. + +Writing to a file that doesn't exist creates the file. +Writing to a file that already exists overwrites the file. +Writing to a file at path that doesn't exist creates the necessary directories. + +**Arguments**: + +- `path`: Path to the file +- `data`: Data to write to the file, can be a `str`, `bytes`, or `IO`. +- `user`: Run the operation as this user +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +Information about the written file + + + +### write\_files + +```python +async def write_files( + files: List[WriteEntry], + user: Optional[Username] = None, + request_timeout: Optional[float] = None) -> List[WriteInfo] +``` + +Writes multiple files. + +Writes a list of files to the filesystem. +When writing to a file that doesn't exist, the file will get created. +When writing to a file that already exists, the file will get overwritten. +When writing to a file that's in a directory that doesn't exist, you'll get an error. + +**Arguments**: + +- `files`: list of files to write as `WriteEntry` objects, each containing `path` and `data` +- `user`: Run the operation as this user +- `request_timeout`: Timeout for the request + +**Returns**: + +Information about the written files + + + +### list + +```python +async def list(path: str, + depth: Optional[int] = 1, + user: Optional[Username] = None, + request_timeout: Optional[float] = None) -> List[EntryInfo] +``` + +List entries in a directory. + +**Arguments**: + +- `path`: Path to the directory +- `depth`: Depth of the directory to list +- `user`: Run the operation as this user +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +List of entries in the directory + + + +### exists + +```python +async def exists(path: str, + user: Optional[Username] = None, + request_timeout: Optional[float] = None) -> bool +``` + +Check if a file or a directory exists. + +**Arguments**: + +- `path`: Path to a file or a directory +- `user`: Run the operation as this user +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`True` if the file or directory exists, `False` otherwise + + + +### get\_info + +```python +async def get_info(path: str, + user: Optional[Username] = None, + request_timeout: Optional[float] = None) -> EntryInfo +``` + +Get information about a file or directory. + +**Arguments**: + +- `path`: Path to a file or a directory +- `user`: Run the operation as this user +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +Information about the file or directory like name, type, and path + + + +### remove + +```python +async def remove(path: str, + user: Optional[Username] = None, + request_timeout: Optional[float] = None) -> None +``` + +Remove a file or a directory. + +**Arguments**: + +- `path`: Path to a file or a directory +- `user`: Run the operation as this user +- `request_timeout`: Timeout for the request in **seconds** + + + +### rename + +```python +async def rename(old_path: str, + new_path: str, + user: Optional[Username] = None, + request_timeout: Optional[float] = None) -> EntryInfo +``` + +Rename a file or directory. + +**Arguments**: + +- `old_path`: Path to the file or directory to rename +- `new_path`: New path to the file or directory +- `user`: Run the operation as this user +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +Information about the renamed file or directory + + + +### make\_dir + +```python +async def make_dir(path: str, + user: Optional[Username] = None, + request_timeout: Optional[float] = None) -> bool +``` + +Create a new directory and all directories along the way if needed on the specified path. + +**Arguments**: + +- `path`: Path to a new directory. For example '/dirA/dirB' when creating 'dirB'. +- `user`: Run the operation as this user +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`True` if the directory was created, `False` if the directory already exists + + + +### watch\_dir + +```python +async def watch_dir(path: str, + on_event: OutputHandler[FilesystemEvent], + on_exit: Optional[OutputHandler[Exception]] = None, + user: Optional[Username] = None, + request_timeout: Optional[float] = None, + timeout: Optional[float] = 60, + recursive: bool = False) -> AsyncWatchHandle +``` + +Watch directory for filesystem events. + +**Arguments**: + +- `path`: Path to a directory to watch +- `on_event`: Callback to call on each event in the directory +- `on_exit`: Callback to call when the watching ends +- `user`: Run the operation as this user +- `request_timeout`: Timeout for the request in **seconds** +- `timeout`: Timeout for the watch operation in **seconds**. Using `0` will not limit the watch time +- `recursive`: Watch directory recursively + +**Returns**: + +`AsyncWatchHandle` object for stopping watching directory + + + + + + +## AsyncSandboxPaginator + +```python +class AsyncSandboxPaginator(SandboxPaginatorBase) +``` + +Paginator for listing sandboxes. + +**Example**: + +```python +paginator = AsyncSandbox.list() + +while paginator.has_next: + sandboxes = await paginator.next_items() + print(sandboxes) +``` + + + +### next\_items + +```python +async def next_items() -> List[SandboxInfo] +``` + +Returns the next page of sandboxes. + +Call this method only if `has_next` is `True`, otherwise it will raise an exception. + +**Returns**: + +List of sandboxes + + + + + + + + + +## SandboxApi + +```python +class SandboxApi(SandboxBase) +``` + + + +### list + +```python +@staticmethod +def list(query: Optional[SandboxQuery] = None, + limit: Optional[int] = None, + next_token: Optional[str] = None, + **opts: Unpack[ApiParams]) -> AsyncSandboxPaginator +``` + +List all running sandboxes. + +**Arguments**: + +- `query`: Filter the list of sandboxes by metadata or state, e.g. `SandboxListQuery(metadata={"key": "value"})` or `SandboxListQuery(state=[SandboxState.RUNNING])` +- `limit`: Maximum number of sandboxes to return per page +- `next_token`: Token for pagination + +**Returns**: + +List of running sandboxes + + + + + + +## Commands + +```python +class Commands() +``` + +Module for executing commands in the sandbox. + + + +### list + +```python +async def list(request_timeout: Optional[float] = None) -> List[ProcessInfo] +``` + +Lists all running commands and PTY sessions. + +**Arguments**: + +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +List of running commands and PTY sessions + + + +### kill + +```python +async def kill(pid: int, request_timeout: Optional[float] = None) -> bool +``` + +Kill a running command specified by its process ID. + +It uses `SIGKILL` signal to kill the command. + +**Arguments**: + +- `pid`: Process ID of the command. You can get the list of processes using `sandbox.commands.list()` +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`True` if the command was killed, `False` if the command was not found + + + +### send\_stdin + +```python +async def send_stdin(pid: int, + data: str, + request_timeout: Optional[float] = None) -> None +``` + +Send data to command stdin. + +:param pid Process ID of the command. You can get the list of processes using `sandbox.commands.list()`. +:param data: Data to send to the command +:param request_timeout: Timeout for the request in **seconds** + + + + +### run + +```python +@overload +async def run(cmd: str, + background: Union[Literal[False], None] = None, + envs: Optional[Dict[str, str]] = None, + user: Optional[Username] = None, + cwd: Optional[str] = None, + on_stdout: Optional[OutputHandler[Stdout]] = None, + on_stderr: Optional[OutputHandler[Stderr]] = None, + stdin: Optional[bool] = None, + timeout: Optional[float] = 60, + request_timeout: Optional[float] = None) -> CommandResult +``` + +Start a new command and wait until it finishes executing. + +**Arguments**: + +- `cmd`: Command to execute +- `background`: **`False` if the command should be executed in the foreground**, `True` if the command should be executed in the background +- `envs`: Environment variables used for the command +- `user`: User to run the command as +- `cwd`: Working directory to run the command +- `on_stdout`: Callback for command stdout output +- `on_stderr`: Callback for command stderr output +- `stdin`: If `True`, the command will have a stdin stream that you can send data to using `sandbox.commands.send_stdin()` +- `timeout`: Timeout for the command connection in **seconds**. Using `0` will not limit the command connection time +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`CommandResult` result of the command execution + + + +### run + +```python +@overload +async def run(cmd: str, + background: Literal[True], + envs: Optional[Dict[str, str]] = None, + user: Optional[Username] = None, + cwd: Optional[str] = None, + on_stdout: Optional[OutputHandler[Stdout]] = None, + on_stderr: Optional[OutputHandler[Stderr]] = None, + stdin: Optional[bool] = None, + timeout: Optional[float] = 60, + request_timeout: Optional[float] = None) -> AsyncCommandHandle +``` + +Start a new command and return a handle to interact with it. + +**Arguments**: + +- `cmd`: Command to execute +- `background`: `False` if the command should be executed in the foreground, **`True` if the command should be executed in the background** +- `envs`: Environment variables used for the command +- `user`: User to run the command as +- `cwd`: Working directory to run the command +- `on_stdout`: Callback for command stdout output +- `on_stderr`: Callback for command stderr output +- `stdin`: If `True`, the command will have a stdin stream that you can send data to using `sandbox.commands.send_stdin()` +- `timeout`: Timeout for the command connection in **seconds**. Using `0` will not limit the command connection time +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`AsyncCommandHandle` handle to interact with the running command + + + +### connect + +```python +async def connect( + pid: int, + timeout: Optional[float] = 60, + request_timeout: Optional[float] = None, + on_stdout: Optional[OutputHandler[Stdout]] = None, + on_stderr: Optional[OutputHandler[Stderr]] = None +) -> AsyncCommandHandle +``` + +Connects to a running command. + +You can use `AsyncCommandHandle.wait()` to wait for the command to finish and get execution results. + +**Arguments**: + +- `pid`: Process ID of the command to connect to. You can get the list of processes using `sandbox.commands.list()` +- `request_timeout`: Request timeout in **seconds** +- `timeout`: Timeout for the command connection in **seconds**. Using `0` will not limit the command connection time +- `on_stdout`: Callback for command stdout output +- `on_stderr`: Callback for command stderr output + +**Returns**: + +`AsyncCommandHandle` handle to interact with the running command + + + + + + +## AsyncCommandHandle + +```python +class AsyncCommandHandle() +``` + +Command execution handle. + +It provides methods for waiting for the command to finish, retrieving stdout/stderr, and killing the command. + + + +### pid + +```python +@property +def pid() +``` + +Command process ID. + + + +### stdout + +```python +@property +def stdout() +``` + +Command stdout output. + + + +### stderr + +```python +@property +def stderr() +``` + +Command stderr output. + + + +### error + +```python +@property +def error() +``` + +Command execution error message. + + + +### exit\_code + +```python +@property +def exit_code() +``` + +Command execution exit code. + +`0` if the command finished successfully. + +It is `None` if the command is still running. + + + +### disconnect + +```python +async def disconnect() -> None +``` + +Disconnects from the command. + +The command is not killed, but SDK stops receiving events from the command. +You can reconnect to the command using `sandbox.commands.connect` method. + + + +### wait + +```python +async def wait() -> CommandResult +``` + +Wait for the command to finish and return the result. + +If the command exits with a non-zero exit code, it throws a `CommandExitException`. + +**Returns**: + +`CommandResult` result of command execution + + + +### kill + +```python +async def kill() -> bool +``` + +Kills the command. + +It uses `SIGKILL` signal to kill the command + +**Returns**: + +`True` if the command was killed successfully, `False` if the command was not found + + + + + + +## Pty + +```python +class Pty() +``` + +Module for interacting with PTYs (pseudo-terminals) in the sandbox. + + + +### kill + +```python +async def kill(pid: int, request_timeout: Optional[float] = None) -> bool +``` + +Kill PTY. + +**Arguments**: + +- `pid`: Process ID of the PTY +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`true` if the PTY was killed, `false` if the PTY was not found + + + +### send\_stdin + +```python +async def send_stdin(pid: int, + data: bytes, + request_timeout: Optional[float] = None) -> None +``` + +Send input to a PTY. + +**Arguments**: + +- `pid`: Process ID of the PTY +- `data`: Input data to send +- `request_timeout`: Timeout for the request in **seconds** + + + +### create + +```python +async def create( + size: PtySize, + on_data: OutputHandler[PtyOutput], + user: Optional[Username] = None, + cwd: Optional[str] = None, + envs: Optional[Dict[str, str]] = None, + timeout: Optional[float] = 60, + request_timeout: Optional[float] = None) -> AsyncCommandHandle +``` + +Start a new PTY (pseudo-terminal). + +**Arguments**: + +- `size`: Size of the PTY +- `on_data`: Callback to handle PTY data +- `user`: User to use for the PTY +- `cwd`: Working directory for the PTY +- `envs`: Environment variables for the PTY +- `timeout`: Timeout for the PTY in **seconds** +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +Handle to interact with the PTY + + + +### connect + +```python +async def connect( + pid: int, + on_data: OutputHandler[PtyOutput], + timeout: Optional[float] = 60, + request_timeout: Optional[float] = None) -> AsyncCommandHandle +``` + +Connect to a running PTY. + +**Arguments**: + +- `pid`: Process ID of the PTY to connect to. You can get the list of running PTYs using `sandbox.pty.list()`. +- `on_data`: Callback to handle PTY data +- `timeout`: Timeout for the PTY connection in **seconds**. Using `0` will not limit the connection time +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +Handle to interact with the PTY + + + +### resize + +```python +async def resize(pid: int, + size: PtySize, + request_timeout: Optional[float] = None) +``` + +Resize PTY. + +Call this when the terminal window is resized and the number of columns and rows has changed. + +**Arguments**: + +- `pid`: Process ID of the PTY +- `size`: New size of the PTY +- `request_timeout`: Timeout for the request in **seconds** + + + + + + +## AsyncSandbox + +```python +class AsyncSandbox(SandboxApi) +``` + +E2B cloud sandbox is a secure and isolated cloud environment. + +The sandbox allows you to: +- Access Linux OS +- Create, list, and delete files and directories +- Run commands +- Run isolated code +- Access the internet + +Check docs [here](https://e2b.dev/docs). + +Use the `AsyncSandbox.create()` to create a new sandbox. + +**Example**: + +```python +from e2b import AsyncSandbox + +sandbox = await AsyncSandbox.create() +``` + + + +### files + +```python +@property +def files() -> Filesystem +``` + +Module for interacting with the sandbox filesystem. + + + +### commands + +```python +@property +def commands() -> Commands +``` + +Module for running commands in the sandbox. + + + +### pty + +```python +@property +def pty() -> Pty +``` + +Module for interacting with the sandbox pseudo-terminal. + + + +### \_\_init\_\_ + +```python +def __init__(**opts: Unpack[SandboxOpts]) +``` + +Use `AsyncSandbox.create()` to create a new sandbox instead. + + + +### is\_running + +```python +async def is_running(request_timeout: Optional[float] = None) -> bool +``` + +Check if the sandbox is running. + +**Arguments**: + +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`True` if the sandbox is running, `False` otherwise +Example +```python +sandbox = await AsyncSandbox.create() +await sandbox.is_running() # Returns True + +await sandbox.kill() +await sandbox.is_running() # Returns False +``` + + + +### create + +```python +@classmethod +async def create(cls, + template: Optional[str] = None, + timeout: Optional[int] = None, + metadata: Optional[Dict[str, str]] = None, + envs: Optional[Dict[str, str]] = None, + secure: bool = True, + allow_internet_access: bool = True, + mcp: Optional[McpServer] = None, + network: Optional[SandboxNetworkOpts] = None, + **opts: Unpack[ApiParams]) -> Self +``` + +Create a new sandbox. + +By default, the sandbox is created from the default `base` sandbox template. + +**Arguments**: + +- `template`: Sandbox template name or ID +- `timeout`: Timeout for the sandbox in **seconds**, default to 300 seconds. The maximum time a sandbox can be kept alive is 24 hours (86_400 seconds) for Pro users and 1 hour (3_600 seconds) for Hobby users. +- `metadata`: Custom metadata for the sandbox +- `envs`: Custom environment variables for the sandbox +- `secure`: Envd is secured with access token and cannot be used without it, defaults to `True`. +- `allow_internet_access`: Allow sandbox to access the internet, defaults to `True`. If set to `False`, it works the same as setting network `deny_out` to `[0.0.0.0/0]`. +- `mcp`: MCP server to enable in the sandbox +- `network`: Sandbox network configuration + +**Returns**: + +A Sandbox instance for the new sandbox +Use this method instead of using the constructor to create a new sandbox. + + + +### connect + +```python +@overload +async def connect(timeout: Optional[int] = None, + **opts: Unpack[ApiParams]) -> Self +``` + +Connect to a sandbox. If the sandbox is paused, it will be automatically resumed. + +Sandbox must be either running or be paused. + +With sandbox ID you can connect to the same sandbox from different places or environments (serverless functions, etc). + +**Arguments**: + +- `timeout`: Timeout for the sandbox in **seconds** +For running sandboxes, the timeout will update only if the new timeout is longer than the existing one. + +**Returns**: + +A running sandbox instance +@example +```python +sandbox = await AsyncSandbox.create() +await sandbox.beta_pause() + +same_sandbox = await sandbox.connect() +``` + + + +### connect + +```python +@overload +@classmethod +async def connect(cls, + sandbox_id: str, + timeout: Optional[int] = None, + **opts: Unpack[ApiParams]) -> Self +``` + +Connect to a sandbox. If the sandbox is paused, it will be automatically resumed. + +Sandbox must be either running or be paused. + +With sandbox ID you can connect to the same sandbox from different places or environments (serverless functions, etc). + +**Arguments**: + +- `sandbox_id`: Sandbox ID +- `timeout`: Timeout for the sandbox in **seconds** +For running sandboxes, the timeout will update only if the new timeout is longer than the existing one. + +**Returns**: + +A running sandbox instance +@example +```python +sandbox = await AsyncSandbox.create() +await AsyncSandbox.beta_pause(sandbox.sandbox_id) + +same_sandbox = await AsyncSandbox.connect(sandbox.sandbox_id)) +``` + + + +### connect + +```python +@class_method_variant("_cls_connect") +async def connect(timeout: Optional[int] = None, + **opts: Unpack[ApiParams]) -> Self +``` + +Connect to a sandbox. If the sandbox is paused, it will be automatically resumed. + +Sandbox must be either running or be paused. + +With sandbox ID you can connect to the same sandbox from different places or environments (serverless functions, etc). + +**Arguments**: + +- `timeout`: Timeout for the sandbox in **seconds** +For running sandboxes, the timeout will update only if the new timeout is longer than the existing one. + +**Returns**: + +A running sandbox instance +@example +```python +sandbox = await AsyncSandbox.create() +await sandbox.beta_pause() + +same_sandbox = await sandbox.connect() +``` + + + +### kill + +```python +@overload +async def kill(**opts: Unpack[ApiParams]) -> bool +``` + +Kill the sandbox. + +**Returns**: + +`True` if the sandbox was killed, `False` if the sandbox was not found + + + +### kill + +```python +@overload +@staticmethod +async def kill(sandbox_id: str, **opts: Unpack[ApiParams]) -> bool +``` + +Kill the sandbox specified by sandbox ID. + +**Arguments**: + +- `sandbox_id`: Sandbox ID + +**Returns**: + +`True` if the sandbox was killed, `False` if the sandbox was not found + + + +### kill + +```python +@class_method_variant("_cls_kill") +async def kill(**opts: Unpack[ApiParams]) -> bool +``` + +Kill the sandbox specified by sandbox ID. + +**Returns**: + +`True` if the sandbox was killed, `False` if the sandbox was not found + + + +### set\_timeout + +```python +@overload +async def set_timeout(timeout: int, **opts: Unpack[ApiParams]) -> None +``` + +Set the timeout of the sandbox. + +After the timeout expires, the sandbox will be automatically killed. +This method can extend or reduce the sandbox timeout set when creating the sandbox or from the last call to `.set_timeout`. + +The maximum time a sandbox can be kept alive is 24 hours (86_400 seconds) for Pro users and 1 hour (3_600 seconds) for Hobby users. + +**Arguments**: + +- `timeout`: Timeout for the sandbox in **seconds** + + + +### set\_timeout + +```python +@overload +@staticmethod +async def set_timeout(sandbox_id: str, timeout: int, + **opts: Unpack[ApiParams]) -> None +``` + +Set the timeout of the specified sandbox. + +After the timeout expires, the sandbox will be automatically killed. +This method can extend or reduce the sandbox timeout set when creating the sandbox or from the last call to `.set_timeout`. + +The maximum time a sandbox can be kept alive is 24 hours (86_400 seconds) for Pro users and 1 hour (3_600 seconds) for Hobby users. + +**Arguments**: + +- `sandbox_id`: Sandbox ID +- `timeout`: Timeout for the sandbox in **seconds** + + + +### set\_timeout + +```python +@class_method_variant("_cls_set_timeout") +async def set_timeout(timeout: int, **opts: Unpack[ApiParams]) -> None +``` + +Set the timeout of the specified sandbox. + +After the timeout expires, the sandbox will be automatically killed. +This method can extend or reduce the sandbox timeout set when creating the sandbox or from the last call to `.set_timeout`. + +The maximum time a sandbox can be kept alive is 24 hours (86_400 seconds) for Pro users and 1 hour (3_600 seconds) for Hobby users. + +**Arguments**: + +- `timeout`: Timeout for the sandbox in **seconds** + + + +### get\_info + +```python +@overload +async def get_info(**opts: Unpack[ApiParams]) -> SandboxInfo +``` + +Get sandbox information like sandbox ID, template, metadata, started at/end at date. + +**Returns**: + +Sandbox info + + + +### get\_info + +```python +@overload +@staticmethod +async def get_info(sandbox_id: str, **opts: Unpack[ApiParams]) -> SandboxInfo +``` + +Get sandbox information like sandbox ID, template, metadata, started at/end at date. + +**Arguments**: + +- `sandbox_id`: Sandbox ID + +**Returns**: + +Sandbox info + + + +### get\_info + +```python +@class_method_variant("_cls_get_info") +async def get_info(**opts: Unpack[ApiParams]) -> SandboxInfo +``` + +Get sandbox information like sandbox ID, template, metadata, started at/end at date. + +**Returns**: + +Sandbox info + + + +### get\_metrics + +```python +@overload +async def get_metrics(start: Optional[datetime.datetime] = None, + end: Optional[datetime.datetime] = None, + **opts: Unpack[ApiParams]) -> List[SandboxMetrics] +``` + +Get the metrics of the current sandbox. + +**Arguments**: + +- `start`: Start time for the metrics, defaults to the start of the sandbox +- `end`: End time for the metrics, defaults to the current time + +**Returns**: + +List of sandbox metrics containing CPU, memory and disk usage information + + + +### get\_metrics + +```python +@overload +@staticmethod +async def get_metrics(sandbox_id: str, + start: Optional[datetime.datetime] = None, + end: Optional[datetime.datetime] = None, + **opts: Unpack[ApiParams]) -> List[SandboxMetrics] +``` + +Get the metrics of the sandbox specified by sandbox ID. + +**Arguments**: + +- `sandbox_id`: Sandbox ID +- `start`: Start time for the metrics, defaults to the start of the sandbox +- `end`: End time for the metrics, defaults to the current time + +**Returns**: + +List of sandbox metrics containing CPU, memory and disk usage information + + + +### get\_metrics + +```python +@class_method_variant("_cls_get_metrics") +async def get_metrics(start: Optional[datetime.datetime] = None, + end: Optional[datetime.datetime] = None, + **opts: Unpack[ApiParams]) -> List[SandboxMetrics] +``` + +Get the metrics of the current sandbox. + +**Arguments**: + +- `start`: Start time for the metrics, defaults to the start of the sandbox +- `end`: End time for the metrics, defaults to the current time + +**Returns**: + +List of sandbox metrics containing CPU, memory and disk usage information + + + +### beta\_create + +```python +@classmethod +async def beta_create(cls, + template: Optional[str] = None, + timeout: Optional[int] = None, + auto_pause: bool = False, + metadata: Optional[Dict[str, str]] = None, + envs: Optional[Dict[str, str]] = None, + secure: bool = True, + allow_internet_access: bool = True, + mcp: Optional[McpServer] = None, + **opts: Unpack[ApiParams]) -> Self +``` + +[BETA] This feature is in beta and may change in the future. + +Create a new sandbox. + +By default, the sandbox is created from the default `base` sandbox template. + +**Arguments**: + +- `template`: Sandbox template name or ID +- `timeout`: Timeout for the sandbox in **seconds**, default to 300 seconds. The maximum time a sandbox can be kept alive is 24 hours (86_400 seconds) for Pro users and 1 hour (3_600 seconds) for Hobby users. +- `auto_pause`: Automatically pause the sandbox after the timeout expires. Defaults to `False`. +- `metadata`: Custom metadata for the sandbox +- `envs`: Custom environment variables for the sandbox +- `secure`: Envd is secured with access token and cannot be used without it, defaults to `True`. +- `allow_internet_access`: Allow sandbox to access the internet, defaults to `True`. +- `mcp`: MCP server to enable in the sandbox + +**Returns**: + +A Sandbox instance for the new sandbox +Use this method instead of using the constructor to create a new sandbox. + + + +### beta\_pause + +```python +@overload +async def beta_pause(**opts: Unpack[ApiParams]) -> None +``` + +[BETA] This feature is in beta and may change in the future. + +Pause the sandbox. + +**Returns**: + +Sandbox ID that can be used to resume the sandbox + + + +### beta\_pause + +```python +@overload +@staticmethod +async def beta_pause(sandbox_id: str, **opts: Unpack[ApiParams]) -> None +``` + +[BETA] This feature is in beta and may change in the future. + +Pause the sandbox specified by sandbox ID. + +**Arguments**: + +- `sandbox_id`: Sandbox ID + +**Returns**: + +Sandbox ID that can be used to resume the sandbox + + + +### beta\_pause + +```python +@class_method_variant("_cls_pause") +async def beta_pause(**opts: Unpack[ApiParams]) -> None +``` + +[BETA] This feature is in beta and may change in the future. + +Pause the sandbox. + +**Returns**: + +Sandbox ID that can be used to resume the sandbox + + + +### get\_mcp\_token + +```python +async def get_mcp_token() -> Optional[str] +``` + +Get the MCP token for the sandbox. + +**Returns**: + +MCP token for the sandbox, or None if MCP is not enabled. diff --git a/docs/sdk-reference/python-sdk/v2.9.0/sandbox_sync.mdx b/docs/sdk-reference/python-sdk/v2.9.0/sandbox_sync.mdx new file mode 100644 index 0000000..729fad1 --- /dev/null +++ b/docs/sdk-reference/python-sdk/v2.9.0/sandbox_sync.mdx @@ -0,0 +1,1365 @@ +--- +sidebarTitle: "Sandbox Sync" +mode: "center" +--- + + + + + + +## WatchHandle + +```python +class WatchHandle() +``` + +Handle for watching filesystem events. +It is used to get the latest events that have occurred in the watched directory. + +Use `.stop()` to stop watching the directory. + + + +### stop + +```python +def stop() +``` + +Stop watching the directory. +After you stop the watcher you won't be able to get the events anymore. + + + +### get\_new\_events + +```python +def get_new_events() -> List[FilesystemEvent] +``` + +Get the latest events that have occurred in the watched directory since the last call, or from the beginning of the watching, up until now. + +**Returns**: + +List of filesystem events + + + + + + +## Filesystem + +```python +class Filesystem() +``` + +Module for interacting with the filesystem in the sandbox. + + + +### read + +```python +@overload +def read(path: str, + format: Literal["text"] = "text", + user: Optional[Username] = None, + request_timeout: Optional[float] = None) -> str +``` + +Read file content as a `str`. + +**Arguments**: + +- `path`: Path to the file +- `user`: Run the operation as this user +- `format`: Format of the file content—`text` by default +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +File content as a `str` + + + +### read + +```python +@overload +def read(path: str, + format: Literal["bytes"], + user: Optional[Username] = None, + request_timeout: Optional[float] = None) -> bytearray +``` + +Read file content as a `bytearray`. + +**Arguments**: + +- `path`: Path to the file +- `user`: Run the operation as this user +- `format`: Format of the file content—`bytes` +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +File content as a `bytearray` + + + +### read + +```python +@overload +def read(path: str, + format: Literal["stream"], + user: Optional[Username] = None, + request_timeout: Optional[float] = None) -> Iterator[bytes] +``` + +Read file content as a `Iterator[bytes]`. + +**Arguments**: + +- `path`: Path to the file +- `user`: Run the operation as this user +- `format`: Format of the file content—`stream` +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +File content as an `Iterator[bytes]` + + + +### write + +```python +def write(path: str, + data: Union[str, bytes, IO], + user: Optional[Username] = None, + request_timeout: Optional[float] = None) -> WriteInfo +``` + +Write content to a file on the path. + +Writing to a file that doesn't exist creates the file. +Writing to a file that already exists overwrites the file. +Writing to a file at path that doesn't exist creates the necessary directories. + +**Arguments**: + +- `path`: Path to the file +- `data`: Data to write to the file, can be a `str`, `bytes`, or `IO`. +- `user`: Run the operation as this user +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +Information about the written file + + + +### write\_files + +```python +def write_files(files: List[WriteEntry], + user: Optional[Username] = None, + request_timeout: Optional[float] = None) -> List[WriteInfo] +``` + +Writes a list of files to the filesystem. + +When writing to a file that doesn't exist, the file will get created. +When writing to a file that already exists, the file will get overwritten. +When writing to a file that's in a directory that doesn't exist, you'll get an error. + +**Arguments**: + +- `files`: list of files to write as `WriteEntry` objects, each containing `path` and `data` +- `user`: Run the operation as this user +- `request_timeout`: Timeout for the request + +**Returns**: + +Information about the written files + + + +### list + +```python +def list(path: str, + depth: Optional[int] = 1, + user: Optional[Username] = None, + request_timeout: Optional[float] = None) -> List[EntryInfo] +``` + +List entries in a directory. + +**Arguments**: + +- `path`: Path to the directory +- `depth`: Depth of the directory to list +- `user`: Run the operation as this user +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +List of entries in the directory + + + +### exists + +```python +def exists(path: str, + user: Optional[Username] = None, + request_timeout: Optional[float] = None) -> bool +``` + +Check if a file or a directory exists. + +**Arguments**: + +- `path`: Path to a file or a directory +- `user`: Run the operation as this user +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`True` if the file or directory exists, `False` otherwise + + + +### get\_info + +```python +def get_info(path: str, + user: Optional[Username] = None, + request_timeout: Optional[float] = None) -> EntryInfo +``` + +Get information about a file or directory. + +**Arguments**: + +- `path`: Path to a file or a directory +- `user`: Run the operation as this user +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +Information about the file or directory like name, type, and path + + + +### remove + +```python +def remove(path: str, + user: Optional[Username] = None, + request_timeout: Optional[float] = None) -> None +``` + +Remove a file or a directory. + +**Arguments**: + +- `path`: Path to a file or a directory +- `user`: Run the operation as this user +- `request_timeout`: Timeout for the request in **seconds** + + + +### rename + +```python +def rename(old_path: str, + new_path: str, + user: Optional[Username] = None, + request_timeout: Optional[float] = None) -> EntryInfo +``` + +Rename a file or directory. + +**Arguments**: + +- `old_path`: Path to the file or directory to rename +- `new_path`: New path to the file or directory +- `user`: Run the operation as this user +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +Information about the renamed file or directory + + + +### make\_dir + +```python +def make_dir(path: str, + user: Optional[Username] = None, + request_timeout: Optional[float] = None) -> bool +``` + +Create a new directory and all directories along the way if needed on the specified path. + +**Arguments**: + +- `path`: Path to a new directory. For example '/dirA/dirB' when creating 'dirB'. +- `user`: Run the operation as this user +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`True` if the directory was created, `False` if the directory already exists + + + +### watch\_dir + +```python +def watch_dir(path: str, + user: Optional[Username] = None, + request_timeout: Optional[float] = None, + recursive: bool = False) -> WatchHandle +``` + +Watch directory for filesystem events. + +**Arguments**: + +- `path`: Path to a directory to watch +- `user`: Run the operation as this user +- `request_timeout`: Timeout for the request in **seconds** +- `recursive`: Watch directory recursively + +**Returns**: + +`WatchHandle` object for stopping watching directory + + + + + + +## SandboxPaginator + +```python +class SandboxPaginator(SandboxPaginatorBase) +``` + +Paginator for listing sandboxes. + +**Example**: + +```python +paginator = Sandbox.list() + +while paginator.has_next: + sandboxes = paginator.next_items() + print(sandboxes) +``` + + + +### next\_items + +```python +def next_items() -> List[SandboxInfo] +``` + +Returns the next page of sandboxes. + +Call this method only if `has_next` is `True`, otherwise it will raise an exception. + +**Returns**: + +List of sandboxes + + + + + + +## SandboxApi + +```python +class SandboxApi(SandboxBase) +``` + + + +### list + +```python +@staticmethod +def list(query: Optional[SandboxQuery] = None, + limit: Optional[int] = None, + next_token: Optional[str] = None, + **opts: Unpack[ApiParams]) -> SandboxPaginator +``` + +List all running sandboxes. + +**Arguments**: + +- `query`: Filter the list of sandboxes by metadata or state, e.g. `SandboxListQuery(metadata={"key": "value"})` or `SandboxListQuery(state=[SandboxState.RUNNING])` +- `limit`: Maximum number of sandboxes to return per page +- `next_token`: Token for pagination + +**Returns**: + +List of running sandboxes + + + + + + +## Commands + +```python +class Commands() +``` + +Module for executing commands in the sandbox. + + + +### list + +```python +def list(request_timeout: Optional[float] = None) -> List[ProcessInfo] +``` + +Lists all running commands and PTY sessions. + +**Arguments**: + +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +List of running commands and PTY sessions + + + +### kill + +```python +def kill(pid: int, request_timeout: Optional[float] = None) -> bool +``` + +Kills a running command specified by its process ID. + +It uses `SIGKILL` signal to kill the command. + +**Arguments**: + +- `pid`: Process ID of the command. You can get the list of processes using `sandbox.commands.list()` +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`True` if the command was killed, `False` if the command was not found + + + +### send\_stdin + +```python +def send_stdin(pid: int, data: str, request_timeout: Optional[float] = None) +``` + +Send data to command stdin. + +:param pid Process ID of the command. You can get the list of processes using `sandbox.commands.list()`. +:param data: Data to send to the command +:param request_timeout: Timeout for the request in **seconds** + + + + +### run + +```python +@overload +def run(cmd: str, + background: Union[Literal[False], None] = None, + envs: Optional[Dict[str, str]] = None, + user: Optional[Username] = None, + cwd: Optional[str] = None, + on_stdout: Optional[Callable[[str], None]] = None, + on_stderr: Optional[Callable[[str], None]] = None, + stdin: Optional[bool] = None, + timeout: Optional[float] = 60, + request_timeout: Optional[float] = None) -> CommandResult +``` + +Start a new command and wait until it finishes executing. + +**Arguments**: + +- `cmd`: Command to execute +- `background`: **`False` if the command should be executed in the foreground**, `True` if the command should be executed in the background +- `envs`: Environment variables used for the command +- `user`: User to run the command as +- `cwd`: Working directory to run the command +- `on_stdout`: Callback for command stdout output +- `on_stderr`: Callback for command stderr output +- `stdin`: If `True`, the command will have a stdin stream that you can send data to using `sandbox.commands.send_stdin()` +- `timeout`: Timeout for the command connection in **seconds**. Using `0` will not limit the command connection time +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`CommandResult` result of the command execution + + + +### run + +```python +@overload +def run(cmd: str, + background: Literal[True], + envs: Optional[Dict[str, str]] = None, + user: Optional[Username] = None, + cwd: Optional[str] = None, + on_stdout: None = None, + on_stderr: None = None, + stdin: Optional[bool] = None, + timeout: Optional[float] = 60, + request_timeout: Optional[float] = None) -> CommandHandle +``` + +Start a new command and return a handle to interact with it. + +**Arguments**: + +- `cmd`: Command to execute +- `background`: `False` if the command should be executed in the foreground, **`True` if the command should be executed in the background** +- `envs`: Environment variables used for the command +- `user`: User to run the command as +- `cwd`: Working directory to run the command +- `stdin`: If `True`, the command will have a stdin stream that you can send data to using `sandbox.commands.send_stdin()` +- `timeout`: Timeout for the command connection in **seconds**. Using `0` will not limit the command connection time +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`CommandHandle` handle to interact with the running command + + + +### connect + +```python +def connect(pid: int, + timeout: Optional[float] = 60, + request_timeout: Optional[float] = None) +``` + +Connects to a running command. + +You can use `CommandHandle.wait()` to wait for the command to finish and get execution results. + +**Arguments**: + +- `pid`: Process ID of the command to connect to. You can get the list of processes using `sandbox.commands.list()` +- `timeout`: Timeout for the connection in **seconds**. Using `0` will not limit the connection time +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`CommandHandle` handle to interact with the running command + + + + + + +## CommandHandle + +```python +class CommandHandle() +``` + +Command execution handle. + +It provides methods for waiting for the command to finish, retrieving stdout/stderr, and killing the command. + + + +### pid + +```python +@property +def pid() +``` + +Command process ID. + + + +### \_\_iter\_\_ + +```python +def __iter__() +``` + +Iterate over the command output. + +**Returns**: + +Generator of command outputs + + + +### disconnect + +```python +def disconnect() -> None +``` + +Disconnect from the command. + +The command is not killed, but SDK stops receiving events from the command. +You can reconnect to the command using `sandbox.commands.connect` method. + + + +### wait + +```python +def wait(on_pty: Optional[Callable[[PtyOutput], None]] = None, + on_stdout: Optional[Callable[[str], None]] = None, + on_stderr: Optional[Callable[[str], None]] = None) -> CommandResult +``` + +Wait for the command to finish and returns the result. + +If the command exits with a non-zero exit code, it throws a `CommandExitException`. + +**Arguments**: + +- `on_pty`: Callback for pty output +- `on_stdout`: Callback for stdout output +- `on_stderr`: Callback for stderr output + +**Returns**: + +`CommandResult` result of command execution + + + +### kill + +```python +def kill() -> bool +``` + +Kills the command. + +It uses `SIGKILL` signal to kill the command. + +**Returns**: + +Whether the command was killed successfully + + + + + + +## Pty + +```python +class Pty() +``` + +Module for interacting with PTYs (pseudo-terminals) in the sandbox. + + + +### kill + +```python +def kill(pid: int, request_timeout: Optional[float] = None) -> bool +``` + +Kill PTY. + +**Arguments**: + +- `pid`: Process ID of the PTY +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`true` if the PTY was killed, `false` if the PTY was not found + + + +### send\_stdin + +```python +def send_stdin(pid: int, + data: bytes, + request_timeout: Optional[float] = None) -> None +``` + +Send input to a PTY. + +**Arguments**: + +- `pid`: Process ID of the PTY +- `data`: Input data to send +- `request_timeout`: Timeout for the request in **seconds** + + + +### create + +```python +def create(size: PtySize, + user: Optional[Username] = None, + cwd: Optional[str] = None, + envs: Optional[Dict[str, str]] = None, + timeout: Optional[float] = 60, + request_timeout: Optional[float] = None) -> CommandHandle +``` + +Start a new PTY (pseudo-terminal). + +**Arguments**: + +- `size`: Size of the PTY +- `user`: User to use for the PTY +- `cwd`: Working directory for the PTY +- `envs`: Environment variables for the PTY +- `timeout`: Timeout for the PTY in **seconds** +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +Handle to interact with the PTY + + + +### connect + +```python +def connect(pid: int, + timeout: Optional[float] = 60, + request_timeout: Optional[float] = None) -> CommandHandle +``` + +Connect to a running PTY. + +**Arguments**: + +- `pid`: Process ID of the PTY to connect to. You can get the list of running PTYs using `sandbox.pty.list()`. +- `timeout`: Timeout for the PTY connection in **seconds**. Using `0` will not limit the connection time +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +Handle to interact with the PTY + + + +### resize + +```python +def resize(pid: int, + size: PtySize, + request_timeout: Optional[float] = None) -> None +``` + +Resize PTY. + +Call this when the terminal window is resized and the number of columns and rows has changed. + +**Arguments**: + +- `pid`: Process ID of the PTY +- `size`: New size of the PTY +- `request_timeout`: Timeout for the request in **seconds**s + + + + + + +## Sandbox + +```python +class Sandbox(SandboxApi) +``` + +E2B cloud sandbox is a secure and isolated cloud environment. + +The sandbox allows you to: +- Access Linux OS +- Create, list, and delete files and directories +- Run commands +- Run isolated code +- Access the internet + +Check docs [here](https://e2b.dev/docs). + +Use the `Sandbox.create()` to create a new sandbox. + +**Example**: + +```python +from e2b import Sandbox + +sandbox = Sandbox.create() +``` + + + +### files + +```python +@property +def files() -> Filesystem +``` + +Module for interacting with the sandbox filesystem. + + + +### commands + +```python +@property +def commands() -> Commands +``` + +Module for running commands in the sandbox. + + + +### pty + +```python +@property +def pty() -> Pty +``` + +Module for interacting with the sandbox pseudo-terminal. + + + +### \_\_init\_\_ + +```python +def __init__(**opts: Unpack[SandboxOpts]) +``` + +:deprecated: This constructor is deprecated + +Use `Sandbox.create()` to create a new sandbox instead. + + + +### is\_running + +```python +def is_running(request_timeout: Optional[float] = None) -> bool +``` + +Check if the sandbox is running. + +**Arguments**: + +- `request_timeout`: Timeout for the request in **seconds** + +**Returns**: + +`True` if the sandbox is running, `False` otherwise +Example +```python +sandbox = Sandbox.create() +sandbox.is_running() # Returns True + +sandbox.kill() +sandbox.is_running() # Returns False +``` + + + +### create + +```python +@classmethod +def create(cls, + template: Optional[str] = None, + timeout: Optional[int] = None, + metadata: Optional[Dict[str, str]] = None, + envs: Optional[Dict[str, str]] = None, + secure: bool = True, + allow_internet_access: bool = True, + mcp: Optional[McpServer] = None, + network: Optional[SandboxNetworkOpts] = None, + **opts: Unpack[ApiParams]) -> Self +``` + +Create a new sandbox. + +By default, the sandbox is created from the default `base` sandbox template. + +**Arguments**: + +- `template`: Sandbox template name or ID +- `timeout`: Timeout for the sandbox in **seconds**, default to 300 seconds. The maximum time a sandbox can be kept alive is 24 hours (86_400 seconds) for Pro users and 1 hour (3_600 seconds) for Hobby users. +- `metadata`: Custom metadata for the sandbox +- `envs`: Custom environment variables for the sandbox +- `secure`: Envd is secured with access token and cannot be used without it, defaults to `True`. +- `allow_internet_access`: Allow sandbox to access the internet, defaults to `True`. If set to `False`, it works the same as setting network `deny_out` to `[0.0.0.0/0]`. +- `mcp`: MCP server to enable in the sandbox +- `network`: Sandbox network configuration + +**Returns**: + +A Sandbox instance for the new sandbox +Use this method instead of using the constructor to create a new sandbox. + + + +### connect + +```python +@overload +def connect(timeout: Optional[int] = None, **opts: Unpack[ApiParams]) -> Self +``` + +Connect to a sandbox. If the sandbox is paused, it will be automatically resumed. + +Sandbox must be either running or be paused. + +With sandbox ID you can connect to the same sandbox from different places or environments (serverless functions, etc). + +**Arguments**: + +- `timeout`: Timeout for the sandbox in **seconds** +For running sandboxes, the timeout will update only if the new timeout is longer than the existing one. + +**Returns**: + +A running sandbox instance +@example +```python +sandbox = Sandbox.create() +sandbox.beta_pause() + +same_sandbox = sandbox.connect() + + + +### connect + +```python +@overload +@classmethod +def connect(cls, + sandbox_id: str, + timeout: Optional[int] = None, + **opts: Unpack[ApiParams]) -> Self +``` + +Connect to a sandbox. If the sandbox is paused, it will be automatically resumed. + +Sandbox must be either running or be paused. + +With sandbox ID you can connect to the same sandbox from different places or environments (serverless functions, etc). + +**Arguments**: + +- `sandbox_id`: Sandbox ID +- `timeout`: Timeout for the sandbox in **seconds**. +For running sandboxes, the timeout will update only if the new timeout is longer than the existing one. + +**Returns**: + +A running sandbox instance +@example +```python +sandbox = Sandbox.create() +Sandbox.beta_pause(sandbox.sandbox_id) + +same_sandbox = Sandbox.connect(sandbox.sandbox_id) +``` + + + +### connect + +```python +@class_method_variant("_cls_connect") +def connect(timeout: Optional[int] = None, **opts: Unpack[ApiParams]) -> Self +``` + +Connect to a sandbox. If the sandbox is paused, it will be automatically resumed. + +Sandbox must be either running or be paused. + +With sandbox ID you can connect to the same sandbox from different places or environments (serverless functions, etc). + +**Arguments**: + +- `timeout`: Timeout for the sandbox in **seconds**. +For running sandboxes, the timeout will update only if the new timeout is longer than the existing one. + +**Returns**: + +A running sandbox instance +@example +```python +sandbox = Sandbox.create() +sandbox.beta_pause() + +same_sandbox = sandbox.connect() +``` + + + +### kill + +```python +@overload +def kill(**opts: Unpack[ApiParams]) -> bool +``` + +Kill the sandbox. + +**Returns**: + +`True` if the sandbox was killed, `False` if the sandbox was not found + + + +### kill + +```python +@overload +@staticmethod +def kill(sandbox_id: str, **opts: Unpack[ApiParams]) -> bool +``` + +Kill the sandbox specified by sandbox ID. + +**Arguments**: + +- `sandbox_id`: Sandbox ID + +**Returns**: + +`True` if the sandbox was killed, `False` if the sandbox was not found + + + +### kill + +```python +@class_method_variant("_cls_kill") +def kill(**opts: Unpack[ApiParams]) -> bool +``` + +Kill the sandbox specified by sandbox ID. + +**Returns**: + +`True` if the sandbox was killed, `False` if the sandbox was not found + + + +### set\_timeout + +```python +@overload +def set_timeout(timeout: int, **opts: Unpack[ApiParams]) -> None +``` + +Set the timeout of the sandbox. + +After the timeout expires, the sandbox will be automatically killed. +This method can extend or reduce the sandbox timeout set when creating the sandbox or from the last call to `.set_timeout`. + +The maximum time a sandbox can be kept alive is 24 hours (86_400 seconds) for Pro users and 1 hour (3_600 seconds) for Hobby users. + +**Arguments**: + +- `timeout`: Timeout for the sandbox in **seconds** + + + +### set\_timeout + +```python +@overload +@staticmethod +def set_timeout(sandbox_id: str, timeout: int, + **opts: Unpack[ApiParams]) -> None +``` + +Set the timeout of the sandbox specified by sandbox ID. + +After the timeout expires, the sandbox will be automatically killed. +This method can extend or reduce the sandbox timeout set when creating the sandbox or from the last call to `.set_timeout`. + +The maximum time a sandbox can be kept alive is 24 hours (86_400 seconds) for Pro users and 1 hour (3_600 seconds) for Hobby users. + +**Arguments**: + +- `sandbox_id`: Sandbox ID +- `timeout`: Timeout for the sandbox in **seconds** + + + +### set\_timeout + +```python +@class_method_variant("_cls_set_timeout") +def set_timeout(timeout: int, **opts: Unpack[ApiParams]) -> None +``` + +Set the timeout of the sandbox. + +After the timeout expires, the sandbox will be automatically killed. +This method can extend or reduce the sandbox timeout set when creating the sandbox or from the last call to `.set_timeout`. + +The maximum time a sandbox can be kept alive is 24 hours (86_400 seconds) for Pro users and 1 hour (3_600 seconds) for Hobby users. + +**Arguments**: + +- `timeout`: Timeout for the sandbox in **seconds** + + + +### get\_info + +```python +@overload +def get_info(**opts: Unpack[ApiParams]) -> SandboxInfo +``` + +Get sandbox information like sandbox ID, template, metadata, started at/end at date. + +**Returns**: + +Sandbox info + + + +### get\_info + +```python +@overload +@staticmethod +def get_info(sandbox_id: str, **opts: Unpack[ApiParams]) -> SandboxInfo +``` + +Get sandbox information like sandbox ID, template, metadata, started at/end at date. + +**Arguments**: + +- `sandbox_id`: Sandbox ID + +**Returns**: + +Sandbox info + + + +### get\_info + +```python +@class_method_variant("_cls_get_info") +def get_info(**opts: Unpack[ApiParams]) -> SandboxInfo +``` + +Get sandbox information like sandbox ID, template, metadata, started at/end at date. + +**Returns**: + +Sandbox info + + + +### get\_metrics + +```python +@overload +def get_metrics(start: Optional[datetime.datetime] = None, + end: Optional[datetime.datetime] = None, + **opts: Unpack[ApiParams]) -> List[SandboxMetrics] +``` + +Get the metrics of the current sandbox. + +**Arguments**: + +- `start`: Start time for the metrics, defaults to the start of the sandbox +- `end`: End time for the metrics, defaults to the current time + +**Returns**: + +List of sandbox metrics containing CPU, memory and disk usage information + + + +### get\_metrics + +```python +@overload +@staticmethod +def get_metrics(sandbox_id: str, + start: Optional[datetime.datetime] = None, + end: Optional[datetime.datetime] = None, + **opts: Unpack[ApiParams]) -> List[SandboxMetrics] +``` + +Get the metrics of the sandbox specified by sandbox ID. + +**Arguments**: + +- `sandbox_id`: Sandbox ID +- `start`: Start time for the metrics, defaults to the start of the sandbox +- `end`: End time for the metrics, defaults to the current time + +**Returns**: + +List of sandbox metrics containing CPU, memory and disk usage information + + + +### get\_metrics + +```python +@class_method_variant("_cls_get_metrics") +def get_metrics(start: Optional[datetime.datetime] = None, + end: Optional[datetime.datetime] = None, + **opts: Unpack[ApiParams]) -> List[SandboxMetrics] +``` + +Get the metrics of the sandbox specified by sandbox ID. + +**Arguments**: + +- `start`: Start time for the metrics, defaults to the start of the sandbox +- `end`: End time for the metrics, defaults to the current time + +**Returns**: + +List of sandbox metrics containing CPU, memory and disk usage information + + + +### beta\_create + +```python +@classmethod +def beta_create(cls, + template: Optional[str] = None, + timeout: Optional[int] = None, + auto_pause: bool = False, + metadata: Optional[Dict[str, str]] = None, + envs: Optional[Dict[str, str]] = None, + secure: bool = True, + allow_internet_access: bool = True, + mcp: Optional[McpServer] = None, + **opts: Unpack[ApiParams]) -> Self +``` + +[BETA] This feature is in beta and may change in the future. + +Create a new sandbox. + +By default, the sandbox is created from the default `base` sandbox template. + +**Arguments**: + +- `template`: Sandbox template name or ID +- `timeout`: Timeout for the sandbox in **seconds**, default to 300 seconds. The maximum time a sandbox can be kept alive is 24 hours (86_400 seconds) for Pro users and 1 hour (3_600 seconds) for Hobby users. +- `auto_pause`: Automatically pause the sandbox after the timeout expires. Defaults to `False`. +- `metadata`: Custom metadata for the sandbox +- `envs`: Custom environment variables for the sandbox +- `secure`: Envd is secured with access token and cannot be used without it, defaults to `True`. +- `allow_internet_access`: Allow sandbox to access the internet, defaults to `True`. +- `mcp`: MCP server to enable in the sandbox + +**Returns**: + +A Sandbox instance for the new sandbox +Use this method instead of using the constructor to create a new sandbox. + + + +### beta\_pause + +```python +@overload +def beta_pause(**opts: Unpack[ApiParams]) -> None +``` + +[BETA] This feature is in beta and may change in the future. + +Pause the sandbox. + + + +### beta\_pause + +```python +@overload +@classmethod +def beta_pause(cls, sandbox_id: str, **opts: Unpack[ApiParams]) -> None +``` + +[BETA] This feature is in beta and may change in the future. + +Pause the sandbox specified by sandbox ID. + +**Arguments**: + +- `sandbox_id`: Sandbox ID + + + +### beta\_pause + +```python +@class_method_variant("_cls_pause") +def beta_pause(**opts: Unpack[ApiParams]) -> None +``` + +[BETA] This feature is in beta and may change in the future. + +Pause the sandbox. + +**Returns**: + +Sandbox ID that can be used to resume the sandbox + + + +### get\_mcp\_token + +```python +def get_mcp_token() -> Optional[str] +``` + +Get the MCP token for the sandbox. + +**Returns**: + +MCP token for the sandbox, or None if MCP is not enabled. diff --git a/docs/sdk-reference/python-sdk/v2.9.0/template.mdx b/docs/sdk-reference/python-sdk/v2.9.0/template.mdx new file mode 100644 index 0000000..644bd22 --- /dev/null +++ b/docs/sdk-reference/python-sdk/v2.9.0/template.mdx @@ -0,0 +1,1706 @@ +--- +sidebarTitle: "Template" +mode: "center" +--- + + + + + + +## DockerfFileFinalParserInterface + +```python +class DockerfFileFinalParserInterface(Protocol) +``` + +Protocol defining the final interface for Dockerfile parsing callbacks. + + + +## DockerfileParserInterface + +```python +class DockerfileParserInterface(Protocol) +``` + +Protocol defining the interface for Dockerfile parsing callbacks. + + + +### run\_cmd + +```python +def run_cmd(command: Union[str, List[str]], + user: Optional[str] = None) -> "DockerfileParserInterface" +``` + +Handle RUN instruction. + + + +### copy + +```python +def copy(src: Union[str, List[CopyItem]], + dest: Optional[str] = None, + force_upload: Optional[Literal[True]] = None, + resolve_symlinks: Optional[bool] = None, + user: Optional[str] = None, + mode: Optional[int] = None) -> "DockerfileParserInterface" +``` + +Handle COPY instruction. + + + +### set\_workdir + +```python +def set_workdir(workdir: str) -> "DockerfileParserInterface" +``` + +Handle WORKDIR instruction. + + + +### set\_user + +```python +def set_user(user: str) -> "DockerfileParserInterface" +``` + +Handle USER instruction. + + + +### set\_envs + +```python +def set_envs(envs: Dict[str, str]) -> "DockerfileParserInterface" +``` + +Handle ENV instruction. + + + +### set\_start\_cmd + +```python +def set_start_cmd(start_cmd: str, + ready_cmd: str) -> "DockerfFileFinalParserInterface" +``` + +Handle CMD/ENTRYPOINT instruction. + + + +### parse\_dockerfile + +```python +def parse_dockerfile(dockerfile_content_or_path: str, + template_builder: DockerfileParserInterface) -> str +``` + +Parse a Dockerfile and convert it to Template SDK format. + +**Arguments**: + +- `dockerfile_content_or_path`: Either the Dockerfile content as a string, or a path to a Dockerfile file +- `template_builder`: Interface providing template builder methods + +**Raises**: + +- `ValueError`: If the Dockerfile is invalid or unsupported + +**Returns**: + +The base image from the Dockerfile + + + + + + +## InstructionType + +```python +class InstructionType(str, Enum) +``` + +Types of instructions that can be used in a template. + + + +## CopyItem + +```python +class CopyItem(TypedDict) +``` + +Configuration for a single file/directory copy operation. + + + +## Instruction + +```python +class Instruction(TypedDict) +``` + +Represents a single instruction in the template build process. + + + +## GenericDockerRegistry + +```python +class GenericDockerRegistry(TypedDict) +``` + +Configuration for a generic Docker registry with basic authentication. + + + +## AWSRegistry + +```python +class AWSRegistry(TypedDict) +``` + +Configuration for AWS Elastic Container Registry (ECR). + + + +## GCPRegistry + +```python +class GCPRegistry(TypedDict) +``` + +Configuration for Google Container Registry (GCR) or Artifact Registry. + + + +## TemplateType + +```python +class TemplateType(TypedDict) +``` + +Internal representation of a template for the E2B build API. + + + +## BuildInfo + +```python +@dataclass +class BuildInfo() +``` + +Information about a built template. + + + + + + +## LogEntry + +```python +@dataclass +class LogEntry() +``` + +Represents a single log entry from the template build process. + + + +## LogEntryStart + +```python +@dataclass +class LogEntryStart(LogEntry) +``` + +Special log entry indicating the start of a build process. + + + +## LogEntryEnd + +```python +@dataclass +class LogEntryEnd(LogEntry) +``` + +Special log entry indicating the end of a build process. + + + +### TIMER\_UPDATE\_INTERVAL\_MS + +Default minimum log level to display. + + + +### DEFAULT\_LEVEL + +Colored labels for each log level. + + + +### levels + +Numeric ordering of log levels for comparison (lower = less severe). + + + +### set\_interval + +```python +def set_interval(func, interval) +``` + +Returns a stop function that can be called to cancel the interval. + +Similar to JavaScript's setInterval. + +**Arguments**: + +- `func`: Function to execute at each interval +- `interval`: Interval duration in **seconds** + +**Returns**: + +Stop function that can be called to cancel the interval + + + +### default\_build\_logger + +```python +def default_build_logger( + min_level: Optional[LogEntryLevel] = None +) -> Callable[[LogEntry], None] +``` + +Create a default build logger with animated timer display. + +**Arguments**: + +- `min_level`: Minimum log level to display (default: 'info') + +**Returns**: + +Logger function that accepts LogEntry instances +Example +```python +from e2b import Template, default_build_logger + +template = Template().from_python_image() + +``` + + + + +Special step name for the finalization phase of template building. +This is the last step that runs after all user-defined instructions. + + + +### FINALIZE\_STEP\_NAME + +Special step name for the base image phase of template building. +This is the first step that sets up the base image. + + + +### BASE\_STEP\_NAME + +Stack trace depth for capturing caller information. + +Depth levels: +1. TemplateClass +2. Caller method (e.g., copy(), from_image(), etc.) + +This depth is used to determine the original caller's location +for stack traces. + + + +### STACK\_TRACE\_DEPTH + +Default setting for whether to resolve symbolic links when copying files. +When False, symlinks are copied as symlinks rather than following them. + + + + + + +## ReadyCmd + +```python +class ReadyCmd() +``` + +Wrapper class for ready check commands. + + + +### wait\_for\_port + +```python +def wait_for_port(port: int) +``` + +Wait for a port to be listening. + +Uses `ss` command to check if a port is open and listening. + +**Arguments**: + +- `port`: Port number to wait for + +**Returns**: + +ReadyCmd that checks for the port +Example +```python +from e2b import Template, wait_for_port + +template = ( + Template() + .from_python_image() + .set_start_cmd('python -m http.server 8000', wait_for_port(8000)) +) +``` + + + +### wait\_for\_url + +```python +def wait_for_url(url: str, status_code: int = 200) +``` + +Wait for a URL to return a specific HTTP status code. + +Uses `curl` to make HTTP requests and check the response status. + +**Arguments**: + +- `url`: URL to check (e.g., 'http://localhost:3000/health') +- `status_code`: Expected HTTP status code (default: 200) + +**Returns**: + +ReadyCmd that checks the URL +Example +```python +from e2b import Template, wait_for_url + +template = ( + Template() + .from_node_image() + .set_start_cmd('npm start', wait_for_url('http://localhost:3000/health')) +) +``` + + + +### wait\_for\_process + +```python +def wait_for_process(process_name: str) +``` + +Wait for a process with a specific name to be running. + +Uses `pgrep` to check if a process exists. + +**Arguments**: + +- `process_name`: Name of the process to wait for + +**Returns**: + +ReadyCmd that checks for the process +Example +```python +from e2b import Template, wait_for_process + +template = ( + Template() + .from_base_image() + .set_start_cmd('./my-daemon', wait_for_process('my-daemon')) +) +``` + + + +### wait\_for\_file + +```python +def wait_for_file(filename: str) +``` + +Wait for a file to exist. + +Uses shell test command to check file existence. + +**Arguments**: + +- `filename`: Path to the file to wait for + +**Returns**: + +ReadyCmd that checks for the file +Example +```python +from e2b import Template, wait_for_file + +template = ( + Template() + .from_base_image() + .set_start_cmd('./init.sh', wait_for_file('/tmp/ready')) +) +``` + + + +### wait\_for\_timeout + +```python +def wait_for_timeout(timeout: int) +``` + +Wait for a specified timeout before considering the sandbox ready. + +Uses `sleep` command to wait for a fixed duration. + +**Arguments**: + +- `timeout`: Time to wait in **milliseconds** (minimum: 1000ms / 1 second) + +**Returns**: + +ReadyCmd that waits for the specified duration +Example +```python +from e2b import Template, wait_for_timeout + +template = ( + Template() + .from_node_image() + .set_start_cmd('npm start', wait_for_timeout(5000)) # Wait 5 seconds +) +``` + + + + + + +### read\_dockerignore + +```python +def read_dockerignore(context_path: str) -> List[str] +``` + +Read and parse a .dockerignore file. + +**Arguments**: + +- `context_path`: Directory path containing the .dockerignore file + +**Returns**: + +Array of ignore patterns (empty lines and comments are filtered out) + + + +### normalize\_path + +```python +def normalize_path(path: str) -> str +``` + +Normalize path separators to forward slashes for glob patterns (glob expects / even on Windows). + +**Arguments**: + +- `path`: The path to normalize + +**Returns**: + +The normalized path + + + +### get\_all\_files\_in\_path + +```python +def get_all_files_in_path(src: str, + context_path: str, + ignore_patterns: List[str], + include_directories: bool = True) -> List[str] +``` + +Get all files for a given path and ignore patterns. + +**Arguments**: + +- `src`: Path to the source directory +- `context_path`: Base directory for resolving relative paths +- `ignore_patterns`: Ignore patterns +- `include_directories`: Whether to include directories + +**Returns**: + +Array of files + + + +### calculate\_files\_hash + +```python +def calculate_files_hash(src: str, dest: str, context_path: str, + ignore_patterns: List[str], resolve_symlinks: bool, + stack_trace: Optional[TracebackType]) -> str +``` + +Calculate a hash of files being copied to detect changes for cache invalidation. + +The hash includes file content, metadata (mode, size), and relative paths. +Note: uid, gid, and mtime are excluded to ensure stable hashes across environments. + +**Arguments**: + +- `src`: Source path pattern for files to copy +- `dest`: Destination path where files will be copied +- `context_path`: Base directory for resolving relative paths +- `ignore_patterns`: Glob patterns to ignore +- `resolve_symlinks`: Whether to resolve symbolic links when hashing +- `stack_trace`: Optional stack trace for error reporting + +**Raises**: + +- `ValueError`: If no files match the source pattern + +**Returns**: + +Hex string hash of all files + + + +### tar\_file\_stream + +```python +def tar_file_stream(file_name: str, file_context_path: str, + ignore_patterns: List[str], + resolve_symlinks: bool) -> io.BytesIO +``` + +Create a tar stream of files matching a pattern. + +**Arguments**: + +- `file_name`: Glob pattern for files to include +- `file_context_path`: Base directory for resolving file paths +- `ignore_patterns`: Ignore patterns +- `resolve_symlinks`: Whether to resolve symbolic links + +**Returns**: + +Tar stream + + + +### strip\_ansi\_escape\_codes + +```python +def strip_ansi_escape_codes(text: str) -> str +``` + +Strip ANSI escape codes from a string. + +Source: https://github.com/chalk/ansi-regex/blob/main/index.js + +**Arguments**: + +- `text`: String with ANSI escape codes + +**Returns**: + +String without ANSI escape codes + + + +### get\_caller\_frame + +```python +def get_caller_frame(depth: int) -> Optional[FrameType] +``` + +Get the caller's stack frame at a specific depth. + +This is used to provide better error messages and debugging information +by tracking where template methods were called from in user code. + +**Arguments**: + +- `depth`: The depth of the stack trace to retrieve + +**Returns**: + +The caller frame, or None if not available + + + +### get\_caller\_directory + +```python +def get_caller_directory(depth: int) -> Optional[str] +``` + +Get the directory of the caller at a specific stack depth. + +This is used to determine the file_context_path when creating a template, +so file paths are resolved relative to the user's template file location. + +**Arguments**: + +- `depth`: The depth of the stack trace + +**Returns**: + +The caller's directory path, or None if not available + + + +### pad\_octal + +```python +def pad_octal(mode: int) -> str +``` + +Convert a numeric file mode to a zero-padded octal string. + +**Arguments**: + +- `mode`: File mode as a number (e.g., 493 for 0o755) + +**Returns**: + +Zero-padded 4-digit octal string (e.g., "0755") +Example +```python +pad_octal(0o755) # Returns "0755" +pad_octal(0o644) # Returns "0644" +``` + + + +### get\_build\_step\_index + +```python +def get_build_step_index(step: str, stack_traces_length: int) -> int +``` + +Get the array index for a build step based on its name. + +Special steps: +- BASE_STEP_NAME: Returns 0 (first step) +- FINALIZE_STEP_NAME: Returns the last index +- Numeric strings: Converted to number + +**Arguments**: + +- `step`: Build step name or number as string +- `stack_traces_length`: Total number of stack traces (used for FINALIZE_STEP_NAME) + +**Returns**: + +Index for the build step + + + +### read\_gcp\_service\_account\_json + +```python +def read_gcp_service_account_json(context_path: str, + path_or_content: Union[str, dict]) -> str +``` + +Read GCP service account JSON from a file or object. + +**Arguments**: + +- `context_path`: Base directory for resolving relative file paths +- `path_or_content`: Either a path to a JSON file or a service account object + +**Returns**: + +Service account JSON as a string + + + + + + +## TemplateBuilder + +```python +class TemplateBuilder() +``` + +Builder class for adding instructions to an E2B template. + +All methods return self to allow method chaining. + + + +### copy + +```python +def copy(src: Union[Union[str, Path], List[Union[str, Path]]], + dest: Union[str, Path], + force_upload: Optional[Literal[True]] = None, + user: Optional[str] = None, + mode: Optional[int] = None, + resolve_symlinks: Optional[bool] = None) -> "TemplateBuilder" +``` + +Copy files or directories from the local filesystem into the template. + +**Arguments**: + +- `src`: Source file(s) or directory path(s) to copy +- `dest`: Destination path in the template +- `force_upload`: Force upload even if files are cached +- `user`: User and optionally group (user:group) to own the files +- `mode`: File permissions in octal format (e.g., 0o755) +- `resolve_symlinks`: Whether to resolve symlinks + +**Returns**: + +`TemplateBuilder` class +Example +```python +template.copy('requirements.txt', '/home/user/') +template.copy(['app.py', 'config.py'], '/app/', mode=0o755) +``` + + + +### copy\_items + +```python +def copy_items(items: List[CopyItem]) -> "TemplateBuilder" +``` + +Copy multiple files or directories using a list of copy items. + +**Arguments**: + +- `items`: List of CopyItem dictionaries with src, dest, and optional parameters + +**Returns**: + +`TemplateBuilder` class +Example +```python +template.copy_items([ + {'src': 'app.py', 'dest': '/app/'}, + {'src': 'config.py', 'dest': '/app/', 'mode': 0o644} +]) +``` + + + +### remove + +```python +def remove(path: Union[Union[str, Path], List[Union[str, Path]]], + force: bool = False, + recursive: bool = False, + user: Optional[str] = None) -> "TemplateBuilder" +``` + +Remove files or directories in the template. + +**Arguments**: + +- `path`: File(s) or directory path(s) to remove +- `force`: Force removal without prompting +- `recursive`: Remove directories recursively +- `user`: User to run the command as + +**Returns**: + +`TemplateBuilder` class +Example +```python +template.remove('/tmp/cache', recursive=True, force=True) +template.remove('/tmp/cache', recursive=True, force=True, user='root') +``` + + + +### rename + +```python +def rename(src: Union[str, Path], + dest: Union[str, Path], + force: bool = False, + user: Optional[str] = None) -> "TemplateBuilder" +``` + +Rename or move a file or directory in the template. + +**Arguments**: + +- `src`: Source path +- `dest`: Destination path +- `force`: Force rename without prompting +- `user`: User to run the command as + +**Returns**: + +`TemplateBuilder` class +Example +```python +template.rename('/tmp/old.txt', '/tmp/new.txt') +template.rename('/tmp/old.txt', '/tmp/new.txt', user='root') +``` + + + +### make\_dir + +```python +def make_dir(path: Union[Union[str, Path], List[Union[str, Path]]], + mode: Optional[int] = None, + user: Optional[str] = None) -> "TemplateBuilder" +``` + +Create directory(ies) in the template. + +**Arguments**: + +- `path`: Directory path(s) to create +- `mode`: Directory permissions in octal format (e.g., 0o755) +- `user`: User to run the command as + +**Returns**: + +`TemplateBuilder` class +Example +```python +template.make_dir('/app/data', mode=0o755) +template.make_dir(['/app/logs', '/app/cache']) +template.make_dir('/app/data', mode=0o755, user='root') +``` + + + +### make\_symlink + +```python +def make_symlink(src: Union[str, Path], + dest: Union[str, Path], + user: Optional[str] = None, + force: bool = False) -> "TemplateBuilder" +``` + +Create a symbolic link in the template. + +**Arguments**: + +- `src`: Source path (target of the symlink) +- `dest`: Destination path (location of the symlink) +- `user`: User to run the command as +- `force`: Force symlink without prompting + +**Returns**: + +`TemplateBuilder` class +Example +```python +template.make_symlink('/usr/bin/python3', '/usr/bin/python') +template.make_symlink('/usr/bin/python3', '/usr/bin/python', user='root') +template.make_symlink('/usr/bin/python3', '/usr/bin/python', force=True) +``` + + + +### run\_cmd + +```python +def run_cmd(command: Union[str, List[str]], + user: Optional[str] = None) -> "TemplateBuilder" +``` + +Run a shell command during template build. + +**Arguments**: + +- `command`: Command string or list of commands to run (joined with &&) +- `user`: User to run the command as + +**Returns**: + +`TemplateBuilder` class +Example +```python +template.run_cmd('apt-get update') +template.run_cmd(['pip install numpy', 'pip install pandas']) +template.run_cmd('apt-get install vim', user='root') +``` + + + +### set\_workdir + +```python +def set_workdir(workdir: Union[str, Path]) -> "TemplateBuilder" +``` + +Set the working directory for subsequent commands in the template. + +**Arguments**: + +- `workdir`: Path to set as the working directory + +**Returns**: + +`TemplateBuilder` class +Example +```python +template.set_workdir('/app') +``` + + + +### set\_user + +```python +def set_user(user: str) -> "TemplateBuilder" +``` + +Set the user for subsequent commands in the template. + +**Arguments**: + +- `user`: Username to set + +**Returns**: + +`TemplateBuilder` class +Example +```python +template.set_user('root') +``` + + + +### pip\_install + +```python +def pip_install(packages: Optional[Union[str, List[str]]] = None, + g: bool = True) -> "TemplateBuilder" +``` + +Install Python packages using pip. + +**Arguments**: + +- `packages`: Package name(s) to install. If None, runs 'pip install .' in the current directory +- `g`: Install packages globally (default: True). If False, installs for user only + +**Returns**: + +`TemplateBuilder` class +Example +```python +template.pip_install('numpy') +template.pip_install(['pandas', 'scikit-learn']) +template.pip_install('numpy', g=False) # Install for user only +template.pip_install() # Installs from current directory +``` + + + +### npm\_install + +```python +def npm_install(packages: Optional[Union[str, List[str]]] = None, + g: Optional[bool] = False, + dev: Optional[bool] = False) -> "TemplateBuilder" +``` + +Install Node.js packages using npm. + +**Arguments**: + +- `packages`: Package name(s) to install. If None, installs from package.json +- `g`: Install packages globally +- `dev`: Install packages as dev dependencies + +**Returns**: + +`TemplateBuilder` class +Example +```python +template.npm_install('express') +template.npm_install(['lodash', 'axios']) +template.npm_install('typescript', g=True) +template.npm_install() # Installs from package.json +``` + + + +### bun\_install + +```python +def bun_install(packages: Optional[Union[str, List[str]]] = None, + g: Optional[bool] = False, + dev: Optional[bool] = False) -> "TemplateBuilder" +``` + +Install Bun packages using bun. + +**Arguments**: + +- `packages`: Package name(s) to install. If None, installs from package.json +- `g`: Install packages globally +- `dev`: Install packages as dev dependencies + +**Returns**: + +`TemplateBuilder` class +Example +```python +template.bun_install('express') +template.bun_install(['lodash', 'axios']) +template.bun_install('tsx', g=True) +template.bun_install('typescript', dev=True) +template.bun_install() // Installs from package.json +``` + + + +### apt\_install + +```python +def apt_install(packages: Union[str, List[str]], + no_install_recommends: bool = False) -> "TemplateBuilder" +``` + +Install system packages using apt-get. + +**Arguments**: + +- `packages`: Package name(s) to install +- `no_install_recommends`: Whether to install recommended packages + +**Returns**: + +`TemplateBuilder` class +Example +```python +template.apt_install('vim') +template.apt_install(['git', 'curl', 'wget']) +``` + + + +### add\_mcp\_server + +```python +def add_mcp_server(servers: Union[str, List[str]]) -> "TemplateBuilder" +``` + +Install MCP servers using mcp-gateway. + +Note: Requires a base image with mcp-gateway pre-installed (e.g., mcp-gateway). + +**Arguments**: + +- `servers`: MCP server name(s) + +**Returns**: + +`TemplateBuilder` class +Example +```python +template.add_mcp_server('exa') +template.add_mcp_server(['brave', 'firecrawl', 'duckduckgo']) +``` + + + +### git\_clone + +```python +def git_clone(url: str, + path: Optional[Union[str, Path]] = None, + branch: Optional[str] = None, + depth: Optional[int] = None, + user: Optional[str] = None) -> "TemplateBuilder" +``` + +Clone a git repository into the template. + +**Arguments**: + +- `url`: Git repository URL +- `path`: Destination path for the clone +- `branch`: Branch to clone +- `depth`: Clone depth for shallow clones +- `user`: User to run the command as + +**Returns**: + +`TemplateBuilder` class +Example +```python +template.git_clone('https://github.com/user/repo.git', '/app/repo') +template.git_clone('https://github.com/user/repo.git', branch='main', depth=1) +template.git_clone('https://github.com/user/repo.git', '/app/repo', user='root') +``` + + + +### beta\_dev\_container\_prebuild + +```python +def beta_dev_container_prebuild( + devcontainer_directory: Union[str, Path]) -> "TemplateBuilder" +``` + +Prebuild a devcontainer from the specified directory during the build process. + +**Arguments**: + +- `devcontainer_directory`: Path to the devcontainer directory + +**Returns**: + +`TemplateBuilder` class +Example +```python +template.git_clone('https://myrepo.com/project.git', '/my-devcontainer') +template.beta_dev_container_prebuild('/my-devcontainer') +``` + + + +### beta\_set\_dev\_container\_start + +```python +def beta_set_dev_container_start( + devcontainer_directory: Union[str, Path]) -> "TemplateFinal" +``` + +Start a devcontainer from the specified directory and set it as the start command. + +This method returns `TemplateFinal`, which means it must be the last method in the chain. + +**Arguments**: + +- `devcontainer_directory`: Path to the devcontainer directory + +**Returns**: + +`TemplateFinal` class +Example +```python +template.git_clone('https://myrepo.com/project.git', '/my-devcontainer') +template.beta_set_devcontainer_start('/my-devcontainer') + +template.git_clone('https://myrepo.com/project.git', '/my-devcontainer') +template.beta_dev_container_prebuild('/my-devcontainer') +template.beta_set_dev_container_start('/my-devcontainer') +``` + + + +### set\_envs + +```python +def set_envs(envs: Dict[str, str]) -> "TemplateBuilder" +``` + +Set environment variables. + +Note: Environment variables defined here are available only during template build. + +**Arguments**: + +- `envs`: Dictionary of environment variable names and values + +**Returns**: + +`TemplateBuilder` class +Example +```python +template.set_envs({'NODE_ENV': 'production', 'PORT': '8080'}) +``` + + + +### skip\_cache + +```python +def skip_cache() -> "TemplateBuilder" +``` + +Skip cache for all subsequent build instructions from this point. + +Call this before any instruction to force it and all following layers +to be rebuilt, ignoring any cached layers. + +**Returns**: + +`TemplateBuilder` class +Example +```python +template.skip_cache().run_cmd('apt-get update') +``` + + + +### set\_start\_cmd + +```python +def set_start_cmd(start_cmd: str, + ready_cmd: Union[str, ReadyCmd]) -> "TemplateFinal" +``` + +Set the command to start when the sandbox launches and the ready check command. + +**Arguments**: + +- `start_cmd`: Command to run when the sandbox starts +- `ready_cmd`: Command or ReadyCmd to check if the sandbox is ready + +**Returns**: + +`TemplateFinal` class +Example +```python +template.set_start_cmd( + 'python app.py', + 'curl http://localhost:8000/health' +) + +from e2b import wait_for_port, wait_for_url + +template.set_start_cmd( + 'python -m http.server 8000', + wait_for_port(8000) +) + +template.set_start_cmd( + 'npm start', + wait_for_url('http://localhost:3000/health', 200) +) +``` + + + +### set\_ready\_cmd + +```python +def set_ready_cmd(ready_cmd: Union[str, ReadyCmd]) -> "TemplateFinal" +``` + +Set the command to check if the sandbox is ready. + +**Arguments**: + +- `ready_cmd`: Command or ReadyCmd to check if the sandbox is ready + +**Returns**: + +`TemplateFinal` class +Example +```python +template.set_ready_cmd('curl http://localhost:8000/health') + +from e2b import wait_for_port, wait_for_file, wait_for_process + +template.set_ready_cmd(wait_for_port(3000)) + +template.set_ready_cmd(wait_for_file('/tmp/ready')) + +template.set_ready_cmd(wait_for_process('nginx')) +``` + + + +## TemplateFinal + +```python +class TemplateFinal() +``` + +Final template state after start/ready commands are set. + + + +## TemplateBase + +```python +class TemplateBase() +``` + +Base class for building E2B sandbox templates. + + + +### \_\_init\_\_ + +```python +def __init__(file_context_path: Optional[Union[str, Path]] = None, + file_ignore_patterns: Optional[List[str]] = None) +``` + +Create a new template builder instance. + +**Arguments**: + +- `file_context_path`: Base path for resolving relative file paths in copy operations +- `file_ignore_patterns`: List of glob patterns to ignore when copying files + + + +### skip\_cache + +```python +def skip_cache() -> "TemplateBase" +``` + +Skip cache for all subsequent build instructions from this point. + +**Returns**: + +`TemplateBase` class +Example +```python +template.skip_cache().from_python_image('3.11') +``` + + + +### from\_debian\_image + +```python +def from_debian_image(variant: str = "stable") -> TemplateBuilder +``` + +Start template from a Debian base image. + +**Arguments**: + +- `variant`: Debian image variant + +**Returns**: + +`TemplateBuilder` class +Example +```python +Template().from_debian_image('bookworm') +``` + + + +### from\_ubuntu\_image + +```python +def from_ubuntu_image(variant: str = "latest") -> TemplateBuilder +``` + +Start template from an Ubuntu base image. + +**Arguments**: + +- `variant`: Ubuntu image variant (default: 'latest') + +**Returns**: + +`TemplateBuilder` class +Example +```python +Template().from_ubuntu_image('24.04') +``` + + + +### from\_python\_image + +```python +def from_python_image(version: str = "3") -> TemplateBuilder +``` + +Start template from a Python base image. + +**Arguments**: + +- `version`: Python version (default: '3') + +**Returns**: + +`TemplateBuilder` class +Example +```python +Template().from_python_image('3') +``` + + + +### from\_node\_image + +```python +def from_node_image(variant: str = "lts") -> TemplateBuilder +``` + +Start template from a Node.js base image. + +**Arguments**: + +- `variant`: Node.js image variant (default: 'lts') + +**Returns**: + +`TemplateBuilder` class +Example +```python +Template().from_node_image('24') +``` + + + +### from\_bun\_image + +```python +def from_bun_image(variant: str = "latest") -> TemplateBuilder +``` + +Start template from a Bun base image. + +**Arguments**: + +- `variant`: Bun image variant (default: 'latest') + +**Returns**: + +`TemplateBuilder` class + + + +### from\_base\_image + +```python +def from_base_image() -> TemplateBuilder +``` + +Start template from the E2B base image (e2bdev/base:latest). + +**Returns**: + +`TemplateBuilder` class +Example +```python +Template().from_base_image() +``` + + + +### from\_image + +```python +def from_image(image: str, + username: Optional[str] = None, + password: Optional[str] = None) -> TemplateBuilder +``` + +Start template from a Docker image. + +**Arguments**: + +- `image`: Docker image name (e.g., 'ubuntu:24.04') +- `username`: Username for private registry authentication +- `password`: Password for private registry authentication + +**Returns**: + +`TemplateBuilder` class +Example +```python +Template().from_image('python:3') + +Template().from_image('myregistry.com/myimage:latest', username='user', password='pass') +``` + + + +### from\_template + +```python +def from_template(template: str) -> TemplateBuilder +``` + +Start template from an existing E2B template. + +**Arguments**: + +- `template`: E2B template ID or alias + +**Returns**: + +`TemplateBuilder` class +Example +```python +Template().from_template('my-base-template') +``` + + + +### from\_dockerfile + +```python +def from_dockerfile(dockerfile_content_or_path: str) -> TemplateBuilder +``` + +Parse a Dockerfile and convert it to Template SDK format. + +**Arguments**: + +- `dockerfile_content_or_path`: Either the Dockerfile content as a string, or a path to a Dockerfile file + +**Returns**: + +`TemplateBuilder` class +Example +```python +Template().from_dockerfile('Dockerfile') +Template().from_dockerfile('FROM python:3\nRUN pip install numpy') +``` + + + +### from\_aws\_registry + +```python +def from_aws_registry(image: str, access_key_id: str, secret_access_key: str, + region: str) -> TemplateBuilder +``` + +Start template from an AWS ECR registry image. + +**Arguments**: + +- `image`: Docker image name from AWS ECR +- `access_key_id`: AWS access key ID +- `secret_access_key`: AWS secret access key +- `region`: AWS region + +**Returns**: + +`TemplateBuilder` class +Example +```python +Template().from_aws_registry( + '123456789.dkr.ecr.us-west-2.amazonaws.com/myimage:latest', + access_key_id='AKIA...', + secret_access_key='...', + region='us-west-2' +) +``` + + + +### from\_gcp\_registry + +```python +def from_gcp_registry( + image: str, service_account_json: Union[str, dict]) -> TemplateBuilder +``` + +Start template from a GCP Artifact Registry or Container Registry image. + +**Arguments**: + +- `image`: Docker image name from GCP registry +- `service_account_json`: Service account JSON string, dict, or path to JSON file + +**Returns**: + +`TemplateBuilder` class +Example +```python +Template().from_gcp_registry( + 'gcr.io/myproject/myimage:latest', + service_account_json='path/to/service-account.json' +) +``` + + + +### to\_json + +```python +@staticmethod +def to_json(template: "TemplateClass") -> str +``` + +Convert a template to JSON representation. + +**Arguments**: + +- `template`: The template to convert (TemplateBuilder or TemplateFinal instance) + +**Returns**: + +JSON string representation of the template +Example +```python +template = Template().from_python_image('3').copy('app.py', '/app/') +json_str = TemplateBase.to_json(template) +``` + + + +### to\_dockerfile + +```python +@staticmethod +def to_dockerfile(template: "TemplateClass") -> str +``` + +Convert a template to Dockerfile format. + +Note: Templates based on other E2B templates cannot be converted to Dockerfile. + +**Arguments**: + +- `template`: The template to convert (TemplateBuilder or TemplateFinal instance) + +**Raises**: + +- `ValueError`: If the template is based on another E2B template or has no base image +Example +```python +template = Template().from_python_image('3').copy('app.py', '/app/') +dockerfile = TemplateBase.to_dockerfile(template) +``` + +**Returns**: + +Dockerfile string representation diff --git a/docs/sdk-reference/python-sdk/v2.9.0/template_async.mdx b/docs/sdk-reference/python-sdk/v2.9.0/template_async.mdx new file mode 100644 index 0000000..950d066 --- /dev/null +++ b/docs/sdk-reference/python-sdk/v2.9.0/template_async.mdx @@ -0,0 +1,150 @@ +--- +sidebarTitle: "Template Async" +mode: "center" +--- + + + + + + + + + +## AsyncTemplate + +```python +class AsyncTemplate(TemplateBase) +``` + +Asynchronous template builder for E2B sandboxes. + + + +### build + +```python +@staticmethod +async def build(template: TemplateClass, + alias: str, + cpu_count: int = 2, + memory_mb: int = 1024, + skip_cache: bool = False, + on_build_logs: Optional[Callable[[LogEntry], None]] = None, + api_key: Optional[str] = None, + domain: Optional[str] = None) -> BuildInfo +``` + +Build and deploy a template to E2B infrastructure. + +**Arguments**: + +- `template`: The template to build +- `alias`: Alias name for the template +- `cpu_count`: Number of CPUs allocated to the sandbox +- `memory_mb`: Amount of memory in MB allocated to the sandbox +- `skip_cache`: If True, forces a complete rebuild ignoring cache +- `on_build_logs`: Callback function to receive build logs during the build process +- `api_key`: E2B API key for authentication +- `domain`: Domain of the E2B API +Example +```python +from e2b import AsyncTemplate + +template = ( + AsyncTemplate() + .from_python_image('3') + .copy('requirements.txt', '/home/user/') + .run_cmd('pip install -r /home/user/requirements.txt') +) + +await AsyncTemplate.build( + template, + alias='my-python-env', + cpu_count=2, + memory_mb=1024 +) +``` + + + +### build\_in\_background + +```python +@staticmethod +async def build_in_background(template: TemplateClass, + alias: str, + cpu_count: int = 2, + memory_mb: int = 1024, + skip_cache: bool = False, + on_build_logs: Optional[Callable[[LogEntry], + None]] = None, + api_key: Optional[str] = None, + domain: Optional[str] = None) -> BuildInfo +``` + +Build and deploy a template to E2B infrastructure without waiting for completion. + +**Arguments**: + +- `template`: The template to build +- `alias`: Alias name for the template +- `cpu_count`: Number of CPUs allocated to the sandbox +- `memory_mb`: Amount of memory in MB allocated to the sandbox +- `skip_cache`: If True, forces a complete rebuild ignoring cache +- `api_key`: E2B API key for authentication +- `domain`: Domain of the E2B API + +**Returns**: + +BuildInfo containing the template ID and build ID +Example +```python +from e2b import AsyncTemplate + +template = ( + AsyncTemplate() + .from_python_image('3') + .run_cmd('echo "test"') + .set_start_cmd('echo "Hello"', 'sleep 1') +) + +build_info = await AsyncTemplate.build_in_background( + template, + alias='my-python-env', + cpu_count=2, + memory_mb=1024 +) +``` + + + +### get\_build\_status + +```python +@staticmethod +async def get_build_status(build_info: BuildInfo, + logs_offset: int = 0, + api_key: Optional[str] = None, + domain: Optional[str] = None) +``` + +Get the status of a build. + +**Arguments**: + +- `build_info`: Build identifiers returned from build_in_background +- `logs_offset`: Offset for fetching logs +- `api_key`: E2B API key for authentication +- `domain`: Domain of the E2B API + +**Returns**: + +TemplateBuild containing the build status and logs +Example +```python +from e2b import AsyncTemplate + +build_info = await AsyncTemplate.build_in_background(template, alias='my-template') +status = await AsyncTemplate.get_build_status(build_info, logs_offset=0) +``` diff --git a/docs/sdk-reference/python-sdk/v2.9.0/template_sync.mdx b/docs/sdk-reference/python-sdk/v2.9.0/template_sync.mdx new file mode 100644 index 0000000..6387438 --- /dev/null +++ b/docs/sdk-reference/python-sdk/v2.9.0/template_sync.mdx @@ -0,0 +1,150 @@ +--- +sidebarTitle: "Template Sync" +mode: "center" +--- + + + + + + + + + +## Template + +```python +class Template(TemplateBase) +``` + +Synchronous template builder for E2B sandboxes. + + + +### build + +```python +@staticmethod +def build(template: TemplateClass, + alias: str, + cpu_count: int = 2, + memory_mb: int = 1024, + skip_cache: bool = False, + on_build_logs: Optional[Callable[[LogEntry], None]] = None, + api_key: Optional[str] = None, + domain: Optional[str] = None) -> BuildInfo +``` + +Build and deploy a template to E2B infrastructure. + +**Arguments**: + +- `template`: The template to build +- `alias`: Alias name for the template +- `cpu_count`: Number of CPUs allocated to the sandbox +- `memory_mb`: Amount of memory in MB allocated to the sandbox +- `skip_cache`: If True, forces a complete rebuild ignoring cache +- `on_build_logs`: Callback function to receive build logs during the build process +- `api_key`: E2B API key for authentication +- `domain`: Domain of the E2B API +Example +```python +from e2b import Template + +template = ( + Template() + .from_python_image('3') + .copy('requirements.txt', '/home/user/') + .run_cmd('pip install -r /home/user/requirements.txt') +) + +Template.build( + template, + alias='my-python-env', + cpu_count=2, + memory_mb=1024 +) +``` + + + +### build\_in\_background + +```python +@staticmethod +def build_in_background(template: TemplateClass, + alias: str, + cpu_count: int = 2, + memory_mb: int = 1024, + skip_cache: bool = False, + on_build_logs: Optional[Callable[[LogEntry], + None]] = None, + api_key: Optional[str] = None, + domain: Optional[str] = None) -> BuildInfo +``` + +Build and deploy a template to E2B infrastructure without waiting for completion. + +**Arguments**: + +- `template`: The template to build +- `alias`: Alias name for the template +- `cpu_count`: Number of CPUs allocated to the sandbox +- `memory_mb`: Amount of memory in MB allocated to the sandbox +- `skip_cache`: If True, forces a complete rebuild ignoring cache +- `api_key`: E2B API key for authentication +- `domain`: Domain of the E2B API + +**Returns**: + +BuildInfo containing the template ID and build ID +Example +```python +from e2b import Template + +template = ( + Template() + .from_python_image('3') + .run_cmd('echo "test"') + .set_start_cmd('echo "Hello"', 'sleep 1') +) + +build_info = Template.build_in_background( + template, + alias='my-python-env', + cpu_count=2, + memory_mb=1024 +) +``` + + + +### get\_build\_status + +```python +@staticmethod +def get_build_status(build_info: BuildInfo, + logs_offset: int = 0, + api_key: Optional[str] = None, + domain: Optional[str] = None) +``` + +Get the status of a build. + +**Arguments**: + +- `build_info`: Build identifiers returned from build_in_background +- `logs_offset`: Offset for fetching logs +- `api_key`: E2B API key for authentication +- `domain`: Domain of the E2B API + +**Returns**: + +TemplateBuild containing the build status and logs +Example +```python +from e2b import Template + +build_info = Template.build_in_background(template, alias='my-template') +status = Template.get_build_status(build_info, logs_offset=0) +``` diff --git a/sdk-reference-generator/src/lib/files.ts b/sdk-reference-generator/src/lib/files.ts index f00372b..0ae9e3f 100644 --- a/sdk-reference-generator/src/lib/files.ts +++ b/sdk-reference-generator/src/lib/files.ts @@ -93,7 +93,7 @@ async function flattenNestedFiles(refDir: string): Promise { log.warn(`Detected ${collisions.length} filename collision(s):`, 1); collisions.forEach((c) => log.data(c, 2)); } -} + } async function removeEmptyDirectories(refDir: string): Promise { const dirs = await glob("**/", { cwd: refDir }); @@ -106,7 +106,7 @@ async function removeEmptyDirectories(refDir: string): Promise { } } catch {} } -} + } async function convertMdToMdx(refDir: string): Promise { const mdFiles = await glob("*.md", { cwd: refDir }); @@ -123,7 +123,7 @@ async function convertMdToMdx(refDir: string): Promise { await fs.writeFile(mdxPath, createFrontmatter(title) + content); await fs.remove(fullPath); } -} + } async function ensureFrontmatter(refDir: string): Promise { const mdxFiles = await glob(`*${CONSTANTS.MDX_EXTENSION}`, { cwd: refDir }); From 9b940a6b4d1b66577dbb26c8298af526bf36cb8c Mon Sep 17 00:00:00 2001 From: ben-fornefeld Date: Sat, 10 Jan 2026 18:51:15 +0100 Subject: [PATCH 20/39] reactive TOC --- sdk-reference-generator/src/lib/utils.ts | 1 - 1 file changed, 1 deletion(-) diff --git a/sdk-reference-generator/src/lib/utils.ts b/sdk-reference-generator/src/lib/utils.ts index ee8f112..58a0eda 100644 --- a/sdk-reference-generator/src/lib/utils.ts +++ b/sdk-reference-generator/src/lib/utils.ts @@ -27,7 +27,6 @@ export function sortVersionsDescending(versions: string[]): string[] { export function createFrontmatter(title: string): string { return `--- sidebarTitle: "${title}" -mode: "center" --- `; From 1dfbd1bf160875967af588931473afd52abe30b9 Mon Sep 17 00:00:00 2001 From: ben-fornefeld Date: Mon, 12 Jan 2026 12:48:01 +0100 Subject: [PATCH 21/39] refactor: enhance SDK reference generation workflow --- .github/workflows/sdk-reference-sync.yml | 39 ++++++++++++++++-------- sdk-reference-generator/README.md | 37 +++++++++++++++++++++- 2 files changed, 62 insertions(+), 14 deletions(-) diff --git a/.github/workflows/sdk-reference-sync.yml b/.github/workflows/sdk-reference-sync.yml index 8b02db6..b2f5906 100644 --- a/.github/workflows/sdk-reference-sync.yml +++ b/.github/workflows/sdk-reference-sync.yml @@ -58,15 +58,19 @@ jobs: - name: Determine SDK and Version id: params + env: + EVENT_NAME: ${{ github.event_name }} + INPUT_SDK: ${{ github.event.inputs.sdk }} + INPUT_VERSION: ${{ github.event.inputs.version }} + PAYLOAD_SDK: ${{ github.event.client_payload.sdk }} + PAYLOAD_VERSION: ${{ github.event.client_payload.version }} run: | - if [[ "${{ github.event_name }}" == "workflow_dispatch" ]]; then - SDK="${{ github.event.inputs.sdk }}" - VERSION="${{ github.event.inputs.version }}" - elif [[ "${{ github.event_name }}" == "repository_dispatch" ]]; then - SDK="${{ github.event.client_payload.sdk }}" - # on repository_dispatch, default to "all" to auto-detect missing versions - VERSION="${{ github.event.client_payload.version }}" - VERSION="${VERSION:-all}" + if [[ "$EVENT_NAME" == "workflow_dispatch" ]]; then + SDK="$INPUT_SDK" + VERSION="$INPUT_VERSION" + elif [[ "$EVENT_NAME" == "repository_dispatch" ]]; then + SDK="$PAYLOAD_SDK" + VERSION="${PAYLOAD_VERSION:-all}" fi echo "sdk=${SDK:-all}" >> $GITHUB_OUTPUT @@ -74,10 +78,13 @@ jobs: - name: Generate SDK Reference working-directory: sdk-reference-generator + env: + SDK_NAME: ${{ steps.params.outputs.sdk }} + SDK_VERSION: ${{ steps.params.outputs.version }} run: | pnpm run generate \ - --sdk "${{ steps.params.outputs.sdk }}" \ - --version "${{ steps.params.outputs.version }}" + --sdk "$SDK_NAME" \ + --version "$SDK_VERSION" - name: Verify generated files run: | @@ -85,6 +92,9 @@ jobs: find docs/sdk-reference -type f -name "*.mdx" 2>/dev/null | head -20 || echo "No MDX files found" - name: Commit and push changes + env: + SDK_NAME: ${{ steps.params.outputs.sdk }} + SDK_VERSION: ${{ steps.params.outputs.version }} run: | git config user.name "github-actions[bot]" git config user.email "github-actions[bot]@users.noreply.github.com" @@ -95,16 +105,19 @@ jobs: if git diff --staged --quiet; then echo "No changes to commit" else - git commit -m "[skip ci] Update SDK reference: ${{ steps.params.outputs.sdk }} ${{ steps.params.outputs.version }}" + git commit -m "[skip ci] Update SDK reference: $SDK_NAME $SDK_VERSION" git push fi - name: Summary + env: + SDK_NAME: ${{ steps.params.outputs.sdk }} + SDK_VERSION: ${{ steps.params.outputs.version }} run: | echo "## SDK Reference Generation Complete" >> $GITHUB_STEP_SUMMARY echo "" >> $GITHUB_STEP_SUMMARY - echo "- **SDK**: ${{ steps.params.outputs.sdk }}" >> $GITHUB_STEP_SUMMARY - echo "- **Version**: ${{ steps.params.outputs.version }}" >> $GITHUB_STEP_SUMMARY + echo "- **SDK**: $SDK_NAME" >> $GITHUB_STEP_SUMMARY + echo "- **Version**: $SDK_VERSION" >> $GITHUB_STEP_SUMMARY echo "" >> $GITHUB_STEP_SUMMARY echo "### Generated Files" >> $GITHUB_STEP_SUMMARY echo '```' >> $GITHUB_STEP_SUMMARY diff --git a/sdk-reference-generator/README.md b/sdk-reference-generator/README.md index 792ef07..790626a 100644 --- a/sdk-reference-generator/README.md +++ b/sdk-reference-generator/README.md @@ -139,11 +139,46 @@ The generator runs in GitHub Actions on: - Manual workflow dispatch - Automatic repository dispatch from SDK repos on release -Safety features: +### Manual Trigger (GitHub UI) + +1. Go to **Actions** → **Sync SDK Reference Documentation** +2. Click **Run workflow** +3. Fill in: + - **SDK**: `all`, or specific SDK key (e.g., `js-sdk`, `python-sdk`, `cli`) + - **Version**: `all`, `latest`, or specific version (e.g., `v2.9.0`) + +### Manual Trigger (GitHub CLI) + +```bash +# generate all SDKs, all versions +gh workflow run sdk-reference-sync.yml -f sdk=all -f version=all + +# generate specific SDK, latest version +gh workflow run sdk-reference-sync.yml -f sdk=js-sdk -f version=latest + +# generate specific version +gh workflow run sdk-reference-sync.yml -f sdk=python-sdk -f version=v2.8.0 +``` + +### Repository Dispatch (from SDK repos) + +SDK repositories can trigger doc generation on release: + +```bash +curl -X POST \ + -H "Authorization: token $GITHUB_TOKEN" \ + -H "Accept: application/vnd.github.v3+json" \ + https://api.github.com/repos/e2b-dev/docs/dispatches \ + -d '{"event_type": "sdk-release", "client_payload": {"sdk": "js-sdk", "version": "v2.9.0"}}' +``` + +### Safety Features + - Validates all generated files before committing - Only commits if changes detected - Skips CI on doc updates (`[skip ci]` in commit message) - Full logging visible in workflow runs +- User inputs passed via environment variables (prevents script injection) ## Performance From 6bfbc7d9b9d6e6cd751ef79492344395185b18f3 Mon Sep 17 00:00:00 2001 From: ben-fornefeld Date: Mon, 12 Jan 2026 12:50:41 +0100 Subject: [PATCH 22/39] fix: pip install fallback --- sdk-reference-generator/src/generator.ts | 16 +++++++----- .../src/generators/pydoc.ts | 18 ++++++++++--- sdk-reference-generator/src/lib/install.ts | 25 ++++++++++--------- sdk-reference-generator/src/types.ts | 4 +++ 4 files changed, 41 insertions(+), 22 deletions(-) diff --git a/sdk-reference-generator/src/generator.ts b/sdk-reference-generator/src/generator.ts index 04aebb0..6a5eed9 100644 --- a/sdk-reference-generator/src/generator.ts +++ b/sdk-reference-generator/src/generator.ts @@ -60,15 +60,19 @@ async function generateVersion( const sdkRefDir = path.join(sdkDir, CONSTANTS.SDK_REF_DIR); await fs.remove(sdkRefDir); - await installDependencies(sdkDir, config.generator); - + const installResult = await installDependencies(sdkDir, config.generator); + let generatedDocsDir: string; switch (config.generator) { case "typedoc": generatedDocsDir = await generateTypedoc(sdkDir, context.configsDir); break; case "pydoc": - generatedDocsDir = await generatePydoc(sdkDir, config.allowedPackages); + generatedDocsDir = await generatePydoc( + sdkDir, + config.allowedPackages, + installResult.usePoetryRun + ); break; case "cli": generatedDocsDir = await generateCli(sdkDir); @@ -268,13 +272,13 @@ function handleGenerationFailures( const shouldAbort = config.required || generated === 0; if (shouldAbort) { - log.blank(); + log.blank(); const reason = config.required ? "Required SDK has failures" : "All versions failed"; log.error(`WORKFLOW ABORTED: ${reason}`, 1); - log.error(`Failed: ${failedVersions.join(" ")}`, 1); - process.exit(1); + log.error(`Failed: ${failedVersions.join(" ")}`, 1); + process.exit(1); } } diff --git a/sdk-reference-generator/src/generators/pydoc.ts b/sdk-reference-generator/src/generators/pydoc.ts index 0e10258..75f0e51 100644 --- a/sdk-reference-generator/src/generators/pydoc.ts +++ b/sdk-reference-generator/src/generators/pydoc.ts @@ -18,7 +18,11 @@ async function processMdx(file: string): Promise { await fs.writeFile(file, content); } -async function processPackage(pkg: string, sdkDir: string): Promise { +async function processPackage( + pkg: string, + sdkDir: string, + usePoetryRun: boolean +): Promise { const rawName = pkg.split(".").pop() || pkg; const name = rawName.replace(/^e2b_/, ""); @@ -31,7 +35,12 @@ async function processPackage(pkg: string, sdkDir: string): Promise { ); try { - const result = await execa("poetry", ["run", "pydoc-markdown", "-p", pkg], { + const cmd = usePoetryRun ? "poetry" : "pydoc-markdown"; + const args = usePoetryRun + ? ["run", "pydoc-markdown", "-p", pkg] + : ["-p", pkg]; + + const result = await execa(cmd, args, { cwd: sdkDir, stdio: "pipe", }); @@ -63,7 +72,8 @@ async function processPackage(pkg: string, sdkDir: string): Promise { export async function generatePydoc( sdkDir: string, - allowedPackages: readonly string[] + allowedPackages: readonly string[], + usePoetryRun: boolean ): Promise { const outputDir = path.join(sdkDir, CONSTANTS.SDK_REF_DIR); await fs.ensureDir(outputDir); @@ -75,7 +85,7 @@ export async function generatePydoc( let successful = 0; for (const pkg of allowedPackages) { - const result = await processPackage(pkg, sdkDir); + const result = await processPackage(pkg, sdkDir, usePoetryRun); if (result) successful++; } diff --git a/sdk-reference-generator/src/lib/install.ts b/sdk-reference-generator/src/lib/install.ts index b6b2ee0..4a82342 100644 --- a/sdk-reference-generator/src/lib/install.ts +++ b/sdk-reference-generator/src/lib/install.ts @@ -1,11 +1,11 @@ import { execa } from "execa"; -import type { GeneratorType } from "../types.js"; +import type { GeneratorType, InstallResult } from "../types.js"; import { log } from "./log.js"; export async function installDependencies( sdkDir: string, generator: GeneratorType -): Promise { +): Promise { log.info("Installing dependencies...", 1); switch (generator) { @@ -23,16 +23,16 @@ export async function installDependencies( }); } catch { log.warn("pnpm failed, falling back to npm...", 1); - await execa( - "npm", - ["install", "--legacy-peer-deps", "--force", "--prefer-offline"], - { - cwd: sdkDir, - stdio: "inherit", - } - ); + await execa( + "npm", + ["install", "--legacy-peer-deps", "--force", "--prefer-offline"], + { + cwd: sdkDir, + stdio: "inherit", + } + ); } - break; + return { usePoetryRun: false }; } case "pydoc": { @@ -41,6 +41,7 @@ export async function installDependencies( cwd: sdkDir, stdio: "inherit", }); + return { usePoetryRun: true }; } catch { log.warn("poetry failed, using global pydoc-markdown...", 1); await execa( @@ -51,8 +52,8 @@ export async function installDependencies( stdio: "inherit", } ); + return { usePoetryRun: false }; } - break; } } } diff --git a/sdk-reference-generator/src/types.ts b/sdk-reference-generator/src/types.ts index 2953b1e..a2d636e 100644 --- a/sdk-reference-generator/src/types.ts +++ b/sdk-reference-generator/src/types.ts @@ -45,6 +45,10 @@ export interface GenerationResult { failedVersions: string[]; } +export interface InstallResult { + usePoetryRun: boolean; +} + export interface NavigationVersion { version: string; default: boolean; From 804758a69fa700283e7e3054d30219ef627de9be Mon Sep 17 00:00:00 2001 From: ben-fornefeld Date: Mon, 12 Jan 2026 12:53:21 +0100 Subject: [PATCH 23/39] fix: update SDK documentation for clarity and accuracy --- .../sdk-reference-generator-test.yml | 37 +++++++++++++++++++ 1 file changed, 37 insertions(+) create mode 100644 .github/workflows/sdk-reference-generator-test.yml diff --git a/.github/workflows/sdk-reference-generator-test.yml b/.github/workflows/sdk-reference-generator-test.yml new file mode 100644 index 0000000..020b2c2 --- /dev/null +++ b/.github/workflows/sdk-reference-generator-test.yml @@ -0,0 +1,37 @@ +name: Test SDK Reference Generator + +on: + pull_request: + paths: + - 'sdk-reference-generator/**' + +jobs: + test: + runs-on: ubuntu-latest + + steps: + - name: Checkout + uses: actions/checkout@v4 + + - name: Setup Node.js + uses: actions/setup-node@v4 + with: + node-version: "20" + + - name: Install pnpm + uses: pnpm/action-setup@v4 + with: + version: 9 + + - name: Install dependencies + working-directory: sdk-reference-generator + run: pnpm install --frozen-lockfile + + - name: Run tests + working-directory: sdk-reference-generator + run: pnpm test + + - name: TypeScript check + working-directory: sdk-reference-generator + run: npx tsc --noEmit + From 13ef59c3796d77857381f16b4d226c17ae537dc0 Mon Sep 17 00:00:00 2001 From: ben-fornefeld Date: Mon, 12 Jan 2026 13:08:06 +0100 Subject: [PATCH 24/39] remove: generated sdk reference --- .../sdk-reference-generator-test.yml | 63 +- docs/sdk-reference/cli/1.0.0/auth.mdx | 63 - docs/sdk-reference/cli/1.0.0/sandbox.mdx | 94 - docs/sdk-reference/cli/1.0.0/template.mdx | 95 - docs/sdk-reference/cli/v2.3.3/auth.mdx | 63 - docs/sdk-reference/cli/v2.3.3/sandbox.mdx | 140 -- docs/sdk-reference/cli/v2.3.3/template.mdx | 185 -- docs/sdk-reference/cli/v2.4.0/auth.mdx | 63 - docs/sdk-reference/cli/v2.4.0/sandbox.mdx | 140 -- docs/sdk-reference/cli/v2.4.0/template.mdx | 185 -- docs/sdk-reference/cli/v2.4.1/auth.mdx | 63 - docs/sdk-reference/cli/v2.4.1/sandbox.mdx | 140 -- docs/sdk-reference/cli/v2.4.1/template.mdx | 185 -- docs/sdk-reference/cli/v2.4.2/auth.mdx | 63 - docs/sdk-reference/cli/v2.4.2/sandbox.mdx | 140 -- docs/sdk-reference/cli/v2.4.2/template.mdx | 185 -- .../code-interpreter-js-sdk/v2.3.0/charts.mdx | 245 -- .../code-interpreter-js-sdk/v2.3.0/consts.mdx | 18 - .../v2.3.0/messaging.mdx | 331 --- .../v2.3.0/sandbox.mdx | 371 --- .../code-interpreter-js-sdk/v2.3.1/charts.mdx | 245 -- .../code-interpreter-js-sdk/v2.3.1/consts.mdx | 18 - .../v2.3.1/messaging.mdx | 331 --- .../v2.3.1/sandbox.mdx | 371 --- .../code-interpreter-js-sdk/v2.3.2/charts.mdx | 245 -- .../code-interpreter-js-sdk/v2.3.2/consts.mdx | 18 - .../v2.3.2/messaging.mdx | 331 --- .../v2.3.2/sandbox.mdx | 371 --- .../code-interpreter-js-sdk/v2.3.3/charts.mdx | 245 -- .../code-interpreter-js-sdk/v2.3.3/consts.mdx | 18 - .../v2.3.3/messaging.mdx | 331 --- .../v2.3.3/sandbox.mdx | 371 --- .../1.0.1/code_interpreter.mdx | 786 ------- .../1.0.4/code_interpreter.mdx | 786 ------- .../v2.2.1/code_interpreter.mdx | 789 ------- .../v2.3.0/code_interpreter.mdx | 789 ------- .../v2.4.0/code_interpreter.mdx | 889 ------- .../v2.4.1/code_interpreter.mdx | 889 ------- .../desktop-js-sdk/v2.1.0/sandbox.mdx | 697 ------ .../desktop-js-sdk/v2.2.0/sandbox.mdx | 697 ------ .../desktop-js-sdk/v2.2.1/sandbox.mdx | 697 ------ .../desktop-js-sdk/v2.2.2/sandbox.mdx | 697 ------ .../desktop-python-sdk/v2.0.0/desktop.mdx | 371 --- .../desktop-python-sdk/v2.0.1/desktop.mdx | 371 --- .../desktop-python-sdk/v2.1.0/desktop.mdx | 371 --- .../desktop-python-sdk/v2.2.0/desktop.mdx | 371 --- docs/sdk-reference/js-sdk/1.0.0/errors.mdx | 197 -- .../js-sdk/1.0.0/sandbox-filesystem.mdx | 521 ----- docs/sdk-reference/js-sdk/1.0.0/sandbox.mdx | 586 ----- docs/sdk-reference/js-sdk/v2.8.2/errors.mdx | 271 --- .../js-sdk/v2.8.2/sandbox-commands.mdx | 533 ----- .../js-sdk/v2.8.2/sandbox-filesystem.mdx | 627 ----- docs/sdk-reference/js-sdk/v2.8.2/sandbox.mdx | 712 ------ .../js-sdk/v2.8.2/template-logger.mdx | 196 -- .../js-sdk/v2.8.2/template-readycmd.mdx | 202 -- docs/sdk-reference/js-sdk/v2.8.2/template.mdx | 2042 ---------------- docs/sdk-reference/js-sdk/v2.8.3/errors.mdx | 271 --- .../js-sdk/v2.8.3/sandbox-commands.mdx | 533 ----- .../js-sdk/v2.8.3/sandbox-filesystem.mdx | 627 ----- docs/sdk-reference/js-sdk/v2.8.3/sandbox.mdx | 712 ------ .../js-sdk/v2.8.3/template-logger.mdx | 196 -- .../js-sdk/v2.8.3/template-readycmd.mdx | 202 -- docs/sdk-reference/js-sdk/v2.8.3/template.mdx | 2042 ---------------- docs/sdk-reference/js-sdk/v2.8.4/errors.mdx | 271 --- .../js-sdk/v2.8.4/sandbox-commands.mdx | 533 ----- .../js-sdk/v2.8.4/sandbox-filesystem.mdx | 627 ----- docs/sdk-reference/js-sdk/v2.8.4/sandbox.mdx | 712 ------ .../js-sdk/v2.8.4/template-logger.mdx | 196 -- .../js-sdk/v2.8.4/template-readycmd.mdx | 202 -- docs/sdk-reference/js-sdk/v2.8.4/template.mdx | 2042 ---------------- docs/sdk-reference/js-sdk/v2.9.0/errors.mdx | 271 --- .../js-sdk/v2.9.0/sandbox-commands.mdx | 554 ----- .../js-sdk/v2.9.0/sandbox-filesystem.mdx | 627 ----- docs/sdk-reference/js-sdk/v2.9.0/sandbox.mdx | 712 ------ .../js-sdk/v2.9.0/template-logger.mdx | 196 -- .../js-sdk/v2.9.0/template-readycmd.mdx | 202 -- docs/sdk-reference/js-sdk/v2.9.0/template.mdx | 2044 ----------------- .../python-sdk/1.0.0/exceptions.mdx | 87 - .../python-sdk/1.0.0/sandbox_async.mdx | 985 -------- .../python-sdk/1.0.0/sandbox_sync.mdx | 959 -------- .../python-sdk/v2.7.0/exceptions.mdx | 117 - .../python-sdk/v2.7.0/logger.mdx | 106 - .../python-sdk/v2.7.0/readycmd.mdx | 168 -- .../python-sdk/v2.7.0/sandbox_async.mdx | 1387 ----------- .../python-sdk/v2.7.0/sandbox_sync.mdx | 1343 ----------- .../python-sdk/v2.7.0/template.mdx | 1686 -------------- .../python-sdk/v2.7.0/template_async.mdx | 150 -- .../python-sdk/v2.7.0/template_sync.mdx | 150 -- .../python-sdk/v2.8.0/exceptions.mdx | 117 - .../python-sdk/v2.8.0/logger.mdx | 106 - .../python-sdk/v2.8.0/readycmd.mdx | 168 -- .../python-sdk/v2.8.0/sandbox_async.mdx | 1387 ----------- .../python-sdk/v2.8.0/sandbox_sync.mdx | 1343 ----------- .../python-sdk/v2.8.0/template.mdx | 1686 -------------- .../python-sdk/v2.8.0/template_async.mdx | 150 -- .../python-sdk/v2.8.0/template_sync.mdx | 150 -- .../python-sdk/v2.8.1/exceptions.mdx | 117 - .../python-sdk/v2.8.1/logger.mdx | 106 - .../python-sdk/v2.8.1/readycmd.mdx | 168 -- .../python-sdk/v2.8.1/sandbox_async.mdx | 1387 ----------- .../python-sdk/v2.8.1/sandbox_sync.mdx | 1343 ----------- .../python-sdk/v2.8.1/template.mdx | 1704 -------------- .../python-sdk/v2.8.1/template_async.mdx | 150 -- .../python-sdk/v2.8.1/template_sync.mdx | 150 -- .../python-sdk/v2.9.0/exceptions.mdx | 117 - .../python-sdk/v2.9.0/logger.mdx | 106 - .../python-sdk/v2.9.0/readycmd.mdx | 168 -- .../python-sdk/v2.9.0/sandbox_async.mdx | 1412 ------------ .../python-sdk/v2.9.0/sandbox_sync.mdx | 1365 ----------- .../python-sdk/v2.9.0/template.mdx | 1706 -------------- .../python-sdk/v2.9.0/template_async.mdx | 150 -- .../python-sdk/v2.9.0/template_sync.mdx | 150 -- 112 files changed, 31 insertions(+), 57099 deletions(-) delete mode 100644 docs/sdk-reference/cli/1.0.0/auth.mdx delete mode 100644 docs/sdk-reference/cli/1.0.0/sandbox.mdx delete mode 100644 docs/sdk-reference/cli/1.0.0/template.mdx delete mode 100644 docs/sdk-reference/cli/v2.3.3/auth.mdx delete mode 100644 docs/sdk-reference/cli/v2.3.3/sandbox.mdx delete mode 100644 docs/sdk-reference/cli/v2.3.3/template.mdx delete mode 100644 docs/sdk-reference/cli/v2.4.0/auth.mdx delete mode 100644 docs/sdk-reference/cli/v2.4.0/sandbox.mdx delete mode 100644 docs/sdk-reference/cli/v2.4.0/template.mdx delete mode 100644 docs/sdk-reference/cli/v2.4.1/auth.mdx delete mode 100644 docs/sdk-reference/cli/v2.4.1/sandbox.mdx delete mode 100644 docs/sdk-reference/cli/v2.4.1/template.mdx delete mode 100644 docs/sdk-reference/cli/v2.4.2/auth.mdx delete mode 100644 docs/sdk-reference/cli/v2.4.2/sandbox.mdx delete mode 100644 docs/sdk-reference/cli/v2.4.2/template.mdx delete mode 100644 docs/sdk-reference/code-interpreter-js-sdk/v2.3.0/charts.mdx delete mode 100644 docs/sdk-reference/code-interpreter-js-sdk/v2.3.0/consts.mdx delete mode 100644 docs/sdk-reference/code-interpreter-js-sdk/v2.3.0/messaging.mdx delete mode 100644 docs/sdk-reference/code-interpreter-js-sdk/v2.3.0/sandbox.mdx delete mode 100644 docs/sdk-reference/code-interpreter-js-sdk/v2.3.1/charts.mdx delete mode 100644 docs/sdk-reference/code-interpreter-js-sdk/v2.3.1/consts.mdx delete mode 100644 docs/sdk-reference/code-interpreter-js-sdk/v2.3.1/messaging.mdx delete mode 100644 docs/sdk-reference/code-interpreter-js-sdk/v2.3.1/sandbox.mdx delete mode 100644 docs/sdk-reference/code-interpreter-js-sdk/v2.3.2/charts.mdx delete mode 100644 docs/sdk-reference/code-interpreter-js-sdk/v2.3.2/consts.mdx delete mode 100644 docs/sdk-reference/code-interpreter-js-sdk/v2.3.2/messaging.mdx delete mode 100644 docs/sdk-reference/code-interpreter-js-sdk/v2.3.2/sandbox.mdx delete mode 100644 docs/sdk-reference/code-interpreter-js-sdk/v2.3.3/charts.mdx delete mode 100644 docs/sdk-reference/code-interpreter-js-sdk/v2.3.3/consts.mdx delete mode 100644 docs/sdk-reference/code-interpreter-js-sdk/v2.3.3/messaging.mdx delete mode 100644 docs/sdk-reference/code-interpreter-js-sdk/v2.3.3/sandbox.mdx delete mode 100644 docs/sdk-reference/code-interpreter-python-sdk/1.0.1/code_interpreter.mdx delete mode 100644 docs/sdk-reference/code-interpreter-python-sdk/1.0.4/code_interpreter.mdx delete mode 100644 docs/sdk-reference/code-interpreter-python-sdk/v2.2.1/code_interpreter.mdx delete mode 100644 docs/sdk-reference/code-interpreter-python-sdk/v2.3.0/code_interpreter.mdx delete mode 100644 docs/sdk-reference/code-interpreter-python-sdk/v2.4.0/code_interpreter.mdx delete mode 100644 docs/sdk-reference/code-interpreter-python-sdk/v2.4.1/code_interpreter.mdx delete mode 100644 docs/sdk-reference/desktop-js-sdk/v2.1.0/sandbox.mdx delete mode 100644 docs/sdk-reference/desktop-js-sdk/v2.2.0/sandbox.mdx delete mode 100644 docs/sdk-reference/desktop-js-sdk/v2.2.1/sandbox.mdx delete mode 100644 docs/sdk-reference/desktop-js-sdk/v2.2.2/sandbox.mdx delete mode 100644 docs/sdk-reference/desktop-python-sdk/v2.0.0/desktop.mdx delete mode 100644 docs/sdk-reference/desktop-python-sdk/v2.0.1/desktop.mdx delete mode 100644 docs/sdk-reference/desktop-python-sdk/v2.1.0/desktop.mdx delete mode 100644 docs/sdk-reference/desktop-python-sdk/v2.2.0/desktop.mdx delete mode 100644 docs/sdk-reference/js-sdk/1.0.0/errors.mdx delete mode 100644 docs/sdk-reference/js-sdk/1.0.0/sandbox-filesystem.mdx delete mode 100644 docs/sdk-reference/js-sdk/1.0.0/sandbox.mdx delete mode 100644 docs/sdk-reference/js-sdk/v2.8.2/errors.mdx delete mode 100644 docs/sdk-reference/js-sdk/v2.8.2/sandbox-commands.mdx delete mode 100644 docs/sdk-reference/js-sdk/v2.8.2/sandbox-filesystem.mdx delete mode 100644 docs/sdk-reference/js-sdk/v2.8.2/sandbox.mdx delete mode 100644 docs/sdk-reference/js-sdk/v2.8.2/template-logger.mdx delete mode 100644 docs/sdk-reference/js-sdk/v2.8.2/template-readycmd.mdx delete mode 100644 docs/sdk-reference/js-sdk/v2.8.2/template.mdx delete mode 100644 docs/sdk-reference/js-sdk/v2.8.3/errors.mdx delete mode 100644 docs/sdk-reference/js-sdk/v2.8.3/sandbox-commands.mdx delete mode 100644 docs/sdk-reference/js-sdk/v2.8.3/sandbox-filesystem.mdx delete mode 100644 docs/sdk-reference/js-sdk/v2.8.3/sandbox.mdx delete mode 100644 docs/sdk-reference/js-sdk/v2.8.3/template-logger.mdx delete mode 100644 docs/sdk-reference/js-sdk/v2.8.3/template-readycmd.mdx delete mode 100644 docs/sdk-reference/js-sdk/v2.8.3/template.mdx delete mode 100644 docs/sdk-reference/js-sdk/v2.8.4/errors.mdx delete mode 100644 docs/sdk-reference/js-sdk/v2.8.4/sandbox-commands.mdx delete mode 100644 docs/sdk-reference/js-sdk/v2.8.4/sandbox-filesystem.mdx delete mode 100644 docs/sdk-reference/js-sdk/v2.8.4/sandbox.mdx delete mode 100644 docs/sdk-reference/js-sdk/v2.8.4/template-logger.mdx delete mode 100644 docs/sdk-reference/js-sdk/v2.8.4/template-readycmd.mdx delete mode 100644 docs/sdk-reference/js-sdk/v2.8.4/template.mdx delete mode 100644 docs/sdk-reference/js-sdk/v2.9.0/errors.mdx delete mode 100644 docs/sdk-reference/js-sdk/v2.9.0/sandbox-commands.mdx delete mode 100644 docs/sdk-reference/js-sdk/v2.9.0/sandbox-filesystem.mdx delete mode 100644 docs/sdk-reference/js-sdk/v2.9.0/sandbox.mdx delete mode 100644 docs/sdk-reference/js-sdk/v2.9.0/template-logger.mdx delete mode 100644 docs/sdk-reference/js-sdk/v2.9.0/template-readycmd.mdx delete mode 100644 docs/sdk-reference/js-sdk/v2.9.0/template.mdx delete mode 100644 docs/sdk-reference/python-sdk/1.0.0/exceptions.mdx delete mode 100644 docs/sdk-reference/python-sdk/1.0.0/sandbox_async.mdx delete mode 100644 docs/sdk-reference/python-sdk/1.0.0/sandbox_sync.mdx delete mode 100644 docs/sdk-reference/python-sdk/v2.7.0/exceptions.mdx delete mode 100644 docs/sdk-reference/python-sdk/v2.7.0/logger.mdx delete mode 100644 docs/sdk-reference/python-sdk/v2.7.0/readycmd.mdx delete mode 100644 docs/sdk-reference/python-sdk/v2.7.0/sandbox_async.mdx delete mode 100644 docs/sdk-reference/python-sdk/v2.7.0/sandbox_sync.mdx delete mode 100644 docs/sdk-reference/python-sdk/v2.7.0/template.mdx delete mode 100644 docs/sdk-reference/python-sdk/v2.7.0/template_async.mdx delete mode 100644 docs/sdk-reference/python-sdk/v2.7.0/template_sync.mdx delete mode 100644 docs/sdk-reference/python-sdk/v2.8.0/exceptions.mdx delete mode 100644 docs/sdk-reference/python-sdk/v2.8.0/logger.mdx delete mode 100644 docs/sdk-reference/python-sdk/v2.8.0/readycmd.mdx delete mode 100644 docs/sdk-reference/python-sdk/v2.8.0/sandbox_async.mdx delete mode 100644 docs/sdk-reference/python-sdk/v2.8.0/sandbox_sync.mdx delete mode 100644 docs/sdk-reference/python-sdk/v2.8.0/template.mdx delete mode 100644 docs/sdk-reference/python-sdk/v2.8.0/template_async.mdx delete mode 100644 docs/sdk-reference/python-sdk/v2.8.0/template_sync.mdx delete mode 100644 docs/sdk-reference/python-sdk/v2.8.1/exceptions.mdx delete mode 100644 docs/sdk-reference/python-sdk/v2.8.1/logger.mdx delete mode 100644 docs/sdk-reference/python-sdk/v2.8.1/readycmd.mdx delete mode 100644 docs/sdk-reference/python-sdk/v2.8.1/sandbox_async.mdx delete mode 100644 docs/sdk-reference/python-sdk/v2.8.1/sandbox_sync.mdx delete mode 100644 docs/sdk-reference/python-sdk/v2.8.1/template.mdx delete mode 100644 docs/sdk-reference/python-sdk/v2.8.1/template_async.mdx delete mode 100644 docs/sdk-reference/python-sdk/v2.8.1/template_sync.mdx delete mode 100644 docs/sdk-reference/python-sdk/v2.9.0/exceptions.mdx delete mode 100644 docs/sdk-reference/python-sdk/v2.9.0/logger.mdx delete mode 100644 docs/sdk-reference/python-sdk/v2.9.0/readycmd.mdx delete mode 100644 docs/sdk-reference/python-sdk/v2.9.0/sandbox_async.mdx delete mode 100644 docs/sdk-reference/python-sdk/v2.9.0/sandbox_sync.mdx delete mode 100644 docs/sdk-reference/python-sdk/v2.9.0/template.mdx delete mode 100644 docs/sdk-reference/python-sdk/v2.9.0/template_async.mdx delete mode 100644 docs/sdk-reference/python-sdk/v2.9.0/template_sync.mdx diff --git a/.github/workflows/sdk-reference-generator-test.yml b/.github/workflows/sdk-reference-generator-test.yml index 020b2c2..b09b760 100644 --- a/.github/workflows/sdk-reference-generator-test.yml +++ b/.github/workflows/sdk-reference-generator-test.yml @@ -1,37 +1,36 @@ name: Test SDK Reference Generator on: - pull_request: - paths: - - 'sdk-reference-generator/**' + pull_request: + paths: + - "sdk-reference-generator/**" jobs: - test: - runs-on: ubuntu-latest - - steps: - - name: Checkout - uses: actions/checkout@v4 - - - name: Setup Node.js - uses: actions/setup-node@v4 - with: - node-version: "20" - - - name: Install pnpm - uses: pnpm/action-setup@v4 - with: - version: 9 - - - name: Install dependencies - working-directory: sdk-reference-generator - run: pnpm install --frozen-lockfile - - - name: Run tests - working-directory: sdk-reference-generator - run: pnpm test - - - name: TypeScript check - working-directory: sdk-reference-generator - run: npx tsc --noEmit - + test: + runs-on: ubuntu-latest + + steps: + - name: Checkout + uses: actions/checkout@v4 + + - name: Setup Node.js + uses: actions/setup-node@v4 + with: + node-version: "20" + + - name: Install pnpm + uses: pnpm/action-setup@v4 + with: + version: 9 + + - name: Install dependencies + working-directory: sdk-reference-generator + run: pnpm install --frozen-lockfile + + - name: Run tests + working-directory: sdk-reference-generator + run: pnpm test + + - name: TypeScript check + working-directory: sdk-reference-generator + run: npx tsc --noEmit diff --git a/docs/sdk-reference/cli/1.0.0/auth.mdx b/docs/sdk-reference/cli/1.0.0/auth.mdx deleted file mode 100644 index d64eb00..0000000 --- a/docs/sdk-reference/cli/1.0.0/auth.mdx +++ /dev/null @@ -1,63 +0,0 @@ ---- -sidebarTitle: "Auth" -mode: "center" ---- - -# e2b auth - - -authentication commands - -## Usage - -```bash -e2b auth [options] [command] -``` -# e2b auth login - - -log in to CLI - -## Usage - -```bash -e2b auth login [options] -``` - - -# e2b auth logout - - -log out of CLI - -## Usage - -```bash -e2b auth logout [options] -``` - - -# e2b auth info - - -get information about the current user - -## Usage - -```bash -e2b auth info [options] -``` - - -# e2b auth configure - - -configure user - -## Usage - -```bash -e2b auth configure [options] -``` - - diff --git a/docs/sdk-reference/cli/1.0.0/sandbox.mdx b/docs/sdk-reference/cli/1.0.0/sandbox.mdx deleted file mode 100644 index ae14239..0000000 --- a/docs/sdk-reference/cli/1.0.0/sandbox.mdx +++ /dev/null @@ -1,94 +0,0 @@ ---- -sidebarTitle: "Sandbox" -mode: "center" ---- - -# e2b sandbox - - -work with sandboxes - -## Usage - -```bash -e2b sandbox [options] [command] -``` -# e2b sandbox connect - - -connect terminal to already running sandbox - -## Usage - -```bash -e2b sandbox connect [options] -``` - - -# e2b sandbox list - - -list all running sandboxes - -## Usage - -```bash -e2b sandbox list [options] -``` - - -# e2b sandbox kill - - -kill sandbox - -## Usage - -```bash -e2b sandbox kill [options] [sandboxID] -``` - -## Options - - - - `-a, --all: kill all running sandboxes ` - - -# e2b sandbox spawn - - -spawn sandbox and connect terminal to it - -## Usage - -```bash -e2b sandbox spawn [options] [template] -``` - -## Options - - - - `-p, --path : change root directory where command is executed to  directory ` - - `--config : specify path to the E2B config toml. By default E2B tries to find ./e2b.toml in root directory. ` - - -# e2b sandbox logs - - -show logs for sandbox - -## Usage - -```bash -e2b sandbox logs [options] -``` - -## Options - - - - `--level : filter logs by level (DEBUG, INFO, WARN, ERROR). The logs with the higher levels will be also shown. [default: INFO]` - - `-f, --follow: keep streaming logs until the sandbox is closed ` - - `--format : specify format for printing logs (json, pretty) [default: pretty]` - - `--loggers [loggers]: filter logs by loggers. Specify multiple loggers by separating them with a comma. ` - - diff --git a/docs/sdk-reference/cli/1.0.0/template.mdx b/docs/sdk-reference/cli/1.0.0/template.mdx deleted file mode 100644 index 9ebf6cf..0000000 --- a/docs/sdk-reference/cli/1.0.0/template.mdx +++ /dev/null @@ -1,95 +0,0 @@ ---- -sidebarTitle: "Template" -mode: "center" ---- - -# e2b template - - -manage sandbox templates - -## Usage - -```bash -e2b template [options] [command] -``` -# e2b template build - - -build sandbox template defined by ./e2b.Dockerfile or ./Dockerfile in root directory. By default the root directory is the current working directory. This command also creates e2b.toml config. - -## Usage - -```bash -e2b template build [options] [template] -``` - -## Options - - - - `-p, --path : change root directory where command is executed to  directory ` - - `-d, --dockerfile : specify path to Dockerfile. By default E2B tries to find e2b.Dockerfile or Dockerfile in root directory. ` - - `-n, --name : specify sandbox template name. You can use the template name to start the sandbox with SDK. The template name must be lowercase and contain only letters, numbers, dashes and underscores. ` - - `-c, --cmd : specify command that will be executed when the sandbox is started. ` - - `-t, --team : specify the team ID that the operation will be associated with. You can find team ID in the team settings in the E2B dashboard (https://e2b.dev/dashboard?tab=team). ` - - `--config : specify path to the E2B config toml. By default E2B tries to find ./e2b.toml in root directory. ` - - `--cpu-count : specify the number of CPUs that will be used to run the sandbox. The default value is 2. ` - - `--memory-mb : specify the amount of memory in megabytes that will be used to run the sandbox. Must be an even number. The default value is 512. ` - - `--build-arg : specify additional build arguments for the build command. The format should be =. ` - - -# e2b template list - - -list sandbox templates - -## Usage - -```bash -e2b template list [options] -``` - -## Options - - - - `-t, --team : specify the team ID that the operation will be associated with. You can find team ID in the team settings in the E2B dashboard (https://e2b.dev/dashboard?tab=team). ` - - -# e2b template init - - -create basic E2B Dockerfile (./e2b.Dockerfile) in root directory. You can then run e2b template build to build sandbox template from this Dockerfile - -## Usage - -```bash -e2b template init [options] -``` - -## Options - - - - `-p, --path : change root directory where command is executed to  directory ` - - -# e2b template delete - - -delete sandbox template and e2b.toml config - -## Usage - -```bash -e2b template delete [options] [template] -``` - -## Options - - - - `-p, --path : change root directory where command is executed to  directory ` - - `--config : specify path to the E2B config toml. By default E2B tries to find ./e2b.toml in root directory. ` - - `-s, --select: select sandbox template from interactive list ` - - `-t, --team : specify the team ID that the operation will be associated with. You can find team ID in the team settings in the E2B dashboard (https://e2b.dev/dashboard?tab=team). ` - - `-y, --yes: skip manual delete confirmation ` - - diff --git a/docs/sdk-reference/cli/v2.3.3/auth.mdx b/docs/sdk-reference/cli/v2.3.3/auth.mdx deleted file mode 100644 index c223c57..0000000 --- a/docs/sdk-reference/cli/v2.3.3/auth.mdx +++ /dev/null @@ -1,63 +0,0 @@ ---- -sidebarTitle: "Auth" -mode: "center" ---- - -## e2b auth - - -authentication commands - -### Usage - -```bash -e2b auth [options] [command] -``` -## e2b auth login - - -log in to CLI - -### Usage - -```bash -e2b auth login [options] -``` - - -## e2b auth logout - - -log out of CLI - -### Usage - -```bash -e2b auth logout [options] -``` - - -## e2b auth info - - -get information about the current user - -### Usage - -```bash -e2b auth info [options] -``` - - -## e2b auth configure - - -configure user - -### Usage - -```bash -e2b auth configure [options] -``` - - diff --git a/docs/sdk-reference/cli/v2.3.3/sandbox.mdx b/docs/sdk-reference/cli/v2.3.3/sandbox.mdx deleted file mode 100644 index cc9ed31..0000000 --- a/docs/sdk-reference/cli/v2.3.3/sandbox.mdx +++ /dev/null @@ -1,140 +0,0 @@ ---- -sidebarTitle: "Sandbox" -mode: "center" ---- - -## e2b sandbox - - -work with sandboxes - -### Usage - -```bash -e2b sandbox [options] [command] -``` -## e2b sandbox connect - - -connect terminal to already running sandbox - -### Usage - -```bash -e2b sandbox connect [options] -``` - - -## e2b sandbox list - - -list all sandboxes, by default it list only running ones - -### Usage - -```bash -e2b sandbox list [options] -``` - -### Options - - - - `-s, --state : filter by state, eg. running, paused. Defaults to running ` - - `-m, --metadata : filter by metadata, eg. key1=value1 ` - - `-l, --limit : limit the number of sandboxes returned ` - - `-f, --format : output format, eg. json, pretty ` - - -## e2b sandbox kill - - -kill sandbox - -### Usage - -```bash -e2b sandbox kill [options] [sandboxIDs...] -``` - -### Options - - - - `-a, --all: kill all sandboxes ` - - `-s, --state : when used with -a/--all flag, filter by state, eg. running, paused. Defaults to running ` - - `-m, --metadata : when used with -a/--all flag, filter by metadata, eg. key1=value1 ` - - -## e2b sandbox create - - -create sandbox and connect terminal to it - -### Usage - -```bash -e2b sandbox create [options] [template] -``` - -### Options - - - - `-p, --path : change root directory where command is executed to  directory ` - - `--config : specify path to the E2B config toml. By default E2B tries to find ./e2b.toml in root directory. ` - - -## e2b sandbox spawn - - -create sandbox and connect terminal to it - -### Usage - -```bash -e2b sandbox spawn [options] [template] -``` - -### Options - - - - `-p, --path : change root directory where command is executed to  directory ` - - `--config : specify path to the E2B config toml. By default E2B tries to find ./e2b.toml in root directory. ` - - -## e2b sandbox logs - - -show logs for sandbox - -### Usage - -```bash -e2b sandbox logs [options] -``` - -### Options - - - - `--level : filter logs by level (DEBUG, INFO, WARN, ERROR). The logs with the higher levels will be also shown. [default: INFO]` - - `-f, --follow: keep streaming logs until the sandbox is closed ` - - `--format : specify format for printing logs (json, pretty) [default: pretty]` - - `--loggers [loggers]: filter logs by loggers. Specify multiple loggers by separating them with a comma. ` - - -## e2b sandbox metrics - - -show metrics for sandbox - -### Usage - -```bash -e2b sandbox metrics [options] -``` - -### Options - - - - `-f, --follow: keep streaming metrics until the sandbox is closed ` - - `--format : specify format for printing metrics (json, pretty) [default: pretty]` - - diff --git a/docs/sdk-reference/cli/v2.3.3/template.mdx b/docs/sdk-reference/cli/v2.3.3/template.mdx deleted file mode 100644 index 8e0b766..0000000 --- a/docs/sdk-reference/cli/v2.3.3/template.mdx +++ /dev/null @@ -1,185 +0,0 @@ ---- -sidebarTitle: "Template" -mode: "center" ---- - -## e2b template - - -manage sandbox templates - -### Usage - -```bash -e2b template [options] [command] -``` -## e2b template create - - -build Dockerfile as a Sandbox template. This command reads a Dockerfile and builds it directly. - -### Usage - -```bash -e2b template create [options] -``` - -### Options - - - - `-p, --path : change root directory where command is executed to  directory ` - - `-d, --dockerfile : specify path to Dockerfile. By default E2B tries to find e2b.Dockerfile or Dockerfile in root directory. ` - - `-c, --cmd : specify command that will be executed when the sandbox is started. ` - - `--ready-cmd : specify command that will need to exit 0 for the template to be ready. ` - - `--cpu-count : specify the number of CPUs that will be used to run the sandbox. The default value is 2. ` - - `--memory-mb : specify the amount of memory in megabytes that will be used to run the sandbox. Must be an even number. The default value is 512. ` - - `--no-cache: skip cache when building the template. ` - - -## e2b template build - - -build sandbox template defined by ./e2b.Dockerfile or ./Dockerfile in root directory. By default the root directory is the current working directory. This command also creates e2b.toml config. - -### Usage - -```bash -e2b template build [options] [template] -``` - -### Options - - - - `-p, --path : change root directory where command is executed to  directory ` - - `-d, --dockerfile : specify path to Dockerfile. By default E2B tries to find e2b.Dockerfile or Dockerfile in root directory. ` - - `-n, --name : specify sandbox template name. You can use the template name to start the sandbox with SDK. The template name must be lowercase and contain only letters, numbers, dashes and underscores. ` - - `-c, --cmd : specify command that will be executed when the sandbox is started. ` - - `--ready-cmd : specify command that will need to exit 0 for the template to be ready. ` - - `-t, --team : specify the team ID that the operation will be associated with. You can find team ID in the team settings in the E2B dashboard (https://e2b.dev/dashboard?tab=team). ` - - `--config : specify path to the E2B config toml. By default E2B tries to find ./e2b.toml in root directory. ` - - `--cpu-count : specify the number of CPUs that will be used to run the sandbox. The default value is 2. ` - - `--memory-mb : specify the amount of memory in megabytes that will be used to run the sandbox. Must be an even number. The default value is 512. ` - - `--build-arg : specify additional build arguments for the build command. The format should be =. ` - - `--no-cache: skip cache when building the template. ` - - -## e2b template list - - -list sandbox templates - -### Usage - -```bash -e2b template list [options] -``` - -### Options - - - - `-t, --team : specify the team ID that the operation will be associated with. You can find team ID in the team settings in the E2B dashboard (https://e2b.dev/dashboard?tab=team). ` - - `-f, --format : output format, eg. json, pretty ` - - -## e2b template init - - -initialize a new sandbox template using the SDK - -### Usage - -```bash -e2b template init [options] -``` - -### Options - - - - `-p, --path : change root directory where command is executed to  directory ` - - `-n, --name : template name (alias) ` - - `-l, --language : target language: typescript, python-sync, python-async ` - - -## e2b template delete - - -delete sandbox template and e2b.toml config - -### Usage - -```bash -e2b template delete [options] [template] -``` - -### Options - - - - `-p, --path : change root directory where command is executed to  directory ` - - `--config : specify path to the E2B config toml. By default E2B tries to find ./e2b.toml in root directory. ` - - `-s, --select: select sandbox template from interactive list ` - - `-t, --team : specify the team ID that the operation will be associated with. You can find team ID in the team settings in the E2B dashboard (https://e2b.dev/dashboard?tab=team). ` - - `-y, --yes: skip manual delete confirmation ` - - -## e2b template publish - - -publish sandbox template - -### Usage - -```bash -e2b template publish [options] [template] -``` - -### Options - - - - `-p, --path : change root directory where command is executed to  directory ` - - `--config : specify path to the E2B config toml. By default E2B tries to find ./e2b.toml in root directory. ` - - `-s, --select: select sandbox template from interactive list ` - - `-t, --team : specify the team ID that the operation will be associated with. You can find team ID in the team settings in the E2B dashboard (https://e2b.dev/dashboard?tab=team). ` - - `-y, --yes: skip manual publish confirmation ` - - -## e2b template unpublish - - -unpublish sandbox template - -### Usage - -```bash -e2b template unpublish [options] [template] -``` - -### Options - - - - `-p, --path : change root directory where command is executed to  directory ` - - `--config : specify path to the E2B config toml. By default E2B tries to find ./e2b.toml in root directory. ` - - `-s, --select: select sandbox template from interactive list ` - - `-t, --team : specify the team ID that the operation will be associated with. You can find team ID in the team settings in the E2B dashboard (https://e2b.dev/dashboard?tab=team). ` - - `-y, --yes: skip manual unpublish confirmation ` - - -## e2b template migrate - - -migrate e2b.Dockerfile and e2b.toml to new Template SDK format - -### Usage - -```bash -e2b template migrate [options] -``` - -### Options - - - - `-d, --dockerfile : specify path to Dockerfile. Defaults to e2b.Dockerfile ` - - `--config : specify path to the E2B config toml. By default E2B tries to find ./e2b.toml in root directory. ` - - `-l, --language : specify target language: typescript, python-sync, python-async ` - - `-p, --path : change root directory where command is executed to  directory ` - - diff --git a/docs/sdk-reference/cli/v2.4.0/auth.mdx b/docs/sdk-reference/cli/v2.4.0/auth.mdx deleted file mode 100644 index c223c57..0000000 --- a/docs/sdk-reference/cli/v2.4.0/auth.mdx +++ /dev/null @@ -1,63 +0,0 @@ ---- -sidebarTitle: "Auth" -mode: "center" ---- - -## e2b auth - - -authentication commands - -### Usage - -```bash -e2b auth [options] [command] -``` -## e2b auth login - - -log in to CLI - -### Usage - -```bash -e2b auth login [options] -``` - - -## e2b auth logout - - -log out of CLI - -### Usage - -```bash -e2b auth logout [options] -``` - - -## e2b auth info - - -get information about the current user - -### Usage - -```bash -e2b auth info [options] -``` - - -## e2b auth configure - - -configure user - -### Usage - -```bash -e2b auth configure [options] -``` - - diff --git a/docs/sdk-reference/cli/v2.4.0/sandbox.mdx b/docs/sdk-reference/cli/v2.4.0/sandbox.mdx deleted file mode 100644 index cc9ed31..0000000 --- a/docs/sdk-reference/cli/v2.4.0/sandbox.mdx +++ /dev/null @@ -1,140 +0,0 @@ ---- -sidebarTitle: "Sandbox" -mode: "center" ---- - -## e2b sandbox - - -work with sandboxes - -### Usage - -```bash -e2b sandbox [options] [command] -``` -## e2b sandbox connect - - -connect terminal to already running sandbox - -### Usage - -```bash -e2b sandbox connect [options] -``` - - -## e2b sandbox list - - -list all sandboxes, by default it list only running ones - -### Usage - -```bash -e2b sandbox list [options] -``` - -### Options - - - - `-s, --state : filter by state, eg. running, paused. Defaults to running ` - - `-m, --metadata : filter by metadata, eg. key1=value1 ` - - `-l, --limit : limit the number of sandboxes returned ` - - `-f, --format : output format, eg. json, pretty ` - - -## e2b sandbox kill - - -kill sandbox - -### Usage - -```bash -e2b sandbox kill [options] [sandboxIDs...] -``` - -### Options - - - - `-a, --all: kill all sandboxes ` - - `-s, --state : when used with -a/--all flag, filter by state, eg. running, paused. Defaults to running ` - - `-m, --metadata : when used with -a/--all flag, filter by metadata, eg. key1=value1 ` - - -## e2b sandbox create - - -create sandbox and connect terminal to it - -### Usage - -```bash -e2b sandbox create [options] [template] -``` - -### Options - - - - `-p, --path : change root directory where command is executed to  directory ` - - `--config : specify path to the E2B config toml. By default E2B tries to find ./e2b.toml in root directory. ` - - -## e2b sandbox spawn - - -create sandbox and connect terminal to it - -### Usage - -```bash -e2b sandbox spawn [options] [template] -``` - -### Options - - - - `-p, --path : change root directory where command is executed to  directory ` - - `--config : specify path to the E2B config toml. By default E2B tries to find ./e2b.toml in root directory. ` - - -## e2b sandbox logs - - -show logs for sandbox - -### Usage - -```bash -e2b sandbox logs [options] -``` - -### Options - - - - `--level : filter logs by level (DEBUG, INFO, WARN, ERROR). The logs with the higher levels will be also shown. [default: INFO]` - - `-f, --follow: keep streaming logs until the sandbox is closed ` - - `--format : specify format for printing logs (json, pretty) [default: pretty]` - - `--loggers [loggers]: filter logs by loggers. Specify multiple loggers by separating them with a comma. ` - - -## e2b sandbox metrics - - -show metrics for sandbox - -### Usage - -```bash -e2b sandbox metrics [options] -``` - -### Options - - - - `-f, --follow: keep streaming metrics until the sandbox is closed ` - - `--format : specify format for printing metrics (json, pretty) [default: pretty]` - - diff --git a/docs/sdk-reference/cli/v2.4.0/template.mdx b/docs/sdk-reference/cli/v2.4.0/template.mdx deleted file mode 100644 index 8e0b766..0000000 --- a/docs/sdk-reference/cli/v2.4.0/template.mdx +++ /dev/null @@ -1,185 +0,0 @@ ---- -sidebarTitle: "Template" -mode: "center" ---- - -## e2b template - - -manage sandbox templates - -### Usage - -```bash -e2b template [options] [command] -``` -## e2b template create - - -build Dockerfile as a Sandbox template. This command reads a Dockerfile and builds it directly. - -### Usage - -```bash -e2b template create [options] -``` - -### Options - - - - `-p, --path : change root directory where command is executed to  directory ` - - `-d, --dockerfile : specify path to Dockerfile. By default E2B tries to find e2b.Dockerfile or Dockerfile in root directory. ` - - `-c, --cmd : specify command that will be executed when the sandbox is started. ` - - `--ready-cmd : specify command that will need to exit 0 for the template to be ready. ` - - `--cpu-count : specify the number of CPUs that will be used to run the sandbox. The default value is 2. ` - - `--memory-mb : specify the amount of memory in megabytes that will be used to run the sandbox. Must be an even number. The default value is 512. ` - - `--no-cache: skip cache when building the template. ` - - -## e2b template build - - -build sandbox template defined by ./e2b.Dockerfile or ./Dockerfile in root directory. By default the root directory is the current working directory. This command also creates e2b.toml config. - -### Usage - -```bash -e2b template build [options] [template] -``` - -### Options - - - - `-p, --path : change root directory where command is executed to  directory ` - - `-d, --dockerfile : specify path to Dockerfile. By default E2B tries to find e2b.Dockerfile or Dockerfile in root directory. ` - - `-n, --name : specify sandbox template name. You can use the template name to start the sandbox with SDK. The template name must be lowercase and contain only letters, numbers, dashes and underscores. ` - - `-c, --cmd : specify command that will be executed when the sandbox is started. ` - - `--ready-cmd : specify command that will need to exit 0 for the template to be ready. ` - - `-t, --team : specify the team ID that the operation will be associated with. You can find team ID in the team settings in the E2B dashboard (https://e2b.dev/dashboard?tab=team). ` - - `--config : specify path to the E2B config toml. By default E2B tries to find ./e2b.toml in root directory. ` - - `--cpu-count : specify the number of CPUs that will be used to run the sandbox. The default value is 2. ` - - `--memory-mb : specify the amount of memory in megabytes that will be used to run the sandbox. Must be an even number. The default value is 512. ` - - `--build-arg : specify additional build arguments for the build command. The format should be =. ` - - `--no-cache: skip cache when building the template. ` - - -## e2b template list - - -list sandbox templates - -### Usage - -```bash -e2b template list [options] -``` - -### Options - - - - `-t, --team : specify the team ID that the operation will be associated with. You can find team ID in the team settings in the E2B dashboard (https://e2b.dev/dashboard?tab=team). ` - - `-f, --format : output format, eg. json, pretty ` - - -## e2b template init - - -initialize a new sandbox template using the SDK - -### Usage - -```bash -e2b template init [options] -``` - -### Options - - - - `-p, --path : change root directory where command is executed to  directory ` - - `-n, --name : template name (alias) ` - - `-l, --language : target language: typescript, python-sync, python-async ` - - -## e2b template delete - - -delete sandbox template and e2b.toml config - -### Usage - -```bash -e2b template delete [options] [template] -``` - -### Options - - - - `-p, --path : change root directory where command is executed to  directory ` - - `--config : specify path to the E2B config toml. By default E2B tries to find ./e2b.toml in root directory. ` - - `-s, --select: select sandbox template from interactive list ` - - `-t, --team : specify the team ID that the operation will be associated with. You can find team ID in the team settings in the E2B dashboard (https://e2b.dev/dashboard?tab=team). ` - - `-y, --yes: skip manual delete confirmation ` - - -## e2b template publish - - -publish sandbox template - -### Usage - -```bash -e2b template publish [options] [template] -``` - -### Options - - - - `-p, --path : change root directory where command is executed to  directory ` - - `--config : specify path to the E2B config toml. By default E2B tries to find ./e2b.toml in root directory. ` - - `-s, --select: select sandbox template from interactive list ` - - `-t, --team : specify the team ID that the operation will be associated with. You can find team ID in the team settings in the E2B dashboard (https://e2b.dev/dashboard?tab=team). ` - - `-y, --yes: skip manual publish confirmation ` - - -## e2b template unpublish - - -unpublish sandbox template - -### Usage - -```bash -e2b template unpublish [options] [template] -``` - -### Options - - - - `-p, --path : change root directory where command is executed to  directory ` - - `--config : specify path to the E2B config toml. By default E2B tries to find ./e2b.toml in root directory. ` - - `-s, --select: select sandbox template from interactive list ` - - `-t, --team : specify the team ID that the operation will be associated with. You can find team ID in the team settings in the E2B dashboard (https://e2b.dev/dashboard?tab=team). ` - - `-y, --yes: skip manual unpublish confirmation ` - - -## e2b template migrate - - -migrate e2b.Dockerfile and e2b.toml to new Template SDK format - -### Usage - -```bash -e2b template migrate [options] -``` - -### Options - - - - `-d, --dockerfile : specify path to Dockerfile. Defaults to e2b.Dockerfile ` - - `--config : specify path to the E2B config toml. By default E2B tries to find ./e2b.toml in root directory. ` - - `-l, --language : specify target language: typescript, python-sync, python-async ` - - `-p, --path : change root directory where command is executed to  directory ` - - diff --git a/docs/sdk-reference/cli/v2.4.1/auth.mdx b/docs/sdk-reference/cli/v2.4.1/auth.mdx deleted file mode 100644 index c223c57..0000000 --- a/docs/sdk-reference/cli/v2.4.1/auth.mdx +++ /dev/null @@ -1,63 +0,0 @@ ---- -sidebarTitle: "Auth" -mode: "center" ---- - -## e2b auth - - -authentication commands - -### Usage - -```bash -e2b auth [options] [command] -``` -## e2b auth login - - -log in to CLI - -### Usage - -```bash -e2b auth login [options] -``` - - -## e2b auth logout - - -log out of CLI - -### Usage - -```bash -e2b auth logout [options] -``` - - -## e2b auth info - - -get information about the current user - -### Usage - -```bash -e2b auth info [options] -``` - - -## e2b auth configure - - -configure user - -### Usage - -```bash -e2b auth configure [options] -``` - - diff --git a/docs/sdk-reference/cli/v2.4.1/sandbox.mdx b/docs/sdk-reference/cli/v2.4.1/sandbox.mdx deleted file mode 100644 index cc9ed31..0000000 --- a/docs/sdk-reference/cli/v2.4.1/sandbox.mdx +++ /dev/null @@ -1,140 +0,0 @@ ---- -sidebarTitle: "Sandbox" -mode: "center" ---- - -## e2b sandbox - - -work with sandboxes - -### Usage - -```bash -e2b sandbox [options] [command] -``` -## e2b sandbox connect - - -connect terminal to already running sandbox - -### Usage - -```bash -e2b sandbox connect [options] -``` - - -## e2b sandbox list - - -list all sandboxes, by default it list only running ones - -### Usage - -```bash -e2b sandbox list [options] -``` - -### Options - - - - `-s, --state : filter by state, eg. running, paused. Defaults to running ` - - `-m, --metadata : filter by metadata, eg. key1=value1 ` - - `-l, --limit : limit the number of sandboxes returned ` - - `-f, --format : output format, eg. json, pretty ` - - -## e2b sandbox kill - - -kill sandbox - -### Usage - -```bash -e2b sandbox kill [options] [sandboxIDs...] -``` - -### Options - - - - `-a, --all: kill all sandboxes ` - - `-s, --state : when used with -a/--all flag, filter by state, eg. running, paused. Defaults to running ` - - `-m, --metadata : when used with -a/--all flag, filter by metadata, eg. key1=value1 ` - - -## e2b sandbox create - - -create sandbox and connect terminal to it - -### Usage - -```bash -e2b sandbox create [options] [template] -``` - -### Options - - - - `-p, --path : change root directory where command is executed to  directory ` - - `--config : specify path to the E2B config toml. By default E2B tries to find ./e2b.toml in root directory. ` - - -## e2b sandbox spawn - - -create sandbox and connect terminal to it - -### Usage - -```bash -e2b sandbox spawn [options] [template] -``` - -### Options - - - - `-p, --path : change root directory where command is executed to  directory ` - - `--config : specify path to the E2B config toml. By default E2B tries to find ./e2b.toml in root directory. ` - - -## e2b sandbox logs - - -show logs for sandbox - -### Usage - -```bash -e2b sandbox logs [options] -``` - -### Options - - - - `--level : filter logs by level (DEBUG, INFO, WARN, ERROR). The logs with the higher levels will be also shown. [default: INFO]` - - `-f, --follow: keep streaming logs until the sandbox is closed ` - - `--format : specify format for printing logs (json, pretty) [default: pretty]` - - `--loggers [loggers]: filter logs by loggers. Specify multiple loggers by separating them with a comma. ` - - -## e2b sandbox metrics - - -show metrics for sandbox - -### Usage - -```bash -e2b sandbox metrics [options] -``` - -### Options - - - - `-f, --follow: keep streaming metrics until the sandbox is closed ` - - `--format : specify format for printing metrics (json, pretty) [default: pretty]` - - diff --git a/docs/sdk-reference/cli/v2.4.1/template.mdx b/docs/sdk-reference/cli/v2.4.1/template.mdx deleted file mode 100644 index 8e0b766..0000000 --- a/docs/sdk-reference/cli/v2.4.1/template.mdx +++ /dev/null @@ -1,185 +0,0 @@ ---- -sidebarTitle: "Template" -mode: "center" ---- - -## e2b template - - -manage sandbox templates - -### Usage - -```bash -e2b template [options] [command] -``` -## e2b template create - - -build Dockerfile as a Sandbox template. This command reads a Dockerfile and builds it directly. - -### Usage - -```bash -e2b template create [options] -``` - -### Options - - - - `-p, --path : change root directory where command is executed to  directory ` - - `-d, --dockerfile : specify path to Dockerfile. By default E2B tries to find e2b.Dockerfile or Dockerfile in root directory. ` - - `-c, --cmd : specify command that will be executed when the sandbox is started. ` - - `--ready-cmd : specify command that will need to exit 0 for the template to be ready. ` - - `--cpu-count : specify the number of CPUs that will be used to run the sandbox. The default value is 2. ` - - `--memory-mb : specify the amount of memory in megabytes that will be used to run the sandbox. Must be an even number. The default value is 512. ` - - `--no-cache: skip cache when building the template. ` - - -## e2b template build - - -build sandbox template defined by ./e2b.Dockerfile or ./Dockerfile in root directory. By default the root directory is the current working directory. This command also creates e2b.toml config. - -### Usage - -```bash -e2b template build [options] [template] -``` - -### Options - - - - `-p, --path : change root directory where command is executed to  directory ` - - `-d, --dockerfile : specify path to Dockerfile. By default E2B tries to find e2b.Dockerfile or Dockerfile in root directory. ` - - `-n, --name : specify sandbox template name. You can use the template name to start the sandbox with SDK. The template name must be lowercase and contain only letters, numbers, dashes and underscores. ` - - `-c, --cmd : specify command that will be executed when the sandbox is started. ` - - `--ready-cmd : specify command that will need to exit 0 for the template to be ready. ` - - `-t, --team : specify the team ID that the operation will be associated with. You can find team ID in the team settings in the E2B dashboard (https://e2b.dev/dashboard?tab=team). ` - - `--config : specify path to the E2B config toml. By default E2B tries to find ./e2b.toml in root directory. ` - - `--cpu-count : specify the number of CPUs that will be used to run the sandbox. The default value is 2. ` - - `--memory-mb : specify the amount of memory in megabytes that will be used to run the sandbox. Must be an even number. The default value is 512. ` - - `--build-arg : specify additional build arguments for the build command. The format should be =. ` - - `--no-cache: skip cache when building the template. ` - - -## e2b template list - - -list sandbox templates - -### Usage - -```bash -e2b template list [options] -``` - -### Options - - - - `-t, --team : specify the team ID that the operation will be associated with. You can find team ID in the team settings in the E2B dashboard (https://e2b.dev/dashboard?tab=team). ` - - `-f, --format : output format, eg. json, pretty ` - - -## e2b template init - - -initialize a new sandbox template using the SDK - -### Usage - -```bash -e2b template init [options] -``` - -### Options - - - - `-p, --path : change root directory where command is executed to  directory ` - - `-n, --name : template name (alias) ` - - `-l, --language : target language: typescript, python-sync, python-async ` - - -## e2b template delete - - -delete sandbox template and e2b.toml config - -### Usage - -```bash -e2b template delete [options] [template] -``` - -### Options - - - - `-p, --path : change root directory where command is executed to  directory ` - - `--config : specify path to the E2B config toml. By default E2B tries to find ./e2b.toml in root directory. ` - - `-s, --select: select sandbox template from interactive list ` - - `-t, --team : specify the team ID that the operation will be associated with. You can find team ID in the team settings in the E2B dashboard (https://e2b.dev/dashboard?tab=team). ` - - `-y, --yes: skip manual delete confirmation ` - - -## e2b template publish - - -publish sandbox template - -### Usage - -```bash -e2b template publish [options] [template] -``` - -### Options - - - - `-p, --path : change root directory where command is executed to  directory ` - - `--config : specify path to the E2B config toml. By default E2B tries to find ./e2b.toml in root directory. ` - - `-s, --select: select sandbox template from interactive list ` - - `-t, --team : specify the team ID that the operation will be associated with. You can find team ID in the team settings in the E2B dashboard (https://e2b.dev/dashboard?tab=team). ` - - `-y, --yes: skip manual publish confirmation ` - - -## e2b template unpublish - - -unpublish sandbox template - -### Usage - -```bash -e2b template unpublish [options] [template] -``` - -### Options - - - - `-p, --path : change root directory where command is executed to  directory ` - - `--config : specify path to the E2B config toml. By default E2B tries to find ./e2b.toml in root directory. ` - - `-s, --select: select sandbox template from interactive list ` - - `-t, --team : specify the team ID that the operation will be associated with. You can find team ID in the team settings in the E2B dashboard (https://e2b.dev/dashboard?tab=team). ` - - `-y, --yes: skip manual unpublish confirmation ` - - -## e2b template migrate - - -migrate e2b.Dockerfile and e2b.toml to new Template SDK format - -### Usage - -```bash -e2b template migrate [options] -``` - -### Options - - - - `-d, --dockerfile : specify path to Dockerfile. Defaults to e2b.Dockerfile ` - - `--config : specify path to the E2B config toml. By default E2B tries to find ./e2b.toml in root directory. ` - - `-l, --language : specify target language: typescript, python-sync, python-async ` - - `-p, --path : change root directory where command is executed to  directory ` - - diff --git a/docs/sdk-reference/cli/v2.4.2/auth.mdx b/docs/sdk-reference/cli/v2.4.2/auth.mdx deleted file mode 100644 index c223c57..0000000 --- a/docs/sdk-reference/cli/v2.4.2/auth.mdx +++ /dev/null @@ -1,63 +0,0 @@ ---- -sidebarTitle: "Auth" -mode: "center" ---- - -## e2b auth - - -authentication commands - -### Usage - -```bash -e2b auth [options] [command] -``` -## e2b auth login - - -log in to CLI - -### Usage - -```bash -e2b auth login [options] -``` - - -## e2b auth logout - - -log out of CLI - -### Usage - -```bash -e2b auth logout [options] -``` - - -## e2b auth info - - -get information about the current user - -### Usage - -```bash -e2b auth info [options] -``` - - -## e2b auth configure - - -configure user - -### Usage - -```bash -e2b auth configure [options] -``` - - diff --git a/docs/sdk-reference/cli/v2.4.2/sandbox.mdx b/docs/sdk-reference/cli/v2.4.2/sandbox.mdx deleted file mode 100644 index cc9ed31..0000000 --- a/docs/sdk-reference/cli/v2.4.2/sandbox.mdx +++ /dev/null @@ -1,140 +0,0 @@ ---- -sidebarTitle: "Sandbox" -mode: "center" ---- - -## e2b sandbox - - -work with sandboxes - -### Usage - -```bash -e2b sandbox [options] [command] -``` -## e2b sandbox connect - - -connect terminal to already running sandbox - -### Usage - -```bash -e2b sandbox connect [options] -``` - - -## e2b sandbox list - - -list all sandboxes, by default it list only running ones - -### Usage - -```bash -e2b sandbox list [options] -``` - -### Options - - - - `-s, --state : filter by state, eg. running, paused. Defaults to running ` - - `-m, --metadata : filter by metadata, eg. key1=value1 ` - - `-l, --limit : limit the number of sandboxes returned ` - - `-f, --format : output format, eg. json, pretty ` - - -## e2b sandbox kill - - -kill sandbox - -### Usage - -```bash -e2b sandbox kill [options] [sandboxIDs...] -``` - -### Options - - - - `-a, --all: kill all sandboxes ` - - `-s, --state : when used with -a/--all flag, filter by state, eg. running, paused. Defaults to running ` - - `-m, --metadata : when used with -a/--all flag, filter by metadata, eg. key1=value1 ` - - -## e2b sandbox create - - -create sandbox and connect terminal to it - -### Usage - -```bash -e2b sandbox create [options] [template] -``` - -### Options - - - - `-p, --path : change root directory where command is executed to  directory ` - - `--config : specify path to the E2B config toml. By default E2B tries to find ./e2b.toml in root directory. ` - - -## e2b sandbox spawn - - -create sandbox and connect terminal to it - -### Usage - -```bash -e2b sandbox spawn [options] [template] -``` - -### Options - - - - `-p, --path : change root directory where command is executed to  directory ` - - `--config : specify path to the E2B config toml. By default E2B tries to find ./e2b.toml in root directory. ` - - -## e2b sandbox logs - - -show logs for sandbox - -### Usage - -```bash -e2b sandbox logs [options] -``` - -### Options - - - - `--level : filter logs by level (DEBUG, INFO, WARN, ERROR). The logs with the higher levels will be also shown. [default: INFO]` - - `-f, --follow: keep streaming logs until the sandbox is closed ` - - `--format : specify format for printing logs (json, pretty) [default: pretty]` - - `--loggers [loggers]: filter logs by loggers. Specify multiple loggers by separating them with a comma. ` - - -## e2b sandbox metrics - - -show metrics for sandbox - -### Usage - -```bash -e2b sandbox metrics [options] -``` - -### Options - - - - `-f, --follow: keep streaming metrics until the sandbox is closed ` - - `--format : specify format for printing metrics (json, pretty) [default: pretty]` - - diff --git a/docs/sdk-reference/cli/v2.4.2/template.mdx b/docs/sdk-reference/cli/v2.4.2/template.mdx deleted file mode 100644 index 8e0b766..0000000 --- a/docs/sdk-reference/cli/v2.4.2/template.mdx +++ /dev/null @@ -1,185 +0,0 @@ ---- -sidebarTitle: "Template" -mode: "center" ---- - -## e2b template - - -manage sandbox templates - -### Usage - -```bash -e2b template [options] [command] -``` -## e2b template create - - -build Dockerfile as a Sandbox template. This command reads a Dockerfile and builds it directly. - -### Usage - -```bash -e2b template create [options] -``` - -### Options - - - - `-p, --path : change root directory where command is executed to  directory ` - - `-d, --dockerfile : specify path to Dockerfile. By default E2B tries to find e2b.Dockerfile or Dockerfile in root directory. ` - - `-c, --cmd : specify command that will be executed when the sandbox is started. ` - - `--ready-cmd : specify command that will need to exit 0 for the template to be ready. ` - - `--cpu-count : specify the number of CPUs that will be used to run the sandbox. The default value is 2. ` - - `--memory-mb : specify the amount of memory in megabytes that will be used to run the sandbox. Must be an even number. The default value is 512. ` - - `--no-cache: skip cache when building the template. ` - - -## e2b template build - - -build sandbox template defined by ./e2b.Dockerfile or ./Dockerfile in root directory. By default the root directory is the current working directory. This command also creates e2b.toml config. - -### Usage - -```bash -e2b template build [options] [template] -``` - -### Options - - - - `-p, --path : change root directory where command is executed to  directory ` - - `-d, --dockerfile : specify path to Dockerfile. By default E2B tries to find e2b.Dockerfile or Dockerfile in root directory. ` - - `-n, --name : specify sandbox template name. You can use the template name to start the sandbox with SDK. The template name must be lowercase and contain only letters, numbers, dashes and underscores. ` - - `-c, --cmd : specify command that will be executed when the sandbox is started. ` - - `--ready-cmd : specify command that will need to exit 0 for the template to be ready. ` - - `-t, --team : specify the team ID that the operation will be associated with. You can find team ID in the team settings in the E2B dashboard (https://e2b.dev/dashboard?tab=team). ` - - `--config : specify path to the E2B config toml. By default E2B tries to find ./e2b.toml in root directory. ` - - `--cpu-count : specify the number of CPUs that will be used to run the sandbox. The default value is 2. ` - - `--memory-mb : specify the amount of memory in megabytes that will be used to run the sandbox. Must be an even number. The default value is 512. ` - - `--build-arg : specify additional build arguments for the build command. The format should be =. ` - - `--no-cache: skip cache when building the template. ` - - -## e2b template list - - -list sandbox templates - -### Usage - -```bash -e2b template list [options] -``` - -### Options - - - - `-t, --team : specify the team ID that the operation will be associated with. You can find team ID in the team settings in the E2B dashboard (https://e2b.dev/dashboard?tab=team). ` - - `-f, --format : output format, eg. json, pretty ` - - -## e2b template init - - -initialize a new sandbox template using the SDK - -### Usage - -```bash -e2b template init [options] -``` - -### Options - - - - `-p, --path : change root directory where command is executed to  directory ` - - `-n, --name : template name (alias) ` - - `-l, --language : target language: typescript, python-sync, python-async ` - - -## e2b template delete - - -delete sandbox template and e2b.toml config - -### Usage - -```bash -e2b template delete [options] [template] -``` - -### Options - - - - `-p, --path : change root directory where command is executed to  directory ` - - `--config : specify path to the E2B config toml. By default E2B tries to find ./e2b.toml in root directory. ` - - `-s, --select: select sandbox template from interactive list ` - - `-t, --team : specify the team ID that the operation will be associated with. You can find team ID in the team settings in the E2B dashboard (https://e2b.dev/dashboard?tab=team). ` - - `-y, --yes: skip manual delete confirmation ` - - -## e2b template publish - - -publish sandbox template - -### Usage - -```bash -e2b template publish [options] [template] -``` - -### Options - - - - `-p, --path : change root directory where command is executed to  directory ` - - `--config : specify path to the E2B config toml. By default E2B tries to find ./e2b.toml in root directory. ` - - `-s, --select: select sandbox template from interactive list ` - - `-t, --team : specify the team ID that the operation will be associated with. You can find team ID in the team settings in the E2B dashboard (https://e2b.dev/dashboard?tab=team). ` - - `-y, --yes: skip manual publish confirmation ` - - -## e2b template unpublish - - -unpublish sandbox template - -### Usage - -```bash -e2b template unpublish [options] [template] -``` - -### Options - - - - `-p, --path : change root directory where command is executed to  directory ` - - `--config : specify path to the E2B config toml. By default E2B tries to find ./e2b.toml in root directory. ` - - `-s, --select: select sandbox template from interactive list ` - - `-t, --team : specify the team ID that the operation will be associated with. You can find team ID in the team settings in the E2B dashboard (https://e2b.dev/dashboard?tab=team). ` - - `-y, --yes: skip manual unpublish confirmation ` - - -## e2b template migrate - - -migrate e2b.Dockerfile and e2b.toml to new Template SDK format - -### Usage - -```bash -e2b template migrate [options] -``` - -### Options - - - - `-d, --dockerfile : specify path to Dockerfile. Defaults to e2b.Dockerfile ` - - `--config : specify path to the E2B config toml. By default E2B tries to find ./e2b.toml in root directory. ` - - `-l, --language : specify target language: typescript, python-sync, python-async ` - - `-p, --path : change root directory where command is executed to  directory ` - - diff --git a/docs/sdk-reference/code-interpreter-js-sdk/v2.3.0/charts.mdx b/docs/sdk-reference/code-interpreter-js-sdk/v2.3.0/charts.mdx deleted file mode 100644 index d4cf7ad..0000000 --- a/docs/sdk-reference/code-interpreter-js-sdk/v2.3.0/charts.mdx +++ /dev/null @@ -1,245 +0,0 @@ ---- -sidebarTitle: "Charts" -mode: "center" ---- - -### ChartType - -Chart types - -#### Enumeration Members - -| Enumeration Member | Value | -| ------ | ------ | -| `BAR` | `"bar"` | -| `BOX_AND_WHISKER` | `"box_and_whisker"` | -| `LINE` | `"line"` | -| `PIE` | `"pie"` | -| `SCATTER` | `"scatter"` | -| `SUPERCHART` | `"superchart"` | -| `UNKNOWN` | `"unknown"` | - -*** - -### ScaleType - -Ax scale types - -#### Enumeration Members - -| Enumeration Member | Value | -| ------ | ------ | -| `ASINH` | `"asinh"` | -| `CATEGORICAL` | `"categorical"` | -| `DATETIME` | `"datetime"` | -| `FUNCTION` | `"function"` | -| `FUNCTIONLOG` | `"functionlog"` | -| `LINEAR` | `"linear"` | -| `LOG` | `"log"` | -| `LOGIT` | `"logit"` | -| `SYMLOG` | `"symlog"` | - -## Type Aliases - -### BarChart - -```ts -type BarChart: Chart2D & object; -``` - -#### Type declaration - -| Name | Type | -| ------ | ------ | -| `elements` | `BarData`[] | -| `type` | `ChartType.BAR` | - -*** - -### BarData - -```ts -type BarData: object; -``` - -#### Type declaration - -| Name | Type | -| ------ | ------ | -| `group` | `string` | -| `label` | `string` | -| `value` | `string` | - -*** - -### BoxAndWhiskerChart - -```ts -type BoxAndWhiskerChart: Chart2D & object; -``` - -#### Type declaration - -| Name | Type | -| ------ | ------ | -| `elements` | `BoxAndWhiskerData`[] | -| `type` | `ChartType.BOX_AND_WHISKER` | - -*** - -### BoxAndWhiskerData - -```ts -type BoxAndWhiskerData: object; -``` - -#### Type declaration - -| Name | Type | -| ------ | ------ | -| `first_quartile` | `number` | -| `label` | `string` | -| `max` | `number` | -| `median` | `number` | -| `min` | `number` | -| `outliers` | `number`[] | -| `third_quartile` | `number` | - -*** - -### Chart - -```ts -type Chart: object; -``` - -Represents a chart. - -#### Type declaration - -| Name | Type | -| ------ | ------ | -| `elements` | `any`[] | -| `title` | `string` | -| `type` | `ChartType` | - -*** - -### ChartTypes - -```ts -type ChartTypes: - | LineChart - | ScatterChart - | BarChart - | PieChart - | BoxAndWhiskerChart - | SuperChart; -``` - -*** - -### LineChart - -```ts -type LineChart: PointChart & object; -``` - -#### Type declaration - -| Name | Type | -| ------ | ------ | -| `type` | `ChartType.LINE` | - -*** - -### PieChart - -```ts -type PieChart: Chart & object; -``` - -#### Type declaration - -| Name | Type | -| ------ | ------ | -| `elements` | `PieData`[] | -| `type` | `ChartType.PIE` | - -*** - -### PieData - -```ts -type PieData: object; -``` - -#### Type declaration - -| Name | Type | -| ------ | ------ | -| `angle` | `number` | -| `label` | `string` | -| `radius` | `number` | - -*** - -### PointData - -```ts -type PointData: object; -``` - -#### Type declaration - -| Name | Type | -| ------ | ------ | -| `label` | `string` | -| `points` | [`number` \| `string`, `number` \| `string`][] | - -*** - -### ScatterChart - -```ts -type ScatterChart: PointChart & object; -``` - -#### Type declaration - -| Name | Type | -| ------ | ------ | -| `type` | `ChartType.SCATTER` | - -*** - -### SuperChart - -```ts -type SuperChart: Chart & object; -``` - -#### Type declaration - -| Name | Type | -| ------ | ------ | -| `elements` | `Chart`[] | -| `type` | `ChartType.SUPERCHART` | - -## Functions - -### deserializeChart() - -```ts -function deserializeChart(data: any): Chart -``` - -#### Parameters - -| Parameter | Type | -| ------ | ------ | -| `data` | `any` | - -#### Returns - -`Chart` diff --git a/docs/sdk-reference/code-interpreter-js-sdk/v2.3.0/consts.mdx b/docs/sdk-reference/code-interpreter-js-sdk/v2.3.0/consts.mdx deleted file mode 100644 index 07462e7..0000000 --- a/docs/sdk-reference/code-interpreter-js-sdk/v2.3.0/consts.mdx +++ /dev/null @@ -1,18 +0,0 @@ ---- -sidebarTitle: "Consts" -mode: "center" ---- - -### DEFAULT\_TIMEOUT\_MS - -```ts -const DEFAULT_TIMEOUT_MS: 60000 = 60_000; -``` - -*** - -### JUPYTER\_PORT - -```ts -const JUPYTER_PORT: 49999 = 49999; -``` diff --git a/docs/sdk-reference/code-interpreter-js-sdk/v2.3.0/messaging.mdx b/docs/sdk-reference/code-interpreter-js-sdk/v2.3.0/messaging.mdx deleted file mode 100644 index ef4f3e7..0000000 --- a/docs/sdk-reference/code-interpreter-js-sdk/v2.3.0/messaging.mdx +++ /dev/null @@ -1,331 +0,0 @@ ---- -sidebarTitle: "Messaging" -mode: "center" ---- - -### Execution - -Represents the result of a cell execution. - -#### Constructors - -```ts -new Execution( - results: Result[], - logs: Logs, - error?: ExecutionError, - executionCount?: number): Execution -``` - -###### Parameters - -| Parameter | Type | Default value | Description | -| ------ | ------ | ------ | ------ | -| `results` | `Result`[] | `[]` | List of result of the cell (interactively interpreted last line), display calls (e.g. matplotlib plots). | -| `logs` | `Logs` | `...` | Logs printed to stdout and stderr during execution. | -| `error`? | `ExecutionError` | `undefined` | An Error object if an error occurred, null otherwise. | -| `executionCount`? | `number` | `undefined` | Execution count of the cell. | - -###### Returns - -`Execution` - -#### Properties - -| Property | Modifier | Type | Default value | Description | -| ------ | ------ | ------ | ------ | ------ | -| `error?` | `public` | `ExecutionError` | `undefined` | An Error object if an error occurred, null otherwise. | -| `executionCount?` | `public` | `number` | `undefined` | Execution count of the cell. | -| `logs` | `public` | `Logs` | `undefined` | Logs printed to stdout and stderr during execution. | -| `results` | `public` | `Result`[] | `[]` | List of result of the cell (interactively interpreted last line), display calls (e.g. matplotlib plots). | - -#### Accessors - -### text - -```ts -get text(): undefined | string -``` - -Returns the text representation of the main result of the cell. - -###### Returns - -`undefined` \| `string` - -#### Methods - -### toJSON() - -```ts -toJSON(): object -``` - -Returns the serializable representation of the execution result. - -###### Returns - -`object` - -| Name | Type | -| ------ | ------ | -| `error` | `undefined` \| `ExecutionError` | -| `logs` | `Logs` | -| `results` | `Result`[] | - -*** - -### ExecutionError - -Represents an error that occurred during the execution of a cell. -The error contains the name of the error, the value of the error, and the traceback. - -#### Constructors - -```ts -new ExecutionError( - name: string, - value: string, - traceback: string): ExecutionError -``` - -###### Parameters - -| Parameter | Type | Description | -| ------ | ------ | ------ | -| `name` | `string` | Name of the error. | -| `value` | `string` | Value of the error. | -| `traceback` | `string` | The raw traceback of the error. | - -###### Returns - -`ExecutionError` - -#### Properties - -| Property | Modifier | Type | Description | -| ------ | ------ | ------ | ------ | -| `name` | `public` | `string` | Name of the error. | -| `traceback` | `public` | `string` | The raw traceback of the error. | -| `value` | `public` | `string` | Value of the error. | - -*** - -### OutputMessage - -Represents an output message from the sandbox code execution. - -#### Constructors - -```ts -new OutputMessage( - line: string, - timestamp: number, - error: boolean): OutputMessage -``` - -###### Parameters - -| Parameter | Type | Description | -| ------ | ------ | ------ | -| `line` | `string` | The output line. | -| `timestamp` | `number` | Unix epoch in nanoseconds. | -| `error` | `boolean` | Whether the output is an error. | - -###### Returns - -`OutputMessage` - -#### Properties - -| Property | Modifier | Type | Description | -| ------ | ------ | ------ | ------ | -| `error` | `readonly` | `boolean` | Whether the output is an error. | -| `line` | `readonly` | `string` | The output line. | -| `timestamp` | `readonly` | `number` | Unix epoch in nanoseconds. | - -#### Methods - -### toString() - -```ts -toString(): string -``` - -###### Returns - -`string` - -*** - -### Result - -Represents the data to be displayed as a result of executing a cell in a Jupyter notebook. -The result is similar to the structure returned by ipython kernel: https://ipython.readthedocs.io/en/stable/development/execution.html#execution-semantics - -The result can contain multiple types of data, such as text, images, plots, etc. Each type of data is represented -as a string, and the result can contain multiple types of data. The display calls don't have to have text representation, -for the actual result the representation is always present for the result, the other representations are always optional. - -#### Constructors - -```ts -new Result(rawData: RawData, isMainResult: boolean): Result -``` - -###### Parameters - -| Parameter | Type | -| ------ | ------ | -| `rawData` | `RawData` | -| `isMainResult` | `boolean` | - -###### Returns - -`Result` - -#### Properties - -| Property | Modifier | Type | Description | -| ------ | ------ | ------ | ------ | -| `chart?` | `readonly` | `ChartTypes` | Contains the chart data. | -| `data?` | `readonly` | `Record`\<`string`, `unknown`\> | Contains the data from DataFrame. | -| `extra?` | `readonly` | `any` | Extra data that can be included. Not part of the standard types. | -| `html?` | `readonly` | `string` | HTML representation of the data. | -| `isMainResult` | `readonly` | `boolean` | - | -| `javascript?` | `readonly` | `string` | JavaScript representation of the data. | -| `jpeg?` | `readonly` | `string` | JPEG representation of the data. | -| `json?` | `readonly` | `string` | JSON representation of the data. | -| `latex?` | `readonly` | `string` | LaTeX representation of the data. | -| `markdown?` | `readonly` | `string` | Markdown representation of the data. | -| `pdf?` | `readonly` | `string` | PDF representation of the data. | -| `png?` | `readonly` | `string` | PNG representation of the data. | -| `raw` | `readonly` | `RawData` | - | -| `svg?` | `readonly` | `string` | SVG representation of the data. | -| `text?` | `readonly` | `string` | Text representation of the result. | - -#### Methods - -### formats() - -```ts -formats(): string[] -``` - -Returns all the formats available for the result. - -###### Returns - -`string`[] - -Array of strings representing the formats available for the result. - -### toJSON() - -```ts -toJSON(): object -``` - -Returns the serializable representation of the result. - -###### Returns - -`object` - -| Name | Type | -| ------ | ------ | -| `extra`? | `any` | -| `html` | `undefined` \| `string` | -| `javascript` | `undefined` \| `string` | -| `jpeg` | `undefined` \| `string` | -| `json` | `undefined` \| `string` | -| `latex` | `undefined` \| `string` | -| `markdown` | `undefined` \| `string` | -| `pdf` | `undefined` \| `string` | -| `png` | `undefined` \| `string` | -| `svg` | `undefined` \| `string` | -| `text` | `undefined` \| `string` | - -## Type Aliases - -### Logs - -```ts -type Logs: object; -``` - -Data printed to stdout and stderr during execution, usually by print statements, logs, warnings, subprocesses, etc. - -#### Type declaration - -| Name | Type | Description | -| ------ | ------ | ------ | -| `stderr` | `string`[] | List of strings printed to stderr by prints, subprocesses, etc. | -| `stdout` | `string`[] | List of strings printed to stdout by prints, subprocesses, etc. | - -*** - -### MIMEType - -```ts -type MIMEType: string; -``` - -Represents a MIME type. - -*** - -### RawData - -```ts -type RawData: object & E2BData; -``` - -Dictionary that maps MIME types to their corresponding representations of the data. - -## Functions - -### extractError() - -```ts -function extractError(res: Response): Promise -``` - -#### Parameters - -| Parameter | Type | -| ------ | ------ | -| `res` | `Response` | - -#### Returns - -`Promise`\<`undefined` \| `SandboxError`\> - -*** - -### parseOutput() - -```ts -function parseOutput( - execution: Execution, - line: string, - onStdout?: (output: OutputMessage) => any, - onStderr?: (output: OutputMessage) => any, - onResult?: (data: Result) => any, -onError?: (error: ExecutionError) => any): Promise -``` - -#### Parameters - -| Parameter | Type | -| ------ | ------ | -| `execution` | `Execution` | -| `line` | `string` | -| `onStdout`? | (`output`: `OutputMessage`) => `any` | -| `onStderr`? | (`output`: `OutputMessage`) => `any` | -| `onResult`? | (`data`: `Result`) => `any` | -| `onError`? | (`error`: `ExecutionError`) => `any` | - -#### Returns - -`Promise`\<`void`\> diff --git a/docs/sdk-reference/code-interpreter-js-sdk/v2.3.0/sandbox.mdx b/docs/sdk-reference/code-interpreter-js-sdk/v2.3.0/sandbox.mdx deleted file mode 100644 index fb801ca..0000000 --- a/docs/sdk-reference/code-interpreter-js-sdk/v2.3.0/sandbox.mdx +++ /dev/null @@ -1,371 +0,0 @@ ---- -sidebarTitle: "Sandbox" -mode: "center" ---- - -### Sandbox - -E2B cloud sandbox is a secure and isolated cloud environment. - -The sandbox allows you to: -- Access Linux OS -- Create, list, and delete files and directories -- Run commands -- Run isolated code -- Access the internet - -Check docs here. - -Use Sandbox.create to create a new sandbox. - -#### Example - -```ts -import { Sandbox } from '@e2b/code-interpreter' - -const sandbox = await Sandbox.create() -``` - -#### Methods - -### createCodeContext() - -```ts -createCodeContext(opts?: CreateCodeContextOpts): Promise -``` - -Creates a new context to run code in. - -###### Parameters - -| Parameter | Type | Description | -| ------ | ------ | ------ | -| `opts`? | `CreateCodeContextOpts` | options for creating the context. | - -###### Returns - -`Promise`\<`Context`\> - -context object. - -### listCodeContexts() - -```ts -listCodeContexts(): Promise -``` - -List all contexts. - -###### Returns - -`Promise`\<`Context`[]\> - -list of contexts. - -### removeCodeContext() - -```ts -removeCodeContext(context: string | Context): Promise -``` - -Removes a context. - -###### Parameters - -| Parameter | Type | Description | -| ------ | ------ | ------ | -| `context` | `string` \| `Context` | context to remove. | - -###### Returns - -`Promise`\<`void`\> - -void. - -### restartCodeContext() - -```ts -restartCodeContext(context: string | Context): Promise -``` - -Restart a context. - -###### Parameters - -| Parameter | Type | Description | -| ------ | ------ | ------ | -| `context` | `string` \| `Context` | context to restart. | - -###### Returns - -`Promise`\<`void`\> - -void. - -### runCode() - -###### runCode(code, opts) - -```ts -runCode(code: string, opts?: RunCodeOpts & object): Promise -``` - -Run the code as Python. - -Specify the `language` or `context` option to run the code as a different language or in a different `Context`. - -You can reference previously defined variables, imports, and functions in the code. - -###### Parameters - -| Parameter | Type | Description | -| ------ | ------ | ------ | -| `code` | `string` | code to execute. | -| `opts`? | `RunCodeOpts` & `object` | options for executing the code. | - -###### Returns - -`Promise`\<`Execution`\> - -`Execution` result object. - -###### runCode(code, opts) - -```ts -runCode(code: string, opts?: RunCodeOpts & object): Promise -``` - -Run the code for the specified language. - -Specify the `language` or `context` option to run the code as a different language or in a different `Context`. -If no language is specified, Python is used. - -You can reference previously defined variables, imports, and functions in the code. - -###### Parameters - -| Parameter | Type | Description | -| ------ | ------ | ------ | -| `code` | `string` | code to execute. | -| `opts`? | `RunCodeOpts` & `object` | options for executing the code. | - -###### Returns - -`Promise`\<`Execution`\> - -`Execution` result object. - -###### runCode(code, opts) - -```ts -runCode(code: string, opts?: RunCodeOpts & object): Promise -``` - -Runs the code in the specified context, if not specified, the default context is used. - -Specify the `language` or `context` option to run the code as a different language or in a different `Context`. - -You can reference previously defined variables, imports, and functions in the code. - -###### Parameters - -| Parameter | Type | Description | -| ------ | ------ | ------ | -| `code` | `string` | code to execute. | -| `opts`? | `RunCodeOpts` & `object` | options for executing the code | - -###### Returns - -`Promise`\<`Execution`\> - -`Execution` result object - -## Interfaces - -### CreateCodeContextOpts - -Options for creating a code context. - -#### Properties - -### cwd? - -```ts -optional cwd: string; -``` - -Working directory for the context. - -###### Default - -```ts -/home/user -``` - -### language? - -```ts -optional language: string; -``` - -Language for the context. - -###### Default - -```ts -python -``` - -### requestTimeoutMs? - -```ts -optional requestTimeoutMs: number; -``` - -Timeout for the request in **milliseconds**. - -###### Default - -```ts -30_000 // 30 seconds -``` - -*** - -### RunCodeOpts - -Options for running code. - -#### Properties - -### envs? - -```ts -optional envs: Record; -``` - -Custom environment variables for code execution. - -###### Default - -```ts -{} -``` - -### onError()? - -```ts -optional onError: (error: ExecutionError) => any; -``` - -Callback for handling the `ExecutionError` object. - -###### Parameters - -| Parameter | Type | -| ------ | ------ | -| `error` | `ExecutionError` | - -###### Returns - -`any` - -### onResult()? - -```ts -optional onResult: (data: Result) => any; -``` - -Callback for handling the final execution result. - -###### Parameters - -| Parameter | Type | -| ------ | ------ | -| `data` | `Result` | - -###### Returns - -`any` - -### onStderr()? - -```ts -optional onStderr: (output: OutputMessage) => any; -``` - -Callback for handling stderr messages. - -###### Parameters - -| Parameter | Type | -| ------ | ------ | -| `output` | `OutputMessage` | - -###### Returns - -`any` - -### onStdout()? - -```ts -optional onStdout: (output: OutputMessage) => any; -``` - -Callback for handling stdout messages. - -###### Parameters - -| Parameter | Type | -| ------ | ------ | -| `output` | `OutputMessage` | - -###### Returns - -`any` - -### requestTimeoutMs? - -```ts -optional requestTimeoutMs: number; -``` - -Timeout for the request in **milliseconds**. - -###### Default - -```ts -30_000 // 30 seconds -``` - -### timeoutMs? - -```ts -optional timeoutMs: number; -``` - -Timeout for the code execution in **milliseconds**. - -###### Default - -```ts -60_000 // 60 seconds -``` - -## Type Aliases - -### Context - -```ts -type Context: object; -``` - -Represents a context for code execution. - -#### Type declaration - -| Name | Type | Description | -| ------ | ------ | ------ | -| `cwd` | `string` | The working directory of the context. | -| `id` | `string` | The ID of the context. | -| `language` | `string` | The language of the context. | diff --git a/docs/sdk-reference/code-interpreter-js-sdk/v2.3.1/charts.mdx b/docs/sdk-reference/code-interpreter-js-sdk/v2.3.1/charts.mdx deleted file mode 100644 index d4cf7ad..0000000 --- a/docs/sdk-reference/code-interpreter-js-sdk/v2.3.1/charts.mdx +++ /dev/null @@ -1,245 +0,0 @@ ---- -sidebarTitle: "Charts" -mode: "center" ---- - -### ChartType - -Chart types - -#### Enumeration Members - -| Enumeration Member | Value | -| ------ | ------ | -| `BAR` | `"bar"` | -| `BOX_AND_WHISKER` | `"box_and_whisker"` | -| `LINE` | `"line"` | -| `PIE` | `"pie"` | -| `SCATTER` | `"scatter"` | -| `SUPERCHART` | `"superchart"` | -| `UNKNOWN` | `"unknown"` | - -*** - -### ScaleType - -Ax scale types - -#### Enumeration Members - -| Enumeration Member | Value | -| ------ | ------ | -| `ASINH` | `"asinh"` | -| `CATEGORICAL` | `"categorical"` | -| `DATETIME` | `"datetime"` | -| `FUNCTION` | `"function"` | -| `FUNCTIONLOG` | `"functionlog"` | -| `LINEAR` | `"linear"` | -| `LOG` | `"log"` | -| `LOGIT` | `"logit"` | -| `SYMLOG` | `"symlog"` | - -## Type Aliases - -### BarChart - -```ts -type BarChart: Chart2D & object; -``` - -#### Type declaration - -| Name | Type | -| ------ | ------ | -| `elements` | `BarData`[] | -| `type` | `ChartType.BAR` | - -*** - -### BarData - -```ts -type BarData: object; -``` - -#### Type declaration - -| Name | Type | -| ------ | ------ | -| `group` | `string` | -| `label` | `string` | -| `value` | `string` | - -*** - -### BoxAndWhiskerChart - -```ts -type BoxAndWhiskerChart: Chart2D & object; -``` - -#### Type declaration - -| Name | Type | -| ------ | ------ | -| `elements` | `BoxAndWhiskerData`[] | -| `type` | `ChartType.BOX_AND_WHISKER` | - -*** - -### BoxAndWhiskerData - -```ts -type BoxAndWhiskerData: object; -``` - -#### Type declaration - -| Name | Type | -| ------ | ------ | -| `first_quartile` | `number` | -| `label` | `string` | -| `max` | `number` | -| `median` | `number` | -| `min` | `number` | -| `outliers` | `number`[] | -| `third_quartile` | `number` | - -*** - -### Chart - -```ts -type Chart: object; -``` - -Represents a chart. - -#### Type declaration - -| Name | Type | -| ------ | ------ | -| `elements` | `any`[] | -| `title` | `string` | -| `type` | `ChartType` | - -*** - -### ChartTypes - -```ts -type ChartTypes: - | LineChart - | ScatterChart - | BarChart - | PieChart - | BoxAndWhiskerChart - | SuperChart; -``` - -*** - -### LineChart - -```ts -type LineChart: PointChart & object; -``` - -#### Type declaration - -| Name | Type | -| ------ | ------ | -| `type` | `ChartType.LINE` | - -*** - -### PieChart - -```ts -type PieChart: Chart & object; -``` - -#### Type declaration - -| Name | Type | -| ------ | ------ | -| `elements` | `PieData`[] | -| `type` | `ChartType.PIE` | - -*** - -### PieData - -```ts -type PieData: object; -``` - -#### Type declaration - -| Name | Type | -| ------ | ------ | -| `angle` | `number` | -| `label` | `string` | -| `radius` | `number` | - -*** - -### PointData - -```ts -type PointData: object; -``` - -#### Type declaration - -| Name | Type | -| ------ | ------ | -| `label` | `string` | -| `points` | [`number` \| `string`, `number` \| `string`][] | - -*** - -### ScatterChart - -```ts -type ScatterChart: PointChart & object; -``` - -#### Type declaration - -| Name | Type | -| ------ | ------ | -| `type` | `ChartType.SCATTER` | - -*** - -### SuperChart - -```ts -type SuperChart: Chart & object; -``` - -#### Type declaration - -| Name | Type | -| ------ | ------ | -| `elements` | `Chart`[] | -| `type` | `ChartType.SUPERCHART` | - -## Functions - -### deserializeChart() - -```ts -function deserializeChart(data: any): Chart -``` - -#### Parameters - -| Parameter | Type | -| ------ | ------ | -| `data` | `any` | - -#### Returns - -`Chart` diff --git a/docs/sdk-reference/code-interpreter-js-sdk/v2.3.1/consts.mdx b/docs/sdk-reference/code-interpreter-js-sdk/v2.3.1/consts.mdx deleted file mode 100644 index 07462e7..0000000 --- a/docs/sdk-reference/code-interpreter-js-sdk/v2.3.1/consts.mdx +++ /dev/null @@ -1,18 +0,0 @@ ---- -sidebarTitle: "Consts" -mode: "center" ---- - -### DEFAULT\_TIMEOUT\_MS - -```ts -const DEFAULT_TIMEOUT_MS: 60000 = 60_000; -``` - -*** - -### JUPYTER\_PORT - -```ts -const JUPYTER_PORT: 49999 = 49999; -``` diff --git a/docs/sdk-reference/code-interpreter-js-sdk/v2.3.1/messaging.mdx b/docs/sdk-reference/code-interpreter-js-sdk/v2.3.1/messaging.mdx deleted file mode 100644 index ef4f3e7..0000000 --- a/docs/sdk-reference/code-interpreter-js-sdk/v2.3.1/messaging.mdx +++ /dev/null @@ -1,331 +0,0 @@ ---- -sidebarTitle: "Messaging" -mode: "center" ---- - -### Execution - -Represents the result of a cell execution. - -#### Constructors - -```ts -new Execution( - results: Result[], - logs: Logs, - error?: ExecutionError, - executionCount?: number): Execution -``` - -###### Parameters - -| Parameter | Type | Default value | Description | -| ------ | ------ | ------ | ------ | -| `results` | `Result`[] | `[]` | List of result of the cell (interactively interpreted last line), display calls (e.g. matplotlib plots). | -| `logs` | `Logs` | `...` | Logs printed to stdout and stderr during execution. | -| `error`? | `ExecutionError` | `undefined` | An Error object if an error occurred, null otherwise. | -| `executionCount`? | `number` | `undefined` | Execution count of the cell. | - -###### Returns - -`Execution` - -#### Properties - -| Property | Modifier | Type | Default value | Description | -| ------ | ------ | ------ | ------ | ------ | -| `error?` | `public` | `ExecutionError` | `undefined` | An Error object if an error occurred, null otherwise. | -| `executionCount?` | `public` | `number` | `undefined` | Execution count of the cell. | -| `logs` | `public` | `Logs` | `undefined` | Logs printed to stdout and stderr during execution. | -| `results` | `public` | `Result`[] | `[]` | List of result of the cell (interactively interpreted last line), display calls (e.g. matplotlib plots). | - -#### Accessors - -### text - -```ts -get text(): undefined | string -``` - -Returns the text representation of the main result of the cell. - -###### Returns - -`undefined` \| `string` - -#### Methods - -### toJSON() - -```ts -toJSON(): object -``` - -Returns the serializable representation of the execution result. - -###### Returns - -`object` - -| Name | Type | -| ------ | ------ | -| `error` | `undefined` \| `ExecutionError` | -| `logs` | `Logs` | -| `results` | `Result`[] | - -*** - -### ExecutionError - -Represents an error that occurred during the execution of a cell. -The error contains the name of the error, the value of the error, and the traceback. - -#### Constructors - -```ts -new ExecutionError( - name: string, - value: string, - traceback: string): ExecutionError -``` - -###### Parameters - -| Parameter | Type | Description | -| ------ | ------ | ------ | -| `name` | `string` | Name of the error. | -| `value` | `string` | Value of the error. | -| `traceback` | `string` | The raw traceback of the error. | - -###### Returns - -`ExecutionError` - -#### Properties - -| Property | Modifier | Type | Description | -| ------ | ------ | ------ | ------ | -| `name` | `public` | `string` | Name of the error. | -| `traceback` | `public` | `string` | The raw traceback of the error. | -| `value` | `public` | `string` | Value of the error. | - -*** - -### OutputMessage - -Represents an output message from the sandbox code execution. - -#### Constructors - -```ts -new OutputMessage( - line: string, - timestamp: number, - error: boolean): OutputMessage -``` - -###### Parameters - -| Parameter | Type | Description | -| ------ | ------ | ------ | -| `line` | `string` | The output line. | -| `timestamp` | `number` | Unix epoch in nanoseconds. | -| `error` | `boolean` | Whether the output is an error. | - -###### Returns - -`OutputMessage` - -#### Properties - -| Property | Modifier | Type | Description | -| ------ | ------ | ------ | ------ | -| `error` | `readonly` | `boolean` | Whether the output is an error. | -| `line` | `readonly` | `string` | The output line. | -| `timestamp` | `readonly` | `number` | Unix epoch in nanoseconds. | - -#### Methods - -### toString() - -```ts -toString(): string -``` - -###### Returns - -`string` - -*** - -### Result - -Represents the data to be displayed as a result of executing a cell in a Jupyter notebook. -The result is similar to the structure returned by ipython kernel: https://ipython.readthedocs.io/en/stable/development/execution.html#execution-semantics - -The result can contain multiple types of data, such as text, images, plots, etc. Each type of data is represented -as a string, and the result can contain multiple types of data. The display calls don't have to have text representation, -for the actual result the representation is always present for the result, the other representations are always optional. - -#### Constructors - -```ts -new Result(rawData: RawData, isMainResult: boolean): Result -``` - -###### Parameters - -| Parameter | Type | -| ------ | ------ | -| `rawData` | `RawData` | -| `isMainResult` | `boolean` | - -###### Returns - -`Result` - -#### Properties - -| Property | Modifier | Type | Description | -| ------ | ------ | ------ | ------ | -| `chart?` | `readonly` | `ChartTypes` | Contains the chart data. | -| `data?` | `readonly` | `Record`\<`string`, `unknown`\> | Contains the data from DataFrame. | -| `extra?` | `readonly` | `any` | Extra data that can be included. Not part of the standard types. | -| `html?` | `readonly` | `string` | HTML representation of the data. | -| `isMainResult` | `readonly` | `boolean` | - | -| `javascript?` | `readonly` | `string` | JavaScript representation of the data. | -| `jpeg?` | `readonly` | `string` | JPEG representation of the data. | -| `json?` | `readonly` | `string` | JSON representation of the data. | -| `latex?` | `readonly` | `string` | LaTeX representation of the data. | -| `markdown?` | `readonly` | `string` | Markdown representation of the data. | -| `pdf?` | `readonly` | `string` | PDF representation of the data. | -| `png?` | `readonly` | `string` | PNG representation of the data. | -| `raw` | `readonly` | `RawData` | - | -| `svg?` | `readonly` | `string` | SVG representation of the data. | -| `text?` | `readonly` | `string` | Text representation of the result. | - -#### Methods - -### formats() - -```ts -formats(): string[] -``` - -Returns all the formats available for the result. - -###### Returns - -`string`[] - -Array of strings representing the formats available for the result. - -### toJSON() - -```ts -toJSON(): object -``` - -Returns the serializable representation of the result. - -###### Returns - -`object` - -| Name | Type | -| ------ | ------ | -| `extra`? | `any` | -| `html` | `undefined` \| `string` | -| `javascript` | `undefined` \| `string` | -| `jpeg` | `undefined` \| `string` | -| `json` | `undefined` \| `string` | -| `latex` | `undefined` \| `string` | -| `markdown` | `undefined` \| `string` | -| `pdf` | `undefined` \| `string` | -| `png` | `undefined` \| `string` | -| `svg` | `undefined` \| `string` | -| `text` | `undefined` \| `string` | - -## Type Aliases - -### Logs - -```ts -type Logs: object; -``` - -Data printed to stdout and stderr during execution, usually by print statements, logs, warnings, subprocesses, etc. - -#### Type declaration - -| Name | Type | Description | -| ------ | ------ | ------ | -| `stderr` | `string`[] | List of strings printed to stderr by prints, subprocesses, etc. | -| `stdout` | `string`[] | List of strings printed to stdout by prints, subprocesses, etc. | - -*** - -### MIMEType - -```ts -type MIMEType: string; -``` - -Represents a MIME type. - -*** - -### RawData - -```ts -type RawData: object & E2BData; -``` - -Dictionary that maps MIME types to their corresponding representations of the data. - -## Functions - -### extractError() - -```ts -function extractError(res: Response): Promise -``` - -#### Parameters - -| Parameter | Type | -| ------ | ------ | -| `res` | `Response` | - -#### Returns - -`Promise`\<`undefined` \| `SandboxError`\> - -*** - -### parseOutput() - -```ts -function parseOutput( - execution: Execution, - line: string, - onStdout?: (output: OutputMessage) => any, - onStderr?: (output: OutputMessage) => any, - onResult?: (data: Result) => any, -onError?: (error: ExecutionError) => any): Promise -``` - -#### Parameters - -| Parameter | Type | -| ------ | ------ | -| `execution` | `Execution` | -| `line` | `string` | -| `onStdout`? | (`output`: `OutputMessage`) => `any` | -| `onStderr`? | (`output`: `OutputMessage`) => `any` | -| `onResult`? | (`data`: `Result`) => `any` | -| `onError`? | (`error`: `ExecutionError`) => `any` | - -#### Returns - -`Promise`\<`void`\> diff --git a/docs/sdk-reference/code-interpreter-js-sdk/v2.3.1/sandbox.mdx b/docs/sdk-reference/code-interpreter-js-sdk/v2.3.1/sandbox.mdx deleted file mode 100644 index fb801ca..0000000 --- a/docs/sdk-reference/code-interpreter-js-sdk/v2.3.1/sandbox.mdx +++ /dev/null @@ -1,371 +0,0 @@ ---- -sidebarTitle: "Sandbox" -mode: "center" ---- - -### Sandbox - -E2B cloud sandbox is a secure and isolated cloud environment. - -The sandbox allows you to: -- Access Linux OS -- Create, list, and delete files and directories -- Run commands -- Run isolated code -- Access the internet - -Check docs here. - -Use Sandbox.create to create a new sandbox. - -#### Example - -```ts -import { Sandbox } from '@e2b/code-interpreter' - -const sandbox = await Sandbox.create() -``` - -#### Methods - -### createCodeContext() - -```ts -createCodeContext(opts?: CreateCodeContextOpts): Promise -``` - -Creates a new context to run code in. - -###### Parameters - -| Parameter | Type | Description | -| ------ | ------ | ------ | -| `opts`? | `CreateCodeContextOpts` | options for creating the context. | - -###### Returns - -`Promise`\<`Context`\> - -context object. - -### listCodeContexts() - -```ts -listCodeContexts(): Promise -``` - -List all contexts. - -###### Returns - -`Promise`\<`Context`[]\> - -list of contexts. - -### removeCodeContext() - -```ts -removeCodeContext(context: string | Context): Promise -``` - -Removes a context. - -###### Parameters - -| Parameter | Type | Description | -| ------ | ------ | ------ | -| `context` | `string` \| `Context` | context to remove. | - -###### Returns - -`Promise`\<`void`\> - -void. - -### restartCodeContext() - -```ts -restartCodeContext(context: string | Context): Promise -``` - -Restart a context. - -###### Parameters - -| Parameter | Type | Description | -| ------ | ------ | ------ | -| `context` | `string` \| `Context` | context to restart. | - -###### Returns - -`Promise`\<`void`\> - -void. - -### runCode() - -###### runCode(code, opts) - -```ts -runCode(code: string, opts?: RunCodeOpts & object): Promise -``` - -Run the code as Python. - -Specify the `language` or `context` option to run the code as a different language or in a different `Context`. - -You can reference previously defined variables, imports, and functions in the code. - -###### Parameters - -| Parameter | Type | Description | -| ------ | ------ | ------ | -| `code` | `string` | code to execute. | -| `opts`? | `RunCodeOpts` & `object` | options for executing the code. | - -###### Returns - -`Promise`\<`Execution`\> - -`Execution` result object. - -###### runCode(code, opts) - -```ts -runCode(code: string, opts?: RunCodeOpts & object): Promise -``` - -Run the code for the specified language. - -Specify the `language` or `context` option to run the code as a different language or in a different `Context`. -If no language is specified, Python is used. - -You can reference previously defined variables, imports, and functions in the code. - -###### Parameters - -| Parameter | Type | Description | -| ------ | ------ | ------ | -| `code` | `string` | code to execute. | -| `opts`? | `RunCodeOpts` & `object` | options for executing the code. | - -###### Returns - -`Promise`\<`Execution`\> - -`Execution` result object. - -###### runCode(code, opts) - -```ts -runCode(code: string, opts?: RunCodeOpts & object): Promise -``` - -Runs the code in the specified context, if not specified, the default context is used. - -Specify the `language` or `context` option to run the code as a different language or in a different `Context`. - -You can reference previously defined variables, imports, and functions in the code. - -###### Parameters - -| Parameter | Type | Description | -| ------ | ------ | ------ | -| `code` | `string` | code to execute. | -| `opts`? | `RunCodeOpts` & `object` | options for executing the code | - -###### Returns - -`Promise`\<`Execution`\> - -`Execution` result object - -## Interfaces - -### CreateCodeContextOpts - -Options for creating a code context. - -#### Properties - -### cwd? - -```ts -optional cwd: string; -``` - -Working directory for the context. - -###### Default - -```ts -/home/user -``` - -### language? - -```ts -optional language: string; -``` - -Language for the context. - -###### Default - -```ts -python -``` - -### requestTimeoutMs? - -```ts -optional requestTimeoutMs: number; -``` - -Timeout for the request in **milliseconds**. - -###### Default - -```ts -30_000 // 30 seconds -``` - -*** - -### RunCodeOpts - -Options for running code. - -#### Properties - -### envs? - -```ts -optional envs: Record; -``` - -Custom environment variables for code execution. - -###### Default - -```ts -{} -``` - -### onError()? - -```ts -optional onError: (error: ExecutionError) => any; -``` - -Callback for handling the `ExecutionError` object. - -###### Parameters - -| Parameter | Type | -| ------ | ------ | -| `error` | `ExecutionError` | - -###### Returns - -`any` - -### onResult()? - -```ts -optional onResult: (data: Result) => any; -``` - -Callback for handling the final execution result. - -###### Parameters - -| Parameter | Type | -| ------ | ------ | -| `data` | `Result` | - -###### Returns - -`any` - -### onStderr()? - -```ts -optional onStderr: (output: OutputMessage) => any; -``` - -Callback for handling stderr messages. - -###### Parameters - -| Parameter | Type | -| ------ | ------ | -| `output` | `OutputMessage` | - -###### Returns - -`any` - -### onStdout()? - -```ts -optional onStdout: (output: OutputMessage) => any; -``` - -Callback for handling stdout messages. - -###### Parameters - -| Parameter | Type | -| ------ | ------ | -| `output` | `OutputMessage` | - -###### Returns - -`any` - -### requestTimeoutMs? - -```ts -optional requestTimeoutMs: number; -``` - -Timeout for the request in **milliseconds**. - -###### Default - -```ts -30_000 // 30 seconds -``` - -### timeoutMs? - -```ts -optional timeoutMs: number; -``` - -Timeout for the code execution in **milliseconds**. - -###### Default - -```ts -60_000 // 60 seconds -``` - -## Type Aliases - -### Context - -```ts -type Context: object; -``` - -Represents a context for code execution. - -#### Type declaration - -| Name | Type | Description | -| ------ | ------ | ------ | -| `cwd` | `string` | The working directory of the context. | -| `id` | `string` | The ID of the context. | -| `language` | `string` | The language of the context. | diff --git a/docs/sdk-reference/code-interpreter-js-sdk/v2.3.2/charts.mdx b/docs/sdk-reference/code-interpreter-js-sdk/v2.3.2/charts.mdx deleted file mode 100644 index d4cf7ad..0000000 --- a/docs/sdk-reference/code-interpreter-js-sdk/v2.3.2/charts.mdx +++ /dev/null @@ -1,245 +0,0 @@ ---- -sidebarTitle: "Charts" -mode: "center" ---- - -### ChartType - -Chart types - -#### Enumeration Members - -| Enumeration Member | Value | -| ------ | ------ | -| `BAR` | `"bar"` | -| `BOX_AND_WHISKER` | `"box_and_whisker"` | -| `LINE` | `"line"` | -| `PIE` | `"pie"` | -| `SCATTER` | `"scatter"` | -| `SUPERCHART` | `"superchart"` | -| `UNKNOWN` | `"unknown"` | - -*** - -### ScaleType - -Ax scale types - -#### Enumeration Members - -| Enumeration Member | Value | -| ------ | ------ | -| `ASINH` | `"asinh"` | -| `CATEGORICAL` | `"categorical"` | -| `DATETIME` | `"datetime"` | -| `FUNCTION` | `"function"` | -| `FUNCTIONLOG` | `"functionlog"` | -| `LINEAR` | `"linear"` | -| `LOG` | `"log"` | -| `LOGIT` | `"logit"` | -| `SYMLOG` | `"symlog"` | - -## Type Aliases - -### BarChart - -```ts -type BarChart: Chart2D & object; -``` - -#### Type declaration - -| Name | Type | -| ------ | ------ | -| `elements` | `BarData`[] | -| `type` | `ChartType.BAR` | - -*** - -### BarData - -```ts -type BarData: object; -``` - -#### Type declaration - -| Name | Type | -| ------ | ------ | -| `group` | `string` | -| `label` | `string` | -| `value` | `string` | - -*** - -### BoxAndWhiskerChart - -```ts -type BoxAndWhiskerChart: Chart2D & object; -``` - -#### Type declaration - -| Name | Type | -| ------ | ------ | -| `elements` | `BoxAndWhiskerData`[] | -| `type` | `ChartType.BOX_AND_WHISKER` | - -*** - -### BoxAndWhiskerData - -```ts -type BoxAndWhiskerData: object; -``` - -#### Type declaration - -| Name | Type | -| ------ | ------ | -| `first_quartile` | `number` | -| `label` | `string` | -| `max` | `number` | -| `median` | `number` | -| `min` | `number` | -| `outliers` | `number`[] | -| `third_quartile` | `number` | - -*** - -### Chart - -```ts -type Chart: object; -``` - -Represents a chart. - -#### Type declaration - -| Name | Type | -| ------ | ------ | -| `elements` | `any`[] | -| `title` | `string` | -| `type` | `ChartType` | - -*** - -### ChartTypes - -```ts -type ChartTypes: - | LineChart - | ScatterChart - | BarChart - | PieChart - | BoxAndWhiskerChart - | SuperChart; -``` - -*** - -### LineChart - -```ts -type LineChart: PointChart & object; -``` - -#### Type declaration - -| Name | Type | -| ------ | ------ | -| `type` | `ChartType.LINE` | - -*** - -### PieChart - -```ts -type PieChart: Chart & object; -``` - -#### Type declaration - -| Name | Type | -| ------ | ------ | -| `elements` | `PieData`[] | -| `type` | `ChartType.PIE` | - -*** - -### PieData - -```ts -type PieData: object; -``` - -#### Type declaration - -| Name | Type | -| ------ | ------ | -| `angle` | `number` | -| `label` | `string` | -| `radius` | `number` | - -*** - -### PointData - -```ts -type PointData: object; -``` - -#### Type declaration - -| Name | Type | -| ------ | ------ | -| `label` | `string` | -| `points` | [`number` \| `string`, `number` \| `string`][] | - -*** - -### ScatterChart - -```ts -type ScatterChart: PointChart & object; -``` - -#### Type declaration - -| Name | Type | -| ------ | ------ | -| `type` | `ChartType.SCATTER` | - -*** - -### SuperChart - -```ts -type SuperChart: Chart & object; -``` - -#### Type declaration - -| Name | Type | -| ------ | ------ | -| `elements` | `Chart`[] | -| `type` | `ChartType.SUPERCHART` | - -## Functions - -### deserializeChart() - -```ts -function deserializeChart(data: any): Chart -``` - -#### Parameters - -| Parameter | Type | -| ------ | ------ | -| `data` | `any` | - -#### Returns - -`Chart` diff --git a/docs/sdk-reference/code-interpreter-js-sdk/v2.3.2/consts.mdx b/docs/sdk-reference/code-interpreter-js-sdk/v2.3.2/consts.mdx deleted file mode 100644 index 07462e7..0000000 --- a/docs/sdk-reference/code-interpreter-js-sdk/v2.3.2/consts.mdx +++ /dev/null @@ -1,18 +0,0 @@ ---- -sidebarTitle: "Consts" -mode: "center" ---- - -### DEFAULT\_TIMEOUT\_MS - -```ts -const DEFAULT_TIMEOUT_MS: 60000 = 60_000; -``` - -*** - -### JUPYTER\_PORT - -```ts -const JUPYTER_PORT: 49999 = 49999; -``` diff --git a/docs/sdk-reference/code-interpreter-js-sdk/v2.3.2/messaging.mdx b/docs/sdk-reference/code-interpreter-js-sdk/v2.3.2/messaging.mdx deleted file mode 100644 index ef4f3e7..0000000 --- a/docs/sdk-reference/code-interpreter-js-sdk/v2.3.2/messaging.mdx +++ /dev/null @@ -1,331 +0,0 @@ ---- -sidebarTitle: "Messaging" -mode: "center" ---- - -### Execution - -Represents the result of a cell execution. - -#### Constructors - -```ts -new Execution( - results: Result[], - logs: Logs, - error?: ExecutionError, - executionCount?: number): Execution -``` - -###### Parameters - -| Parameter | Type | Default value | Description | -| ------ | ------ | ------ | ------ | -| `results` | `Result`[] | `[]` | List of result of the cell (interactively interpreted last line), display calls (e.g. matplotlib plots). | -| `logs` | `Logs` | `...` | Logs printed to stdout and stderr during execution. | -| `error`? | `ExecutionError` | `undefined` | An Error object if an error occurred, null otherwise. | -| `executionCount`? | `number` | `undefined` | Execution count of the cell. | - -###### Returns - -`Execution` - -#### Properties - -| Property | Modifier | Type | Default value | Description | -| ------ | ------ | ------ | ------ | ------ | -| `error?` | `public` | `ExecutionError` | `undefined` | An Error object if an error occurred, null otherwise. | -| `executionCount?` | `public` | `number` | `undefined` | Execution count of the cell. | -| `logs` | `public` | `Logs` | `undefined` | Logs printed to stdout and stderr during execution. | -| `results` | `public` | `Result`[] | `[]` | List of result of the cell (interactively interpreted last line), display calls (e.g. matplotlib plots). | - -#### Accessors - -### text - -```ts -get text(): undefined | string -``` - -Returns the text representation of the main result of the cell. - -###### Returns - -`undefined` \| `string` - -#### Methods - -### toJSON() - -```ts -toJSON(): object -``` - -Returns the serializable representation of the execution result. - -###### Returns - -`object` - -| Name | Type | -| ------ | ------ | -| `error` | `undefined` \| `ExecutionError` | -| `logs` | `Logs` | -| `results` | `Result`[] | - -*** - -### ExecutionError - -Represents an error that occurred during the execution of a cell. -The error contains the name of the error, the value of the error, and the traceback. - -#### Constructors - -```ts -new ExecutionError( - name: string, - value: string, - traceback: string): ExecutionError -``` - -###### Parameters - -| Parameter | Type | Description | -| ------ | ------ | ------ | -| `name` | `string` | Name of the error. | -| `value` | `string` | Value of the error. | -| `traceback` | `string` | The raw traceback of the error. | - -###### Returns - -`ExecutionError` - -#### Properties - -| Property | Modifier | Type | Description | -| ------ | ------ | ------ | ------ | -| `name` | `public` | `string` | Name of the error. | -| `traceback` | `public` | `string` | The raw traceback of the error. | -| `value` | `public` | `string` | Value of the error. | - -*** - -### OutputMessage - -Represents an output message from the sandbox code execution. - -#### Constructors - -```ts -new OutputMessage( - line: string, - timestamp: number, - error: boolean): OutputMessage -``` - -###### Parameters - -| Parameter | Type | Description | -| ------ | ------ | ------ | -| `line` | `string` | The output line. | -| `timestamp` | `number` | Unix epoch in nanoseconds. | -| `error` | `boolean` | Whether the output is an error. | - -###### Returns - -`OutputMessage` - -#### Properties - -| Property | Modifier | Type | Description | -| ------ | ------ | ------ | ------ | -| `error` | `readonly` | `boolean` | Whether the output is an error. | -| `line` | `readonly` | `string` | The output line. | -| `timestamp` | `readonly` | `number` | Unix epoch in nanoseconds. | - -#### Methods - -### toString() - -```ts -toString(): string -``` - -###### Returns - -`string` - -*** - -### Result - -Represents the data to be displayed as a result of executing a cell in a Jupyter notebook. -The result is similar to the structure returned by ipython kernel: https://ipython.readthedocs.io/en/stable/development/execution.html#execution-semantics - -The result can contain multiple types of data, such as text, images, plots, etc. Each type of data is represented -as a string, and the result can contain multiple types of data. The display calls don't have to have text representation, -for the actual result the representation is always present for the result, the other representations are always optional. - -#### Constructors - -```ts -new Result(rawData: RawData, isMainResult: boolean): Result -``` - -###### Parameters - -| Parameter | Type | -| ------ | ------ | -| `rawData` | `RawData` | -| `isMainResult` | `boolean` | - -###### Returns - -`Result` - -#### Properties - -| Property | Modifier | Type | Description | -| ------ | ------ | ------ | ------ | -| `chart?` | `readonly` | `ChartTypes` | Contains the chart data. | -| `data?` | `readonly` | `Record`\<`string`, `unknown`\> | Contains the data from DataFrame. | -| `extra?` | `readonly` | `any` | Extra data that can be included. Not part of the standard types. | -| `html?` | `readonly` | `string` | HTML representation of the data. | -| `isMainResult` | `readonly` | `boolean` | - | -| `javascript?` | `readonly` | `string` | JavaScript representation of the data. | -| `jpeg?` | `readonly` | `string` | JPEG representation of the data. | -| `json?` | `readonly` | `string` | JSON representation of the data. | -| `latex?` | `readonly` | `string` | LaTeX representation of the data. | -| `markdown?` | `readonly` | `string` | Markdown representation of the data. | -| `pdf?` | `readonly` | `string` | PDF representation of the data. | -| `png?` | `readonly` | `string` | PNG representation of the data. | -| `raw` | `readonly` | `RawData` | - | -| `svg?` | `readonly` | `string` | SVG representation of the data. | -| `text?` | `readonly` | `string` | Text representation of the result. | - -#### Methods - -### formats() - -```ts -formats(): string[] -``` - -Returns all the formats available for the result. - -###### Returns - -`string`[] - -Array of strings representing the formats available for the result. - -### toJSON() - -```ts -toJSON(): object -``` - -Returns the serializable representation of the result. - -###### Returns - -`object` - -| Name | Type | -| ------ | ------ | -| `extra`? | `any` | -| `html` | `undefined` \| `string` | -| `javascript` | `undefined` \| `string` | -| `jpeg` | `undefined` \| `string` | -| `json` | `undefined` \| `string` | -| `latex` | `undefined` \| `string` | -| `markdown` | `undefined` \| `string` | -| `pdf` | `undefined` \| `string` | -| `png` | `undefined` \| `string` | -| `svg` | `undefined` \| `string` | -| `text` | `undefined` \| `string` | - -## Type Aliases - -### Logs - -```ts -type Logs: object; -``` - -Data printed to stdout and stderr during execution, usually by print statements, logs, warnings, subprocesses, etc. - -#### Type declaration - -| Name | Type | Description | -| ------ | ------ | ------ | -| `stderr` | `string`[] | List of strings printed to stderr by prints, subprocesses, etc. | -| `stdout` | `string`[] | List of strings printed to stdout by prints, subprocesses, etc. | - -*** - -### MIMEType - -```ts -type MIMEType: string; -``` - -Represents a MIME type. - -*** - -### RawData - -```ts -type RawData: object & E2BData; -``` - -Dictionary that maps MIME types to their corresponding representations of the data. - -## Functions - -### extractError() - -```ts -function extractError(res: Response): Promise -``` - -#### Parameters - -| Parameter | Type | -| ------ | ------ | -| `res` | `Response` | - -#### Returns - -`Promise`\<`undefined` \| `SandboxError`\> - -*** - -### parseOutput() - -```ts -function parseOutput( - execution: Execution, - line: string, - onStdout?: (output: OutputMessage) => any, - onStderr?: (output: OutputMessage) => any, - onResult?: (data: Result) => any, -onError?: (error: ExecutionError) => any): Promise -``` - -#### Parameters - -| Parameter | Type | -| ------ | ------ | -| `execution` | `Execution` | -| `line` | `string` | -| `onStdout`? | (`output`: `OutputMessage`) => `any` | -| `onStderr`? | (`output`: `OutputMessage`) => `any` | -| `onResult`? | (`data`: `Result`) => `any` | -| `onError`? | (`error`: `ExecutionError`) => `any` | - -#### Returns - -`Promise`\<`void`\> diff --git a/docs/sdk-reference/code-interpreter-js-sdk/v2.3.2/sandbox.mdx b/docs/sdk-reference/code-interpreter-js-sdk/v2.3.2/sandbox.mdx deleted file mode 100644 index fb801ca..0000000 --- a/docs/sdk-reference/code-interpreter-js-sdk/v2.3.2/sandbox.mdx +++ /dev/null @@ -1,371 +0,0 @@ ---- -sidebarTitle: "Sandbox" -mode: "center" ---- - -### Sandbox - -E2B cloud sandbox is a secure and isolated cloud environment. - -The sandbox allows you to: -- Access Linux OS -- Create, list, and delete files and directories -- Run commands -- Run isolated code -- Access the internet - -Check docs here. - -Use Sandbox.create to create a new sandbox. - -#### Example - -```ts -import { Sandbox } from '@e2b/code-interpreter' - -const sandbox = await Sandbox.create() -``` - -#### Methods - -### createCodeContext() - -```ts -createCodeContext(opts?: CreateCodeContextOpts): Promise -``` - -Creates a new context to run code in. - -###### Parameters - -| Parameter | Type | Description | -| ------ | ------ | ------ | -| `opts`? | `CreateCodeContextOpts` | options for creating the context. | - -###### Returns - -`Promise`\<`Context`\> - -context object. - -### listCodeContexts() - -```ts -listCodeContexts(): Promise -``` - -List all contexts. - -###### Returns - -`Promise`\<`Context`[]\> - -list of contexts. - -### removeCodeContext() - -```ts -removeCodeContext(context: string | Context): Promise -``` - -Removes a context. - -###### Parameters - -| Parameter | Type | Description | -| ------ | ------ | ------ | -| `context` | `string` \| `Context` | context to remove. | - -###### Returns - -`Promise`\<`void`\> - -void. - -### restartCodeContext() - -```ts -restartCodeContext(context: string | Context): Promise -``` - -Restart a context. - -###### Parameters - -| Parameter | Type | Description | -| ------ | ------ | ------ | -| `context` | `string` \| `Context` | context to restart. | - -###### Returns - -`Promise`\<`void`\> - -void. - -### runCode() - -###### runCode(code, opts) - -```ts -runCode(code: string, opts?: RunCodeOpts & object): Promise -``` - -Run the code as Python. - -Specify the `language` or `context` option to run the code as a different language or in a different `Context`. - -You can reference previously defined variables, imports, and functions in the code. - -###### Parameters - -| Parameter | Type | Description | -| ------ | ------ | ------ | -| `code` | `string` | code to execute. | -| `opts`? | `RunCodeOpts` & `object` | options for executing the code. | - -###### Returns - -`Promise`\<`Execution`\> - -`Execution` result object. - -###### runCode(code, opts) - -```ts -runCode(code: string, opts?: RunCodeOpts & object): Promise -``` - -Run the code for the specified language. - -Specify the `language` or `context` option to run the code as a different language or in a different `Context`. -If no language is specified, Python is used. - -You can reference previously defined variables, imports, and functions in the code. - -###### Parameters - -| Parameter | Type | Description | -| ------ | ------ | ------ | -| `code` | `string` | code to execute. | -| `opts`? | `RunCodeOpts` & `object` | options for executing the code. | - -###### Returns - -`Promise`\<`Execution`\> - -`Execution` result object. - -###### runCode(code, opts) - -```ts -runCode(code: string, opts?: RunCodeOpts & object): Promise -``` - -Runs the code in the specified context, if not specified, the default context is used. - -Specify the `language` or `context` option to run the code as a different language or in a different `Context`. - -You can reference previously defined variables, imports, and functions in the code. - -###### Parameters - -| Parameter | Type | Description | -| ------ | ------ | ------ | -| `code` | `string` | code to execute. | -| `opts`? | `RunCodeOpts` & `object` | options for executing the code | - -###### Returns - -`Promise`\<`Execution`\> - -`Execution` result object - -## Interfaces - -### CreateCodeContextOpts - -Options for creating a code context. - -#### Properties - -### cwd? - -```ts -optional cwd: string; -``` - -Working directory for the context. - -###### Default - -```ts -/home/user -``` - -### language? - -```ts -optional language: string; -``` - -Language for the context. - -###### Default - -```ts -python -``` - -### requestTimeoutMs? - -```ts -optional requestTimeoutMs: number; -``` - -Timeout for the request in **milliseconds**. - -###### Default - -```ts -30_000 // 30 seconds -``` - -*** - -### RunCodeOpts - -Options for running code. - -#### Properties - -### envs? - -```ts -optional envs: Record; -``` - -Custom environment variables for code execution. - -###### Default - -```ts -{} -``` - -### onError()? - -```ts -optional onError: (error: ExecutionError) => any; -``` - -Callback for handling the `ExecutionError` object. - -###### Parameters - -| Parameter | Type | -| ------ | ------ | -| `error` | `ExecutionError` | - -###### Returns - -`any` - -### onResult()? - -```ts -optional onResult: (data: Result) => any; -``` - -Callback for handling the final execution result. - -###### Parameters - -| Parameter | Type | -| ------ | ------ | -| `data` | `Result` | - -###### Returns - -`any` - -### onStderr()? - -```ts -optional onStderr: (output: OutputMessage) => any; -``` - -Callback for handling stderr messages. - -###### Parameters - -| Parameter | Type | -| ------ | ------ | -| `output` | `OutputMessage` | - -###### Returns - -`any` - -### onStdout()? - -```ts -optional onStdout: (output: OutputMessage) => any; -``` - -Callback for handling stdout messages. - -###### Parameters - -| Parameter | Type | -| ------ | ------ | -| `output` | `OutputMessage` | - -###### Returns - -`any` - -### requestTimeoutMs? - -```ts -optional requestTimeoutMs: number; -``` - -Timeout for the request in **milliseconds**. - -###### Default - -```ts -30_000 // 30 seconds -``` - -### timeoutMs? - -```ts -optional timeoutMs: number; -``` - -Timeout for the code execution in **milliseconds**. - -###### Default - -```ts -60_000 // 60 seconds -``` - -## Type Aliases - -### Context - -```ts -type Context: object; -``` - -Represents a context for code execution. - -#### Type declaration - -| Name | Type | Description | -| ------ | ------ | ------ | -| `cwd` | `string` | The working directory of the context. | -| `id` | `string` | The ID of the context. | -| `language` | `string` | The language of the context. | diff --git a/docs/sdk-reference/code-interpreter-js-sdk/v2.3.3/charts.mdx b/docs/sdk-reference/code-interpreter-js-sdk/v2.3.3/charts.mdx deleted file mode 100644 index d4cf7ad..0000000 --- a/docs/sdk-reference/code-interpreter-js-sdk/v2.3.3/charts.mdx +++ /dev/null @@ -1,245 +0,0 @@ ---- -sidebarTitle: "Charts" -mode: "center" ---- - -### ChartType - -Chart types - -#### Enumeration Members - -| Enumeration Member | Value | -| ------ | ------ | -| `BAR` | `"bar"` | -| `BOX_AND_WHISKER` | `"box_and_whisker"` | -| `LINE` | `"line"` | -| `PIE` | `"pie"` | -| `SCATTER` | `"scatter"` | -| `SUPERCHART` | `"superchart"` | -| `UNKNOWN` | `"unknown"` | - -*** - -### ScaleType - -Ax scale types - -#### Enumeration Members - -| Enumeration Member | Value | -| ------ | ------ | -| `ASINH` | `"asinh"` | -| `CATEGORICAL` | `"categorical"` | -| `DATETIME` | `"datetime"` | -| `FUNCTION` | `"function"` | -| `FUNCTIONLOG` | `"functionlog"` | -| `LINEAR` | `"linear"` | -| `LOG` | `"log"` | -| `LOGIT` | `"logit"` | -| `SYMLOG` | `"symlog"` | - -## Type Aliases - -### BarChart - -```ts -type BarChart: Chart2D & object; -``` - -#### Type declaration - -| Name | Type | -| ------ | ------ | -| `elements` | `BarData`[] | -| `type` | `ChartType.BAR` | - -*** - -### BarData - -```ts -type BarData: object; -``` - -#### Type declaration - -| Name | Type | -| ------ | ------ | -| `group` | `string` | -| `label` | `string` | -| `value` | `string` | - -*** - -### BoxAndWhiskerChart - -```ts -type BoxAndWhiskerChart: Chart2D & object; -``` - -#### Type declaration - -| Name | Type | -| ------ | ------ | -| `elements` | `BoxAndWhiskerData`[] | -| `type` | `ChartType.BOX_AND_WHISKER` | - -*** - -### BoxAndWhiskerData - -```ts -type BoxAndWhiskerData: object; -``` - -#### Type declaration - -| Name | Type | -| ------ | ------ | -| `first_quartile` | `number` | -| `label` | `string` | -| `max` | `number` | -| `median` | `number` | -| `min` | `number` | -| `outliers` | `number`[] | -| `third_quartile` | `number` | - -*** - -### Chart - -```ts -type Chart: object; -``` - -Represents a chart. - -#### Type declaration - -| Name | Type | -| ------ | ------ | -| `elements` | `any`[] | -| `title` | `string` | -| `type` | `ChartType` | - -*** - -### ChartTypes - -```ts -type ChartTypes: - | LineChart - | ScatterChart - | BarChart - | PieChart - | BoxAndWhiskerChart - | SuperChart; -``` - -*** - -### LineChart - -```ts -type LineChart: PointChart & object; -``` - -#### Type declaration - -| Name | Type | -| ------ | ------ | -| `type` | `ChartType.LINE` | - -*** - -### PieChart - -```ts -type PieChart: Chart & object; -``` - -#### Type declaration - -| Name | Type | -| ------ | ------ | -| `elements` | `PieData`[] | -| `type` | `ChartType.PIE` | - -*** - -### PieData - -```ts -type PieData: object; -``` - -#### Type declaration - -| Name | Type | -| ------ | ------ | -| `angle` | `number` | -| `label` | `string` | -| `radius` | `number` | - -*** - -### PointData - -```ts -type PointData: object; -``` - -#### Type declaration - -| Name | Type | -| ------ | ------ | -| `label` | `string` | -| `points` | [`number` \| `string`, `number` \| `string`][] | - -*** - -### ScatterChart - -```ts -type ScatterChart: PointChart & object; -``` - -#### Type declaration - -| Name | Type | -| ------ | ------ | -| `type` | `ChartType.SCATTER` | - -*** - -### SuperChart - -```ts -type SuperChart: Chart & object; -``` - -#### Type declaration - -| Name | Type | -| ------ | ------ | -| `elements` | `Chart`[] | -| `type` | `ChartType.SUPERCHART` | - -## Functions - -### deserializeChart() - -```ts -function deserializeChart(data: any): Chart -``` - -#### Parameters - -| Parameter | Type | -| ------ | ------ | -| `data` | `any` | - -#### Returns - -`Chart` diff --git a/docs/sdk-reference/code-interpreter-js-sdk/v2.3.3/consts.mdx b/docs/sdk-reference/code-interpreter-js-sdk/v2.3.3/consts.mdx deleted file mode 100644 index 07462e7..0000000 --- a/docs/sdk-reference/code-interpreter-js-sdk/v2.3.3/consts.mdx +++ /dev/null @@ -1,18 +0,0 @@ ---- -sidebarTitle: "Consts" -mode: "center" ---- - -### DEFAULT\_TIMEOUT\_MS - -```ts -const DEFAULT_TIMEOUT_MS: 60000 = 60_000; -``` - -*** - -### JUPYTER\_PORT - -```ts -const JUPYTER_PORT: 49999 = 49999; -``` diff --git a/docs/sdk-reference/code-interpreter-js-sdk/v2.3.3/messaging.mdx b/docs/sdk-reference/code-interpreter-js-sdk/v2.3.3/messaging.mdx deleted file mode 100644 index ef4f3e7..0000000 --- a/docs/sdk-reference/code-interpreter-js-sdk/v2.3.3/messaging.mdx +++ /dev/null @@ -1,331 +0,0 @@ ---- -sidebarTitle: "Messaging" -mode: "center" ---- - -### Execution - -Represents the result of a cell execution. - -#### Constructors - -```ts -new Execution( - results: Result[], - logs: Logs, - error?: ExecutionError, - executionCount?: number): Execution -``` - -###### Parameters - -| Parameter | Type | Default value | Description | -| ------ | ------ | ------ | ------ | -| `results` | `Result`[] | `[]` | List of result of the cell (interactively interpreted last line), display calls (e.g. matplotlib plots). | -| `logs` | `Logs` | `...` | Logs printed to stdout and stderr during execution. | -| `error`? | `ExecutionError` | `undefined` | An Error object if an error occurred, null otherwise. | -| `executionCount`? | `number` | `undefined` | Execution count of the cell. | - -###### Returns - -`Execution` - -#### Properties - -| Property | Modifier | Type | Default value | Description | -| ------ | ------ | ------ | ------ | ------ | -| `error?` | `public` | `ExecutionError` | `undefined` | An Error object if an error occurred, null otherwise. | -| `executionCount?` | `public` | `number` | `undefined` | Execution count of the cell. | -| `logs` | `public` | `Logs` | `undefined` | Logs printed to stdout and stderr during execution. | -| `results` | `public` | `Result`[] | `[]` | List of result of the cell (interactively interpreted last line), display calls (e.g. matplotlib plots). | - -#### Accessors - -### text - -```ts -get text(): undefined | string -``` - -Returns the text representation of the main result of the cell. - -###### Returns - -`undefined` \| `string` - -#### Methods - -### toJSON() - -```ts -toJSON(): object -``` - -Returns the serializable representation of the execution result. - -###### Returns - -`object` - -| Name | Type | -| ------ | ------ | -| `error` | `undefined` \| `ExecutionError` | -| `logs` | `Logs` | -| `results` | `Result`[] | - -*** - -### ExecutionError - -Represents an error that occurred during the execution of a cell. -The error contains the name of the error, the value of the error, and the traceback. - -#### Constructors - -```ts -new ExecutionError( - name: string, - value: string, - traceback: string): ExecutionError -``` - -###### Parameters - -| Parameter | Type | Description | -| ------ | ------ | ------ | -| `name` | `string` | Name of the error. | -| `value` | `string` | Value of the error. | -| `traceback` | `string` | The raw traceback of the error. | - -###### Returns - -`ExecutionError` - -#### Properties - -| Property | Modifier | Type | Description | -| ------ | ------ | ------ | ------ | -| `name` | `public` | `string` | Name of the error. | -| `traceback` | `public` | `string` | The raw traceback of the error. | -| `value` | `public` | `string` | Value of the error. | - -*** - -### OutputMessage - -Represents an output message from the sandbox code execution. - -#### Constructors - -```ts -new OutputMessage( - line: string, - timestamp: number, - error: boolean): OutputMessage -``` - -###### Parameters - -| Parameter | Type | Description | -| ------ | ------ | ------ | -| `line` | `string` | The output line. | -| `timestamp` | `number` | Unix epoch in nanoseconds. | -| `error` | `boolean` | Whether the output is an error. | - -###### Returns - -`OutputMessage` - -#### Properties - -| Property | Modifier | Type | Description | -| ------ | ------ | ------ | ------ | -| `error` | `readonly` | `boolean` | Whether the output is an error. | -| `line` | `readonly` | `string` | The output line. | -| `timestamp` | `readonly` | `number` | Unix epoch in nanoseconds. | - -#### Methods - -### toString() - -```ts -toString(): string -``` - -###### Returns - -`string` - -*** - -### Result - -Represents the data to be displayed as a result of executing a cell in a Jupyter notebook. -The result is similar to the structure returned by ipython kernel: https://ipython.readthedocs.io/en/stable/development/execution.html#execution-semantics - -The result can contain multiple types of data, such as text, images, plots, etc. Each type of data is represented -as a string, and the result can contain multiple types of data. The display calls don't have to have text representation, -for the actual result the representation is always present for the result, the other representations are always optional. - -#### Constructors - -```ts -new Result(rawData: RawData, isMainResult: boolean): Result -``` - -###### Parameters - -| Parameter | Type | -| ------ | ------ | -| `rawData` | `RawData` | -| `isMainResult` | `boolean` | - -###### Returns - -`Result` - -#### Properties - -| Property | Modifier | Type | Description | -| ------ | ------ | ------ | ------ | -| `chart?` | `readonly` | `ChartTypes` | Contains the chart data. | -| `data?` | `readonly` | `Record`\<`string`, `unknown`\> | Contains the data from DataFrame. | -| `extra?` | `readonly` | `any` | Extra data that can be included. Not part of the standard types. | -| `html?` | `readonly` | `string` | HTML representation of the data. | -| `isMainResult` | `readonly` | `boolean` | - | -| `javascript?` | `readonly` | `string` | JavaScript representation of the data. | -| `jpeg?` | `readonly` | `string` | JPEG representation of the data. | -| `json?` | `readonly` | `string` | JSON representation of the data. | -| `latex?` | `readonly` | `string` | LaTeX representation of the data. | -| `markdown?` | `readonly` | `string` | Markdown representation of the data. | -| `pdf?` | `readonly` | `string` | PDF representation of the data. | -| `png?` | `readonly` | `string` | PNG representation of the data. | -| `raw` | `readonly` | `RawData` | - | -| `svg?` | `readonly` | `string` | SVG representation of the data. | -| `text?` | `readonly` | `string` | Text representation of the result. | - -#### Methods - -### formats() - -```ts -formats(): string[] -``` - -Returns all the formats available for the result. - -###### Returns - -`string`[] - -Array of strings representing the formats available for the result. - -### toJSON() - -```ts -toJSON(): object -``` - -Returns the serializable representation of the result. - -###### Returns - -`object` - -| Name | Type | -| ------ | ------ | -| `extra`? | `any` | -| `html` | `undefined` \| `string` | -| `javascript` | `undefined` \| `string` | -| `jpeg` | `undefined` \| `string` | -| `json` | `undefined` \| `string` | -| `latex` | `undefined` \| `string` | -| `markdown` | `undefined` \| `string` | -| `pdf` | `undefined` \| `string` | -| `png` | `undefined` \| `string` | -| `svg` | `undefined` \| `string` | -| `text` | `undefined` \| `string` | - -## Type Aliases - -### Logs - -```ts -type Logs: object; -``` - -Data printed to stdout and stderr during execution, usually by print statements, logs, warnings, subprocesses, etc. - -#### Type declaration - -| Name | Type | Description | -| ------ | ------ | ------ | -| `stderr` | `string`[] | List of strings printed to stderr by prints, subprocesses, etc. | -| `stdout` | `string`[] | List of strings printed to stdout by prints, subprocesses, etc. | - -*** - -### MIMEType - -```ts -type MIMEType: string; -``` - -Represents a MIME type. - -*** - -### RawData - -```ts -type RawData: object & E2BData; -``` - -Dictionary that maps MIME types to their corresponding representations of the data. - -## Functions - -### extractError() - -```ts -function extractError(res: Response): Promise -``` - -#### Parameters - -| Parameter | Type | -| ------ | ------ | -| `res` | `Response` | - -#### Returns - -`Promise`\<`undefined` \| `SandboxError`\> - -*** - -### parseOutput() - -```ts -function parseOutput( - execution: Execution, - line: string, - onStdout?: (output: OutputMessage) => any, - onStderr?: (output: OutputMessage) => any, - onResult?: (data: Result) => any, -onError?: (error: ExecutionError) => any): Promise -``` - -#### Parameters - -| Parameter | Type | -| ------ | ------ | -| `execution` | `Execution` | -| `line` | `string` | -| `onStdout`? | (`output`: `OutputMessage`) => `any` | -| `onStderr`? | (`output`: `OutputMessage`) => `any` | -| `onResult`? | (`data`: `Result`) => `any` | -| `onError`? | (`error`: `ExecutionError`) => `any` | - -#### Returns - -`Promise`\<`void`\> diff --git a/docs/sdk-reference/code-interpreter-js-sdk/v2.3.3/sandbox.mdx b/docs/sdk-reference/code-interpreter-js-sdk/v2.3.3/sandbox.mdx deleted file mode 100644 index fb801ca..0000000 --- a/docs/sdk-reference/code-interpreter-js-sdk/v2.3.3/sandbox.mdx +++ /dev/null @@ -1,371 +0,0 @@ ---- -sidebarTitle: "Sandbox" -mode: "center" ---- - -### Sandbox - -E2B cloud sandbox is a secure and isolated cloud environment. - -The sandbox allows you to: -- Access Linux OS -- Create, list, and delete files and directories -- Run commands -- Run isolated code -- Access the internet - -Check docs here. - -Use Sandbox.create to create a new sandbox. - -#### Example - -```ts -import { Sandbox } from '@e2b/code-interpreter' - -const sandbox = await Sandbox.create() -``` - -#### Methods - -### createCodeContext() - -```ts -createCodeContext(opts?: CreateCodeContextOpts): Promise -``` - -Creates a new context to run code in. - -###### Parameters - -| Parameter | Type | Description | -| ------ | ------ | ------ | -| `opts`? | `CreateCodeContextOpts` | options for creating the context. | - -###### Returns - -`Promise`\<`Context`\> - -context object. - -### listCodeContexts() - -```ts -listCodeContexts(): Promise -``` - -List all contexts. - -###### Returns - -`Promise`\<`Context`[]\> - -list of contexts. - -### removeCodeContext() - -```ts -removeCodeContext(context: string | Context): Promise -``` - -Removes a context. - -###### Parameters - -| Parameter | Type | Description | -| ------ | ------ | ------ | -| `context` | `string` \| `Context` | context to remove. | - -###### Returns - -`Promise`\<`void`\> - -void. - -### restartCodeContext() - -```ts -restartCodeContext(context: string | Context): Promise -``` - -Restart a context. - -###### Parameters - -| Parameter | Type | Description | -| ------ | ------ | ------ | -| `context` | `string` \| `Context` | context to restart. | - -###### Returns - -`Promise`\<`void`\> - -void. - -### runCode() - -###### runCode(code, opts) - -```ts -runCode(code: string, opts?: RunCodeOpts & object): Promise -``` - -Run the code as Python. - -Specify the `language` or `context` option to run the code as a different language or in a different `Context`. - -You can reference previously defined variables, imports, and functions in the code. - -###### Parameters - -| Parameter | Type | Description | -| ------ | ------ | ------ | -| `code` | `string` | code to execute. | -| `opts`? | `RunCodeOpts` & `object` | options for executing the code. | - -###### Returns - -`Promise`\<`Execution`\> - -`Execution` result object. - -###### runCode(code, opts) - -```ts -runCode(code: string, opts?: RunCodeOpts & object): Promise -``` - -Run the code for the specified language. - -Specify the `language` or `context` option to run the code as a different language or in a different `Context`. -If no language is specified, Python is used. - -You can reference previously defined variables, imports, and functions in the code. - -###### Parameters - -| Parameter | Type | Description | -| ------ | ------ | ------ | -| `code` | `string` | code to execute. | -| `opts`? | `RunCodeOpts` & `object` | options for executing the code. | - -###### Returns - -`Promise`\<`Execution`\> - -`Execution` result object. - -###### runCode(code, opts) - -```ts -runCode(code: string, opts?: RunCodeOpts & object): Promise -``` - -Runs the code in the specified context, if not specified, the default context is used. - -Specify the `language` or `context` option to run the code as a different language or in a different `Context`. - -You can reference previously defined variables, imports, and functions in the code. - -###### Parameters - -| Parameter | Type | Description | -| ------ | ------ | ------ | -| `code` | `string` | code to execute. | -| `opts`? | `RunCodeOpts` & `object` | options for executing the code | - -###### Returns - -`Promise`\<`Execution`\> - -`Execution` result object - -## Interfaces - -### CreateCodeContextOpts - -Options for creating a code context. - -#### Properties - -### cwd? - -```ts -optional cwd: string; -``` - -Working directory for the context. - -###### Default - -```ts -/home/user -``` - -### language? - -```ts -optional language: string; -``` - -Language for the context. - -###### Default - -```ts -python -``` - -### requestTimeoutMs? - -```ts -optional requestTimeoutMs: number; -``` - -Timeout for the request in **milliseconds**. - -###### Default - -```ts -30_000 // 30 seconds -``` - -*** - -### RunCodeOpts - -Options for running code. - -#### Properties - -### envs? - -```ts -optional envs: Record; -``` - -Custom environment variables for code execution. - -###### Default - -```ts -{} -``` - -### onError()? - -```ts -optional onError: (error: ExecutionError) => any; -``` - -Callback for handling the `ExecutionError` object. - -###### Parameters - -| Parameter | Type | -| ------ | ------ | -| `error` | `ExecutionError` | - -###### Returns - -`any` - -### onResult()? - -```ts -optional onResult: (data: Result) => any; -``` - -Callback for handling the final execution result. - -###### Parameters - -| Parameter | Type | -| ------ | ------ | -| `data` | `Result` | - -###### Returns - -`any` - -### onStderr()? - -```ts -optional onStderr: (output: OutputMessage) => any; -``` - -Callback for handling stderr messages. - -###### Parameters - -| Parameter | Type | -| ------ | ------ | -| `output` | `OutputMessage` | - -###### Returns - -`any` - -### onStdout()? - -```ts -optional onStdout: (output: OutputMessage) => any; -``` - -Callback for handling stdout messages. - -###### Parameters - -| Parameter | Type | -| ------ | ------ | -| `output` | `OutputMessage` | - -###### Returns - -`any` - -### requestTimeoutMs? - -```ts -optional requestTimeoutMs: number; -``` - -Timeout for the request in **milliseconds**. - -###### Default - -```ts -30_000 // 30 seconds -``` - -### timeoutMs? - -```ts -optional timeoutMs: number; -``` - -Timeout for the code execution in **milliseconds**. - -###### Default - -```ts -60_000 // 60 seconds -``` - -## Type Aliases - -### Context - -```ts -type Context: object; -``` - -Represents a context for code execution. - -#### Type declaration - -| Name | Type | Description | -| ------ | ------ | ------ | -| `cwd` | `string` | The working directory of the context. | -| `id` | `string` | The ID of the context. | -| `language` | `string` | The language of the context. | diff --git a/docs/sdk-reference/code-interpreter-python-sdk/1.0.1/code_interpreter.mdx b/docs/sdk-reference/code-interpreter-python-sdk/1.0.1/code_interpreter.mdx deleted file mode 100644 index 0d3e5ea..0000000 --- a/docs/sdk-reference/code-interpreter-python-sdk/1.0.1/code_interpreter.mdx +++ /dev/null @@ -1,786 +0,0 @@ ---- -sidebarTitle: "Code Interpreter" -mode: "center" ---- - - - - - - - - - -## AsyncSandbox - -```python -class AsyncSandbox(BaseAsyncSandbox) -``` - -E2B cloud sandbox is a secure and isolated cloud environment. - -The sandbox allows you to: -- Access Linux OS -- Create, list, and delete files and directories -- Run commands -- Run isolated code -- Access the internet - -Check docs [here](https://e2b.dev/docs). - -Use the `AsyncSandbox.create()` to create a new sandbox. - -**Example**: - -```python -from e2b_code_interpreter import AsyncSandbox -sandbox = await AsyncSandbox.create() -``` - - - -### run\_code - -```python -@overload -async def run_code(code: str, - language: Union[Literal["python"], None] = None, - on_stdout: Optional[OutputHandler[OutputMessage]] = None, - on_stderr: Optional[OutputHandler[OutputMessage]] = None, - on_result: Optional[OutputHandler[Result]] = None, - on_error: Optional[OutputHandler[ExecutionError]] = None, - envs: Optional[Dict[str, str]] = None, - timeout: Optional[float] = None, - request_timeout: Optional[float] = None) -> Execution -``` - -Runs the code as Python. - -Specify the `language` or `context` option to run the code as a different language or in a different `Context`. - -You can reference previously defined variables, imports, and functions in the code. - -**Arguments**: - -- `code`: Code to execute -- `language`: Language to use for code execution. If not defined, the default Python context is used. -- `on_stdout`: Callback for stdout messages -- `on_stderr`: Callback for stderr messages -- `on_result`: Callback for the `Result` object -- `on_error`: Callback for the `ExecutionError` object -- `envs`: Custom environment variables -- `timeout`: Timeout for the code execution in **seconds** -- `request_timeout`: Timeout for the request in **seconds** - -**Returns**: - -`Execution` result object - - - -### run\_code - -```python -@overload -async def run_code(code: str, - language: Optional[str] = None, - on_stdout: Optional[OutputHandler[OutputMessage]] = None, - on_stderr: Optional[OutputHandler[OutputMessage]] = None, - on_result: Optional[OutputHandler[Result]] = None, - on_error: Optional[OutputHandler[ExecutionError]] = None, - envs: Optional[Dict[str, str]] = None, - timeout: Optional[float] = None, - request_timeout: Optional[float] = None) -> Execution -``` - -Runs the code for the specified language. - -Specify the `language` or `context` option to run the code as a different language or in a different `Context`. -If no language is specified, Python is used. - -You can reference previously defined variables, imports, and functions in the code. - -**Arguments**: - -- `code`: Code to execute -- `language`: Language to use for code execution. If not defined, the default Python context is used. -- `on_stdout`: Callback for stdout messages -- `on_stderr`: Callback for stderr messages -- `on_result`: Callback for the `Result` object -- `on_error`: Callback for the `ExecutionError` object -- `envs`: Custom environment variables -- `timeout`: Timeout for the code execution in **seconds** -- `request_timeout`: Timeout for the request in **seconds** - -**Returns**: - -`Execution` result object - - - -### run\_code - -```python -@overload -async def run_code(code: str, - context: Optional[Context] = None, - on_stdout: Optional[OutputHandler[OutputMessage]] = None, - on_stderr: Optional[OutputHandler[OutputMessage]] = None, - on_result: Optional[OutputHandler[Result]] = None, - on_error: Optional[OutputHandler[ExecutionError]] = None, - envs: Optional[Dict[str, str]] = None, - timeout: Optional[float] = None, - request_timeout: Optional[float] = None) -> Execution -``` - -Runs the code in the specified context, if not specified, the default context is used. - -Specify the `language` or `context` option to run the code as a different language or in a different `Context`. - -You can reference previously defined variables, imports, and functions in the code. - -**Arguments**: - -- `code`: Code to execute -- `context`: Concrete context to run the code in. If not specified, the default context for the language is used. It's mutually exclusive with the language. -- `on_stdout`: Callback for stdout messages -- `on_stderr`: Callback for stderr messages -- `on_result`: Callback for the `Result` object -- `on_error`: Callback for the `ExecutionError` object -- `envs`: Custom environment variables -- `timeout`: Timeout for the code execution in **seconds** -- `request_timeout`: Timeout for the request in **seconds** - -**Returns**: - -`Execution` result object - - - -### create\_code\_context - -```python -async def create_code_context( - cwd: Optional[str] = None, - language: Optional[str] = None, - request_timeout: Optional[float] = None) -> Context -``` - -Creates a new context to run code in. - -**Arguments**: - -- `cwd`: Set the current working directory for the context, defaults to `/home/user` -- `language`: Language of the context. If not specified, defaults to Python -- `request_timeout`: Timeout for the request in **milliseconds** - -**Returns**: - -Context object - - - - - - -## OutputMessage - -```python -@dataclass -class OutputMessage() -``` - -Represents an output message from the sandbox code execution. - - - -### line - -The output line. - - - -### timestamp - -Unix epoch in nanoseconds - - - -### error - -Whether the output is an error. - - - -## ExecutionError - -```python -@dataclass -class ExecutionError() -``` - -Represents an error that occurred during the execution of a cell. -The error contains the name of the error, the value of the error, and the traceback. - - - -### name - -Name of the error. - - - -### value - -Value of the error. - - - -### traceback - -The raw traceback of the error. - - - -### to\_json - -```python -def to_json() -> str -``` - -Returns the JSON representation of the Error object. - - - -## MIMEType - -```python -class MIMEType(str) -``` - -Represents a MIME type. - - - -## Result - -```python -@dataclass -class Result() -``` - -Represents the data to be displayed as a result of executing a cell in a Jupyter notebook. -The result is similar to the structure returned by ipython kernel: https://ipython.readthedocs.io/en/stable/development/execution.html#execution-semantics - -The result can contain multiple types of data, such as text, images, plots, etc. Each type of data is represented -as a string, and the result can contain multiple types of data. The display calls don't have to have text representation, -for the actual result the representation is always present for the result, the other representations are always optional. - - - -### is\_main\_result - -Whether this data is the result of the cell. Data can be produced by display calls of which can be multiple in a cell. - - - -### extra - -Extra data that can be included. Not part of the standard types. - - - -### formats - -```python -def formats() -> Iterable[str] -``` - -Returns all available formats of the result. - -**Returns**: - -All available formats of the result in MIME types. - - - -### \_\_str\_\_ - -```python -def __str__() -> Optional[str] -``` - -Returns the text representation of the data. - -**Returns**: - -The text representation of the data. - - - -### \_repr\_html\_ - -```python -def _repr_html_() -> Optional[str] -``` - -Returns the HTML representation of the data. - -**Returns**: - -The HTML representation of the data. - - - -### \_repr\_markdown\_ - -```python -def _repr_markdown_() -> Optional[str] -``` - -Returns the Markdown representation of the data. - -**Returns**: - -The Markdown representation of the data. - - - -### \_repr\_svg\_ - -```python -def _repr_svg_() -> Optional[str] -``` - -Returns the SVG representation of the data. - -**Returns**: - -The SVG representation of the data. - - - -### \_repr\_png\_ - -```python -def _repr_png_() -> Optional[str] -``` - -Returns the base64 representation of the PNG data. - -**Returns**: - -The base64 representation of the PNG data. - - - -### \_repr\_jpeg\_ - -```python -def _repr_jpeg_() -> Optional[str] -``` - -Returns the base64 representation of the JPEG data. - -**Returns**: - -The base64 representation of the JPEG data. - - - -### \_repr\_pdf\_ - -```python -def _repr_pdf_() -> Optional[str] -``` - -Returns the PDF representation of the data. - -**Returns**: - -The PDF representation of the data. - - - -### \_repr\_latex\_ - -```python -def _repr_latex_() -> Optional[str] -``` - -Returns the LaTeX representation of the data. - -**Returns**: - -The LaTeX representation of the data. - - - -### \_repr\_json\_ - -```python -def _repr_json_() -> Optional[dict] -``` - -Returns the JSON representation of the data. - -**Returns**: - -The JSON representation of the data. - - - -### \_repr\_javascript\_ - -```python -def _repr_javascript_() -> Optional[str] -``` - -Returns the JavaScript representation of the data. - -**Returns**: - -The JavaScript representation of the data. - - - -## Logs - -```python -@dataclass(repr=False) -class Logs() -``` - -Data printed to stdout and stderr during execution, usually by print statements, logs, warnings, subprocesses, etc. - - - -### stdout - -List of strings printed to stdout by prints, subprocesses, etc. - - - -### stderr - -List of strings printed to stderr by prints, subprocesses, etc. - - - -### to\_json - -```python -def to_json() -> str -``` - -Returns the JSON representation of the Logs object. - - - -### serialize\_results - -```python -def serialize_results(results: List[Result]) -> List[Dict[str, str]] -``` - -Serializes the results to JSON. - - - -## Execution - -```python -@dataclass(repr=False) -class Execution() -``` - -Represents the result of a cell execution. - - - -### results - -List of the result of the cell (interactively interpreted last line), display calls (e.g. matplotlib plots). - - - -### logs - -Logs printed to stdout and stderr during execution. - - - -### error - -Error object if an error occurred, None otherwise. - - - -### execution\_count - -Execution count of the cell. - - - -### text - -```python -@property -def text() -> Optional[str] -``` - -Returns the text representation of the result. - -**Returns**: - -The text representation of the result. - - - -### to\_json - -```python -def to_json() -> str -``` - -Returns the JSON representation of the Execution object. - - - -## Context - -```python -@dataclass -class Context() -``` - -Represents a context for code execution. - - - -### id - -The ID of the context. - - - -### language - -The language of the context. - - - -### cwd - -The working directory of the context. - - - - - - -## ChartType - -```python -class ChartType(str, enum.Enum) -``` - -Chart types - - - -## ScaleType - -```python -class ScaleType(str, enum.Enum) -``` - -Ax scale types - - - -## Chart - -```python -class Chart() -``` - -Extracted data from a chart. It's useful for building an interactive charts or custom visualizations. - - - - - - -## Sandbox - -```python -class Sandbox(BaseSandbox) -``` - -E2B cloud sandbox is a secure and isolated cloud environment. - -The sandbox allows you to: -- Access Linux OS -- Create, list, and delete files and directories -- Run commands -- Run isolated code -- Access the internet - -Check docs [here](https://e2b.dev/docs). - -Use the `Sandbox()` to create a new sandbox. - -**Example**: - -```python -from e2b_code_interpreter import Sandbox - -sandbox = Sandbox() -``` - - - -### run\_code - -```python -@overload -def run_code(code: str, - language: Union[Literal["python"], None] = None, - on_stdout: Optional[OutputHandler[OutputMessage]] = None, - on_stderr: Optional[OutputHandler[OutputMessage]] = None, - on_result: Optional[OutputHandler[Result]] = None, - on_error: Optional[OutputHandler[ExecutionError]] = None, - envs: Optional[Dict[str, str]] = None, - timeout: Optional[float] = None, - request_timeout: Optional[float] = None) -> Execution -``` - -Runs the code as Python. - -Specify the `language` or `context` option to run the code as a different language or in a different `Context`. - -You can reference previously defined variables, imports, and functions in the code. - -**Arguments**: - -- `code`: Code to execute -- `language`: Language to use for code execution. If not defined, the default Python context is used. -- `on_stdout`: Callback for stdout messages -- `on_stderr`: Callback for stderr messages -- `on_result`: Callback for the `Result` object -- `on_error`: Callback for the `ExecutionError` object -- `envs`: Custom environment variables -- `timeout`: Timeout for the code execution in **seconds** -- `request_timeout`: Timeout for the request in **seconds** - -**Returns**: - -`Execution` result object - - - -### run\_code - -```python -@overload -def run_code(code: str, - language: Optional[str] = None, - on_stdout: Optional[OutputHandler[OutputMessage]] = None, - on_stderr: Optional[OutputHandler[OutputMessage]] = None, - on_result: Optional[OutputHandler[Result]] = None, - on_error: Optional[OutputHandler[ExecutionError]] = None, - envs: Optional[Dict[str, str]] = None, - timeout: Optional[float] = None, - request_timeout: Optional[float] = None) -> Execution -``` - -Runs the code for the specified language. - -Specify the `language` or `context` option to run the code as a different language or in a different `Context`. -If no language is specified, Python is used. - -You can reference previously defined variables, imports, and functions in the code. - -**Arguments**: - -- `code`: Code to execute -- `language`: Language to use for code execution. If not defined, the default Python context is used. -- `on_stdout`: Callback for stdout messages -- `on_stderr`: Callback for stderr messages -- `on_result`: Callback for the `Result` object -- `on_error`: Callback for the `ExecutionError` object -- `envs`: Custom environment variables -- `timeout`: Timeout for the code execution in **seconds** -- `request_timeout`: Timeout for the request in **seconds** - -**Returns**: - -`Execution` result object - - - -### run\_code - -```python -@overload -def run_code(code: str, - context: Optional[Context] = None, - on_stdout: Optional[OutputHandler[OutputMessage]] = None, - on_stderr: Optional[OutputHandler[OutputMessage]] = None, - on_result: Optional[OutputHandler[Result]] = None, - on_error: Optional[OutputHandler[ExecutionError]] = None, - envs: Optional[Dict[str, str]] = None, - timeout: Optional[float] = None, - request_timeout: Optional[float] = None) -> Execution -``` - -Runs the code in the specified context, if not specified, the default context is used. - -Specify the `language` or `context` option to run the code as a different language or in a different `Context`. - -You can reference previously defined variables, imports, and functions in the code. - -**Arguments**: - -- `code`: Code to execute -- `context`: Concrete context to run the code in. If not specified, the default context for the language is used. It's mutually exclusive with the language. -- `on_stdout`: Callback for stdout messages -- `on_stderr`: Callback for stderr messages -- `on_result`: Callback for the `Result` object -- `on_error`: Callback for the `ExecutionError` object -- `envs`: Custom environment variables -- `timeout`: Timeout for the code execution in **seconds** -- `request_timeout`: Timeout for the request in **seconds** - -**Returns**: - -`Execution` result object - - - -### create\_code\_context - -```python -def create_code_context(cwd: Optional[str] = None, - language: Optional[str] = None, - request_timeout: Optional[float] = None) -> Context -``` - -Creates a new context to run code in. - -**Arguments**: - -- `cwd`: Set the current working directory for the context, defaults to `/home/user` -- `language`: Language of the context. If not specified, defaults to Python -- `request_timeout`: Timeout for the request in **milliseconds** - -**Returns**: - -Context object - - - - - - diff --git a/docs/sdk-reference/code-interpreter-python-sdk/1.0.4/code_interpreter.mdx b/docs/sdk-reference/code-interpreter-python-sdk/1.0.4/code_interpreter.mdx deleted file mode 100644 index 0d3e5ea..0000000 --- a/docs/sdk-reference/code-interpreter-python-sdk/1.0.4/code_interpreter.mdx +++ /dev/null @@ -1,786 +0,0 @@ ---- -sidebarTitle: "Code Interpreter" -mode: "center" ---- - - - - - - - - - -## AsyncSandbox - -```python -class AsyncSandbox(BaseAsyncSandbox) -``` - -E2B cloud sandbox is a secure and isolated cloud environment. - -The sandbox allows you to: -- Access Linux OS -- Create, list, and delete files and directories -- Run commands -- Run isolated code -- Access the internet - -Check docs [here](https://e2b.dev/docs). - -Use the `AsyncSandbox.create()` to create a new sandbox. - -**Example**: - -```python -from e2b_code_interpreter import AsyncSandbox -sandbox = await AsyncSandbox.create() -``` - - - -### run\_code - -```python -@overload -async def run_code(code: str, - language: Union[Literal["python"], None] = None, - on_stdout: Optional[OutputHandler[OutputMessage]] = None, - on_stderr: Optional[OutputHandler[OutputMessage]] = None, - on_result: Optional[OutputHandler[Result]] = None, - on_error: Optional[OutputHandler[ExecutionError]] = None, - envs: Optional[Dict[str, str]] = None, - timeout: Optional[float] = None, - request_timeout: Optional[float] = None) -> Execution -``` - -Runs the code as Python. - -Specify the `language` or `context` option to run the code as a different language or in a different `Context`. - -You can reference previously defined variables, imports, and functions in the code. - -**Arguments**: - -- `code`: Code to execute -- `language`: Language to use for code execution. If not defined, the default Python context is used. -- `on_stdout`: Callback for stdout messages -- `on_stderr`: Callback for stderr messages -- `on_result`: Callback for the `Result` object -- `on_error`: Callback for the `ExecutionError` object -- `envs`: Custom environment variables -- `timeout`: Timeout for the code execution in **seconds** -- `request_timeout`: Timeout for the request in **seconds** - -**Returns**: - -`Execution` result object - - - -### run\_code - -```python -@overload -async def run_code(code: str, - language: Optional[str] = None, - on_stdout: Optional[OutputHandler[OutputMessage]] = None, - on_stderr: Optional[OutputHandler[OutputMessage]] = None, - on_result: Optional[OutputHandler[Result]] = None, - on_error: Optional[OutputHandler[ExecutionError]] = None, - envs: Optional[Dict[str, str]] = None, - timeout: Optional[float] = None, - request_timeout: Optional[float] = None) -> Execution -``` - -Runs the code for the specified language. - -Specify the `language` or `context` option to run the code as a different language or in a different `Context`. -If no language is specified, Python is used. - -You can reference previously defined variables, imports, and functions in the code. - -**Arguments**: - -- `code`: Code to execute -- `language`: Language to use for code execution. If not defined, the default Python context is used. -- `on_stdout`: Callback for stdout messages -- `on_stderr`: Callback for stderr messages -- `on_result`: Callback for the `Result` object -- `on_error`: Callback for the `ExecutionError` object -- `envs`: Custom environment variables -- `timeout`: Timeout for the code execution in **seconds** -- `request_timeout`: Timeout for the request in **seconds** - -**Returns**: - -`Execution` result object - - - -### run\_code - -```python -@overload -async def run_code(code: str, - context: Optional[Context] = None, - on_stdout: Optional[OutputHandler[OutputMessage]] = None, - on_stderr: Optional[OutputHandler[OutputMessage]] = None, - on_result: Optional[OutputHandler[Result]] = None, - on_error: Optional[OutputHandler[ExecutionError]] = None, - envs: Optional[Dict[str, str]] = None, - timeout: Optional[float] = None, - request_timeout: Optional[float] = None) -> Execution -``` - -Runs the code in the specified context, if not specified, the default context is used. - -Specify the `language` or `context` option to run the code as a different language or in a different `Context`. - -You can reference previously defined variables, imports, and functions in the code. - -**Arguments**: - -- `code`: Code to execute -- `context`: Concrete context to run the code in. If not specified, the default context for the language is used. It's mutually exclusive with the language. -- `on_stdout`: Callback for stdout messages -- `on_stderr`: Callback for stderr messages -- `on_result`: Callback for the `Result` object -- `on_error`: Callback for the `ExecutionError` object -- `envs`: Custom environment variables -- `timeout`: Timeout for the code execution in **seconds** -- `request_timeout`: Timeout for the request in **seconds** - -**Returns**: - -`Execution` result object - - - -### create\_code\_context - -```python -async def create_code_context( - cwd: Optional[str] = None, - language: Optional[str] = None, - request_timeout: Optional[float] = None) -> Context -``` - -Creates a new context to run code in. - -**Arguments**: - -- `cwd`: Set the current working directory for the context, defaults to `/home/user` -- `language`: Language of the context. If not specified, defaults to Python -- `request_timeout`: Timeout for the request in **milliseconds** - -**Returns**: - -Context object - - - - - - -## OutputMessage - -```python -@dataclass -class OutputMessage() -``` - -Represents an output message from the sandbox code execution. - - - -### line - -The output line. - - - -### timestamp - -Unix epoch in nanoseconds - - - -### error - -Whether the output is an error. - - - -## ExecutionError - -```python -@dataclass -class ExecutionError() -``` - -Represents an error that occurred during the execution of a cell. -The error contains the name of the error, the value of the error, and the traceback. - - - -### name - -Name of the error. - - - -### value - -Value of the error. - - - -### traceback - -The raw traceback of the error. - - - -### to\_json - -```python -def to_json() -> str -``` - -Returns the JSON representation of the Error object. - - - -## MIMEType - -```python -class MIMEType(str) -``` - -Represents a MIME type. - - - -## Result - -```python -@dataclass -class Result() -``` - -Represents the data to be displayed as a result of executing a cell in a Jupyter notebook. -The result is similar to the structure returned by ipython kernel: https://ipython.readthedocs.io/en/stable/development/execution.html#execution-semantics - -The result can contain multiple types of data, such as text, images, plots, etc. Each type of data is represented -as a string, and the result can contain multiple types of data. The display calls don't have to have text representation, -for the actual result the representation is always present for the result, the other representations are always optional. - - - -### is\_main\_result - -Whether this data is the result of the cell. Data can be produced by display calls of which can be multiple in a cell. - - - -### extra - -Extra data that can be included. Not part of the standard types. - - - -### formats - -```python -def formats() -> Iterable[str] -``` - -Returns all available formats of the result. - -**Returns**: - -All available formats of the result in MIME types. - - - -### \_\_str\_\_ - -```python -def __str__() -> Optional[str] -``` - -Returns the text representation of the data. - -**Returns**: - -The text representation of the data. - - - -### \_repr\_html\_ - -```python -def _repr_html_() -> Optional[str] -``` - -Returns the HTML representation of the data. - -**Returns**: - -The HTML representation of the data. - - - -### \_repr\_markdown\_ - -```python -def _repr_markdown_() -> Optional[str] -``` - -Returns the Markdown representation of the data. - -**Returns**: - -The Markdown representation of the data. - - - -### \_repr\_svg\_ - -```python -def _repr_svg_() -> Optional[str] -``` - -Returns the SVG representation of the data. - -**Returns**: - -The SVG representation of the data. - - - -### \_repr\_png\_ - -```python -def _repr_png_() -> Optional[str] -``` - -Returns the base64 representation of the PNG data. - -**Returns**: - -The base64 representation of the PNG data. - - - -### \_repr\_jpeg\_ - -```python -def _repr_jpeg_() -> Optional[str] -``` - -Returns the base64 representation of the JPEG data. - -**Returns**: - -The base64 representation of the JPEG data. - - - -### \_repr\_pdf\_ - -```python -def _repr_pdf_() -> Optional[str] -``` - -Returns the PDF representation of the data. - -**Returns**: - -The PDF representation of the data. - - - -### \_repr\_latex\_ - -```python -def _repr_latex_() -> Optional[str] -``` - -Returns the LaTeX representation of the data. - -**Returns**: - -The LaTeX representation of the data. - - - -### \_repr\_json\_ - -```python -def _repr_json_() -> Optional[dict] -``` - -Returns the JSON representation of the data. - -**Returns**: - -The JSON representation of the data. - - - -### \_repr\_javascript\_ - -```python -def _repr_javascript_() -> Optional[str] -``` - -Returns the JavaScript representation of the data. - -**Returns**: - -The JavaScript representation of the data. - - - -## Logs - -```python -@dataclass(repr=False) -class Logs() -``` - -Data printed to stdout and stderr during execution, usually by print statements, logs, warnings, subprocesses, etc. - - - -### stdout - -List of strings printed to stdout by prints, subprocesses, etc. - - - -### stderr - -List of strings printed to stderr by prints, subprocesses, etc. - - - -### to\_json - -```python -def to_json() -> str -``` - -Returns the JSON representation of the Logs object. - - - -### serialize\_results - -```python -def serialize_results(results: List[Result]) -> List[Dict[str, str]] -``` - -Serializes the results to JSON. - - - -## Execution - -```python -@dataclass(repr=False) -class Execution() -``` - -Represents the result of a cell execution. - - - -### results - -List of the result of the cell (interactively interpreted last line), display calls (e.g. matplotlib plots). - - - -### logs - -Logs printed to stdout and stderr during execution. - - - -### error - -Error object if an error occurred, None otherwise. - - - -### execution\_count - -Execution count of the cell. - - - -### text - -```python -@property -def text() -> Optional[str] -``` - -Returns the text representation of the result. - -**Returns**: - -The text representation of the result. - - - -### to\_json - -```python -def to_json() -> str -``` - -Returns the JSON representation of the Execution object. - - - -## Context - -```python -@dataclass -class Context() -``` - -Represents a context for code execution. - - - -### id - -The ID of the context. - - - -### language - -The language of the context. - - - -### cwd - -The working directory of the context. - - - - - - -## ChartType - -```python -class ChartType(str, enum.Enum) -``` - -Chart types - - - -## ScaleType - -```python -class ScaleType(str, enum.Enum) -``` - -Ax scale types - - - -## Chart - -```python -class Chart() -``` - -Extracted data from a chart. It's useful for building an interactive charts or custom visualizations. - - - - - - -## Sandbox - -```python -class Sandbox(BaseSandbox) -``` - -E2B cloud sandbox is a secure and isolated cloud environment. - -The sandbox allows you to: -- Access Linux OS -- Create, list, and delete files and directories -- Run commands -- Run isolated code -- Access the internet - -Check docs [here](https://e2b.dev/docs). - -Use the `Sandbox()` to create a new sandbox. - -**Example**: - -```python -from e2b_code_interpreter import Sandbox - -sandbox = Sandbox() -``` - - - -### run\_code - -```python -@overload -def run_code(code: str, - language: Union[Literal["python"], None] = None, - on_stdout: Optional[OutputHandler[OutputMessage]] = None, - on_stderr: Optional[OutputHandler[OutputMessage]] = None, - on_result: Optional[OutputHandler[Result]] = None, - on_error: Optional[OutputHandler[ExecutionError]] = None, - envs: Optional[Dict[str, str]] = None, - timeout: Optional[float] = None, - request_timeout: Optional[float] = None) -> Execution -``` - -Runs the code as Python. - -Specify the `language` or `context` option to run the code as a different language or in a different `Context`. - -You can reference previously defined variables, imports, and functions in the code. - -**Arguments**: - -- `code`: Code to execute -- `language`: Language to use for code execution. If not defined, the default Python context is used. -- `on_stdout`: Callback for stdout messages -- `on_stderr`: Callback for stderr messages -- `on_result`: Callback for the `Result` object -- `on_error`: Callback for the `ExecutionError` object -- `envs`: Custom environment variables -- `timeout`: Timeout for the code execution in **seconds** -- `request_timeout`: Timeout for the request in **seconds** - -**Returns**: - -`Execution` result object - - - -### run\_code - -```python -@overload -def run_code(code: str, - language: Optional[str] = None, - on_stdout: Optional[OutputHandler[OutputMessage]] = None, - on_stderr: Optional[OutputHandler[OutputMessage]] = None, - on_result: Optional[OutputHandler[Result]] = None, - on_error: Optional[OutputHandler[ExecutionError]] = None, - envs: Optional[Dict[str, str]] = None, - timeout: Optional[float] = None, - request_timeout: Optional[float] = None) -> Execution -``` - -Runs the code for the specified language. - -Specify the `language` or `context` option to run the code as a different language or in a different `Context`. -If no language is specified, Python is used. - -You can reference previously defined variables, imports, and functions in the code. - -**Arguments**: - -- `code`: Code to execute -- `language`: Language to use for code execution. If not defined, the default Python context is used. -- `on_stdout`: Callback for stdout messages -- `on_stderr`: Callback for stderr messages -- `on_result`: Callback for the `Result` object -- `on_error`: Callback for the `ExecutionError` object -- `envs`: Custom environment variables -- `timeout`: Timeout for the code execution in **seconds** -- `request_timeout`: Timeout for the request in **seconds** - -**Returns**: - -`Execution` result object - - - -### run\_code - -```python -@overload -def run_code(code: str, - context: Optional[Context] = None, - on_stdout: Optional[OutputHandler[OutputMessage]] = None, - on_stderr: Optional[OutputHandler[OutputMessage]] = None, - on_result: Optional[OutputHandler[Result]] = None, - on_error: Optional[OutputHandler[ExecutionError]] = None, - envs: Optional[Dict[str, str]] = None, - timeout: Optional[float] = None, - request_timeout: Optional[float] = None) -> Execution -``` - -Runs the code in the specified context, if not specified, the default context is used. - -Specify the `language` or `context` option to run the code as a different language or in a different `Context`. - -You can reference previously defined variables, imports, and functions in the code. - -**Arguments**: - -- `code`: Code to execute -- `context`: Concrete context to run the code in. If not specified, the default context for the language is used. It's mutually exclusive with the language. -- `on_stdout`: Callback for stdout messages -- `on_stderr`: Callback for stderr messages -- `on_result`: Callback for the `Result` object -- `on_error`: Callback for the `ExecutionError` object -- `envs`: Custom environment variables -- `timeout`: Timeout for the code execution in **seconds** -- `request_timeout`: Timeout for the request in **seconds** - -**Returns**: - -`Execution` result object - - - -### create\_code\_context - -```python -def create_code_context(cwd: Optional[str] = None, - language: Optional[str] = None, - request_timeout: Optional[float] = None) -> Context -``` - -Creates a new context to run code in. - -**Arguments**: - -- `cwd`: Set the current working directory for the context, defaults to `/home/user` -- `language`: Language of the context. If not specified, defaults to Python -- `request_timeout`: Timeout for the request in **milliseconds** - -**Returns**: - -Context object - - - - - - diff --git a/docs/sdk-reference/code-interpreter-python-sdk/v2.2.1/code_interpreter.mdx b/docs/sdk-reference/code-interpreter-python-sdk/v2.2.1/code_interpreter.mdx deleted file mode 100644 index f250edb..0000000 --- a/docs/sdk-reference/code-interpreter-python-sdk/v2.2.1/code_interpreter.mdx +++ /dev/null @@ -1,789 +0,0 @@ ---- -sidebarTitle: "Code Interpreter" -mode: "center" ---- - - - - - - - - - -## AsyncSandbox - -```python -class AsyncSandbox(BaseAsyncSandbox) -``` - -E2B cloud sandbox is a secure and isolated cloud environment. - -The sandbox allows you to: -- Access Linux OS -- Create, list, and delete files and directories -- Run commands -- Run isolated code -- Access the internet - -Check docs [here](https://e2b.dev/docs). - -Use the `AsyncSandbox.create()` to create a new sandbox. - -**Example**: - -```python -from e2b_code_interpreter import AsyncSandbox -sandbox = await AsyncSandbox.create() -``` - - - -### run\_code - -```python -@overload -async def run_code( - code: str, - language: Union[Literal["python"], None] = None, - on_stdout: Optional[OutputHandlerWithAsync[OutputMessage]] = None, - on_stderr: Optional[OutputHandlerWithAsync[OutputMessage]] = None, - on_result: Optional[OutputHandlerWithAsync[Result]] = None, - on_error: Optional[OutputHandlerWithAsync[ExecutionError]] = None, - envs: Optional[Dict[str, str]] = None, - timeout: Optional[float] = None, - request_timeout: Optional[float] = None) -> Execution -``` - -Runs the code as Python. - -Specify the `language` or `context` option to run the code as a different language or in a different `Context`. - -You can reference previously defined variables, imports, and functions in the code. - -**Arguments**: - -- `code`: Code to execute -- `language`: Language to use for code execution. If not defined, the default Python context is used. -- `on_stdout`: Callback for stdout messages -- `on_stderr`: Callback for stderr messages -- `on_result`: Callback for the `Result` object -- `on_error`: Callback for the `ExecutionError` object -- `envs`: Custom environment variables -- `timeout`: Timeout for the code execution in **seconds** -- `request_timeout`: Timeout for the request in **seconds** - -**Returns**: - -`Execution` result object - - - -### run\_code - -```python -@overload -async def run_code( - code: str, - language: Optional[str] = None, - on_stdout: Optional[OutputHandlerWithAsync[OutputMessage]] = None, - on_stderr: Optional[OutputHandlerWithAsync[OutputMessage]] = None, - on_result: Optional[OutputHandlerWithAsync[Result]] = None, - on_error: Optional[OutputHandlerWithAsync[ExecutionError]] = None, - envs: Optional[Dict[str, str]] = None, - timeout: Optional[float] = None, - request_timeout: Optional[float] = None) -> Execution -``` - -Runs the code for the specified language. - -Specify the `language` or `context` option to run the code as a different language or in a different `Context`. -If no language is specified, Python is used. - -You can reference previously defined variables, imports, and functions in the code. - -**Arguments**: - -- `code`: Code to execute -- `language`: Language to use for code execution. If not defined, the default Python context is used. -- `on_stdout`: Callback for stdout messages -- `on_stderr`: Callback for stderr messages -- `on_result`: Callback for the `Result` object -- `on_error`: Callback for the `ExecutionError` object -- `envs`: Custom environment variables -- `timeout`: Timeout for the code execution in **seconds** -- `request_timeout`: Timeout for the request in **seconds** - -**Returns**: - -`Execution` result object - - - -### run\_code - -```python -@overload -async def run_code( - code: str, - context: Optional[Context] = None, - on_stdout: Optional[OutputHandlerWithAsync[OutputMessage]] = None, - on_stderr: Optional[OutputHandlerWithAsync[OutputMessage]] = None, - on_result: Optional[OutputHandlerWithAsync[Result]] = None, - on_error: Optional[OutputHandlerWithAsync[ExecutionError]] = None, - envs: Optional[Dict[str, str]] = None, - timeout: Optional[float] = None, - request_timeout: Optional[float] = None) -> Execution -``` - -Runs the code in the specified context, if not specified, the default context is used. - -Specify the `language` or `context` option to run the code as a different language or in a different `Context`. - -You can reference previously defined variables, imports, and functions in the code. - -**Arguments**: - -- `code`: Code to execute -- `context`: Concrete context to run the code in. If not specified, the default context for the language is used. It's mutually exclusive with the language. -- `on_stdout`: Callback for stdout messages -- `on_stderr`: Callback for stderr messages -- `on_result`: Callback for the `Result` object -- `on_error`: Callback for the `ExecutionError` object -- `envs`: Custom environment variables -- `timeout`: Timeout for the code execution in **seconds** -- `request_timeout`: Timeout for the request in **seconds** - -**Returns**: - -`Execution` result object - - - -### create\_code\_context - -```python -async def create_code_context( - cwd: Optional[str] = None, - language: Optional[str] = None, - request_timeout: Optional[float] = None) -> Context -``` - -Creates a new context to run code in. - -**Arguments**: - -- `cwd`: Set the current working directory for the context, defaults to `/home/user` -- `language`: Language of the context. If not specified, defaults to Python -- `request_timeout`: Timeout for the request in **milliseconds** - -**Returns**: - -Context object - - - - - - -## OutputMessage - -```python -@dataclass -class OutputMessage() -``` - -Represents an output message from the sandbox code execution. - - - -### line - -The output line. - - - -### timestamp - -Unix epoch in nanoseconds - - - -### error - -Whether the output is an error. - - - -## ExecutionError - -```python -@dataclass -class ExecutionError() -``` - -Represents an error that occurred during the execution of a cell. -The error contains the name of the error, the value of the error, and the traceback. - - - -### name - -Name of the error. - - - -### value - -Value of the error. - - - -### traceback - -The raw traceback of the error. - - - -### to\_json - -```python -def to_json() -> str -``` - -Returns the JSON representation of the Error object. - - - -## MIMEType - -```python -class MIMEType(str) -``` - -Represents a MIME type. - - - -## Result - -```python -@dataclass -class Result() -``` - -Represents the data to be displayed as a result of executing a cell in a Jupyter notebook. -The result is similar to the structure returned by ipython kernel: https://ipython.readthedocs.io/en/stable/development/execution.html#execution-semantics - -The result can contain multiple types of data, such as text, images, plots, etc. Each type of data is represented -as a string, and the result can contain multiple types of data. The display calls don't have to have text representation, -for the actual result the representation is always present for the result, the other representations are always optional. - - - -### is\_main\_result - -Whether this data is the result of the cell. Data can be produced by display calls of which can be multiple in a cell. - - - -### extra - -Extra data that can be included. Not part of the standard types. - - - -### formats - -```python -def formats() -> Iterable[str] -``` - -Returns all available formats of the result. - -**Returns**: - -All available formats of the result in MIME types. - - - -### \_\_str\_\_ - -```python -def __str__() -> Optional[str] -``` - -Returns the text representation of the data. - -**Returns**: - -The text representation of the data. - - - -### \_repr\_html\_ - -```python -def _repr_html_() -> Optional[str] -``` - -Returns the HTML representation of the data. - -**Returns**: - -The HTML representation of the data. - - - -### \_repr\_markdown\_ - -```python -def _repr_markdown_() -> Optional[str] -``` - -Returns the Markdown representation of the data. - -**Returns**: - -The Markdown representation of the data. - - - -### \_repr\_svg\_ - -```python -def _repr_svg_() -> Optional[str] -``` - -Returns the SVG representation of the data. - -**Returns**: - -The SVG representation of the data. - - - -### \_repr\_png\_ - -```python -def _repr_png_() -> Optional[str] -``` - -Returns the base64 representation of the PNG data. - -**Returns**: - -The base64 representation of the PNG data. - - - -### \_repr\_jpeg\_ - -```python -def _repr_jpeg_() -> Optional[str] -``` - -Returns the base64 representation of the JPEG data. - -**Returns**: - -The base64 representation of the JPEG data. - - - -### \_repr\_pdf\_ - -```python -def _repr_pdf_() -> Optional[str] -``` - -Returns the PDF representation of the data. - -**Returns**: - -The PDF representation of the data. - - - -### \_repr\_latex\_ - -```python -def _repr_latex_() -> Optional[str] -``` - -Returns the LaTeX representation of the data. - -**Returns**: - -The LaTeX representation of the data. - - - -### \_repr\_json\_ - -```python -def _repr_json_() -> Optional[dict] -``` - -Returns the JSON representation of the data. - -**Returns**: - -The JSON representation of the data. - - - -### \_repr\_javascript\_ - -```python -def _repr_javascript_() -> Optional[str] -``` - -Returns the JavaScript representation of the data. - -**Returns**: - -The JavaScript representation of the data. - - - -## Logs - -```python -@dataclass(repr=False) -class Logs() -``` - -Data printed to stdout and stderr during execution, usually by print statements, logs, warnings, subprocesses, etc. - - - -### stdout - -List of strings printed to stdout by prints, subprocesses, etc. - - - -### stderr - -List of strings printed to stderr by prints, subprocesses, etc. - - - -### to\_json - -```python -def to_json() -> str -``` - -Returns the JSON representation of the Logs object. - - - -### serialize\_results - -```python -def serialize_results(results: List[Result]) -> List[Dict[str, str]] -``` - -Serializes the results to JSON. - - - -## Execution - -```python -@dataclass(repr=False) -class Execution() -``` - -Represents the result of a cell execution. - - - -### results - -List of the result of the cell (interactively interpreted last line), display calls (e.g. matplotlib plots). - - - -### logs - -Logs printed to stdout and stderr during execution. - - - -### error - -Error object if an error occurred, None otherwise. - - - -### execution\_count - -Execution count of the cell. - - - -### text - -```python -@property -def text() -> Optional[str] -``` - -Returns the text representation of the result. - -**Returns**: - -The text representation of the result. - - - -### to\_json - -```python -def to_json() -> str -``` - -Returns the JSON representation of the Execution object. - - - -## Context - -```python -@dataclass -class Context() -``` - -Represents a context for code execution. - - - -### id - -The ID of the context. - - - -### language - -The language of the context. - - - -### cwd - -The working directory of the context. - - - - - - -## ChartType - -```python -class ChartType(str, enum.Enum) -``` - -Chart types - - - -## ScaleType - -```python -class ScaleType(str, enum.Enum) -``` - -Ax scale types - - - -## Chart - -```python -class Chart() -``` - -Extracted data from a chart. It's useful for building an interactive charts or custom visualizations. - - - - - - -## Sandbox - -```python -class Sandbox(BaseSandbox) -``` - -E2B cloud sandbox is a secure and isolated cloud environment. - -The sandbox allows you to: -- Access Linux OS -- Create, list, and delete files and directories -- Run commands -- Run isolated code -- Access the internet - -Check docs [here](https://e2b.dev/docs). - -Use the `Sandbox.create()` to create a new sandbox. - -**Example**: - -```python -from e2b_code_interpreter import Sandbox - -sandbox = Sandbox.create() -``` - - - -### run\_code - -```python -@overload -def run_code(code: str, - language: Union[Literal["python"], None] = None, - on_stdout: Optional[OutputHandler[OutputMessage]] = None, - on_stderr: Optional[OutputHandler[OutputMessage]] = None, - on_result: Optional[OutputHandler[Result]] = None, - on_error: Optional[OutputHandler[ExecutionError]] = None, - envs: Optional[Dict[str, str]] = None, - timeout: Optional[float] = None, - request_timeout: Optional[float] = None) -> Execution -``` - -Runs the code as Python. - -Specify the `language` or `context` option to run the code as a different language or in a different `Context`. - -You can reference previously defined variables, imports, and functions in the code. - -**Arguments**: - -- `code`: Code to execute -- `language`: Language to use for code execution. If not defined, the default Python context is used. -- `on_stdout`: Callback for stdout messages -- `on_stderr`: Callback for stderr messages -- `on_result`: Callback for the `Result` object -- `on_error`: Callback for the `ExecutionError` object -- `envs`: Custom environment variables -- `timeout`: Timeout for the code execution in **seconds** -- `request_timeout`: Timeout for the request in **seconds** - -**Returns**: - -`Execution` result object - - - -### run\_code - -```python -@overload -def run_code(code: str, - language: Optional[str] = None, - on_stdout: Optional[OutputHandler[OutputMessage]] = None, - on_stderr: Optional[OutputHandler[OutputMessage]] = None, - on_result: Optional[OutputHandler[Result]] = None, - on_error: Optional[OutputHandler[ExecutionError]] = None, - envs: Optional[Dict[str, str]] = None, - timeout: Optional[float] = None, - request_timeout: Optional[float] = None) -> Execution -``` - -Runs the code for the specified language. - -Specify the `language` or `context` option to run the code as a different language or in a different `Context`. -If no language is specified, Python is used. - -You can reference previously defined variables, imports, and functions in the code. - -**Arguments**: - -- `code`: Code to execute -- `language`: Language to use for code execution. If not defined, the default Python context is used. -- `on_stdout`: Callback for stdout messages -- `on_stderr`: Callback for stderr messages -- `on_result`: Callback for the `Result` object -- `on_error`: Callback for the `ExecutionError` object -- `envs`: Custom environment variables -- `timeout`: Timeout for the code execution in **seconds** -- `request_timeout`: Timeout for the request in **seconds** - -**Returns**: - -`Execution` result object - - - -### run\_code - -```python -@overload -def run_code(code: str, - context: Optional[Context] = None, - on_stdout: Optional[OutputHandler[OutputMessage]] = None, - on_stderr: Optional[OutputHandler[OutputMessage]] = None, - on_result: Optional[OutputHandler[Result]] = None, - on_error: Optional[OutputHandler[ExecutionError]] = None, - envs: Optional[Dict[str, str]] = None, - timeout: Optional[float] = None, - request_timeout: Optional[float] = None) -> Execution -``` - -Runs the code in the specified context, if not specified, the default context is used. - -Specify the `language` or `context` option to run the code as a different language or in a different `Context`. - -You can reference previously defined variables, imports, and functions in the code. - -**Arguments**: - -- `code`: Code to execute -- `context`: Concrete context to run the code in. If not specified, the default context for the language is used. It's mutually exclusive with the language. -- `on_stdout`: Callback for stdout messages -- `on_stderr`: Callback for stderr messages -- `on_result`: Callback for the `Result` object -- `on_error`: Callback for the `ExecutionError` object -- `envs`: Custom environment variables -- `timeout`: Timeout for the code execution in **seconds** -- `request_timeout`: Timeout for the request in **seconds** - -**Returns**: - -`Execution` result object - - - -### create\_code\_context - -```python -def create_code_context(cwd: Optional[str] = None, - language: Optional[str] = None, - request_timeout: Optional[float] = None) -> Context -``` - -Creates a new context to run code in. - -**Arguments**: - -- `cwd`: Set the current working directory for the context, defaults to `/home/user` -- `language`: Language of the context. If not specified, defaults to Python -- `request_timeout`: Timeout for the request in **milliseconds** - -**Returns**: - -Context object - - - - - - diff --git a/docs/sdk-reference/code-interpreter-python-sdk/v2.3.0/code_interpreter.mdx b/docs/sdk-reference/code-interpreter-python-sdk/v2.3.0/code_interpreter.mdx deleted file mode 100644 index f250edb..0000000 --- a/docs/sdk-reference/code-interpreter-python-sdk/v2.3.0/code_interpreter.mdx +++ /dev/null @@ -1,789 +0,0 @@ ---- -sidebarTitle: "Code Interpreter" -mode: "center" ---- - - - - - - - - - -## AsyncSandbox - -```python -class AsyncSandbox(BaseAsyncSandbox) -``` - -E2B cloud sandbox is a secure and isolated cloud environment. - -The sandbox allows you to: -- Access Linux OS -- Create, list, and delete files and directories -- Run commands -- Run isolated code -- Access the internet - -Check docs [here](https://e2b.dev/docs). - -Use the `AsyncSandbox.create()` to create a new sandbox. - -**Example**: - -```python -from e2b_code_interpreter import AsyncSandbox -sandbox = await AsyncSandbox.create() -``` - - - -### run\_code - -```python -@overload -async def run_code( - code: str, - language: Union[Literal["python"], None] = None, - on_stdout: Optional[OutputHandlerWithAsync[OutputMessage]] = None, - on_stderr: Optional[OutputHandlerWithAsync[OutputMessage]] = None, - on_result: Optional[OutputHandlerWithAsync[Result]] = None, - on_error: Optional[OutputHandlerWithAsync[ExecutionError]] = None, - envs: Optional[Dict[str, str]] = None, - timeout: Optional[float] = None, - request_timeout: Optional[float] = None) -> Execution -``` - -Runs the code as Python. - -Specify the `language` or `context` option to run the code as a different language or in a different `Context`. - -You can reference previously defined variables, imports, and functions in the code. - -**Arguments**: - -- `code`: Code to execute -- `language`: Language to use for code execution. If not defined, the default Python context is used. -- `on_stdout`: Callback for stdout messages -- `on_stderr`: Callback for stderr messages -- `on_result`: Callback for the `Result` object -- `on_error`: Callback for the `ExecutionError` object -- `envs`: Custom environment variables -- `timeout`: Timeout for the code execution in **seconds** -- `request_timeout`: Timeout for the request in **seconds** - -**Returns**: - -`Execution` result object - - - -### run\_code - -```python -@overload -async def run_code( - code: str, - language: Optional[str] = None, - on_stdout: Optional[OutputHandlerWithAsync[OutputMessage]] = None, - on_stderr: Optional[OutputHandlerWithAsync[OutputMessage]] = None, - on_result: Optional[OutputHandlerWithAsync[Result]] = None, - on_error: Optional[OutputHandlerWithAsync[ExecutionError]] = None, - envs: Optional[Dict[str, str]] = None, - timeout: Optional[float] = None, - request_timeout: Optional[float] = None) -> Execution -``` - -Runs the code for the specified language. - -Specify the `language` or `context` option to run the code as a different language or in a different `Context`. -If no language is specified, Python is used. - -You can reference previously defined variables, imports, and functions in the code. - -**Arguments**: - -- `code`: Code to execute -- `language`: Language to use for code execution. If not defined, the default Python context is used. -- `on_stdout`: Callback for stdout messages -- `on_stderr`: Callback for stderr messages -- `on_result`: Callback for the `Result` object -- `on_error`: Callback for the `ExecutionError` object -- `envs`: Custom environment variables -- `timeout`: Timeout for the code execution in **seconds** -- `request_timeout`: Timeout for the request in **seconds** - -**Returns**: - -`Execution` result object - - - -### run\_code - -```python -@overload -async def run_code( - code: str, - context: Optional[Context] = None, - on_stdout: Optional[OutputHandlerWithAsync[OutputMessage]] = None, - on_stderr: Optional[OutputHandlerWithAsync[OutputMessage]] = None, - on_result: Optional[OutputHandlerWithAsync[Result]] = None, - on_error: Optional[OutputHandlerWithAsync[ExecutionError]] = None, - envs: Optional[Dict[str, str]] = None, - timeout: Optional[float] = None, - request_timeout: Optional[float] = None) -> Execution -``` - -Runs the code in the specified context, if not specified, the default context is used. - -Specify the `language` or `context` option to run the code as a different language or in a different `Context`. - -You can reference previously defined variables, imports, and functions in the code. - -**Arguments**: - -- `code`: Code to execute -- `context`: Concrete context to run the code in. If not specified, the default context for the language is used. It's mutually exclusive with the language. -- `on_stdout`: Callback for stdout messages -- `on_stderr`: Callback for stderr messages -- `on_result`: Callback for the `Result` object -- `on_error`: Callback for the `ExecutionError` object -- `envs`: Custom environment variables -- `timeout`: Timeout for the code execution in **seconds** -- `request_timeout`: Timeout for the request in **seconds** - -**Returns**: - -`Execution` result object - - - -### create\_code\_context - -```python -async def create_code_context( - cwd: Optional[str] = None, - language: Optional[str] = None, - request_timeout: Optional[float] = None) -> Context -``` - -Creates a new context to run code in. - -**Arguments**: - -- `cwd`: Set the current working directory for the context, defaults to `/home/user` -- `language`: Language of the context. If not specified, defaults to Python -- `request_timeout`: Timeout for the request in **milliseconds** - -**Returns**: - -Context object - - - - - - -## OutputMessage - -```python -@dataclass -class OutputMessage() -``` - -Represents an output message from the sandbox code execution. - - - -### line - -The output line. - - - -### timestamp - -Unix epoch in nanoseconds - - - -### error - -Whether the output is an error. - - - -## ExecutionError - -```python -@dataclass -class ExecutionError() -``` - -Represents an error that occurred during the execution of a cell. -The error contains the name of the error, the value of the error, and the traceback. - - - -### name - -Name of the error. - - - -### value - -Value of the error. - - - -### traceback - -The raw traceback of the error. - - - -### to\_json - -```python -def to_json() -> str -``` - -Returns the JSON representation of the Error object. - - - -## MIMEType - -```python -class MIMEType(str) -``` - -Represents a MIME type. - - - -## Result - -```python -@dataclass -class Result() -``` - -Represents the data to be displayed as a result of executing a cell in a Jupyter notebook. -The result is similar to the structure returned by ipython kernel: https://ipython.readthedocs.io/en/stable/development/execution.html#execution-semantics - -The result can contain multiple types of data, such as text, images, plots, etc. Each type of data is represented -as a string, and the result can contain multiple types of data. The display calls don't have to have text representation, -for the actual result the representation is always present for the result, the other representations are always optional. - - - -### is\_main\_result - -Whether this data is the result of the cell. Data can be produced by display calls of which can be multiple in a cell. - - - -### extra - -Extra data that can be included. Not part of the standard types. - - - -### formats - -```python -def formats() -> Iterable[str] -``` - -Returns all available formats of the result. - -**Returns**: - -All available formats of the result in MIME types. - - - -### \_\_str\_\_ - -```python -def __str__() -> Optional[str] -``` - -Returns the text representation of the data. - -**Returns**: - -The text representation of the data. - - - -### \_repr\_html\_ - -```python -def _repr_html_() -> Optional[str] -``` - -Returns the HTML representation of the data. - -**Returns**: - -The HTML representation of the data. - - - -### \_repr\_markdown\_ - -```python -def _repr_markdown_() -> Optional[str] -``` - -Returns the Markdown representation of the data. - -**Returns**: - -The Markdown representation of the data. - - - -### \_repr\_svg\_ - -```python -def _repr_svg_() -> Optional[str] -``` - -Returns the SVG representation of the data. - -**Returns**: - -The SVG representation of the data. - - - -### \_repr\_png\_ - -```python -def _repr_png_() -> Optional[str] -``` - -Returns the base64 representation of the PNG data. - -**Returns**: - -The base64 representation of the PNG data. - - - -### \_repr\_jpeg\_ - -```python -def _repr_jpeg_() -> Optional[str] -``` - -Returns the base64 representation of the JPEG data. - -**Returns**: - -The base64 representation of the JPEG data. - - - -### \_repr\_pdf\_ - -```python -def _repr_pdf_() -> Optional[str] -``` - -Returns the PDF representation of the data. - -**Returns**: - -The PDF representation of the data. - - - -### \_repr\_latex\_ - -```python -def _repr_latex_() -> Optional[str] -``` - -Returns the LaTeX representation of the data. - -**Returns**: - -The LaTeX representation of the data. - - - -### \_repr\_json\_ - -```python -def _repr_json_() -> Optional[dict] -``` - -Returns the JSON representation of the data. - -**Returns**: - -The JSON representation of the data. - - - -### \_repr\_javascript\_ - -```python -def _repr_javascript_() -> Optional[str] -``` - -Returns the JavaScript representation of the data. - -**Returns**: - -The JavaScript representation of the data. - - - -## Logs - -```python -@dataclass(repr=False) -class Logs() -``` - -Data printed to stdout and stderr during execution, usually by print statements, logs, warnings, subprocesses, etc. - - - -### stdout - -List of strings printed to stdout by prints, subprocesses, etc. - - - -### stderr - -List of strings printed to stderr by prints, subprocesses, etc. - - - -### to\_json - -```python -def to_json() -> str -``` - -Returns the JSON representation of the Logs object. - - - -### serialize\_results - -```python -def serialize_results(results: List[Result]) -> List[Dict[str, str]] -``` - -Serializes the results to JSON. - - - -## Execution - -```python -@dataclass(repr=False) -class Execution() -``` - -Represents the result of a cell execution. - - - -### results - -List of the result of the cell (interactively interpreted last line), display calls (e.g. matplotlib plots). - - - -### logs - -Logs printed to stdout and stderr during execution. - - - -### error - -Error object if an error occurred, None otherwise. - - - -### execution\_count - -Execution count of the cell. - - - -### text - -```python -@property -def text() -> Optional[str] -``` - -Returns the text representation of the result. - -**Returns**: - -The text representation of the result. - - - -### to\_json - -```python -def to_json() -> str -``` - -Returns the JSON representation of the Execution object. - - - -## Context - -```python -@dataclass -class Context() -``` - -Represents a context for code execution. - - - -### id - -The ID of the context. - - - -### language - -The language of the context. - - - -### cwd - -The working directory of the context. - - - - - - -## ChartType - -```python -class ChartType(str, enum.Enum) -``` - -Chart types - - - -## ScaleType - -```python -class ScaleType(str, enum.Enum) -``` - -Ax scale types - - - -## Chart - -```python -class Chart() -``` - -Extracted data from a chart. It's useful for building an interactive charts or custom visualizations. - - - - - - -## Sandbox - -```python -class Sandbox(BaseSandbox) -``` - -E2B cloud sandbox is a secure and isolated cloud environment. - -The sandbox allows you to: -- Access Linux OS -- Create, list, and delete files and directories -- Run commands -- Run isolated code -- Access the internet - -Check docs [here](https://e2b.dev/docs). - -Use the `Sandbox.create()` to create a new sandbox. - -**Example**: - -```python -from e2b_code_interpreter import Sandbox - -sandbox = Sandbox.create() -``` - - - -### run\_code - -```python -@overload -def run_code(code: str, - language: Union[Literal["python"], None] = None, - on_stdout: Optional[OutputHandler[OutputMessage]] = None, - on_stderr: Optional[OutputHandler[OutputMessage]] = None, - on_result: Optional[OutputHandler[Result]] = None, - on_error: Optional[OutputHandler[ExecutionError]] = None, - envs: Optional[Dict[str, str]] = None, - timeout: Optional[float] = None, - request_timeout: Optional[float] = None) -> Execution -``` - -Runs the code as Python. - -Specify the `language` or `context` option to run the code as a different language or in a different `Context`. - -You can reference previously defined variables, imports, and functions in the code. - -**Arguments**: - -- `code`: Code to execute -- `language`: Language to use for code execution. If not defined, the default Python context is used. -- `on_stdout`: Callback for stdout messages -- `on_stderr`: Callback for stderr messages -- `on_result`: Callback for the `Result` object -- `on_error`: Callback for the `ExecutionError` object -- `envs`: Custom environment variables -- `timeout`: Timeout for the code execution in **seconds** -- `request_timeout`: Timeout for the request in **seconds** - -**Returns**: - -`Execution` result object - - - -### run\_code - -```python -@overload -def run_code(code: str, - language: Optional[str] = None, - on_stdout: Optional[OutputHandler[OutputMessage]] = None, - on_stderr: Optional[OutputHandler[OutputMessage]] = None, - on_result: Optional[OutputHandler[Result]] = None, - on_error: Optional[OutputHandler[ExecutionError]] = None, - envs: Optional[Dict[str, str]] = None, - timeout: Optional[float] = None, - request_timeout: Optional[float] = None) -> Execution -``` - -Runs the code for the specified language. - -Specify the `language` or `context` option to run the code as a different language or in a different `Context`. -If no language is specified, Python is used. - -You can reference previously defined variables, imports, and functions in the code. - -**Arguments**: - -- `code`: Code to execute -- `language`: Language to use for code execution. If not defined, the default Python context is used. -- `on_stdout`: Callback for stdout messages -- `on_stderr`: Callback for stderr messages -- `on_result`: Callback for the `Result` object -- `on_error`: Callback for the `ExecutionError` object -- `envs`: Custom environment variables -- `timeout`: Timeout for the code execution in **seconds** -- `request_timeout`: Timeout for the request in **seconds** - -**Returns**: - -`Execution` result object - - - -### run\_code - -```python -@overload -def run_code(code: str, - context: Optional[Context] = None, - on_stdout: Optional[OutputHandler[OutputMessage]] = None, - on_stderr: Optional[OutputHandler[OutputMessage]] = None, - on_result: Optional[OutputHandler[Result]] = None, - on_error: Optional[OutputHandler[ExecutionError]] = None, - envs: Optional[Dict[str, str]] = None, - timeout: Optional[float] = None, - request_timeout: Optional[float] = None) -> Execution -``` - -Runs the code in the specified context, if not specified, the default context is used. - -Specify the `language` or `context` option to run the code as a different language or in a different `Context`. - -You can reference previously defined variables, imports, and functions in the code. - -**Arguments**: - -- `code`: Code to execute -- `context`: Concrete context to run the code in. If not specified, the default context for the language is used. It's mutually exclusive with the language. -- `on_stdout`: Callback for stdout messages -- `on_stderr`: Callback for stderr messages -- `on_result`: Callback for the `Result` object -- `on_error`: Callback for the `ExecutionError` object -- `envs`: Custom environment variables -- `timeout`: Timeout for the code execution in **seconds** -- `request_timeout`: Timeout for the request in **seconds** - -**Returns**: - -`Execution` result object - - - -### create\_code\_context - -```python -def create_code_context(cwd: Optional[str] = None, - language: Optional[str] = None, - request_timeout: Optional[float] = None) -> Context -``` - -Creates a new context to run code in. - -**Arguments**: - -- `cwd`: Set the current working directory for the context, defaults to `/home/user` -- `language`: Language of the context. If not specified, defaults to Python -- `request_timeout`: Timeout for the request in **milliseconds** - -**Returns**: - -Context object - - - - - - diff --git a/docs/sdk-reference/code-interpreter-python-sdk/v2.4.0/code_interpreter.mdx b/docs/sdk-reference/code-interpreter-python-sdk/v2.4.0/code_interpreter.mdx deleted file mode 100644 index f4a3f16..0000000 --- a/docs/sdk-reference/code-interpreter-python-sdk/v2.4.0/code_interpreter.mdx +++ /dev/null @@ -1,889 +0,0 @@ ---- -sidebarTitle: "Code Interpreter" -mode: "center" ---- - - - - - - - - - -## AsyncSandbox - -```python -class AsyncSandbox(BaseAsyncSandbox) -``` - -E2B cloud sandbox is a secure and isolated cloud environment. - -The sandbox allows you to: -- Access Linux OS -- Create, list, and delete files and directories -- Run commands -- Run isolated code -- Access the internet - -Check docs [here](https://e2b.dev/docs). - -Use the `AsyncSandbox.create()` to create a new sandbox. - -**Example**: - -```python -from e2b_code_interpreter import AsyncSandbox -sandbox = await AsyncSandbox.create() -``` - - - -### run\_code - -```python -@overload -async def run_code( - code: str, - language: Union[Literal["python"], None] = None, - on_stdout: Optional[OutputHandlerWithAsync[OutputMessage]] = None, - on_stderr: Optional[OutputHandlerWithAsync[OutputMessage]] = None, - on_result: Optional[OutputHandlerWithAsync[Result]] = None, - on_error: Optional[OutputHandlerWithAsync[ExecutionError]] = None, - envs: Optional[Dict[str, str]] = None, - timeout: Optional[float] = None, - request_timeout: Optional[float] = None) -> Execution -``` - -Runs the code as Python. - -Specify the `language` or `context` option to run the code as a different language or in a different `Context`. - -You can reference previously defined variables, imports, and functions in the code. - -**Arguments**: - -- `code`: Code to execute -- `language`: Language to use for code execution. If not defined, the default Python context is used. -- `on_stdout`: Callback for stdout messages -- `on_stderr`: Callback for stderr messages -- `on_result`: Callback for the `Result` object -- `on_error`: Callback for the `ExecutionError` object -- `envs`: Custom environment variables -- `timeout`: Timeout for the code execution in **seconds** -- `request_timeout`: Timeout for the request in **seconds** - -**Returns**: - -`Execution` result object - - - -### run\_code - -```python -@overload -async def run_code( - code: str, - language: Optional[str] = None, - on_stdout: Optional[OutputHandlerWithAsync[OutputMessage]] = None, - on_stderr: Optional[OutputHandlerWithAsync[OutputMessage]] = None, - on_result: Optional[OutputHandlerWithAsync[Result]] = None, - on_error: Optional[OutputHandlerWithAsync[ExecutionError]] = None, - envs: Optional[Dict[str, str]] = None, - timeout: Optional[float] = None, - request_timeout: Optional[float] = None) -> Execution -``` - -Runs the code for the specified language. - -Specify the `language` or `context` option to run the code as a different language or in a different `Context`. -If no language is specified, Python is used. - -You can reference previously defined variables, imports, and functions in the code. - -**Arguments**: - -- `code`: Code to execute -- `language`: Language to use for code execution. If not defined, the default Python context is used. -- `on_stdout`: Callback for stdout messages -- `on_stderr`: Callback for stderr messages -- `on_result`: Callback for the `Result` object -- `on_error`: Callback for the `ExecutionError` object -- `envs`: Custom environment variables -- `timeout`: Timeout for the code execution in **seconds** -- `request_timeout`: Timeout for the request in **seconds** - -**Returns**: - -`Execution` result object - - - -### run\_code - -```python -@overload -async def run_code( - code: str, - context: Optional[Context] = None, - on_stdout: Optional[OutputHandlerWithAsync[OutputMessage]] = None, - on_stderr: Optional[OutputHandlerWithAsync[OutputMessage]] = None, - on_result: Optional[OutputHandlerWithAsync[Result]] = None, - on_error: Optional[OutputHandlerWithAsync[ExecutionError]] = None, - envs: Optional[Dict[str, str]] = None, - timeout: Optional[float] = None, - request_timeout: Optional[float] = None) -> Execution -``` - -Runs the code in the specified context, if not specified, the default context is used. - -Specify the `language` or `context` option to run the code as a different language or in a different `Context`. - -You can reference previously defined variables, imports, and functions in the code. - -**Arguments**: - -- `code`: Code to execute -- `context`: Concrete context to run the code in. If not specified, the default context for the language is used. It's mutually exclusive with the language. -- `on_stdout`: Callback for stdout messages -- `on_stderr`: Callback for stderr messages -- `on_result`: Callback for the `Result` object -- `on_error`: Callback for the `ExecutionError` object -- `envs`: Custom environment variables -- `timeout`: Timeout for the code execution in **seconds** -- `request_timeout`: Timeout for the request in **seconds** - -**Returns**: - -`Execution` result object - - - -### create\_code\_context - -```python -async def create_code_context( - cwd: Optional[str] = None, - language: Optional[str] = None, - request_timeout: Optional[float] = None) -> Context -``` - -Creates a new context to run code in. - -**Arguments**: - -- `cwd`: Set the current working directory for the context, defaults to `/home/user` -- `language`: Language of the context. If not specified, defaults to Python -- `request_timeout`: Timeout for the request in **milliseconds** - -**Returns**: - -Context object - - - -### remove\_code\_context - -```python -async def remove_code_context(context: Union[Context, str]) -> None -``` - -Removes a context. - -**Arguments**: - -- `context`: Context to remove. Can be a Context object or a context ID string. - -**Returns**: - -None - - - -### list\_code\_contexts - -```python -async def list_code_contexts() -> List[Context] -``` - -List all contexts. - -**Returns**: - -List of contexts. - - - -### restart\_code\_context - -```python -async def restart_code_context(context: Union[Context, str]) -> None -``` - -Restart a context. - -**Arguments**: - -- `context`: Context to restart. Can be a Context object or a context ID string. - -**Returns**: - -None - - - - - - -## OutputMessage - -```python -@dataclass -class OutputMessage() -``` - -Represents an output message from the sandbox code execution. - - - -### line - -The output line. - - - -### timestamp - -Unix epoch in nanoseconds - - - -### error - -Whether the output is an error. - - - -## ExecutionError - -```python -@dataclass -class ExecutionError() -``` - -Represents an error that occurred during the execution of a cell. -The error contains the name of the error, the value of the error, and the traceback. - - - -### name - -Name of the error. - - - -### value - -Value of the error. - - - -### traceback - -The raw traceback of the error. - - - -### to\_json - -```python -def to_json() -> str -``` - -Returns the JSON representation of the Error object. - - - -## MIMEType - -```python -class MIMEType(str) -``` - -Represents a MIME type. - - - -## Result - -```python -@dataclass -class Result() -``` - -Represents the data to be displayed as a result of executing a cell in a Jupyter notebook. -The result is similar to the structure returned by ipython kernel: https://ipython.readthedocs.io/en/stable/development/execution.html#execution-semantics - -The result can contain multiple types of data, such as text, images, plots, etc. Each type of data is represented -as a string, and the result can contain multiple types of data. The display calls don't have to have text representation, -for the actual result the representation is always present for the result, the other representations are always optional. - - - -### is\_main\_result - -Whether this data is the result of the cell. Data can be produced by display calls of which can be multiple in a cell. - - - -### extra - -Extra data that can be included. Not part of the standard types. - - - -### formats - -```python -def formats() -> Iterable[str] -``` - -Returns all available formats of the result. - -**Returns**: - -All available formats of the result in MIME types. - - - -### \_\_str\_\_ - -```python -def __str__() -> Optional[str] -``` - -Returns the text representation of the data. - -**Returns**: - -The text representation of the data. - - - -### \_repr\_html\_ - -```python -def _repr_html_() -> Optional[str] -``` - -Returns the HTML representation of the data. - -**Returns**: - -The HTML representation of the data. - - - -### \_repr\_markdown\_ - -```python -def _repr_markdown_() -> Optional[str] -``` - -Returns the Markdown representation of the data. - -**Returns**: - -The Markdown representation of the data. - - - -### \_repr\_svg\_ - -```python -def _repr_svg_() -> Optional[str] -``` - -Returns the SVG representation of the data. - -**Returns**: - -The SVG representation of the data. - - - -### \_repr\_png\_ - -```python -def _repr_png_() -> Optional[str] -``` - -Returns the base64 representation of the PNG data. - -**Returns**: - -The base64 representation of the PNG data. - - - -### \_repr\_jpeg\_ - -```python -def _repr_jpeg_() -> Optional[str] -``` - -Returns the base64 representation of the JPEG data. - -**Returns**: - -The base64 representation of the JPEG data. - - - -### \_repr\_pdf\_ - -```python -def _repr_pdf_() -> Optional[str] -``` - -Returns the PDF representation of the data. - -**Returns**: - -The PDF representation of the data. - - - -### \_repr\_latex\_ - -```python -def _repr_latex_() -> Optional[str] -``` - -Returns the LaTeX representation of the data. - -**Returns**: - -The LaTeX representation of the data. - - - -### \_repr\_json\_ - -```python -def _repr_json_() -> Optional[dict] -``` - -Returns the JSON representation of the data. - -**Returns**: - -The JSON representation of the data. - - - -### \_repr\_javascript\_ - -```python -def _repr_javascript_() -> Optional[str] -``` - -Returns the JavaScript representation of the data. - -**Returns**: - -The JavaScript representation of the data. - - - -## Logs - -```python -@dataclass(repr=False) -class Logs() -``` - -Data printed to stdout and stderr during execution, usually by print statements, logs, warnings, subprocesses, etc. - - - -### stdout - -List of strings printed to stdout by prints, subprocesses, etc. - - - -### stderr - -List of strings printed to stderr by prints, subprocesses, etc. - - - -### to\_json - -```python -def to_json() -> str -``` - -Returns the JSON representation of the Logs object. - - - -### serialize\_results - -```python -def serialize_results(results: List[Result]) -> List[Dict[str, str]] -``` - -Serializes the results to JSON. - - - -## Execution - -```python -@dataclass(repr=False) -class Execution() -``` - -Represents the result of a cell execution. - - - -### results - -List of the result of the cell (interactively interpreted last line), display calls (e.g. matplotlib plots). - - - -### logs - -Logs printed to stdout and stderr during execution. - - - -### error - -Error object if an error occurred, None otherwise. - - - -### execution\_count - -Execution count of the cell. - - - -### text - -```python -@property -def text() -> Optional[str] -``` - -Returns the text representation of the result. - -**Returns**: - -The text representation of the result. - - - -### to\_json - -```python -def to_json() -> str -``` - -Returns the JSON representation of the Execution object. - - - -## Context - -```python -@dataclass -class Context() -``` - -Represents a context for code execution. - - - -### id - -The ID of the context. - - - -### language - -The language of the context. - - - -### cwd - -The working directory of the context. - - - - - - -## ChartType - -```python -class ChartType(str, enum.Enum) -``` - -Chart types - - - -## ScaleType - -```python -class ScaleType(str, enum.Enum) -``` - -Ax scale types - - - -## Chart - -```python -class Chart() -``` - -Extracted data from a chart. It's useful for building an interactive charts or custom visualizations. - - - - - - -## Sandbox - -```python -class Sandbox(BaseSandbox) -``` - -E2B cloud sandbox is a secure and isolated cloud environment. - -The sandbox allows you to: -- Access Linux OS -- Create, list, and delete files and directories -- Run commands -- Run isolated code -- Access the internet - -Check docs [here](https://e2b.dev/docs). - -Use the `Sandbox.create()` to create a new sandbox. - -**Example**: - -```python -from e2b_code_interpreter import Sandbox - -sandbox = Sandbox.create() -``` - - - -### run\_code - -```python -@overload -def run_code(code: str, - language: Union[Literal["python"], None] = None, - on_stdout: Optional[OutputHandler[OutputMessage]] = None, - on_stderr: Optional[OutputHandler[OutputMessage]] = None, - on_result: Optional[OutputHandler[Result]] = None, - on_error: Optional[OutputHandler[ExecutionError]] = None, - envs: Optional[Dict[str, str]] = None, - timeout: Optional[float] = None, - request_timeout: Optional[float] = None) -> Execution -``` - -Runs the code as Python. - -Specify the `language` or `context` option to run the code as a different language or in a different `Context`. - -You can reference previously defined variables, imports, and functions in the code. - -**Arguments**: - -- `code`: Code to execute -- `language`: Language to use for code execution. If not defined, the default Python context is used. -- `on_stdout`: Callback for stdout messages -- `on_stderr`: Callback for stderr messages -- `on_result`: Callback for the `Result` object -- `on_error`: Callback for the `ExecutionError` object -- `envs`: Custom environment variables -- `timeout`: Timeout for the code execution in **seconds** -- `request_timeout`: Timeout for the request in **seconds** - -**Returns**: - -`Execution` result object - - - -### run\_code - -```python -@overload -def run_code(code: str, - language: Optional[str] = None, - on_stdout: Optional[OutputHandler[OutputMessage]] = None, - on_stderr: Optional[OutputHandler[OutputMessage]] = None, - on_result: Optional[OutputHandler[Result]] = None, - on_error: Optional[OutputHandler[ExecutionError]] = None, - envs: Optional[Dict[str, str]] = None, - timeout: Optional[float] = None, - request_timeout: Optional[float] = None) -> Execution -``` - -Runs the code for the specified language. - -Specify the `language` or `context` option to run the code as a different language or in a different `Context`. -If no language is specified, Python is used. - -You can reference previously defined variables, imports, and functions in the code. - -**Arguments**: - -- `code`: Code to execute -- `language`: Language to use for code execution. If not defined, the default Python context is used. -- `on_stdout`: Callback for stdout messages -- `on_stderr`: Callback for stderr messages -- `on_result`: Callback for the `Result` object -- `on_error`: Callback for the `ExecutionError` object -- `envs`: Custom environment variables -- `timeout`: Timeout for the code execution in **seconds** -- `request_timeout`: Timeout for the request in **seconds** - -**Returns**: - -`Execution` result object - - - -### run\_code - -```python -@overload -def run_code(code: str, - context: Optional[Context] = None, - on_stdout: Optional[OutputHandler[OutputMessage]] = None, - on_stderr: Optional[OutputHandler[OutputMessage]] = None, - on_result: Optional[OutputHandler[Result]] = None, - on_error: Optional[OutputHandler[ExecutionError]] = None, - envs: Optional[Dict[str, str]] = None, - timeout: Optional[float] = None, - request_timeout: Optional[float] = None) -> Execution -``` - -Runs the code in the specified context, if not specified, the default context is used. - -Specify the `language` or `context` option to run the code as a different language or in a different `Context`. - -You can reference previously defined variables, imports, and functions in the code. - -**Arguments**: - -- `code`: Code to execute -- `context`: Concrete context to run the code in. If not specified, the default context for the language is used. It's mutually exclusive with the language. -- `on_stdout`: Callback for stdout messages -- `on_stderr`: Callback for stderr messages -- `on_result`: Callback for the `Result` object -- `on_error`: Callback for the `ExecutionError` object -- `envs`: Custom environment variables -- `timeout`: Timeout for the code execution in **seconds** -- `request_timeout`: Timeout for the request in **seconds** - -**Returns**: - -`Execution` result object - - - -### create\_code\_context - -```python -def create_code_context(cwd: Optional[str] = None, - language: Optional[str] = None, - request_timeout: Optional[float] = None) -> Context -``` - -Creates a new context to run code in. - -**Arguments**: - -- `cwd`: Set the current working directory for the context, defaults to `/home/user` -- `language`: Language of the context. If not specified, defaults to Python -- `request_timeout`: Timeout for the request in **milliseconds** - -**Returns**: - -Context object - - - -### remove\_code\_context - -```python -def remove_code_context(context: Union[Context, str]) -> None -``` - -Removes a context. - -**Arguments**: - -- `context`: Context to remove. Can be a Context object or a context ID string. - -**Returns**: - -None - - - -### list\_code\_contexts - -```python -def list_code_contexts() -> List[Context] -``` - -List all contexts. - -**Returns**: - -List of contexts. - - - -### restart\_code\_context - -```python -def restart_code_context(context: Union[Context, str]) -> None -``` - -Restart a context. - -**Arguments**: - -- `context`: Context to restart. Can be a Context object or a context ID string. - -**Returns**: - -None - - - - - - diff --git a/docs/sdk-reference/code-interpreter-python-sdk/v2.4.1/code_interpreter.mdx b/docs/sdk-reference/code-interpreter-python-sdk/v2.4.1/code_interpreter.mdx deleted file mode 100644 index f4a3f16..0000000 --- a/docs/sdk-reference/code-interpreter-python-sdk/v2.4.1/code_interpreter.mdx +++ /dev/null @@ -1,889 +0,0 @@ ---- -sidebarTitle: "Code Interpreter" -mode: "center" ---- - - - - - - - - - -## AsyncSandbox - -```python -class AsyncSandbox(BaseAsyncSandbox) -``` - -E2B cloud sandbox is a secure and isolated cloud environment. - -The sandbox allows you to: -- Access Linux OS -- Create, list, and delete files and directories -- Run commands -- Run isolated code -- Access the internet - -Check docs [here](https://e2b.dev/docs). - -Use the `AsyncSandbox.create()` to create a new sandbox. - -**Example**: - -```python -from e2b_code_interpreter import AsyncSandbox -sandbox = await AsyncSandbox.create() -``` - - - -### run\_code - -```python -@overload -async def run_code( - code: str, - language: Union[Literal["python"], None] = None, - on_stdout: Optional[OutputHandlerWithAsync[OutputMessage]] = None, - on_stderr: Optional[OutputHandlerWithAsync[OutputMessage]] = None, - on_result: Optional[OutputHandlerWithAsync[Result]] = None, - on_error: Optional[OutputHandlerWithAsync[ExecutionError]] = None, - envs: Optional[Dict[str, str]] = None, - timeout: Optional[float] = None, - request_timeout: Optional[float] = None) -> Execution -``` - -Runs the code as Python. - -Specify the `language` or `context` option to run the code as a different language or in a different `Context`. - -You can reference previously defined variables, imports, and functions in the code. - -**Arguments**: - -- `code`: Code to execute -- `language`: Language to use for code execution. If not defined, the default Python context is used. -- `on_stdout`: Callback for stdout messages -- `on_stderr`: Callback for stderr messages -- `on_result`: Callback for the `Result` object -- `on_error`: Callback for the `ExecutionError` object -- `envs`: Custom environment variables -- `timeout`: Timeout for the code execution in **seconds** -- `request_timeout`: Timeout for the request in **seconds** - -**Returns**: - -`Execution` result object - - - -### run\_code - -```python -@overload -async def run_code( - code: str, - language: Optional[str] = None, - on_stdout: Optional[OutputHandlerWithAsync[OutputMessage]] = None, - on_stderr: Optional[OutputHandlerWithAsync[OutputMessage]] = None, - on_result: Optional[OutputHandlerWithAsync[Result]] = None, - on_error: Optional[OutputHandlerWithAsync[ExecutionError]] = None, - envs: Optional[Dict[str, str]] = None, - timeout: Optional[float] = None, - request_timeout: Optional[float] = None) -> Execution -``` - -Runs the code for the specified language. - -Specify the `language` or `context` option to run the code as a different language or in a different `Context`. -If no language is specified, Python is used. - -You can reference previously defined variables, imports, and functions in the code. - -**Arguments**: - -- `code`: Code to execute -- `language`: Language to use for code execution. If not defined, the default Python context is used. -- `on_stdout`: Callback for stdout messages -- `on_stderr`: Callback for stderr messages -- `on_result`: Callback for the `Result` object -- `on_error`: Callback for the `ExecutionError` object -- `envs`: Custom environment variables -- `timeout`: Timeout for the code execution in **seconds** -- `request_timeout`: Timeout for the request in **seconds** - -**Returns**: - -`Execution` result object - - - -### run\_code - -```python -@overload -async def run_code( - code: str, - context: Optional[Context] = None, - on_stdout: Optional[OutputHandlerWithAsync[OutputMessage]] = None, - on_stderr: Optional[OutputHandlerWithAsync[OutputMessage]] = None, - on_result: Optional[OutputHandlerWithAsync[Result]] = None, - on_error: Optional[OutputHandlerWithAsync[ExecutionError]] = None, - envs: Optional[Dict[str, str]] = None, - timeout: Optional[float] = None, - request_timeout: Optional[float] = None) -> Execution -``` - -Runs the code in the specified context, if not specified, the default context is used. - -Specify the `language` or `context` option to run the code as a different language or in a different `Context`. - -You can reference previously defined variables, imports, and functions in the code. - -**Arguments**: - -- `code`: Code to execute -- `context`: Concrete context to run the code in. If not specified, the default context for the language is used. It's mutually exclusive with the language. -- `on_stdout`: Callback for stdout messages -- `on_stderr`: Callback for stderr messages -- `on_result`: Callback for the `Result` object -- `on_error`: Callback for the `ExecutionError` object -- `envs`: Custom environment variables -- `timeout`: Timeout for the code execution in **seconds** -- `request_timeout`: Timeout for the request in **seconds** - -**Returns**: - -`Execution` result object - - - -### create\_code\_context - -```python -async def create_code_context( - cwd: Optional[str] = None, - language: Optional[str] = None, - request_timeout: Optional[float] = None) -> Context -``` - -Creates a new context to run code in. - -**Arguments**: - -- `cwd`: Set the current working directory for the context, defaults to `/home/user` -- `language`: Language of the context. If not specified, defaults to Python -- `request_timeout`: Timeout for the request in **milliseconds** - -**Returns**: - -Context object - - - -### remove\_code\_context - -```python -async def remove_code_context(context: Union[Context, str]) -> None -``` - -Removes a context. - -**Arguments**: - -- `context`: Context to remove. Can be a Context object or a context ID string. - -**Returns**: - -None - - - -### list\_code\_contexts - -```python -async def list_code_contexts() -> List[Context] -``` - -List all contexts. - -**Returns**: - -List of contexts. - - - -### restart\_code\_context - -```python -async def restart_code_context(context: Union[Context, str]) -> None -``` - -Restart a context. - -**Arguments**: - -- `context`: Context to restart. Can be a Context object or a context ID string. - -**Returns**: - -None - - - - - - -## OutputMessage - -```python -@dataclass -class OutputMessage() -``` - -Represents an output message from the sandbox code execution. - - - -### line - -The output line. - - - -### timestamp - -Unix epoch in nanoseconds - - - -### error - -Whether the output is an error. - - - -## ExecutionError - -```python -@dataclass -class ExecutionError() -``` - -Represents an error that occurred during the execution of a cell. -The error contains the name of the error, the value of the error, and the traceback. - - - -### name - -Name of the error. - - - -### value - -Value of the error. - - - -### traceback - -The raw traceback of the error. - - - -### to\_json - -```python -def to_json() -> str -``` - -Returns the JSON representation of the Error object. - - - -## MIMEType - -```python -class MIMEType(str) -``` - -Represents a MIME type. - - - -## Result - -```python -@dataclass -class Result() -``` - -Represents the data to be displayed as a result of executing a cell in a Jupyter notebook. -The result is similar to the structure returned by ipython kernel: https://ipython.readthedocs.io/en/stable/development/execution.html#execution-semantics - -The result can contain multiple types of data, such as text, images, plots, etc. Each type of data is represented -as a string, and the result can contain multiple types of data. The display calls don't have to have text representation, -for the actual result the representation is always present for the result, the other representations are always optional. - - - -### is\_main\_result - -Whether this data is the result of the cell. Data can be produced by display calls of which can be multiple in a cell. - - - -### extra - -Extra data that can be included. Not part of the standard types. - - - -### formats - -```python -def formats() -> Iterable[str] -``` - -Returns all available formats of the result. - -**Returns**: - -All available formats of the result in MIME types. - - - -### \_\_str\_\_ - -```python -def __str__() -> Optional[str] -``` - -Returns the text representation of the data. - -**Returns**: - -The text representation of the data. - - - -### \_repr\_html\_ - -```python -def _repr_html_() -> Optional[str] -``` - -Returns the HTML representation of the data. - -**Returns**: - -The HTML representation of the data. - - - -### \_repr\_markdown\_ - -```python -def _repr_markdown_() -> Optional[str] -``` - -Returns the Markdown representation of the data. - -**Returns**: - -The Markdown representation of the data. - - - -### \_repr\_svg\_ - -```python -def _repr_svg_() -> Optional[str] -``` - -Returns the SVG representation of the data. - -**Returns**: - -The SVG representation of the data. - - - -### \_repr\_png\_ - -```python -def _repr_png_() -> Optional[str] -``` - -Returns the base64 representation of the PNG data. - -**Returns**: - -The base64 representation of the PNG data. - - - -### \_repr\_jpeg\_ - -```python -def _repr_jpeg_() -> Optional[str] -``` - -Returns the base64 representation of the JPEG data. - -**Returns**: - -The base64 representation of the JPEG data. - - - -### \_repr\_pdf\_ - -```python -def _repr_pdf_() -> Optional[str] -``` - -Returns the PDF representation of the data. - -**Returns**: - -The PDF representation of the data. - - - -### \_repr\_latex\_ - -```python -def _repr_latex_() -> Optional[str] -``` - -Returns the LaTeX representation of the data. - -**Returns**: - -The LaTeX representation of the data. - - - -### \_repr\_json\_ - -```python -def _repr_json_() -> Optional[dict] -``` - -Returns the JSON representation of the data. - -**Returns**: - -The JSON representation of the data. - - - -### \_repr\_javascript\_ - -```python -def _repr_javascript_() -> Optional[str] -``` - -Returns the JavaScript representation of the data. - -**Returns**: - -The JavaScript representation of the data. - - - -## Logs - -```python -@dataclass(repr=False) -class Logs() -``` - -Data printed to stdout and stderr during execution, usually by print statements, logs, warnings, subprocesses, etc. - - - -### stdout - -List of strings printed to stdout by prints, subprocesses, etc. - - - -### stderr - -List of strings printed to stderr by prints, subprocesses, etc. - - - -### to\_json - -```python -def to_json() -> str -``` - -Returns the JSON representation of the Logs object. - - - -### serialize\_results - -```python -def serialize_results(results: List[Result]) -> List[Dict[str, str]] -``` - -Serializes the results to JSON. - - - -## Execution - -```python -@dataclass(repr=False) -class Execution() -``` - -Represents the result of a cell execution. - - - -### results - -List of the result of the cell (interactively interpreted last line), display calls (e.g. matplotlib plots). - - - -### logs - -Logs printed to stdout and stderr during execution. - - - -### error - -Error object if an error occurred, None otherwise. - - - -### execution\_count - -Execution count of the cell. - - - -### text - -```python -@property -def text() -> Optional[str] -``` - -Returns the text representation of the result. - -**Returns**: - -The text representation of the result. - - - -### to\_json - -```python -def to_json() -> str -``` - -Returns the JSON representation of the Execution object. - - - -## Context - -```python -@dataclass -class Context() -``` - -Represents a context for code execution. - - - -### id - -The ID of the context. - - - -### language - -The language of the context. - - - -### cwd - -The working directory of the context. - - - - - - -## ChartType - -```python -class ChartType(str, enum.Enum) -``` - -Chart types - - - -## ScaleType - -```python -class ScaleType(str, enum.Enum) -``` - -Ax scale types - - - -## Chart - -```python -class Chart() -``` - -Extracted data from a chart. It's useful for building an interactive charts or custom visualizations. - - - - - - -## Sandbox - -```python -class Sandbox(BaseSandbox) -``` - -E2B cloud sandbox is a secure and isolated cloud environment. - -The sandbox allows you to: -- Access Linux OS -- Create, list, and delete files and directories -- Run commands -- Run isolated code -- Access the internet - -Check docs [here](https://e2b.dev/docs). - -Use the `Sandbox.create()` to create a new sandbox. - -**Example**: - -```python -from e2b_code_interpreter import Sandbox - -sandbox = Sandbox.create() -``` - - - -### run\_code - -```python -@overload -def run_code(code: str, - language: Union[Literal["python"], None] = None, - on_stdout: Optional[OutputHandler[OutputMessage]] = None, - on_stderr: Optional[OutputHandler[OutputMessage]] = None, - on_result: Optional[OutputHandler[Result]] = None, - on_error: Optional[OutputHandler[ExecutionError]] = None, - envs: Optional[Dict[str, str]] = None, - timeout: Optional[float] = None, - request_timeout: Optional[float] = None) -> Execution -``` - -Runs the code as Python. - -Specify the `language` or `context` option to run the code as a different language or in a different `Context`. - -You can reference previously defined variables, imports, and functions in the code. - -**Arguments**: - -- `code`: Code to execute -- `language`: Language to use for code execution. If not defined, the default Python context is used. -- `on_stdout`: Callback for stdout messages -- `on_stderr`: Callback for stderr messages -- `on_result`: Callback for the `Result` object -- `on_error`: Callback for the `ExecutionError` object -- `envs`: Custom environment variables -- `timeout`: Timeout for the code execution in **seconds** -- `request_timeout`: Timeout for the request in **seconds** - -**Returns**: - -`Execution` result object - - - -### run\_code - -```python -@overload -def run_code(code: str, - language: Optional[str] = None, - on_stdout: Optional[OutputHandler[OutputMessage]] = None, - on_stderr: Optional[OutputHandler[OutputMessage]] = None, - on_result: Optional[OutputHandler[Result]] = None, - on_error: Optional[OutputHandler[ExecutionError]] = None, - envs: Optional[Dict[str, str]] = None, - timeout: Optional[float] = None, - request_timeout: Optional[float] = None) -> Execution -``` - -Runs the code for the specified language. - -Specify the `language` or `context` option to run the code as a different language or in a different `Context`. -If no language is specified, Python is used. - -You can reference previously defined variables, imports, and functions in the code. - -**Arguments**: - -- `code`: Code to execute -- `language`: Language to use for code execution. If not defined, the default Python context is used. -- `on_stdout`: Callback for stdout messages -- `on_stderr`: Callback for stderr messages -- `on_result`: Callback for the `Result` object -- `on_error`: Callback for the `ExecutionError` object -- `envs`: Custom environment variables -- `timeout`: Timeout for the code execution in **seconds** -- `request_timeout`: Timeout for the request in **seconds** - -**Returns**: - -`Execution` result object - - - -### run\_code - -```python -@overload -def run_code(code: str, - context: Optional[Context] = None, - on_stdout: Optional[OutputHandler[OutputMessage]] = None, - on_stderr: Optional[OutputHandler[OutputMessage]] = None, - on_result: Optional[OutputHandler[Result]] = None, - on_error: Optional[OutputHandler[ExecutionError]] = None, - envs: Optional[Dict[str, str]] = None, - timeout: Optional[float] = None, - request_timeout: Optional[float] = None) -> Execution -``` - -Runs the code in the specified context, if not specified, the default context is used. - -Specify the `language` or `context` option to run the code as a different language or in a different `Context`. - -You can reference previously defined variables, imports, and functions in the code. - -**Arguments**: - -- `code`: Code to execute -- `context`: Concrete context to run the code in. If not specified, the default context for the language is used. It's mutually exclusive with the language. -- `on_stdout`: Callback for stdout messages -- `on_stderr`: Callback for stderr messages -- `on_result`: Callback for the `Result` object -- `on_error`: Callback for the `ExecutionError` object -- `envs`: Custom environment variables -- `timeout`: Timeout for the code execution in **seconds** -- `request_timeout`: Timeout for the request in **seconds** - -**Returns**: - -`Execution` result object - - - -### create\_code\_context - -```python -def create_code_context(cwd: Optional[str] = None, - language: Optional[str] = None, - request_timeout: Optional[float] = None) -> Context -``` - -Creates a new context to run code in. - -**Arguments**: - -- `cwd`: Set the current working directory for the context, defaults to `/home/user` -- `language`: Language of the context. If not specified, defaults to Python -- `request_timeout`: Timeout for the request in **milliseconds** - -**Returns**: - -Context object - - - -### remove\_code\_context - -```python -def remove_code_context(context: Union[Context, str]) -> None -``` - -Removes a context. - -**Arguments**: - -- `context`: Context to remove. Can be a Context object or a context ID string. - -**Returns**: - -None - - - -### list\_code\_contexts - -```python -def list_code_contexts() -> List[Context] -``` - -List all contexts. - -**Returns**: - -List of contexts. - - - -### restart\_code\_context - -```python -def restart_code_context(context: Union[Context, str]) -> None -``` - -Restart a context. - -**Arguments**: - -- `context`: Context to restart. Can be a Context object or a context ID string. - -**Returns**: - -None - - - - - - diff --git a/docs/sdk-reference/desktop-js-sdk/v2.1.0/sandbox.mdx b/docs/sdk-reference/desktop-js-sdk/v2.1.0/sandbox.mdx deleted file mode 100644 index 890b05b..0000000 --- a/docs/sdk-reference/desktop-js-sdk/v2.1.0/sandbox.mdx +++ /dev/null @@ -1,697 +0,0 @@ ---- -sidebarTitle: "Sandbox" -mode: "center" ---- - -### Sandbox - -#### Properties - -| Property | Modifier | Type | Default value | -| ------ | ------ | ------ | ------ | -| `display` | `public` | `string` | `':0'` | -| `stream` | `public` | `VNCServer` | `undefined` | - -#### Methods - -### doubleClick() - -```ts -doubleClick(x?: number, y?: number): Promise -``` - -Double left click on the mouse position. - -###### Parameters - -| Parameter | Type | -| ------ | ------ | -| `x`? | `number` | -| `y`? | `number` | - -###### Returns - -`Promise`\<`void`\> - -### drag() - -```ts -drag(from: [number, number], to: [number, number]): Promise -``` - -Drag the mouse from the given position to the given position. - -###### Parameters - -| Parameter | Type | Description | -| ------ | ------ | ------ | -| `from` | [`number`, `number`] | The starting position. | -| `to` | [`number`, `number`] | The ending position. | - -###### Returns - -`Promise`\<`void`\> - -### getApplicationWindows() - -```ts -getApplicationWindows(application: string): Promise -``` - -Get the window ID of the window with the given title. - -###### Parameters - -| Parameter | Type | -| ------ | ------ | -| `application` | `string` | - -###### Returns - -`Promise`\<`string`[]\> - -The ID of the window. - -### getCurrentWindowId() - -```ts -getCurrentWindowId(): Promise -``` - -Get the current window ID. - -###### Returns - -`Promise`\<`string`\> - -The ID of the current window. - -### getCursorPosition() - -```ts -getCursorPosition(): Promise -``` - -Get the current cursor position. - -###### Returns - -`Promise`\<`CursorPosition`\> - -A object with the x and y coordinates - -###### Throws - -Error if cursor position cannot be determined - -### getScreenSize() - -```ts -getScreenSize(): Promise -``` - -Get the current screen size. - -###### Returns - -`Promise`\<`ScreenSize`\> - -An ScreenSize object - -###### Throws - -Error if screen size cannot be determined - -### getWindowTitle() - -```ts -getWindowTitle(windowId: string): Promise -``` - -Get the title of the window with the given ID. - -###### Parameters - -| Parameter | Type | Description | -| ------ | ------ | ------ | -| `windowId` | `string` | The ID of the window. | - -###### Returns - -`Promise`\<`string`\> - -The title of the window. - -### launch() - -```ts -launch(application: string, uri?: string): Promise -``` - -Launch an application. - -###### Parameters - -| Parameter | Type | Description | -| ------ | ------ | ------ | -| `application` | `string` | The application to launch. | -| `uri`? | `string` | The URI to open in the application. | - -###### Returns - -`Promise`\<`void`\> - -### leftClick() - -```ts -leftClick(x?: number, y?: number): Promise -``` - -Left click on the mouse position. - -###### Parameters - -| Parameter | Type | -| ------ | ------ | -| `x`? | `number` | -| `y`? | `number` | - -###### Returns - -`Promise`\<`void`\> - -### middleClick() - -```ts -middleClick(x?: number, y?: number): Promise -``` - -Middle click on the mouse position. - -###### Parameters - -| Parameter | Type | -| ------ | ------ | -| `x`? | `number` | -| `y`? | `number` | - -###### Returns - -`Promise`\<`void`\> - -### mousePress() - -```ts -mousePress(button: "left" | "right" | "middle"): Promise -``` - -Press the mouse button. - -###### Parameters - -| Parameter | Type | Default value | -| ------ | ------ | ------ | -| `button` | `"left"` \| `"right"` \| `"middle"` | `'left'` | - -###### Returns - -`Promise`\<`void`\> - -### mouseRelease() - -```ts -mouseRelease(button: "left" | "right" | "middle"): Promise -``` - -Release the mouse button. - -###### Parameters - -| Parameter | Type | Default value | -| ------ | ------ | ------ | -| `button` | `"left"` \| `"right"` \| `"middle"` | `'left'` | - -###### Returns - -`Promise`\<`void`\> - -### moveMouse() - -```ts -moveMouse(x: number, y: number): Promise -``` - -Move the mouse to the given coordinates. - -###### Parameters - -| Parameter | Type | Description | -| ------ | ------ | ------ | -| `x` | `number` | The x coordinate. | -| `y` | `number` | The y coordinate. | - -###### Returns - -`Promise`\<`void`\> - -### open() - -```ts -open(fileOrUrl: string): Promise -``` - -Open a file or a URL in the default application. - -###### Parameters - -| Parameter | Type | Description | -| ------ | ------ | ------ | -| `fileOrUrl` | `string` | The file or URL to open. | - -###### Returns - -`Promise`\<`void`\> - -### press() - -```ts -press(key: string | string[]): Promise -``` - -Press a key. - -###### Parameters - -| Parameter | Type | Description | -| ------ | ------ | ------ | -| `key` | `string` \| `string`[] | The key to press (e.g. "enter", "space", "backspace", etc.). Can be a single key or an array of keys. | - -###### Returns - -`Promise`\<`void`\> - -### rightClick() - -```ts -rightClick(x?: number, y?: number): Promise -``` - -Right click on the mouse position. - -###### Parameters - -| Parameter | Type | -| ------ | ------ | -| `x`? | `number` | -| `y`? | `number` | - -###### Returns - -`Promise`\<`void`\> - -### screenshot() - -###### screenshot() - -```ts -screenshot(): Promise> -``` - -Take a screenshot and save it to the given name. - -###### Returns - -`Promise`\<`Uint8Array`\<`ArrayBufferLike`\>\> - -A Uint8Array bytes representation of the screenshot. - -###### screenshot(format) - -```ts -screenshot(format: "bytes"): Promise> -``` - -Take a screenshot and save it to the given name. - -###### Parameters - -| Parameter | Type | Description | -| ------ | ------ | ------ | -| `format` | `"bytes"` | The format of the screenshot. | - -###### Returns - -`Promise`\<`Uint8Array`\<`ArrayBufferLike`\>\> - -A Uint8Array bytes representation of the screenshot. - -###### screenshot(format) - -```ts -screenshot(format: "blob"): Promise -``` - -Take a screenshot and save it to the given name. - -###### Parameters - -| Parameter | Type | -| ------ | ------ | -| `format` | `"blob"` | - -###### Returns - -`Promise`\<`Blob`\> - -A Blob representation of the screenshot. - -###### screenshot(format) - -```ts -screenshot(format: "stream"): Promise>> -``` - -Take a screenshot and save it to the given name. - -###### Parameters - -| Parameter | Type | -| ------ | ------ | -| `format` | `"stream"` | - -###### Returns - -`Promise`\<`ReadableStream`\<`Uint8Array`\<`ArrayBufferLike`\>\>\> - -A ReadableStream of bytes representation of the screenshot. - -### scroll() - -```ts -scroll(direction: "down" | "up", amount: number): Promise -``` - -Scroll the mouse wheel by the given amount. - -###### Parameters - -| Parameter | Type | Default value | Description | -| ------ | ------ | ------ | ------ | -| `direction` | `"down"` \| `"up"` | `'down'` | The direction to scroll. Can be "up" or "down". | -| `amount` | `number` | `1` | The amount to scroll. | - -###### Returns - -`Promise`\<`void`\> - -### wait() - -```ts -wait(ms: number): Promise -``` - -Wait for the given amount of time. - -###### Parameters - -| Parameter | Type | Description | -| ------ | ------ | ------ | -| `ms` | `number` | The amount of time to wait in milliseconds. | - -###### Returns - -`Promise`\<`void`\> - -### waitAndVerify() - -```ts -waitAndVerify( - cmd: string, - onResult: (result: CommandResult) => boolean, - timeout: number, -interval: number): Promise -``` - -Wait for a command to return a specific result. - -###### Parameters - -| Parameter | Type | Default value | Description | -| ------ | ------ | ------ | ------ | -| `cmd` | `string` | `undefined` | The command to run. | -| `onResult` | (`result`: `CommandResult`) => `boolean` | `undefined` | The function to check the result of the command. | -| `timeout` | `number` | `10` | The maximum time to wait for the command to return the result. | -| `interval` | `number` | `0.5` | The interval to wait between checks. | - -###### Returns - -`Promise`\<`boolean`\> - -`true` if the command returned the result within the timeout, otherwise `false`. - -### write() - -```ts -write(text: string, options: object): Promise -``` - -Write the given text at the current cursor position. - -###### Parameters - -| Parameter | Type | Description | -| ------ | ------ | ------ | -| `text` | `string` | The text to write. | -| `options` | `object` | An object containing the chunk size and delay between each chunk of text. | -| `options.chunkSize` | `number` | The size of each chunk of text to write. Default is 25 characters. | -| `options.delayInMs` | `number` | The delay between each chunk of text. Default is 75 ms. | - -###### Returns - -`Promise`\<`void`\> - -### betaCreate() - -###### betaCreate(this, opts) - -```ts -static betaCreate(this: S, opts?: SandboxBetaCreateOpts): Promise> -``` - -Create a new sandbox from the default `desktop` sandbox template. - -###### Type Parameters - -| Type Parameter | -| ------ | -| `S` *extends* *typeof* `Sandbox` | - -###### Parameters - -| Parameter | Type | Description | -| ------ | ------ | ------ | -| `this` | `S` | - | -| `opts`? | `SandboxBetaCreateOpts` | connection options. | - -###### Returns - -`Promise`\<`InstanceType`\<`S`\>\> - -sandbox instance for the new sandbox. - -###### Example - -```ts -const sandbox = await Sandbox.create() -``` - -###### Constructs - -Sandbox - -###### betaCreate(this, template, opts) - -```ts -static betaCreate( - this: S, - template: string, -opts?: SandboxBetaCreateOpts): Promise> -``` - -Create a new sandbox from the specified sandbox template. - -###### Type Parameters - -| Type Parameter | -| ------ | -| `S` *extends* *typeof* `Sandbox` | - -###### Parameters - -| Parameter | Type | Description | -| ------ | ------ | ------ | -| `this` | `S` | - | -| `template` | `string` | sandbox template name or ID. | -| `opts`? | `SandboxBetaCreateOpts` | connection options. | - -###### Returns - -`Promise`\<`InstanceType`\<`S`\>\> - -sandbox instance for the new sandbox. - -###### Example - -```ts -const sandbox = await Sandbox.create('') -``` - -###### Constructs - -Sandbox - -### create() - -###### create(this, opts) - -```ts -static create(this: S, opts?: SandboxOpts): Promise> -``` - -Create a new sandbox from the default `desktop` sandbox template. - -###### Type Parameters - -| Type Parameter | -| ------ | -| `S` *extends* *typeof* `Sandbox` | - -###### Parameters - -| Parameter | Type | Description | -| ------ | ------ | ------ | -| `this` | `S` | - | -| `opts`? | `SandboxOpts` | connection options. | - -###### Returns - -`Promise`\<`InstanceType`\<`S`\>\> - -sandbox instance for the new sandbox. - -###### Example - -```ts -const sandbox = await Sandbox.create() -``` - -###### Constructs - -Sandbox - -###### create(this, template, opts) - -```ts -static create( - this: S, - template: string, -opts?: SandboxOpts): Promise> -``` - -Create a new sandbox from the specified sandbox template. - -###### Type Parameters - -| Type Parameter | -| ------ | -| `S` *extends* *typeof* `Sandbox` | - -###### Parameters - -| Parameter | Type | Description | -| ------ | ------ | ------ | -| `this` | `S` | - | -| `template` | `string` | sandbox template name or ID. | -| `opts`? | `SandboxOpts` | connection options. | - -###### Returns - -`Promise`\<`InstanceType`\<`S`\>\> - -sandbox instance for the new sandbox. - -###### Example - -```ts -const sandbox = await Sandbox.create('') -``` - -###### Constructs - -Sandbox - -## Interfaces - -### SandboxBetaCreateOpts - -Configuration options for the Sandbox environment. - SandboxOpts - -#### Properties - -### display? - -```ts -optional display: string; -``` - -Display identifier. - -### dpi? - -```ts -optional dpi: number; -``` - -Dots per inch (DPI) setting for the display. - -### resolution? - -```ts -optional resolution: [number, number]; -``` - -The screen resolution in pixels, specified as [width, height]. - -*** - -### SandboxOpts - -Configuration options for the Sandbox environment. - SandboxOpts - -#### Properties - -### display? - -```ts -optional display: string; -``` - -Display identifier. - -### dpi? - -```ts -optional dpi: number; -``` - -Dots per inch (DPI) setting for the display. - -### resolution? - -```ts -optional resolution: [number, number]; -``` - -The screen resolution in pixels, specified as [width, height]. diff --git a/docs/sdk-reference/desktop-js-sdk/v2.2.0/sandbox.mdx b/docs/sdk-reference/desktop-js-sdk/v2.2.0/sandbox.mdx deleted file mode 100644 index 890b05b..0000000 --- a/docs/sdk-reference/desktop-js-sdk/v2.2.0/sandbox.mdx +++ /dev/null @@ -1,697 +0,0 @@ ---- -sidebarTitle: "Sandbox" -mode: "center" ---- - -### Sandbox - -#### Properties - -| Property | Modifier | Type | Default value | -| ------ | ------ | ------ | ------ | -| `display` | `public` | `string` | `':0'` | -| `stream` | `public` | `VNCServer` | `undefined` | - -#### Methods - -### doubleClick() - -```ts -doubleClick(x?: number, y?: number): Promise -``` - -Double left click on the mouse position. - -###### Parameters - -| Parameter | Type | -| ------ | ------ | -| `x`? | `number` | -| `y`? | `number` | - -###### Returns - -`Promise`\<`void`\> - -### drag() - -```ts -drag(from: [number, number], to: [number, number]): Promise -``` - -Drag the mouse from the given position to the given position. - -###### Parameters - -| Parameter | Type | Description | -| ------ | ------ | ------ | -| `from` | [`number`, `number`] | The starting position. | -| `to` | [`number`, `number`] | The ending position. | - -###### Returns - -`Promise`\<`void`\> - -### getApplicationWindows() - -```ts -getApplicationWindows(application: string): Promise -``` - -Get the window ID of the window with the given title. - -###### Parameters - -| Parameter | Type | -| ------ | ------ | -| `application` | `string` | - -###### Returns - -`Promise`\<`string`[]\> - -The ID of the window. - -### getCurrentWindowId() - -```ts -getCurrentWindowId(): Promise -``` - -Get the current window ID. - -###### Returns - -`Promise`\<`string`\> - -The ID of the current window. - -### getCursorPosition() - -```ts -getCursorPosition(): Promise -``` - -Get the current cursor position. - -###### Returns - -`Promise`\<`CursorPosition`\> - -A object with the x and y coordinates - -###### Throws - -Error if cursor position cannot be determined - -### getScreenSize() - -```ts -getScreenSize(): Promise -``` - -Get the current screen size. - -###### Returns - -`Promise`\<`ScreenSize`\> - -An ScreenSize object - -###### Throws - -Error if screen size cannot be determined - -### getWindowTitle() - -```ts -getWindowTitle(windowId: string): Promise -``` - -Get the title of the window with the given ID. - -###### Parameters - -| Parameter | Type | Description | -| ------ | ------ | ------ | -| `windowId` | `string` | The ID of the window. | - -###### Returns - -`Promise`\<`string`\> - -The title of the window. - -### launch() - -```ts -launch(application: string, uri?: string): Promise -``` - -Launch an application. - -###### Parameters - -| Parameter | Type | Description | -| ------ | ------ | ------ | -| `application` | `string` | The application to launch. | -| `uri`? | `string` | The URI to open in the application. | - -###### Returns - -`Promise`\<`void`\> - -### leftClick() - -```ts -leftClick(x?: number, y?: number): Promise -``` - -Left click on the mouse position. - -###### Parameters - -| Parameter | Type | -| ------ | ------ | -| `x`? | `number` | -| `y`? | `number` | - -###### Returns - -`Promise`\<`void`\> - -### middleClick() - -```ts -middleClick(x?: number, y?: number): Promise -``` - -Middle click on the mouse position. - -###### Parameters - -| Parameter | Type | -| ------ | ------ | -| `x`? | `number` | -| `y`? | `number` | - -###### Returns - -`Promise`\<`void`\> - -### mousePress() - -```ts -mousePress(button: "left" | "right" | "middle"): Promise -``` - -Press the mouse button. - -###### Parameters - -| Parameter | Type | Default value | -| ------ | ------ | ------ | -| `button` | `"left"` \| `"right"` \| `"middle"` | `'left'` | - -###### Returns - -`Promise`\<`void`\> - -### mouseRelease() - -```ts -mouseRelease(button: "left" | "right" | "middle"): Promise -``` - -Release the mouse button. - -###### Parameters - -| Parameter | Type | Default value | -| ------ | ------ | ------ | -| `button` | `"left"` \| `"right"` \| `"middle"` | `'left'` | - -###### Returns - -`Promise`\<`void`\> - -### moveMouse() - -```ts -moveMouse(x: number, y: number): Promise -``` - -Move the mouse to the given coordinates. - -###### Parameters - -| Parameter | Type | Description | -| ------ | ------ | ------ | -| `x` | `number` | The x coordinate. | -| `y` | `number` | The y coordinate. | - -###### Returns - -`Promise`\<`void`\> - -### open() - -```ts -open(fileOrUrl: string): Promise -``` - -Open a file or a URL in the default application. - -###### Parameters - -| Parameter | Type | Description | -| ------ | ------ | ------ | -| `fileOrUrl` | `string` | The file or URL to open. | - -###### Returns - -`Promise`\<`void`\> - -### press() - -```ts -press(key: string | string[]): Promise -``` - -Press a key. - -###### Parameters - -| Parameter | Type | Description | -| ------ | ------ | ------ | -| `key` | `string` \| `string`[] | The key to press (e.g. "enter", "space", "backspace", etc.). Can be a single key or an array of keys. | - -###### Returns - -`Promise`\<`void`\> - -### rightClick() - -```ts -rightClick(x?: number, y?: number): Promise -``` - -Right click on the mouse position. - -###### Parameters - -| Parameter | Type | -| ------ | ------ | -| `x`? | `number` | -| `y`? | `number` | - -###### Returns - -`Promise`\<`void`\> - -### screenshot() - -###### screenshot() - -```ts -screenshot(): Promise> -``` - -Take a screenshot and save it to the given name. - -###### Returns - -`Promise`\<`Uint8Array`\<`ArrayBufferLike`\>\> - -A Uint8Array bytes representation of the screenshot. - -###### screenshot(format) - -```ts -screenshot(format: "bytes"): Promise> -``` - -Take a screenshot and save it to the given name. - -###### Parameters - -| Parameter | Type | Description | -| ------ | ------ | ------ | -| `format` | `"bytes"` | The format of the screenshot. | - -###### Returns - -`Promise`\<`Uint8Array`\<`ArrayBufferLike`\>\> - -A Uint8Array bytes representation of the screenshot. - -###### screenshot(format) - -```ts -screenshot(format: "blob"): Promise -``` - -Take a screenshot and save it to the given name. - -###### Parameters - -| Parameter | Type | -| ------ | ------ | -| `format` | `"blob"` | - -###### Returns - -`Promise`\<`Blob`\> - -A Blob representation of the screenshot. - -###### screenshot(format) - -```ts -screenshot(format: "stream"): Promise>> -``` - -Take a screenshot and save it to the given name. - -###### Parameters - -| Parameter | Type | -| ------ | ------ | -| `format` | `"stream"` | - -###### Returns - -`Promise`\<`ReadableStream`\<`Uint8Array`\<`ArrayBufferLike`\>\>\> - -A ReadableStream of bytes representation of the screenshot. - -### scroll() - -```ts -scroll(direction: "down" | "up", amount: number): Promise -``` - -Scroll the mouse wheel by the given amount. - -###### Parameters - -| Parameter | Type | Default value | Description | -| ------ | ------ | ------ | ------ | -| `direction` | `"down"` \| `"up"` | `'down'` | The direction to scroll. Can be "up" or "down". | -| `amount` | `number` | `1` | The amount to scroll. | - -###### Returns - -`Promise`\<`void`\> - -### wait() - -```ts -wait(ms: number): Promise -``` - -Wait for the given amount of time. - -###### Parameters - -| Parameter | Type | Description | -| ------ | ------ | ------ | -| `ms` | `number` | The amount of time to wait in milliseconds. | - -###### Returns - -`Promise`\<`void`\> - -### waitAndVerify() - -```ts -waitAndVerify( - cmd: string, - onResult: (result: CommandResult) => boolean, - timeout: number, -interval: number): Promise -``` - -Wait for a command to return a specific result. - -###### Parameters - -| Parameter | Type | Default value | Description | -| ------ | ------ | ------ | ------ | -| `cmd` | `string` | `undefined` | The command to run. | -| `onResult` | (`result`: `CommandResult`) => `boolean` | `undefined` | The function to check the result of the command. | -| `timeout` | `number` | `10` | The maximum time to wait for the command to return the result. | -| `interval` | `number` | `0.5` | The interval to wait between checks. | - -###### Returns - -`Promise`\<`boolean`\> - -`true` if the command returned the result within the timeout, otherwise `false`. - -### write() - -```ts -write(text: string, options: object): Promise -``` - -Write the given text at the current cursor position. - -###### Parameters - -| Parameter | Type | Description | -| ------ | ------ | ------ | -| `text` | `string` | The text to write. | -| `options` | `object` | An object containing the chunk size and delay between each chunk of text. | -| `options.chunkSize` | `number` | The size of each chunk of text to write. Default is 25 characters. | -| `options.delayInMs` | `number` | The delay between each chunk of text. Default is 75 ms. | - -###### Returns - -`Promise`\<`void`\> - -### betaCreate() - -###### betaCreate(this, opts) - -```ts -static betaCreate(this: S, opts?: SandboxBetaCreateOpts): Promise> -``` - -Create a new sandbox from the default `desktop` sandbox template. - -###### Type Parameters - -| Type Parameter | -| ------ | -| `S` *extends* *typeof* `Sandbox` | - -###### Parameters - -| Parameter | Type | Description | -| ------ | ------ | ------ | -| `this` | `S` | - | -| `opts`? | `SandboxBetaCreateOpts` | connection options. | - -###### Returns - -`Promise`\<`InstanceType`\<`S`\>\> - -sandbox instance for the new sandbox. - -###### Example - -```ts -const sandbox = await Sandbox.create() -``` - -###### Constructs - -Sandbox - -###### betaCreate(this, template, opts) - -```ts -static betaCreate( - this: S, - template: string, -opts?: SandboxBetaCreateOpts): Promise> -``` - -Create a new sandbox from the specified sandbox template. - -###### Type Parameters - -| Type Parameter | -| ------ | -| `S` *extends* *typeof* `Sandbox` | - -###### Parameters - -| Parameter | Type | Description | -| ------ | ------ | ------ | -| `this` | `S` | - | -| `template` | `string` | sandbox template name or ID. | -| `opts`? | `SandboxBetaCreateOpts` | connection options. | - -###### Returns - -`Promise`\<`InstanceType`\<`S`\>\> - -sandbox instance for the new sandbox. - -###### Example - -```ts -const sandbox = await Sandbox.create('') -``` - -###### Constructs - -Sandbox - -### create() - -###### create(this, opts) - -```ts -static create(this: S, opts?: SandboxOpts): Promise> -``` - -Create a new sandbox from the default `desktop` sandbox template. - -###### Type Parameters - -| Type Parameter | -| ------ | -| `S` *extends* *typeof* `Sandbox` | - -###### Parameters - -| Parameter | Type | Description | -| ------ | ------ | ------ | -| `this` | `S` | - | -| `opts`? | `SandboxOpts` | connection options. | - -###### Returns - -`Promise`\<`InstanceType`\<`S`\>\> - -sandbox instance for the new sandbox. - -###### Example - -```ts -const sandbox = await Sandbox.create() -``` - -###### Constructs - -Sandbox - -###### create(this, template, opts) - -```ts -static create( - this: S, - template: string, -opts?: SandboxOpts): Promise> -``` - -Create a new sandbox from the specified sandbox template. - -###### Type Parameters - -| Type Parameter | -| ------ | -| `S` *extends* *typeof* `Sandbox` | - -###### Parameters - -| Parameter | Type | Description | -| ------ | ------ | ------ | -| `this` | `S` | - | -| `template` | `string` | sandbox template name or ID. | -| `opts`? | `SandboxOpts` | connection options. | - -###### Returns - -`Promise`\<`InstanceType`\<`S`\>\> - -sandbox instance for the new sandbox. - -###### Example - -```ts -const sandbox = await Sandbox.create('') -``` - -###### Constructs - -Sandbox - -## Interfaces - -### SandboxBetaCreateOpts - -Configuration options for the Sandbox environment. - SandboxOpts - -#### Properties - -### display? - -```ts -optional display: string; -``` - -Display identifier. - -### dpi? - -```ts -optional dpi: number; -``` - -Dots per inch (DPI) setting for the display. - -### resolution? - -```ts -optional resolution: [number, number]; -``` - -The screen resolution in pixels, specified as [width, height]. - -*** - -### SandboxOpts - -Configuration options for the Sandbox environment. - SandboxOpts - -#### Properties - -### display? - -```ts -optional display: string; -``` - -Display identifier. - -### dpi? - -```ts -optional dpi: number; -``` - -Dots per inch (DPI) setting for the display. - -### resolution? - -```ts -optional resolution: [number, number]; -``` - -The screen resolution in pixels, specified as [width, height]. diff --git a/docs/sdk-reference/desktop-js-sdk/v2.2.1/sandbox.mdx b/docs/sdk-reference/desktop-js-sdk/v2.2.1/sandbox.mdx deleted file mode 100644 index 890b05b..0000000 --- a/docs/sdk-reference/desktop-js-sdk/v2.2.1/sandbox.mdx +++ /dev/null @@ -1,697 +0,0 @@ ---- -sidebarTitle: "Sandbox" -mode: "center" ---- - -### Sandbox - -#### Properties - -| Property | Modifier | Type | Default value | -| ------ | ------ | ------ | ------ | -| `display` | `public` | `string` | `':0'` | -| `stream` | `public` | `VNCServer` | `undefined` | - -#### Methods - -### doubleClick() - -```ts -doubleClick(x?: number, y?: number): Promise -``` - -Double left click on the mouse position. - -###### Parameters - -| Parameter | Type | -| ------ | ------ | -| `x`? | `number` | -| `y`? | `number` | - -###### Returns - -`Promise`\<`void`\> - -### drag() - -```ts -drag(from: [number, number], to: [number, number]): Promise -``` - -Drag the mouse from the given position to the given position. - -###### Parameters - -| Parameter | Type | Description | -| ------ | ------ | ------ | -| `from` | [`number`, `number`] | The starting position. | -| `to` | [`number`, `number`] | The ending position. | - -###### Returns - -`Promise`\<`void`\> - -### getApplicationWindows() - -```ts -getApplicationWindows(application: string): Promise -``` - -Get the window ID of the window with the given title. - -###### Parameters - -| Parameter | Type | -| ------ | ------ | -| `application` | `string` | - -###### Returns - -`Promise`\<`string`[]\> - -The ID of the window. - -### getCurrentWindowId() - -```ts -getCurrentWindowId(): Promise -``` - -Get the current window ID. - -###### Returns - -`Promise`\<`string`\> - -The ID of the current window. - -### getCursorPosition() - -```ts -getCursorPosition(): Promise -``` - -Get the current cursor position. - -###### Returns - -`Promise`\<`CursorPosition`\> - -A object with the x and y coordinates - -###### Throws - -Error if cursor position cannot be determined - -### getScreenSize() - -```ts -getScreenSize(): Promise -``` - -Get the current screen size. - -###### Returns - -`Promise`\<`ScreenSize`\> - -An ScreenSize object - -###### Throws - -Error if screen size cannot be determined - -### getWindowTitle() - -```ts -getWindowTitle(windowId: string): Promise -``` - -Get the title of the window with the given ID. - -###### Parameters - -| Parameter | Type | Description | -| ------ | ------ | ------ | -| `windowId` | `string` | The ID of the window. | - -###### Returns - -`Promise`\<`string`\> - -The title of the window. - -### launch() - -```ts -launch(application: string, uri?: string): Promise -``` - -Launch an application. - -###### Parameters - -| Parameter | Type | Description | -| ------ | ------ | ------ | -| `application` | `string` | The application to launch. | -| `uri`? | `string` | The URI to open in the application. | - -###### Returns - -`Promise`\<`void`\> - -### leftClick() - -```ts -leftClick(x?: number, y?: number): Promise -``` - -Left click on the mouse position. - -###### Parameters - -| Parameter | Type | -| ------ | ------ | -| `x`? | `number` | -| `y`? | `number` | - -###### Returns - -`Promise`\<`void`\> - -### middleClick() - -```ts -middleClick(x?: number, y?: number): Promise -``` - -Middle click on the mouse position. - -###### Parameters - -| Parameter | Type | -| ------ | ------ | -| `x`? | `number` | -| `y`? | `number` | - -###### Returns - -`Promise`\<`void`\> - -### mousePress() - -```ts -mousePress(button: "left" | "right" | "middle"): Promise -``` - -Press the mouse button. - -###### Parameters - -| Parameter | Type | Default value | -| ------ | ------ | ------ | -| `button` | `"left"` \| `"right"` \| `"middle"` | `'left'` | - -###### Returns - -`Promise`\<`void`\> - -### mouseRelease() - -```ts -mouseRelease(button: "left" | "right" | "middle"): Promise -``` - -Release the mouse button. - -###### Parameters - -| Parameter | Type | Default value | -| ------ | ------ | ------ | -| `button` | `"left"` \| `"right"` \| `"middle"` | `'left'` | - -###### Returns - -`Promise`\<`void`\> - -### moveMouse() - -```ts -moveMouse(x: number, y: number): Promise -``` - -Move the mouse to the given coordinates. - -###### Parameters - -| Parameter | Type | Description | -| ------ | ------ | ------ | -| `x` | `number` | The x coordinate. | -| `y` | `number` | The y coordinate. | - -###### Returns - -`Promise`\<`void`\> - -### open() - -```ts -open(fileOrUrl: string): Promise -``` - -Open a file or a URL in the default application. - -###### Parameters - -| Parameter | Type | Description | -| ------ | ------ | ------ | -| `fileOrUrl` | `string` | The file or URL to open. | - -###### Returns - -`Promise`\<`void`\> - -### press() - -```ts -press(key: string | string[]): Promise -``` - -Press a key. - -###### Parameters - -| Parameter | Type | Description | -| ------ | ------ | ------ | -| `key` | `string` \| `string`[] | The key to press (e.g. "enter", "space", "backspace", etc.). Can be a single key or an array of keys. | - -###### Returns - -`Promise`\<`void`\> - -### rightClick() - -```ts -rightClick(x?: number, y?: number): Promise -``` - -Right click on the mouse position. - -###### Parameters - -| Parameter | Type | -| ------ | ------ | -| `x`? | `number` | -| `y`? | `number` | - -###### Returns - -`Promise`\<`void`\> - -### screenshot() - -###### screenshot() - -```ts -screenshot(): Promise> -``` - -Take a screenshot and save it to the given name. - -###### Returns - -`Promise`\<`Uint8Array`\<`ArrayBufferLike`\>\> - -A Uint8Array bytes representation of the screenshot. - -###### screenshot(format) - -```ts -screenshot(format: "bytes"): Promise> -``` - -Take a screenshot and save it to the given name. - -###### Parameters - -| Parameter | Type | Description | -| ------ | ------ | ------ | -| `format` | `"bytes"` | The format of the screenshot. | - -###### Returns - -`Promise`\<`Uint8Array`\<`ArrayBufferLike`\>\> - -A Uint8Array bytes representation of the screenshot. - -###### screenshot(format) - -```ts -screenshot(format: "blob"): Promise -``` - -Take a screenshot and save it to the given name. - -###### Parameters - -| Parameter | Type | -| ------ | ------ | -| `format` | `"blob"` | - -###### Returns - -`Promise`\<`Blob`\> - -A Blob representation of the screenshot. - -###### screenshot(format) - -```ts -screenshot(format: "stream"): Promise>> -``` - -Take a screenshot and save it to the given name. - -###### Parameters - -| Parameter | Type | -| ------ | ------ | -| `format` | `"stream"` | - -###### Returns - -`Promise`\<`ReadableStream`\<`Uint8Array`\<`ArrayBufferLike`\>\>\> - -A ReadableStream of bytes representation of the screenshot. - -### scroll() - -```ts -scroll(direction: "down" | "up", amount: number): Promise -``` - -Scroll the mouse wheel by the given amount. - -###### Parameters - -| Parameter | Type | Default value | Description | -| ------ | ------ | ------ | ------ | -| `direction` | `"down"` \| `"up"` | `'down'` | The direction to scroll. Can be "up" or "down". | -| `amount` | `number` | `1` | The amount to scroll. | - -###### Returns - -`Promise`\<`void`\> - -### wait() - -```ts -wait(ms: number): Promise -``` - -Wait for the given amount of time. - -###### Parameters - -| Parameter | Type | Description | -| ------ | ------ | ------ | -| `ms` | `number` | The amount of time to wait in milliseconds. | - -###### Returns - -`Promise`\<`void`\> - -### waitAndVerify() - -```ts -waitAndVerify( - cmd: string, - onResult: (result: CommandResult) => boolean, - timeout: number, -interval: number): Promise -``` - -Wait for a command to return a specific result. - -###### Parameters - -| Parameter | Type | Default value | Description | -| ------ | ------ | ------ | ------ | -| `cmd` | `string` | `undefined` | The command to run. | -| `onResult` | (`result`: `CommandResult`) => `boolean` | `undefined` | The function to check the result of the command. | -| `timeout` | `number` | `10` | The maximum time to wait for the command to return the result. | -| `interval` | `number` | `0.5` | The interval to wait between checks. | - -###### Returns - -`Promise`\<`boolean`\> - -`true` if the command returned the result within the timeout, otherwise `false`. - -### write() - -```ts -write(text: string, options: object): Promise -``` - -Write the given text at the current cursor position. - -###### Parameters - -| Parameter | Type | Description | -| ------ | ------ | ------ | -| `text` | `string` | The text to write. | -| `options` | `object` | An object containing the chunk size and delay between each chunk of text. | -| `options.chunkSize` | `number` | The size of each chunk of text to write. Default is 25 characters. | -| `options.delayInMs` | `number` | The delay between each chunk of text. Default is 75 ms. | - -###### Returns - -`Promise`\<`void`\> - -### betaCreate() - -###### betaCreate(this, opts) - -```ts -static betaCreate(this: S, opts?: SandboxBetaCreateOpts): Promise> -``` - -Create a new sandbox from the default `desktop` sandbox template. - -###### Type Parameters - -| Type Parameter | -| ------ | -| `S` *extends* *typeof* `Sandbox` | - -###### Parameters - -| Parameter | Type | Description | -| ------ | ------ | ------ | -| `this` | `S` | - | -| `opts`? | `SandboxBetaCreateOpts` | connection options. | - -###### Returns - -`Promise`\<`InstanceType`\<`S`\>\> - -sandbox instance for the new sandbox. - -###### Example - -```ts -const sandbox = await Sandbox.create() -``` - -###### Constructs - -Sandbox - -###### betaCreate(this, template, opts) - -```ts -static betaCreate( - this: S, - template: string, -opts?: SandboxBetaCreateOpts): Promise> -``` - -Create a new sandbox from the specified sandbox template. - -###### Type Parameters - -| Type Parameter | -| ------ | -| `S` *extends* *typeof* `Sandbox` | - -###### Parameters - -| Parameter | Type | Description | -| ------ | ------ | ------ | -| `this` | `S` | - | -| `template` | `string` | sandbox template name or ID. | -| `opts`? | `SandboxBetaCreateOpts` | connection options. | - -###### Returns - -`Promise`\<`InstanceType`\<`S`\>\> - -sandbox instance for the new sandbox. - -###### Example - -```ts -const sandbox = await Sandbox.create('') -``` - -###### Constructs - -Sandbox - -### create() - -###### create(this, opts) - -```ts -static create(this: S, opts?: SandboxOpts): Promise> -``` - -Create a new sandbox from the default `desktop` sandbox template. - -###### Type Parameters - -| Type Parameter | -| ------ | -| `S` *extends* *typeof* `Sandbox` | - -###### Parameters - -| Parameter | Type | Description | -| ------ | ------ | ------ | -| `this` | `S` | - | -| `opts`? | `SandboxOpts` | connection options. | - -###### Returns - -`Promise`\<`InstanceType`\<`S`\>\> - -sandbox instance for the new sandbox. - -###### Example - -```ts -const sandbox = await Sandbox.create() -``` - -###### Constructs - -Sandbox - -###### create(this, template, opts) - -```ts -static create( - this: S, - template: string, -opts?: SandboxOpts): Promise> -``` - -Create a new sandbox from the specified sandbox template. - -###### Type Parameters - -| Type Parameter | -| ------ | -| `S` *extends* *typeof* `Sandbox` | - -###### Parameters - -| Parameter | Type | Description | -| ------ | ------ | ------ | -| `this` | `S` | - | -| `template` | `string` | sandbox template name or ID. | -| `opts`? | `SandboxOpts` | connection options. | - -###### Returns - -`Promise`\<`InstanceType`\<`S`\>\> - -sandbox instance for the new sandbox. - -###### Example - -```ts -const sandbox = await Sandbox.create('') -``` - -###### Constructs - -Sandbox - -## Interfaces - -### SandboxBetaCreateOpts - -Configuration options for the Sandbox environment. - SandboxOpts - -#### Properties - -### display? - -```ts -optional display: string; -``` - -Display identifier. - -### dpi? - -```ts -optional dpi: number; -``` - -Dots per inch (DPI) setting for the display. - -### resolution? - -```ts -optional resolution: [number, number]; -``` - -The screen resolution in pixels, specified as [width, height]. - -*** - -### SandboxOpts - -Configuration options for the Sandbox environment. - SandboxOpts - -#### Properties - -### display? - -```ts -optional display: string; -``` - -Display identifier. - -### dpi? - -```ts -optional dpi: number; -``` - -Dots per inch (DPI) setting for the display. - -### resolution? - -```ts -optional resolution: [number, number]; -``` - -The screen resolution in pixels, specified as [width, height]. diff --git a/docs/sdk-reference/desktop-js-sdk/v2.2.2/sandbox.mdx b/docs/sdk-reference/desktop-js-sdk/v2.2.2/sandbox.mdx deleted file mode 100644 index 890b05b..0000000 --- a/docs/sdk-reference/desktop-js-sdk/v2.2.2/sandbox.mdx +++ /dev/null @@ -1,697 +0,0 @@ ---- -sidebarTitle: "Sandbox" -mode: "center" ---- - -### Sandbox - -#### Properties - -| Property | Modifier | Type | Default value | -| ------ | ------ | ------ | ------ | -| `display` | `public` | `string` | `':0'` | -| `stream` | `public` | `VNCServer` | `undefined` | - -#### Methods - -### doubleClick() - -```ts -doubleClick(x?: number, y?: number): Promise -``` - -Double left click on the mouse position. - -###### Parameters - -| Parameter | Type | -| ------ | ------ | -| `x`? | `number` | -| `y`? | `number` | - -###### Returns - -`Promise`\<`void`\> - -### drag() - -```ts -drag(from: [number, number], to: [number, number]): Promise -``` - -Drag the mouse from the given position to the given position. - -###### Parameters - -| Parameter | Type | Description | -| ------ | ------ | ------ | -| `from` | [`number`, `number`] | The starting position. | -| `to` | [`number`, `number`] | The ending position. | - -###### Returns - -`Promise`\<`void`\> - -### getApplicationWindows() - -```ts -getApplicationWindows(application: string): Promise -``` - -Get the window ID of the window with the given title. - -###### Parameters - -| Parameter | Type | -| ------ | ------ | -| `application` | `string` | - -###### Returns - -`Promise`\<`string`[]\> - -The ID of the window. - -### getCurrentWindowId() - -```ts -getCurrentWindowId(): Promise -``` - -Get the current window ID. - -###### Returns - -`Promise`\<`string`\> - -The ID of the current window. - -### getCursorPosition() - -```ts -getCursorPosition(): Promise -``` - -Get the current cursor position. - -###### Returns - -`Promise`\<`CursorPosition`\> - -A object with the x and y coordinates - -###### Throws - -Error if cursor position cannot be determined - -### getScreenSize() - -```ts -getScreenSize(): Promise -``` - -Get the current screen size. - -###### Returns - -`Promise`\<`ScreenSize`\> - -An ScreenSize object - -###### Throws - -Error if screen size cannot be determined - -### getWindowTitle() - -```ts -getWindowTitle(windowId: string): Promise -``` - -Get the title of the window with the given ID. - -###### Parameters - -| Parameter | Type | Description | -| ------ | ------ | ------ | -| `windowId` | `string` | The ID of the window. | - -###### Returns - -`Promise`\<`string`\> - -The title of the window. - -### launch() - -```ts -launch(application: string, uri?: string): Promise -``` - -Launch an application. - -###### Parameters - -| Parameter | Type | Description | -| ------ | ------ | ------ | -| `application` | `string` | The application to launch. | -| `uri`? | `string` | The URI to open in the application. | - -###### Returns - -`Promise`\<`void`\> - -### leftClick() - -```ts -leftClick(x?: number, y?: number): Promise -``` - -Left click on the mouse position. - -###### Parameters - -| Parameter | Type | -| ------ | ------ | -| `x`? | `number` | -| `y`? | `number` | - -###### Returns - -`Promise`\<`void`\> - -### middleClick() - -```ts -middleClick(x?: number, y?: number): Promise -``` - -Middle click on the mouse position. - -###### Parameters - -| Parameter | Type | -| ------ | ------ | -| `x`? | `number` | -| `y`? | `number` | - -###### Returns - -`Promise`\<`void`\> - -### mousePress() - -```ts -mousePress(button: "left" | "right" | "middle"): Promise -``` - -Press the mouse button. - -###### Parameters - -| Parameter | Type | Default value | -| ------ | ------ | ------ | -| `button` | `"left"` \| `"right"` \| `"middle"` | `'left'` | - -###### Returns - -`Promise`\<`void`\> - -### mouseRelease() - -```ts -mouseRelease(button: "left" | "right" | "middle"): Promise -``` - -Release the mouse button. - -###### Parameters - -| Parameter | Type | Default value | -| ------ | ------ | ------ | -| `button` | `"left"` \| `"right"` \| `"middle"` | `'left'` | - -###### Returns - -`Promise`\<`void`\> - -### moveMouse() - -```ts -moveMouse(x: number, y: number): Promise -``` - -Move the mouse to the given coordinates. - -###### Parameters - -| Parameter | Type | Description | -| ------ | ------ | ------ | -| `x` | `number` | The x coordinate. | -| `y` | `number` | The y coordinate. | - -###### Returns - -`Promise`\<`void`\> - -### open() - -```ts -open(fileOrUrl: string): Promise -``` - -Open a file or a URL in the default application. - -###### Parameters - -| Parameter | Type | Description | -| ------ | ------ | ------ | -| `fileOrUrl` | `string` | The file or URL to open. | - -###### Returns - -`Promise`\<`void`\> - -### press() - -```ts -press(key: string | string[]): Promise -``` - -Press a key. - -###### Parameters - -| Parameter | Type | Description | -| ------ | ------ | ------ | -| `key` | `string` \| `string`[] | The key to press (e.g. "enter", "space", "backspace", etc.). Can be a single key or an array of keys. | - -###### Returns - -`Promise`\<`void`\> - -### rightClick() - -```ts -rightClick(x?: number, y?: number): Promise -``` - -Right click on the mouse position. - -###### Parameters - -| Parameter | Type | -| ------ | ------ | -| `x`? | `number` | -| `y`? | `number` | - -###### Returns - -`Promise`\<`void`\> - -### screenshot() - -###### screenshot() - -```ts -screenshot(): Promise> -``` - -Take a screenshot and save it to the given name. - -###### Returns - -`Promise`\<`Uint8Array`\<`ArrayBufferLike`\>\> - -A Uint8Array bytes representation of the screenshot. - -###### screenshot(format) - -```ts -screenshot(format: "bytes"): Promise> -``` - -Take a screenshot and save it to the given name. - -###### Parameters - -| Parameter | Type | Description | -| ------ | ------ | ------ | -| `format` | `"bytes"` | The format of the screenshot. | - -###### Returns - -`Promise`\<`Uint8Array`\<`ArrayBufferLike`\>\> - -A Uint8Array bytes representation of the screenshot. - -###### screenshot(format) - -```ts -screenshot(format: "blob"): Promise -``` - -Take a screenshot and save it to the given name. - -###### Parameters - -| Parameter | Type | -| ------ | ------ | -| `format` | `"blob"` | - -###### Returns - -`Promise`\<`Blob`\> - -A Blob representation of the screenshot. - -###### screenshot(format) - -```ts -screenshot(format: "stream"): Promise>> -``` - -Take a screenshot and save it to the given name. - -###### Parameters - -| Parameter | Type | -| ------ | ------ | -| `format` | `"stream"` | - -###### Returns - -`Promise`\<`ReadableStream`\<`Uint8Array`\<`ArrayBufferLike`\>\>\> - -A ReadableStream of bytes representation of the screenshot. - -### scroll() - -```ts -scroll(direction: "down" | "up", amount: number): Promise -``` - -Scroll the mouse wheel by the given amount. - -###### Parameters - -| Parameter | Type | Default value | Description | -| ------ | ------ | ------ | ------ | -| `direction` | `"down"` \| `"up"` | `'down'` | The direction to scroll. Can be "up" or "down". | -| `amount` | `number` | `1` | The amount to scroll. | - -###### Returns - -`Promise`\<`void`\> - -### wait() - -```ts -wait(ms: number): Promise -``` - -Wait for the given amount of time. - -###### Parameters - -| Parameter | Type | Description | -| ------ | ------ | ------ | -| `ms` | `number` | The amount of time to wait in milliseconds. | - -###### Returns - -`Promise`\<`void`\> - -### waitAndVerify() - -```ts -waitAndVerify( - cmd: string, - onResult: (result: CommandResult) => boolean, - timeout: number, -interval: number): Promise -``` - -Wait for a command to return a specific result. - -###### Parameters - -| Parameter | Type | Default value | Description | -| ------ | ------ | ------ | ------ | -| `cmd` | `string` | `undefined` | The command to run. | -| `onResult` | (`result`: `CommandResult`) => `boolean` | `undefined` | The function to check the result of the command. | -| `timeout` | `number` | `10` | The maximum time to wait for the command to return the result. | -| `interval` | `number` | `0.5` | The interval to wait between checks. | - -###### Returns - -`Promise`\<`boolean`\> - -`true` if the command returned the result within the timeout, otherwise `false`. - -### write() - -```ts -write(text: string, options: object): Promise -``` - -Write the given text at the current cursor position. - -###### Parameters - -| Parameter | Type | Description | -| ------ | ------ | ------ | -| `text` | `string` | The text to write. | -| `options` | `object` | An object containing the chunk size and delay between each chunk of text. | -| `options.chunkSize` | `number` | The size of each chunk of text to write. Default is 25 characters. | -| `options.delayInMs` | `number` | The delay between each chunk of text. Default is 75 ms. | - -###### Returns - -`Promise`\<`void`\> - -### betaCreate() - -###### betaCreate(this, opts) - -```ts -static betaCreate(this: S, opts?: SandboxBetaCreateOpts): Promise> -``` - -Create a new sandbox from the default `desktop` sandbox template. - -###### Type Parameters - -| Type Parameter | -| ------ | -| `S` *extends* *typeof* `Sandbox` | - -###### Parameters - -| Parameter | Type | Description | -| ------ | ------ | ------ | -| `this` | `S` | - | -| `opts`? | `SandboxBetaCreateOpts` | connection options. | - -###### Returns - -`Promise`\<`InstanceType`\<`S`\>\> - -sandbox instance for the new sandbox. - -###### Example - -```ts -const sandbox = await Sandbox.create() -``` - -###### Constructs - -Sandbox - -###### betaCreate(this, template, opts) - -```ts -static betaCreate( - this: S, - template: string, -opts?: SandboxBetaCreateOpts): Promise> -``` - -Create a new sandbox from the specified sandbox template. - -###### Type Parameters - -| Type Parameter | -| ------ | -| `S` *extends* *typeof* `Sandbox` | - -###### Parameters - -| Parameter | Type | Description | -| ------ | ------ | ------ | -| `this` | `S` | - | -| `template` | `string` | sandbox template name or ID. | -| `opts`? | `SandboxBetaCreateOpts` | connection options. | - -###### Returns - -`Promise`\<`InstanceType`\<`S`\>\> - -sandbox instance for the new sandbox. - -###### Example - -```ts -const sandbox = await Sandbox.create('') -``` - -###### Constructs - -Sandbox - -### create() - -###### create(this, opts) - -```ts -static create(this: S, opts?: SandboxOpts): Promise> -``` - -Create a new sandbox from the default `desktop` sandbox template. - -###### Type Parameters - -| Type Parameter | -| ------ | -| `S` *extends* *typeof* `Sandbox` | - -###### Parameters - -| Parameter | Type | Description | -| ------ | ------ | ------ | -| `this` | `S` | - | -| `opts`? | `SandboxOpts` | connection options. | - -###### Returns - -`Promise`\<`InstanceType`\<`S`\>\> - -sandbox instance for the new sandbox. - -###### Example - -```ts -const sandbox = await Sandbox.create() -``` - -###### Constructs - -Sandbox - -###### create(this, template, opts) - -```ts -static create( - this: S, - template: string, -opts?: SandboxOpts): Promise> -``` - -Create a new sandbox from the specified sandbox template. - -###### Type Parameters - -| Type Parameter | -| ------ | -| `S` *extends* *typeof* `Sandbox` | - -###### Parameters - -| Parameter | Type | Description | -| ------ | ------ | ------ | -| `this` | `S` | - | -| `template` | `string` | sandbox template name or ID. | -| `opts`? | `SandboxOpts` | connection options. | - -###### Returns - -`Promise`\<`InstanceType`\<`S`\>\> - -sandbox instance for the new sandbox. - -###### Example - -```ts -const sandbox = await Sandbox.create('') -``` - -###### Constructs - -Sandbox - -## Interfaces - -### SandboxBetaCreateOpts - -Configuration options for the Sandbox environment. - SandboxOpts - -#### Properties - -### display? - -```ts -optional display: string; -``` - -Display identifier. - -### dpi? - -```ts -optional dpi: number; -``` - -Dots per inch (DPI) setting for the display. - -### resolution? - -```ts -optional resolution: [number, number]; -``` - -The screen resolution in pixels, specified as [width, height]. - -*** - -### SandboxOpts - -Configuration options for the Sandbox environment. - SandboxOpts - -#### Properties - -### display? - -```ts -optional display: string; -``` - -Display identifier. - -### dpi? - -```ts -optional dpi: number; -``` - -Dots per inch (DPI) setting for the display. - -### resolution? - -```ts -optional resolution: [number, number]; -``` - -The screen resolution in pixels, specified as [width, height]. diff --git a/docs/sdk-reference/desktop-python-sdk/v2.0.0/desktop.mdx b/docs/sdk-reference/desktop-python-sdk/v2.0.0/desktop.mdx deleted file mode 100644 index 391f449..0000000 --- a/docs/sdk-reference/desktop-python-sdk/v2.0.0/desktop.mdx +++ /dev/null @@ -1,371 +0,0 @@ ---- -sidebarTitle: "Desktop" -mode: "center" ---- - - - - - - - - - -## Sandbox - -```python -class Sandbox(SandboxBase) -``` - - - -### create - -```python -@classmethod -def create(cls, - template: Optional[str] = None, - resolution: Optional[Tuple[int, int]] = None, - dpi: Optional[int] = None, - display: Optional[str] = None, - timeout: Optional[int] = None, - metadata: Optional[Dict[str, str]] = None, - envs: Optional[Dict[str, str]] = None, - secure: bool = True, - allow_internet_access: bool = True, - **opts: Unpack[ApiParams]) -> Self -``` - -Create a new sandbox. - -By default, the sandbox is created from the default `desktop` sandbox template. - -**Arguments**: - -- `template`: Sandbox template name or ID -- `resolution`: Startup the desktop with custom screen resolution. Defaults to (1024, 768) -- `dpi`: Startup the desktop with custom DPI. Defaults to 96 -- `display`: Startup the desktop with custom display. Defaults to ":0" -- `timeout`: Timeout for the sandbox in **seconds**, default to 300 seconds. The maximum time a sandbox can be kept alive is 24 hours (86_400 seconds) for Pro users and 1 hour (3_600 seconds) for Hobby users. -- `metadata`: Custom metadata for the sandbox -- `envs`: Custom environment variables for the sandbox -- `secure`: Envd is secured with access token and cannot be used without it -- `allow_internet_access`: Allow sandbox to access the internet, defaults to `True`. - -**Returns**: - -A Sandbox instance for the new sandbox -Use this method instead of using the constructor to create a new sandbox. - - - -### beta\_create - -```python -@classmethod -def beta_create(cls, - template: Optional[str] = None, - resolution: Optional[Tuple[int, int]] = None, - dpi: Optional[int] = None, - display: Optional[str] = None, - timeout: Optional[int] = None, - auto_pause: Optional[bool] = False, - metadata: Optional[Dict[str, str]] = None, - envs: Optional[Dict[str, str]] = None, - secure: bool = True, - allow_internet_access: bool = True, - **opts: Unpack[ApiParams]) -> Self -``` - -[BETA] This feature is in beta and may change in the future. - -Create a new sandbox. - -By default, the sandbox is created from the default `desktop` sandbox template. - -**Arguments**: - -- `template`: Sandbox template name or ID -- `resolution`: Startup the desktop with custom screen resolution. Defaults to (1024, 768) -- `dpi`: Startup the desktop with custom DPI. Defaults to 96 -- `display`: Startup the desktop with custom display. Defaults to ":0" -- `timeout`: Timeout for the sandbox in **seconds**, default to 300 seconds. The maximum time a sandbox can be kept alive is 24 hours (86_400 seconds) for Pro users and 1 hour (3_600 seconds) for Hobby users. -- `auto_pause`: Automatically pause the sandbox after the timeout expires. Defaults to `False`. -- `metadata`: Custom metadata for the sandbox -- `envs`: Custom environment variables for the sandbox -- `secure`: Envd is secured with access token and cannot be used without it -- `allow_internet_access`: Allow sandbox to access the internet, defaults to `True`. - -**Returns**: - -A Sandbox instance for the new sandbox -Use this method instead of using the constructor to create a new sandbox. - - - -### screenshot - -```python -@overload -def screenshot(format: Literal["stream"]) -> Iterator[bytes] -``` - -Take a screenshot and return it as a stream of bytes. - - - -### screenshot - -```python -@overload -def screenshot(format: Literal["bytes"]) -> bytearray -``` - -Take a screenshot and return it as a bytearray. - - - -### screenshot - -```python -def screenshot(format: Literal["bytes", "stream"] = "bytes") -``` - -Take a screenshot and return it in the specified format. - -**Arguments**: - -- `format`: The format of the screenshot. Can be 'bytes', 'blob', or 'stream'. - -**Returns**: - -The screenshot in the specified format. - - - -### left\_click - -```python -def left_click(x: Optional[int] = None, y: Optional[int] = None) -``` - -Left click on the mouse position. - - - -### double\_click - -```python -def double_click(x: Optional[int] = None, y: Optional[int] = None) -``` - -Double left click on the mouse position. - - - -### middle\_click - -```python -def middle_click(x: Optional[int] = None, y: Optional[int] = None) -``` - -Middle click on the mouse position. - - - -### scroll - -```python -def scroll(direction: Literal["up", "down"] = "down", amount: int = 1) -``` - -Scroll the mouse wheel by the given amount. - -**Arguments**: - -- `direction`: The direction to scroll. Can be "up" or "down". -- `amount`: The amount to scroll. - - - -### move\_mouse - -```python -def move_mouse(x: int, y: int) -``` - -Move the mouse to the given coordinates. - -**Arguments**: - -- `x`: The x coordinate. -- `y`: The y coordinate. - - - -### mouse\_press - -```python -def mouse_press(button: Literal["left", "right", "middle"] = "left") -``` - -Press the mouse button. - - - -### mouse\_release - -```python -def mouse_release(button: Literal["left", "right", "middle"] = "left") -``` - -Release the mouse button. - - - -### get\_cursor\_position - -```python -def get_cursor_position() -> tuple[int, int] -``` - -Get the current cursor position. - -**Raises**: - -- `RuntimeError`: If the cursor position cannot be determined - -**Returns**: - -A tuple with the x and y coordinates - - - -### get\_screen\_size - -```python -def get_screen_size() -> tuple[int, int] -``` - -Get the current screen size. - -**Raises**: - -- `RuntimeError`: If the screen size cannot be determined - -**Returns**: - -A tuple with the width and height - - - -### write - -```python -def write(text: str, *, chunk_size: int = 25, delay_in_ms: int = 75) -> None -``` - -Write the given text at the current cursor position. - -**Arguments**: - -- `text`: The text to write. -- `chunk_size`: The size of each chunk of text to write. -- `delay_in_ms`: The delay between each chunk of text. - - - -### press - -```python -def press(key: Union[str, list[str]]) -``` - -Press a key. - -**Arguments**: - -- `key`: The key to press (e.g. "enter", "space", "backspace", etc.). - - - -### drag - -```python -def drag(fr: tuple[int, int], to: tuple[int, int]) -``` - -Drag the mouse from the given position to the given position. - -**Arguments**: - -- `from`: The starting position. -- `to`: The ending position. - - - -### wait - -```python -def wait(ms: int) -``` - -Wait for the given amount of time. - -**Arguments**: - -- `ms`: The amount of time to wait in milliseconds. - - - -### open - -```python -def open(file_or_url: str) -``` - -Open a file or a URL in the default application. - -**Arguments**: - -- `file_or_url`: The file or URL to open. - - - -### get\_current\_window\_id - -```python -def get_current_window_id() -> str -``` - -Get the current window ID. - - - -### get\_application\_windows - -```python -def get_application_windows(application: str) -> list[str] -``` - -Get the window IDs of all windows for the given application. - - - -### get\_window\_title - -```python -def get_window_title(window_id: str) -> str -``` - -Get the title of the window with the given ID. - - - -### launch - -```python -def launch(application: str, uri: Optional[str] = None) -``` - -Launch an application. diff --git a/docs/sdk-reference/desktop-python-sdk/v2.0.1/desktop.mdx b/docs/sdk-reference/desktop-python-sdk/v2.0.1/desktop.mdx deleted file mode 100644 index 391f449..0000000 --- a/docs/sdk-reference/desktop-python-sdk/v2.0.1/desktop.mdx +++ /dev/null @@ -1,371 +0,0 @@ ---- -sidebarTitle: "Desktop" -mode: "center" ---- - - - - - - - - - -## Sandbox - -```python -class Sandbox(SandboxBase) -``` - - - -### create - -```python -@classmethod -def create(cls, - template: Optional[str] = None, - resolution: Optional[Tuple[int, int]] = None, - dpi: Optional[int] = None, - display: Optional[str] = None, - timeout: Optional[int] = None, - metadata: Optional[Dict[str, str]] = None, - envs: Optional[Dict[str, str]] = None, - secure: bool = True, - allow_internet_access: bool = True, - **opts: Unpack[ApiParams]) -> Self -``` - -Create a new sandbox. - -By default, the sandbox is created from the default `desktop` sandbox template. - -**Arguments**: - -- `template`: Sandbox template name or ID -- `resolution`: Startup the desktop with custom screen resolution. Defaults to (1024, 768) -- `dpi`: Startup the desktop with custom DPI. Defaults to 96 -- `display`: Startup the desktop with custom display. Defaults to ":0" -- `timeout`: Timeout for the sandbox in **seconds**, default to 300 seconds. The maximum time a sandbox can be kept alive is 24 hours (86_400 seconds) for Pro users and 1 hour (3_600 seconds) for Hobby users. -- `metadata`: Custom metadata for the sandbox -- `envs`: Custom environment variables for the sandbox -- `secure`: Envd is secured with access token and cannot be used without it -- `allow_internet_access`: Allow sandbox to access the internet, defaults to `True`. - -**Returns**: - -A Sandbox instance for the new sandbox -Use this method instead of using the constructor to create a new sandbox. - - - -### beta\_create - -```python -@classmethod -def beta_create(cls, - template: Optional[str] = None, - resolution: Optional[Tuple[int, int]] = None, - dpi: Optional[int] = None, - display: Optional[str] = None, - timeout: Optional[int] = None, - auto_pause: Optional[bool] = False, - metadata: Optional[Dict[str, str]] = None, - envs: Optional[Dict[str, str]] = None, - secure: bool = True, - allow_internet_access: bool = True, - **opts: Unpack[ApiParams]) -> Self -``` - -[BETA] This feature is in beta and may change in the future. - -Create a new sandbox. - -By default, the sandbox is created from the default `desktop` sandbox template. - -**Arguments**: - -- `template`: Sandbox template name or ID -- `resolution`: Startup the desktop with custom screen resolution. Defaults to (1024, 768) -- `dpi`: Startup the desktop with custom DPI. Defaults to 96 -- `display`: Startup the desktop with custom display. Defaults to ":0" -- `timeout`: Timeout for the sandbox in **seconds**, default to 300 seconds. The maximum time a sandbox can be kept alive is 24 hours (86_400 seconds) for Pro users and 1 hour (3_600 seconds) for Hobby users. -- `auto_pause`: Automatically pause the sandbox after the timeout expires. Defaults to `False`. -- `metadata`: Custom metadata for the sandbox -- `envs`: Custom environment variables for the sandbox -- `secure`: Envd is secured with access token and cannot be used without it -- `allow_internet_access`: Allow sandbox to access the internet, defaults to `True`. - -**Returns**: - -A Sandbox instance for the new sandbox -Use this method instead of using the constructor to create a new sandbox. - - - -### screenshot - -```python -@overload -def screenshot(format: Literal["stream"]) -> Iterator[bytes] -``` - -Take a screenshot and return it as a stream of bytes. - - - -### screenshot - -```python -@overload -def screenshot(format: Literal["bytes"]) -> bytearray -``` - -Take a screenshot and return it as a bytearray. - - - -### screenshot - -```python -def screenshot(format: Literal["bytes", "stream"] = "bytes") -``` - -Take a screenshot and return it in the specified format. - -**Arguments**: - -- `format`: The format of the screenshot. Can be 'bytes', 'blob', or 'stream'. - -**Returns**: - -The screenshot in the specified format. - - - -### left\_click - -```python -def left_click(x: Optional[int] = None, y: Optional[int] = None) -``` - -Left click on the mouse position. - - - -### double\_click - -```python -def double_click(x: Optional[int] = None, y: Optional[int] = None) -``` - -Double left click on the mouse position. - - - -### middle\_click - -```python -def middle_click(x: Optional[int] = None, y: Optional[int] = None) -``` - -Middle click on the mouse position. - - - -### scroll - -```python -def scroll(direction: Literal["up", "down"] = "down", amount: int = 1) -``` - -Scroll the mouse wheel by the given amount. - -**Arguments**: - -- `direction`: The direction to scroll. Can be "up" or "down". -- `amount`: The amount to scroll. - - - -### move\_mouse - -```python -def move_mouse(x: int, y: int) -``` - -Move the mouse to the given coordinates. - -**Arguments**: - -- `x`: The x coordinate. -- `y`: The y coordinate. - - - -### mouse\_press - -```python -def mouse_press(button: Literal["left", "right", "middle"] = "left") -``` - -Press the mouse button. - - - -### mouse\_release - -```python -def mouse_release(button: Literal["left", "right", "middle"] = "left") -``` - -Release the mouse button. - - - -### get\_cursor\_position - -```python -def get_cursor_position() -> tuple[int, int] -``` - -Get the current cursor position. - -**Raises**: - -- `RuntimeError`: If the cursor position cannot be determined - -**Returns**: - -A tuple with the x and y coordinates - - - -### get\_screen\_size - -```python -def get_screen_size() -> tuple[int, int] -``` - -Get the current screen size. - -**Raises**: - -- `RuntimeError`: If the screen size cannot be determined - -**Returns**: - -A tuple with the width and height - - - -### write - -```python -def write(text: str, *, chunk_size: int = 25, delay_in_ms: int = 75) -> None -``` - -Write the given text at the current cursor position. - -**Arguments**: - -- `text`: The text to write. -- `chunk_size`: The size of each chunk of text to write. -- `delay_in_ms`: The delay between each chunk of text. - - - -### press - -```python -def press(key: Union[str, list[str]]) -``` - -Press a key. - -**Arguments**: - -- `key`: The key to press (e.g. "enter", "space", "backspace", etc.). - - - -### drag - -```python -def drag(fr: tuple[int, int], to: tuple[int, int]) -``` - -Drag the mouse from the given position to the given position. - -**Arguments**: - -- `from`: The starting position. -- `to`: The ending position. - - - -### wait - -```python -def wait(ms: int) -``` - -Wait for the given amount of time. - -**Arguments**: - -- `ms`: The amount of time to wait in milliseconds. - - - -### open - -```python -def open(file_or_url: str) -``` - -Open a file or a URL in the default application. - -**Arguments**: - -- `file_or_url`: The file or URL to open. - - - -### get\_current\_window\_id - -```python -def get_current_window_id() -> str -``` - -Get the current window ID. - - - -### get\_application\_windows - -```python -def get_application_windows(application: str) -> list[str] -``` - -Get the window IDs of all windows for the given application. - - - -### get\_window\_title - -```python -def get_window_title(window_id: str) -> str -``` - -Get the title of the window with the given ID. - - - -### launch - -```python -def launch(application: str, uri: Optional[str] = None) -``` - -Launch an application. diff --git a/docs/sdk-reference/desktop-python-sdk/v2.1.0/desktop.mdx b/docs/sdk-reference/desktop-python-sdk/v2.1.0/desktop.mdx deleted file mode 100644 index 391f449..0000000 --- a/docs/sdk-reference/desktop-python-sdk/v2.1.0/desktop.mdx +++ /dev/null @@ -1,371 +0,0 @@ ---- -sidebarTitle: "Desktop" -mode: "center" ---- - - - - - - - - - -## Sandbox - -```python -class Sandbox(SandboxBase) -``` - - - -### create - -```python -@classmethod -def create(cls, - template: Optional[str] = None, - resolution: Optional[Tuple[int, int]] = None, - dpi: Optional[int] = None, - display: Optional[str] = None, - timeout: Optional[int] = None, - metadata: Optional[Dict[str, str]] = None, - envs: Optional[Dict[str, str]] = None, - secure: bool = True, - allow_internet_access: bool = True, - **opts: Unpack[ApiParams]) -> Self -``` - -Create a new sandbox. - -By default, the sandbox is created from the default `desktop` sandbox template. - -**Arguments**: - -- `template`: Sandbox template name or ID -- `resolution`: Startup the desktop with custom screen resolution. Defaults to (1024, 768) -- `dpi`: Startup the desktop with custom DPI. Defaults to 96 -- `display`: Startup the desktop with custom display. Defaults to ":0" -- `timeout`: Timeout for the sandbox in **seconds**, default to 300 seconds. The maximum time a sandbox can be kept alive is 24 hours (86_400 seconds) for Pro users and 1 hour (3_600 seconds) for Hobby users. -- `metadata`: Custom metadata for the sandbox -- `envs`: Custom environment variables for the sandbox -- `secure`: Envd is secured with access token and cannot be used without it -- `allow_internet_access`: Allow sandbox to access the internet, defaults to `True`. - -**Returns**: - -A Sandbox instance for the new sandbox -Use this method instead of using the constructor to create a new sandbox. - - - -### beta\_create - -```python -@classmethod -def beta_create(cls, - template: Optional[str] = None, - resolution: Optional[Tuple[int, int]] = None, - dpi: Optional[int] = None, - display: Optional[str] = None, - timeout: Optional[int] = None, - auto_pause: Optional[bool] = False, - metadata: Optional[Dict[str, str]] = None, - envs: Optional[Dict[str, str]] = None, - secure: bool = True, - allow_internet_access: bool = True, - **opts: Unpack[ApiParams]) -> Self -``` - -[BETA] This feature is in beta and may change in the future. - -Create a new sandbox. - -By default, the sandbox is created from the default `desktop` sandbox template. - -**Arguments**: - -- `template`: Sandbox template name or ID -- `resolution`: Startup the desktop with custom screen resolution. Defaults to (1024, 768) -- `dpi`: Startup the desktop with custom DPI. Defaults to 96 -- `display`: Startup the desktop with custom display. Defaults to ":0" -- `timeout`: Timeout for the sandbox in **seconds**, default to 300 seconds. The maximum time a sandbox can be kept alive is 24 hours (86_400 seconds) for Pro users and 1 hour (3_600 seconds) for Hobby users. -- `auto_pause`: Automatically pause the sandbox after the timeout expires. Defaults to `False`. -- `metadata`: Custom metadata for the sandbox -- `envs`: Custom environment variables for the sandbox -- `secure`: Envd is secured with access token and cannot be used without it -- `allow_internet_access`: Allow sandbox to access the internet, defaults to `True`. - -**Returns**: - -A Sandbox instance for the new sandbox -Use this method instead of using the constructor to create a new sandbox. - - - -### screenshot - -```python -@overload -def screenshot(format: Literal["stream"]) -> Iterator[bytes] -``` - -Take a screenshot and return it as a stream of bytes. - - - -### screenshot - -```python -@overload -def screenshot(format: Literal["bytes"]) -> bytearray -``` - -Take a screenshot and return it as a bytearray. - - - -### screenshot - -```python -def screenshot(format: Literal["bytes", "stream"] = "bytes") -``` - -Take a screenshot and return it in the specified format. - -**Arguments**: - -- `format`: The format of the screenshot. Can be 'bytes', 'blob', or 'stream'. - -**Returns**: - -The screenshot in the specified format. - - - -### left\_click - -```python -def left_click(x: Optional[int] = None, y: Optional[int] = None) -``` - -Left click on the mouse position. - - - -### double\_click - -```python -def double_click(x: Optional[int] = None, y: Optional[int] = None) -``` - -Double left click on the mouse position. - - - -### middle\_click - -```python -def middle_click(x: Optional[int] = None, y: Optional[int] = None) -``` - -Middle click on the mouse position. - - - -### scroll - -```python -def scroll(direction: Literal["up", "down"] = "down", amount: int = 1) -``` - -Scroll the mouse wheel by the given amount. - -**Arguments**: - -- `direction`: The direction to scroll. Can be "up" or "down". -- `amount`: The amount to scroll. - - - -### move\_mouse - -```python -def move_mouse(x: int, y: int) -``` - -Move the mouse to the given coordinates. - -**Arguments**: - -- `x`: The x coordinate. -- `y`: The y coordinate. - - - -### mouse\_press - -```python -def mouse_press(button: Literal["left", "right", "middle"] = "left") -``` - -Press the mouse button. - - - -### mouse\_release - -```python -def mouse_release(button: Literal["left", "right", "middle"] = "left") -``` - -Release the mouse button. - - - -### get\_cursor\_position - -```python -def get_cursor_position() -> tuple[int, int] -``` - -Get the current cursor position. - -**Raises**: - -- `RuntimeError`: If the cursor position cannot be determined - -**Returns**: - -A tuple with the x and y coordinates - - - -### get\_screen\_size - -```python -def get_screen_size() -> tuple[int, int] -``` - -Get the current screen size. - -**Raises**: - -- `RuntimeError`: If the screen size cannot be determined - -**Returns**: - -A tuple with the width and height - - - -### write - -```python -def write(text: str, *, chunk_size: int = 25, delay_in_ms: int = 75) -> None -``` - -Write the given text at the current cursor position. - -**Arguments**: - -- `text`: The text to write. -- `chunk_size`: The size of each chunk of text to write. -- `delay_in_ms`: The delay between each chunk of text. - - - -### press - -```python -def press(key: Union[str, list[str]]) -``` - -Press a key. - -**Arguments**: - -- `key`: The key to press (e.g. "enter", "space", "backspace", etc.). - - - -### drag - -```python -def drag(fr: tuple[int, int], to: tuple[int, int]) -``` - -Drag the mouse from the given position to the given position. - -**Arguments**: - -- `from`: The starting position. -- `to`: The ending position. - - - -### wait - -```python -def wait(ms: int) -``` - -Wait for the given amount of time. - -**Arguments**: - -- `ms`: The amount of time to wait in milliseconds. - - - -### open - -```python -def open(file_or_url: str) -``` - -Open a file or a URL in the default application. - -**Arguments**: - -- `file_or_url`: The file or URL to open. - - - -### get\_current\_window\_id - -```python -def get_current_window_id() -> str -``` - -Get the current window ID. - - - -### get\_application\_windows - -```python -def get_application_windows(application: str) -> list[str] -``` - -Get the window IDs of all windows for the given application. - - - -### get\_window\_title - -```python -def get_window_title(window_id: str) -> str -``` - -Get the title of the window with the given ID. - - - -### launch - -```python -def launch(application: str, uri: Optional[str] = None) -``` - -Launch an application. diff --git a/docs/sdk-reference/desktop-python-sdk/v2.2.0/desktop.mdx b/docs/sdk-reference/desktop-python-sdk/v2.2.0/desktop.mdx deleted file mode 100644 index 391f449..0000000 --- a/docs/sdk-reference/desktop-python-sdk/v2.2.0/desktop.mdx +++ /dev/null @@ -1,371 +0,0 @@ ---- -sidebarTitle: "Desktop" -mode: "center" ---- - - - - - - - - - -## Sandbox - -```python -class Sandbox(SandboxBase) -``` - - - -### create - -```python -@classmethod -def create(cls, - template: Optional[str] = None, - resolution: Optional[Tuple[int, int]] = None, - dpi: Optional[int] = None, - display: Optional[str] = None, - timeout: Optional[int] = None, - metadata: Optional[Dict[str, str]] = None, - envs: Optional[Dict[str, str]] = None, - secure: bool = True, - allow_internet_access: bool = True, - **opts: Unpack[ApiParams]) -> Self -``` - -Create a new sandbox. - -By default, the sandbox is created from the default `desktop` sandbox template. - -**Arguments**: - -- `template`: Sandbox template name or ID -- `resolution`: Startup the desktop with custom screen resolution. Defaults to (1024, 768) -- `dpi`: Startup the desktop with custom DPI. Defaults to 96 -- `display`: Startup the desktop with custom display. Defaults to ":0" -- `timeout`: Timeout for the sandbox in **seconds**, default to 300 seconds. The maximum time a sandbox can be kept alive is 24 hours (86_400 seconds) for Pro users and 1 hour (3_600 seconds) for Hobby users. -- `metadata`: Custom metadata for the sandbox -- `envs`: Custom environment variables for the sandbox -- `secure`: Envd is secured with access token and cannot be used without it -- `allow_internet_access`: Allow sandbox to access the internet, defaults to `True`. - -**Returns**: - -A Sandbox instance for the new sandbox -Use this method instead of using the constructor to create a new sandbox. - - - -### beta\_create - -```python -@classmethod -def beta_create(cls, - template: Optional[str] = None, - resolution: Optional[Tuple[int, int]] = None, - dpi: Optional[int] = None, - display: Optional[str] = None, - timeout: Optional[int] = None, - auto_pause: Optional[bool] = False, - metadata: Optional[Dict[str, str]] = None, - envs: Optional[Dict[str, str]] = None, - secure: bool = True, - allow_internet_access: bool = True, - **opts: Unpack[ApiParams]) -> Self -``` - -[BETA] This feature is in beta and may change in the future. - -Create a new sandbox. - -By default, the sandbox is created from the default `desktop` sandbox template. - -**Arguments**: - -- `template`: Sandbox template name or ID -- `resolution`: Startup the desktop with custom screen resolution. Defaults to (1024, 768) -- `dpi`: Startup the desktop with custom DPI. Defaults to 96 -- `display`: Startup the desktop with custom display. Defaults to ":0" -- `timeout`: Timeout for the sandbox in **seconds**, default to 300 seconds. The maximum time a sandbox can be kept alive is 24 hours (86_400 seconds) for Pro users and 1 hour (3_600 seconds) for Hobby users. -- `auto_pause`: Automatically pause the sandbox after the timeout expires. Defaults to `False`. -- `metadata`: Custom metadata for the sandbox -- `envs`: Custom environment variables for the sandbox -- `secure`: Envd is secured with access token and cannot be used without it -- `allow_internet_access`: Allow sandbox to access the internet, defaults to `True`. - -**Returns**: - -A Sandbox instance for the new sandbox -Use this method instead of using the constructor to create a new sandbox. - - - -### screenshot - -```python -@overload -def screenshot(format: Literal["stream"]) -> Iterator[bytes] -``` - -Take a screenshot and return it as a stream of bytes. - - - -### screenshot - -```python -@overload -def screenshot(format: Literal["bytes"]) -> bytearray -``` - -Take a screenshot and return it as a bytearray. - - - -### screenshot - -```python -def screenshot(format: Literal["bytes", "stream"] = "bytes") -``` - -Take a screenshot and return it in the specified format. - -**Arguments**: - -- `format`: The format of the screenshot. Can be 'bytes', 'blob', or 'stream'. - -**Returns**: - -The screenshot in the specified format. - - - -### left\_click - -```python -def left_click(x: Optional[int] = None, y: Optional[int] = None) -``` - -Left click on the mouse position. - - - -### double\_click - -```python -def double_click(x: Optional[int] = None, y: Optional[int] = None) -``` - -Double left click on the mouse position. - - - -### middle\_click - -```python -def middle_click(x: Optional[int] = None, y: Optional[int] = None) -``` - -Middle click on the mouse position. - - - -### scroll - -```python -def scroll(direction: Literal["up", "down"] = "down", amount: int = 1) -``` - -Scroll the mouse wheel by the given amount. - -**Arguments**: - -- `direction`: The direction to scroll. Can be "up" or "down". -- `amount`: The amount to scroll. - - - -### move\_mouse - -```python -def move_mouse(x: int, y: int) -``` - -Move the mouse to the given coordinates. - -**Arguments**: - -- `x`: The x coordinate. -- `y`: The y coordinate. - - - -### mouse\_press - -```python -def mouse_press(button: Literal["left", "right", "middle"] = "left") -``` - -Press the mouse button. - - - -### mouse\_release - -```python -def mouse_release(button: Literal["left", "right", "middle"] = "left") -``` - -Release the mouse button. - - - -### get\_cursor\_position - -```python -def get_cursor_position() -> tuple[int, int] -``` - -Get the current cursor position. - -**Raises**: - -- `RuntimeError`: If the cursor position cannot be determined - -**Returns**: - -A tuple with the x and y coordinates - - - -### get\_screen\_size - -```python -def get_screen_size() -> tuple[int, int] -``` - -Get the current screen size. - -**Raises**: - -- `RuntimeError`: If the screen size cannot be determined - -**Returns**: - -A tuple with the width and height - - - -### write - -```python -def write(text: str, *, chunk_size: int = 25, delay_in_ms: int = 75) -> None -``` - -Write the given text at the current cursor position. - -**Arguments**: - -- `text`: The text to write. -- `chunk_size`: The size of each chunk of text to write. -- `delay_in_ms`: The delay between each chunk of text. - - - -### press - -```python -def press(key: Union[str, list[str]]) -``` - -Press a key. - -**Arguments**: - -- `key`: The key to press (e.g. "enter", "space", "backspace", etc.). - - - -### drag - -```python -def drag(fr: tuple[int, int], to: tuple[int, int]) -``` - -Drag the mouse from the given position to the given position. - -**Arguments**: - -- `from`: The starting position. -- `to`: The ending position. - - - -### wait - -```python -def wait(ms: int) -``` - -Wait for the given amount of time. - -**Arguments**: - -- `ms`: The amount of time to wait in milliseconds. - - - -### open - -```python -def open(file_or_url: str) -``` - -Open a file or a URL in the default application. - -**Arguments**: - -- `file_or_url`: The file or URL to open. - - - -### get\_current\_window\_id - -```python -def get_current_window_id() -> str -``` - -Get the current window ID. - - - -### get\_application\_windows - -```python -def get_application_windows(application: str) -> list[str] -``` - -Get the window IDs of all windows for the given application. - - - -### get\_window\_title - -```python -def get_window_title(window_id: str) -> str -``` - -Get the title of the window with the given ID. - - - -### launch - -```python -def launch(application: str, uri: Optional[str] = None) -``` - -Launch an application. diff --git a/docs/sdk-reference/js-sdk/1.0.0/errors.mdx b/docs/sdk-reference/js-sdk/1.0.0/errors.mdx deleted file mode 100644 index 1e56924..0000000 --- a/docs/sdk-reference/js-sdk/1.0.0/errors.mdx +++ /dev/null @@ -1,197 +0,0 @@ ---- -sidebarTitle: "Errors" -mode: "center" ---- - -# errors - -## Classes - -### AuthenticationError - -Thrown when authentication fails. - -#### Constructors - -> **new AuthenticationError**(`message`): `AuthenticationError` - -###### Parameters - -• **message**: `any` - -###### Returns - -`AuthenticationError` - -###### Defined in - -errors.ts:72 - -*** - -### InvalidArgumentError - -Thrown when an invalid argument is provided. - -#### Constructors - -> **new InvalidArgumentError**(`message`): `InvalidArgumentError` - -###### Parameters - -• **message**: `string` - -###### Returns - -`InvalidArgumentError` - -###### Defined in - -errors.ts:42 - -*** - -### NotEnoughSpaceError - -Thrown when there is not enough disk space. - -#### Constructors - -> **new NotEnoughSpaceError**(`message`): `NotEnoughSpaceError` - -###### Parameters - -• **message**: `string` - -###### Returns - -`NotEnoughSpaceError` - -###### Defined in - -errors.ts:52 - -*** - -### NotFoundError - -Thrown when a resource is not found. - -#### Constructors - -> **new NotFoundError**(`message`): `NotFoundError` - -###### Parameters - -• **message**: `string` - -###### Returns - -`NotFoundError` - -###### Defined in - -errors.ts:62 - -*** - -### SandboxError - -Base class for all sandbox errors. - -Thrown when general sandbox errors occur. - -#### Extended by - -- `TimeoutError` -- `InvalidArgumentError` -- `NotEnoughSpaceError` -- `NotFoundError` -- `AuthenticationError` -- `TemplateError` - -#### Constructors - -> **new SandboxError**(`message`): `SandboxError` - -###### Parameters - -• **message**: `any` - -###### Returns - -`SandboxError` - -###### Defined in - -errors.ts:14 - -*** - -### TemplateError - -Thrown when the template uses old envd version. It isn't compatible with the new SDK. - -#### Constructors - -> **new TemplateError**(`message`): `TemplateError` - -###### Parameters - -• **message**: `string` - -###### Returns - -`TemplateError` - -###### Defined in - -errors.ts:82 - -*** - -### TimeoutError - -Thrown when a timeout error occurs. - -The [unavailable] error type is caused by sandbox timeout. - -The [canceled] error type is caused by exceeding request timeout. - -The [deadline_exceeded] error type is caused by exceeding the timeout for command execution, watch, etc. - -The [unknown] error type is sometimes caused by the sandbox timeout when the request is not processed correctly. - -#### Constructors - -> **new TimeoutError**(`message`): `TimeoutError` - -###### Parameters - -• **message**: `string` - -###### Returns - -`TimeoutError` - -###### Defined in - -errors.ts:32 - -## Functions - -### formatSandboxTimeoutError() - -> **formatSandboxTimeoutError**(`message`): `TimeoutError` - -#### Parameters - -• **message**: `string` - -#### Returns - -`TimeoutError` - -#### Defined in - -errors.ts:2 diff --git a/docs/sdk-reference/js-sdk/1.0.0/sandbox-filesystem.mdx b/docs/sdk-reference/js-sdk/1.0.0/sandbox-filesystem.mdx deleted file mode 100644 index 32481ec..0000000 --- a/docs/sdk-reference/js-sdk/1.0.0/sandbox-filesystem.mdx +++ /dev/null @@ -1,521 +0,0 @@ ---- -sidebarTitle: "Filesystem" -mode: "center" ---- - -# sandbox/filesystem - -## Enumerations - -### FileType - -Sandbox filesystem object type. - -#### Enumeration Members - -### DIR - -> **DIR**: `"dir"` - -Filesystem object is a directory. - -###### Defined in - -sandbox/filesystem/index.ts:55 - -### FILE - -> **FILE**: `"file"` - -Filesystem object is a file. - -###### Defined in - -sandbox/filesystem/index.ts:51 - -## Classes - -### Filesystem - -Module for interacting with the sandbox filesystem. - -#### Constructors - -> **new Filesystem**(`transport`, `envdApi`, `connectionConfig`): `Filesystem` - -###### Parameters - -• **transport**: `Transport` - -• **envdApi**: `EnvdApiClient` - -• **connectionConfig**: `ConnectionConfig` - -###### Returns - -`Filesystem` - -###### Defined in - -sandbox/filesystem/index.ts:104 - -#### Methods - -### exists() - -> **exists**(`path`, `opts`?): `Promise`\<`boolean`\> - -Check if a file or a directory exists. - -###### Parameters - -• **path**: `string` - -path to a file or a directory - -• **opts?**: `FilesystemRequestOpts` - -connection options. - -###### Returns - -`Promise`\<`boolean`\> - -`true` if the file or directory exists, `false` otherwise - -###### Defined in - -sandbox/filesystem/index.ts:399 - -### list() - -> **list**(`path`, `opts`?): `Promise`\<`EntryInfo`[]\> - -List entries in a directory. - -###### Parameters - -• **path**: `string` - -path to the directory. - -• **opts?**: `FilesystemRequestOpts` - -connection options. - -###### Returns - -`Promise`\<`EntryInfo`[]\> - -list of entries in the sandbox filesystem directory. - -###### Defined in - -sandbox/filesystem/index.ts:270 - -### makeDir() - -> **makeDir**(`path`, `opts`?): `Promise`\<`boolean`\> - -Create a new directory and all directories along the way if needed on the specified path. - -###### Parameters - -• **path**: `string` - -path to a new directory. For example '/dirA/dirB' when creating 'dirB'. - -• **opts?**: `FilesystemRequestOpts` - -connection options. - -###### Returns - -`Promise`\<`boolean`\> - -`true` if the directory was created, `false` if it already exists. - -###### Defined in - -sandbox/filesystem/index.ts:308 - -### read() - -###### read(path, opts) - -> **read**(`path`, `opts`?): `Promise`\<`string`\> - -Read file content as a `string`. - -You can pass `text`, `bytes`, `blob`, or `stream` to `opts.format` to change the return type. - -###### Parameters - -• **path**: `string` - -path to the file. - -• **opts?**: `FilesystemRequestOpts` & `object` - -connection options. - -###### Returns - -`Promise`\<`string`\> - -file content as string - -###### Defined in - -sandbox/filesystem/index.ts:123 - -###### read(path, opts) - -> **read**(`path`, `opts`?): `Promise`\<`Uint8Array`\> - -Read file content as a `Uint8Array`. - -You can pass `text`, `bytes`, `blob`, or `stream` to `opts.format` to change the return type. - -###### Parameters - -• **path**: `string` - -path to the file. - -• **opts?**: `FilesystemRequestOpts` & `object` - -connection options. - -###### Returns - -`Promise`\<`Uint8Array`\> - -file content as `Uint8Array` - -###### Defined in - -sandbox/filesystem/index.ts:138 - -###### read(path, opts) - -> **read**(`path`, `opts`?): `Promise`\<`Blob`\> - -Read file content as a `Blob`. - -You can pass `text`, `bytes`, `blob`, or `stream` to `opts.format` to change the return type. - -###### Parameters - -• **path**: `string` - -path to the file. - -• **opts?**: `FilesystemRequestOpts` & `object` - -connection options. - -###### Returns - -`Promise`\<`Blob`\> - -file content as `Blob` - -###### Defined in - -sandbox/filesystem/index.ts:153 - -###### read(path, opts) - -> **read**(`path`, `opts`?): `Promise`\<`ReadableStream`\<`Uint8Array`\>\> - -Read file content as a `ReadableStream`. - -You can pass `text`, `bytes`, `blob`, or `stream` to `opts.format` to change the return type. - -###### Parameters - -• **path**: `string` - -path to the file. - -• **opts?**: `FilesystemRequestOpts` & `object` - -connection options. - -###### Returns - -`Promise`\<`ReadableStream`\<`Uint8Array`\>\> - -file content as `ReadableStream` - -###### Defined in - -sandbox/filesystem/index.ts:168 - -### remove() - -> **remove**(`path`, `opts`?): `Promise`\<`void`\> - -Remove a file or directory. - -###### Parameters - -• **path**: `string` - -path to a file or directory. - -• **opts?**: `FilesystemRequestOpts` - -connection options. - -###### Returns - -`Promise`\<`void`\> - -###### Defined in - -sandbox/filesystem/index.ts:377 - -### rename() - -> **rename**(`oldPath`, `newPath`, `opts`?): `Promise`\<`EntryInfo`\> - -Rename a file or directory. - -###### Parameters - -• **oldPath**: `string` - -path to the file or directory to rename. - -• **newPath**: `string` - -new path for the file or directory. - -• **opts?**: `FilesystemRequestOpts` - -connection options. - -###### Returns - -`Promise`\<`EntryInfo`\> - -information about renamed file or directory. - -###### Defined in - -sandbox/filesystem/index.ts:339 - -### watchDir() - -> **watchDir**(`path`, `onEvent`, `opts`?): `Promise`\<`WatchHandle`\> - -Start watching a directory for filesystem events. - -###### Parameters - -• **path**: `string` - -path to directory to watch. - -• **onEvent** - -callback to call when an event in the directory occurs. - -• **opts?**: `WatchOpts` - -connection options. - -###### Returns - -`Promise`\<`WatchHandle`\> - -`WatchHandle` object for stopping watching directory. - -###### Defined in - -sandbox/filesystem/index.ts:430 - -### write() - -> **write**(`path`, `data`, `opts`?): `Promise`\<`EntryInfo`\> - -Write content to a file. - -Writing to a file that doesn't exist creates the file. - -Writing to a file that already exists overwrites the file. - -Writing to a file at path that doesn't exist creates the necessary directories. - -###### Parameters - -• **path**: `string` - -path to file. - -• **data**: `string` \| `ArrayBuffer` \| `Blob` \| `ReadableStream`\<`any`\> - -data to write to the file. Data can be a string, `ArrayBuffer`, `Blob`, or `ReadableStream`. - -• **opts?**: `FilesystemRequestOpts` - -connection options. - -###### Returns - -`Promise`\<`EntryInfo`\> - -information about the written file - -###### Defined in - -sandbox/filesystem/index.ts:224 - -## Interfaces - -### EntryInfo - -Sandbox filesystem object information. - -#### Properties - -### name - -> **name**: `string` - -Name of the filesystem object. - -###### Defined in - -sandbox/filesystem/index.ts:33 - -### path - -> **path**: `string` - -Path to the filesystem object. - -###### Defined in - -sandbox/filesystem/index.ts:41 - -### type? - -> `optional` **type**: `FileType` - -Type of the filesystem object. - -###### Defined in - -sandbox/filesystem/index.ts:37 - -*** - -### FilesystemRequestOpts - -Options for the sandbox filesystem operations. - -#### Extended by - -- `WatchOpts` - -#### Properties - -### requestTimeoutMs? - -> `optional` **requestTimeoutMs**: `number` - -Timeout for requests to the API in **milliseconds**. - -###### Default - -```ts -30_000 // 30 seconds -``` - -###### Defined in - -connectionConfig.ts:42 - -### user? - -> `optional` **user**: `Username` - -User to use for the operation in the sandbox. -This affects the resolution of relative paths and ownership of the created filesystem objects. - -###### Defined in - -sandbox/filesystem/index.ts:76 - -*** - -### WatchOpts - -Options for watching a directory. - -#### Properties - -### onExit()? - -> `optional` **onExit**: (`err`?) => `void` \| `Promise`\<`void`\> - -Callback to call when the watch operation stops. - -###### Parameters - -• **err?**: `Error` - -###### Returns - -`void` \| `Promise`\<`void`\> - -###### Defined in - -sandbox/filesystem/index.ts:93 - -### requestTimeoutMs? - -> `optional` **requestTimeoutMs**: `number` - -Timeout for requests to the API in **milliseconds**. - -###### Default - -```ts -30_000 // 30 seconds -``` - -###### Defined in - -connectionConfig.ts:42 - -### timeoutMs? - -> `optional` **timeoutMs**: `number` - -Timeout for the watch operation in **milliseconds**. -You can pass `0` to disable the timeout. - -###### Default - -```ts -60_000 // 60 seconds -``` - -###### Defined in - -sandbox/filesystem/index.ts:89 - -### user? - -> `optional` **user**: `Username` - -User to use for the operation in the sandbox. -This affects the resolution of relative paths and ownership of the created filesystem objects. - -###### Defined in - -sandbox/filesystem/index.ts:76 diff --git a/docs/sdk-reference/js-sdk/1.0.0/sandbox.mdx b/docs/sdk-reference/js-sdk/1.0.0/sandbox.mdx deleted file mode 100644 index 388c4d2..0000000 --- a/docs/sdk-reference/js-sdk/1.0.0/sandbox.mdx +++ /dev/null @@ -1,586 +0,0 @@ ---- -sidebarTitle: "Sandbox" -mode: "center" ---- - -# sandbox - -## Classes - -### Sandbox - -E2B cloud sandbox is a secure and isolated cloud environment. - -The sandbox allows you to: -- Access Linux OS -- Create, list, and delete files and directories -- Run commands -- Run isolated code -- Access the internet - -Check docs here. - -Use Sandbox.create to create a new sandbox. - -#### Example - -```ts -import { Sandbox } from 'e2b' - -const sandbox = await Sandbox.create() -``` - -#### Properties - -### commands - -> `readonly` **commands**: `Commands` - -Module for running commands in the sandbox - -###### Defined in - -sandbox/index.ts:74 - -### files - -> `readonly` **files**: `Filesystem` - -Module for interacting with the sandbox filesystem - -###### Defined in - -sandbox/index.ts:70 - -### pty - -> `readonly` **pty**: `Pty` - -Module for interacting with the sandbox pseudo-terminals - -###### Defined in - -sandbox/index.ts:78 - -### sandboxId - -> `readonly` **sandboxId**: `string` - -Unique identifier of the sandbox. - -###### Defined in - -sandbox/index.ts:83 - -#### Methods - -### downloadUrl() - -> **downloadUrl**(`path`): `string` - -Get the URL to download a file from the sandbox. - -###### Parameters - -• **path**: `string` - -path to the file to download. - -###### Returns - -`string` - -URL for downloading file. - -###### Defined in - -sandbox/index.ts:339 - -### getHost() - -> **getHost**(`port`): `string` - -Get the host address for the specified sandbox port. -You can then use this address to connect to the sandbox port from outside the sandbox via HTTP or WebSocket. - -###### Parameters - -• **port**: `number` - -number of the port in the sandbox. - -###### Returns - -`string` - -host address of the sandbox port. - -###### Example - -```ts -const sandbox = await Sandbox.create() -// Start an HTTP server -await sandbox.commands.exec('python3 -m http.server 3000') -// Get the hostname of the HTTP server -const serverURL = sandbox.getHost(3000) -`` - -###### Defined in - -sandbox/index.ts:237 - -### isRunning() - -> **isRunning**(`opts`?): `Promise`\<`boolean`\> - -Check if the sandbox is running. - -###### Parameters - -• **opts?**: `Pick`\<`ConnectionOpts`, `"requestTimeoutMs"`\> - -###### Returns - -`Promise`\<`boolean`\> - -`true` if the sandbox is running, `false` otherwise. - -###### Example - -```ts -const sandbox = await Sandbox.create() -await sandbox.isRunning() // Returns true - -await sandbox.kill() -await sandbox.isRunning() // Returns false -``` - -###### Defined in - -sandbox/index.ts:259 - -### kill() - -> **kill**(`opts`?): `Promise`\<`void`\> - -Kill the sandbox. - -###### Parameters - -• **opts?**: `Pick`\<`SandboxOpts`, `"requestTimeoutMs"`\> - -connection options. - -###### Returns - -`Promise`\<`void`\> - -###### Defined in - -sandbox/index.ts:310 - -### setTimeout() - -> **setTimeout**(`timeoutMs`, `opts`?): `Promise`\<`void`\> - -Set the timeout of the sandbox. -After the timeout expires the sandbox will be automatically killed. - -This method can extend or reduce the sandbox timeout set when creating the sandbox or from the last call to `.setTimeout`. -Maximum time a sandbox can be kept alive is 24 hours (86_400_000 milliseconds) for Pro users and 1 hour (3_600_000 milliseconds) for Hobby users. - -###### Parameters - -• **timeoutMs**: `number` - -timeout in **milliseconds**. - -• **opts?**: `Pick`\<`SandboxOpts`, `"requestTimeoutMs"`\> - -connection options. - -###### Returns - -`Promise`\<`void`\> - -###### Defined in - -sandbox/index.ts:290 - -### uploadUrl() - -> **uploadUrl**(`path`?): `string` - -Get the URL to upload a file to the sandbox. - -You have to send a POST request to this URL with the file as multipart/form-data. - -###### Parameters - -• **path?**: `string` - -the directory where to upload the file, defaults to user's home directory. - -###### Returns - -`string` - -URL for uploading file. - -###### Defined in - -sandbox/index.ts:328 - -### connect() - -> `static` **connect**\<`S`\>(`this`, `sandboxId`, `opts`?): `Promise`\<`InstanceType`\<`S`\>\> - -Connect to an existing sandbox. -With sandbox ID you can connect to the same sandbox from different places or environments (serverless functions, etc). - -###### Type Parameters - -• **S** *extends* *typeof* `Sandbox` - -###### Parameters - -• **this**: `S` - -• **sandboxId**: `string` - -sandbox ID. - -• **opts?**: `Omit`\<`SandboxOpts`, `"timeoutMs"` \| `"metadata"` \| `"envs"`\> - -connection options. - -###### Returns - -`Promise`\<`InstanceType`\<`S`\>\> - -sandbox instance for the existing sandbox. - -###### Example - -```ts -const sandbox = await Sandbox.create() -const sandboxId = sandbox.sandboxId - -// Connect to the same sandbox. -const sameSandbox = await Sandbox.connect(sandboxId) -``` - -###### Defined in - -sandbox/index.ts:209 - -### create() - -###### create(this, opts) - -> `static` **create**\<`S`\>(`this`, `opts`?): `Promise`\<`InstanceType`\<`S`\>\> - -Create a new sandbox from the default `base` sandbox template. - -###### Type Parameters - -• **S** *extends* *typeof* `Sandbox` - -###### Parameters - -• **this**: `S` - -• **opts?**: `SandboxOpts` - -connection options. - -###### Returns - -`Promise`\<`InstanceType`\<`S`\>\> - -sandbox instance for the new sandbox. - -###### Example - -```ts -const sandbox = await Sandbox.create() -``` - -###### Constructs - -Sandbox - -###### Defined in - -sandbox/index.ts:143 - -###### create(this, template, opts) - -> `static` **create**\<`S`\>(`this`, `template`, `opts`?): `Promise`\<`InstanceType`\<`S`\>\> - -Create a new sandbox from the specified sandbox template. - -###### Type Parameters - -• **S** *extends* *typeof* `Sandbox` - -###### Parameters - -• **this**: `S` - -• **template**: `string` - -sandbox template name or ID. - -• **opts?**: `SandboxOpts` - -connection options. - -###### Returns - -`Promise`\<`InstanceType`\<`S`\>\> - -sandbox instance for the new sandbox. - -###### Example - -```ts -const sandbox = await Sandbox.create('') -``` - -###### Constructs - -Sandbox - -###### Defined in - -sandbox/index.ts:162 - -### kill() - -> `static` **kill**(`sandboxId`, `opts`?): `Promise`\<`boolean`\> - -Kill the sandbox specified by sandbox ID. - -###### Parameters - -• **sandboxId**: `string` - -sandbox ID. - -• **opts?**: `SandboxApiOpts` - -connection options. - -###### Returns - -`Promise`\<`boolean`\> - -`true` if the sandbox was found and killed, `false` otherwise. - -###### Defined in - -sandbox/sandboxApi.ts:55 - -### list() - -> `static` **list**(`opts`?): `Promise`\<`SandboxInfo`[]\> - -List all running sandboxes. - -###### Parameters - -• **opts?**: `SandboxApiOpts` - -connection options. - -###### Returns - -`Promise`\<`SandboxInfo`[]\> - -list of running sandboxes. - -###### Defined in - -sandbox/sandboxApi.ts:90 - -### setTimeout() - -> `static` **setTimeout**(`sandboxId`, `timeoutMs`, `opts`?): `Promise`\<`void`\> - -Set the timeout of the specified sandbox. -After the timeout expires the sandbox will be automatically killed. - -This method can extend or reduce the sandbox timeout set when creating the sandbox or from the last call to Sandbox.setTimeout. - -Maximum time a sandbox can be kept alive is 24 hours (86_400_000 milliseconds) for Pro users and 1 hour (3_600_000 milliseconds) for Hobby users. - -###### Parameters - -• **sandboxId**: `string` - -sandbox ID. - -• **timeoutMs**: `number` - -timeout in **milliseconds**. - -• **opts?**: `SandboxApiOpts` - -connection options. - -###### Returns - -`Promise`\<`void`\> - -###### Defined in - -sandbox/sandboxApi.ts:129 - -## Interfaces - -### SandboxOpts - -Options for creating a new Sandbox. - -#### Properties - -### accessToken? - -> `optional` **accessToken**: `string` - -E2B access token to use for authentication. - -###### Default - -```ts -E2B_ACCESS_TOKEN // environment variable -``` - -###### Defined in - -connectionConfig.ts:24 - -### apiKey? - -> `optional` **apiKey**: `string` - -E2B API key to use for authentication. - -###### Default - -```ts -E2B_API_KEY // environment variable -``` - -###### Defined in - -connectionConfig.ts:18 - -### debug? - -> `optional` **debug**: `boolean` - -**`Internal`** - -If true the SDK starts in the debug mode and connects to the local envd API server. - -###### Default - -E2B_DEBUG // environment variable or `false` - -###### Defined in - -connectionConfig.ts:36 - -### domain? - -> `optional` **domain**: `string` - -Domain to use for the API. - -###### Default - -E2B_DOMAIN // environment variable or `e2b.dev` - -###### Defined in - -connectionConfig.ts:30 - -### envs? - -> `optional` **envs**: `Record`\<`string`, `string`\> - -Custom environment variables for the sandbox. - -Used when executing commands and code in the sandbox. -Can be overridden with the `envs` argument when executing commands or code. - -###### Default - -```ts -{} -``` - -###### Defined in - -sandbox/index.ts:32 - -### logger? - -> `optional` **logger**: `Logger` - -Logger to use for logging messages. It can accept any object that implements `Logger` interface—for example, console. - -###### Defined in - -connectionConfig.ts:46 - -### metadata? - -> `optional` **metadata**: `Record`\<`string`, `string`\> - -Custom metadata for the sandbox. - -###### Default - -```ts -{} -``` - -###### Defined in - -sandbox/index.ts:23 - -### requestTimeoutMs? - -> `optional` **requestTimeoutMs**: `number` - -Timeout for requests to the API in **milliseconds**. - -###### Default - -```ts -30_000 // 30 seconds -``` - -###### Defined in - -connectionConfig.ts:42 - -### timeoutMs? - -> `optional` **timeoutMs**: `number` - -Timeout for the sandbox in **milliseconds**. -Maximum time a sandbox can be kept alive is 24 hours (86_400_000 milliseconds) for Pro users and 1 hour (3_600_000 milliseconds) for Hobby users. - -###### Default - -```ts -300_000 // 5 minutes -``` - -###### Defined in - -sandbox/index.ts:39 diff --git a/docs/sdk-reference/js-sdk/v2.8.2/errors.mdx b/docs/sdk-reference/js-sdk/v2.8.2/errors.mdx deleted file mode 100644 index bfe0deb..0000000 --- a/docs/sdk-reference/js-sdk/v2.8.2/errors.mdx +++ /dev/null @@ -1,271 +0,0 @@ ---- -sidebarTitle: "Errors" -mode: "center" ---- - -### AuthenticationError - -Thrown when authentication fails. - -#### Constructors - -```ts -new AuthenticationError(message: string): AuthenticationError -``` - -###### Parameters - -| Parameter | Type | -| ------ | ------ | -| `message` | `string` | - -###### Returns - -`AuthenticationError` - -*** - -### BuildError - -Thrown when the build fails. - -#### Extended by - -- `FileUploadError` - -#### Constructors - -```ts -new BuildError(message: string, stackTrace?: string): BuildError -``` - -###### Parameters - -| Parameter | Type | -| ------ | ------ | -| `message` | `string` | -| `stackTrace`? | `string` | - -###### Returns - -`BuildError` - -*** - -### FileUploadError - -Thrown when the file upload fails. - -#### Constructors - -```ts -new FileUploadError(message: string, stackTrace?: string): FileUploadError -``` - -###### Parameters - -| Parameter | Type | -| ------ | ------ | -| `message` | `string` | -| `stackTrace`? | `string` | - -###### Returns - -`FileUploadError` - -*** - -### InvalidArgumentError - -Thrown when an invalid argument is provided. - -#### Constructors - -```ts -new InvalidArgumentError(message: string, stackTrace?: string): InvalidArgumentError -``` - -###### Parameters - -| Parameter | Type | -| ------ | ------ | -| `message` | `string` | -| `stackTrace`? | `string` | - -###### Returns - -`InvalidArgumentError` - -*** - -### NotEnoughSpaceError - -Thrown when there is not enough disk space. - -#### Constructors - -```ts -new NotEnoughSpaceError(message: string, stackTrace?: string): NotEnoughSpaceError -``` - -###### Parameters - -| Parameter | Type | -| ------ | ------ | -| `message` | `string` | -| `stackTrace`? | `string` | - -###### Returns - -`NotEnoughSpaceError` - -*** - -### NotFoundError - -Thrown when a resource is not found. - -#### Constructors - -```ts -new NotFoundError(message: string, stackTrace?: string): NotFoundError -``` - -###### Parameters - -| Parameter | Type | -| ------ | ------ | -| `message` | `string` | -| `stackTrace`? | `string` | - -###### Returns - -`NotFoundError` - -*** - -### RateLimitError - -Thrown when the API rate limit is exceeded. - -#### Constructors - -```ts -new RateLimitError(message: string): RateLimitError -``` - -###### Parameters - -| Parameter | Type | -| ------ | ------ | -| `message` | `string` | - -###### Returns - -`RateLimitError` - -*** - -### SandboxError - -Base class for all sandbox errors. - -Thrown when general sandbox errors occur. - -#### Extended by - -- `TimeoutError` -- `InvalidArgumentError` -- `NotEnoughSpaceError` -- `NotFoundError` -- `TemplateError` -- `RateLimitError` - -#### Constructors - -```ts -new SandboxError(message?: string, stackTrace?: string): SandboxError -``` - -###### Parameters - -| Parameter | Type | -| ------ | ------ | -| `message`? | `string` | -| `stackTrace`? | `string` | - -###### Returns - -`SandboxError` - -*** - -### TemplateError - -Thrown when the template uses old envd version. It isn't compatible with the new SDK. - -#### Constructors - -```ts -new TemplateError(message: string, stackTrace?: string): TemplateError -``` - -###### Parameters - -| Parameter | Type | -| ------ | ------ | -| `message` | `string` | -| `stackTrace`? | `string` | - -###### Returns - -`TemplateError` - -*** - -### TimeoutError - -Thrown when a timeout error occurs. - -The [unavailable] error type is caused by sandbox timeout. - -The [canceled] error type is caused by exceeding request timeout. - -The [deadline_exceeded] error type is caused by exceeding the timeout for command execution, watch, etc. - -The [unknown] error type is sometimes caused by the sandbox timeout when the request is not processed correctly. - -#### Constructors - -```ts -new TimeoutError(message: string, stackTrace?: string): TimeoutError -``` - -###### Parameters - -| Parameter | Type | -| ------ | ------ | -| `message` | `string` | -| `stackTrace`? | `string` | - -###### Returns - -`TimeoutError` - -## Functions - -### formatSandboxTimeoutError() - -```ts -function formatSandboxTimeoutError(message: string): TimeoutError -``` - -#### Parameters - -| Parameter | Type | -| ------ | ------ | -| `message` | `string` | - -#### Returns - -`TimeoutError` diff --git a/docs/sdk-reference/js-sdk/v2.8.2/sandbox-commands.mdx b/docs/sdk-reference/js-sdk/v2.8.2/sandbox-commands.mdx deleted file mode 100644 index 16d736c..0000000 --- a/docs/sdk-reference/js-sdk/v2.8.2/sandbox-commands.mdx +++ /dev/null @@ -1,533 +0,0 @@ ---- -sidebarTitle: "Commands" -mode: "center" ---- - -### Commands - -Module for starting and interacting with commands in the sandbox. - -#### Constructors - -```ts -new Commands( - transport: Transport, - connectionConfig: ConnectionConfig, - metadata: object): Commands -``` - -###### Parameters - -| Parameter | Type | -| ------ | ------ | -| `transport` | `Transport` | -| `connectionConfig` | `ConnectionConfig` | -| `metadata` | `object` | -| `metadata.version` | `string` | - -###### Returns - -`Commands` - -#### Methods - -### connect() - -```ts -connect(pid: number, opts?: CommandConnectOpts): Promise -``` - -Connect to a running command. -You can use CommandHandle.wait to wait for the command to finish and get execution results. - -###### Parameters - -| Parameter | Type | Description | -| ------ | ------ | ------ | -| `pid` | `number` | process ID of the command to connect to. You can get the list of running commands using Commands.list. | -| `opts`? | `CommandConnectOpts` | connection options. | - -###### Returns - -`Promise`\<`CommandHandle`\> - -`CommandHandle` handle to interact with the running command. - -### kill() - -```ts -kill(pid: number, opts?: CommandRequestOpts): Promise -``` - -Kill a running command specified by its process ID. -It uses `SIGKILL` signal to kill the command. - -###### Parameters - -| Parameter | Type | Description | -| ------ | ------ | ------ | -| `pid` | `number` | process ID of the command. You can get the list of running commands using Commands.list. | -| `opts`? | `CommandRequestOpts` | connection options. | - -###### Returns - -`Promise`\<`boolean`\> - -`true` if the command was killed, `false` if the command was not found. - -### list() - -```ts -list(opts?: CommandRequestOpts): Promise -``` - -List all running commands and PTY sessions. - -###### Parameters - -| Parameter | Type | Description | -| ------ | ------ | ------ | -| `opts`? | `CommandRequestOpts` | connection options. | - -###### Returns - -`Promise`\<`ProcessInfo`[]\> - -list of running commands and PTY sessions. - -### run() - -###### run(cmd, opts) - -```ts -run(cmd: string, opts?: CommandStartOpts & object): Promise -``` - -Start a new command and wait until it finishes executing. - -###### Parameters - -| Parameter | Type | Description | -| ------ | ------ | ------ | -| `cmd` | `string` | command to execute. | -| `opts`? | `CommandStartOpts` & `object` | options for starting the command. | - -###### Returns - -`Promise`\<`CommandResult`\> - -`CommandResult` result of the command execution. - -###### run(cmd, opts) - -```ts -run(cmd: string, opts: CommandStartOpts & object): Promise -``` - -Start a new command in the background. -You can use CommandHandle.wait to wait for the command to finish and get its result. - -###### Parameters - -| Parameter | Type | Description | -| ------ | ------ | ------ | -| `cmd` | `string` | command to execute. | -| `opts` | `CommandStartOpts` & `object` | options for starting the command | - -###### Returns - -`Promise`\<`CommandHandle`\> - -`CommandHandle` handle to interact with the running command. - -###### run(cmd, opts) - -```ts -run(cmd: string, opts?: CommandStartOpts & object): Promise -``` - -Start a new command. - -###### Parameters - -| Parameter | Type | Description | -| ------ | ------ | ------ | -| `cmd` | `string` | command to execute. | -| `opts`? | `CommandStartOpts` & `object` | options for starting the command. - `opts.background: true` - runs in background, returns `CommandHandle` - `opts.background: false | undefined` - waits for completion, returns `CommandResult` | - -###### Returns - -`Promise`\<`CommandResult` \| `CommandHandle`\> - -Either a `CommandHandle` or a `CommandResult` (depending on `opts.background`). - -### sendStdin() - -```ts -sendStdin( - pid: number, - data: string, -opts?: CommandRequestOpts): Promise -``` - -Send data to command stdin. - -###### Parameters - -| Parameter | Type | Description | -| ------ | ------ | ------ | -| `pid` | `number` | process ID of the command. You can get the list of running commands using Commands.list. | -| `data` | `string` | data to send to the command. | -| `opts`? | `CommandRequestOpts` | connection options. | - -###### Returns - -`Promise`\<`void`\> - -*** - -### Pty - -Module for interacting with PTYs (pseudo-terminals) in the sandbox. - -#### Constructors - -```ts -new Pty( - transport: Transport, - connectionConfig: ConnectionConfig, - metadata: object): Pty -``` - -###### Parameters - -| Parameter | Type | -| ------ | ------ | -| `transport` | `Transport` | -| `connectionConfig` | `ConnectionConfig` | -| `metadata` | `object` | -| `metadata.version` | `string` | - -###### Returns - -`Pty` - -#### Methods - -### create() - -```ts -create(opts: PtyCreateOpts): Promise -``` - -Create a new PTY (pseudo-terminal). - -###### Parameters - -| Parameter | Type | Description | -| ------ | ------ | ------ | -| `opts` | `PtyCreateOpts` | options for creating the PTY. | - -###### Returns - -`Promise`\<`CommandHandle`\> - -handle to interact with the PTY. - -### kill() - -```ts -kill(pid: number, opts?: Pick): Promise -``` - -Kill a running PTY specified by process ID. -It uses `SIGKILL` signal to kill the PTY. - -###### Parameters - -| Parameter | Type | Description | -| ------ | ------ | ------ | -| `pid` | `number` | process ID of the PTY. | -| `opts`? | `Pick`\<`ConnectionOpts`, `"requestTimeoutMs"`\> | connection options. | - -###### Returns - -`Promise`\<`boolean`\> - -`true` if the PTY was killed, `false` if the PTY was not found. - -### resize() - -```ts -resize( - pid: number, - size: object, -opts?: Pick): Promise -``` - -Resize PTY. -Call this when the terminal window is resized and the number of columns and rows has changed. - -###### Parameters - -| Parameter | Type | Description | -| ------ | ------ | ------ | -| `pid` | `number` | process ID of the PTY. | -| `size` | `object` | new size of the PTY. | -| `size.cols` | `number` | - | -| `size.rows`? | `number` | - | -| `opts`? | `Pick`\<`ConnectionOpts`, `"requestTimeoutMs"`\> | connection options. | - -###### Returns - -`Promise`\<`void`\> - -### sendInput() - -```ts -sendInput( - pid: number, - data: Uint8Array, -opts?: Pick): Promise -``` - -Send input to a PTY. - -###### Parameters - -| Parameter | Type | Description | -| ------ | ------ | ------ | -| `pid` | `number` | process ID of the PTY. | -| `data` | `Uint8Array` | input data to send to the PTY. | -| `opts`? | `Pick`\<`ConnectionOpts`, `"requestTimeoutMs"`\> | connection options. | - -###### Returns - -`Promise`\<`void`\> - -## Interfaces - -### CommandRequestOpts - -Options for sending a command request. - -#### Extended by - -- `CommandStartOpts` - -#### Properties - -### requestTimeoutMs? - -```ts -optional requestTimeoutMs: number; -``` - -Timeout for requests to the API in **milliseconds**. - -###### Default - -```ts -60_000 // 60 seconds -``` - -*** - -### CommandStartOpts - -Options for starting a new command. - -#### Properties - -### background? - -```ts -optional background: boolean; -``` - -If true, starts command in the background and the method returns immediately. -You can use CommandHandle.wait to wait for the command to finish. - -### cwd? - -```ts -optional cwd: string; -``` - -Working directory for the command. - -###### Default - -```ts -// home directory of the user used to start the command -``` - -### envs? - -```ts -optional envs: Record; -``` - -Environment variables used for the command. - -This overrides the default environment variables from `Sandbox` constructor. - -###### Default - -`{}` - -### onStderr()? - -```ts -optional onStderr: (data: string) => void | Promise; -``` - -Callback for command stderr output. - -###### Parameters - -| Parameter | Type | -| ------ | ------ | -| `data` | `string` | - -###### Returns - -`void` \| `Promise`\<`void`\> - -### onStdout()? - -```ts -optional onStdout: (data: string) => void | Promise; -``` - -Callback for command stdout output. - -###### Parameters - -| Parameter | Type | -| ------ | ------ | -| `data` | `string` | - -###### Returns - -`void` \| `Promise`\<`void`\> - -### requestTimeoutMs? - -```ts -optional requestTimeoutMs: number; -``` - -Timeout for requests to the API in **milliseconds**. - -###### Default - -```ts -60_000 // 60 seconds -``` - -### stdin? - -```ts -optional stdin: boolean; -``` - -If true, command stdin is kept open and you can send data to it using Commands.sendStdin or CommandHandle.sendStdin. - -###### Default - -```ts -false -``` - -### timeoutMs? - -```ts -optional timeoutMs: number; -``` - -Timeout for the command in **milliseconds**. - -###### Default - -```ts -60_000 // 60 seconds -``` - -### user? - -```ts -optional user: string; -``` - -User to run the command as. - -###### Default - -`default Sandbox user (as specified in the template)` - -*** - -### ProcessInfo - -Information about a command, PTY session or start command running in the sandbox as process. - -#### Properties - -### args - -```ts -args: string[]; -``` - -Command arguments. - -### cmd - -```ts -cmd: string; -``` - -Command that was executed. - -### cwd? - -```ts -optional cwd: string; -``` - -Executed command working directory. - -### envs - -```ts -envs: Record; -``` - -Environment variables used for the command. - -### pid - -```ts -pid: number; -``` - -Process ID. - -### tag? - -```ts -optional tag: string; -``` - -Custom tag used for identifying special commands like start command in the custom template. - -## Type Aliases - -### CommandConnectOpts - -```ts -type CommandConnectOpts: Pick & CommandRequestOpts; -``` - -Options for connecting to a command. diff --git a/docs/sdk-reference/js-sdk/v2.8.2/sandbox-filesystem.mdx b/docs/sdk-reference/js-sdk/v2.8.2/sandbox-filesystem.mdx deleted file mode 100644 index c43ac2f..0000000 --- a/docs/sdk-reference/js-sdk/v2.8.2/sandbox-filesystem.mdx +++ /dev/null @@ -1,627 +0,0 @@ ---- -sidebarTitle: "Filesystem" -mode: "center" ---- - -### FileType - -Sandbox filesystem object type. - -#### Enumeration Members - -| Enumeration Member | Value | Description | -| ------ | ------ | ------ | -| `DIR` | `"dir"` | Filesystem object is a directory. | -| `FILE` | `"file"` | Filesystem object is a file. | - -## Classes - -### Filesystem - -Module for interacting with the sandbox filesystem. - -#### Constructors - -```ts -new Filesystem( - transport: Transport, - envdApi: EnvdApiClient, - connectionConfig: ConnectionConfig): Filesystem -``` - -###### Parameters - -| Parameter | Type | -| ------ | ------ | -| `transport` | `Transport` | -| `envdApi` | `EnvdApiClient` | -| `connectionConfig` | `ConnectionConfig` | - -###### Returns - -`Filesystem` - -#### Methods - -### exists() - -```ts -exists(path: string, opts?: FilesystemRequestOpts): Promise -``` - -Check if a file or a directory exists. - -###### Parameters - -| Parameter | Type | Description | -| ------ | ------ | ------ | -| `path` | `string` | path to a file or a directory | -| `opts`? | `FilesystemRequestOpts` | connection options. | - -###### Returns - -`Promise`\<`boolean`\> - -`true` if the file or directory exists, `false` otherwise - -### getInfo() - -```ts -getInfo(path: string, opts?: FilesystemRequestOpts): Promise -``` - -Get information about a file or directory. - -###### Parameters - -| Parameter | Type | Description | -| ------ | ------ | ------ | -| `path` | `string` | path to a file or directory. | -| `opts`? | `FilesystemRequestOpts` | connection options. | - -###### Returns - -`Promise`\<`EntryInfo`\> - -information about the file or directory like name, type, and path. - -### list() - -```ts -list(path: string, opts?: FilesystemListOpts): Promise -``` - -List entries in a directory. - -###### Parameters - -| Parameter | Type | Description | -| ------ | ------ | ------ | -| `path` | `string` | path to the directory. | -| `opts`? | `FilesystemListOpts` | connection options. | - -###### Returns - -`Promise`\<`EntryInfo`[]\> - -list of entries in the sandbox filesystem directory. - -### makeDir() - -```ts -makeDir(path: string, opts?: FilesystemRequestOpts): Promise -``` - -Create a new directory and all directories along the way if needed on the specified path. - -###### Parameters - -| Parameter | Type | Description | -| ------ | ------ | ------ | -| `path` | `string` | path to a new directory. For example '/dirA/dirB' when creating 'dirB'. | -| `opts`? | `FilesystemRequestOpts` | connection options. | - -###### Returns - -`Promise`\<`boolean`\> - -`true` if the directory was created, `false` if it already exists. - -### read() - -###### read(path, opts) - -```ts -read(path: string, opts?: FilesystemRequestOpts & object): Promise -``` - -Read file content as a `string`. - -You can pass `text`, `bytes`, `blob`, or `stream` to `opts.format` to change the return type. - -###### Parameters - -| Parameter | Type | Description | -| ------ | ------ | ------ | -| `path` | `string` | path to the file. | -| `opts`? | `FilesystemRequestOpts` & `object` | connection options. | - -###### Returns - -`Promise`\<`string`\> - -file content as string - -###### read(path, opts) - -```ts -read(path: string, opts?: FilesystemRequestOpts & object): Promise -``` - -Read file content as a `Uint8Array`. - -You can pass `text`, `bytes`, `blob`, or `stream` to `opts.format` to change the return type. - -###### Parameters - -| Parameter | Type | Description | -| ------ | ------ | ------ | -| `path` | `string` | path to the file. | -| `opts`? | `FilesystemRequestOpts` & `object` | connection options. | - -###### Returns - -`Promise`\<`Uint8Array`\> - -file content as `Uint8Array` - -###### read(path, opts) - -```ts -read(path: string, opts?: FilesystemRequestOpts & object): Promise -``` - -Read file content as a `Blob`. - -You can pass `text`, `bytes`, `blob`, or `stream` to `opts.format` to change the return type. - -###### Parameters - -| Parameter | Type | Description | -| ------ | ------ | ------ | -| `path` | `string` | path to the file. | -| `opts`? | `FilesystemRequestOpts` & `object` | connection options. | - -###### Returns - -`Promise`\<`Blob`\> - -file content as `Blob` - -###### read(path, opts) - -```ts -read(path: string, opts?: FilesystemRequestOpts & object): Promise> -``` - -Read file content as a `ReadableStream`. - -You can pass `text`, `bytes`, `blob`, or `stream` to `opts.format` to change the return type. - -###### Parameters - -| Parameter | Type | Description | -| ------ | ------ | ------ | -| `path` | `string` | path to the file. | -| `opts`? | `FilesystemRequestOpts` & `object` | connection options. | - -###### Returns - -`Promise`\<`ReadableStream`\<`Uint8Array`\>\> - -file content as `ReadableStream` - -### remove() - -```ts -remove(path: string, opts?: FilesystemRequestOpts): Promise -``` - -Remove a file or directory. - -###### Parameters - -| Parameter | Type | Description | -| ------ | ------ | ------ | -| `path` | `string` | path to a file or directory. | -| `opts`? | `FilesystemRequestOpts` | connection options. | - -###### Returns - -`Promise`\<`void`\> - -### rename() - -```ts -rename( - oldPath: string, - newPath: string, -opts?: FilesystemRequestOpts): Promise -``` - -Rename a file or directory. - -###### Parameters - -| Parameter | Type | Description | -| ------ | ------ | ------ | -| `oldPath` | `string` | path to the file or directory to rename. | -| `newPath` | `string` | new path for the file or directory. | -| `opts`? | `FilesystemRequestOpts` | connection options. | - -###### Returns - -`Promise`\<`EntryInfo`\> - -information about renamed file or directory. - -### watchDir() - -```ts -watchDir( - path: string, - onEvent: (event: FilesystemEvent) => void | Promise, -opts?: WatchOpts & object): Promise -``` - -Start watching a directory for filesystem events. - -###### Parameters - -| Parameter | Type | Description | -| ------ | ------ | ------ | -| `path` | `string` | path to directory to watch. | -| `onEvent` | (`event`: `FilesystemEvent`) => `void` \| `Promise`\<`void`\> | callback to call when an event in the directory occurs. | -| `opts`? | `WatchOpts` & `object` | connection options. | - -###### Returns - -`Promise`\<`WatchHandle`\> - -`WatchHandle` object for stopping watching directory. - -### write() - -###### write(path, data, opts) - -```ts -write( - path: string, - data: string | ArrayBuffer | Blob | ReadableStream, -opts?: FilesystemRequestOpts): Promise -``` - -Write content to a file. - -Writing to a file that doesn't exist creates the file. - -Writing to a file that already exists overwrites the file. - -Writing to a file at path that doesn't exist creates the necessary directories. - -###### Parameters - -| Parameter | Type | Description | -| ------ | ------ | ------ | -| `path` | `string` | path to file. | -| `data` | `string` \| `ArrayBuffer` \| `Blob` \| `ReadableStream`\<`any`\> | data to write to the file. Data can be a string, `ArrayBuffer`, `Blob`, or `ReadableStream`. | -| `opts`? | `FilesystemRequestOpts` | connection options. | - -###### Returns - -`Promise`\<`WriteInfo`\> - -information about the written file - -###### write(files, opts) - -```ts -write(files: WriteEntry[], opts?: FilesystemRequestOpts): Promise -``` - -###### Parameters - -| Parameter | Type | -| ------ | ------ | -| `files` | `WriteEntry`[] | -| `opts`? | `FilesystemRequestOpts` | - -###### Returns - -`Promise`\<`WriteInfo`[]\> - -## Interfaces - -### EntryInfo - -Sandbox filesystem object information. - -#### Properties - -### group - -```ts -group: string; -``` - -Group owner of the filesystem object. - -### mode - -```ts -mode: number; -``` - -File mode and permission bits. - -### modifiedTime? - -```ts -optional modifiedTime: Date; -``` - -Last modification time of the filesystem object. - -### name - -```ts -name: string; -``` - -Name of the filesystem object. - -### owner - -```ts -owner: string; -``` - -Owner of the filesystem object. - -### path - -```ts -path: string; -``` - -Path to the filesystem object. - -### permissions - -```ts -permissions: string; -``` - -String representation of file permissions (e.g. 'rwxr-xr-x'). - -### size - -```ts -size: number; -``` - -Size of the filesystem object in bytes. - -### symlinkTarget? - -```ts -optional symlinkTarget: string; -``` - -If the filesystem object is a symlink, this is the target of the symlink. - -### type? - -```ts -optional type: FileType; -``` - -Type of the filesystem object. - -*** - -### FilesystemListOpts - -Options for the sandbox filesystem operations. - -#### Properties - -### depth? - -```ts -optional depth: number; -``` - -Depth of the directory to list. - -### requestTimeoutMs? - -```ts -optional requestTimeoutMs: number; -``` - -Timeout for requests to the API in **milliseconds**. - -###### Default - -```ts -60_000 // 60 seconds -``` - -### user? - -```ts -optional user: string; -``` - -User to use for the operation in the sandbox. -This affects the resolution of relative paths and ownership of the created filesystem objects. - -*** - -### FilesystemRequestOpts - -Options for the sandbox filesystem operations. - -#### Extended by - -- `FilesystemListOpts` -- `WatchOpts` - -#### Properties - -### requestTimeoutMs? - -```ts -optional requestTimeoutMs: number; -``` - -Timeout for requests to the API in **milliseconds**. - -###### Default - -```ts -60_000 // 60 seconds -``` - -### user? - -```ts -optional user: string; -``` - -User to use for the operation in the sandbox. -This affects the resolution of relative paths and ownership of the created filesystem objects. - -*** - -### WatchOpts - -Options for watching a directory. - -#### Properties - -### onExit()? - -```ts -optional onExit: (err?: Error) => void | Promise; -``` - -Callback to call when the watch operation stops. - -###### Parameters - -| Parameter | Type | -| ------ | ------ | -| `err`? | `Error` | - -###### Returns - -`void` \| `Promise`\<`void`\> - -### recursive? - -```ts -optional recursive: boolean; -``` - -Watch the directory recursively - -### requestTimeoutMs? - -```ts -optional requestTimeoutMs: number; -``` - -Timeout for requests to the API in **milliseconds**. - -###### Default - -```ts -60_000 // 60 seconds -``` - -### timeoutMs? - -```ts -optional timeoutMs: number; -``` - -Timeout for the watch operation in **milliseconds**. -You can pass `0` to disable the timeout. - -###### Default - -```ts -60_000 // 60 seconds -``` - -### user? - -```ts -optional user: string; -``` - -User to use for the operation in the sandbox. -This affects the resolution of relative paths and ownership of the created filesystem objects. - -*** - -### WriteInfo - -Sandbox filesystem object information. - -#### Extended by - -- `EntryInfo` - -#### Properties - -### name - -```ts -name: string; -``` - -Name of the filesystem object. - -### path - -```ts -path: string; -``` - -Path to the filesystem object. - -### type? - -```ts -optional type: FileType; -``` - -Type of the filesystem object. - -## Type Aliases - -### WriteEntry - -```ts -type WriteEntry: object; -``` - -#### Type declaration - -| Name | Type | -| ------ | ------ | -| `data` | `string` \| `ArrayBuffer` \| `Blob` \| `ReadableStream` | -| `path` | `string` | diff --git a/docs/sdk-reference/js-sdk/v2.8.2/sandbox.mdx b/docs/sdk-reference/js-sdk/v2.8.2/sandbox.mdx deleted file mode 100644 index e430744..0000000 --- a/docs/sdk-reference/js-sdk/v2.8.2/sandbox.mdx +++ /dev/null @@ -1,712 +0,0 @@ ---- -sidebarTitle: "Sandbox" -mode: "center" ---- - -### Sandbox - -E2B cloud sandbox is a secure and isolated cloud environment. - -The sandbox allows you to: -- Access Linux OS -- Create, list, and delete files and directories -- Run commands -- Run isolated code -- Access the internet - -Check docs here. - -Use Sandbox.create to create a new sandbox. - -#### Example - -```ts -import { Sandbox } from 'e2b' - -const sandbox = await Sandbox.create() -``` - -#### Properties - -| Property | Modifier | Type | Description | -| ------ | ------ | ------ | ------ | -| `commands` | `readonly` | `Commands` | Module for running commands in the sandbox | -| `files` | `readonly` | `Filesystem` | Module for interacting with the sandbox filesystem | -| `pty` | `readonly` | `Pty` | Module for interacting with the sandbox pseudo-terminals | -| `sandboxDomain` | `readonly` | `string` | Domain where the sandbox is hosted. | -| `sandboxId` | `readonly` | `string` | Unique identifier of the sandbox. | -| `trafficAccessToken?` | `readonly` | `string` | Traffic access token for accessing sandbox services with restricted public traffic. | - -#### Methods - -### betaPause() - -```ts -betaPause(opts?: ConnectionOpts): Promise -``` - -**`Beta`** - -This feature is in beta and may change in the future. - -Pause a sandbox by its ID. - -###### Parameters - -| Parameter | Type | Description | -| ------ | ------ | ------ | -| `opts`? | `ConnectionOpts` | connection options. | - -###### Returns - -`Promise`\<`boolean`\> - -sandbox ID that can be used to resume the sandbox. - -### connect() - -```ts -connect(opts?: SandboxBetaCreateOpts): Promise -``` - -Connect to a sandbox. If the sandbox is paused, it will be automatically resumed. -Sandbox must be either running or be paused. - -With sandbox ID you can connect to the same sandbox from different places or environments (serverless functions, etc). - -###### Parameters - -| Parameter | Type | Description | -| ------ | ------ | ------ | -| `opts`? | `SandboxBetaCreateOpts` | connection options. | - -###### Returns - -`Promise`\<`Sandbox`\> - -A running sandbox instance - -###### Example - -```ts -const sandbox = await Sandbox.create() -await sandbox.betaPause() - -// Connect to the same sandbox. -const sameSandbox = await sandbox.connect() -``` - -### downloadUrl() - -```ts -downloadUrl(path: string, opts?: SandboxUrlOpts): Promise -``` - -Get the URL to download a file from the sandbox. - -###### Parameters - -| Parameter | Type | Description | -| ------ | ------ | ------ | -| `path` | `string` | path to the file in the sandbox. | -| `opts`? | `SandboxUrlOpts` | download url options. | - -###### Returns - -`Promise`\<`string`\> - -URL for downloading file. - -### getHost() - -```ts -getHost(port: number): string -``` - -Get the host address for the specified sandbox port. -You can then use this address to connect to the sandbox port from outside the sandbox via HTTP or WebSocket. - -###### Parameters - -| Parameter | Type | Description | -| ------ | ------ | ------ | -| `port` | `number` | number of the port in the sandbox. | - -###### Returns - -`string` - -host address of the sandbox port. - -###### Example - -```ts -const sandbox = await Sandbox.create() -// Start an HTTP server -await sandbox.commands.exec('python3 -m http.server 3000') -// Get the hostname of the HTTP server -const serverURL = sandbox.getHost(3000) -``` - -### getInfo() - -```ts -getInfo(opts?: Pick): Promise -``` - -Get sandbox information like sandbox ID, template, metadata, started at/end at date. - -###### Parameters - -| Parameter | Type | Description | -| ------ | ------ | ------ | -| `opts`? | `Pick`\<`SandboxOpts`, `"requestTimeoutMs"`\> | connection options. | - -###### Returns - -`Promise`\<`SandboxInfo`\> - -information about the sandbox - -### getMcpToken() - -```ts -getMcpToken(): Promise -``` - -Get the MCP token for the sandbox. - -###### Returns - -`Promise`\<`undefined` \| `string`\> - -MCP token for the sandbox, or undefined if MCP is not enabled. - -### getMcpUrl() - -```ts -getMcpUrl(): string -``` - -Get the MCP URL for the sandbox. - -###### Returns - -`string` - -MCP URL for the sandbox. - -### getMetrics() - -```ts -getMetrics(opts?: SandboxMetricsOpts): Promise -``` - -Get the metrics of the sandbox. - -###### Parameters - -| Parameter | Type | Description | -| ------ | ------ | ------ | -| `opts`? | `SandboxMetricsOpts` | connection options. | - -###### Returns - -`Promise`\<`SandboxMetrics`[]\> - -List of sandbox metrics containing CPU, memory and disk usage information. - -### isRunning() - -```ts -isRunning(opts?: Pick): Promise -``` - -Check if the sandbox is running. - -###### Parameters - -| Parameter | Type | -| ------ | ------ | -| `opts`? | `Pick`\<`ConnectionOpts`, `"requestTimeoutMs"`\> | - -###### Returns - -`Promise`\<`boolean`\> - -`true` if the sandbox is running, `false` otherwise. - -###### Example - -```ts -const sandbox = await Sandbox.create() -await sandbox.isRunning() // Returns true - -await sandbox.kill() -await sandbox.isRunning() // Returns false -``` - -### kill() - -```ts -kill(opts?: Pick): Promise -``` - -Kill the sandbox. - -###### Parameters - -| Parameter | Type | Description | -| ------ | ------ | ------ | -| `opts`? | `Pick`\<`SandboxOpts`, `"requestTimeoutMs"`\> | connection options. | - -###### Returns - -`Promise`\<`void`\> - -### setTimeout() - -```ts -setTimeout(timeoutMs: number, opts?: Pick): Promise -``` - -Set the timeout of the sandbox. -After the timeout expires the sandbox will be automatically killed. - -This method can extend or reduce the sandbox timeout set when creating the sandbox or from the last call to `.setTimeout`. -Maximum time a sandbox can be kept alive is 24 hours (86_400_000 milliseconds) for Pro users and 1 hour (3_600_000 milliseconds) for Hobby users. - -###### Parameters - -| Parameter | Type | Description | -| ------ | ------ | ------ | -| `timeoutMs` | `number` | timeout in **milliseconds**. | -| `opts`? | `Pick`\<`SandboxOpts`, `"requestTimeoutMs"`\> | connection options. | - -###### Returns - -`Promise`\<`void`\> - -### uploadUrl() - -```ts -uploadUrl(path?: string, opts?: SandboxUrlOpts): Promise -``` - -Get the URL to upload a file to the sandbox. - -You have to send a POST request to this URL with the file as multipart/form-data. - -###### Parameters - -| Parameter | Type | Description | -| ------ | ------ | ------ | -| `path`? | `string` | path to the file in the sandbox. | -| `opts`? | `SandboxUrlOpts` | download url options. | - -###### Returns - -`Promise`\<`string`\> - -URL for uploading file. - -### betaCreate() - -###### betaCreate(this, opts) - -```ts -static betaCreate(this: S, opts?: SandboxBetaCreateOpts): Promise> -``` - -**`Beta`** - -This feature is in beta and may change in the future. - -Create a new sandbox from the default `base` sandbox template. - -###### Type Parameters - -| Type Parameter | -| ------ | -| `S` *extends* *typeof* `Sandbox` | - -###### Parameters - -| Parameter | Type | Description | -| ------ | ------ | ------ | -| `this` | `S` | - | -| `opts`? | `SandboxBetaCreateOpts` | connection options. | - -###### Returns - -`Promise`\<`InstanceType`\<`S`\>\> - -sandbox instance for the new sandbox. - -###### Example - -```ts -const sandbox = await Sandbox.betaCreate() -``` - -###### Constructs - -Sandbox - -###### betaCreate(this, template, opts) - -```ts -static betaCreate( - this: S, - template: string, -opts?: SandboxBetaCreateOpts): Promise> -``` - -**`Beta`** - -This feature is in beta and may change in the future. - -Create a new sandbox from the specified sandbox template. - -###### Type Parameters - -| Type Parameter | -| ------ | -| `S` *extends* *typeof* `Sandbox` | - -###### Parameters - -| Parameter | Type | Description | -| ------ | ------ | ------ | -| `this` | `S` | - | -| `template` | `string` | sandbox template name or ID. | -| `opts`? | `SandboxBetaCreateOpts` | connection options. | - -###### Returns - -`Promise`\<`InstanceType`\<`S`\>\> - -sandbox instance for the new sandbox. - -###### Example - -```ts -const sandbox = await Sandbox.betaCreate('') -``` - -###### Constructs - -Sandbox - -### betaPause() - -```ts -static betaPause(sandboxId: string, opts?: SandboxApiOpts): Promise -``` - -Pause the sandbox specified by sandbox ID. - -###### Parameters - -| Parameter | Type | Description | -| ------ | ------ | ------ | -| `sandboxId` | `string` | sandbox ID. | -| `opts`? | `SandboxApiOpts` | connection options. | - -###### Returns - -`Promise`\<`boolean`\> - -`true` if the sandbox got paused, `false` if the sandbox was already paused. - -### connect() - -```ts -static connect( - this: S, - sandboxId: string, -opts?: SandboxConnectOpts): Promise> -``` - -Connect to a sandbox. If the sandbox is paused, it will be automatically resumed. -Sandbox must be either running or be paused. - -With sandbox ID you can connect to the same sandbox from different places or environments (serverless functions, etc). - -###### Type Parameters - -| Type Parameter | -| ------ | -| `S` *extends* *typeof* `Sandbox` | - -###### Parameters - -| Parameter | Type | Description | -| ------ | ------ | ------ | -| `this` | `S` | - | -| `sandboxId` | `string` | sandbox ID. | -| `opts`? | `SandboxConnectOpts` | connection options. | - -###### Returns - -`Promise`\<`InstanceType`\<`S`\>\> - -A running sandbox instance - -###### Example - -```ts -const sandbox = await Sandbox.create() -const sandboxId = sandbox.sandboxId - -// Connect to the same sandbox. -const sameSandbox = await Sandbox.connect(sandboxId) -``` - -### create() - -###### create(this, opts) - -```ts -static create(this: S, opts?: SandboxOpts): Promise> -``` - -Create a new sandbox from the default `base` sandbox template. - -###### Type Parameters - -| Type Parameter | -| ------ | -| `S` *extends* *typeof* `Sandbox` | - -###### Parameters - -| Parameter | Type | Description | -| ------ | ------ | ------ | -| `this` | `S` | - | -| `opts`? | `SandboxOpts` | connection options. | - -###### Returns - -`Promise`\<`InstanceType`\<`S`\>\> - -sandbox instance for the new sandbox. - -###### Example - -```ts -const sandbox = await Sandbox.create() -``` - -###### Constructs - -Sandbox - -###### create(this, template, opts) - -```ts -static create( - this: S, - template: string, -opts?: SandboxOpts): Promise> -``` - -Create a new sandbox from the specified sandbox template. - -###### Type Parameters - -| Type Parameter | -| ------ | -| `S` *extends* *typeof* `Sandbox` | - -###### Parameters - -| Parameter | Type | Description | -| ------ | ------ | ------ | -| `this` | `S` | - | -| `template` | `string` | sandbox template name or ID. | -| `opts`? | `SandboxOpts` | connection options. | - -###### Returns - -`Promise`\<`InstanceType`\<`S`\>\> - -sandbox instance for the new sandbox. - -###### Example - -```ts -const sandbox = await Sandbox.create('') -``` - -###### Constructs - -Sandbox - -### getFullInfo() - -```ts -static getFullInfo(sandboxId: string, opts?: SandboxApiOpts): Promise -``` - -###### Parameters - -| Parameter | Type | -| ------ | ------ | -| `sandboxId` | `string` | -| `opts`? | `SandboxApiOpts` | - -###### Returns - -`Promise`\<`object`\> - -| Name | Type | Default value | -| ------ | ------ | ------ | -| `cpuCount` | `number` | res.data.cpuCount | -| `endAt` | `Date` | - | -| `envdAccessToken` | `undefined` \| `string` | res.data.envdAccessToken | -| `envdVersion` | `string` | res.data.envdVersion | -| `memoryMB` | `number` | res.data.memoryMB | -| `metadata` | `object` | - | -| `name`? | `string` | res.data.alias | -| `sandboxDomain` | `undefined` \| `string` | - | -| `sandboxId` | `string` | res.data.sandboxID | -| `startedAt` | `Date` | - | -| `state` | `"running"` \| `"paused"` | res.data.state | -| `templateId` | `string` | res.data.templateID | - -### getInfo() - -```ts -static getInfo(sandboxId: string, opts?: SandboxApiOpts): Promise -``` - -Get sandbox information like sandbox ID, template, metadata, started at/end at date. - -###### Parameters - -| Parameter | Type | Description | -| ------ | ------ | ------ | -| `sandboxId` | `string` | sandbox ID. | -| `opts`? | `SandboxApiOpts` | connection options. | - -###### Returns - -`Promise`\<`SandboxInfo`\> - -sandbox information. - -### getMetrics() - -```ts -static getMetrics(sandboxId: string, opts?: SandboxMetricsOpts): Promise -``` - -Get the metrics of the sandbox. - -###### Parameters - -| Parameter | Type | Description | -| ------ | ------ | ------ | -| `sandboxId` | `string` | sandbox ID. | -| `opts`? | `SandboxMetricsOpts` | sandbox metrics options. | - -###### Returns - -`Promise`\<`SandboxMetrics`[]\> - -List of sandbox metrics containing CPU, memory and disk usage information. - -### kill() - -```ts -static kill(sandboxId: string, opts?: SandboxApiOpts): Promise -``` - -Kill the sandbox specified by sandbox ID. - -###### Parameters - -| Parameter | Type | Description | -| ------ | ------ | ------ | -| `sandboxId` | `string` | sandbox ID. | -| `opts`? | `SandboxApiOpts` | connection options. | - -###### Returns - -`Promise`\<`boolean`\> - -`true` if the sandbox was found and killed, `false` otherwise. - -### list() - -```ts -static list(opts?: SandboxListOpts): SandboxPaginator -``` - -List all sandboxes. - -###### Parameters - -| Parameter | Type | Description | -| ------ | ------ | ------ | -| `opts`? | `SandboxListOpts` | connection options. | - -###### Returns - -`SandboxPaginator` - -paginator for listing sandboxes. - -### setTimeout() - -```ts -static setTimeout( - sandboxId: string, - timeoutMs: number, -opts?: SandboxApiOpts): Promise -``` - -Set the timeout of the specified sandbox. -After the timeout expires the sandbox will be automatically killed. - -This method can extend or reduce the sandbox timeout set when creating the sandbox or from the last call to Sandbox.setTimeout. - -Maximum time a sandbox can be kept alive is 24 hours (86_400_000 milliseconds) for Pro users and 1 hour (3_600_000 milliseconds) for Hobby users. - -###### Parameters - -| Parameter | Type | Description | -| ------ | ------ | ------ | -| `sandboxId` | `string` | sandbox ID. | -| `timeoutMs` | `number` | timeout in **milliseconds**. | -| `opts`? | `SandboxApiOpts` | connection options. | - -###### Returns - -`Promise`\<`void`\> - -## Interfaces - -### SandboxUrlOpts - -Options for sandbox upload/download URL generation. - -#### Properties - -### user? - -```ts -optional user: string; -``` - -User that will be used to access the file. - -### useSignatureExpiration? - -```ts -optional useSignatureExpiration: number; -``` - -Use signature expiration for the URL. -Optional parameter to set the expiration time for the signature in seconds. diff --git a/docs/sdk-reference/js-sdk/v2.8.2/template-logger.mdx b/docs/sdk-reference/js-sdk/v2.8.2/template-logger.mdx deleted file mode 100644 index fdebde3..0000000 --- a/docs/sdk-reference/js-sdk/v2.8.2/template-logger.mdx +++ /dev/null @@ -1,196 +0,0 @@ ---- -sidebarTitle: "Logger" -mode: "center" ---- - -### LogEntry - -Represents a single log entry from the template build process. - -#### Extended by - -- `LogEntryStart` -- `LogEntryEnd` - -#### Constructors - -```ts -new LogEntry( - timestamp: Date, - level: LogEntryLevel, - message: string): LogEntry -``` - -###### Parameters - -| Parameter | Type | -| ------ | ------ | -| `timestamp` | `Date` | -| `level` | `LogEntryLevel` | -| `message` | `string` | - -###### Returns - -`LogEntry` - -#### Properties - -| Property | Modifier | Type | -| ------ | ------ | ------ | -| `level` | `readonly` | `LogEntryLevel` | -| `message` | `readonly` | `string` | -| `timestamp` | `readonly` | `Date` | - -#### Methods - -### toString() - -```ts -toString(): string -``` - -###### Returns - -`string` - -*** - -### LogEntryEnd - -Special log entry indicating the end of a build process. - -#### Constructors - -```ts -new LogEntryEnd(timestamp: Date, message: string): LogEntryEnd -``` - -###### Parameters - -| Parameter | Type | -| ------ | ------ | -| `timestamp` | `Date` | -| `message` | `string` | - -###### Returns - -`LogEntryEnd` - -#### Properties - -| Property | Modifier | Type | Inherited from | -| ------ | ------ | ------ | ------ | -| `level` | `readonly` | `LogEntryLevel` | `LogEntry`.`level` | -| `message` | `readonly` | `string` | `LogEntry`.`message` | -| `timestamp` | `readonly` | `Date` | `LogEntry`.`timestamp` | - -#### Methods - -### toString() - -```ts -toString(): string -``` - -###### Returns - -`string` - -*** - -### LogEntryStart - -Special log entry indicating the start of a build process. - -#### Constructors - -```ts -new LogEntryStart(timestamp: Date, message: string): LogEntryStart -``` - -###### Parameters - -| Parameter | Type | -| ------ | ------ | -| `timestamp` | `Date` | -| `message` | `string` | - -###### Returns - -`LogEntryStart` - -#### Properties - -| Property | Modifier | Type | Inherited from | -| ------ | ------ | ------ | ------ | -| `level` | `readonly` | `LogEntryLevel` | `LogEntry`.`level` | -| `message` | `readonly` | `string` | `LogEntry`.`message` | -| `timestamp` | `readonly` | `Date` | `LogEntry`.`timestamp` | - -#### Methods - -### toString() - -```ts -toString(): string -``` - -###### Returns - -`string` - -## Type Aliases - -### LogEntryLevel - -```ts -type LogEntryLevel: "debug" | "info" | "warn" | "error"; -``` - -Log entry severity levels. - -## Functions - -### defaultBuildLogger() - -```ts -function defaultBuildLogger(options?: object): (logEntry: LogEntry) => void -``` - -Create a default build logger with animated timer display. - -#### Parameters - -| Parameter | Type | Description | -| ------ | ------ | ------ | -| `options`? | `object` | Logger configuration options | -| `options.minLevel`? | `LogEntryLevel` | Minimum log level to display (default: 'info') | - -#### Returns - -`Function` - -Logger function that accepts LogEntry instances - -### Parameters - -| Parameter | Type | -| ------ | ------ | -| `logEntry` | `LogEntry` | - -### Returns - -`void` - -#### Example - -```ts -import { Template, defaultBuildLogger } from 'e2b' - -const template = Template().fromPythonImage() - -await Template.build(template, { - alias: 'my-template', - onBuildLogs: defaultBuildLogger({ minLevel: 'debug' }) -}) -``` diff --git a/docs/sdk-reference/js-sdk/v2.8.2/template-readycmd.mdx b/docs/sdk-reference/js-sdk/v2.8.2/template-readycmd.mdx deleted file mode 100644 index 56fb0b7..0000000 --- a/docs/sdk-reference/js-sdk/v2.8.2/template-readycmd.mdx +++ /dev/null @@ -1,202 +0,0 @@ ---- -sidebarTitle: "Readycmd" -mode: "center" ---- - -### ReadyCmd - -Class for ready check commands. - -#### Constructors - -```ts -new ReadyCmd(cmd: string): ReadyCmd -``` - -###### Parameters - -| Parameter | Type | -| ------ | ------ | -| `cmd` | `string` | - -###### Returns - -`ReadyCmd` - -#### Methods - -### getCmd() - -```ts -getCmd(): string -``` - -###### Returns - -`string` - -## Functions - -### waitForFile() - -```ts -function waitForFile(filename: string): ReadyCmd -``` - -Wait for a file to exist. -Uses shell test command to check file existence. - -#### Parameters - -| Parameter | Type | Description | -| ------ | ------ | ------ | -| `filename` | `string` | Path to the file to wait for | - -#### Returns - -`ReadyCmd` - -ReadyCmd that checks for the file - -#### Example - -```ts -import { Template, waitForFile } from 'e2b' - -const template = Template() - .fromBaseImage() - .setStartCmd('./init.sh', waitForFile('/tmp/ready')) -``` - -*** - -### waitForPort() - -```ts -function waitForPort(port: number): ReadyCmd -``` - -Wait for a port to be listening. -Uses `ss` command to check if a port is open and listening. - -#### Parameters - -| Parameter | Type | Description | -| ------ | ------ | ------ | -| `port` | `number` | Port number to wait for | - -#### Returns - -`ReadyCmd` - -ReadyCmd that checks for the port - -#### Example - -```ts -import { Template, waitForPort } from 'e2b' - -const template = Template() - .fromPythonImage() - .setStartCmd('python -m http.server 8000', waitForPort(8000)) -``` - -*** - -### waitForProcess() - -```ts -function waitForProcess(processName: string): ReadyCmd -``` - -Wait for a process with a specific name to be running. -Uses `pgrep` to check if a process exists. - -#### Parameters - -| Parameter | Type | Description | -| ------ | ------ | ------ | -| `processName` | `string` | Name of the process to wait for | - -#### Returns - -`ReadyCmd` - -ReadyCmd that checks for the process - -#### Example - -```ts -import { Template, waitForProcess } from 'e2b' - -const template = Template() - .fromBaseImage() - .setStartCmd('./my-daemon', waitForProcess('my-daemon')) -``` - -*** - -### waitForTimeout() - -```ts -function waitForTimeout(timeout: number): ReadyCmd -``` - -Wait for a specified timeout before considering the sandbox ready. -Uses `sleep` command to wait for a fixed duration. - -#### Parameters - -| Parameter | Type | Description | -| ------ | ------ | ------ | -| `timeout` | `number` | Time to wait in milliseconds (minimum: 1000ms / 1 second) | - -#### Returns - -`ReadyCmd` - -ReadyCmd that waits for the specified duration - -#### Example - -```ts -import { Template, waitForTimeout } from 'e2b' - -const template = Template() - .fromNodeImage() - .setStartCmd('npm start', waitForTimeout(5000)) // Wait 5 seconds -``` - -*** - -### waitForURL() - -```ts -function waitForURL(url: string, statusCode: number): ReadyCmd -``` - -Wait for a URL to return a specific HTTP status code. -Uses `curl` to make HTTP requests and check the response status. - -#### Parameters - -| Parameter | Type | Default value | Description | -| ------ | ------ | ------ | ------ | -| `url` | `string` | `undefined` | URL to check (e.g., 'http://localhost:3000/health') | -| `statusCode` | `number` | `200` | Expected HTTP status code (default: 200) | - -#### Returns - -`ReadyCmd` - -ReadyCmd that checks the URL - -#### Example - -```ts -import { Template, waitForURL } from 'e2b' - -const template = Template() - .fromNodeImage() - .setStartCmd('npm start', waitForURL('http://localhost:3000/health')) -``` diff --git a/docs/sdk-reference/js-sdk/v2.8.2/template.mdx b/docs/sdk-reference/js-sdk/v2.8.2/template.mdx deleted file mode 100644 index c644e02..0000000 --- a/docs/sdk-reference/js-sdk/v2.8.2/template.mdx +++ /dev/null @@ -1,2042 +0,0 @@ ---- -sidebarTitle: "Template" -mode: "center" ---- - -### TemplateBase - -Base class for building E2B sandbox templates. - -#### Implements - -- `TemplateFromImage` -- `TemplateBuilder` -- `TemplateFinal` - -#### Constructors - -```ts -new TemplateBase(options?: TemplateOptions): TemplateBase -``` - -###### Parameters - -| Parameter | Type | -| ------ | ------ | -| `options`? | `TemplateOptions` | - -###### Returns - -`TemplateBase` - -#### Methods - -### addMcpServer() - -```ts -addMcpServer(servers: keyof McpServer | keyof McpServer[]): TemplateBuilder -``` - -Install MCP servers using mcp-gateway. -Note: Requires a base image with mcp-gateway pre-installed (e.g., mcp-gateway). - -###### Parameters - -| Parameter | Type | Description | -| ------ | ------ | ------ | -| `servers` | keyof McpServer \| keyof McpServer[] | MCP server name(s) | - -###### Returns - -`TemplateBuilder` - -###### Throws - -If the base template is not mcp-gateway - -###### Example - -```ts -template.addMcpServer('exa') -template.addMcpServer(['brave', 'firecrawl', 'duckduckgo']) -``` - -###### Implementation of - -`TemplateBuilder`.`addMcpServer` - -### aptInstall() - -```ts -aptInstall(packages: string | string[], options?: object): TemplateBuilder -``` - -Install Debian/Ubuntu packages using apt-get. - -###### Parameters - -| Parameter | Type | Description | -| ------ | ------ | ------ | -| `packages` | `string` \| `string`[] | Package name(s) | -| `options`? | `object` | - | -| `options.noInstallRecommends`? | `boolean` | - | - -###### Returns - -`TemplateBuilder` - -###### Example - -```ts -template.aptInstall('vim') -template.aptInstall(['git', 'curl', 'wget']) -template.aptInstall(['vim'], { noInstallRecommends: true }) -``` - -###### Implementation of - -`TemplateBuilder`.`aptInstall` - -### betaDevContainerPrebuild() - -```ts -betaDevContainerPrebuild(devcontainerDirectory: string): TemplateBuilder -``` - -Prebuild a devcontainer from the specified directory. - -###### Parameters - -| Parameter | Type | Description | -| ------ | ------ | ------ | -| `devcontainerDirectory` | `string` | Path to the devcontainer directory | - -###### Returns - -`TemplateBuilder` - -###### Example - -```ts -template - .gitClone('https://myrepo.com/project.git', '/my-devcontainer') - .betaDevContainerPrebuild('/my-devcontainer') -``` - -###### Implementation of - -`TemplateBuilder`.`betaDevContainerPrebuild` - -### betaSetDevContainerStart() - -```ts -betaSetDevContainerStart(devcontainerDirectory: string): TemplateFinal -``` - -Start a devcontainer from the specified directory. - -###### Parameters - -| Parameter | Type | Description | -| ------ | ------ | ------ | -| `devcontainerDirectory` | `string` | Path to the devcontainer directory | - -###### Returns - -`TemplateFinal` - -###### Example - -```ts -template - .gitClone('https://myrepo.com/project.git', '/my-devcontainer') - .startDevcontainer('/my-devcontainer') - -// Prebuild and start -template - .gitClone('https://myrepo.com/project.git', '/my-devcontainer') - .betaDevContainerPrebuild('/my-devcontainer') - // Other instructions... - .betaSetDevContainerStart('/my-devcontainer') -``` - -###### Implementation of - -`TemplateBuilder`.`betaSetDevContainerStart` - -### bunInstall() - -```ts -bunInstall(packages?: string | string[], options?: object): TemplateBuilder -``` - -Install Bun packages using bun. - -###### Parameters - -| Parameter | Type | Description | -| ------ | ------ | ------ | -| `packages`? | `string` \| `string`[] | Package name(s) or undefined for package.json | -| `options`? | `object` | Install options | -| `options.dev`? | `boolean` | - | -| `options.g`? | `boolean` | - | - -###### Returns - -`TemplateBuilder` - -###### Example - -```ts -template.bunInstall('express') -template.bunInstall(['lodash', 'axios']) -template.bunInstall('tsx', { g: true }) -template.bunInstall('typescript', { dev: true }) -template.bunInstall() // Installs from package.json -``` - -###### Implementation of - -`TemplateBuilder`.`bunInstall` - -### copy() - -```ts -copy( - src: PathLike | PathLike[], - dest: PathLike, - options?: object): TemplateBuilder -``` - -Copy files or directories into the template. - -###### Parameters - -| Parameter | Type | Description | -| ------ | ------ | ------ | -| `src` | `PathLike` \| `PathLike`[] | Source path(s) | -| `dest` | `PathLike` | Destination path | -| `options`? | `object` | Copy options | -| `options.forceUpload`? | `true` | - | -| `options.mode`? | `number` | - | -| `options.resolveSymlinks`? | `boolean` | - | -| `options.user`? | `string` | - | - -###### Returns - -`TemplateBuilder` - -###### Example - -```ts -template.copy('requirements.txt', '/home/user/') -template.copy(['app.ts', 'config.ts'], '/app/', { mode: 0o755 }) -``` - -###### Implementation of - -`TemplateBuilder`.`copy` - -### copyItems() - -```ts -copyItems(items: CopyItem[]): TemplateBuilder -``` - -Copy multiple items with individual options. - -###### Parameters - -| Parameter | Type | Description | -| ------ | ------ | ------ | -| `items` | `CopyItem`[] | Array of copy items | - -###### Returns - -`TemplateBuilder` - -###### Example - -```ts -template.copyItems([ - { src: 'app.ts', dest: '/app/' }, - { src: 'config.ts', dest: '/app/', mode: 0o644 } -]) -``` - -###### Implementation of - -`TemplateBuilder`.`copyItems` - -### fromAWSRegistry() - -```ts -fromAWSRegistry(image: string, credentials: object): TemplateBuilder -``` - -Start from a Docker image in AWS ECR. - -###### Parameters - -| Parameter | Type | Description | -| ------ | ------ | ------ | -| `image` | `string` | Full ECR image path | -| `credentials` | `object` | AWS credentials | -| `credentials.accessKeyId` | `string` | - | -| `credentials.region` | `string` | - | -| `credentials.secretAccessKey` | `string` | - | - -###### Returns - -`TemplateBuilder` - -###### Example - -```ts -Template().fromAWSRegistry( - '123456789.dkr.ecr.us-west-2.amazonaws.com/myimage:latest', - { - accessKeyId: 'AKIA...', - secretAccessKey: '...', - region: 'us-west-2' - } -) -``` - -###### Implementation of - -`TemplateFromImage.fromAWSRegistry` - -### fromBaseImage() - -```ts -fromBaseImage(): TemplateBuilder -``` - -Start from E2B's default base image (e2bdev/base:latest). - -###### Returns - -`TemplateBuilder` - -###### Example - -```ts -Template().fromBaseImage() -``` - -###### Implementation of - -`TemplateFromImage.fromBaseImage` - -### fromBunImage() - -```ts -fromBunImage(variant: string): TemplateBuilder -``` - -Start from a Bun-based Docker image. - -###### Parameters - -| Parameter | Type | Default value | Description | -| ------ | ------ | ------ | ------ | -| `variant` | `string` | `'latest'` | Bun variant (default: 'latest') | - -###### Returns - -`TemplateBuilder` - -###### Example - -```ts -Template().fromBunImage('1.3') -``` - -###### Implementation of - -`TemplateFromImage.fromBunImage` - -### fromDebianImage() - -```ts -fromDebianImage(variant: string): TemplateBuilder -``` - -Start from a Debian-based Docker image. - -###### Parameters - -| Parameter | Type | Default value | Description | -| ------ | ------ | ------ | ------ | -| `variant` | `string` | `'stable'` | Debian variant (default: 'stable') | - -###### Returns - -`TemplateBuilder` - -###### Example - -```ts -Template().fromDebianImage('bookworm') -``` - -###### Implementation of - -`TemplateFromImage.fromDebianImage` - -### fromDockerfile() - -```ts -fromDockerfile(dockerfileContentOrPath: string): TemplateBuilder -``` - -Parse a Dockerfile and convert it to Template SDK format. - -###### Parameters - -| Parameter | Type | Description | -| ------ | ------ | ------ | -| `dockerfileContentOrPath` | `string` | Dockerfile content or path | - -###### Returns - -`TemplateBuilder` - -###### Example - -```ts -Template().fromDockerfile('Dockerfile') -Template().fromDockerfile('FROM python:3\nRUN pip install numpy') -``` - -###### Implementation of - -`TemplateFromImage.fromDockerfile` - -### fromGCPRegistry() - -```ts -fromGCPRegistry(image: string, credentials: object): TemplateBuilder -``` - -Start from a Docker image in Google Container Registry. - -###### Parameters - -| Parameter | Type | Description | -| ------ | ------ | ------ | -| `image` | `string` | Full GCR/GAR image path | -| `credentials` | `object` | GCP service account credentials | -| `credentials.serviceAccountJSON` | `string` \| `object` | - | - -###### Returns - -`TemplateBuilder` - -###### Example - -```ts -Template().fromGCPRegistry( - 'gcr.io/myproject/myimage:latest', - { serviceAccountJSON: 'path/to/service-account.json' } -) -``` - -###### Implementation of - -`TemplateFromImage.fromGCPRegistry` - -### fromImage() - -```ts -fromImage(baseImage: string, credentials?: object): TemplateBuilder -``` - -Start from a custom Docker image. - -###### Parameters - -| Parameter | Type | Description | -| ------ | ------ | ------ | -| `baseImage` | `string` | Docker image name | -| `credentials`? | `object` | Optional credentials for private registries | -| `credentials.password`? | `string` | - | -| `credentials.username`? | `string` | - | - -###### Returns - -`TemplateBuilder` - -###### Example - -```ts -Template().fromImage('python:3') - -// With credentials (optional) -Template().fromImage('myregistry.com/myimage:latest', { - username: 'user', - password: 'pass' -}) -``` - -###### Implementation of - -`TemplateFromImage.fromImage` - -### fromNodeImage() - -```ts -fromNodeImage(variant: string): TemplateBuilder -``` - -Start from a Node.js-based Docker image. - -###### Parameters - -| Parameter | Type | Default value | Description | -| ------ | ------ | ------ | ------ | -| `variant` | `string` | `'lts'` | Node.js variant (default: 'lts') | - -###### Returns - -`TemplateBuilder` - -###### Example - -```ts -Template().fromNodeImage('24') -``` - -###### Implementation of - -`TemplateFromImage.fromNodeImage` - -### fromPythonImage() - -```ts -fromPythonImage(version: string): TemplateBuilder -``` - -Start from a Python-based Docker image. - -###### Parameters - -| Parameter | Type | Default value | Description | -| ------ | ------ | ------ | ------ | -| `version` | `string` | `'3'` | Python version (default: '3') | - -###### Returns - -`TemplateBuilder` - -###### Example - -```ts -Template().fromPythonImage('3') -``` - -###### Implementation of - -`TemplateFromImage.fromPythonImage` - -### fromTemplate() - -```ts -fromTemplate(template: string): TemplateBuilder -``` - -Start from an existing E2B template. - -###### Parameters - -| Parameter | Type | Description | -| ------ | ------ | ------ | -| `template` | `string` | E2B template ID or alias | - -###### Returns - -`TemplateBuilder` - -###### Example - -```ts -Template().fromTemplate('my-base-template') -``` - -###### Implementation of - -`TemplateFromImage.fromTemplate` - -### fromUbuntuImage() - -```ts -fromUbuntuImage(variant: string): TemplateBuilder -``` - -Start from an Ubuntu-based Docker image. - -###### Parameters - -| Parameter | Type | Default value | Description | -| ------ | ------ | ------ | ------ | -| `variant` | `string` | `'latest'` | Ubuntu variant (default: 'latest') | - -###### Returns - -`TemplateBuilder` - -###### Example - -```ts -Template().fromUbuntuImage('24.04') -``` - -###### Implementation of - -`TemplateFromImage.fromUbuntuImage` - -### gitClone() - -```ts -gitClone( - url: string, - path?: PathLike, - options?: object): TemplateBuilder -``` - -Clone a Git repository. - -###### Parameters - -| Parameter | Type | Description | -| ------ | ------ | ------ | -| `url` | `string` | Repository URL | -| `path`? | `PathLike` | Optional destination path | -| `options`? | `object` | Clone options | -| `options.branch`? | `string` | - | -| `options.depth`? | `number` | - | -| `options.user`? | `string` | - | - -###### Returns - -`TemplateBuilder` - -###### Example - -```ts -template.gitClone('https://github.com/user/repo.git', '/app/repo') -template.gitClone('https://github.com/user/repo.git', undefined, { - branch: 'main', - depth: 1 -}) -template.gitClone('https://github.com/user/repo.git', '/app/repo', { - user: 'root' -}) -``` - -###### Implementation of - -`TemplateBuilder`.`gitClone` - -### makeDir() - -```ts -makeDir(path: PathLike | PathLike[], options?: object): TemplateBuilder -``` - -Create directories. - -###### Parameters - -| Parameter | Type | Description | -| ------ | ------ | ------ | -| `path` | `PathLike` \| `PathLike`[] | Directory path(s) | -| `options`? | `object` | Directory options | -| `options.mode`? | `number` | - | -| `options.user`? | `string` | - | - -###### Returns - -`TemplateBuilder` - -###### Example - -```ts -template.makeDir('/app/data', { mode: 0o755 }) -template.makeDir(['/app/logs', '/app/cache']) -template.makeDir('/app/data', { mode: 0o755, user: 'root' }) -``` - -###### Implementation of - -`TemplateBuilder`.`makeDir` - -### makeSymlink() - -```ts -makeSymlink( - src: PathLike, - dest: PathLike, - options?: object): TemplateBuilder -``` - -Create a symbolic link. - -###### Parameters - -| Parameter | Type | Description | -| ------ | ------ | ------ | -| `src` | `PathLike` | Source path (target) | -| `dest` | `PathLike` | Destination path (symlink location) | -| `options`? | `object` | Symlink options | -| `options.force`? | `boolean` | - | -| `options.user`? | `string` | - | - -###### Returns - -`TemplateBuilder` - -###### Example - -```ts -template.makeSymlink('/usr/bin/python3', '/usr/bin/python') -template.makeSymlink('/usr/bin/python3', '/usr/bin/python', { user: 'root' }) -template.makeSymlink('/usr/bin/python3', '/usr/bin/python', { force: true }) -``` - -###### Implementation of - -`TemplateBuilder`.`makeSymlink` - -### npmInstall() - -```ts -npmInstall(packages?: string | string[], options?: object): TemplateBuilder -``` - -Install Node.js packages using npm. - -###### Parameters - -| Parameter | Type | Description | -| ------ | ------ | ------ | -| `packages`? | `string` \| `string`[] | Package name(s) or undefined for package.json | -| `options`? | `object` | Install options | -| `options.dev`? | `boolean` | - | -| `options.g`? | `boolean` | - | - -###### Returns - -`TemplateBuilder` - -###### Example - -```ts -template.npmInstall('express') -template.npmInstall(['lodash', 'axios']) -template.npmInstall('tsx', { g: true }) -template.npmInstall('typescript', { dev: true }) -template.npmInstall() // Installs from package.json -``` - -###### Implementation of - -`TemplateBuilder`.`npmInstall` - -### pipInstall() - -```ts -pipInstall(packages?: string | string[], options?: object): TemplateBuilder -``` - -Install Python packages using pip. - -###### Parameters - -| Parameter | Type | Description | -| ------ | ------ | ------ | -| `packages`? | `string` \| `string`[] | Package name(s) or undefined for current directory | -| `options`? | `object` | Install options | -| `options.g`? | `boolean` | Install globally as root (default: true). Set to false for user-only installation with --user flag | - -###### Returns - -`TemplateBuilder` - -###### Example - -```ts -template.pipInstall('numpy') // Installs globally (default) -template.pipInstall(['pandas', 'scikit-learn']) -template.pipInstall('numpy', { g: false }) // Install for user only -template.pipInstall() // Installs from current directory -``` - -###### Implementation of - -`TemplateBuilder`.`pipInstall` - -### remove() - -```ts -remove(path: PathLike | PathLike[], options?: object): TemplateBuilder -``` - -Remove files or directories. - -###### Parameters - -| Parameter | Type | Description | -| ------ | ------ | ------ | -| `path` | `PathLike` \| `PathLike`[] | Path(s) to remove | -| `options`? | `object` | Remove options | -| `options.force`? | `boolean` | - | -| `options.recursive`? | `boolean` | - | -| `options.user`? | `string` | - | - -###### Returns - -`TemplateBuilder` - -###### Example - -```ts -template.remove('/tmp/cache', { recursive: true, force: true }) -template.remove('/tmp/cache', { recursive: true, force: true, user: 'root' }) -``` - -###### Implementation of - -`TemplateBuilder`.`remove` - -### rename() - -```ts -rename( - src: PathLike, - dest: PathLike, - options?: object): TemplateBuilder -``` - -Rename or move a file or directory. - -###### Parameters - -| Parameter | Type | Description | -| ------ | ------ | ------ | -| `src` | `PathLike` | Source path | -| `dest` | `PathLike` | Destination path | -| `options`? | `object` | Rename options | -| `options.force`? | `boolean` | - | -| `options.user`? | `string` | - | - -###### Returns - -`TemplateBuilder` - -###### Example - -```ts -template.rename('/tmp/old.txt', '/tmp/new.txt') -template.rename('/tmp/old.txt', '/tmp/new.txt', { user: 'root' }) -``` - -###### Implementation of - -`TemplateBuilder`.`rename` - -### runCmd() - -###### runCmd(command, options) - -```ts -runCmd(command: string, options?: object): TemplateBuilder -``` - -Run a shell command. - -###### Parameters - -| Parameter | Type | Description | -| ------ | ------ | ------ | -| `command` | `string` | Command string | -| `options`? | `object` | Command options | -| `options.user`? | `string` | - | - -###### Returns - -`TemplateBuilder` - -###### Example - -```ts -template.runCmd('apt-get update') -template.runCmd(['pip install numpy', 'pip install pandas']) -template.runCmd('apt-get install vim', { user: 'root' }) -``` - -###### Implementation of - -`TemplateBuilder`.`runCmd` - -###### runCmd(commands, options) - -```ts -runCmd(commands: string[], options?: object): TemplateBuilder -``` - -Run a shell command. - -###### Parameters - -| Parameter | Type | Description | -| ------ | ------ | ------ | -| `commands` | `string`[] | - | -| `options`? | `object` | Command options | -| `options.user`? | `string` | - | - -###### Returns - -`TemplateBuilder` - -###### Example - -```ts -template.runCmd('apt-get update') -template.runCmd(['pip install numpy', 'pip install pandas']) -template.runCmd('apt-get install vim', { user: 'root' }) -``` - -###### Implementation of - -`TemplateBuilder`.`runCmd` - -### setEnvs() - -```ts -setEnvs(envs: Record): TemplateBuilder -``` - -Set environment variables. - -###### Parameters - -| Parameter | Type | Description | -| ------ | ------ | ------ | -| `envs` | `Record`\<`string`, `string`\> | Environment variables | - -###### Returns - -`TemplateBuilder` - -###### Example - -```ts -template.setEnvs({ NODE_ENV: 'production', PORT: '8080' }) -``` - -###### Implementation of - -`TemplateBuilder`.`setEnvs` - -### setReadyCmd() - -```ts -setReadyCmd(readyCommand: string | ReadyCmd): TemplateFinal -``` - -Set or update the ready check command. - -###### Parameters - -| Parameter | Type | Description | -| ------ | ------ | ------ | -| `readyCommand` | `string` \| `ReadyCmd` | Command to check readiness | - -###### Returns - -`TemplateFinal` - -###### Example - -```ts -// Using a string command -template.setReadyCmd('curl http://localhost:8000/health') - -// Using ReadyCmd helpers -import { waitForPort, waitForFile, waitForProcess } from 'e2b' - -template.setReadyCmd(waitForPort(3000)) - -template.setReadyCmd(waitForFile('/tmp/ready')) - -template.setReadyCmd(waitForProcess('nginx')) -``` - -###### Implementation of - -`TemplateBuilder`.`setReadyCmd` - -### setStartCmd() - -```ts -setStartCmd(startCommand: string, readyCommand: string | ReadyCmd): TemplateFinal -``` - -Set the start command and ready check. - -###### Parameters - -| Parameter | Type | Description | -| ------ | ------ | ------ | -| `startCommand` | `string` | Command to run on startup | -| `readyCommand` | `string` \| `ReadyCmd` | Command to check readiness | - -###### Returns - -`TemplateFinal` - -###### Example - -```ts -// Using a string command -template.setStartCmd( - 'node app.js', - 'curl http://localhost:8000/health' -) - -// Using ReadyCmd helpers -import { waitForPort, waitForURL } from 'e2b' - -template.setStartCmd( - 'python -m http.server 8000', - waitForPort(8000) -) - -template.setStartCmd( - 'npm start', - waitForURL('http://localhost:3000/health', 200) -) -``` - -###### Implementation of - -`TemplateBuilder`.`setStartCmd` - -### setUser() - -```ts -setUser(user: string): TemplateBuilder -``` - -Set the user for subsequent commands. - -###### Parameters - -| Parameter | Type | Description | -| ------ | ------ | ------ | -| `user` | `string` | Username | - -###### Returns - -`TemplateBuilder` - -###### Example - -```ts -template.setUser('root') -``` - -###### Implementation of - -`TemplateBuilder`.`setUser` - -### setWorkdir() - -```ts -setWorkdir(workdir: PathLike): TemplateBuilder -``` - -Set the working directory. - -###### Parameters - -| Parameter | Type | Description | -| ------ | ------ | ------ | -| `workdir` | `PathLike` | Working directory path | - -###### Returns - -`TemplateBuilder` - -###### Example - -```ts -template.setWorkdir('/app') -``` - -###### Implementation of - -`TemplateBuilder`.`setWorkdir` - -### skipCache() - -```ts -skipCache(): this -``` - -Skip cache for all subsequent build instructions from this point. - -###### Returns - -`this` - -###### Example - -```ts -Template().skipCache().fromPythonImage('3') -``` - -###### Implementation of - -`TemplateBuilder`.`skipCache` - -### build() - -```ts -static build(template: TemplateClass, options: BuildOptions): Promise -``` - -Build and deploy a template to E2B infrastructure. - -###### Parameters - -| Parameter | Type | Description | -| ------ | ------ | ------ | -| `template` | `TemplateClass` | The template to build | -| `options` | `BuildOptions` | Build configuration options | - -###### Returns - -`Promise`\<`BuildInfo`\> - -###### Example - -```ts -const template = Template().fromPythonImage('3') -await Template.build(template, { - alias: 'my-python-env', - cpuCount: 2, - memoryMB: 1024 -}) -``` - -### buildInBackground() - -```ts -static buildInBackground(template: TemplateClass, options: BuildOptions): Promise -``` - -Build and deploy a template to E2B infrastructure. - -###### Parameters - -| Parameter | Type | Description | -| ------ | ------ | ------ | -| `template` | `TemplateClass` | The template to build | -| `options` | `BuildOptions` | Build configuration options | - -###### Returns - -`Promise`\<`BuildInfo`\> - -###### Example - -```ts -const template = Template().fromPythonImage('3') -const data = await Template.buildInBackground(template, { - alias: 'my-python-env', - cpuCount: 2, - memoryMB: 1024 -}) -``` - -### getBuildStatus() - -```ts -static getBuildStatus(data: Pick, options?: GetBuildStatusOptions): Promise -``` - -Get the status of a build. - -###### Parameters - -| Parameter | Type | Description | -| ------ | ------ | ------ | -| `data` | `Pick`\<`BuildInfo`, `"templateId"` \| `"buildId"`\> | Build identifiers | -| `options`? | `GetBuildStatusOptions` | Authentication options | - -###### Returns - -`Promise`\<`object`\> - -| Name | Type | Description | -| ------ | ------ | ------ | -| `buildID` | `string` | **Description** Identifier of the build | -| `logEntries` | `object`[] | **Description** Build logs structured **Default** `[]` | -| `logs` | `string`[] | **Description** Build logs **Default** `[]` | -| `reason`? | `object` | - | -| `reason.logEntries`? | `object`[] | **Description** Log entries related to the status reason **Default** `[]` | -| `reason.message` | `string` | **Description** Message with the status reason, currently reporting only for error status | -| `reason.step`? | `string` | **Description** Step that failed | -| `status` | `"error"` \| `"ready"` \| `"building"` \| `"waiting"` | - | -| `templateID` | `string` | **Description** Identifier of the template | - -###### Example - -```ts -const status = await Template.getBuildStatus(data, { logsOffset: 0 }) -``` - -### toDockerfile() - -```ts -static toDockerfile(template: TemplateClass): string -``` - -Convert a template to Dockerfile format. -Note: Templates based on other E2B templates cannot be converted to Dockerfile. - -###### Parameters - -| Parameter | Type | Description | -| ------ | ------ | ------ | -| `template` | `TemplateClass` | The template to convert | - -###### Returns - -`string` - -Dockerfile string representation - -###### Throws - -Error if the template is based on another E2B template - -### toJSON() - -```ts -static toJSON(template: TemplateClass, computeHashes: boolean): Promise -``` - -Convert a template to JSON representation. - -###### Parameters - -| Parameter | Type | Default value | Description | -| ------ | ------ | ------ | ------ | -| `template` | `TemplateClass` | `undefined` | The template to convert | -| `computeHashes` | `boolean` | `true` | Whether to compute file hashes for cache invalidation | - -###### Returns - -`Promise`\<`string`\> - -JSON string representation of the template - -## Interfaces - -### TemplateBuilder - -Main builder state for constructing templates. -Provides methods for customizing the template environment. - -#### Methods - -### addMcpServer() - -```ts -addMcpServer(servers: keyof McpServer | keyof McpServer[]): TemplateBuilder -``` - -Install MCP servers using mcp-gateway. -Note: Requires a base image with mcp-gateway pre-installed (e.g., mcp-gateway). - -###### Parameters - -| Parameter | Type | Description | -| ------ | ------ | ------ | -| `servers` | keyof McpServer \| keyof McpServer[] | MCP server name(s) | - -###### Returns - -`TemplateBuilder` - -###### Throws - -If the base template is not mcp-gateway - -###### Example - -```ts -template.addMcpServer('exa') -template.addMcpServer(['brave', 'firecrawl', 'duckduckgo']) -``` - -### aptInstall() - -```ts -aptInstall(packages: string | string[], options?: object): TemplateBuilder -``` - -Install Debian/Ubuntu packages using apt-get. - -###### Parameters - -| Parameter | Type | Description | -| ------ | ------ | ------ | -| `packages` | `string` \| `string`[] | Package name(s) | -| `options`? | `object` | - | -| `options.noInstallRecommends`? | `boolean` | - | - -###### Returns - -`TemplateBuilder` - -###### Example - -```ts -template.aptInstall('vim') -template.aptInstall(['git', 'curl', 'wget']) -template.aptInstall(['vim'], { noInstallRecommends: true }) -``` - -### betaDevContainerPrebuild() - -```ts -betaDevContainerPrebuild(devcontainerDirectory: string): TemplateBuilder -``` - -Prebuild a devcontainer from the specified directory. - -###### Parameters - -| Parameter | Type | Description | -| ------ | ------ | ------ | -| `devcontainerDirectory` | `string` | Path to the devcontainer directory | - -###### Returns - -`TemplateBuilder` - -###### Example - -```ts -template - .gitClone('https://myrepo.com/project.git', '/my-devcontainer') - .betaDevContainerPrebuild('/my-devcontainer') -``` - -### betaSetDevContainerStart() - -```ts -betaSetDevContainerStart(devcontainerDirectory: string): TemplateFinal -``` - -Start a devcontainer from the specified directory. - -###### Parameters - -| Parameter | Type | Description | -| ------ | ------ | ------ | -| `devcontainerDirectory` | `string` | Path to the devcontainer directory | - -###### Returns - -`TemplateFinal` - -###### Example - -```ts -template - .gitClone('https://myrepo.com/project.git', '/my-devcontainer') - .startDevcontainer('/my-devcontainer') - -// Prebuild and start -template - .gitClone('https://myrepo.com/project.git', '/my-devcontainer') - .betaDevContainerPrebuild('/my-devcontainer') - // Other instructions... - .betaSetDevContainerStart('/my-devcontainer') -``` - -### bunInstall() - -```ts -bunInstall(packages?: string | string[], options?: object): TemplateBuilder -``` - -Install Bun packages using bun. - -###### Parameters - -| Parameter | Type | Description | -| ------ | ------ | ------ | -| `packages`? | `string` \| `string`[] | Package name(s) or undefined for package.json | -| `options`? | `object` | Install options | -| `options.dev`? | `boolean` | - | -| `options.g`? | `boolean` | - | - -###### Returns - -`TemplateBuilder` - -###### Example - -```ts -template.bunInstall('express') -template.bunInstall(['lodash', 'axios']) -template.bunInstall('tsx', { g: true }) -template.bunInstall('typescript', { dev: true }) -template.bunInstall() // Installs from package.json -``` - -### copy() - -```ts -copy( - src: PathLike | PathLike[], - dest: PathLike, - options?: object): TemplateBuilder -``` - -Copy files or directories into the template. - -###### Parameters - -| Parameter | Type | Description | -| ------ | ------ | ------ | -| `src` | `PathLike` \| `PathLike`[] | Source path(s) | -| `dest` | `PathLike` | Destination path | -| `options`? | `object` | Copy options | -| `options.forceUpload`? | `true` | - | -| `options.mode`? | `number` | - | -| `options.resolveSymlinks`? | `boolean` | - | -| `options.user`? | `string` | - | - -###### Returns - -`TemplateBuilder` - -###### Example - -```ts -template.copy('requirements.txt', '/home/user/') -template.copy(['app.ts', 'config.ts'], '/app/', { mode: 0o755 }) -``` - -### copyItems() - -```ts -copyItems(items: CopyItem[]): TemplateBuilder -``` - -Copy multiple items with individual options. - -###### Parameters - -| Parameter | Type | Description | -| ------ | ------ | ------ | -| `items` | `CopyItem`[] | Array of copy items | - -###### Returns - -`TemplateBuilder` - -###### Example - -```ts -template.copyItems([ - { src: 'app.ts', dest: '/app/' }, - { src: 'config.ts', dest: '/app/', mode: 0o644 } -]) -``` - -### gitClone() - -```ts -gitClone( - url: string, - path?: PathLike, - options?: object): TemplateBuilder -``` - -Clone a Git repository. - -###### Parameters - -| Parameter | Type | Description | -| ------ | ------ | ------ | -| `url` | `string` | Repository URL | -| `path`? | `PathLike` | Optional destination path | -| `options`? | `object` | Clone options | -| `options.branch`? | `string` | - | -| `options.depth`? | `number` | - | -| `options.user`? | `string` | - | - -###### Returns - -`TemplateBuilder` - -###### Example - -```ts -template.gitClone('https://github.com/user/repo.git', '/app/repo') -template.gitClone('https://github.com/user/repo.git', undefined, { - branch: 'main', - depth: 1 -}) -template.gitClone('https://github.com/user/repo.git', '/app/repo', { - user: 'root' -}) -``` - -### makeDir() - -```ts -makeDir(path: PathLike | PathLike[], options?: object): TemplateBuilder -``` - -Create directories. - -###### Parameters - -| Parameter | Type | Description | -| ------ | ------ | ------ | -| `path` | `PathLike` \| `PathLike`[] | Directory path(s) | -| `options`? | `object` | Directory options | -| `options.mode`? | `number` | - | -| `options.user`? | `string` | - | - -###### Returns - -`TemplateBuilder` - -###### Example - -```ts -template.makeDir('/app/data', { mode: 0o755 }) -template.makeDir(['/app/logs', '/app/cache']) -template.makeDir('/app/data', { mode: 0o755, user: 'root' }) -``` - -### makeSymlink() - -```ts -makeSymlink( - src: PathLike, - dest: PathLike, - options?: object): TemplateBuilder -``` - -Create a symbolic link. - -###### Parameters - -| Parameter | Type | Description | -| ------ | ------ | ------ | -| `src` | `PathLike` | Source path (target) | -| `dest` | `PathLike` | Destination path (symlink location) | -| `options`? | `object` | Symlink options | -| `options.force`? | `boolean` | - | -| `options.user`? | `string` | - | - -###### Returns - -`TemplateBuilder` - -###### Example - -```ts -template.makeSymlink('/usr/bin/python3', '/usr/bin/python') -template.makeSymlink('/usr/bin/python3', '/usr/bin/python', { user: 'root' }) -template.makeSymlink('/usr/bin/python3', '/usr/bin/python', { force: true }) -``` - -### npmInstall() - -```ts -npmInstall(packages?: string | string[], options?: object): TemplateBuilder -``` - -Install Node.js packages using npm. - -###### Parameters - -| Parameter | Type | Description | -| ------ | ------ | ------ | -| `packages`? | `string` \| `string`[] | Package name(s) or undefined for package.json | -| `options`? | `object` | Install options | -| `options.dev`? | `boolean` | - | -| `options.g`? | `boolean` | - | - -###### Returns - -`TemplateBuilder` - -###### Example - -```ts -template.npmInstall('express') -template.npmInstall(['lodash', 'axios']) -template.npmInstall('tsx', { g: true }) -template.npmInstall('typescript', { dev: true }) -template.npmInstall() // Installs from package.json -``` - -### pipInstall() - -```ts -pipInstall(packages?: string | string[], options?: object): TemplateBuilder -``` - -Install Python packages using pip. - -###### Parameters - -| Parameter | Type | Description | -| ------ | ------ | ------ | -| `packages`? | `string` \| `string`[] | Package name(s) or undefined for current directory | -| `options`? | `object` | Install options | -| `options.g`? | `boolean` | Install globally as root (default: true). Set to false for user-only installation with --user flag | - -###### Returns - -`TemplateBuilder` - -###### Example - -```ts -template.pipInstall('numpy') // Installs globally (default) -template.pipInstall(['pandas', 'scikit-learn']) -template.pipInstall('numpy', { g: false }) // Install for user only -template.pipInstall() // Installs from current directory -``` - -### remove() - -```ts -remove(path: PathLike | PathLike[], options?: object): TemplateBuilder -``` - -Remove files or directories. - -###### Parameters - -| Parameter | Type | Description | -| ------ | ------ | ------ | -| `path` | `PathLike` \| `PathLike`[] | Path(s) to remove | -| `options`? | `object` | Remove options | -| `options.force`? | `boolean` | - | -| `options.recursive`? | `boolean` | - | -| `options.user`? | `string` | - | - -###### Returns - -`TemplateBuilder` - -###### Example - -```ts -template.remove('/tmp/cache', { recursive: true, force: true }) -template.remove('/tmp/cache', { recursive: true, force: true, user: 'root' }) -``` - -### rename() - -```ts -rename( - src: PathLike, - dest: PathLike, - options?: object): TemplateBuilder -``` - -Rename or move a file or directory. - -###### Parameters - -| Parameter | Type | Description | -| ------ | ------ | ------ | -| `src` | `PathLike` | Source path | -| `dest` | `PathLike` | Destination path | -| `options`? | `object` | Rename options | -| `options.force`? | `boolean` | - | -| `options.user`? | `string` | - | - -###### Returns - -`TemplateBuilder` - -###### Example - -```ts -template.rename('/tmp/old.txt', '/tmp/new.txt') -template.rename('/tmp/old.txt', '/tmp/new.txt', { user: 'root' }) -``` - -### runCmd() - -###### runCmd(command, options) - -```ts -runCmd(command: string, options?: object): TemplateBuilder -``` - -Run a shell command. - -###### Parameters - -| Parameter | Type | Description | -| ------ | ------ | ------ | -| `command` | `string` | Command string | -| `options`? | `object` | Command options | -| `options.user`? | `string` | - | - -###### Returns - -`TemplateBuilder` - -###### Example - -```ts -template.runCmd('apt-get update') -template.runCmd(['pip install numpy', 'pip install pandas']) -template.runCmd('apt-get install vim', { user: 'root' }) -``` - -###### runCmd(commands, options) - -```ts -runCmd(commands: string[], options?: object): TemplateBuilder -``` - -Run multiple shell commands. - -###### Parameters - -| Parameter | Type | Description | -| ------ | ------ | ------ | -| `commands` | `string`[] | Array of command strings | -| `options`? | `object` | Command options | -| `options.user`? | `string` | - | - -###### Returns - -`TemplateBuilder` - -###### runCmd(commandOrCommands, options) - -```ts -runCmd(commandOrCommands: string | string[], options?: object): TemplateBuilder -``` - -Run command(s). - -###### Parameters - -| Parameter | Type | Description | -| ------ | ------ | ------ | -| `commandOrCommands` | `string` \| `string`[] | Command or commands | -| `options`? | `object` | Command options | -| `options.user`? | `string` | - | - -###### Returns - -`TemplateBuilder` - -### setEnvs() - -```ts -setEnvs(envs: Record): TemplateBuilder -``` - -Set environment variables. - -###### Parameters - -| Parameter | Type | Description | -| ------ | ------ | ------ | -| `envs` | `Record`\<`string`, `string`\> | Environment variables | - -###### Returns - -`TemplateBuilder` - -###### Example - -```ts -template.setEnvs({ NODE_ENV: 'production', PORT: '8080' }) -``` - -### setReadyCmd() - -```ts -setReadyCmd(readyCommand: string | ReadyCmd): TemplateFinal -``` - -Set or update the ready check command. - -###### Parameters - -| Parameter | Type | Description | -| ------ | ------ | ------ | -| `readyCommand` | `string` \| `ReadyCmd` | Command to check readiness | - -###### Returns - -`TemplateFinal` - -###### Example - -```ts -// Using a string command -template.setReadyCmd('curl http://localhost:8000/health') - -// Using ReadyCmd helpers -import { waitForPort, waitForFile, waitForProcess } from 'e2b' - -template.setReadyCmd(waitForPort(3000)) - -template.setReadyCmd(waitForFile('/tmp/ready')) - -template.setReadyCmd(waitForProcess('nginx')) -``` - -### setStartCmd() - -```ts -setStartCmd(startCommand: string, readyCommand: string | ReadyCmd): TemplateFinal -``` - -Set the start command and ready check. - -###### Parameters - -| Parameter | Type | Description | -| ------ | ------ | ------ | -| `startCommand` | `string` | Command to run on startup | -| `readyCommand` | `string` \| `ReadyCmd` | Command to check readiness | - -###### Returns - -`TemplateFinal` - -###### Example - -```ts -// Using a string command -template.setStartCmd( - 'node app.js', - 'curl http://localhost:8000/health' -) - -// Using ReadyCmd helpers -import { waitForPort, waitForURL } from 'e2b' - -template.setStartCmd( - 'python -m http.server 8000', - waitForPort(8000) -) - -template.setStartCmd( - 'npm start', - waitForURL('http://localhost:3000/health', 200) -) -``` - -### setUser() - -```ts -setUser(user: string): TemplateBuilder -``` - -Set the user for subsequent commands. - -###### Parameters - -| Parameter | Type | Description | -| ------ | ------ | ------ | -| `user` | `string` | Username | - -###### Returns - -`TemplateBuilder` - -###### Example - -```ts -template.setUser('root') -``` - -### setWorkdir() - -```ts -setWorkdir(workdir: PathLike): TemplateBuilder -``` - -Set the working directory. - -###### Parameters - -| Parameter | Type | Description | -| ------ | ------ | ------ | -| `workdir` | `PathLike` | Working directory path | - -###### Returns - -`TemplateBuilder` - -###### Example - -```ts -template.setWorkdir('/app') -``` - -### skipCache() - -```ts -skipCache(): this -``` - -Skip cache for all subsequent build instructions from this point. - -###### Returns - -`this` - -###### Example - -```ts -template.skipCache().runCmd('apt-get update') -``` - -## Type Aliases - -### BuildInfo - -```ts -type BuildInfo: object; -``` - -Information about a built template. - -#### Type declaration - -| Name | Type | -| ------ | ------ | -| `alias` | `string` | -| `buildId` | `string` | -| `templateId` | `string` | - -*** - -### BuildOptions - -```ts -type BuildOptions: AuthOptions & BasicBuildOptions; -``` - -Options for building a template with authentication. - -*** - -### CopyItem - -```ts -type CopyItem: object; -``` - -Configuration for a single file/directory copy operation. - -#### Type declaration - -| Name | Type | -| ------ | ------ | -| `dest` | `PathLike` | -| `forceUpload`? | `true` | -| `mode`? | `number` | -| `resolveSymlinks`? | `boolean` | -| `src` | `PathLike` \| `PathLike`[] | -| `user`? | `string` | - -*** - -### GetBuildStatusOptions - -```ts -type GetBuildStatusOptions: AuthOptions & object; -``` - -Response from getting build status. - -#### Type declaration - -| Name | Type | -| ------ | ------ | -| `logsOffset`? | `number` | - -*** - -### McpServerName - -```ts -type McpServerName: keyof McpServer; -``` - -MCP server names that can be installed. - -*** - -### TemplateClass - -```ts -type TemplateClass: TemplateBuilder | TemplateFinal; -``` - -Type representing a template in any state (builder or final). - -## Functions - -### Template() - -```ts -function Template(options?: TemplateOptions): TemplateFromImage -``` - -Create a new E2B template builder instance. - -#### Parameters - -| Parameter | Type | Description | -| ------ | ------ | ------ | -| `options`? | `TemplateOptions` | Optional configuration for the template builder | - -#### Returns - -`TemplateFromImage` - -A new template builder instance - -#### Example - -```ts -import { Template } from 'e2b' - -const template = Template() - .fromPythonImage('3') - .copy('requirements.txt', '/app/') - .pipInstall() - -await Template.build(template, { alias: 'my-python-app' }) -``` diff --git a/docs/sdk-reference/js-sdk/v2.8.3/errors.mdx b/docs/sdk-reference/js-sdk/v2.8.3/errors.mdx deleted file mode 100644 index bfe0deb..0000000 --- a/docs/sdk-reference/js-sdk/v2.8.3/errors.mdx +++ /dev/null @@ -1,271 +0,0 @@ ---- -sidebarTitle: "Errors" -mode: "center" ---- - -### AuthenticationError - -Thrown when authentication fails. - -#### Constructors - -```ts -new AuthenticationError(message: string): AuthenticationError -``` - -###### Parameters - -| Parameter | Type | -| ------ | ------ | -| `message` | `string` | - -###### Returns - -`AuthenticationError` - -*** - -### BuildError - -Thrown when the build fails. - -#### Extended by - -- `FileUploadError` - -#### Constructors - -```ts -new BuildError(message: string, stackTrace?: string): BuildError -``` - -###### Parameters - -| Parameter | Type | -| ------ | ------ | -| `message` | `string` | -| `stackTrace`? | `string` | - -###### Returns - -`BuildError` - -*** - -### FileUploadError - -Thrown when the file upload fails. - -#### Constructors - -```ts -new FileUploadError(message: string, stackTrace?: string): FileUploadError -``` - -###### Parameters - -| Parameter | Type | -| ------ | ------ | -| `message` | `string` | -| `stackTrace`? | `string` | - -###### Returns - -`FileUploadError` - -*** - -### InvalidArgumentError - -Thrown when an invalid argument is provided. - -#### Constructors - -```ts -new InvalidArgumentError(message: string, stackTrace?: string): InvalidArgumentError -``` - -###### Parameters - -| Parameter | Type | -| ------ | ------ | -| `message` | `string` | -| `stackTrace`? | `string` | - -###### Returns - -`InvalidArgumentError` - -*** - -### NotEnoughSpaceError - -Thrown when there is not enough disk space. - -#### Constructors - -```ts -new NotEnoughSpaceError(message: string, stackTrace?: string): NotEnoughSpaceError -``` - -###### Parameters - -| Parameter | Type | -| ------ | ------ | -| `message` | `string` | -| `stackTrace`? | `string` | - -###### Returns - -`NotEnoughSpaceError` - -*** - -### NotFoundError - -Thrown when a resource is not found. - -#### Constructors - -```ts -new NotFoundError(message: string, stackTrace?: string): NotFoundError -``` - -###### Parameters - -| Parameter | Type | -| ------ | ------ | -| `message` | `string` | -| `stackTrace`? | `string` | - -###### Returns - -`NotFoundError` - -*** - -### RateLimitError - -Thrown when the API rate limit is exceeded. - -#### Constructors - -```ts -new RateLimitError(message: string): RateLimitError -``` - -###### Parameters - -| Parameter | Type | -| ------ | ------ | -| `message` | `string` | - -###### Returns - -`RateLimitError` - -*** - -### SandboxError - -Base class for all sandbox errors. - -Thrown when general sandbox errors occur. - -#### Extended by - -- `TimeoutError` -- `InvalidArgumentError` -- `NotEnoughSpaceError` -- `NotFoundError` -- `TemplateError` -- `RateLimitError` - -#### Constructors - -```ts -new SandboxError(message?: string, stackTrace?: string): SandboxError -``` - -###### Parameters - -| Parameter | Type | -| ------ | ------ | -| `message`? | `string` | -| `stackTrace`? | `string` | - -###### Returns - -`SandboxError` - -*** - -### TemplateError - -Thrown when the template uses old envd version. It isn't compatible with the new SDK. - -#### Constructors - -```ts -new TemplateError(message: string, stackTrace?: string): TemplateError -``` - -###### Parameters - -| Parameter | Type | -| ------ | ------ | -| `message` | `string` | -| `stackTrace`? | `string` | - -###### Returns - -`TemplateError` - -*** - -### TimeoutError - -Thrown when a timeout error occurs. - -The [unavailable] error type is caused by sandbox timeout. - -The [canceled] error type is caused by exceeding request timeout. - -The [deadline_exceeded] error type is caused by exceeding the timeout for command execution, watch, etc. - -The [unknown] error type is sometimes caused by the sandbox timeout when the request is not processed correctly. - -#### Constructors - -```ts -new TimeoutError(message: string, stackTrace?: string): TimeoutError -``` - -###### Parameters - -| Parameter | Type | -| ------ | ------ | -| `message` | `string` | -| `stackTrace`? | `string` | - -###### Returns - -`TimeoutError` - -## Functions - -### formatSandboxTimeoutError() - -```ts -function formatSandboxTimeoutError(message: string): TimeoutError -``` - -#### Parameters - -| Parameter | Type | -| ------ | ------ | -| `message` | `string` | - -#### Returns - -`TimeoutError` diff --git a/docs/sdk-reference/js-sdk/v2.8.3/sandbox-commands.mdx b/docs/sdk-reference/js-sdk/v2.8.3/sandbox-commands.mdx deleted file mode 100644 index 16d736c..0000000 --- a/docs/sdk-reference/js-sdk/v2.8.3/sandbox-commands.mdx +++ /dev/null @@ -1,533 +0,0 @@ ---- -sidebarTitle: "Commands" -mode: "center" ---- - -### Commands - -Module for starting and interacting with commands in the sandbox. - -#### Constructors - -```ts -new Commands( - transport: Transport, - connectionConfig: ConnectionConfig, - metadata: object): Commands -``` - -###### Parameters - -| Parameter | Type | -| ------ | ------ | -| `transport` | `Transport` | -| `connectionConfig` | `ConnectionConfig` | -| `metadata` | `object` | -| `metadata.version` | `string` | - -###### Returns - -`Commands` - -#### Methods - -### connect() - -```ts -connect(pid: number, opts?: CommandConnectOpts): Promise -``` - -Connect to a running command. -You can use CommandHandle.wait to wait for the command to finish and get execution results. - -###### Parameters - -| Parameter | Type | Description | -| ------ | ------ | ------ | -| `pid` | `number` | process ID of the command to connect to. You can get the list of running commands using Commands.list. | -| `opts`? | `CommandConnectOpts` | connection options. | - -###### Returns - -`Promise`\<`CommandHandle`\> - -`CommandHandle` handle to interact with the running command. - -### kill() - -```ts -kill(pid: number, opts?: CommandRequestOpts): Promise -``` - -Kill a running command specified by its process ID. -It uses `SIGKILL` signal to kill the command. - -###### Parameters - -| Parameter | Type | Description | -| ------ | ------ | ------ | -| `pid` | `number` | process ID of the command. You can get the list of running commands using Commands.list. | -| `opts`? | `CommandRequestOpts` | connection options. | - -###### Returns - -`Promise`\<`boolean`\> - -`true` if the command was killed, `false` if the command was not found. - -### list() - -```ts -list(opts?: CommandRequestOpts): Promise -``` - -List all running commands and PTY sessions. - -###### Parameters - -| Parameter | Type | Description | -| ------ | ------ | ------ | -| `opts`? | `CommandRequestOpts` | connection options. | - -###### Returns - -`Promise`\<`ProcessInfo`[]\> - -list of running commands and PTY sessions. - -### run() - -###### run(cmd, opts) - -```ts -run(cmd: string, opts?: CommandStartOpts & object): Promise -``` - -Start a new command and wait until it finishes executing. - -###### Parameters - -| Parameter | Type | Description | -| ------ | ------ | ------ | -| `cmd` | `string` | command to execute. | -| `opts`? | `CommandStartOpts` & `object` | options for starting the command. | - -###### Returns - -`Promise`\<`CommandResult`\> - -`CommandResult` result of the command execution. - -###### run(cmd, opts) - -```ts -run(cmd: string, opts: CommandStartOpts & object): Promise -``` - -Start a new command in the background. -You can use CommandHandle.wait to wait for the command to finish and get its result. - -###### Parameters - -| Parameter | Type | Description | -| ------ | ------ | ------ | -| `cmd` | `string` | command to execute. | -| `opts` | `CommandStartOpts` & `object` | options for starting the command | - -###### Returns - -`Promise`\<`CommandHandle`\> - -`CommandHandle` handle to interact with the running command. - -###### run(cmd, opts) - -```ts -run(cmd: string, opts?: CommandStartOpts & object): Promise -``` - -Start a new command. - -###### Parameters - -| Parameter | Type | Description | -| ------ | ------ | ------ | -| `cmd` | `string` | command to execute. | -| `opts`? | `CommandStartOpts` & `object` | options for starting the command. - `opts.background: true` - runs in background, returns `CommandHandle` - `opts.background: false | undefined` - waits for completion, returns `CommandResult` | - -###### Returns - -`Promise`\<`CommandResult` \| `CommandHandle`\> - -Either a `CommandHandle` or a `CommandResult` (depending on `opts.background`). - -### sendStdin() - -```ts -sendStdin( - pid: number, - data: string, -opts?: CommandRequestOpts): Promise -``` - -Send data to command stdin. - -###### Parameters - -| Parameter | Type | Description | -| ------ | ------ | ------ | -| `pid` | `number` | process ID of the command. You can get the list of running commands using Commands.list. | -| `data` | `string` | data to send to the command. | -| `opts`? | `CommandRequestOpts` | connection options. | - -###### Returns - -`Promise`\<`void`\> - -*** - -### Pty - -Module for interacting with PTYs (pseudo-terminals) in the sandbox. - -#### Constructors - -```ts -new Pty( - transport: Transport, - connectionConfig: ConnectionConfig, - metadata: object): Pty -``` - -###### Parameters - -| Parameter | Type | -| ------ | ------ | -| `transport` | `Transport` | -| `connectionConfig` | `ConnectionConfig` | -| `metadata` | `object` | -| `metadata.version` | `string` | - -###### Returns - -`Pty` - -#### Methods - -### create() - -```ts -create(opts: PtyCreateOpts): Promise -``` - -Create a new PTY (pseudo-terminal). - -###### Parameters - -| Parameter | Type | Description | -| ------ | ------ | ------ | -| `opts` | `PtyCreateOpts` | options for creating the PTY. | - -###### Returns - -`Promise`\<`CommandHandle`\> - -handle to interact with the PTY. - -### kill() - -```ts -kill(pid: number, opts?: Pick): Promise -``` - -Kill a running PTY specified by process ID. -It uses `SIGKILL` signal to kill the PTY. - -###### Parameters - -| Parameter | Type | Description | -| ------ | ------ | ------ | -| `pid` | `number` | process ID of the PTY. | -| `opts`? | `Pick`\<`ConnectionOpts`, `"requestTimeoutMs"`\> | connection options. | - -###### Returns - -`Promise`\<`boolean`\> - -`true` if the PTY was killed, `false` if the PTY was not found. - -### resize() - -```ts -resize( - pid: number, - size: object, -opts?: Pick): Promise -``` - -Resize PTY. -Call this when the terminal window is resized and the number of columns and rows has changed. - -###### Parameters - -| Parameter | Type | Description | -| ------ | ------ | ------ | -| `pid` | `number` | process ID of the PTY. | -| `size` | `object` | new size of the PTY. | -| `size.cols` | `number` | - | -| `size.rows`? | `number` | - | -| `opts`? | `Pick`\<`ConnectionOpts`, `"requestTimeoutMs"`\> | connection options. | - -###### Returns - -`Promise`\<`void`\> - -### sendInput() - -```ts -sendInput( - pid: number, - data: Uint8Array, -opts?: Pick): Promise -``` - -Send input to a PTY. - -###### Parameters - -| Parameter | Type | Description | -| ------ | ------ | ------ | -| `pid` | `number` | process ID of the PTY. | -| `data` | `Uint8Array` | input data to send to the PTY. | -| `opts`? | `Pick`\<`ConnectionOpts`, `"requestTimeoutMs"`\> | connection options. | - -###### Returns - -`Promise`\<`void`\> - -## Interfaces - -### CommandRequestOpts - -Options for sending a command request. - -#### Extended by - -- `CommandStartOpts` - -#### Properties - -### requestTimeoutMs? - -```ts -optional requestTimeoutMs: number; -``` - -Timeout for requests to the API in **milliseconds**. - -###### Default - -```ts -60_000 // 60 seconds -``` - -*** - -### CommandStartOpts - -Options for starting a new command. - -#### Properties - -### background? - -```ts -optional background: boolean; -``` - -If true, starts command in the background and the method returns immediately. -You can use CommandHandle.wait to wait for the command to finish. - -### cwd? - -```ts -optional cwd: string; -``` - -Working directory for the command. - -###### Default - -```ts -// home directory of the user used to start the command -``` - -### envs? - -```ts -optional envs: Record; -``` - -Environment variables used for the command. - -This overrides the default environment variables from `Sandbox` constructor. - -###### Default - -`{}` - -### onStderr()? - -```ts -optional onStderr: (data: string) => void | Promise; -``` - -Callback for command stderr output. - -###### Parameters - -| Parameter | Type | -| ------ | ------ | -| `data` | `string` | - -###### Returns - -`void` \| `Promise`\<`void`\> - -### onStdout()? - -```ts -optional onStdout: (data: string) => void | Promise; -``` - -Callback for command stdout output. - -###### Parameters - -| Parameter | Type | -| ------ | ------ | -| `data` | `string` | - -###### Returns - -`void` \| `Promise`\<`void`\> - -### requestTimeoutMs? - -```ts -optional requestTimeoutMs: number; -``` - -Timeout for requests to the API in **milliseconds**. - -###### Default - -```ts -60_000 // 60 seconds -``` - -### stdin? - -```ts -optional stdin: boolean; -``` - -If true, command stdin is kept open and you can send data to it using Commands.sendStdin or CommandHandle.sendStdin. - -###### Default - -```ts -false -``` - -### timeoutMs? - -```ts -optional timeoutMs: number; -``` - -Timeout for the command in **milliseconds**. - -###### Default - -```ts -60_000 // 60 seconds -``` - -### user? - -```ts -optional user: string; -``` - -User to run the command as. - -###### Default - -`default Sandbox user (as specified in the template)` - -*** - -### ProcessInfo - -Information about a command, PTY session or start command running in the sandbox as process. - -#### Properties - -### args - -```ts -args: string[]; -``` - -Command arguments. - -### cmd - -```ts -cmd: string; -``` - -Command that was executed. - -### cwd? - -```ts -optional cwd: string; -``` - -Executed command working directory. - -### envs - -```ts -envs: Record; -``` - -Environment variables used for the command. - -### pid - -```ts -pid: number; -``` - -Process ID. - -### tag? - -```ts -optional tag: string; -``` - -Custom tag used for identifying special commands like start command in the custom template. - -## Type Aliases - -### CommandConnectOpts - -```ts -type CommandConnectOpts: Pick & CommandRequestOpts; -``` - -Options for connecting to a command. diff --git a/docs/sdk-reference/js-sdk/v2.8.3/sandbox-filesystem.mdx b/docs/sdk-reference/js-sdk/v2.8.3/sandbox-filesystem.mdx deleted file mode 100644 index c43ac2f..0000000 --- a/docs/sdk-reference/js-sdk/v2.8.3/sandbox-filesystem.mdx +++ /dev/null @@ -1,627 +0,0 @@ ---- -sidebarTitle: "Filesystem" -mode: "center" ---- - -### FileType - -Sandbox filesystem object type. - -#### Enumeration Members - -| Enumeration Member | Value | Description | -| ------ | ------ | ------ | -| `DIR` | `"dir"` | Filesystem object is a directory. | -| `FILE` | `"file"` | Filesystem object is a file. | - -## Classes - -### Filesystem - -Module for interacting with the sandbox filesystem. - -#### Constructors - -```ts -new Filesystem( - transport: Transport, - envdApi: EnvdApiClient, - connectionConfig: ConnectionConfig): Filesystem -``` - -###### Parameters - -| Parameter | Type | -| ------ | ------ | -| `transport` | `Transport` | -| `envdApi` | `EnvdApiClient` | -| `connectionConfig` | `ConnectionConfig` | - -###### Returns - -`Filesystem` - -#### Methods - -### exists() - -```ts -exists(path: string, opts?: FilesystemRequestOpts): Promise -``` - -Check if a file or a directory exists. - -###### Parameters - -| Parameter | Type | Description | -| ------ | ------ | ------ | -| `path` | `string` | path to a file or a directory | -| `opts`? | `FilesystemRequestOpts` | connection options. | - -###### Returns - -`Promise`\<`boolean`\> - -`true` if the file or directory exists, `false` otherwise - -### getInfo() - -```ts -getInfo(path: string, opts?: FilesystemRequestOpts): Promise -``` - -Get information about a file or directory. - -###### Parameters - -| Parameter | Type | Description | -| ------ | ------ | ------ | -| `path` | `string` | path to a file or directory. | -| `opts`? | `FilesystemRequestOpts` | connection options. | - -###### Returns - -`Promise`\<`EntryInfo`\> - -information about the file or directory like name, type, and path. - -### list() - -```ts -list(path: string, opts?: FilesystemListOpts): Promise -``` - -List entries in a directory. - -###### Parameters - -| Parameter | Type | Description | -| ------ | ------ | ------ | -| `path` | `string` | path to the directory. | -| `opts`? | `FilesystemListOpts` | connection options. | - -###### Returns - -`Promise`\<`EntryInfo`[]\> - -list of entries in the sandbox filesystem directory. - -### makeDir() - -```ts -makeDir(path: string, opts?: FilesystemRequestOpts): Promise -``` - -Create a new directory and all directories along the way if needed on the specified path. - -###### Parameters - -| Parameter | Type | Description | -| ------ | ------ | ------ | -| `path` | `string` | path to a new directory. For example '/dirA/dirB' when creating 'dirB'. | -| `opts`? | `FilesystemRequestOpts` | connection options. | - -###### Returns - -`Promise`\<`boolean`\> - -`true` if the directory was created, `false` if it already exists. - -### read() - -###### read(path, opts) - -```ts -read(path: string, opts?: FilesystemRequestOpts & object): Promise -``` - -Read file content as a `string`. - -You can pass `text`, `bytes`, `blob`, or `stream` to `opts.format` to change the return type. - -###### Parameters - -| Parameter | Type | Description | -| ------ | ------ | ------ | -| `path` | `string` | path to the file. | -| `opts`? | `FilesystemRequestOpts` & `object` | connection options. | - -###### Returns - -`Promise`\<`string`\> - -file content as string - -###### read(path, opts) - -```ts -read(path: string, opts?: FilesystemRequestOpts & object): Promise -``` - -Read file content as a `Uint8Array`. - -You can pass `text`, `bytes`, `blob`, or `stream` to `opts.format` to change the return type. - -###### Parameters - -| Parameter | Type | Description | -| ------ | ------ | ------ | -| `path` | `string` | path to the file. | -| `opts`? | `FilesystemRequestOpts` & `object` | connection options. | - -###### Returns - -`Promise`\<`Uint8Array`\> - -file content as `Uint8Array` - -###### read(path, opts) - -```ts -read(path: string, opts?: FilesystemRequestOpts & object): Promise -``` - -Read file content as a `Blob`. - -You can pass `text`, `bytes`, `blob`, or `stream` to `opts.format` to change the return type. - -###### Parameters - -| Parameter | Type | Description | -| ------ | ------ | ------ | -| `path` | `string` | path to the file. | -| `opts`? | `FilesystemRequestOpts` & `object` | connection options. | - -###### Returns - -`Promise`\<`Blob`\> - -file content as `Blob` - -###### read(path, opts) - -```ts -read(path: string, opts?: FilesystemRequestOpts & object): Promise> -``` - -Read file content as a `ReadableStream`. - -You can pass `text`, `bytes`, `blob`, or `stream` to `opts.format` to change the return type. - -###### Parameters - -| Parameter | Type | Description | -| ------ | ------ | ------ | -| `path` | `string` | path to the file. | -| `opts`? | `FilesystemRequestOpts` & `object` | connection options. | - -###### Returns - -`Promise`\<`ReadableStream`\<`Uint8Array`\>\> - -file content as `ReadableStream` - -### remove() - -```ts -remove(path: string, opts?: FilesystemRequestOpts): Promise -``` - -Remove a file or directory. - -###### Parameters - -| Parameter | Type | Description | -| ------ | ------ | ------ | -| `path` | `string` | path to a file or directory. | -| `opts`? | `FilesystemRequestOpts` | connection options. | - -###### Returns - -`Promise`\<`void`\> - -### rename() - -```ts -rename( - oldPath: string, - newPath: string, -opts?: FilesystemRequestOpts): Promise -``` - -Rename a file or directory. - -###### Parameters - -| Parameter | Type | Description | -| ------ | ------ | ------ | -| `oldPath` | `string` | path to the file or directory to rename. | -| `newPath` | `string` | new path for the file or directory. | -| `opts`? | `FilesystemRequestOpts` | connection options. | - -###### Returns - -`Promise`\<`EntryInfo`\> - -information about renamed file or directory. - -### watchDir() - -```ts -watchDir( - path: string, - onEvent: (event: FilesystemEvent) => void | Promise, -opts?: WatchOpts & object): Promise -``` - -Start watching a directory for filesystem events. - -###### Parameters - -| Parameter | Type | Description | -| ------ | ------ | ------ | -| `path` | `string` | path to directory to watch. | -| `onEvent` | (`event`: `FilesystemEvent`) => `void` \| `Promise`\<`void`\> | callback to call when an event in the directory occurs. | -| `opts`? | `WatchOpts` & `object` | connection options. | - -###### Returns - -`Promise`\<`WatchHandle`\> - -`WatchHandle` object for stopping watching directory. - -### write() - -###### write(path, data, opts) - -```ts -write( - path: string, - data: string | ArrayBuffer | Blob | ReadableStream, -opts?: FilesystemRequestOpts): Promise -``` - -Write content to a file. - -Writing to a file that doesn't exist creates the file. - -Writing to a file that already exists overwrites the file. - -Writing to a file at path that doesn't exist creates the necessary directories. - -###### Parameters - -| Parameter | Type | Description | -| ------ | ------ | ------ | -| `path` | `string` | path to file. | -| `data` | `string` \| `ArrayBuffer` \| `Blob` \| `ReadableStream`\<`any`\> | data to write to the file. Data can be a string, `ArrayBuffer`, `Blob`, or `ReadableStream`. | -| `opts`? | `FilesystemRequestOpts` | connection options. | - -###### Returns - -`Promise`\<`WriteInfo`\> - -information about the written file - -###### write(files, opts) - -```ts -write(files: WriteEntry[], opts?: FilesystemRequestOpts): Promise -``` - -###### Parameters - -| Parameter | Type | -| ------ | ------ | -| `files` | `WriteEntry`[] | -| `opts`? | `FilesystemRequestOpts` | - -###### Returns - -`Promise`\<`WriteInfo`[]\> - -## Interfaces - -### EntryInfo - -Sandbox filesystem object information. - -#### Properties - -### group - -```ts -group: string; -``` - -Group owner of the filesystem object. - -### mode - -```ts -mode: number; -``` - -File mode and permission bits. - -### modifiedTime? - -```ts -optional modifiedTime: Date; -``` - -Last modification time of the filesystem object. - -### name - -```ts -name: string; -``` - -Name of the filesystem object. - -### owner - -```ts -owner: string; -``` - -Owner of the filesystem object. - -### path - -```ts -path: string; -``` - -Path to the filesystem object. - -### permissions - -```ts -permissions: string; -``` - -String representation of file permissions (e.g. 'rwxr-xr-x'). - -### size - -```ts -size: number; -``` - -Size of the filesystem object in bytes. - -### symlinkTarget? - -```ts -optional symlinkTarget: string; -``` - -If the filesystem object is a symlink, this is the target of the symlink. - -### type? - -```ts -optional type: FileType; -``` - -Type of the filesystem object. - -*** - -### FilesystemListOpts - -Options for the sandbox filesystem operations. - -#### Properties - -### depth? - -```ts -optional depth: number; -``` - -Depth of the directory to list. - -### requestTimeoutMs? - -```ts -optional requestTimeoutMs: number; -``` - -Timeout for requests to the API in **milliseconds**. - -###### Default - -```ts -60_000 // 60 seconds -``` - -### user? - -```ts -optional user: string; -``` - -User to use for the operation in the sandbox. -This affects the resolution of relative paths and ownership of the created filesystem objects. - -*** - -### FilesystemRequestOpts - -Options for the sandbox filesystem operations. - -#### Extended by - -- `FilesystemListOpts` -- `WatchOpts` - -#### Properties - -### requestTimeoutMs? - -```ts -optional requestTimeoutMs: number; -``` - -Timeout for requests to the API in **milliseconds**. - -###### Default - -```ts -60_000 // 60 seconds -``` - -### user? - -```ts -optional user: string; -``` - -User to use for the operation in the sandbox. -This affects the resolution of relative paths and ownership of the created filesystem objects. - -*** - -### WatchOpts - -Options for watching a directory. - -#### Properties - -### onExit()? - -```ts -optional onExit: (err?: Error) => void | Promise; -``` - -Callback to call when the watch operation stops. - -###### Parameters - -| Parameter | Type | -| ------ | ------ | -| `err`? | `Error` | - -###### Returns - -`void` \| `Promise`\<`void`\> - -### recursive? - -```ts -optional recursive: boolean; -``` - -Watch the directory recursively - -### requestTimeoutMs? - -```ts -optional requestTimeoutMs: number; -``` - -Timeout for requests to the API in **milliseconds**. - -###### Default - -```ts -60_000 // 60 seconds -``` - -### timeoutMs? - -```ts -optional timeoutMs: number; -``` - -Timeout for the watch operation in **milliseconds**. -You can pass `0` to disable the timeout. - -###### Default - -```ts -60_000 // 60 seconds -``` - -### user? - -```ts -optional user: string; -``` - -User to use for the operation in the sandbox. -This affects the resolution of relative paths and ownership of the created filesystem objects. - -*** - -### WriteInfo - -Sandbox filesystem object information. - -#### Extended by - -- `EntryInfo` - -#### Properties - -### name - -```ts -name: string; -``` - -Name of the filesystem object. - -### path - -```ts -path: string; -``` - -Path to the filesystem object. - -### type? - -```ts -optional type: FileType; -``` - -Type of the filesystem object. - -## Type Aliases - -### WriteEntry - -```ts -type WriteEntry: object; -``` - -#### Type declaration - -| Name | Type | -| ------ | ------ | -| `data` | `string` \| `ArrayBuffer` \| `Blob` \| `ReadableStream` | -| `path` | `string` | diff --git a/docs/sdk-reference/js-sdk/v2.8.3/sandbox.mdx b/docs/sdk-reference/js-sdk/v2.8.3/sandbox.mdx deleted file mode 100644 index e430744..0000000 --- a/docs/sdk-reference/js-sdk/v2.8.3/sandbox.mdx +++ /dev/null @@ -1,712 +0,0 @@ ---- -sidebarTitle: "Sandbox" -mode: "center" ---- - -### Sandbox - -E2B cloud sandbox is a secure and isolated cloud environment. - -The sandbox allows you to: -- Access Linux OS -- Create, list, and delete files and directories -- Run commands -- Run isolated code -- Access the internet - -Check docs here. - -Use Sandbox.create to create a new sandbox. - -#### Example - -```ts -import { Sandbox } from 'e2b' - -const sandbox = await Sandbox.create() -``` - -#### Properties - -| Property | Modifier | Type | Description | -| ------ | ------ | ------ | ------ | -| `commands` | `readonly` | `Commands` | Module for running commands in the sandbox | -| `files` | `readonly` | `Filesystem` | Module for interacting with the sandbox filesystem | -| `pty` | `readonly` | `Pty` | Module for interacting with the sandbox pseudo-terminals | -| `sandboxDomain` | `readonly` | `string` | Domain where the sandbox is hosted. | -| `sandboxId` | `readonly` | `string` | Unique identifier of the sandbox. | -| `trafficAccessToken?` | `readonly` | `string` | Traffic access token for accessing sandbox services with restricted public traffic. | - -#### Methods - -### betaPause() - -```ts -betaPause(opts?: ConnectionOpts): Promise -``` - -**`Beta`** - -This feature is in beta and may change in the future. - -Pause a sandbox by its ID. - -###### Parameters - -| Parameter | Type | Description | -| ------ | ------ | ------ | -| `opts`? | `ConnectionOpts` | connection options. | - -###### Returns - -`Promise`\<`boolean`\> - -sandbox ID that can be used to resume the sandbox. - -### connect() - -```ts -connect(opts?: SandboxBetaCreateOpts): Promise -``` - -Connect to a sandbox. If the sandbox is paused, it will be automatically resumed. -Sandbox must be either running or be paused. - -With sandbox ID you can connect to the same sandbox from different places or environments (serverless functions, etc). - -###### Parameters - -| Parameter | Type | Description | -| ------ | ------ | ------ | -| `opts`? | `SandboxBetaCreateOpts` | connection options. | - -###### Returns - -`Promise`\<`Sandbox`\> - -A running sandbox instance - -###### Example - -```ts -const sandbox = await Sandbox.create() -await sandbox.betaPause() - -// Connect to the same sandbox. -const sameSandbox = await sandbox.connect() -``` - -### downloadUrl() - -```ts -downloadUrl(path: string, opts?: SandboxUrlOpts): Promise -``` - -Get the URL to download a file from the sandbox. - -###### Parameters - -| Parameter | Type | Description | -| ------ | ------ | ------ | -| `path` | `string` | path to the file in the sandbox. | -| `opts`? | `SandboxUrlOpts` | download url options. | - -###### Returns - -`Promise`\<`string`\> - -URL for downloading file. - -### getHost() - -```ts -getHost(port: number): string -``` - -Get the host address for the specified sandbox port. -You can then use this address to connect to the sandbox port from outside the sandbox via HTTP or WebSocket. - -###### Parameters - -| Parameter | Type | Description | -| ------ | ------ | ------ | -| `port` | `number` | number of the port in the sandbox. | - -###### Returns - -`string` - -host address of the sandbox port. - -###### Example - -```ts -const sandbox = await Sandbox.create() -// Start an HTTP server -await sandbox.commands.exec('python3 -m http.server 3000') -// Get the hostname of the HTTP server -const serverURL = sandbox.getHost(3000) -``` - -### getInfo() - -```ts -getInfo(opts?: Pick): Promise -``` - -Get sandbox information like sandbox ID, template, metadata, started at/end at date. - -###### Parameters - -| Parameter | Type | Description | -| ------ | ------ | ------ | -| `opts`? | `Pick`\<`SandboxOpts`, `"requestTimeoutMs"`\> | connection options. | - -###### Returns - -`Promise`\<`SandboxInfo`\> - -information about the sandbox - -### getMcpToken() - -```ts -getMcpToken(): Promise -``` - -Get the MCP token for the sandbox. - -###### Returns - -`Promise`\<`undefined` \| `string`\> - -MCP token for the sandbox, or undefined if MCP is not enabled. - -### getMcpUrl() - -```ts -getMcpUrl(): string -``` - -Get the MCP URL for the sandbox. - -###### Returns - -`string` - -MCP URL for the sandbox. - -### getMetrics() - -```ts -getMetrics(opts?: SandboxMetricsOpts): Promise -``` - -Get the metrics of the sandbox. - -###### Parameters - -| Parameter | Type | Description | -| ------ | ------ | ------ | -| `opts`? | `SandboxMetricsOpts` | connection options. | - -###### Returns - -`Promise`\<`SandboxMetrics`[]\> - -List of sandbox metrics containing CPU, memory and disk usage information. - -### isRunning() - -```ts -isRunning(opts?: Pick): Promise -``` - -Check if the sandbox is running. - -###### Parameters - -| Parameter | Type | -| ------ | ------ | -| `opts`? | `Pick`\<`ConnectionOpts`, `"requestTimeoutMs"`\> | - -###### Returns - -`Promise`\<`boolean`\> - -`true` if the sandbox is running, `false` otherwise. - -###### Example - -```ts -const sandbox = await Sandbox.create() -await sandbox.isRunning() // Returns true - -await sandbox.kill() -await sandbox.isRunning() // Returns false -``` - -### kill() - -```ts -kill(opts?: Pick): Promise -``` - -Kill the sandbox. - -###### Parameters - -| Parameter | Type | Description | -| ------ | ------ | ------ | -| `opts`? | `Pick`\<`SandboxOpts`, `"requestTimeoutMs"`\> | connection options. | - -###### Returns - -`Promise`\<`void`\> - -### setTimeout() - -```ts -setTimeout(timeoutMs: number, opts?: Pick): Promise -``` - -Set the timeout of the sandbox. -After the timeout expires the sandbox will be automatically killed. - -This method can extend or reduce the sandbox timeout set when creating the sandbox or from the last call to `.setTimeout`. -Maximum time a sandbox can be kept alive is 24 hours (86_400_000 milliseconds) for Pro users and 1 hour (3_600_000 milliseconds) for Hobby users. - -###### Parameters - -| Parameter | Type | Description | -| ------ | ------ | ------ | -| `timeoutMs` | `number` | timeout in **milliseconds**. | -| `opts`? | `Pick`\<`SandboxOpts`, `"requestTimeoutMs"`\> | connection options. | - -###### Returns - -`Promise`\<`void`\> - -### uploadUrl() - -```ts -uploadUrl(path?: string, opts?: SandboxUrlOpts): Promise -``` - -Get the URL to upload a file to the sandbox. - -You have to send a POST request to this URL with the file as multipart/form-data. - -###### Parameters - -| Parameter | Type | Description | -| ------ | ------ | ------ | -| `path`? | `string` | path to the file in the sandbox. | -| `opts`? | `SandboxUrlOpts` | download url options. | - -###### Returns - -`Promise`\<`string`\> - -URL for uploading file. - -### betaCreate() - -###### betaCreate(this, opts) - -```ts -static betaCreate(this: S, opts?: SandboxBetaCreateOpts): Promise> -``` - -**`Beta`** - -This feature is in beta and may change in the future. - -Create a new sandbox from the default `base` sandbox template. - -###### Type Parameters - -| Type Parameter | -| ------ | -| `S` *extends* *typeof* `Sandbox` | - -###### Parameters - -| Parameter | Type | Description | -| ------ | ------ | ------ | -| `this` | `S` | - | -| `opts`? | `SandboxBetaCreateOpts` | connection options. | - -###### Returns - -`Promise`\<`InstanceType`\<`S`\>\> - -sandbox instance for the new sandbox. - -###### Example - -```ts -const sandbox = await Sandbox.betaCreate() -``` - -###### Constructs - -Sandbox - -###### betaCreate(this, template, opts) - -```ts -static betaCreate( - this: S, - template: string, -opts?: SandboxBetaCreateOpts): Promise> -``` - -**`Beta`** - -This feature is in beta and may change in the future. - -Create a new sandbox from the specified sandbox template. - -###### Type Parameters - -| Type Parameter | -| ------ | -| `S` *extends* *typeof* `Sandbox` | - -###### Parameters - -| Parameter | Type | Description | -| ------ | ------ | ------ | -| `this` | `S` | - | -| `template` | `string` | sandbox template name or ID. | -| `opts`? | `SandboxBetaCreateOpts` | connection options. | - -###### Returns - -`Promise`\<`InstanceType`\<`S`\>\> - -sandbox instance for the new sandbox. - -###### Example - -```ts -const sandbox = await Sandbox.betaCreate('') -``` - -###### Constructs - -Sandbox - -### betaPause() - -```ts -static betaPause(sandboxId: string, opts?: SandboxApiOpts): Promise -``` - -Pause the sandbox specified by sandbox ID. - -###### Parameters - -| Parameter | Type | Description | -| ------ | ------ | ------ | -| `sandboxId` | `string` | sandbox ID. | -| `opts`? | `SandboxApiOpts` | connection options. | - -###### Returns - -`Promise`\<`boolean`\> - -`true` if the sandbox got paused, `false` if the sandbox was already paused. - -### connect() - -```ts -static connect( - this: S, - sandboxId: string, -opts?: SandboxConnectOpts): Promise> -``` - -Connect to a sandbox. If the sandbox is paused, it will be automatically resumed. -Sandbox must be either running or be paused. - -With sandbox ID you can connect to the same sandbox from different places or environments (serverless functions, etc). - -###### Type Parameters - -| Type Parameter | -| ------ | -| `S` *extends* *typeof* `Sandbox` | - -###### Parameters - -| Parameter | Type | Description | -| ------ | ------ | ------ | -| `this` | `S` | - | -| `sandboxId` | `string` | sandbox ID. | -| `opts`? | `SandboxConnectOpts` | connection options. | - -###### Returns - -`Promise`\<`InstanceType`\<`S`\>\> - -A running sandbox instance - -###### Example - -```ts -const sandbox = await Sandbox.create() -const sandboxId = sandbox.sandboxId - -// Connect to the same sandbox. -const sameSandbox = await Sandbox.connect(sandboxId) -``` - -### create() - -###### create(this, opts) - -```ts -static create(this: S, opts?: SandboxOpts): Promise> -``` - -Create a new sandbox from the default `base` sandbox template. - -###### Type Parameters - -| Type Parameter | -| ------ | -| `S` *extends* *typeof* `Sandbox` | - -###### Parameters - -| Parameter | Type | Description | -| ------ | ------ | ------ | -| `this` | `S` | - | -| `opts`? | `SandboxOpts` | connection options. | - -###### Returns - -`Promise`\<`InstanceType`\<`S`\>\> - -sandbox instance for the new sandbox. - -###### Example - -```ts -const sandbox = await Sandbox.create() -``` - -###### Constructs - -Sandbox - -###### create(this, template, opts) - -```ts -static create( - this: S, - template: string, -opts?: SandboxOpts): Promise> -``` - -Create a new sandbox from the specified sandbox template. - -###### Type Parameters - -| Type Parameter | -| ------ | -| `S` *extends* *typeof* `Sandbox` | - -###### Parameters - -| Parameter | Type | Description | -| ------ | ------ | ------ | -| `this` | `S` | - | -| `template` | `string` | sandbox template name or ID. | -| `opts`? | `SandboxOpts` | connection options. | - -###### Returns - -`Promise`\<`InstanceType`\<`S`\>\> - -sandbox instance for the new sandbox. - -###### Example - -```ts -const sandbox = await Sandbox.create('') -``` - -###### Constructs - -Sandbox - -### getFullInfo() - -```ts -static getFullInfo(sandboxId: string, opts?: SandboxApiOpts): Promise -``` - -###### Parameters - -| Parameter | Type | -| ------ | ------ | -| `sandboxId` | `string` | -| `opts`? | `SandboxApiOpts` | - -###### Returns - -`Promise`\<`object`\> - -| Name | Type | Default value | -| ------ | ------ | ------ | -| `cpuCount` | `number` | res.data.cpuCount | -| `endAt` | `Date` | - | -| `envdAccessToken` | `undefined` \| `string` | res.data.envdAccessToken | -| `envdVersion` | `string` | res.data.envdVersion | -| `memoryMB` | `number` | res.data.memoryMB | -| `metadata` | `object` | - | -| `name`? | `string` | res.data.alias | -| `sandboxDomain` | `undefined` \| `string` | - | -| `sandboxId` | `string` | res.data.sandboxID | -| `startedAt` | `Date` | - | -| `state` | `"running"` \| `"paused"` | res.data.state | -| `templateId` | `string` | res.data.templateID | - -### getInfo() - -```ts -static getInfo(sandboxId: string, opts?: SandboxApiOpts): Promise -``` - -Get sandbox information like sandbox ID, template, metadata, started at/end at date. - -###### Parameters - -| Parameter | Type | Description | -| ------ | ------ | ------ | -| `sandboxId` | `string` | sandbox ID. | -| `opts`? | `SandboxApiOpts` | connection options. | - -###### Returns - -`Promise`\<`SandboxInfo`\> - -sandbox information. - -### getMetrics() - -```ts -static getMetrics(sandboxId: string, opts?: SandboxMetricsOpts): Promise -``` - -Get the metrics of the sandbox. - -###### Parameters - -| Parameter | Type | Description | -| ------ | ------ | ------ | -| `sandboxId` | `string` | sandbox ID. | -| `opts`? | `SandboxMetricsOpts` | sandbox metrics options. | - -###### Returns - -`Promise`\<`SandboxMetrics`[]\> - -List of sandbox metrics containing CPU, memory and disk usage information. - -### kill() - -```ts -static kill(sandboxId: string, opts?: SandboxApiOpts): Promise -``` - -Kill the sandbox specified by sandbox ID. - -###### Parameters - -| Parameter | Type | Description | -| ------ | ------ | ------ | -| `sandboxId` | `string` | sandbox ID. | -| `opts`? | `SandboxApiOpts` | connection options. | - -###### Returns - -`Promise`\<`boolean`\> - -`true` if the sandbox was found and killed, `false` otherwise. - -### list() - -```ts -static list(opts?: SandboxListOpts): SandboxPaginator -``` - -List all sandboxes. - -###### Parameters - -| Parameter | Type | Description | -| ------ | ------ | ------ | -| `opts`? | `SandboxListOpts` | connection options. | - -###### Returns - -`SandboxPaginator` - -paginator for listing sandboxes. - -### setTimeout() - -```ts -static setTimeout( - sandboxId: string, - timeoutMs: number, -opts?: SandboxApiOpts): Promise -``` - -Set the timeout of the specified sandbox. -After the timeout expires the sandbox will be automatically killed. - -This method can extend or reduce the sandbox timeout set when creating the sandbox or from the last call to Sandbox.setTimeout. - -Maximum time a sandbox can be kept alive is 24 hours (86_400_000 milliseconds) for Pro users and 1 hour (3_600_000 milliseconds) for Hobby users. - -###### Parameters - -| Parameter | Type | Description | -| ------ | ------ | ------ | -| `sandboxId` | `string` | sandbox ID. | -| `timeoutMs` | `number` | timeout in **milliseconds**. | -| `opts`? | `SandboxApiOpts` | connection options. | - -###### Returns - -`Promise`\<`void`\> - -## Interfaces - -### SandboxUrlOpts - -Options for sandbox upload/download URL generation. - -#### Properties - -### user? - -```ts -optional user: string; -``` - -User that will be used to access the file. - -### useSignatureExpiration? - -```ts -optional useSignatureExpiration: number; -``` - -Use signature expiration for the URL. -Optional parameter to set the expiration time for the signature in seconds. diff --git a/docs/sdk-reference/js-sdk/v2.8.3/template-logger.mdx b/docs/sdk-reference/js-sdk/v2.8.3/template-logger.mdx deleted file mode 100644 index fdebde3..0000000 --- a/docs/sdk-reference/js-sdk/v2.8.3/template-logger.mdx +++ /dev/null @@ -1,196 +0,0 @@ ---- -sidebarTitle: "Logger" -mode: "center" ---- - -### LogEntry - -Represents a single log entry from the template build process. - -#### Extended by - -- `LogEntryStart` -- `LogEntryEnd` - -#### Constructors - -```ts -new LogEntry( - timestamp: Date, - level: LogEntryLevel, - message: string): LogEntry -``` - -###### Parameters - -| Parameter | Type | -| ------ | ------ | -| `timestamp` | `Date` | -| `level` | `LogEntryLevel` | -| `message` | `string` | - -###### Returns - -`LogEntry` - -#### Properties - -| Property | Modifier | Type | -| ------ | ------ | ------ | -| `level` | `readonly` | `LogEntryLevel` | -| `message` | `readonly` | `string` | -| `timestamp` | `readonly` | `Date` | - -#### Methods - -### toString() - -```ts -toString(): string -``` - -###### Returns - -`string` - -*** - -### LogEntryEnd - -Special log entry indicating the end of a build process. - -#### Constructors - -```ts -new LogEntryEnd(timestamp: Date, message: string): LogEntryEnd -``` - -###### Parameters - -| Parameter | Type | -| ------ | ------ | -| `timestamp` | `Date` | -| `message` | `string` | - -###### Returns - -`LogEntryEnd` - -#### Properties - -| Property | Modifier | Type | Inherited from | -| ------ | ------ | ------ | ------ | -| `level` | `readonly` | `LogEntryLevel` | `LogEntry`.`level` | -| `message` | `readonly` | `string` | `LogEntry`.`message` | -| `timestamp` | `readonly` | `Date` | `LogEntry`.`timestamp` | - -#### Methods - -### toString() - -```ts -toString(): string -``` - -###### Returns - -`string` - -*** - -### LogEntryStart - -Special log entry indicating the start of a build process. - -#### Constructors - -```ts -new LogEntryStart(timestamp: Date, message: string): LogEntryStart -``` - -###### Parameters - -| Parameter | Type | -| ------ | ------ | -| `timestamp` | `Date` | -| `message` | `string` | - -###### Returns - -`LogEntryStart` - -#### Properties - -| Property | Modifier | Type | Inherited from | -| ------ | ------ | ------ | ------ | -| `level` | `readonly` | `LogEntryLevel` | `LogEntry`.`level` | -| `message` | `readonly` | `string` | `LogEntry`.`message` | -| `timestamp` | `readonly` | `Date` | `LogEntry`.`timestamp` | - -#### Methods - -### toString() - -```ts -toString(): string -``` - -###### Returns - -`string` - -## Type Aliases - -### LogEntryLevel - -```ts -type LogEntryLevel: "debug" | "info" | "warn" | "error"; -``` - -Log entry severity levels. - -## Functions - -### defaultBuildLogger() - -```ts -function defaultBuildLogger(options?: object): (logEntry: LogEntry) => void -``` - -Create a default build logger with animated timer display. - -#### Parameters - -| Parameter | Type | Description | -| ------ | ------ | ------ | -| `options`? | `object` | Logger configuration options | -| `options.minLevel`? | `LogEntryLevel` | Minimum log level to display (default: 'info') | - -#### Returns - -`Function` - -Logger function that accepts LogEntry instances - -### Parameters - -| Parameter | Type | -| ------ | ------ | -| `logEntry` | `LogEntry` | - -### Returns - -`void` - -#### Example - -```ts -import { Template, defaultBuildLogger } from 'e2b' - -const template = Template().fromPythonImage() - -await Template.build(template, { - alias: 'my-template', - onBuildLogs: defaultBuildLogger({ minLevel: 'debug' }) -}) -``` diff --git a/docs/sdk-reference/js-sdk/v2.8.3/template-readycmd.mdx b/docs/sdk-reference/js-sdk/v2.8.3/template-readycmd.mdx deleted file mode 100644 index 56fb0b7..0000000 --- a/docs/sdk-reference/js-sdk/v2.8.3/template-readycmd.mdx +++ /dev/null @@ -1,202 +0,0 @@ ---- -sidebarTitle: "Readycmd" -mode: "center" ---- - -### ReadyCmd - -Class for ready check commands. - -#### Constructors - -```ts -new ReadyCmd(cmd: string): ReadyCmd -``` - -###### Parameters - -| Parameter | Type | -| ------ | ------ | -| `cmd` | `string` | - -###### Returns - -`ReadyCmd` - -#### Methods - -### getCmd() - -```ts -getCmd(): string -``` - -###### Returns - -`string` - -## Functions - -### waitForFile() - -```ts -function waitForFile(filename: string): ReadyCmd -``` - -Wait for a file to exist. -Uses shell test command to check file existence. - -#### Parameters - -| Parameter | Type | Description | -| ------ | ------ | ------ | -| `filename` | `string` | Path to the file to wait for | - -#### Returns - -`ReadyCmd` - -ReadyCmd that checks for the file - -#### Example - -```ts -import { Template, waitForFile } from 'e2b' - -const template = Template() - .fromBaseImage() - .setStartCmd('./init.sh', waitForFile('/tmp/ready')) -``` - -*** - -### waitForPort() - -```ts -function waitForPort(port: number): ReadyCmd -``` - -Wait for a port to be listening. -Uses `ss` command to check if a port is open and listening. - -#### Parameters - -| Parameter | Type | Description | -| ------ | ------ | ------ | -| `port` | `number` | Port number to wait for | - -#### Returns - -`ReadyCmd` - -ReadyCmd that checks for the port - -#### Example - -```ts -import { Template, waitForPort } from 'e2b' - -const template = Template() - .fromPythonImage() - .setStartCmd('python -m http.server 8000', waitForPort(8000)) -``` - -*** - -### waitForProcess() - -```ts -function waitForProcess(processName: string): ReadyCmd -``` - -Wait for a process with a specific name to be running. -Uses `pgrep` to check if a process exists. - -#### Parameters - -| Parameter | Type | Description | -| ------ | ------ | ------ | -| `processName` | `string` | Name of the process to wait for | - -#### Returns - -`ReadyCmd` - -ReadyCmd that checks for the process - -#### Example - -```ts -import { Template, waitForProcess } from 'e2b' - -const template = Template() - .fromBaseImage() - .setStartCmd('./my-daemon', waitForProcess('my-daemon')) -``` - -*** - -### waitForTimeout() - -```ts -function waitForTimeout(timeout: number): ReadyCmd -``` - -Wait for a specified timeout before considering the sandbox ready. -Uses `sleep` command to wait for a fixed duration. - -#### Parameters - -| Parameter | Type | Description | -| ------ | ------ | ------ | -| `timeout` | `number` | Time to wait in milliseconds (minimum: 1000ms / 1 second) | - -#### Returns - -`ReadyCmd` - -ReadyCmd that waits for the specified duration - -#### Example - -```ts -import { Template, waitForTimeout } from 'e2b' - -const template = Template() - .fromNodeImage() - .setStartCmd('npm start', waitForTimeout(5000)) // Wait 5 seconds -``` - -*** - -### waitForURL() - -```ts -function waitForURL(url: string, statusCode: number): ReadyCmd -``` - -Wait for a URL to return a specific HTTP status code. -Uses `curl` to make HTTP requests and check the response status. - -#### Parameters - -| Parameter | Type | Default value | Description | -| ------ | ------ | ------ | ------ | -| `url` | `string` | `undefined` | URL to check (e.g., 'http://localhost:3000/health') | -| `statusCode` | `number` | `200` | Expected HTTP status code (default: 200) | - -#### Returns - -`ReadyCmd` - -ReadyCmd that checks the URL - -#### Example - -```ts -import { Template, waitForURL } from 'e2b' - -const template = Template() - .fromNodeImage() - .setStartCmd('npm start', waitForURL('http://localhost:3000/health')) -``` diff --git a/docs/sdk-reference/js-sdk/v2.8.3/template.mdx b/docs/sdk-reference/js-sdk/v2.8.3/template.mdx deleted file mode 100644 index c644e02..0000000 --- a/docs/sdk-reference/js-sdk/v2.8.3/template.mdx +++ /dev/null @@ -1,2042 +0,0 @@ ---- -sidebarTitle: "Template" -mode: "center" ---- - -### TemplateBase - -Base class for building E2B sandbox templates. - -#### Implements - -- `TemplateFromImage` -- `TemplateBuilder` -- `TemplateFinal` - -#### Constructors - -```ts -new TemplateBase(options?: TemplateOptions): TemplateBase -``` - -###### Parameters - -| Parameter | Type | -| ------ | ------ | -| `options`? | `TemplateOptions` | - -###### Returns - -`TemplateBase` - -#### Methods - -### addMcpServer() - -```ts -addMcpServer(servers: keyof McpServer | keyof McpServer[]): TemplateBuilder -``` - -Install MCP servers using mcp-gateway. -Note: Requires a base image with mcp-gateway pre-installed (e.g., mcp-gateway). - -###### Parameters - -| Parameter | Type | Description | -| ------ | ------ | ------ | -| `servers` | keyof McpServer \| keyof McpServer[] | MCP server name(s) | - -###### Returns - -`TemplateBuilder` - -###### Throws - -If the base template is not mcp-gateway - -###### Example - -```ts -template.addMcpServer('exa') -template.addMcpServer(['brave', 'firecrawl', 'duckduckgo']) -``` - -###### Implementation of - -`TemplateBuilder`.`addMcpServer` - -### aptInstall() - -```ts -aptInstall(packages: string | string[], options?: object): TemplateBuilder -``` - -Install Debian/Ubuntu packages using apt-get. - -###### Parameters - -| Parameter | Type | Description | -| ------ | ------ | ------ | -| `packages` | `string` \| `string`[] | Package name(s) | -| `options`? | `object` | - | -| `options.noInstallRecommends`? | `boolean` | - | - -###### Returns - -`TemplateBuilder` - -###### Example - -```ts -template.aptInstall('vim') -template.aptInstall(['git', 'curl', 'wget']) -template.aptInstall(['vim'], { noInstallRecommends: true }) -``` - -###### Implementation of - -`TemplateBuilder`.`aptInstall` - -### betaDevContainerPrebuild() - -```ts -betaDevContainerPrebuild(devcontainerDirectory: string): TemplateBuilder -``` - -Prebuild a devcontainer from the specified directory. - -###### Parameters - -| Parameter | Type | Description | -| ------ | ------ | ------ | -| `devcontainerDirectory` | `string` | Path to the devcontainer directory | - -###### Returns - -`TemplateBuilder` - -###### Example - -```ts -template - .gitClone('https://myrepo.com/project.git', '/my-devcontainer') - .betaDevContainerPrebuild('/my-devcontainer') -``` - -###### Implementation of - -`TemplateBuilder`.`betaDevContainerPrebuild` - -### betaSetDevContainerStart() - -```ts -betaSetDevContainerStart(devcontainerDirectory: string): TemplateFinal -``` - -Start a devcontainer from the specified directory. - -###### Parameters - -| Parameter | Type | Description | -| ------ | ------ | ------ | -| `devcontainerDirectory` | `string` | Path to the devcontainer directory | - -###### Returns - -`TemplateFinal` - -###### Example - -```ts -template - .gitClone('https://myrepo.com/project.git', '/my-devcontainer') - .startDevcontainer('/my-devcontainer') - -// Prebuild and start -template - .gitClone('https://myrepo.com/project.git', '/my-devcontainer') - .betaDevContainerPrebuild('/my-devcontainer') - // Other instructions... - .betaSetDevContainerStart('/my-devcontainer') -``` - -###### Implementation of - -`TemplateBuilder`.`betaSetDevContainerStart` - -### bunInstall() - -```ts -bunInstall(packages?: string | string[], options?: object): TemplateBuilder -``` - -Install Bun packages using bun. - -###### Parameters - -| Parameter | Type | Description | -| ------ | ------ | ------ | -| `packages`? | `string` \| `string`[] | Package name(s) or undefined for package.json | -| `options`? | `object` | Install options | -| `options.dev`? | `boolean` | - | -| `options.g`? | `boolean` | - | - -###### Returns - -`TemplateBuilder` - -###### Example - -```ts -template.bunInstall('express') -template.bunInstall(['lodash', 'axios']) -template.bunInstall('tsx', { g: true }) -template.bunInstall('typescript', { dev: true }) -template.bunInstall() // Installs from package.json -``` - -###### Implementation of - -`TemplateBuilder`.`bunInstall` - -### copy() - -```ts -copy( - src: PathLike | PathLike[], - dest: PathLike, - options?: object): TemplateBuilder -``` - -Copy files or directories into the template. - -###### Parameters - -| Parameter | Type | Description | -| ------ | ------ | ------ | -| `src` | `PathLike` \| `PathLike`[] | Source path(s) | -| `dest` | `PathLike` | Destination path | -| `options`? | `object` | Copy options | -| `options.forceUpload`? | `true` | - | -| `options.mode`? | `number` | - | -| `options.resolveSymlinks`? | `boolean` | - | -| `options.user`? | `string` | - | - -###### Returns - -`TemplateBuilder` - -###### Example - -```ts -template.copy('requirements.txt', '/home/user/') -template.copy(['app.ts', 'config.ts'], '/app/', { mode: 0o755 }) -``` - -###### Implementation of - -`TemplateBuilder`.`copy` - -### copyItems() - -```ts -copyItems(items: CopyItem[]): TemplateBuilder -``` - -Copy multiple items with individual options. - -###### Parameters - -| Parameter | Type | Description | -| ------ | ------ | ------ | -| `items` | `CopyItem`[] | Array of copy items | - -###### Returns - -`TemplateBuilder` - -###### Example - -```ts -template.copyItems([ - { src: 'app.ts', dest: '/app/' }, - { src: 'config.ts', dest: '/app/', mode: 0o644 } -]) -``` - -###### Implementation of - -`TemplateBuilder`.`copyItems` - -### fromAWSRegistry() - -```ts -fromAWSRegistry(image: string, credentials: object): TemplateBuilder -``` - -Start from a Docker image in AWS ECR. - -###### Parameters - -| Parameter | Type | Description | -| ------ | ------ | ------ | -| `image` | `string` | Full ECR image path | -| `credentials` | `object` | AWS credentials | -| `credentials.accessKeyId` | `string` | - | -| `credentials.region` | `string` | - | -| `credentials.secretAccessKey` | `string` | - | - -###### Returns - -`TemplateBuilder` - -###### Example - -```ts -Template().fromAWSRegistry( - '123456789.dkr.ecr.us-west-2.amazonaws.com/myimage:latest', - { - accessKeyId: 'AKIA...', - secretAccessKey: '...', - region: 'us-west-2' - } -) -``` - -###### Implementation of - -`TemplateFromImage.fromAWSRegistry` - -### fromBaseImage() - -```ts -fromBaseImage(): TemplateBuilder -``` - -Start from E2B's default base image (e2bdev/base:latest). - -###### Returns - -`TemplateBuilder` - -###### Example - -```ts -Template().fromBaseImage() -``` - -###### Implementation of - -`TemplateFromImage.fromBaseImage` - -### fromBunImage() - -```ts -fromBunImage(variant: string): TemplateBuilder -``` - -Start from a Bun-based Docker image. - -###### Parameters - -| Parameter | Type | Default value | Description | -| ------ | ------ | ------ | ------ | -| `variant` | `string` | `'latest'` | Bun variant (default: 'latest') | - -###### Returns - -`TemplateBuilder` - -###### Example - -```ts -Template().fromBunImage('1.3') -``` - -###### Implementation of - -`TemplateFromImage.fromBunImage` - -### fromDebianImage() - -```ts -fromDebianImage(variant: string): TemplateBuilder -``` - -Start from a Debian-based Docker image. - -###### Parameters - -| Parameter | Type | Default value | Description | -| ------ | ------ | ------ | ------ | -| `variant` | `string` | `'stable'` | Debian variant (default: 'stable') | - -###### Returns - -`TemplateBuilder` - -###### Example - -```ts -Template().fromDebianImage('bookworm') -``` - -###### Implementation of - -`TemplateFromImage.fromDebianImage` - -### fromDockerfile() - -```ts -fromDockerfile(dockerfileContentOrPath: string): TemplateBuilder -``` - -Parse a Dockerfile and convert it to Template SDK format. - -###### Parameters - -| Parameter | Type | Description | -| ------ | ------ | ------ | -| `dockerfileContentOrPath` | `string` | Dockerfile content or path | - -###### Returns - -`TemplateBuilder` - -###### Example - -```ts -Template().fromDockerfile('Dockerfile') -Template().fromDockerfile('FROM python:3\nRUN pip install numpy') -``` - -###### Implementation of - -`TemplateFromImage.fromDockerfile` - -### fromGCPRegistry() - -```ts -fromGCPRegistry(image: string, credentials: object): TemplateBuilder -``` - -Start from a Docker image in Google Container Registry. - -###### Parameters - -| Parameter | Type | Description | -| ------ | ------ | ------ | -| `image` | `string` | Full GCR/GAR image path | -| `credentials` | `object` | GCP service account credentials | -| `credentials.serviceAccountJSON` | `string` \| `object` | - | - -###### Returns - -`TemplateBuilder` - -###### Example - -```ts -Template().fromGCPRegistry( - 'gcr.io/myproject/myimage:latest', - { serviceAccountJSON: 'path/to/service-account.json' } -) -``` - -###### Implementation of - -`TemplateFromImage.fromGCPRegistry` - -### fromImage() - -```ts -fromImage(baseImage: string, credentials?: object): TemplateBuilder -``` - -Start from a custom Docker image. - -###### Parameters - -| Parameter | Type | Description | -| ------ | ------ | ------ | -| `baseImage` | `string` | Docker image name | -| `credentials`? | `object` | Optional credentials for private registries | -| `credentials.password`? | `string` | - | -| `credentials.username`? | `string` | - | - -###### Returns - -`TemplateBuilder` - -###### Example - -```ts -Template().fromImage('python:3') - -// With credentials (optional) -Template().fromImage('myregistry.com/myimage:latest', { - username: 'user', - password: 'pass' -}) -``` - -###### Implementation of - -`TemplateFromImage.fromImage` - -### fromNodeImage() - -```ts -fromNodeImage(variant: string): TemplateBuilder -``` - -Start from a Node.js-based Docker image. - -###### Parameters - -| Parameter | Type | Default value | Description | -| ------ | ------ | ------ | ------ | -| `variant` | `string` | `'lts'` | Node.js variant (default: 'lts') | - -###### Returns - -`TemplateBuilder` - -###### Example - -```ts -Template().fromNodeImage('24') -``` - -###### Implementation of - -`TemplateFromImage.fromNodeImage` - -### fromPythonImage() - -```ts -fromPythonImage(version: string): TemplateBuilder -``` - -Start from a Python-based Docker image. - -###### Parameters - -| Parameter | Type | Default value | Description | -| ------ | ------ | ------ | ------ | -| `version` | `string` | `'3'` | Python version (default: '3') | - -###### Returns - -`TemplateBuilder` - -###### Example - -```ts -Template().fromPythonImage('3') -``` - -###### Implementation of - -`TemplateFromImage.fromPythonImage` - -### fromTemplate() - -```ts -fromTemplate(template: string): TemplateBuilder -``` - -Start from an existing E2B template. - -###### Parameters - -| Parameter | Type | Description | -| ------ | ------ | ------ | -| `template` | `string` | E2B template ID or alias | - -###### Returns - -`TemplateBuilder` - -###### Example - -```ts -Template().fromTemplate('my-base-template') -``` - -###### Implementation of - -`TemplateFromImage.fromTemplate` - -### fromUbuntuImage() - -```ts -fromUbuntuImage(variant: string): TemplateBuilder -``` - -Start from an Ubuntu-based Docker image. - -###### Parameters - -| Parameter | Type | Default value | Description | -| ------ | ------ | ------ | ------ | -| `variant` | `string` | `'latest'` | Ubuntu variant (default: 'latest') | - -###### Returns - -`TemplateBuilder` - -###### Example - -```ts -Template().fromUbuntuImage('24.04') -``` - -###### Implementation of - -`TemplateFromImage.fromUbuntuImage` - -### gitClone() - -```ts -gitClone( - url: string, - path?: PathLike, - options?: object): TemplateBuilder -``` - -Clone a Git repository. - -###### Parameters - -| Parameter | Type | Description | -| ------ | ------ | ------ | -| `url` | `string` | Repository URL | -| `path`? | `PathLike` | Optional destination path | -| `options`? | `object` | Clone options | -| `options.branch`? | `string` | - | -| `options.depth`? | `number` | - | -| `options.user`? | `string` | - | - -###### Returns - -`TemplateBuilder` - -###### Example - -```ts -template.gitClone('https://github.com/user/repo.git', '/app/repo') -template.gitClone('https://github.com/user/repo.git', undefined, { - branch: 'main', - depth: 1 -}) -template.gitClone('https://github.com/user/repo.git', '/app/repo', { - user: 'root' -}) -``` - -###### Implementation of - -`TemplateBuilder`.`gitClone` - -### makeDir() - -```ts -makeDir(path: PathLike | PathLike[], options?: object): TemplateBuilder -``` - -Create directories. - -###### Parameters - -| Parameter | Type | Description | -| ------ | ------ | ------ | -| `path` | `PathLike` \| `PathLike`[] | Directory path(s) | -| `options`? | `object` | Directory options | -| `options.mode`? | `number` | - | -| `options.user`? | `string` | - | - -###### Returns - -`TemplateBuilder` - -###### Example - -```ts -template.makeDir('/app/data', { mode: 0o755 }) -template.makeDir(['/app/logs', '/app/cache']) -template.makeDir('/app/data', { mode: 0o755, user: 'root' }) -``` - -###### Implementation of - -`TemplateBuilder`.`makeDir` - -### makeSymlink() - -```ts -makeSymlink( - src: PathLike, - dest: PathLike, - options?: object): TemplateBuilder -``` - -Create a symbolic link. - -###### Parameters - -| Parameter | Type | Description | -| ------ | ------ | ------ | -| `src` | `PathLike` | Source path (target) | -| `dest` | `PathLike` | Destination path (symlink location) | -| `options`? | `object` | Symlink options | -| `options.force`? | `boolean` | - | -| `options.user`? | `string` | - | - -###### Returns - -`TemplateBuilder` - -###### Example - -```ts -template.makeSymlink('/usr/bin/python3', '/usr/bin/python') -template.makeSymlink('/usr/bin/python3', '/usr/bin/python', { user: 'root' }) -template.makeSymlink('/usr/bin/python3', '/usr/bin/python', { force: true }) -``` - -###### Implementation of - -`TemplateBuilder`.`makeSymlink` - -### npmInstall() - -```ts -npmInstall(packages?: string | string[], options?: object): TemplateBuilder -``` - -Install Node.js packages using npm. - -###### Parameters - -| Parameter | Type | Description | -| ------ | ------ | ------ | -| `packages`? | `string` \| `string`[] | Package name(s) or undefined for package.json | -| `options`? | `object` | Install options | -| `options.dev`? | `boolean` | - | -| `options.g`? | `boolean` | - | - -###### Returns - -`TemplateBuilder` - -###### Example - -```ts -template.npmInstall('express') -template.npmInstall(['lodash', 'axios']) -template.npmInstall('tsx', { g: true }) -template.npmInstall('typescript', { dev: true }) -template.npmInstall() // Installs from package.json -``` - -###### Implementation of - -`TemplateBuilder`.`npmInstall` - -### pipInstall() - -```ts -pipInstall(packages?: string | string[], options?: object): TemplateBuilder -``` - -Install Python packages using pip. - -###### Parameters - -| Parameter | Type | Description | -| ------ | ------ | ------ | -| `packages`? | `string` \| `string`[] | Package name(s) or undefined for current directory | -| `options`? | `object` | Install options | -| `options.g`? | `boolean` | Install globally as root (default: true). Set to false for user-only installation with --user flag | - -###### Returns - -`TemplateBuilder` - -###### Example - -```ts -template.pipInstall('numpy') // Installs globally (default) -template.pipInstall(['pandas', 'scikit-learn']) -template.pipInstall('numpy', { g: false }) // Install for user only -template.pipInstall() // Installs from current directory -``` - -###### Implementation of - -`TemplateBuilder`.`pipInstall` - -### remove() - -```ts -remove(path: PathLike | PathLike[], options?: object): TemplateBuilder -``` - -Remove files or directories. - -###### Parameters - -| Parameter | Type | Description | -| ------ | ------ | ------ | -| `path` | `PathLike` \| `PathLike`[] | Path(s) to remove | -| `options`? | `object` | Remove options | -| `options.force`? | `boolean` | - | -| `options.recursive`? | `boolean` | - | -| `options.user`? | `string` | - | - -###### Returns - -`TemplateBuilder` - -###### Example - -```ts -template.remove('/tmp/cache', { recursive: true, force: true }) -template.remove('/tmp/cache', { recursive: true, force: true, user: 'root' }) -``` - -###### Implementation of - -`TemplateBuilder`.`remove` - -### rename() - -```ts -rename( - src: PathLike, - dest: PathLike, - options?: object): TemplateBuilder -``` - -Rename or move a file or directory. - -###### Parameters - -| Parameter | Type | Description | -| ------ | ------ | ------ | -| `src` | `PathLike` | Source path | -| `dest` | `PathLike` | Destination path | -| `options`? | `object` | Rename options | -| `options.force`? | `boolean` | - | -| `options.user`? | `string` | - | - -###### Returns - -`TemplateBuilder` - -###### Example - -```ts -template.rename('/tmp/old.txt', '/tmp/new.txt') -template.rename('/tmp/old.txt', '/tmp/new.txt', { user: 'root' }) -``` - -###### Implementation of - -`TemplateBuilder`.`rename` - -### runCmd() - -###### runCmd(command, options) - -```ts -runCmd(command: string, options?: object): TemplateBuilder -``` - -Run a shell command. - -###### Parameters - -| Parameter | Type | Description | -| ------ | ------ | ------ | -| `command` | `string` | Command string | -| `options`? | `object` | Command options | -| `options.user`? | `string` | - | - -###### Returns - -`TemplateBuilder` - -###### Example - -```ts -template.runCmd('apt-get update') -template.runCmd(['pip install numpy', 'pip install pandas']) -template.runCmd('apt-get install vim', { user: 'root' }) -``` - -###### Implementation of - -`TemplateBuilder`.`runCmd` - -###### runCmd(commands, options) - -```ts -runCmd(commands: string[], options?: object): TemplateBuilder -``` - -Run a shell command. - -###### Parameters - -| Parameter | Type | Description | -| ------ | ------ | ------ | -| `commands` | `string`[] | - | -| `options`? | `object` | Command options | -| `options.user`? | `string` | - | - -###### Returns - -`TemplateBuilder` - -###### Example - -```ts -template.runCmd('apt-get update') -template.runCmd(['pip install numpy', 'pip install pandas']) -template.runCmd('apt-get install vim', { user: 'root' }) -``` - -###### Implementation of - -`TemplateBuilder`.`runCmd` - -### setEnvs() - -```ts -setEnvs(envs: Record): TemplateBuilder -``` - -Set environment variables. - -###### Parameters - -| Parameter | Type | Description | -| ------ | ------ | ------ | -| `envs` | `Record`\<`string`, `string`\> | Environment variables | - -###### Returns - -`TemplateBuilder` - -###### Example - -```ts -template.setEnvs({ NODE_ENV: 'production', PORT: '8080' }) -``` - -###### Implementation of - -`TemplateBuilder`.`setEnvs` - -### setReadyCmd() - -```ts -setReadyCmd(readyCommand: string | ReadyCmd): TemplateFinal -``` - -Set or update the ready check command. - -###### Parameters - -| Parameter | Type | Description | -| ------ | ------ | ------ | -| `readyCommand` | `string` \| `ReadyCmd` | Command to check readiness | - -###### Returns - -`TemplateFinal` - -###### Example - -```ts -// Using a string command -template.setReadyCmd('curl http://localhost:8000/health') - -// Using ReadyCmd helpers -import { waitForPort, waitForFile, waitForProcess } from 'e2b' - -template.setReadyCmd(waitForPort(3000)) - -template.setReadyCmd(waitForFile('/tmp/ready')) - -template.setReadyCmd(waitForProcess('nginx')) -``` - -###### Implementation of - -`TemplateBuilder`.`setReadyCmd` - -### setStartCmd() - -```ts -setStartCmd(startCommand: string, readyCommand: string | ReadyCmd): TemplateFinal -``` - -Set the start command and ready check. - -###### Parameters - -| Parameter | Type | Description | -| ------ | ------ | ------ | -| `startCommand` | `string` | Command to run on startup | -| `readyCommand` | `string` \| `ReadyCmd` | Command to check readiness | - -###### Returns - -`TemplateFinal` - -###### Example - -```ts -// Using a string command -template.setStartCmd( - 'node app.js', - 'curl http://localhost:8000/health' -) - -// Using ReadyCmd helpers -import { waitForPort, waitForURL } from 'e2b' - -template.setStartCmd( - 'python -m http.server 8000', - waitForPort(8000) -) - -template.setStartCmd( - 'npm start', - waitForURL('http://localhost:3000/health', 200) -) -``` - -###### Implementation of - -`TemplateBuilder`.`setStartCmd` - -### setUser() - -```ts -setUser(user: string): TemplateBuilder -``` - -Set the user for subsequent commands. - -###### Parameters - -| Parameter | Type | Description | -| ------ | ------ | ------ | -| `user` | `string` | Username | - -###### Returns - -`TemplateBuilder` - -###### Example - -```ts -template.setUser('root') -``` - -###### Implementation of - -`TemplateBuilder`.`setUser` - -### setWorkdir() - -```ts -setWorkdir(workdir: PathLike): TemplateBuilder -``` - -Set the working directory. - -###### Parameters - -| Parameter | Type | Description | -| ------ | ------ | ------ | -| `workdir` | `PathLike` | Working directory path | - -###### Returns - -`TemplateBuilder` - -###### Example - -```ts -template.setWorkdir('/app') -``` - -###### Implementation of - -`TemplateBuilder`.`setWorkdir` - -### skipCache() - -```ts -skipCache(): this -``` - -Skip cache for all subsequent build instructions from this point. - -###### Returns - -`this` - -###### Example - -```ts -Template().skipCache().fromPythonImage('3') -``` - -###### Implementation of - -`TemplateBuilder`.`skipCache` - -### build() - -```ts -static build(template: TemplateClass, options: BuildOptions): Promise -``` - -Build and deploy a template to E2B infrastructure. - -###### Parameters - -| Parameter | Type | Description | -| ------ | ------ | ------ | -| `template` | `TemplateClass` | The template to build | -| `options` | `BuildOptions` | Build configuration options | - -###### Returns - -`Promise`\<`BuildInfo`\> - -###### Example - -```ts -const template = Template().fromPythonImage('3') -await Template.build(template, { - alias: 'my-python-env', - cpuCount: 2, - memoryMB: 1024 -}) -``` - -### buildInBackground() - -```ts -static buildInBackground(template: TemplateClass, options: BuildOptions): Promise -``` - -Build and deploy a template to E2B infrastructure. - -###### Parameters - -| Parameter | Type | Description | -| ------ | ------ | ------ | -| `template` | `TemplateClass` | The template to build | -| `options` | `BuildOptions` | Build configuration options | - -###### Returns - -`Promise`\<`BuildInfo`\> - -###### Example - -```ts -const template = Template().fromPythonImage('3') -const data = await Template.buildInBackground(template, { - alias: 'my-python-env', - cpuCount: 2, - memoryMB: 1024 -}) -``` - -### getBuildStatus() - -```ts -static getBuildStatus(data: Pick, options?: GetBuildStatusOptions): Promise -``` - -Get the status of a build. - -###### Parameters - -| Parameter | Type | Description | -| ------ | ------ | ------ | -| `data` | `Pick`\<`BuildInfo`, `"templateId"` \| `"buildId"`\> | Build identifiers | -| `options`? | `GetBuildStatusOptions` | Authentication options | - -###### Returns - -`Promise`\<`object`\> - -| Name | Type | Description | -| ------ | ------ | ------ | -| `buildID` | `string` | **Description** Identifier of the build | -| `logEntries` | `object`[] | **Description** Build logs structured **Default** `[]` | -| `logs` | `string`[] | **Description** Build logs **Default** `[]` | -| `reason`? | `object` | - | -| `reason.logEntries`? | `object`[] | **Description** Log entries related to the status reason **Default** `[]` | -| `reason.message` | `string` | **Description** Message with the status reason, currently reporting only for error status | -| `reason.step`? | `string` | **Description** Step that failed | -| `status` | `"error"` \| `"ready"` \| `"building"` \| `"waiting"` | - | -| `templateID` | `string` | **Description** Identifier of the template | - -###### Example - -```ts -const status = await Template.getBuildStatus(data, { logsOffset: 0 }) -``` - -### toDockerfile() - -```ts -static toDockerfile(template: TemplateClass): string -``` - -Convert a template to Dockerfile format. -Note: Templates based on other E2B templates cannot be converted to Dockerfile. - -###### Parameters - -| Parameter | Type | Description | -| ------ | ------ | ------ | -| `template` | `TemplateClass` | The template to convert | - -###### Returns - -`string` - -Dockerfile string representation - -###### Throws - -Error if the template is based on another E2B template - -### toJSON() - -```ts -static toJSON(template: TemplateClass, computeHashes: boolean): Promise -``` - -Convert a template to JSON representation. - -###### Parameters - -| Parameter | Type | Default value | Description | -| ------ | ------ | ------ | ------ | -| `template` | `TemplateClass` | `undefined` | The template to convert | -| `computeHashes` | `boolean` | `true` | Whether to compute file hashes for cache invalidation | - -###### Returns - -`Promise`\<`string`\> - -JSON string representation of the template - -## Interfaces - -### TemplateBuilder - -Main builder state for constructing templates. -Provides methods for customizing the template environment. - -#### Methods - -### addMcpServer() - -```ts -addMcpServer(servers: keyof McpServer | keyof McpServer[]): TemplateBuilder -``` - -Install MCP servers using mcp-gateway. -Note: Requires a base image with mcp-gateway pre-installed (e.g., mcp-gateway). - -###### Parameters - -| Parameter | Type | Description | -| ------ | ------ | ------ | -| `servers` | keyof McpServer \| keyof McpServer[] | MCP server name(s) | - -###### Returns - -`TemplateBuilder` - -###### Throws - -If the base template is not mcp-gateway - -###### Example - -```ts -template.addMcpServer('exa') -template.addMcpServer(['brave', 'firecrawl', 'duckduckgo']) -``` - -### aptInstall() - -```ts -aptInstall(packages: string | string[], options?: object): TemplateBuilder -``` - -Install Debian/Ubuntu packages using apt-get. - -###### Parameters - -| Parameter | Type | Description | -| ------ | ------ | ------ | -| `packages` | `string` \| `string`[] | Package name(s) | -| `options`? | `object` | - | -| `options.noInstallRecommends`? | `boolean` | - | - -###### Returns - -`TemplateBuilder` - -###### Example - -```ts -template.aptInstall('vim') -template.aptInstall(['git', 'curl', 'wget']) -template.aptInstall(['vim'], { noInstallRecommends: true }) -``` - -### betaDevContainerPrebuild() - -```ts -betaDevContainerPrebuild(devcontainerDirectory: string): TemplateBuilder -``` - -Prebuild a devcontainer from the specified directory. - -###### Parameters - -| Parameter | Type | Description | -| ------ | ------ | ------ | -| `devcontainerDirectory` | `string` | Path to the devcontainer directory | - -###### Returns - -`TemplateBuilder` - -###### Example - -```ts -template - .gitClone('https://myrepo.com/project.git', '/my-devcontainer') - .betaDevContainerPrebuild('/my-devcontainer') -``` - -### betaSetDevContainerStart() - -```ts -betaSetDevContainerStart(devcontainerDirectory: string): TemplateFinal -``` - -Start a devcontainer from the specified directory. - -###### Parameters - -| Parameter | Type | Description | -| ------ | ------ | ------ | -| `devcontainerDirectory` | `string` | Path to the devcontainer directory | - -###### Returns - -`TemplateFinal` - -###### Example - -```ts -template - .gitClone('https://myrepo.com/project.git', '/my-devcontainer') - .startDevcontainer('/my-devcontainer') - -// Prebuild and start -template - .gitClone('https://myrepo.com/project.git', '/my-devcontainer') - .betaDevContainerPrebuild('/my-devcontainer') - // Other instructions... - .betaSetDevContainerStart('/my-devcontainer') -``` - -### bunInstall() - -```ts -bunInstall(packages?: string | string[], options?: object): TemplateBuilder -``` - -Install Bun packages using bun. - -###### Parameters - -| Parameter | Type | Description | -| ------ | ------ | ------ | -| `packages`? | `string` \| `string`[] | Package name(s) or undefined for package.json | -| `options`? | `object` | Install options | -| `options.dev`? | `boolean` | - | -| `options.g`? | `boolean` | - | - -###### Returns - -`TemplateBuilder` - -###### Example - -```ts -template.bunInstall('express') -template.bunInstall(['lodash', 'axios']) -template.bunInstall('tsx', { g: true }) -template.bunInstall('typescript', { dev: true }) -template.bunInstall() // Installs from package.json -``` - -### copy() - -```ts -copy( - src: PathLike | PathLike[], - dest: PathLike, - options?: object): TemplateBuilder -``` - -Copy files or directories into the template. - -###### Parameters - -| Parameter | Type | Description | -| ------ | ------ | ------ | -| `src` | `PathLike` \| `PathLike`[] | Source path(s) | -| `dest` | `PathLike` | Destination path | -| `options`? | `object` | Copy options | -| `options.forceUpload`? | `true` | - | -| `options.mode`? | `number` | - | -| `options.resolveSymlinks`? | `boolean` | - | -| `options.user`? | `string` | - | - -###### Returns - -`TemplateBuilder` - -###### Example - -```ts -template.copy('requirements.txt', '/home/user/') -template.copy(['app.ts', 'config.ts'], '/app/', { mode: 0o755 }) -``` - -### copyItems() - -```ts -copyItems(items: CopyItem[]): TemplateBuilder -``` - -Copy multiple items with individual options. - -###### Parameters - -| Parameter | Type | Description | -| ------ | ------ | ------ | -| `items` | `CopyItem`[] | Array of copy items | - -###### Returns - -`TemplateBuilder` - -###### Example - -```ts -template.copyItems([ - { src: 'app.ts', dest: '/app/' }, - { src: 'config.ts', dest: '/app/', mode: 0o644 } -]) -``` - -### gitClone() - -```ts -gitClone( - url: string, - path?: PathLike, - options?: object): TemplateBuilder -``` - -Clone a Git repository. - -###### Parameters - -| Parameter | Type | Description | -| ------ | ------ | ------ | -| `url` | `string` | Repository URL | -| `path`? | `PathLike` | Optional destination path | -| `options`? | `object` | Clone options | -| `options.branch`? | `string` | - | -| `options.depth`? | `number` | - | -| `options.user`? | `string` | - | - -###### Returns - -`TemplateBuilder` - -###### Example - -```ts -template.gitClone('https://github.com/user/repo.git', '/app/repo') -template.gitClone('https://github.com/user/repo.git', undefined, { - branch: 'main', - depth: 1 -}) -template.gitClone('https://github.com/user/repo.git', '/app/repo', { - user: 'root' -}) -``` - -### makeDir() - -```ts -makeDir(path: PathLike | PathLike[], options?: object): TemplateBuilder -``` - -Create directories. - -###### Parameters - -| Parameter | Type | Description | -| ------ | ------ | ------ | -| `path` | `PathLike` \| `PathLike`[] | Directory path(s) | -| `options`? | `object` | Directory options | -| `options.mode`? | `number` | - | -| `options.user`? | `string` | - | - -###### Returns - -`TemplateBuilder` - -###### Example - -```ts -template.makeDir('/app/data', { mode: 0o755 }) -template.makeDir(['/app/logs', '/app/cache']) -template.makeDir('/app/data', { mode: 0o755, user: 'root' }) -``` - -### makeSymlink() - -```ts -makeSymlink( - src: PathLike, - dest: PathLike, - options?: object): TemplateBuilder -``` - -Create a symbolic link. - -###### Parameters - -| Parameter | Type | Description | -| ------ | ------ | ------ | -| `src` | `PathLike` | Source path (target) | -| `dest` | `PathLike` | Destination path (symlink location) | -| `options`? | `object` | Symlink options | -| `options.force`? | `boolean` | - | -| `options.user`? | `string` | - | - -###### Returns - -`TemplateBuilder` - -###### Example - -```ts -template.makeSymlink('/usr/bin/python3', '/usr/bin/python') -template.makeSymlink('/usr/bin/python3', '/usr/bin/python', { user: 'root' }) -template.makeSymlink('/usr/bin/python3', '/usr/bin/python', { force: true }) -``` - -### npmInstall() - -```ts -npmInstall(packages?: string | string[], options?: object): TemplateBuilder -``` - -Install Node.js packages using npm. - -###### Parameters - -| Parameter | Type | Description | -| ------ | ------ | ------ | -| `packages`? | `string` \| `string`[] | Package name(s) or undefined for package.json | -| `options`? | `object` | Install options | -| `options.dev`? | `boolean` | - | -| `options.g`? | `boolean` | - | - -###### Returns - -`TemplateBuilder` - -###### Example - -```ts -template.npmInstall('express') -template.npmInstall(['lodash', 'axios']) -template.npmInstall('tsx', { g: true }) -template.npmInstall('typescript', { dev: true }) -template.npmInstall() // Installs from package.json -``` - -### pipInstall() - -```ts -pipInstall(packages?: string | string[], options?: object): TemplateBuilder -``` - -Install Python packages using pip. - -###### Parameters - -| Parameter | Type | Description | -| ------ | ------ | ------ | -| `packages`? | `string` \| `string`[] | Package name(s) or undefined for current directory | -| `options`? | `object` | Install options | -| `options.g`? | `boolean` | Install globally as root (default: true). Set to false for user-only installation with --user flag | - -###### Returns - -`TemplateBuilder` - -###### Example - -```ts -template.pipInstall('numpy') // Installs globally (default) -template.pipInstall(['pandas', 'scikit-learn']) -template.pipInstall('numpy', { g: false }) // Install for user only -template.pipInstall() // Installs from current directory -``` - -### remove() - -```ts -remove(path: PathLike | PathLike[], options?: object): TemplateBuilder -``` - -Remove files or directories. - -###### Parameters - -| Parameter | Type | Description | -| ------ | ------ | ------ | -| `path` | `PathLike` \| `PathLike`[] | Path(s) to remove | -| `options`? | `object` | Remove options | -| `options.force`? | `boolean` | - | -| `options.recursive`? | `boolean` | - | -| `options.user`? | `string` | - | - -###### Returns - -`TemplateBuilder` - -###### Example - -```ts -template.remove('/tmp/cache', { recursive: true, force: true }) -template.remove('/tmp/cache', { recursive: true, force: true, user: 'root' }) -``` - -### rename() - -```ts -rename( - src: PathLike, - dest: PathLike, - options?: object): TemplateBuilder -``` - -Rename or move a file or directory. - -###### Parameters - -| Parameter | Type | Description | -| ------ | ------ | ------ | -| `src` | `PathLike` | Source path | -| `dest` | `PathLike` | Destination path | -| `options`? | `object` | Rename options | -| `options.force`? | `boolean` | - | -| `options.user`? | `string` | - | - -###### Returns - -`TemplateBuilder` - -###### Example - -```ts -template.rename('/tmp/old.txt', '/tmp/new.txt') -template.rename('/tmp/old.txt', '/tmp/new.txt', { user: 'root' }) -``` - -### runCmd() - -###### runCmd(command, options) - -```ts -runCmd(command: string, options?: object): TemplateBuilder -``` - -Run a shell command. - -###### Parameters - -| Parameter | Type | Description | -| ------ | ------ | ------ | -| `command` | `string` | Command string | -| `options`? | `object` | Command options | -| `options.user`? | `string` | - | - -###### Returns - -`TemplateBuilder` - -###### Example - -```ts -template.runCmd('apt-get update') -template.runCmd(['pip install numpy', 'pip install pandas']) -template.runCmd('apt-get install vim', { user: 'root' }) -``` - -###### runCmd(commands, options) - -```ts -runCmd(commands: string[], options?: object): TemplateBuilder -``` - -Run multiple shell commands. - -###### Parameters - -| Parameter | Type | Description | -| ------ | ------ | ------ | -| `commands` | `string`[] | Array of command strings | -| `options`? | `object` | Command options | -| `options.user`? | `string` | - | - -###### Returns - -`TemplateBuilder` - -###### runCmd(commandOrCommands, options) - -```ts -runCmd(commandOrCommands: string | string[], options?: object): TemplateBuilder -``` - -Run command(s). - -###### Parameters - -| Parameter | Type | Description | -| ------ | ------ | ------ | -| `commandOrCommands` | `string` \| `string`[] | Command or commands | -| `options`? | `object` | Command options | -| `options.user`? | `string` | - | - -###### Returns - -`TemplateBuilder` - -### setEnvs() - -```ts -setEnvs(envs: Record): TemplateBuilder -``` - -Set environment variables. - -###### Parameters - -| Parameter | Type | Description | -| ------ | ------ | ------ | -| `envs` | `Record`\<`string`, `string`\> | Environment variables | - -###### Returns - -`TemplateBuilder` - -###### Example - -```ts -template.setEnvs({ NODE_ENV: 'production', PORT: '8080' }) -``` - -### setReadyCmd() - -```ts -setReadyCmd(readyCommand: string | ReadyCmd): TemplateFinal -``` - -Set or update the ready check command. - -###### Parameters - -| Parameter | Type | Description | -| ------ | ------ | ------ | -| `readyCommand` | `string` \| `ReadyCmd` | Command to check readiness | - -###### Returns - -`TemplateFinal` - -###### Example - -```ts -// Using a string command -template.setReadyCmd('curl http://localhost:8000/health') - -// Using ReadyCmd helpers -import { waitForPort, waitForFile, waitForProcess } from 'e2b' - -template.setReadyCmd(waitForPort(3000)) - -template.setReadyCmd(waitForFile('/tmp/ready')) - -template.setReadyCmd(waitForProcess('nginx')) -``` - -### setStartCmd() - -```ts -setStartCmd(startCommand: string, readyCommand: string | ReadyCmd): TemplateFinal -``` - -Set the start command and ready check. - -###### Parameters - -| Parameter | Type | Description | -| ------ | ------ | ------ | -| `startCommand` | `string` | Command to run on startup | -| `readyCommand` | `string` \| `ReadyCmd` | Command to check readiness | - -###### Returns - -`TemplateFinal` - -###### Example - -```ts -// Using a string command -template.setStartCmd( - 'node app.js', - 'curl http://localhost:8000/health' -) - -// Using ReadyCmd helpers -import { waitForPort, waitForURL } from 'e2b' - -template.setStartCmd( - 'python -m http.server 8000', - waitForPort(8000) -) - -template.setStartCmd( - 'npm start', - waitForURL('http://localhost:3000/health', 200) -) -``` - -### setUser() - -```ts -setUser(user: string): TemplateBuilder -``` - -Set the user for subsequent commands. - -###### Parameters - -| Parameter | Type | Description | -| ------ | ------ | ------ | -| `user` | `string` | Username | - -###### Returns - -`TemplateBuilder` - -###### Example - -```ts -template.setUser('root') -``` - -### setWorkdir() - -```ts -setWorkdir(workdir: PathLike): TemplateBuilder -``` - -Set the working directory. - -###### Parameters - -| Parameter | Type | Description | -| ------ | ------ | ------ | -| `workdir` | `PathLike` | Working directory path | - -###### Returns - -`TemplateBuilder` - -###### Example - -```ts -template.setWorkdir('/app') -``` - -### skipCache() - -```ts -skipCache(): this -``` - -Skip cache for all subsequent build instructions from this point. - -###### Returns - -`this` - -###### Example - -```ts -template.skipCache().runCmd('apt-get update') -``` - -## Type Aliases - -### BuildInfo - -```ts -type BuildInfo: object; -``` - -Information about a built template. - -#### Type declaration - -| Name | Type | -| ------ | ------ | -| `alias` | `string` | -| `buildId` | `string` | -| `templateId` | `string` | - -*** - -### BuildOptions - -```ts -type BuildOptions: AuthOptions & BasicBuildOptions; -``` - -Options for building a template with authentication. - -*** - -### CopyItem - -```ts -type CopyItem: object; -``` - -Configuration for a single file/directory copy operation. - -#### Type declaration - -| Name | Type | -| ------ | ------ | -| `dest` | `PathLike` | -| `forceUpload`? | `true` | -| `mode`? | `number` | -| `resolveSymlinks`? | `boolean` | -| `src` | `PathLike` \| `PathLike`[] | -| `user`? | `string` | - -*** - -### GetBuildStatusOptions - -```ts -type GetBuildStatusOptions: AuthOptions & object; -``` - -Response from getting build status. - -#### Type declaration - -| Name | Type | -| ------ | ------ | -| `logsOffset`? | `number` | - -*** - -### McpServerName - -```ts -type McpServerName: keyof McpServer; -``` - -MCP server names that can be installed. - -*** - -### TemplateClass - -```ts -type TemplateClass: TemplateBuilder | TemplateFinal; -``` - -Type representing a template in any state (builder or final). - -## Functions - -### Template() - -```ts -function Template(options?: TemplateOptions): TemplateFromImage -``` - -Create a new E2B template builder instance. - -#### Parameters - -| Parameter | Type | Description | -| ------ | ------ | ------ | -| `options`? | `TemplateOptions` | Optional configuration for the template builder | - -#### Returns - -`TemplateFromImage` - -A new template builder instance - -#### Example - -```ts -import { Template } from 'e2b' - -const template = Template() - .fromPythonImage('3') - .copy('requirements.txt', '/app/') - .pipInstall() - -await Template.build(template, { alias: 'my-python-app' }) -``` diff --git a/docs/sdk-reference/js-sdk/v2.8.4/errors.mdx b/docs/sdk-reference/js-sdk/v2.8.4/errors.mdx deleted file mode 100644 index bfe0deb..0000000 --- a/docs/sdk-reference/js-sdk/v2.8.4/errors.mdx +++ /dev/null @@ -1,271 +0,0 @@ ---- -sidebarTitle: "Errors" -mode: "center" ---- - -### AuthenticationError - -Thrown when authentication fails. - -#### Constructors - -```ts -new AuthenticationError(message: string): AuthenticationError -``` - -###### Parameters - -| Parameter | Type | -| ------ | ------ | -| `message` | `string` | - -###### Returns - -`AuthenticationError` - -*** - -### BuildError - -Thrown when the build fails. - -#### Extended by - -- `FileUploadError` - -#### Constructors - -```ts -new BuildError(message: string, stackTrace?: string): BuildError -``` - -###### Parameters - -| Parameter | Type | -| ------ | ------ | -| `message` | `string` | -| `stackTrace`? | `string` | - -###### Returns - -`BuildError` - -*** - -### FileUploadError - -Thrown when the file upload fails. - -#### Constructors - -```ts -new FileUploadError(message: string, stackTrace?: string): FileUploadError -``` - -###### Parameters - -| Parameter | Type | -| ------ | ------ | -| `message` | `string` | -| `stackTrace`? | `string` | - -###### Returns - -`FileUploadError` - -*** - -### InvalidArgumentError - -Thrown when an invalid argument is provided. - -#### Constructors - -```ts -new InvalidArgumentError(message: string, stackTrace?: string): InvalidArgumentError -``` - -###### Parameters - -| Parameter | Type | -| ------ | ------ | -| `message` | `string` | -| `stackTrace`? | `string` | - -###### Returns - -`InvalidArgumentError` - -*** - -### NotEnoughSpaceError - -Thrown when there is not enough disk space. - -#### Constructors - -```ts -new NotEnoughSpaceError(message: string, stackTrace?: string): NotEnoughSpaceError -``` - -###### Parameters - -| Parameter | Type | -| ------ | ------ | -| `message` | `string` | -| `stackTrace`? | `string` | - -###### Returns - -`NotEnoughSpaceError` - -*** - -### NotFoundError - -Thrown when a resource is not found. - -#### Constructors - -```ts -new NotFoundError(message: string, stackTrace?: string): NotFoundError -``` - -###### Parameters - -| Parameter | Type | -| ------ | ------ | -| `message` | `string` | -| `stackTrace`? | `string` | - -###### Returns - -`NotFoundError` - -*** - -### RateLimitError - -Thrown when the API rate limit is exceeded. - -#### Constructors - -```ts -new RateLimitError(message: string): RateLimitError -``` - -###### Parameters - -| Parameter | Type | -| ------ | ------ | -| `message` | `string` | - -###### Returns - -`RateLimitError` - -*** - -### SandboxError - -Base class for all sandbox errors. - -Thrown when general sandbox errors occur. - -#### Extended by - -- `TimeoutError` -- `InvalidArgumentError` -- `NotEnoughSpaceError` -- `NotFoundError` -- `TemplateError` -- `RateLimitError` - -#### Constructors - -```ts -new SandboxError(message?: string, stackTrace?: string): SandboxError -``` - -###### Parameters - -| Parameter | Type | -| ------ | ------ | -| `message`? | `string` | -| `stackTrace`? | `string` | - -###### Returns - -`SandboxError` - -*** - -### TemplateError - -Thrown when the template uses old envd version. It isn't compatible with the new SDK. - -#### Constructors - -```ts -new TemplateError(message: string, stackTrace?: string): TemplateError -``` - -###### Parameters - -| Parameter | Type | -| ------ | ------ | -| `message` | `string` | -| `stackTrace`? | `string` | - -###### Returns - -`TemplateError` - -*** - -### TimeoutError - -Thrown when a timeout error occurs. - -The [unavailable] error type is caused by sandbox timeout. - -The [canceled] error type is caused by exceeding request timeout. - -The [deadline_exceeded] error type is caused by exceeding the timeout for command execution, watch, etc. - -The [unknown] error type is sometimes caused by the sandbox timeout when the request is not processed correctly. - -#### Constructors - -```ts -new TimeoutError(message: string, stackTrace?: string): TimeoutError -``` - -###### Parameters - -| Parameter | Type | -| ------ | ------ | -| `message` | `string` | -| `stackTrace`? | `string` | - -###### Returns - -`TimeoutError` - -## Functions - -### formatSandboxTimeoutError() - -```ts -function formatSandboxTimeoutError(message: string): TimeoutError -``` - -#### Parameters - -| Parameter | Type | -| ------ | ------ | -| `message` | `string` | - -#### Returns - -`TimeoutError` diff --git a/docs/sdk-reference/js-sdk/v2.8.4/sandbox-commands.mdx b/docs/sdk-reference/js-sdk/v2.8.4/sandbox-commands.mdx deleted file mode 100644 index 16d736c..0000000 --- a/docs/sdk-reference/js-sdk/v2.8.4/sandbox-commands.mdx +++ /dev/null @@ -1,533 +0,0 @@ ---- -sidebarTitle: "Commands" -mode: "center" ---- - -### Commands - -Module for starting and interacting with commands in the sandbox. - -#### Constructors - -```ts -new Commands( - transport: Transport, - connectionConfig: ConnectionConfig, - metadata: object): Commands -``` - -###### Parameters - -| Parameter | Type | -| ------ | ------ | -| `transport` | `Transport` | -| `connectionConfig` | `ConnectionConfig` | -| `metadata` | `object` | -| `metadata.version` | `string` | - -###### Returns - -`Commands` - -#### Methods - -### connect() - -```ts -connect(pid: number, opts?: CommandConnectOpts): Promise -``` - -Connect to a running command. -You can use CommandHandle.wait to wait for the command to finish and get execution results. - -###### Parameters - -| Parameter | Type | Description | -| ------ | ------ | ------ | -| `pid` | `number` | process ID of the command to connect to. You can get the list of running commands using Commands.list. | -| `opts`? | `CommandConnectOpts` | connection options. | - -###### Returns - -`Promise`\<`CommandHandle`\> - -`CommandHandle` handle to interact with the running command. - -### kill() - -```ts -kill(pid: number, opts?: CommandRequestOpts): Promise -``` - -Kill a running command specified by its process ID. -It uses `SIGKILL` signal to kill the command. - -###### Parameters - -| Parameter | Type | Description | -| ------ | ------ | ------ | -| `pid` | `number` | process ID of the command. You can get the list of running commands using Commands.list. | -| `opts`? | `CommandRequestOpts` | connection options. | - -###### Returns - -`Promise`\<`boolean`\> - -`true` if the command was killed, `false` if the command was not found. - -### list() - -```ts -list(opts?: CommandRequestOpts): Promise -``` - -List all running commands and PTY sessions. - -###### Parameters - -| Parameter | Type | Description | -| ------ | ------ | ------ | -| `opts`? | `CommandRequestOpts` | connection options. | - -###### Returns - -`Promise`\<`ProcessInfo`[]\> - -list of running commands and PTY sessions. - -### run() - -###### run(cmd, opts) - -```ts -run(cmd: string, opts?: CommandStartOpts & object): Promise -``` - -Start a new command and wait until it finishes executing. - -###### Parameters - -| Parameter | Type | Description | -| ------ | ------ | ------ | -| `cmd` | `string` | command to execute. | -| `opts`? | `CommandStartOpts` & `object` | options for starting the command. | - -###### Returns - -`Promise`\<`CommandResult`\> - -`CommandResult` result of the command execution. - -###### run(cmd, opts) - -```ts -run(cmd: string, opts: CommandStartOpts & object): Promise -``` - -Start a new command in the background. -You can use CommandHandle.wait to wait for the command to finish and get its result. - -###### Parameters - -| Parameter | Type | Description | -| ------ | ------ | ------ | -| `cmd` | `string` | command to execute. | -| `opts` | `CommandStartOpts` & `object` | options for starting the command | - -###### Returns - -`Promise`\<`CommandHandle`\> - -`CommandHandle` handle to interact with the running command. - -###### run(cmd, opts) - -```ts -run(cmd: string, opts?: CommandStartOpts & object): Promise -``` - -Start a new command. - -###### Parameters - -| Parameter | Type | Description | -| ------ | ------ | ------ | -| `cmd` | `string` | command to execute. | -| `opts`? | `CommandStartOpts` & `object` | options for starting the command. - `opts.background: true` - runs in background, returns `CommandHandle` - `opts.background: false | undefined` - waits for completion, returns `CommandResult` | - -###### Returns - -`Promise`\<`CommandResult` \| `CommandHandle`\> - -Either a `CommandHandle` or a `CommandResult` (depending on `opts.background`). - -### sendStdin() - -```ts -sendStdin( - pid: number, - data: string, -opts?: CommandRequestOpts): Promise -``` - -Send data to command stdin. - -###### Parameters - -| Parameter | Type | Description | -| ------ | ------ | ------ | -| `pid` | `number` | process ID of the command. You can get the list of running commands using Commands.list. | -| `data` | `string` | data to send to the command. | -| `opts`? | `CommandRequestOpts` | connection options. | - -###### Returns - -`Promise`\<`void`\> - -*** - -### Pty - -Module for interacting with PTYs (pseudo-terminals) in the sandbox. - -#### Constructors - -```ts -new Pty( - transport: Transport, - connectionConfig: ConnectionConfig, - metadata: object): Pty -``` - -###### Parameters - -| Parameter | Type | -| ------ | ------ | -| `transport` | `Transport` | -| `connectionConfig` | `ConnectionConfig` | -| `metadata` | `object` | -| `metadata.version` | `string` | - -###### Returns - -`Pty` - -#### Methods - -### create() - -```ts -create(opts: PtyCreateOpts): Promise -``` - -Create a new PTY (pseudo-terminal). - -###### Parameters - -| Parameter | Type | Description | -| ------ | ------ | ------ | -| `opts` | `PtyCreateOpts` | options for creating the PTY. | - -###### Returns - -`Promise`\<`CommandHandle`\> - -handle to interact with the PTY. - -### kill() - -```ts -kill(pid: number, opts?: Pick): Promise -``` - -Kill a running PTY specified by process ID. -It uses `SIGKILL` signal to kill the PTY. - -###### Parameters - -| Parameter | Type | Description | -| ------ | ------ | ------ | -| `pid` | `number` | process ID of the PTY. | -| `opts`? | `Pick`\<`ConnectionOpts`, `"requestTimeoutMs"`\> | connection options. | - -###### Returns - -`Promise`\<`boolean`\> - -`true` if the PTY was killed, `false` if the PTY was not found. - -### resize() - -```ts -resize( - pid: number, - size: object, -opts?: Pick): Promise -``` - -Resize PTY. -Call this when the terminal window is resized and the number of columns and rows has changed. - -###### Parameters - -| Parameter | Type | Description | -| ------ | ------ | ------ | -| `pid` | `number` | process ID of the PTY. | -| `size` | `object` | new size of the PTY. | -| `size.cols` | `number` | - | -| `size.rows`? | `number` | - | -| `opts`? | `Pick`\<`ConnectionOpts`, `"requestTimeoutMs"`\> | connection options. | - -###### Returns - -`Promise`\<`void`\> - -### sendInput() - -```ts -sendInput( - pid: number, - data: Uint8Array, -opts?: Pick): Promise -``` - -Send input to a PTY. - -###### Parameters - -| Parameter | Type | Description | -| ------ | ------ | ------ | -| `pid` | `number` | process ID of the PTY. | -| `data` | `Uint8Array` | input data to send to the PTY. | -| `opts`? | `Pick`\<`ConnectionOpts`, `"requestTimeoutMs"`\> | connection options. | - -###### Returns - -`Promise`\<`void`\> - -## Interfaces - -### CommandRequestOpts - -Options for sending a command request. - -#### Extended by - -- `CommandStartOpts` - -#### Properties - -### requestTimeoutMs? - -```ts -optional requestTimeoutMs: number; -``` - -Timeout for requests to the API in **milliseconds**. - -###### Default - -```ts -60_000 // 60 seconds -``` - -*** - -### CommandStartOpts - -Options for starting a new command. - -#### Properties - -### background? - -```ts -optional background: boolean; -``` - -If true, starts command in the background and the method returns immediately. -You can use CommandHandle.wait to wait for the command to finish. - -### cwd? - -```ts -optional cwd: string; -``` - -Working directory for the command. - -###### Default - -```ts -// home directory of the user used to start the command -``` - -### envs? - -```ts -optional envs: Record; -``` - -Environment variables used for the command. - -This overrides the default environment variables from `Sandbox` constructor. - -###### Default - -`{}` - -### onStderr()? - -```ts -optional onStderr: (data: string) => void | Promise; -``` - -Callback for command stderr output. - -###### Parameters - -| Parameter | Type | -| ------ | ------ | -| `data` | `string` | - -###### Returns - -`void` \| `Promise`\<`void`\> - -### onStdout()? - -```ts -optional onStdout: (data: string) => void | Promise; -``` - -Callback for command stdout output. - -###### Parameters - -| Parameter | Type | -| ------ | ------ | -| `data` | `string` | - -###### Returns - -`void` \| `Promise`\<`void`\> - -### requestTimeoutMs? - -```ts -optional requestTimeoutMs: number; -``` - -Timeout for requests to the API in **milliseconds**. - -###### Default - -```ts -60_000 // 60 seconds -``` - -### stdin? - -```ts -optional stdin: boolean; -``` - -If true, command stdin is kept open and you can send data to it using Commands.sendStdin or CommandHandle.sendStdin. - -###### Default - -```ts -false -``` - -### timeoutMs? - -```ts -optional timeoutMs: number; -``` - -Timeout for the command in **milliseconds**. - -###### Default - -```ts -60_000 // 60 seconds -``` - -### user? - -```ts -optional user: string; -``` - -User to run the command as. - -###### Default - -`default Sandbox user (as specified in the template)` - -*** - -### ProcessInfo - -Information about a command, PTY session or start command running in the sandbox as process. - -#### Properties - -### args - -```ts -args: string[]; -``` - -Command arguments. - -### cmd - -```ts -cmd: string; -``` - -Command that was executed. - -### cwd? - -```ts -optional cwd: string; -``` - -Executed command working directory. - -### envs - -```ts -envs: Record; -``` - -Environment variables used for the command. - -### pid - -```ts -pid: number; -``` - -Process ID. - -### tag? - -```ts -optional tag: string; -``` - -Custom tag used for identifying special commands like start command in the custom template. - -## Type Aliases - -### CommandConnectOpts - -```ts -type CommandConnectOpts: Pick & CommandRequestOpts; -``` - -Options for connecting to a command. diff --git a/docs/sdk-reference/js-sdk/v2.8.4/sandbox-filesystem.mdx b/docs/sdk-reference/js-sdk/v2.8.4/sandbox-filesystem.mdx deleted file mode 100644 index c43ac2f..0000000 --- a/docs/sdk-reference/js-sdk/v2.8.4/sandbox-filesystem.mdx +++ /dev/null @@ -1,627 +0,0 @@ ---- -sidebarTitle: "Filesystem" -mode: "center" ---- - -### FileType - -Sandbox filesystem object type. - -#### Enumeration Members - -| Enumeration Member | Value | Description | -| ------ | ------ | ------ | -| `DIR` | `"dir"` | Filesystem object is a directory. | -| `FILE` | `"file"` | Filesystem object is a file. | - -## Classes - -### Filesystem - -Module for interacting with the sandbox filesystem. - -#### Constructors - -```ts -new Filesystem( - transport: Transport, - envdApi: EnvdApiClient, - connectionConfig: ConnectionConfig): Filesystem -``` - -###### Parameters - -| Parameter | Type | -| ------ | ------ | -| `transport` | `Transport` | -| `envdApi` | `EnvdApiClient` | -| `connectionConfig` | `ConnectionConfig` | - -###### Returns - -`Filesystem` - -#### Methods - -### exists() - -```ts -exists(path: string, opts?: FilesystemRequestOpts): Promise -``` - -Check if a file or a directory exists. - -###### Parameters - -| Parameter | Type | Description | -| ------ | ------ | ------ | -| `path` | `string` | path to a file or a directory | -| `opts`? | `FilesystemRequestOpts` | connection options. | - -###### Returns - -`Promise`\<`boolean`\> - -`true` if the file or directory exists, `false` otherwise - -### getInfo() - -```ts -getInfo(path: string, opts?: FilesystemRequestOpts): Promise -``` - -Get information about a file or directory. - -###### Parameters - -| Parameter | Type | Description | -| ------ | ------ | ------ | -| `path` | `string` | path to a file or directory. | -| `opts`? | `FilesystemRequestOpts` | connection options. | - -###### Returns - -`Promise`\<`EntryInfo`\> - -information about the file or directory like name, type, and path. - -### list() - -```ts -list(path: string, opts?: FilesystemListOpts): Promise -``` - -List entries in a directory. - -###### Parameters - -| Parameter | Type | Description | -| ------ | ------ | ------ | -| `path` | `string` | path to the directory. | -| `opts`? | `FilesystemListOpts` | connection options. | - -###### Returns - -`Promise`\<`EntryInfo`[]\> - -list of entries in the sandbox filesystem directory. - -### makeDir() - -```ts -makeDir(path: string, opts?: FilesystemRequestOpts): Promise -``` - -Create a new directory and all directories along the way if needed on the specified path. - -###### Parameters - -| Parameter | Type | Description | -| ------ | ------ | ------ | -| `path` | `string` | path to a new directory. For example '/dirA/dirB' when creating 'dirB'. | -| `opts`? | `FilesystemRequestOpts` | connection options. | - -###### Returns - -`Promise`\<`boolean`\> - -`true` if the directory was created, `false` if it already exists. - -### read() - -###### read(path, opts) - -```ts -read(path: string, opts?: FilesystemRequestOpts & object): Promise -``` - -Read file content as a `string`. - -You can pass `text`, `bytes`, `blob`, or `stream` to `opts.format` to change the return type. - -###### Parameters - -| Parameter | Type | Description | -| ------ | ------ | ------ | -| `path` | `string` | path to the file. | -| `opts`? | `FilesystemRequestOpts` & `object` | connection options. | - -###### Returns - -`Promise`\<`string`\> - -file content as string - -###### read(path, opts) - -```ts -read(path: string, opts?: FilesystemRequestOpts & object): Promise -``` - -Read file content as a `Uint8Array`. - -You can pass `text`, `bytes`, `blob`, or `stream` to `opts.format` to change the return type. - -###### Parameters - -| Parameter | Type | Description | -| ------ | ------ | ------ | -| `path` | `string` | path to the file. | -| `opts`? | `FilesystemRequestOpts` & `object` | connection options. | - -###### Returns - -`Promise`\<`Uint8Array`\> - -file content as `Uint8Array` - -###### read(path, opts) - -```ts -read(path: string, opts?: FilesystemRequestOpts & object): Promise -``` - -Read file content as a `Blob`. - -You can pass `text`, `bytes`, `blob`, or `stream` to `opts.format` to change the return type. - -###### Parameters - -| Parameter | Type | Description | -| ------ | ------ | ------ | -| `path` | `string` | path to the file. | -| `opts`? | `FilesystemRequestOpts` & `object` | connection options. | - -###### Returns - -`Promise`\<`Blob`\> - -file content as `Blob` - -###### read(path, opts) - -```ts -read(path: string, opts?: FilesystemRequestOpts & object): Promise> -``` - -Read file content as a `ReadableStream`. - -You can pass `text`, `bytes`, `blob`, or `stream` to `opts.format` to change the return type. - -###### Parameters - -| Parameter | Type | Description | -| ------ | ------ | ------ | -| `path` | `string` | path to the file. | -| `opts`? | `FilesystemRequestOpts` & `object` | connection options. | - -###### Returns - -`Promise`\<`ReadableStream`\<`Uint8Array`\>\> - -file content as `ReadableStream` - -### remove() - -```ts -remove(path: string, opts?: FilesystemRequestOpts): Promise -``` - -Remove a file or directory. - -###### Parameters - -| Parameter | Type | Description | -| ------ | ------ | ------ | -| `path` | `string` | path to a file or directory. | -| `opts`? | `FilesystemRequestOpts` | connection options. | - -###### Returns - -`Promise`\<`void`\> - -### rename() - -```ts -rename( - oldPath: string, - newPath: string, -opts?: FilesystemRequestOpts): Promise -``` - -Rename a file or directory. - -###### Parameters - -| Parameter | Type | Description | -| ------ | ------ | ------ | -| `oldPath` | `string` | path to the file or directory to rename. | -| `newPath` | `string` | new path for the file or directory. | -| `opts`? | `FilesystemRequestOpts` | connection options. | - -###### Returns - -`Promise`\<`EntryInfo`\> - -information about renamed file or directory. - -### watchDir() - -```ts -watchDir( - path: string, - onEvent: (event: FilesystemEvent) => void | Promise, -opts?: WatchOpts & object): Promise -``` - -Start watching a directory for filesystem events. - -###### Parameters - -| Parameter | Type | Description | -| ------ | ------ | ------ | -| `path` | `string` | path to directory to watch. | -| `onEvent` | (`event`: `FilesystemEvent`) => `void` \| `Promise`\<`void`\> | callback to call when an event in the directory occurs. | -| `opts`? | `WatchOpts` & `object` | connection options. | - -###### Returns - -`Promise`\<`WatchHandle`\> - -`WatchHandle` object for stopping watching directory. - -### write() - -###### write(path, data, opts) - -```ts -write( - path: string, - data: string | ArrayBuffer | Blob | ReadableStream, -opts?: FilesystemRequestOpts): Promise -``` - -Write content to a file. - -Writing to a file that doesn't exist creates the file. - -Writing to a file that already exists overwrites the file. - -Writing to a file at path that doesn't exist creates the necessary directories. - -###### Parameters - -| Parameter | Type | Description | -| ------ | ------ | ------ | -| `path` | `string` | path to file. | -| `data` | `string` \| `ArrayBuffer` \| `Blob` \| `ReadableStream`\<`any`\> | data to write to the file. Data can be a string, `ArrayBuffer`, `Blob`, or `ReadableStream`. | -| `opts`? | `FilesystemRequestOpts` | connection options. | - -###### Returns - -`Promise`\<`WriteInfo`\> - -information about the written file - -###### write(files, opts) - -```ts -write(files: WriteEntry[], opts?: FilesystemRequestOpts): Promise -``` - -###### Parameters - -| Parameter | Type | -| ------ | ------ | -| `files` | `WriteEntry`[] | -| `opts`? | `FilesystemRequestOpts` | - -###### Returns - -`Promise`\<`WriteInfo`[]\> - -## Interfaces - -### EntryInfo - -Sandbox filesystem object information. - -#### Properties - -### group - -```ts -group: string; -``` - -Group owner of the filesystem object. - -### mode - -```ts -mode: number; -``` - -File mode and permission bits. - -### modifiedTime? - -```ts -optional modifiedTime: Date; -``` - -Last modification time of the filesystem object. - -### name - -```ts -name: string; -``` - -Name of the filesystem object. - -### owner - -```ts -owner: string; -``` - -Owner of the filesystem object. - -### path - -```ts -path: string; -``` - -Path to the filesystem object. - -### permissions - -```ts -permissions: string; -``` - -String representation of file permissions (e.g. 'rwxr-xr-x'). - -### size - -```ts -size: number; -``` - -Size of the filesystem object in bytes. - -### symlinkTarget? - -```ts -optional symlinkTarget: string; -``` - -If the filesystem object is a symlink, this is the target of the symlink. - -### type? - -```ts -optional type: FileType; -``` - -Type of the filesystem object. - -*** - -### FilesystemListOpts - -Options for the sandbox filesystem operations. - -#### Properties - -### depth? - -```ts -optional depth: number; -``` - -Depth of the directory to list. - -### requestTimeoutMs? - -```ts -optional requestTimeoutMs: number; -``` - -Timeout for requests to the API in **milliseconds**. - -###### Default - -```ts -60_000 // 60 seconds -``` - -### user? - -```ts -optional user: string; -``` - -User to use for the operation in the sandbox. -This affects the resolution of relative paths and ownership of the created filesystem objects. - -*** - -### FilesystemRequestOpts - -Options for the sandbox filesystem operations. - -#### Extended by - -- `FilesystemListOpts` -- `WatchOpts` - -#### Properties - -### requestTimeoutMs? - -```ts -optional requestTimeoutMs: number; -``` - -Timeout for requests to the API in **milliseconds**. - -###### Default - -```ts -60_000 // 60 seconds -``` - -### user? - -```ts -optional user: string; -``` - -User to use for the operation in the sandbox. -This affects the resolution of relative paths and ownership of the created filesystem objects. - -*** - -### WatchOpts - -Options for watching a directory. - -#### Properties - -### onExit()? - -```ts -optional onExit: (err?: Error) => void | Promise; -``` - -Callback to call when the watch operation stops. - -###### Parameters - -| Parameter | Type | -| ------ | ------ | -| `err`? | `Error` | - -###### Returns - -`void` \| `Promise`\<`void`\> - -### recursive? - -```ts -optional recursive: boolean; -``` - -Watch the directory recursively - -### requestTimeoutMs? - -```ts -optional requestTimeoutMs: number; -``` - -Timeout for requests to the API in **milliseconds**. - -###### Default - -```ts -60_000 // 60 seconds -``` - -### timeoutMs? - -```ts -optional timeoutMs: number; -``` - -Timeout for the watch operation in **milliseconds**. -You can pass `0` to disable the timeout. - -###### Default - -```ts -60_000 // 60 seconds -``` - -### user? - -```ts -optional user: string; -``` - -User to use for the operation in the sandbox. -This affects the resolution of relative paths and ownership of the created filesystem objects. - -*** - -### WriteInfo - -Sandbox filesystem object information. - -#### Extended by - -- `EntryInfo` - -#### Properties - -### name - -```ts -name: string; -``` - -Name of the filesystem object. - -### path - -```ts -path: string; -``` - -Path to the filesystem object. - -### type? - -```ts -optional type: FileType; -``` - -Type of the filesystem object. - -## Type Aliases - -### WriteEntry - -```ts -type WriteEntry: object; -``` - -#### Type declaration - -| Name | Type | -| ------ | ------ | -| `data` | `string` \| `ArrayBuffer` \| `Blob` \| `ReadableStream` | -| `path` | `string` | diff --git a/docs/sdk-reference/js-sdk/v2.8.4/sandbox.mdx b/docs/sdk-reference/js-sdk/v2.8.4/sandbox.mdx deleted file mode 100644 index e430744..0000000 --- a/docs/sdk-reference/js-sdk/v2.8.4/sandbox.mdx +++ /dev/null @@ -1,712 +0,0 @@ ---- -sidebarTitle: "Sandbox" -mode: "center" ---- - -### Sandbox - -E2B cloud sandbox is a secure and isolated cloud environment. - -The sandbox allows you to: -- Access Linux OS -- Create, list, and delete files and directories -- Run commands -- Run isolated code -- Access the internet - -Check docs here. - -Use Sandbox.create to create a new sandbox. - -#### Example - -```ts -import { Sandbox } from 'e2b' - -const sandbox = await Sandbox.create() -``` - -#### Properties - -| Property | Modifier | Type | Description | -| ------ | ------ | ------ | ------ | -| `commands` | `readonly` | `Commands` | Module for running commands in the sandbox | -| `files` | `readonly` | `Filesystem` | Module for interacting with the sandbox filesystem | -| `pty` | `readonly` | `Pty` | Module for interacting with the sandbox pseudo-terminals | -| `sandboxDomain` | `readonly` | `string` | Domain where the sandbox is hosted. | -| `sandboxId` | `readonly` | `string` | Unique identifier of the sandbox. | -| `trafficAccessToken?` | `readonly` | `string` | Traffic access token for accessing sandbox services with restricted public traffic. | - -#### Methods - -### betaPause() - -```ts -betaPause(opts?: ConnectionOpts): Promise -``` - -**`Beta`** - -This feature is in beta and may change in the future. - -Pause a sandbox by its ID. - -###### Parameters - -| Parameter | Type | Description | -| ------ | ------ | ------ | -| `opts`? | `ConnectionOpts` | connection options. | - -###### Returns - -`Promise`\<`boolean`\> - -sandbox ID that can be used to resume the sandbox. - -### connect() - -```ts -connect(opts?: SandboxBetaCreateOpts): Promise -``` - -Connect to a sandbox. If the sandbox is paused, it will be automatically resumed. -Sandbox must be either running or be paused. - -With sandbox ID you can connect to the same sandbox from different places or environments (serverless functions, etc). - -###### Parameters - -| Parameter | Type | Description | -| ------ | ------ | ------ | -| `opts`? | `SandboxBetaCreateOpts` | connection options. | - -###### Returns - -`Promise`\<`Sandbox`\> - -A running sandbox instance - -###### Example - -```ts -const sandbox = await Sandbox.create() -await sandbox.betaPause() - -// Connect to the same sandbox. -const sameSandbox = await sandbox.connect() -``` - -### downloadUrl() - -```ts -downloadUrl(path: string, opts?: SandboxUrlOpts): Promise -``` - -Get the URL to download a file from the sandbox. - -###### Parameters - -| Parameter | Type | Description | -| ------ | ------ | ------ | -| `path` | `string` | path to the file in the sandbox. | -| `opts`? | `SandboxUrlOpts` | download url options. | - -###### Returns - -`Promise`\<`string`\> - -URL for downloading file. - -### getHost() - -```ts -getHost(port: number): string -``` - -Get the host address for the specified sandbox port. -You can then use this address to connect to the sandbox port from outside the sandbox via HTTP or WebSocket. - -###### Parameters - -| Parameter | Type | Description | -| ------ | ------ | ------ | -| `port` | `number` | number of the port in the sandbox. | - -###### Returns - -`string` - -host address of the sandbox port. - -###### Example - -```ts -const sandbox = await Sandbox.create() -// Start an HTTP server -await sandbox.commands.exec('python3 -m http.server 3000') -// Get the hostname of the HTTP server -const serverURL = sandbox.getHost(3000) -``` - -### getInfo() - -```ts -getInfo(opts?: Pick): Promise -``` - -Get sandbox information like sandbox ID, template, metadata, started at/end at date. - -###### Parameters - -| Parameter | Type | Description | -| ------ | ------ | ------ | -| `opts`? | `Pick`\<`SandboxOpts`, `"requestTimeoutMs"`\> | connection options. | - -###### Returns - -`Promise`\<`SandboxInfo`\> - -information about the sandbox - -### getMcpToken() - -```ts -getMcpToken(): Promise -``` - -Get the MCP token for the sandbox. - -###### Returns - -`Promise`\<`undefined` \| `string`\> - -MCP token for the sandbox, or undefined if MCP is not enabled. - -### getMcpUrl() - -```ts -getMcpUrl(): string -``` - -Get the MCP URL for the sandbox. - -###### Returns - -`string` - -MCP URL for the sandbox. - -### getMetrics() - -```ts -getMetrics(opts?: SandboxMetricsOpts): Promise -``` - -Get the metrics of the sandbox. - -###### Parameters - -| Parameter | Type | Description | -| ------ | ------ | ------ | -| `opts`? | `SandboxMetricsOpts` | connection options. | - -###### Returns - -`Promise`\<`SandboxMetrics`[]\> - -List of sandbox metrics containing CPU, memory and disk usage information. - -### isRunning() - -```ts -isRunning(opts?: Pick): Promise -``` - -Check if the sandbox is running. - -###### Parameters - -| Parameter | Type | -| ------ | ------ | -| `opts`? | `Pick`\<`ConnectionOpts`, `"requestTimeoutMs"`\> | - -###### Returns - -`Promise`\<`boolean`\> - -`true` if the sandbox is running, `false` otherwise. - -###### Example - -```ts -const sandbox = await Sandbox.create() -await sandbox.isRunning() // Returns true - -await sandbox.kill() -await sandbox.isRunning() // Returns false -``` - -### kill() - -```ts -kill(opts?: Pick): Promise -``` - -Kill the sandbox. - -###### Parameters - -| Parameter | Type | Description | -| ------ | ------ | ------ | -| `opts`? | `Pick`\<`SandboxOpts`, `"requestTimeoutMs"`\> | connection options. | - -###### Returns - -`Promise`\<`void`\> - -### setTimeout() - -```ts -setTimeout(timeoutMs: number, opts?: Pick): Promise -``` - -Set the timeout of the sandbox. -After the timeout expires the sandbox will be automatically killed. - -This method can extend or reduce the sandbox timeout set when creating the sandbox or from the last call to `.setTimeout`. -Maximum time a sandbox can be kept alive is 24 hours (86_400_000 milliseconds) for Pro users and 1 hour (3_600_000 milliseconds) for Hobby users. - -###### Parameters - -| Parameter | Type | Description | -| ------ | ------ | ------ | -| `timeoutMs` | `number` | timeout in **milliseconds**. | -| `opts`? | `Pick`\<`SandboxOpts`, `"requestTimeoutMs"`\> | connection options. | - -###### Returns - -`Promise`\<`void`\> - -### uploadUrl() - -```ts -uploadUrl(path?: string, opts?: SandboxUrlOpts): Promise -``` - -Get the URL to upload a file to the sandbox. - -You have to send a POST request to this URL with the file as multipart/form-data. - -###### Parameters - -| Parameter | Type | Description | -| ------ | ------ | ------ | -| `path`? | `string` | path to the file in the sandbox. | -| `opts`? | `SandboxUrlOpts` | download url options. | - -###### Returns - -`Promise`\<`string`\> - -URL for uploading file. - -### betaCreate() - -###### betaCreate(this, opts) - -```ts -static betaCreate(this: S, opts?: SandboxBetaCreateOpts): Promise> -``` - -**`Beta`** - -This feature is in beta and may change in the future. - -Create a new sandbox from the default `base` sandbox template. - -###### Type Parameters - -| Type Parameter | -| ------ | -| `S` *extends* *typeof* `Sandbox` | - -###### Parameters - -| Parameter | Type | Description | -| ------ | ------ | ------ | -| `this` | `S` | - | -| `opts`? | `SandboxBetaCreateOpts` | connection options. | - -###### Returns - -`Promise`\<`InstanceType`\<`S`\>\> - -sandbox instance for the new sandbox. - -###### Example - -```ts -const sandbox = await Sandbox.betaCreate() -``` - -###### Constructs - -Sandbox - -###### betaCreate(this, template, opts) - -```ts -static betaCreate( - this: S, - template: string, -opts?: SandboxBetaCreateOpts): Promise> -``` - -**`Beta`** - -This feature is in beta and may change in the future. - -Create a new sandbox from the specified sandbox template. - -###### Type Parameters - -| Type Parameter | -| ------ | -| `S` *extends* *typeof* `Sandbox` | - -###### Parameters - -| Parameter | Type | Description | -| ------ | ------ | ------ | -| `this` | `S` | - | -| `template` | `string` | sandbox template name or ID. | -| `opts`? | `SandboxBetaCreateOpts` | connection options. | - -###### Returns - -`Promise`\<`InstanceType`\<`S`\>\> - -sandbox instance for the new sandbox. - -###### Example - -```ts -const sandbox = await Sandbox.betaCreate('') -``` - -###### Constructs - -Sandbox - -### betaPause() - -```ts -static betaPause(sandboxId: string, opts?: SandboxApiOpts): Promise -``` - -Pause the sandbox specified by sandbox ID. - -###### Parameters - -| Parameter | Type | Description | -| ------ | ------ | ------ | -| `sandboxId` | `string` | sandbox ID. | -| `opts`? | `SandboxApiOpts` | connection options. | - -###### Returns - -`Promise`\<`boolean`\> - -`true` if the sandbox got paused, `false` if the sandbox was already paused. - -### connect() - -```ts -static connect( - this: S, - sandboxId: string, -opts?: SandboxConnectOpts): Promise> -``` - -Connect to a sandbox. If the sandbox is paused, it will be automatically resumed. -Sandbox must be either running or be paused. - -With sandbox ID you can connect to the same sandbox from different places or environments (serverless functions, etc). - -###### Type Parameters - -| Type Parameter | -| ------ | -| `S` *extends* *typeof* `Sandbox` | - -###### Parameters - -| Parameter | Type | Description | -| ------ | ------ | ------ | -| `this` | `S` | - | -| `sandboxId` | `string` | sandbox ID. | -| `opts`? | `SandboxConnectOpts` | connection options. | - -###### Returns - -`Promise`\<`InstanceType`\<`S`\>\> - -A running sandbox instance - -###### Example - -```ts -const sandbox = await Sandbox.create() -const sandboxId = sandbox.sandboxId - -// Connect to the same sandbox. -const sameSandbox = await Sandbox.connect(sandboxId) -``` - -### create() - -###### create(this, opts) - -```ts -static create(this: S, opts?: SandboxOpts): Promise> -``` - -Create a new sandbox from the default `base` sandbox template. - -###### Type Parameters - -| Type Parameter | -| ------ | -| `S` *extends* *typeof* `Sandbox` | - -###### Parameters - -| Parameter | Type | Description | -| ------ | ------ | ------ | -| `this` | `S` | - | -| `opts`? | `SandboxOpts` | connection options. | - -###### Returns - -`Promise`\<`InstanceType`\<`S`\>\> - -sandbox instance for the new sandbox. - -###### Example - -```ts -const sandbox = await Sandbox.create() -``` - -###### Constructs - -Sandbox - -###### create(this, template, opts) - -```ts -static create( - this: S, - template: string, -opts?: SandboxOpts): Promise> -``` - -Create a new sandbox from the specified sandbox template. - -###### Type Parameters - -| Type Parameter | -| ------ | -| `S` *extends* *typeof* `Sandbox` | - -###### Parameters - -| Parameter | Type | Description | -| ------ | ------ | ------ | -| `this` | `S` | - | -| `template` | `string` | sandbox template name or ID. | -| `opts`? | `SandboxOpts` | connection options. | - -###### Returns - -`Promise`\<`InstanceType`\<`S`\>\> - -sandbox instance for the new sandbox. - -###### Example - -```ts -const sandbox = await Sandbox.create('') -``` - -###### Constructs - -Sandbox - -### getFullInfo() - -```ts -static getFullInfo(sandboxId: string, opts?: SandboxApiOpts): Promise -``` - -###### Parameters - -| Parameter | Type | -| ------ | ------ | -| `sandboxId` | `string` | -| `opts`? | `SandboxApiOpts` | - -###### Returns - -`Promise`\<`object`\> - -| Name | Type | Default value | -| ------ | ------ | ------ | -| `cpuCount` | `number` | res.data.cpuCount | -| `endAt` | `Date` | - | -| `envdAccessToken` | `undefined` \| `string` | res.data.envdAccessToken | -| `envdVersion` | `string` | res.data.envdVersion | -| `memoryMB` | `number` | res.data.memoryMB | -| `metadata` | `object` | - | -| `name`? | `string` | res.data.alias | -| `sandboxDomain` | `undefined` \| `string` | - | -| `sandboxId` | `string` | res.data.sandboxID | -| `startedAt` | `Date` | - | -| `state` | `"running"` \| `"paused"` | res.data.state | -| `templateId` | `string` | res.data.templateID | - -### getInfo() - -```ts -static getInfo(sandboxId: string, opts?: SandboxApiOpts): Promise -``` - -Get sandbox information like sandbox ID, template, metadata, started at/end at date. - -###### Parameters - -| Parameter | Type | Description | -| ------ | ------ | ------ | -| `sandboxId` | `string` | sandbox ID. | -| `opts`? | `SandboxApiOpts` | connection options. | - -###### Returns - -`Promise`\<`SandboxInfo`\> - -sandbox information. - -### getMetrics() - -```ts -static getMetrics(sandboxId: string, opts?: SandboxMetricsOpts): Promise -``` - -Get the metrics of the sandbox. - -###### Parameters - -| Parameter | Type | Description | -| ------ | ------ | ------ | -| `sandboxId` | `string` | sandbox ID. | -| `opts`? | `SandboxMetricsOpts` | sandbox metrics options. | - -###### Returns - -`Promise`\<`SandboxMetrics`[]\> - -List of sandbox metrics containing CPU, memory and disk usage information. - -### kill() - -```ts -static kill(sandboxId: string, opts?: SandboxApiOpts): Promise -``` - -Kill the sandbox specified by sandbox ID. - -###### Parameters - -| Parameter | Type | Description | -| ------ | ------ | ------ | -| `sandboxId` | `string` | sandbox ID. | -| `opts`? | `SandboxApiOpts` | connection options. | - -###### Returns - -`Promise`\<`boolean`\> - -`true` if the sandbox was found and killed, `false` otherwise. - -### list() - -```ts -static list(opts?: SandboxListOpts): SandboxPaginator -``` - -List all sandboxes. - -###### Parameters - -| Parameter | Type | Description | -| ------ | ------ | ------ | -| `opts`? | `SandboxListOpts` | connection options. | - -###### Returns - -`SandboxPaginator` - -paginator for listing sandboxes. - -### setTimeout() - -```ts -static setTimeout( - sandboxId: string, - timeoutMs: number, -opts?: SandboxApiOpts): Promise -``` - -Set the timeout of the specified sandbox. -After the timeout expires the sandbox will be automatically killed. - -This method can extend or reduce the sandbox timeout set when creating the sandbox or from the last call to Sandbox.setTimeout. - -Maximum time a sandbox can be kept alive is 24 hours (86_400_000 milliseconds) for Pro users and 1 hour (3_600_000 milliseconds) for Hobby users. - -###### Parameters - -| Parameter | Type | Description | -| ------ | ------ | ------ | -| `sandboxId` | `string` | sandbox ID. | -| `timeoutMs` | `number` | timeout in **milliseconds**. | -| `opts`? | `SandboxApiOpts` | connection options. | - -###### Returns - -`Promise`\<`void`\> - -## Interfaces - -### SandboxUrlOpts - -Options for sandbox upload/download URL generation. - -#### Properties - -### user? - -```ts -optional user: string; -``` - -User that will be used to access the file. - -### useSignatureExpiration? - -```ts -optional useSignatureExpiration: number; -``` - -Use signature expiration for the URL. -Optional parameter to set the expiration time for the signature in seconds. diff --git a/docs/sdk-reference/js-sdk/v2.8.4/template-logger.mdx b/docs/sdk-reference/js-sdk/v2.8.4/template-logger.mdx deleted file mode 100644 index fdebde3..0000000 --- a/docs/sdk-reference/js-sdk/v2.8.4/template-logger.mdx +++ /dev/null @@ -1,196 +0,0 @@ ---- -sidebarTitle: "Logger" -mode: "center" ---- - -### LogEntry - -Represents a single log entry from the template build process. - -#### Extended by - -- `LogEntryStart` -- `LogEntryEnd` - -#### Constructors - -```ts -new LogEntry( - timestamp: Date, - level: LogEntryLevel, - message: string): LogEntry -``` - -###### Parameters - -| Parameter | Type | -| ------ | ------ | -| `timestamp` | `Date` | -| `level` | `LogEntryLevel` | -| `message` | `string` | - -###### Returns - -`LogEntry` - -#### Properties - -| Property | Modifier | Type | -| ------ | ------ | ------ | -| `level` | `readonly` | `LogEntryLevel` | -| `message` | `readonly` | `string` | -| `timestamp` | `readonly` | `Date` | - -#### Methods - -### toString() - -```ts -toString(): string -``` - -###### Returns - -`string` - -*** - -### LogEntryEnd - -Special log entry indicating the end of a build process. - -#### Constructors - -```ts -new LogEntryEnd(timestamp: Date, message: string): LogEntryEnd -``` - -###### Parameters - -| Parameter | Type | -| ------ | ------ | -| `timestamp` | `Date` | -| `message` | `string` | - -###### Returns - -`LogEntryEnd` - -#### Properties - -| Property | Modifier | Type | Inherited from | -| ------ | ------ | ------ | ------ | -| `level` | `readonly` | `LogEntryLevel` | `LogEntry`.`level` | -| `message` | `readonly` | `string` | `LogEntry`.`message` | -| `timestamp` | `readonly` | `Date` | `LogEntry`.`timestamp` | - -#### Methods - -### toString() - -```ts -toString(): string -``` - -###### Returns - -`string` - -*** - -### LogEntryStart - -Special log entry indicating the start of a build process. - -#### Constructors - -```ts -new LogEntryStart(timestamp: Date, message: string): LogEntryStart -``` - -###### Parameters - -| Parameter | Type | -| ------ | ------ | -| `timestamp` | `Date` | -| `message` | `string` | - -###### Returns - -`LogEntryStart` - -#### Properties - -| Property | Modifier | Type | Inherited from | -| ------ | ------ | ------ | ------ | -| `level` | `readonly` | `LogEntryLevel` | `LogEntry`.`level` | -| `message` | `readonly` | `string` | `LogEntry`.`message` | -| `timestamp` | `readonly` | `Date` | `LogEntry`.`timestamp` | - -#### Methods - -### toString() - -```ts -toString(): string -``` - -###### Returns - -`string` - -## Type Aliases - -### LogEntryLevel - -```ts -type LogEntryLevel: "debug" | "info" | "warn" | "error"; -``` - -Log entry severity levels. - -## Functions - -### defaultBuildLogger() - -```ts -function defaultBuildLogger(options?: object): (logEntry: LogEntry) => void -``` - -Create a default build logger with animated timer display. - -#### Parameters - -| Parameter | Type | Description | -| ------ | ------ | ------ | -| `options`? | `object` | Logger configuration options | -| `options.minLevel`? | `LogEntryLevel` | Minimum log level to display (default: 'info') | - -#### Returns - -`Function` - -Logger function that accepts LogEntry instances - -### Parameters - -| Parameter | Type | -| ------ | ------ | -| `logEntry` | `LogEntry` | - -### Returns - -`void` - -#### Example - -```ts -import { Template, defaultBuildLogger } from 'e2b' - -const template = Template().fromPythonImage() - -await Template.build(template, { - alias: 'my-template', - onBuildLogs: defaultBuildLogger({ minLevel: 'debug' }) -}) -``` diff --git a/docs/sdk-reference/js-sdk/v2.8.4/template-readycmd.mdx b/docs/sdk-reference/js-sdk/v2.8.4/template-readycmd.mdx deleted file mode 100644 index 56fb0b7..0000000 --- a/docs/sdk-reference/js-sdk/v2.8.4/template-readycmd.mdx +++ /dev/null @@ -1,202 +0,0 @@ ---- -sidebarTitle: "Readycmd" -mode: "center" ---- - -### ReadyCmd - -Class for ready check commands. - -#### Constructors - -```ts -new ReadyCmd(cmd: string): ReadyCmd -``` - -###### Parameters - -| Parameter | Type | -| ------ | ------ | -| `cmd` | `string` | - -###### Returns - -`ReadyCmd` - -#### Methods - -### getCmd() - -```ts -getCmd(): string -``` - -###### Returns - -`string` - -## Functions - -### waitForFile() - -```ts -function waitForFile(filename: string): ReadyCmd -``` - -Wait for a file to exist. -Uses shell test command to check file existence. - -#### Parameters - -| Parameter | Type | Description | -| ------ | ------ | ------ | -| `filename` | `string` | Path to the file to wait for | - -#### Returns - -`ReadyCmd` - -ReadyCmd that checks for the file - -#### Example - -```ts -import { Template, waitForFile } from 'e2b' - -const template = Template() - .fromBaseImage() - .setStartCmd('./init.sh', waitForFile('/tmp/ready')) -``` - -*** - -### waitForPort() - -```ts -function waitForPort(port: number): ReadyCmd -``` - -Wait for a port to be listening. -Uses `ss` command to check if a port is open and listening. - -#### Parameters - -| Parameter | Type | Description | -| ------ | ------ | ------ | -| `port` | `number` | Port number to wait for | - -#### Returns - -`ReadyCmd` - -ReadyCmd that checks for the port - -#### Example - -```ts -import { Template, waitForPort } from 'e2b' - -const template = Template() - .fromPythonImage() - .setStartCmd('python -m http.server 8000', waitForPort(8000)) -``` - -*** - -### waitForProcess() - -```ts -function waitForProcess(processName: string): ReadyCmd -``` - -Wait for a process with a specific name to be running. -Uses `pgrep` to check if a process exists. - -#### Parameters - -| Parameter | Type | Description | -| ------ | ------ | ------ | -| `processName` | `string` | Name of the process to wait for | - -#### Returns - -`ReadyCmd` - -ReadyCmd that checks for the process - -#### Example - -```ts -import { Template, waitForProcess } from 'e2b' - -const template = Template() - .fromBaseImage() - .setStartCmd('./my-daemon', waitForProcess('my-daemon')) -``` - -*** - -### waitForTimeout() - -```ts -function waitForTimeout(timeout: number): ReadyCmd -``` - -Wait for a specified timeout before considering the sandbox ready. -Uses `sleep` command to wait for a fixed duration. - -#### Parameters - -| Parameter | Type | Description | -| ------ | ------ | ------ | -| `timeout` | `number` | Time to wait in milliseconds (minimum: 1000ms / 1 second) | - -#### Returns - -`ReadyCmd` - -ReadyCmd that waits for the specified duration - -#### Example - -```ts -import { Template, waitForTimeout } from 'e2b' - -const template = Template() - .fromNodeImage() - .setStartCmd('npm start', waitForTimeout(5000)) // Wait 5 seconds -``` - -*** - -### waitForURL() - -```ts -function waitForURL(url: string, statusCode: number): ReadyCmd -``` - -Wait for a URL to return a specific HTTP status code. -Uses `curl` to make HTTP requests and check the response status. - -#### Parameters - -| Parameter | Type | Default value | Description | -| ------ | ------ | ------ | ------ | -| `url` | `string` | `undefined` | URL to check (e.g., 'http://localhost:3000/health') | -| `statusCode` | `number` | `200` | Expected HTTP status code (default: 200) | - -#### Returns - -`ReadyCmd` - -ReadyCmd that checks the URL - -#### Example - -```ts -import { Template, waitForURL } from 'e2b' - -const template = Template() - .fromNodeImage() - .setStartCmd('npm start', waitForURL('http://localhost:3000/health')) -``` diff --git a/docs/sdk-reference/js-sdk/v2.8.4/template.mdx b/docs/sdk-reference/js-sdk/v2.8.4/template.mdx deleted file mode 100644 index c644e02..0000000 --- a/docs/sdk-reference/js-sdk/v2.8.4/template.mdx +++ /dev/null @@ -1,2042 +0,0 @@ ---- -sidebarTitle: "Template" -mode: "center" ---- - -### TemplateBase - -Base class for building E2B sandbox templates. - -#### Implements - -- `TemplateFromImage` -- `TemplateBuilder` -- `TemplateFinal` - -#### Constructors - -```ts -new TemplateBase(options?: TemplateOptions): TemplateBase -``` - -###### Parameters - -| Parameter | Type | -| ------ | ------ | -| `options`? | `TemplateOptions` | - -###### Returns - -`TemplateBase` - -#### Methods - -### addMcpServer() - -```ts -addMcpServer(servers: keyof McpServer | keyof McpServer[]): TemplateBuilder -``` - -Install MCP servers using mcp-gateway. -Note: Requires a base image with mcp-gateway pre-installed (e.g., mcp-gateway). - -###### Parameters - -| Parameter | Type | Description | -| ------ | ------ | ------ | -| `servers` | keyof McpServer \| keyof McpServer[] | MCP server name(s) | - -###### Returns - -`TemplateBuilder` - -###### Throws - -If the base template is not mcp-gateway - -###### Example - -```ts -template.addMcpServer('exa') -template.addMcpServer(['brave', 'firecrawl', 'duckduckgo']) -``` - -###### Implementation of - -`TemplateBuilder`.`addMcpServer` - -### aptInstall() - -```ts -aptInstall(packages: string | string[], options?: object): TemplateBuilder -``` - -Install Debian/Ubuntu packages using apt-get. - -###### Parameters - -| Parameter | Type | Description | -| ------ | ------ | ------ | -| `packages` | `string` \| `string`[] | Package name(s) | -| `options`? | `object` | - | -| `options.noInstallRecommends`? | `boolean` | - | - -###### Returns - -`TemplateBuilder` - -###### Example - -```ts -template.aptInstall('vim') -template.aptInstall(['git', 'curl', 'wget']) -template.aptInstall(['vim'], { noInstallRecommends: true }) -``` - -###### Implementation of - -`TemplateBuilder`.`aptInstall` - -### betaDevContainerPrebuild() - -```ts -betaDevContainerPrebuild(devcontainerDirectory: string): TemplateBuilder -``` - -Prebuild a devcontainer from the specified directory. - -###### Parameters - -| Parameter | Type | Description | -| ------ | ------ | ------ | -| `devcontainerDirectory` | `string` | Path to the devcontainer directory | - -###### Returns - -`TemplateBuilder` - -###### Example - -```ts -template - .gitClone('https://myrepo.com/project.git', '/my-devcontainer') - .betaDevContainerPrebuild('/my-devcontainer') -``` - -###### Implementation of - -`TemplateBuilder`.`betaDevContainerPrebuild` - -### betaSetDevContainerStart() - -```ts -betaSetDevContainerStart(devcontainerDirectory: string): TemplateFinal -``` - -Start a devcontainer from the specified directory. - -###### Parameters - -| Parameter | Type | Description | -| ------ | ------ | ------ | -| `devcontainerDirectory` | `string` | Path to the devcontainer directory | - -###### Returns - -`TemplateFinal` - -###### Example - -```ts -template - .gitClone('https://myrepo.com/project.git', '/my-devcontainer') - .startDevcontainer('/my-devcontainer') - -// Prebuild and start -template - .gitClone('https://myrepo.com/project.git', '/my-devcontainer') - .betaDevContainerPrebuild('/my-devcontainer') - // Other instructions... - .betaSetDevContainerStart('/my-devcontainer') -``` - -###### Implementation of - -`TemplateBuilder`.`betaSetDevContainerStart` - -### bunInstall() - -```ts -bunInstall(packages?: string | string[], options?: object): TemplateBuilder -``` - -Install Bun packages using bun. - -###### Parameters - -| Parameter | Type | Description | -| ------ | ------ | ------ | -| `packages`? | `string` \| `string`[] | Package name(s) or undefined for package.json | -| `options`? | `object` | Install options | -| `options.dev`? | `boolean` | - | -| `options.g`? | `boolean` | - | - -###### Returns - -`TemplateBuilder` - -###### Example - -```ts -template.bunInstall('express') -template.bunInstall(['lodash', 'axios']) -template.bunInstall('tsx', { g: true }) -template.bunInstall('typescript', { dev: true }) -template.bunInstall() // Installs from package.json -``` - -###### Implementation of - -`TemplateBuilder`.`bunInstall` - -### copy() - -```ts -copy( - src: PathLike | PathLike[], - dest: PathLike, - options?: object): TemplateBuilder -``` - -Copy files or directories into the template. - -###### Parameters - -| Parameter | Type | Description | -| ------ | ------ | ------ | -| `src` | `PathLike` \| `PathLike`[] | Source path(s) | -| `dest` | `PathLike` | Destination path | -| `options`? | `object` | Copy options | -| `options.forceUpload`? | `true` | - | -| `options.mode`? | `number` | - | -| `options.resolveSymlinks`? | `boolean` | - | -| `options.user`? | `string` | - | - -###### Returns - -`TemplateBuilder` - -###### Example - -```ts -template.copy('requirements.txt', '/home/user/') -template.copy(['app.ts', 'config.ts'], '/app/', { mode: 0o755 }) -``` - -###### Implementation of - -`TemplateBuilder`.`copy` - -### copyItems() - -```ts -copyItems(items: CopyItem[]): TemplateBuilder -``` - -Copy multiple items with individual options. - -###### Parameters - -| Parameter | Type | Description | -| ------ | ------ | ------ | -| `items` | `CopyItem`[] | Array of copy items | - -###### Returns - -`TemplateBuilder` - -###### Example - -```ts -template.copyItems([ - { src: 'app.ts', dest: '/app/' }, - { src: 'config.ts', dest: '/app/', mode: 0o644 } -]) -``` - -###### Implementation of - -`TemplateBuilder`.`copyItems` - -### fromAWSRegistry() - -```ts -fromAWSRegistry(image: string, credentials: object): TemplateBuilder -``` - -Start from a Docker image in AWS ECR. - -###### Parameters - -| Parameter | Type | Description | -| ------ | ------ | ------ | -| `image` | `string` | Full ECR image path | -| `credentials` | `object` | AWS credentials | -| `credentials.accessKeyId` | `string` | - | -| `credentials.region` | `string` | - | -| `credentials.secretAccessKey` | `string` | - | - -###### Returns - -`TemplateBuilder` - -###### Example - -```ts -Template().fromAWSRegistry( - '123456789.dkr.ecr.us-west-2.amazonaws.com/myimage:latest', - { - accessKeyId: 'AKIA...', - secretAccessKey: '...', - region: 'us-west-2' - } -) -``` - -###### Implementation of - -`TemplateFromImage.fromAWSRegistry` - -### fromBaseImage() - -```ts -fromBaseImage(): TemplateBuilder -``` - -Start from E2B's default base image (e2bdev/base:latest). - -###### Returns - -`TemplateBuilder` - -###### Example - -```ts -Template().fromBaseImage() -``` - -###### Implementation of - -`TemplateFromImage.fromBaseImage` - -### fromBunImage() - -```ts -fromBunImage(variant: string): TemplateBuilder -``` - -Start from a Bun-based Docker image. - -###### Parameters - -| Parameter | Type | Default value | Description | -| ------ | ------ | ------ | ------ | -| `variant` | `string` | `'latest'` | Bun variant (default: 'latest') | - -###### Returns - -`TemplateBuilder` - -###### Example - -```ts -Template().fromBunImage('1.3') -``` - -###### Implementation of - -`TemplateFromImage.fromBunImage` - -### fromDebianImage() - -```ts -fromDebianImage(variant: string): TemplateBuilder -``` - -Start from a Debian-based Docker image. - -###### Parameters - -| Parameter | Type | Default value | Description | -| ------ | ------ | ------ | ------ | -| `variant` | `string` | `'stable'` | Debian variant (default: 'stable') | - -###### Returns - -`TemplateBuilder` - -###### Example - -```ts -Template().fromDebianImage('bookworm') -``` - -###### Implementation of - -`TemplateFromImage.fromDebianImage` - -### fromDockerfile() - -```ts -fromDockerfile(dockerfileContentOrPath: string): TemplateBuilder -``` - -Parse a Dockerfile and convert it to Template SDK format. - -###### Parameters - -| Parameter | Type | Description | -| ------ | ------ | ------ | -| `dockerfileContentOrPath` | `string` | Dockerfile content or path | - -###### Returns - -`TemplateBuilder` - -###### Example - -```ts -Template().fromDockerfile('Dockerfile') -Template().fromDockerfile('FROM python:3\nRUN pip install numpy') -``` - -###### Implementation of - -`TemplateFromImage.fromDockerfile` - -### fromGCPRegistry() - -```ts -fromGCPRegistry(image: string, credentials: object): TemplateBuilder -``` - -Start from a Docker image in Google Container Registry. - -###### Parameters - -| Parameter | Type | Description | -| ------ | ------ | ------ | -| `image` | `string` | Full GCR/GAR image path | -| `credentials` | `object` | GCP service account credentials | -| `credentials.serviceAccountJSON` | `string` \| `object` | - | - -###### Returns - -`TemplateBuilder` - -###### Example - -```ts -Template().fromGCPRegistry( - 'gcr.io/myproject/myimage:latest', - { serviceAccountJSON: 'path/to/service-account.json' } -) -``` - -###### Implementation of - -`TemplateFromImage.fromGCPRegistry` - -### fromImage() - -```ts -fromImage(baseImage: string, credentials?: object): TemplateBuilder -``` - -Start from a custom Docker image. - -###### Parameters - -| Parameter | Type | Description | -| ------ | ------ | ------ | -| `baseImage` | `string` | Docker image name | -| `credentials`? | `object` | Optional credentials for private registries | -| `credentials.password`? | `string` | - | -| `credentials.username`? | `string` | - | - -###### Returns - -`TemplateBuilder` - -###### Example - -```ts -Template().fromImage('python:3') - -// With credentials (optional) -Template().fromImage('myregistry.com/myimage:latest', { - username: 'user', - password: 'pass' -}) -``` - -###### Implementation of - -`TemplateFromImage.fromImage` - -### fromNodeImage() - -```ts -fromNodeImage(variant: string): TemplateBuilder -``` - -Start from a Node.js-based Docker image. - -###### Parameters - -| Parameter | Type | Default value | Description | -| ------ | ------ | ------ | ------ | -| `variant` | `string` | `'lts'` | Node.js variant (default: 'lts') | - -###### Returns - -`TemplateBuilder` - -###### Example - -```ts -Template().fromNodeImage('24') -``` - -###### Implementation of - -`TemplateFromImage.fromNodeImage` - -### fromPythonImage() - -```ts -fromPythonImage(version: string): TemplateBuilder -``` - -Start from a Python-based Docker image. - -###### Parameters - -| Parameter | Type | Default value | Description | -| ------ | ------ | ------ | ------ | -| `version` | `string` | `'3'` | Python version (default: '3') | - -###### Returns - -`TemplateBuilder` - -###### Example - -```ts -Template().fromPythonImage('3') -``` - -###### Implementation of - -`TemplateFromImage.fromPythonImage` - -### fromTemplate() - -```ts -fromTemplate(template: string): TemplateBuilder -``` - -Start from an existing E2B template. - -###### Parameters - -| Parameter | Type | Description | -| ------ | ------ | ------ | -| `template` | `string` | E2B template ID or alias | - -###### Returns - -`TemplateBuilder` - -###### Example - -```ts -Template().fromTemplate('my-base-template') -``` - -###### Implementation of - -`TemplateFromImage.fromTemplate` - -### fromUbuntuImage() - -```ts -fromUbuntuImage(variant: string): TemplateBuilder -``` - -Start from an Ubuntu-based Docker image. - -###### Parameters - -| Parameter | Type | Default value | Description | -| ------ | ------ | ------ | ------ | -| `variant` | `string` | `'latest'` | Ubuntu variant (default: 'latest') | - -###### Returns - -`TemplateBuilder` - -###### Example - -```ts -Template().fromUbuntuImage('24.04') -``` - -###### Implementation of - -`TemplateFromImage.fromUbuntuImage` - -### gitClone() - -```ts -gitClone( - url: string, - path?: PathLike, - options?: object): TemplateBuilder -``` - -Clone a Git repository. - -###### Parameters - -| Parameter | Type | Description | -| ------ | ------ | ------ | -| `url` | `string` | Repository URL | -| `path`? | `PathLike` | Optional destination path | -| `options`? | `object` | Clone options | -| `options.branch`? | `string` | - | -| `options.depth`? | `number` | - | -| `options.user`? | `string` | - | - -###### Returns - -`TemplateBuilder` - -###### Example - -```ts -template.gitClone('https://github.com/user/repo.git', '/app/repo') -template.gitClone('https://github.com/user/repo.git', undefined, { - branch: 'main', - depth: 1 -}) -template.gitClone('https://github.com/user/repo.git', '/app/repo', { - user: 'root' -}) -``` - -###### Implementation of - -`TemplateBuilder`.`gitClone` - -### makeDir() - -```ts -makeDir(path: PathLike | PathLike[], options?: object): TemplateBuilder -``` - -Create directories. - -###### Parameters - -| Parameter | Type | Description | -| ------ | ------ | ------ | -| `path` | `PathLike` \| `PathLike`[] | Directory path(s) | -| `options`? | `object` | Directory options | -| `options.mode`? | `number` | - | -| `options.user`? | `string` | - | - -###### Returns - -`TemplateBuilder` - -###### Example - -```ts -template.makeDir('/app/data', { mode: 0o755 }) -template.makeDir(['/app/logs', '/app/cache']) -template.makeDir('/app/data', { mode: 0o755, user: 'root' }) -``` - -###### Implementation of - -`TemplateBuilder`.`makeDir` - -### makeSymlink() - -```ts -makeSymlink( - src: PathLike, - dest: PathLike, - options?: object): TemplateBuilder -``` - -Create a symbolic link. - -###### Parameters - -| Parameter | Type | Description | -| ------ | ------ | ------ | -| `src` | `PathLike` | Source path (target) | -| `dest` | `PathLike` | Destination path (symlink location) | -| `options`? | `object` | Symlink options | -| `options.force`? | `boolean` | - | -| `options.user`? | `string` | - | - -###### Returns - -`TemplateBuilder` - -###### Example - -```ts -template.makeSymlink('/usr/bin/python3', '/usr/bin/python') -template.makeSymlink('/usr/bin/python3', '/usr/bin/python', { user: 'root' }) -template.makeSymlink('/usr/bin/python3', '/usr/bin/python', { force: true }) -``` - -###### Implementation of - -`TemplateBuilder`.`makeSymlink` - -### npmInstall() - -```ts -npmInstall(packages?: string | string[], options?: object): TemplateBuilder -``` - -Install Node.js packages using npm. - -###### Parameters - -| Parameter | Type | Description | -| ------ | ------ | ------ | -| `packages`? | `string` \| `string`[] | Package name(s) or undefined for package.json | -| `options`? | `object` | Install options | -| `options.dev`? | `boolean` | - | -| `options.g`? | `boolean` | - | - -###### Returns - -`TemplateBuilder` - -###### Example - -```ts -template.npmInstall('express') -template.npmInstall(['lodash', 'axios']) -template.npmInstall('tsx', { g: true }) -template.npmInstall('typescript', { dev: true }) -template.npmInstall() // Installs from package.json -``` - -###### Implementation of - -`TemplateBuilder`.`npmInstall` - -### pipInstall() - -```ts -pipInstall(packages?: string | string[], options?: object): TemplateBuilder -``` - -Install Python packages using pip. - -###### Parameters - -| Parameter | Type | Description | -| ------ | ------ | ------ | -| `packages`? | `string` \| `string`[] | Package name(s) or undefined for current directory | -| `options`? | `object` | Install options | -| `options.g`? | `boolean` | Install globally as root (default: true). Set to false for user-only installation with --user flag | - -###### Returns - -`TemplateBuilder` - -###### Example - -```ts -template.pipInstall('numpy') // Installs globally (default) -template.pipInstall(['pandas', 'scikit-learn']) -template.pipInstall('numpy', { g: false }) // Install for user only -template.pipInstall() // Installs from current directory -``` - -###### Implementation of - -`TemplateBuilder`.`pipInstall` - -### remove() - -```ts -remove(path: PathLike | PathLike[], options?: object): TemplateBuilder -``` - -Remove files or directories. - -###### Parameters - -| Parameter | Type | Description | -| ------ | ------ | ------ | -| `path` | `PathLike` \| `PathLike`[] | Path(s) to remove | -| `options`? | `object` | Remove options | -| `options.force`? | `boolean` | - | -| `options.recursive`? | `boolean` | - | -| `options.user`? | `string` | - | - -###### Returns - -`TemplateBuilder` - -###### Example - -```ts -template.remove('/tmp/cache', { recursive: true, force: true }) -template.remove('/tmp/cache', { recursive: true, force: true, user: 'root' }) -``` - -###### Implementation of - -`TemplateBuilder`.`remove` - -### rename() - -```ts -rename( - src: PathLike, - dest: PathLike, - options?: object): TemplateBuilder -``` - -Rename or move a file or directory. - -###### Parameters - -| Parameter | Type | Description | -| ------ | ------ | ------ | -| `src` | `PathLike` | Source path | -| `dest` | `PathLike` | Destination path | -| `options`? | `object` | Rename options | -| `options.force`? | `boolean` | - | -| `options.user`? | `string` | - | - -###### Returns - -`TemplateBuilder` - -###### Example - -```ts -template.rename('/tmp/old.txt', '/tmp/new.txt') -template.rename('/tmp/old.txt', '/tmp/new.txt', { user: 'root' }) -``` - -###### Implementation of - -`TemplateBuilder`.`rename` - -### runCmd() - -###### runCmd(command, options) - -```ts -runCmd(command: string, options?: object): TemplateBuilder -``` - -Run a shell command. - -###### Parameters - -| Parameter | Type | Description | -| ------ | ------ | ------ | -| `command` | `string` | Command string | -| `options`? | `object` | Command options | -| `options.user`? | `string` | - | - -###### Returns - -`TemplateBuilder` - -###### Example - -```ts -template.runCmd('apt-get update') -template.runCmd(['pip install numpy', 'pip install pandas']) -template.runCmd('apt-get install vim', { user: 'root' }) -``` - -###### Implementation of - -`TemplateBuilder`.`runCmd` - -###### runCmd(commands, options) - -```ts -runCmd(commands: string[], options?: object): TemplateBuilder -``` - -Run a shell command. - -###### Parameters - -| Parameter | Type | Description | -| ------ | ------ | ------ | -| `commands` | `string`[] | - | -| `options`? | `object` | Command options | -| `options.user`? | `string` | - | - -###### Returns - -`TemplateBuilder` - -###### Example - -```ts -template.runCmd('apt-get update') -template.runCmd(['pip install numpy', 'pip install pandas']) -template.runCmd('apt-get install vim', { user: 'root' }) -``` - -###### Implementation of - -`TemplateBuilder`.`runCmd` - -### setEnvs() - -```ts -setEnvs(envs: Record): TemplateBuilder -``` - -Set environment variables. - -###### Parameters - -| Parameter | Type | Description | -| ------ | ------ | ------ | -| `envs` | `Record`\<`string`, `string`\> | Environment variables | - -###### Returns - -`TemplateBuilder` - -###### Example - -```ts -template.setEnvs({ NODE_ENV: 'production', PORT: '8080' }) -``` - -###### Implementation of - -`TemplateBuilder`.`setEnvs` - -### setReadyCmd() - -```ts -setReadyCmd(readyCommand: string | ReadyCmd): TemplateFinal -``` - -Set or update the ready check command. - -###### Parameters - -| Parameter | Type | Description | -| ------ | ------ | ------ | -| `readyCommand` | `string` \| `ReadyCmd` | Command to check readiness | - -###### Returns - -`TemplateFinal` - -###### Example - -```ts -// Using a string command -template.setReadyCmd('curl http://localhost:8000/health') - -// Using ReadyCmd helpers -import { waitForPort, waitForFile, waitForProcess } from 'e2b' - -template.setReadyCmd(waitForPort(3000)) - -template.setReadyCmd(waitForFile('/tmp/ready')) - -template.setReadyCmd(waitForProcess('nginx')) -``` - -###### Implementation of - -`TemplateBuilder`.`setReadyCmd` - -### setStartCmd() - -```ts -setStartCmd(startCommand: string, readyCommand: string | ReadyCmd): TemplateFinal -``` - -Set the start command and ready check. - -###### Parameters - -| Parameter | Type | Description | -| ------ | ------ | ------ | -| `startCommand` | `string` | Command to run on startup | -| `readyCommand` | `string` \| `ReadyCmd` | Command to check readiness | - -###### Returns - -`TemplateFinal` - -###### Example - -```ts -// Using a string command -template.setStartCmd( - 'node app.js', - 'curl http://localhost:8000/health' -) - -// Using ReadyCmd helpers -import { waitForPort, waitForURL } from 'e2b' - -template.setStartCmd( - 'python -m http.server 8000', - waitForPort(8000) -) - -template.setStartCmd( - 'npm start', - waitForURL('http://localhost:3000/health', 200) -) -``` - -###### Implementation of - -`TemplateBuilder`.`setStartCmd` - -### setUser() - -```ts -setUser(user: string): TemplateBuilder -``` - -Set the user for subsequent commands. - -###### Parameters - -| Parameter | Type | Description | -| ------ | ------ | ------ | -| `user` | `string` | Username | - -###### Returns - -`TemplateBuilder` - -###### Example - -```ts -template.setUser('root') -``` - -###### Implementation of - -`TemplateBuilder`.`setUser` - -### setWorkdir() - -```ts -setWorkdir(workdir: PathLike): TemplateBuilder -``` - -Set the working directory. - -###### Parameters - -| Parameter | Type | Description | -| ------ | ------ | ------ | -| `workdir` | `PathLike` | Working directory path | - -###### Returns - -`TemplateBuilder` - -###### Example - -```ts -template.setWorkdir('/app') -``` - -###### Implementation of - -`TemplateBuilder`.`setWorkdir` - -### skipCache() - -```ts -skipCache(): this -``` - -Skip cache for all subsequent build instructions from this point. - -###### Returns - -`this` - -###### Example - -```ts -Template().skipCache().fromPythonImage('3') -``` - -###### Implementation of - -`TemplateBuilder`.`skipCache` - -### build() - -```ts -static build(template: TemplateClass, options: BuildOptions): Promise -``` - -Build and deploy a template to E2B infrastructure. - -###### Parameters - -| Parameter | Type | Description | -| ------ | ------ | ------ | -| `template` | `TemplateClass` | The template to build | -| `options` | `BuildOptions` | Build configuration options | - -###### Returns - -`Promise`\<`BuildInfo`\> - -###### Example - -```ts -const template = Template().fromPythonImage('3') -await Template.build(template, { - alias: 'my-python-env', - cpuCount: 2, - memoryMB: 1024 -}) -``` - -### buildInBackground() - -```ts -static buildInBackground(template: TemplateClass, options: BuildOptions): Promise -``` - -Build and deploy a template to E2B infrastructure. - -###### Parameters - -| Parameter | Type | Description | -| ------ | ------ | ------ | -| `template` | `TemplateClass` | The template to build | -| `options` | `BuildOptions` | Build configuration options | - -###### Returns - -`Promise`\<`BuildInfo`\> - -###### Example - -```ts -const template = Template().fromPythonImage('3') -const data = await Template.buildInBackground(template, { - alias: 'my-python-env', - cpuCount: 2, - memoryMB: 1024 -}) -``` - -### getBuildStatus() - -```ts -static getBuildStatus(data: Pick, options?: GetBuildStatusOptions): Promise -``` - -Get the status of a build. - -###### Parameters - -| Parameter | Type | Description | -| ------ | ------ | ------ | -| `data` | `Pick`\<`BuildInfo`, `"templateId"` \| `"buildId"`\> | Build identifiers | -| `options`? | `GetBuildStatusOptions` | Authentication options | - -###### Returns - -`Promise`\<`object`\> - -| Name | Type | Description | -| ------ | ------ | ------ | -| `buildID` | `string` | **Description** Identifier of the build | -| `logEntries` | `object`[] | **Description** Build logs structured **Default** `[]` | -| `logs` | `string`[] | **Description** Build logs **Default** `[]` | -| `reason`? | `object` | - | -| `reason.logEntries`? | `object`[] | **Description** Log entries related to the status reason **Default** `[]` | -| `reason.message` | `string` | **Description** Message with the status reason, currently reporting only for error status | -| `reason.step`? | `string` | **Description** Step that failed | -| `status` | `"error"` \| `"ready"` \| `"building"` \| `"waiting"` | - | -| `templateID` | `string` | **Description** Identifier of the template | - -###### Example - -```ts -const status = await Template.getBuildStatus(data, { logsOffset: 0 }) -``` - -### toDockerfile() - -```ts -static toDockerfile(template: TemplateClass): string -``` - -Convert a template to Dockerfile format. -Note: Templates based on other E2B templates cannot be converted to Dockerfile. - -###### Parameters - -| Parameter | Type | Description | -| ------ | ------ | ------ | -| `template` | `TemplateClass` | The template to convert | - -###### Returns - -`string` - -Dockerfile string representation - -###### Throws - -Error if the template is based on another E2B template - -### toJSON() - -```ts -static toJSON(template: TemplateClass, computeHashes: boolean): Promise -``` - -Convert a template to JSON representation. - -###### Parameters - -| Parameter | Type | Default value | Description | -| ------ | ------ | ------ | ------ | -| `template` | `TemplateClass` | `undefined` | The template to convert | -| `computeHashes` | `boolean` | `true` | Whether to compute file hashes for cache invalidation | - -###### Returns - -`Promise`\<`string`\> - -JSON string representation of the template - -## Interfaces - -### TemplateBuilder - -Main builder state for constructing templates. -Provides methods for customizing the template environment. - -#### Methods - -### addMcpServer() - -```ts -addMcpServer(servers: keyof McpServer | keyof McpServer[]): TemplateBuilder -``` - -Install MCP servers using mcp-gateway. -Note: Requires a base image with mcp-gateway pre-installed (e.g., mcp-gateway). - -###### Parameters - -| Parameter | Type | Description | -| ------ | ------ | ------ | -| `servers` | keyof McpServer \| keyof McpServer[] | MCP server name(s) | - -###### Returns - -`TemplateBuilder` - -###### Throws - -If the base template is not mcp-gateway - -###### Example - -```ts -template.addMcpServer('exa') -template.addMcpServer(['brave', 'firecrawl', 'duckduckgo']) -``` - -### aptInstall() - -```ts -aptInstall(packages: string | string[], options?: object): TemplateBuilder -``` - -Install Debian/Ubuntu packages using apt-get. - -###### Parameters - -| Parameter | Type | Description | -| ------ | ------ | ------ | -| `packages` | `string` \| `string`[] | Package name(s) | -| `options`? | `object` | - | -| `options.noInstallRecommends`? | `boolean` | - | - -###### Returns - -`TemplateBuilder` - -###### Example - -```ts -template.aptInstall('vim') -template.aptInstall(['git', 'curl', 'wget']) -template.aptInstall(['vim'], { noInstallRecommends: true }) -``` - -### betaDevContainerPrebuild() - -```ts -betaDevContainerPrebuild(devcontainerDirectory: string): TemplateBuilder -``` - -Prebuild a devcontainer from the specified directory. - -###### Parameters - -| Parameter | Type | Description | -| ------ | ------ | ------ | -| `devcontainerDirectory` | `string` | Path to the devcontainer directory | - -###### Returns - -`TemplateBuilder` - -###### Example - -```ts -template - .gitClone('https://myrepo.com/project.git', '/my-devcontainer') - .betaDevContainerPrebuild('/my-devcontainer') -``` - -### betaSetDevContainerStart() - -```ts -betaSetDevContainerStart(devcontainerDirectory: string): TemplateFinal -``` - -Start a devcontainer from the specified directory. - -###### Parameters - -| Parameter | Type | Description | -| ------ | ------ | ------ | -| `devcontainerDirectory` | `string` | Path to the devcontainer directory | - -###### Returns - -`TemplateFinal` - -###### Example - -```ts -template - .gitClone('https://myrepo.com/project.git', '/my-devcontainer') - .startDevcontainer('/my-devcontainer') - -// Prebuild and start -template - .gitClone('https://myrepo.com/project.git', '/my-devcontainer') - .betaDevContainerPrebuild('/my-devcontainer') - // Other instructions... - .betaSetDevContainerStart('/my-devcontainer') -``` - -### bunInstall() - -```ts -bunInstall(packages?: string | string[], options?: object): TemplateBuilder -``` - -Install Bun packages using bun. - -###### Parameters - -| Parameter | Type | Description | -| ------ | ------ | ------ | -| `packages`? | `string` \| `string`[] | Package name(s) or undefined for package.json | -| `options`? | `object` | Install options | -| `options.dev`? | `boolean` | - | -| `options.g`? | `boolean` | - | - -###### Returns - -`TemplateBuilder` - -###### Example - -```ts -template.bunInstall('express') -template.bunInstall(['lodash', 'axios']) -template.bunInstall('tsx', { g: true }) -template.bunInstall('typescript', { dev: true }) -template.bunInstall() // Installs from package.json -``` - -### copy() - -```ts -copy( - src: PathLike | PathLike[], - dest: PathLike, - options?: object): TemplateBuilder -``` - -Copy files or directories into the template. - -###### Parameters - -| Parameter | Type | Description | -| ------ | ------ | ------ | -| `src` | `PathLike` \| `PathLike`[] | Source path(s) | -| `dest` | `PathLike` | Destination path | -| `options`? | `object` | Copy options | -| `options.forceUpload`? | `true` | - | -| `options.mode`? | `number` | - | -| `options.resolveSymlinks`? | `boolean` | - | -| `options.user`? | `string` | - | - -###### Returns - -`TemplateBuilder` - -###### Example - -```ts -template.copy('requirements.txt', '/home/user/') -template.copy(['app.ts', 'config.ts'], '/app/', { mode: 0o755 }) -``` - -### copyItems() - -```ts -copyItems(items: CopyItem[]): TemplateBuilder -``` - -Copy multiple items with individual options. - -###### Parameters - -| Parameter | Type | Description | -| ------ | ------ | ------ | -| `items` | `CopyItem`[] | Array of copy items | - -###### Returns - -`TemplateBuilder` - -###### Example - -```ts -template.copyItems([ - { src: 'app.ts', dest: '/app/' }, - { src: 'config.ts', dest: '/app/', mode: 0o644 } -]) -``` - -### gitClone() - -```ts -gitClone( - url: string, - path?: PathLike, - options?: object): TemplateBuilder -``` - -Clone a Git repository. - -###### Parameters - -| Parameter | Type | Description | -| ------ | ------ | ------ | -| `url` | `string` | Repository URL | -| `path`? | `PathLike` | Optional destination path | -| `options`? | `object` | Clone options | -| `options.branch`? | `string` | - | -| `options.depth`? | `number` | - | -| `options.user`? | `string` | - | - -###### Returns - -`TemplateBuilder` - -###### Example - -```ts -template.gitClone('https://github.com/user/repo.git', '/app/repo') -template.gitClone('https://github.com/user/repo.git', undefined, { - branch: 'main', - depth: 1 -}) -template.gitClone('https://github.com/user/repo.git', '/app/repo', { - user: 'root' -}) -``` - -### makeDir() - -```ts -makeDir(path: PathLike | PathLike[], options?: object): TemplateBuilder -``` - -Create directories. - -###### Parameters - -| Parameter | Type | Description | -| ------ | ------ | ------ | -| `path` | `PathLike` \| `PathLike`[] | Directory path(s) | -| `options`? | `object` | Directory options | -| `options.mode`? | `number` | - | -| `options.user`? | `string` | - | - -###### Returns - -`TemplateBuilder` - -###### Example - -```ts -template.makeDir('/app/data', { mode: 0o755 }) -template.makeDir(['/app/logs', '/app/cache']) -template.makeDir('/app/data', { mode: 0o755, user: 'root' }) -``` - -### makeSymlink() - -```ts -makeSymlink( - src: PathLike, - dest: PathLike, - options?: object): TemplateBuilder -``` - -Create a symbolic link. - -###### Parameters - -| Parameter | Type | Description | -| ------ | ------ | ------ | -| `src` | `PathLike` | Source path (target) | -| `dest` | `PathLike` | Destination path (symlink location) | -| `options`? | `object` | Symlink options | -| `options.force`? | `boolean` | - | -| `options.user`? | `string` | - | - -###### Returns - -`TemplateBuilder` - -###### Example - -```ts -template.makeSymlink('/usr/bin/python3', '/usr/bin/python') -template.makeSymlink('/usr/bin/python3', '/usr/bin/python', { user: 'root' }) -template.makeSymlink('/usr/bin/python3', '/usr/bin/python', { force: true }) -``` - -### npmInstall() - -```ts -npmInstall(packages?: string | string[], options?: object): TemplateBuilder -``` - -Install Node.js packages using npm. - -###### Parameters - -| Parameter | Type | Description | -| ------ | ------ | ------ | -| `packages`? | `string` \| `string`[] | Package name(s) or undefined for package.json | -| `options`? | `object` | Install options | -| `options.dev`? | `boolean` | - | -| `options.g`? | `boolean` | - | - -###### Returns - -`TemplateBuilder` - -###### Example - -```ts -template.npmInstall('express') -template.npmInstall(['lodash', 'axios']) -template.npmInstall('tsx', { g: true }) -template.npmInstall('typescript', { dev: true }) -template.npmInstall() // Installs from package.json -``` - -### pipInstall() - -```ts -pipInstall(packages?: string | string[], options?: object): TemplateBuilder -``` - -Install Python packages using pip. - -###### Parameters - -| Parameter | Type | Description | -| ------ | ------ | ------ | -| `packages`? | `string` \| `string`[] | Package name(s) or undefined for current directory | -| `options`? | `object` | Install options | -| `options.g`? | `boolean` | Install globally as root (default: true). Set to false for user-only installation with --user flag | - -###### Returns - -`TemplateBuilder` - -###### Example - -```ts -template.pipInstall('numpy') // Installs globally (default) -template.pipInstall(['pandas', 'scikit-learn']) -template.pipInstall('numpy', { g: false }) // Install for user only -template.pipInstall() // Installs from current directory -``` - -### remove() - -```ts -remove(path: PathLike | PathLike[], options?: object): TemplateBuilder -``` - -Remove files or directories. - -###### Parameters - -| Parameter | Type | Description | -| ------ | ------ | ------ | -| `path` | `PathLike` \| `PathLike`[] | Path(s) to remove | -| `options`? | `object` | Remove options | -| `options.force`? | `boolean` | - | -| `options.recursive`? | `boolean` | - | -| `options.user`? | `string` | - | - -###### Returns - -`TemplateBuilder` - -###### Example - -```ts -template.remove('/tmp/cache', { recursive: true, force: true }) -template.remove('/tmp/cache', { recursive: true, force: true, user: 'root' }) -``` - -### rename() - -```ts -rename( - src: PathLike, - dest: PathLike, - options?: object): TemplateBuilder -``` - -Rename or move a file or directory. - -###### Parameters - -| Parameter | Type | Description | -| ------ | ------ | ------ | -| `src` | `PathLike` | Source path | -| `dest` | `PathLike` | Destination path | -| `options`? | `object` | Rename options | -| `options.force`? | `boolean` | - | -| `options.user`? | `string` | - | - -###### Returns - -`TemplateBuilder` - -###### Example - -```ts -template.rename('/tmp/old.txt', '/tmp/new.txt') -template.rename('/tmp/old.txt', '/tmp/new.txt', { user: 'root' }) -``` - -### runCmd() - -###### runCmd(command, options) - -```ts -runCmd(command: string, options?: object): TemplateBuilder -``` - -Run a shell command. - -###### Parameters - -| Parameter | Type | Description | -| ------ | ------ | ------ | -| `command` | `string` | Command string | -| `options`? | `object` | Command options | -| `options.user`? | `string` | - | - -###### Returns - -`TemplateBuilder` - -###### Example - -```ts -template.runCmd('apt-get update') -template.runCmd(['pip install numpy', 'pip install pandas']) -template.runCmd('apt-get install vim', { user: 'root' }) -``` - -###### runCmd(commands, options) - -```ts -runCmd(commands: string[], options?: object): TemplateBuilder -``` - -Run multiple shell commands. - -###### Parameters - -| Parameter | Type | Description | -| ------ | ------ | ------ | -| `commands` | `string`[] | Array of command strings | -| `options`? | `object` | Command options | -| `options.user`? | `string` | - | - -###### Returns - -`TemplateBuilder` - -###### runCmd(commandOrCommands, options) - -```ts -runCmd(commandOrCommands: string | string[], options?: object): TemplateBuilder -``` - -Run command(s). - -###### Parameters - -| Parameter | Type | Description | -| ------ | ------ | ------ | -| `commandOrCommands` | `string` \| `string`[] | Command or commands | -| `options`? | `object` | Command options | -| `options.user`? | `string` | - | - -###### Returns - -`TemplateBuilder` - -### setEnvs() - -```ts -setEnvs(envs: Record): TemplateBuilder -``` - -Set environment variables. - -###### Parameters - -| Parameter | Type | Description | -| ------ | ------ | ------ | -| `envs` | `Record`\<`string`, `string`\> | Environment variables | - -###### Returns - -`TemplateBuilder` - -###### Example - -```ts -template.setEnvs({ NODE_ENV: 'production', PORT: '8080' }) -``` - -### setReadyCmd() - -```ts -setReadyCmd(readyCommand: string | ReadyCmd): TemplateFinal -``` - -Set or update the ready check command. - -###### Parameters - -| Parameter | Type | Description | -| ------ | ------ | ------ | -| `readyCommand` | `string` \| `ReadyCmd` | Command to check readiness | - -###### Returns - -`TemplateFinal` - -###### Example - -```ts -// Using a string command -template.setReadyCmd('curl http://localhost:8000/health') - -// Using ReadyCmd helpers -import { waitForPort, waitForFile, waitForProcess } from 'e2b' - -template.setReadyCmd(waitForPort(3000)) - -template.setReadyCmd(waitForFile('/tmp/ready')) - -template.setReadyCmd(waitForProcess('nginx')) -``` - -### setStartCmd() - -```ts -setStartCmd(startCommand: string, readyCommand: string | ReadyCmd): TemplateFinal -``` - -Set the start command and ready check. - -###### Parameters - -| Parameter | Type | Description | -| ------ | ------ | ------ | -| `startCommand` | `string` | Command to run on startup | -| `readyCommand` | `string` \| `ReadyCmd` | Command to check readiness | - -###### Returns - -`TemplateFinal` - -###### Example - -```ts -// Using a string command -template.setStartCmd( - 'node app.js', - 'curl http://localhost:8000/health' -) - -// Using ReadyCmd helpers -import { waitForPort, waitForURL } from 'e2b' - -template.setStartCmd( - 'python -m http.server 8000', - waitForPort(8000) -) - -template.setStartCmd( - 'npm start', - waitForURL('http://localhost:3000/health', 200) -) -``` - -### setUser() - -```ts -setUser(user: string): TemplateBuilder -``` - -Set the user for subsequent commands. - -###### Parameters - -| Parameter | Type | Description | -| ------ | ------ | ------ | -| `user` | `string` | Username | - -###### Returns - -`TemplateBuilder` - -###### Example - -```ts -template.setUser('root') -``` - -### setWorkdir() - -```ts -setWorkdir(workdir: PathLike): TemplateBuilder -``` - -Set the working directory. - -###### Parameters - -| Parameter | Type | Description | -| ------ | ------ | ------ | -| `workdir` | `PathLike` | Working directory path | - -###### Returns - -`TemplateBuilder` - -###### Example - -```ts -template.setWorkdir('/app') -``` - -### skipCache() - -```ts -skipCache(): this -``` - -Skip cache for all subsequent build instructions from this point. - -###### Returns - -`this` - -###### Example - -```ts -template.skipCache().runCmd('apt-get update') -``` - -## Type Aliases - -### BuildInfo - -```ts -type BuildInfo: object; -``` - -Information about a built template. - -#### Type declaration - -| Name | Type | -| ------ | ------ | -| `alias` | `string` | -| `buildId` | `string` | -| `templateId` | `string` | - -*** - -### BuildOptions - -```ts -type BuildOptions: AuthOptions & BasicBuildOptions; -``` - -Options for building a template with authentication. - -*** - -### CopyItem - -```ts -type CopyItem: object; -``` - -Configuration for a single file/directory copy operation. - -#### Type declaration - -| Name | Type | -| ------ | ------ | -| `dest` | `PathLike` | -| `forceUpload`? | `true` | -| `mode`? | `number` | -| `resolveSymlinks`? | `boolean` | -| `src` | `PathLike` \| `PathLike`[] | -| `user`? | `string` | - -*** - -### GetBuildStatusOptions - -```ts -type GetBuildStatusOptions: AuthOptions & object; -``` - -Response from getting build status. - -#### Type declaration - -| Name | Type | -| ------ | ------ | -| `logsOffset`? | `number` | - -*** - -### McpServerName - -```ts -type McpServerName: keyof McpServer; -``` - -MCP server names that can be installed. - -*** - -### TemplateClass - -```ts -type TemplateClass: TemplateBuilder | TemplateFinal; -``` - -Type representing a template in any state (builder or final). - -## Functions - -### Template() - -```ts -function Template(options?: TemplateOptions): TemplateFromImage -``` - -Create a new E2B template builder instance. - -#### Parameters - -| Parameter | Type | Description | -| ------ | ------ | ------ | -| `options`? | `TemplateOptions` | Optional configuration for the template builder | - -#### Returns - -`TemplateFromImage` - -A new template builder instance - -#### Example - -```ts -import { Template } from 'e2b' - -const template = Template() - .fromPythonImage('3') - .copy('requirements.txt', '/app/') - .pipInstall() - -await Template.build(template, { alias: 'my-python-app' }) -``` diff --git a/docs/sdk-reference/js-sdk/v2.9.0/errors.mdx b/docs/sdk-reference/js-sdk/v2.9.0/errors.mdx deleted file mode 100644 index bfe0deb..0000000 --- a/docs/sdk-reference/js-sdk/v2.9.0/errors.mdx +++ /dev/null @@ -1,271 +0,0 @@ ---- -sidebarTitle: "Errors" -mode: "center" ---- - -### AuthenticationError - -Thrown when authentication fails. - -#### Constructors - -```ts -new AuthenticationError(message: string): AuthenticationError -``` - -###### Parameters - -| Parameter | Type | -| ------ | ------ | -| `message` | `string` | - -###### Returns - -`AuthenticationError` - -*** - -### BuildError - -Thrown when the build fails. - -#### Extended by - -- `FileUploadError` - -#### Constructors - -```ts -new BuildError(message: string, stackTrace?: string): BuildError -``` - -###### Parameters - -| Parameter | Type | -| ------ | ------ | -| `message` | `string` | -| `stackTrace`? | `string` | - -###### Returns - -`BuildError` - -*** - -### FileUploadError - -Thrown when the file upload fails. - -#### Constructors - -```ts -new FileUploadError(message: string, stackTrace?: string): FileUploadError -``` - -###### Parameters - -| Parameter | Type | -| ------ | ------ | -| `message` | `string` | -| `stackTrace`? | `string` | - -###### Returns - -`FileUploadError` - -*** - -### InvalidArgumentError - -Thrown when an invalid argument is provided. - -#### Constructors - -```ts -new InvalidArgumentError(message: string, stackTrace?: string): InvalidArgumentError -``` - -###### Parameters - -| Parameter | Type | -| ------ | ------ | -| `message` | `string` | -| `stackTrace`? | `string` | - -###### Returns - -`InvalidArgumentError` - -*** - -### NotEnoughSpaceError - -Thrown when there is not enough disk space. - -#### Constructors - -```ts -new NotEnoughSpaceError(message: string, stackTrace?: string): NotEnoughSpaceError -``` - -###### Parameters - -| Parameter | Type | -| ------ | ------ | -| `message` | `string` | -| `stackTrace`? | `string` | - -###### Returns - -`NotEnoughSpaceError` - -*** - -### NotFoundError - -Thrown when a resource is not found. - -#### Constructors - -```ts -new NotFoundError(message: string, stackTrace?: string): NotFoundError -``` - -###### Parameters - -| Parameter | Type | -| ------ | ------ | -| `message` | `string` | -| `stackTrace`? | `string` | - -###### Returns - -`NotFoundError` - -*** - -### RateLimitError - -Thrown when the API rate limit is exceeded. - -#### Constructors - -```ts -new RateLimitError(message: string): RateLimitError -``` - -###### Parameters - -| Parameter | Type | -| ------ | ------ | -| `message` | `string` | - -###### Returns - -`RateLimitError` - -*** - -### SandboxError - -Base class for all sandbox errors. - -Thrown when general sandbox errors occur. - -#### Extended by - -- `TimeoutError` -- `InvalidArgumentError` -- `NotEnoughSpaceError` -- `NotFoundError` -- `TemplateError` -- `RateLimitError` - -#### Constructors - -```ts -new SandboxError(message?: string, stackTrace?: string): SandboxError -``` - -###### Parameters - -| Parameter | Type | -| ------ | ------ | -| `message`? | `string` | -| `stackTrace`? | `string` | - -###### Returns - -`SandboxError` - -*** - -### TemplateError - -Thrown when the template uses old envd version. It isn't compatible with the new SDK. - -#### Constructors - -```ts -new TemplateError(message: string, stackTrace?: string): TemplateError -``` - -###### Parameters - -| Parameter | Type | -| ------ | ------ | -| `message` | `string` | -| `stackTrace`? | `string` | - -###### Returns - -`TemplateError` - -*** - -### TimeoutError - -Thrown when a timeout error occurs. - -The [unavailable] error type is caused by sandbox timeout. - -The [canceled] error type is caused by exceeding request timeout. - -The [deadline_exceeded] error type is caused by exceeding the timeout for command execution, watch, etc. - -The [unknown] error type is sometimes caused by the sandbox timeout when the request is not processed correctly. - -#### Constructors - -```ts -new TimeoutError(message: string, stackTrace?: string): TimeoutError -``` - -###### Parameters - -| Parameter | Type | -| ------ | ------ | -| `message` | `string` | -| `stackTrace`? | `string` | - -###### Returns - -`TimeoutError` - -## Functions - -### formatSandboxTimeoutError() - -```ts -function formatSandboxTimeoutError(message: string): TimeoutError -``` - -#### Parameters - -| Parameter | Type | -| ------ | ------ | -| `message` | `string` | - -#### Returns - -`TimeoutError` diff --git a/docs/sdk-reference/js-sdk/v2.9.0/sandbox-commands.mdx b/docs/sdk-reference/js-sdk/v2.9.0/sandbox-commands.mdx deleted file mode 100644 index bebbd9a..0000000 --- a/docs/sdk-reference/js-sdk/v2.9.0/sandbox-commands.mdx +++ /dev/null @@ -1,554 +0,0 @@ ---- -sidebarTitle: "Commands" -mode: "center" ---- - -### Commands - -Module for starting and interacting with commands in the sandbox. - -#### Constructors - -```ts -new Commands( - transport: Transport, - connectionConfig: ConnectionConfig, - metadata: object): Commands -``` - -###### Parameters - -| Parameter | Type | -| ------ | ------ | -| `transport` | `Transport` | -| `connectionConfig` | `ConnectionConfig` | -| `metadata` | `object` | -| `metadata.version` | `string` | - -###### Returns - -`Commands` - -#### Methods - -### connect() - -```ts -connect(pid: number, opts?: CommandConnectOpts): Promise -``` - -Connect to a running command. -You can use CommandHandle.wait to wait for the command to finish and get execution results. - -###### Parameters - -| Parameter | Type | Description | -| ------ | ------ | ------ | -| `pid` | `number` | process ID of the command to connect to. You can get the list of running commands using Commands.list. | -| `opts`? | `CommandConnectOpts` | connection options. | - -###### Returns - -`Promise`\<`CommandHandle`\> - -`CommandHandle` handle to interact with the running command. - -### kill() - -```ts -kill(pid: number, opts?: CommandRequestOpts): Promise -``` - -Kill a running command specified by its process ID. -It uses `SIGKILL` signal to kill the command. - -###### Parameters - -| Parameter | Type | Description | -| ------ | ------ | ------ | -| `pid` | `number` | process ID of the command. You can get the list of running commands using Commands.list. | -| `opts`? | `CommandRequestOpts` | connection options. | - -###### Returns - -`Promise`\<`boolean`\> - -`true` if the command was killed, `false` if the command was not found. - -### list() - -```ts -list(opts?: CommandRequestOpts): Promise -``` - -List all running commands and PTY sessions. - -###### Parameters - -| Parameter | Type | Description | -| ------ | ------ | ------ | -| `opts`? | `CommandRequestOpts` | connection options. | - -###### Returns - -`Promise`\<`ProcessInfo`[]\> - -list of running commands and PTY sessions. - -### run() - -###### run(cmd, opts) - -```ts -run(cmd: string, opts?: CommandStartOpts & object): Promise -``` - -Start a new command and wait until it finishes executing. - -###### Parameters - -| Parameter | Type | Description | -| ------ | ------ | ------ | -| `cmd` | `string` | command to execute. | -| `opts`? | `CommandStartOpts` & `object` | options for starting the command. | - -###### Returns - -`Promise`\<`CommandResult`\> - -`CommandResult` result of the command execution. - -###### run(cmd, opts) - -```ts -run(cmd: string, opts: CommandStartOpts & object): Promise -``` - -Start a new command in the background. -You can use CommandHandle.wait to wait for the command to finish and get its result. - -###### Parameters - -| Parameter | Type | Description | -| ------ | ------ | ------ | -| `cmd` | `string` | command to execute. | -| `opts` | `CommandStartOpts` & `object` | options for starting the command | - -###### Returns - -`Promise`\<`CommandHandle`\> - -`CommandHandle` handle to interact with the running command. - -###### run(cmd, opts) - -```ts -run(cmd: string, opts?: CommandStartOpts & object): Promise -``` - -Start a new command. - -###### Parameters - -| Parameter | Type | Description | -| ------ | ------ | ------ | -| `cmd` | `string` | command to execute. | -| `opts`? | `CommandStartOpts` & `object` | options for starting the command. - `opts.background: true` - runs in background, returns `CommandHandle` - `opts.background: false | undefined` - waits for completion, returns `CommandResult` | - -###### Returns - -`Promise`\<`CommandResult` \| `CommandHandle`\> - -Either a `CommandHandle` or a `CommandResult` (depending on `opts.background`). - -### sendStdin() - -```ts -sendStdin( - pid: number, - data: string, -opts?: CommandRequestOpts): Promise -``` - -Send data to command stdin. - -###### Parameters - -| Parameter | Type | Description | -| ------ | ------ | ------ | -| `pid` | `number` | process ID of the command. You can get the list of running commands using Commands.list. | -| `data` | `string` | data to send to the command. | -| `opts`? | `CommandRequestOpts` | connection options. | - -###### Returns - -`Promise`\<`void`\> - -*** - -### Pty - -Module for interacting with PTYs (pseudo-terminals) in the sandbox. - -#### Constructors - -```ts -new Pty( - transport: Transport, - connectionConfig: ConnectionConfig, - metadata: object): Pty -``` - -###### Parameters - -| Parameter | Type | -| ------ | ------ | -| `transport` | `Transport` | -| `connectionConfig` | `ConnectionConfig` | -| `metadata` | `object` | -| `metadata.version` | `string` | - -###### Returns - -`Pty` - -#### Methods - -### connect() - -```ts -connect(pid: number, opts?: PtyConnectOpts): Promise -``` - -Connect to a running PTY. - -###### Parameters - -| Parameter | Type | Description | -| ------ | ------ | ------ | -| `pid` | `number` | process ID of the PTY to connect to. You can get the list of running PTYs using Commands.list. | -| `opts`? | `PtyConnectOpts` | connection options. | - -###### Returns - -`Promise`\<`CommandHandle`\> - -handle to interact with the PTY. - -### create() - -```ts -create(opts: PtyCreateOpts): Promise -``` - -Create a new PTY (pseudo-terminal). - -###### Parameters - -| Parameter | Type | Description | -| ------ | ------ | ------ | -| `opts` | `PtyCreateOpts` | options for creating the PTY. | - -###### Returns - -`Promise`\<`CommandHandle`\> - -handle to interact with the PTY. - -### kill() - -```ts -kill(pid: number, opts?: Pick): Promise -``` - -Kill a running PTY specified by process ID. -It uses `SIGKILL` signal to kill the PTY. - -###### Parameters - -| Parameter | Type | Description | -| ------ | ------ | ------ | -| `pid` | `number` | process ID of the PTY. | -| `opts`? | `Pick`\<`ConnectionOpts`, `"requestTimeoutMs"`\> | connection options. | - -###### Returns - -`Promise`\<`boolean`\> - -`true` if the PTY was killed, `false` if the PTY was not found. - -### resize() - -```ts -resize( - pid: number, - size: object, -opts?: Pick): Promise -``` - -Resize PTY. -Call this when the terminal window is resized and the number of columns and rows has changed. - -###### Parameters - -| Parameter | Type | Description | -| ------ | ------ | ------ | -| `pid` | `number` | process ID of the PTY. | -| `size` | `object` | new size of the PTY. | -| `size.cols` | `number` | - | -| `size.rows`? | `number` | - | -| `opts`? | `Pick`\<`ConnectionOpts`, `"requestTimeoutMs"`\> | connection options. | - -###### Returns - -`Promise`\<`void`\> - -### sendInput() - -```ts -sendInput( - pid: number, - data: Uint8Array, -opts?: Pick): Promise -``` - -Send input to a PTY. - -###### Parameters - -| Parameter | Type | Description | -| ------ | ------ | ------ | -| `pid` | `number` | process ID of the PTY. | -| `data` | `Uint8Array` | input data to send to the PTY. | -| `opts`? | `Pick`\<`ConnectionOpts`, `"requestTimeoutMs"`\> | connection options. | - -###### Returns - -`Promise`\<`void`\> - -## Interfaces - -### CommandRequestOpts - -Options for sending a command request. - -#### Extended by - -- `CommandStartOpts` - -#### Properties - -### requestTimeoutMs? - -```ts -optional requestTimeoutMs: number; -``` - -Timeout for requests to the API in **milliseconds**. - -###### Default - -```ts -60_000 // 60 seconds -``` - -*** - -### CommandStartOpts - -Options for starting a new command. - -#### Properties - -### background? - -```ts -optional background: boolean; -``` - -If true, starts command in the background and the method returns immediately. -You can use CommandHandle.wait to wait for the command to finish. - -### cwd? - -```ts -optional cwd: string; -``` - -Working directory for the command. - -###### Default - -```ts -// home directory of the user used to start the command -``` - -### envs? - -```ts -optional envs: Record; -``` - -Environment variables used for the command. - -This overrides the default environment variables from `Sandbox` constructor. - -###### Default - -`{}` - -### onStderr()? - -```ts -optional onStderr: (data: string) => void | Promise; -``` - -Callback for command stderr output. - -###### Parameters - -| Parameter | Type | -| ------ | ------ | -| `data` | `string` | - -###### Returns - -`void` \| `Promise`\<`void`\> - -### onStdout()? - -```ts -optional onStdout: (data: string) => void | Promise; -``` - -Callback for command stdout output. - -###### Parameters - -| Parameter | Type | -| ------ | ------ | -| `data` | `string` | - -###### Returns - -`void` \| `Promise`\<`void`\> - -### requestTimeoutMs? - -```ts -optional requestTimeoutMs: number; -``` - -Timeout for requests to the API in **milliseconds**. - -###### Default - -```ts -60_000 // 60 seconds -``` - -### stdin? - -```ts -optional stdin: boolean; -``` - -If true, command stdin is kept open and you can send data to it using Commands.sendStdin or CommandHandle.sendStdin. - -###### Default - -```ts -false -``` - -### timeoutMs? - -```ts -optional timeoutMs: number; -``` - -Timeout for the command in **milliseconds**. - -###### Default - -```ts -60_000 // 60 seconds -``` - -### user? - -```ts -optional user: string; -``` - -User to run the command as. - -###### Default - -`default Sandbox user (as specified in the template)` - -*** - -### ProcessInfo - -Information about a command, PTY session or start command running in the sandbox as process. - -#### Properties - -### args - -```ts -args: string[]; -``` - -Command arguments. - -### cmd - -```ts -cmd: string; -``` - -Command that was executed. - -### cwd? - -```ts -optional cwd: string; -``` - -Executed command working directory. - -### envs - -```ts -envs: Record; -``` - -Environment variables used for the command. - -### pid - -```ts -pid: number; -``` - -Process ID. - -### tag? - -```ts -optional tag: string; -``` - -Custom tag used for identifying special commands like start command in the custom template. - -## Type Aliases - -### CommandConnectOpts - -```ts -type CommandConnectOpts: Pick & CommandRequestOpts; -``` - -Options for connecting to a command. diff --git a/docs/sdk-reference/js-sdk/v2.9.0/sandbox-filesystem.mdx b/docs/sdk-reference/js-sdk/v2.9.0/sandbox-filesystem.mdx deleted file mode 100644 index c43ac2f..0000000 --- a/docs/sdk-reference/js-sdk/v2.9.0/sandbox-filesystem.mdx +++ /dev/null @@ -1,627 +0,0 @@ ---- -sidebarTitle: "Filesystem" -mode: "center" ---- - -### FileType - -Sandbox filesystem object type. - -#### Enumeration Members - -| Enumeration Member | Value | Description | -| ------ | ------ | ------ | -| `DIR` | `"dir"` | Filesystem object is a directory. | -| `FILE` | `"file"` | Filesystem object is a file. | - -## Classes - -### Filesystem - -Module for interacting with the sandbox filesystem. - -#### Constructors - -```ts -new Filesystem( - transport: Transport, - envdApi: EnvdApiClient, - connectionConfig: ConnectionConfig): Filesystem -``` - -###### Parameters - -| Parameter | Type | -| ------ | ------ | -| `transport` | `Transport` | -| `envdApi` | `EnvdApiClient` | -| `connectionConfig` | `ConnectionConfig` | - -###### Returns - -`Filesystem` - -#### Methods - -### exists() - -```ts -exists(path: string, opts?: FilesystemRequestOpts): Promise -``` - -Check if a file or a directory exists. - -###### Parameters - -| Parameter | Type | Description | -| ------ | ------ | ------ | -| `path` | `string` | path to a file or a directory | -| `opts`? | `FilesystemRequestOpts` | connection options. | - -###### Returns - -`Promise`\<`boolean`\> - -`true` if the file or directory exists, `false` otherwise - -### getInfo() - -```ts -getInfo(path: string, opts?: FilesystemRequestOpts): Promise -``` - -Get information about a file or directory. - -###### Parameters - -| Parameter | Type | Description | -| ------ | ------ | ------ | -| `path` | `string` | path to a file or directory. | -| `opts`? | `FilesystemRequestOpts` | connection options. | - -###### Returns - -`Promise`\<`EntryInfo`\> - -information about the file or directory like name, type, and path. - -### list() - -```ts -list(path: string, opts?: FilesystemListOpts): Promise -``` - -List entries in a directory. - -###### Parameters - -| Parameter | Type | Description | -| ------ | ------ | ------ | -| `path` | `string` | path to the directory. | -| `opts`? | `FilesystemListOpts` | connection options. | - -###### Returns - -`Promise`\<`EntryInfo`[]\> - -list of entries in the sandbox filesystem directory. - -### makeDir() - -```ts -makeDir(path: string, opts?: FilesystemRequestOpts): Promise -``` - -Create a new directory and all directories along the way if needed on the specified path. - -###### Parameters - -| Parameter | Type | Description | -| ------ | ------ | ------ | -| `path` | `string` | path to a new directory. For example '/dirA/dirB' when creating 'dirB'. | -| `opts`? | `FilesystemRequestOpts` | connection options. | - -###### Returns - -`Promise`\<`boolean`\> - -`true` if the directory was created, `false` if it already exists. - -### read() - -###### read(path, opts) - -```ts -read(path: string, opts?: FilesystemRequestOpts & object): Promise -``` - -Read file content as a `string`. - -You can pass `text`, `bytes`, `blob`, or `stream` to `opts.format` to change the return type. - -###### Parameters - -| Parameter | Type | Description | -| ------ | ------ | ------ | -| `path` | `string` | path to the file. | -| `opts`? | `FilesystemRequestOpts` & `object` | connection options. | - -###### Returns - -`Promise`\<`string`\> - -file content as string - -###### read(path, opts) - -```ts -read(path: string, opts?: FilesystemRequestOpts & object): Promise -``` - -Read file content as a `Uint8Array`. - -You can pass `text`, `bytes`, `blob`, or `stream` to `opts.format` to change the return type. - -###### Parameters - -| Parameter | Type | Description | -| ------ | ------ | ------ | -| `path` | `string` | path to the file. | -| `opts`? | `FilesystemRequestOpts` & `object` | connection options. | - -###### Returns - -`Promise`\<`Uint8Array`\> - -file content as `Uint8Array` - -###### read(path, opts) - -```ts -read(path: string, opts?: FilesystemRequestOpts & object): Promise -``` - -Read file content as a `Blob`. - -You can pass `text`, `bytes`, `blob`, or `stream` to `opts.format` to change the return type. - -###### Parameters - -| Parameter | Type | Description | -| ------ | ------ | ------ | -| `path` | `string` | path to the file. | -| `opts`? | `FilesystemRequestOpts` & `object` | connection options. | - -###### Returns - -`Promise`\<`Blob`\> - -file content as `Blob` - -###### read(path, opts) - -```ts -read(path: string, opts?: FilesystemRequestOpts & object): Promise> -``` - -Read file content as a `ReadableStream`. - -You can pass `text`, `bytes`, `blob`, or `stream` to `opts.format` to change the return type. - -###### Parameters - -| Parameter | Type | Description | -| ------ | ------ | ------ | -| `path` | `string` | path to the file. | -| `opts`? | `FilesystemRequestOpts` & `object` | connection options. | - -###### Returns - -`Promise`\<`ReadableStream`\<`Uint8Array`\>\> - -file content as `ReadableStream` - -### remove() - -```ts -remove(path: string, opts?: FilesystemRequestOpts): Promise -``` - -Remove a file or directory. - -###### Parameters - -| Parameter | Type | Description | -| ------ | ------ | ------ | -| `path` | `string` | path to a file or directory. | -| `opts`? | `FilesystemRequestOpts` | connection options. | - -###### Returns - -`Promise`\<`void`\> - -### rename() - -```ts -rename( - oldPath: string, - newPath: string, -opts?: FilesystemRequestOpts): Promise -``` - -Rename a file or directory. - -###### Parameters - -| Parameter | Type | Description | -| ------ | ------ | ------ | -| `oldPath` | `string` | path to the file or directory to rename. | -| `newPath` | `string` | new path for the file or directory. | -| `opts`? | `FilesystemRequestOpts` | connection options. | - -###### Returns - -`Promise`\<`EntryInfo`\> - -information about renamed file or directory. - -### watchDir() - -```ts -watchDir( - path: string, - onEvent: (event: FilesystemEvent) => void | Promise, -opts?: WatchOpts & object): Promise -``` - -Start watching a directory for filesystem events. - -###### Parameters - -| Parameter | Type | Description | -| ------ | ------ | ------ | -| `path` | `string` | path to directory to watch. | -| `onEvent` | (`event`: `FilesystemEvent`) => `void` \| `Promise`\<`void`\> | callback to call when an event in the directory occurs. | -| `opts`? | `WatchOpts` & `object` | connection options. | - -###### Returns - -`Promise`\<`WatchHandle`\> - -`WatchHandle` object for stopping watching directory. - -### write() - -###### write(path, data, opts) - -```ts -write( - path: string, - data: string | ArrayBuffer | Blob | ReadableStream, -opts?: FilesystemRequestOpts): Promise -``` - -Write content to a file. - -Writing to a file that doesn't exist creates the file. - -Writing to a file that already exists overwrites the file. - -Writing to a file at path that doesn't exist creates the necessary directories. - -###### Parameters - -| Parameter | Type | Description | -| ------ | ------ | ------ | -| `path` | `string` | path to file. | -| `data` | `string` \| `ArrayBuffer` \| `Blob` \| `ReadableStream`\<`any`\> | data to write to the file. Data can be a string, `ArrayBuffer`, `Blob`, or `ReadableStream`. | -| `opts`? | `FilesystemRequestOpts` | connection options. | - -###### Returns - -`Promise`\<`WriteInfo`\> - -information about the written file - -###### write(files, opts) - -```ts -write(files: WriteEntry[], opts?: FilesystemRequestOpts): Promise -``` - -###### Parameters - -| Parameter | Type | -| ------ | ------ | -| `files` | `WriteEntry`[] | -| `opts`? | `FilesystemRequestOpts` | - -###### Returns - -`Promise`\<`WriteInfo`[]\> - -## Interfaces - -### EntryInfo - -Sandbox filesystem object information. - -#### Properties - -### group - -```ts -group: string; -``` - -Group owner of the filesystem object. - -### mode - -```ts -mode: number; -``` - -File mode and permission bits. - -### modifiedTime? - -```ts -optional modifiedTime: Date; -``` - -Last modification time of the filesystem object. - -### name - -```ts -name: string; -``` - -Name of the filesystem object. - -### owner - -```ts -owner: string; -``` - -Owner of the filesystem object. - -### path - -```ts -path: string; -``` - -Path to the filesystem object. - -### permissions - -```ts -permissions: string; -``` - -String representation of file permissions (e.g. 'rwxr-xr-x'). - -### size - -```ts -size: number; -``` - -Size of the filesystem object in bytes. - -### symlinkTarget? - -```ts -optional symlinkTarget: string; -``` - -If the filesystem object is a symlink, this is the target of the symlink. - -### type? - -```ts -optional type: FileType; -``` - -Type of the filesystem object. - -*** - -### FilesystemListOpts - -Options for the sandbox filesystem operations. - -#### Properties - -### depth? - -```ts -optional depth: number; -``` - -Depth of the directory to list. - -### requestTimeoutMs? - -```ts -optional requestTimeoutMs: number; -``` - -Timeout for requests to the API in **milliseconds**. - -###### Default - -```ts -60_000 // 60 seconds -``` - -### user? - -```ts -optional user: string; -``` - -User to use for the operation in the sandbox. -This affects the resolution of relative paths and ownership of the created filesystem objects. - -*** - -### FilesystemRequestOpts - -Options for the sandbox filesystem operations. - -#### Extended by - -- `FilesystemListOpts` -- `WatchOpts` - -#### Properties - -### requestTimeoutMs? - -```ts -optional requestTimeoutMs: number; -``` - -Timeout for requests to the API in **milliseconds**. - -###### Default - -```ts -60_000 // 60 seconds -``` - -### user? - -```ts -optional user: string; -``` - -User to use for the operation in the sandbox. -This affects the resolution of relative paths and ownership of the created filesystem objects. - -*** - -### WatchOpts - -Options for watching a directory. - -#### Properties - -### onExit()? - -```ts -optional onExit: (err?: Error) => void | Promise; -``` - -Callback to call when the watch operation stops. - -###### Parameters - -| Parameter | Type | -| ------ | ------ | -| `err`? | `Error` | - -###### Returns - -`void` \| `Promise`\<`void`\> - -### recursive? - -```ts -optional recursive: boolean; -``` - -Watch the directory recursively - -### requestTimeoutMs? - -```ts -optional requestTimeoutMs: number; -``` - -Timeout for requests to the API in **milliseconds**. - -###### Default - -```ts -60_000 // 60 seconds -``` - -### timeoutMs? - -```ts -optional timeoutMs: number; -``` - -Timeout for the watch operation in **milliseconds**. -You can pass `0` to disable the timeout. - -###### Default - -```ts -60_000 // 60 seconds -``` - -### user? - -```ts -optional user: string; -``` - -User to use for the operation in the sandbox. -This affects the resolution of relative paths and ownership of the created filesystem objects. - -*** - -### WriteInfo - -Sandbox filesystem object information. - -#### Extended by - -- `EntryInfo` - -#### Properties - -### name - -```ts -name: string; -``` - -Name of the filesystem object. - -### path - -```ts -path: string; -``` - -Path to the filesystem object. - -### type? - -```ts -optional type: FileType; -``` - -Type of the filesystem object. - -## Type Aliases - -### WriteEntry - -```ts -type WriteEntry: object; -``` - -#### Type declaration - -| Name | Type | -| ------ | ------ | -| `data` | `string` \| `ArrayBuffer` \| `Blob` \| `ReadableStream` | -| `path` | `string` | diff --git a/docs/sdk-reference/js-sdk/v2.9.0/sandbox.mdx b/docs/sdk-reference/js-sdk/v2.9.0/sandbox.mdx deleted file mode 100644 index e430744..0000000 --- a/docs/sdk-reference/js-sdk/v2.9.0/sandbox.mdx +++ /dev/null @@ -1,712 +0,0 @@ ---- -sidebarTitle: "Sandbox" -mode: "center" ---- - -### Sandbox - -E2B cloud sandbox is a secure and isolated cloud environment. - -The sandbox allows you to: -- Access Linux OS -- Create, list, and delete files and directories -- Run commands -- Run isolated code -- Access the internet - -Check docs here. - -Use Sandbox.create to create a new sandbox. - -#### Example - -```ts -import { Sandbox } from 'e2b' - -const sandbox = await Sandbox.create() -``` - -#### Properties - -| Property | Modifier | Type | Description | -| ------ | ------ | ------ | ------ | -| `commands` | `readonly` | `Commands` | Module for running commands in the sandbox | -| `files` | `readonly` | `Filesystem` | Module for interacting with the sandbox filesystem | -| `pty` | `readonly` | `Pty` | Module for interacting with the sandbox pseudo-terminals | -| `sandboxDomain` | `readonly` | `string` | Domain where the sandbox is hosted. | -| `sandboxId` | `readonly` | `string` | Unique identifier of the sandbox. | -| `trafficAccessToken?` | `readonly` | `string` | Traffic access token for accessing sandbox services with restricted public traffic. | - -#### Methods - -### betaPause() - -```ts -betaPause(opts?: ConnectionOpts): Promise -``` - -**`Beta`** - -This feature is in beta and may change in the future. - -Pause a sandbox by its ID. - -###### Parameters - -| Parameter | Type | Description | -| ------ | ------ | ------ | -| `opts`? | `ConnectionOpts` | connection options. | - -###### Returns - -`Promise`\<`boolean`\> - -sandbox ID that can be used to resume the sandbox. - -### connect() - -```ts -connect(opts?: SandboxBetaCreateOpts): Promise -``` - -Connect to a sandbox. If the sandbox is paused, it will be automatically resumed. -Sandbox must be either running or be paused. - -With sandbox ID you can connect to the same sandbox from different places or environments (serverless functions, etc). - -###### Parameters - -| Parameter | Type | Description | -| ------ | ------ | ------ | -| `opts`? | `SandboxBetaCreateOpts` | connection options. | - -###### Returns - -`Promise`\<`Sandbox`\> - -A running sandbox instance - -###### Example - -```ts -const sandbox = await Sandbox.create() -await sandbox.betaPause() - -// Connect to the same sandbox. -const sameSandbox = await sandbox.connect() -``` - -### downloadUrl() - -```ts -downloadUrl(path: string, opts?: SandboxUrlOpts): Promise -``` - -Get the URL to download a file from the sandbox. - -###### Parameters - -| Parameter | Type | Description | -| ------ | ------ | ------ | -| `path` | `string` | path to the file in the sandbox. | -| `opts`? | `SandboxUrlOpts` | download url options. | - -###### Returns - -`Promise`\<`string`\> - -URL for downloading file. - -### getHost() - -```ts -getHost(port: number): string -``` - -Get the host address for the specified sandbox port. -You can then use this address to connect to the sandbox port from outside the sandbox via HTTP or WebSocket. - -###### Parameters - -| Parameter | Type | Description | -| ------ | ------ | ------ | -| `port` | `number` | number of the port in the sandbox. | - -###### Returns - -`string` - -host address of the sandbox port. - -###### Example - -```ts -const sandbox = await Sandbox.create() -// Start an HTTP server -await sandbox.commands.exec('python3 -m http.server 3000') -// Get the hostname of the HTTP server -const serverURL = sandbox.getHost(3000) -``` - -### getInfo() - -```ts -getInfo(opts?: Pick): Promise -``` - -Get sandbox information like sandbox ID, template, metadata, started at/end at date. - -###### Parameters - -| Parameter | Type | Description | -| ------ | ------ | ------ | -| `opts`? | `Pick`\<`SandboxOpts`, `"requestTimeoutMs"`\> | connection options. | - -###### Returns - -`Promise`\<`SandboxInfo`\> - -information about the sandbox - -### getMcpToken() - -```ts -getMcpToken(): Promise -``` - -Get the MCP token for the sandbox. - -###### Returns - -`Promise`\<`undefined` \| `string`\> - -MCP token for the sandbox, or undefined if MCP is not enabled. - -### getMcpUrl() - -```ts -getMcpUrl(): string -``` - -Get the MCP URL for the sandbox. - -###### Returns - -`string` - -MCP URL for the sandbox. - -### getMetrics() - -```ts -getMetrics(opts?: SandboxMetricsOpts): Promise -``` - -Get the metrics of the sandbox. - -###### Parameters - -| Parameter | Type | Description | -| ------ | ------ | ------ | -| `opts`? | `SandboxMetricsOpts` | connection options. | - -###### Returns - -`Promise`\<`SandboxMetrics`[]\> - -List of sandbox metrics containing CPU, memory and disk usage information. - -### isRunning() - -```ts -isRunning(opts?: Pick): Promise -``` - -Check if the sandbox is running. - -###### Parameters - -| Parameter | Type | -| ------ | ------ | -| `opts`? | `Pick`\<`ConnectionOpts`, `"requestTimeoutMs"`\> | - -###### Returns - -`Promise`\<`boolean`\> - -`true` if the sandbox is running, `false` otherwise. - -###### Example - -```ts -const sandbox = await Sandbox.create() -await sandbox.isRunning() // Returns true - -await sandbox.kill() -await sandbox.isRunning() // Returns false -``` - -### kill() - -```ts -kill(opts?: Pick): Promise -``` - -Kill the sandbox. - -###### Parameters - -| Parameter | Type | Description | -| ------ | ------ | ------ | -| `opts`? | `Pick`\<`SandboxOpts`, `"requestTimeoutMs"`\> | connection options. | - -###### Returns - -`Promise`\<`void`\> - -### setTimeout() - -```ts -setTimeout(timeoutMs: number, opts?: Pick): Promise -``` - -Set the timeout of the sandbox. -After the timeout expires the sandbox will be automatically killed. - -This method can extend or reduce the sandbox timeout set when creating the sandbox or from the last call to `.setTimeout`. -Maximum time a sandbox can be kept alive is 24 hours (86_400_000 milliseconds) for Pro users and 1 hour (3_600_000 milliseconds) for Hobby users. - -###### Parameters - -| Parameter | Type | Description | -| ------ | ------ | ------ | -| `timeoutMs` | `number` | timeout in **milliseconds**. | -| `opts`? | `Pick`\<`SandboxOpts`, `"requestTimeoutMs"`\> | connection options. | - -###### Returns - -`Promise`\<`void`\> - -### uploadUrl() - -```ts -uploadUrl(path?: string, opts?: SandboxUrlOpts): Promise -``` - -Get the URL to upload a file to the sandbox. - -You have to send a POST request to this URL with the file as multipart/form-data. - -###### Parameters - -| Parameter | Type | Description | -| ------ | ------ | ------ | -| `path`? | `string` | path to the file in the sandbox. | -| `opts`? | `SandboxUrlOpts` | download url options. | - -###### Returns - -`Promise`\<`string`\> - -URL for uploading file. - -### betaCreate() - -###### betaCreate(this, opts) - -```ts -static betaCreate(this: S, opts?: SandboxBetaCreateOpts): Promise> -``` - -**`Beta`** - -This feature is in beta and may change in the future. - -Create a new sandbox from the default `base` sandbox template. - -###### Type Parameters - -| Type Parameter | -| ------ | -| `S` *extends* *typeof* `Sandbox` | - -###### Parameters - -| Parameter | Type | Description | -| ------ | ------ | ------ | -| `this` | `S` | - | -| `opts`? | `SandboxBetaCreateOpts` | connection options. | - -###### Returns - -`Promise`\<`InstanceType`\<`S`\>\> - -sandbox instance for the new sandbox. - -###### Example - -```ts -const sandbox = await Sandbox.betaCreate() -``` - -###### Constructs - -Sandbox - -###### betaCreate(this, template, opts) - -```ts -static betaCreate( - this: S, - template: string, -opts?: SandboxBetaCreateOpts): Promise> -``` - -**`Beta`** - -This feature is in beta and may change in the future. - -Create a new sandbox from the specified sandbox template. - -###### Type Parameters - -| Type Parameter | -| ------ | -| `S` *extends* *typeof* `Sandbox` | - -###### Parameters - -| Parameter | Type | Description | -| ------ | ------ | ------ | -| `this` | `S` | - | -| `template` | `string` | sandbox template name or ID. | -| `opts`? | `SandboxBetaCreateOpts` | connection options. | - -###### Returns - -`Promise`\<`InstanceType`\<`S`\>\> - -sandbox instance for the new sandbox. - -###### Example - -```ts -const sandbox = await Sandbox.betaCreate('') -``` - -###### Constructs - -Sandbox - -### betaPause() - -```ts -static betaPause(sandboxId: string, opts?: SandboxApiOpts): Promise -``` - -Pause the sandbox specified by sandbox ID. - -###### Parameters - -| Parameter | Type | Description | -| ------ | ------ | ------ | -| `sandboxId` | `string` | sandbox ID. | -| `opts`? | `SandboxApiOpts` | connection options. | - -###### Returns - -`Promise`\<`boolean`\> - -`true` if the sandbox got paused, `false` if the sandbox was already paused. - -### connect() - -```ts -static connect( - this: S, - sandboxId: string, -opts?: SandboxConnectOpts): Promise> -``` - -Connect to a sandbox. If the sandbox is paused, it will be automatically resumed. -Sandbox must be either running or be paused. - -With sandbox ID you can connect to the same sandbox from different places or environments (serverless functions, etc). - -###### Type Parameters - -| Type Parameter | -| ------ | -| `S` *extends* *typeof* `Sandbox` | - -###### Parameters - -| Parameter | Type | Description | -| ------ | ------ | ------ | -| `this` | `S` | - | -| `sandboxId` | `string` | sandbox ID. | -| `opts`? | `SandboxConnectOpts` | connection options. | - -###### Returns - -`Promise`\<`InstanceType`\<`S`\>\> - -A running sandbox instance - -###### Example - -```ts -const sandbox = await Sandbox.create() -const sandboxId = sandbox.sandboxId - -// Connect to the same sandbox. -const sameSandbox = await Sandbox.connect(sandboxId) -``` - -### create() - -###### create(this, opts) - -```ts -static create(this: S, opts?: SandboxOpts): Promise> -``` - -Create a new sandbox from the default `base` sandbox template. - -###### Type Parameters - -| Type Parameter | -| ------ | -| `S` *extends* *typeof* `Sandbox` | - -###### Parameters - -| Parameter | Type | Description | -| ------ | ------ | ------ | -| `this` | `S` | - | -| `opts`? | `SandboxOpts` | connection options. | - -###### Returns - -`Promise`\<`InstanceType`\<`S`\>\> - -sandbox instance for the new sandbox. - -###### Example - -```ts -const sandbox = await Sandbox.create() -``` - -###### Constructs - -Sandbox - -###### create(this, template, opts) - -```ts -static create( - this: S, - template: string, -opts?: SandboxOpts): Promise> -``` - -Create a new sandbox from the specified sandbox template. - -###### Type Parameters - -| Type Parameter | -| ------ | -| `S` *extends* *typeof* `Sandbox` | - -###### Parameters - -| Parameter | Type | Description | -| ------ | ------ | ------ | -| `this` | `S` | - | -| `template` | `string` | sandbox template name or ID. | -| `opts`? | `SandboxOpts` | connection options. | - -###### Returns - -`Promise`\<`InstanceType`\<`S`\>\> - -sandbox instance for the new sandbox. - -###### Example - -```ts -const sandbox = await Sandbox.create('') -``` - -###### Constructs - -Sandbox - -### getFullInfo() - -```ts -static getFullInfo(sandboxId: string, opts?: SandboxApiOpts): Promise -``` - -###### Parameters - -| Parameter | Type | -| ------ | ------ | -| `sandboxId` | `string` | -| `opts`? | `SandboxApiOpts` | - -###### Returns - -`Promise`\<`object`\> - -| Name | Type | Default value | -| ------ | ------ | ------ | -| `cpuCount` | `number` | res.data.cpuCount | -| `endAt` | `Date` | - | -| `envdAccessToken` | `undefined` \| `string` | res.data.envdAccessToken | -| `envdVersion` | `string` | res.data.envdVersion | -| `memoryMB` | `number` | res.data.memoryMB | -| `metadata` | `object` | - | -| `name`? | `string` | res.data.alias | -| `sandboxDomain` | `undefined` \| `string` | - | -| `sandboxId` | `string` | res.data.sandboxID | -| `startedAt` | `Date` | - | -| `state` | `"running"` \| `"paused"` | res.data.state | -| `templateId` | `string` | res.data.templateID | - -### getInfo() - -```ts -static getInfo(sandboxId: string, opts?: SandboxApiOpts): Promise -``` - -Get sandbox information like sandbox ID, template, metadata, started at/end at date. - -###### Parameters - -| Parameter | Type | Description | -| ------ | ------ | ------ | -| `sandboxId` | `string` | sandbox ID. | -| `opts`? | `SandboxApiOpts` | connection options. | - -###### Returns - -`Promise`\<`SandboxInfo`\> - -sandbox information. - -### getMetrics() - -```ts -static getMetrics(sandboxId: string, opts?: SandboxMetricsOpts): Promise -``` - -Get the metrics of the sandbox. - -###### Parameters - -| Parameter | Type | Description | -| ------ | ------ | ------ | -| `sandboxId` | `string` | sandbox ID. | -| `opts`? | `SandboxMetricsOpts` | sandbox metrics options. | - -###### Returns - -`Promise`\<`SandboxMetrics`[]\> - -List of sandbox metrics containing CPU, memory and disk usage information. - -### kill() - -```ts -static kill(sandboxId: string, opts?: SandboxApiOpts): Promise -``` - -Kill the sandbox specified by sandbox ID. - -###### Parameters - -| Parameter | Type | Description | -| ------ | ------ | ------ | -| `sandboxId` | `string` | sandbox ID. | -| `opts`? | `SandboxApiOpts` | connection options. | - -###### Returns - -`Promise`\<`boolean`\> - -`true` if the sandbox was found and killed, `false` otherwise. - -### list() - -```ts -static list(opts?: SandboxListOpts): SandboxPaginator -``` - -List all sandboxes. - -###### Parameters - -| Parameter | Type | Description | -| ------ | ------ | ------ | -| `opts`? | `SandboxListOpts` | connection options. | - -###### Returns - -`SandboxPaginator` - -paginator for listing sandboxes. - -### setTimeout() - -```ts -static setTimeout( - sandboxId: string, - timeoutMs: number, -opts?: SandboxApiOpts): Promise -``` - -Set the timeout of the specified sandbox. -After the timeout expires the sandbox will be automatically killed. - -This method can extend or reduce the sandbox timeout set when creating the sandbox or from the last call to Sandbox.setTimeout. - -Maximum time a sandbox can be kept alive is 24 hours (86_400_000 milliseconds) for Pro users and 1 hour (3_600_000 milliseconds) for Hobby users. - -###### Parameters - -| Parameter | Type | Description | -| ------ | ------ | ------ | -| `sandboxId` | `string` | sandbox ID. | -| `timeoutMs` | `number` | timeout in **milliseconds**. | -| `opts`? | `SandboxApiOpts` | connection options. | - -###### Returns - -`Promise`\<`void`\> - -## Interfaces - -### SandboxUrlOpts - -Options for sandbox upload/download URL generation. - -#### Properties - -### user? - -```ts -optional user: string; -``` - -User that will be used to access the file. - -### useSignatureExpiration? - -```ts -optional useSignatureExpiration: number; -``` - -Use signature expiration for the URL. -Optional parameter to set the expiration time for the signature in seconds. diff --git a/docs/sdk-reference/js-sdk/v2.9.0/template-logger.mdx b/docs/sdk-reference/js-sdk/v2.9.0/template-logger.mdx deleted file mode 100644 index fdebde3..0000000 --- a/docs/sdk-reference/js-sdk/v2.9.0/template-logger.mdx +++ /dev/null @@ -1,196 +0,0 @@ ---- -sidebarTitle: "Logger" -mode: "center" ---- - -### LogEntry - -Represents a single log entry from the template build process. - -#### Extended by - -- `LogEntryStart` -- `LogEntryEnd` - -#### Constructors - -```ts -new LogEntry( - timestamp: Date, - level: LogEntryLevel, - message: string): LogEntry -``` - -###### Parameters - -| Parameter | Type | -| ------ | ------ | -| `timestamp` | `Date` | -| `level` | `LogEntryLevel` | -| `message` | `string` | - -###### Returns - -`LogEntry` - -#### Properties - -| Property | Modifier | Type | -| ------ | ------ | ------ | -| `level` | `readonly` | `LogEntryLevel` | -| `message` | `readonly` | `string` | -| `timestamp` | `readonly` | `Date` | - -#### Methods - -### toString() - -```ts -toString(): string -``` - -###### Returns - -`string` - -*** - -### LogEntryEnd - -Special log entry indicating the end of a build process. - -#### Constructors - -```ts -new LogEntryEnd(timestamp: Date, message: string): LogEntryEnd -``` - -###### Parameters - -| Parameter | Type | -| ------ | ------ | -| `timestamp` | `Date` | -| `message` | `string` | - -###### Returns - -`LogEntryEnd` - -#### Properties - -| Property | Modifier | Type | Inherited from | -| ------ | ------ | ------ | ------ | -| `level` | `readonly` | `LogEntryLevel` | `LogEntry`.`level` | -| `message` | `readonly` | `string` | `LogEntry`.`message` | -| `timestamp` | `readonly` | `Date` | `LogEntry`.`timestamp` | - -#### Methods - -### toString() - -```ts -toString(): string -``` - -###### Returns - -`string` - -*** - -### LogEntryStart - -Special log entry indicating the start of a build process. - -#### Constructors - -```ts -new LogEntryStart(timestamp: Date, message: string): LogEntryStart -``` - -###### Parameters - -| Parameter | Type | -| ------ | ------ | -| `timestamp` | `Date` | -| `message` | `string` | - -###### Returns - -`LogEntryStart` - -#### Properties - -| Property | Modifier | Type | Inherited from | -| ------ | ------ | ------ | ------ | -| `level` | `readonly` | `LogEntryLevel` | `LogEntry`.`level` | -| `message` | `readonly` | `string` | `LogEntry`.`message` | -| `timestamp` | `readonly` | `Date` | `LogEntry`.`timestamp` | - -#### Methods - -### toString() - -```ts -toString(): string -``` - -###### Returns - -`string` - -## Type Aliases - -### LogEntryLevel - -```ts -type LogEntryLevel: "debug" | "info" | "warn" | "error"; -``` - -Log entry severity levels. - -## Functions - -### defaultBuildLogger() - -```ts -function defaultBuildLogger(options?: object): (logEntry: LogEntry) => void -``` - -Create a default build logger with animated timer display. - -#### Parameters - -| Parameter | Type | Description | -| ------ | ------ | ------ | -| `options`? | `object` | Logger configuration options | -| `options.minLevel`? | `LogEntryLevel` | Minimum log level to display (default: 'info') | - -#### Returns - -`Function` - -Logger function that accepts LogEntry instances - -### Parameters - -| Parameter | Type | -| ------ | ------ | -| `logEntry` | `LogEntry` | - -### Returns - -`void` - -#### Example - -```ts -import { Template, defaultBuildLogger } from 'e2b' - -const template = Template().fromPythonImage() - -await Template.build(template, { - alias: 'my-template', - onBuildLogs: defaultBuildLogger({ minLevel: 'debug' }) -}) -``` diff --git a/docs/sdk-reference/js-sdk/v2.9.0/template-readycmd.mdx b/docs/sdk-reference/js-sdk/v2.9.0/template-readycmd.mdx deleted file mode 100644 index 56fb0b7..0000000 --- a/docs/sdk-reference/js-sdk/v2.9.0/template-readycmd.mdx +++ /dev/null @@ -1,202 +0,0 @@ ---- -sidebarTitle: "Readycmd" -mode: "center" ---- - -### ReadyCmd - -Class for ready check commands. - -#### Constructors - -```ts -new ReadyCmd(cmd: string): ReadyCmd -``` - -###### Parameters - -| Parameter | Type | -| ------ | ------ | -| `cmd` | `string` | - -###### Returns - -`ReadyCmd` - -#### Methods - -### getCmd() - -```ts -getCmd(): string -``` - -###### Returns - -`string` - -## Functions - -### waitForFile() - -```ts -function waitForFile(filename: string): ReadyCmd -``` - -Wait for a file to exist. -Uses shell test command to check file existence. - -#### Parameters - -| Parameter | Type | Description | -| ------ | ------ | ------ | -| `filename` | `string` | Path to the file to wait for | - -#### Returns - -`ReadyCmd` - -ReadyCmd that checks for the file - -#### Example - -```ts -import { Template, waitForFile } from 'e2b' - -const template = Template() - .fromBaseImage() - .setStartCmd('./init.sh', waitForFile('/tmp/ready')) -``` - -*** - -### waitForPort() - -```ts -function waitForPort(port: number): ReadyCmd -``` - -Wait for a port to be listening. -Uses `ss` command to check if a port is open and listening. - -#### Parameters - -| Parameter | Type | Description | -| ------ | ------ | ------ | -| `port` | `number` | Port number to wait for | - -#### Returns - -`ReadyCmd` - -ReadyCmd that checks for the port - -#### Example - -```ts -import { Template, waitForPort } from 'e2b' - -const template = Template() - .fromPythonImage() - .setStartCmd('python -m http.server 8000', waitForPort(8000)) -``` - -*** - -### waitForProcess() - -```ts -function waitForProcess(processName: string): ReadyCmd -``` - -Wait for a process with a specific name to be running. -Uses `pgrep` to check if a process exists. - -#### Parameters - -| Parameter | Type | Description | -| ------ | ------ | ------ | -| `processName` | `string` | Name of the process to wait for | - -#### Returns - -`ReadyCmd` - -ReadyCmd that checks for the process - -#### Example - -```ts -import { Template, waitForProcess } from 'e2b' - -const template = Template() - .fromBaseImage() - .setStartCmd('./my-daemon', waitForProcess('my-daemon')) -``` - -*** - -### waitForTimeout() - -```ts -function waitForTimeout(timeout: number): ReadyCmd -``` - -Wait for a specified timeout before considering the sandbox ready. -Uses `sleep` command to wait for a fixed duration. - -#### Parameters - -| Parameter | Type | Description | -| ------ | ------ | ------ | -| `timeout` | `number` | Time to wait in milliseconds (minimum: 1000ms / 1 second) | - -#### Returns - -`ReadyCmd` - -ReadyCmd that waits for the specified duration - -#### Example - -```ts -import { Template, waitForTimeout } from 'e2b' - -const template = Template() - .fromNodeImage() - .setStartCmd('npm start', waitForTimeout(5000)) // Wait 5 seconds -``` - -*** - -### waitForURL() - -```ts -function waitForURL(url: string, statusCode: number): ReadyCmd -``` - -Wait for a URL to return a specific HTTP status code. -Uses `curl` to make HTTP requests and check the response status. - -#### Parameters - -| Parameter | Type | Default value | Description | -| ------ | ------ | ------ | ------ | -| `url` | `string` | `undefined` | URL to check (e.g., 'http://localhost:3000/health') | -| `statusCode` | `number` | `200` | Expected HTTP status code (default: 200) | - -#### Returns - -`ReadyCmd` - -ReadyCmd that checks the URL - -#### Example - -```ts -import { Template, waitForURL } from 'e2b' - -const template = Template() - .fromNodeImage() - .setStartCmd('npm start', waitForURL('http://localhost:3000/health')) -``` diff --git a/docs/sdk-reference/js-sdk/v2.9.0/template.mdx b/docs/sdk-reference/js-sdk/v2.9.0/template.mdx deleted file mode 100644 index 5f1eccd..0000000 --- a/docs/sdk-reference/js-sdk/v2.9.0/template.mdx +++ /dev/null @@ -1,2044 +0,0 @@ ---- -sidebarTitle: "Template" -mode: "center" ---- - -### TemplateBase - -Base class for building E2B sandbox templates. - -#### Implements - -- `TemplateFromImage` -- `TemplateBuilder` -- `TemplateFinal` - -#### Constructors - -```ts -new TemplateBase(options?: TemplateOptions): TemplateBase -``` - -###### Parameters - -| Parameter | Type | -| ------ | ------ | -| `options`? | `TemplateOptions` | - -###### Returns - -`TemplateBase` - -#### Methods - -### addMcpServer() - -```ts -addMcpServer(servers: keyof McpServer | keyof McpServer[]): TemplateBuilder -``` - -Install MCP servers using mcp-gateway. -Note: Requires a base image with mcp-gateway pre-installed (e.g., mcp-gateway). - -###### Parameters - -| Parameter | Type | Description | -| ------ | ------ | ------ | -| `servers` | keyof McpServer \| keyof McpServer[] | MCP server name(s) | - -###### Returns - -`TemplateBuilder` - -###### Throws - -If the base template is not mcp-gateway - -###### Example - -```ts -template.addMcpServer('exa') -template.addMcpServer(['brave', 'firecrawl', 'duckduckgo']) -``` - -###### Implementation of - -`TemplateBuilder`.`addMcpServer` - -### aptInstall() - -```ts -aptInstall(packages: string | string[], options?: object): TemplateBuilder -``` - -Install Debian/Ubuntu packages using apt-get. - -###### Parameters - -| Parameter | Type | Description | -| ------ | ------ | ------ | -| `packages` | `string` \| `string`[] | Package name(s) | -| `options`? | `object` | - | -| `options.noInstallRecommends`? | `boolean` | - | - -###### Returns - -`TemplateBuilder` - -###### Example - -```ts -template.aptInstall('vim') -template.aptInstall(['git', 'curl', 'wget']) -template.aptInstall(['vim'], { noInstallRecommends: true }) -``` - -###### Implementation of - -`TemplateBuilder`.`aptInstall` - -### betaDevContainerPrebuild() - -```ts -betaDevContainerPrebuild(devcontainerDirectory: string): TemplateBuilder -``` - -Prebuild a devcontainer from the specified directory. - -###### Parameters - -| Parameter | Type | Description | -| ------ | ------ | ------ | -| `devcontainerDirectory` | `string` | Path to the devcontainer directory | - -###### Returns - -`TemplateBuilder` - -###### Example - -```ts -template - .gitClone('https://myrepo.com/project.git', '/my-devcontainer') - .betaDevContainerPrebuild('/my-devcontainer') -``` - -###### Implementation of - -`TemplateBuilder`.`betaDevContainerPrebuild` - -### betaSetDevContainerStart() - -```ts -betaSetDevContainerStart(devcontainerDirectory: string): TemplateFinal -``` - -Start a devcontainer from the specified directory. - -###### Parameters - -| Parameter | Type | Description | -| ------ | ------ | ------ | -| `devcontainerDirectory` | `string` | Path to the devcontainer directory | - -###### Returns - -`TemplateFinal` - -###### Example - -```ts -template - .gitClone('https://myrepo.com/project.git', '/my-devcontainer') - .startDevcontainer('/my-devcontainer') - -// Prebuild and start -template - .gitClone('https://myrepo.com/project.git', '/my-devcontainer') - .betaDevContainerPrebuild('/my-devcontainer') - // Other instructions... - .betaSetDevContainerStart('/my-devcontainer') -``` - -###### Implementation of - -`TemplateBuilder`.`betaSetDevContainerStart` - -### bunInstall() - -```ts -bunInstall(packages?: string | string[], options?: object): TemplateBuilder -``` - -Install Bun packages using bun. - -###### Parameters - -| Parameter | Type | Description | -| ------ | ------ | ------ | -| `packages`? | `string` \| `string`[] | Package name(s) or undefined for package.json | -| `options`? | `object` | Install options | -| `options.dev`? | `boolean` | - | -| `options.g`? | `boolean` | - | - -###### Returns - -`TemplateBuilder` - -###### Example - -```ts -template.bunInstall('express') -template.bunInstall(['lodash', 'axios']) -template.bunInstall('tsx', { g: true }) -template.bunInstall('typescript', { dev: true }) -template.bunInstall() // Installs from package.json -``` - -###### Implementation of - -`TemplateBuilder`.`bunInstall` - -### copy() - -```ts -copy( - src: PathLike | PathLike[], - dest: PathLike, - options?: object): TemplateBuilder -``` - -Copy files or directories into the template. - -###### Parameters - -| Parameter | Type | Description | -| ------ | ------ | ------ | -| `src` | `PathLike` \| `PathLike`[] | Source path(s) | -| `dest` | `PathLike` | Destination path | -| `options`? | `object` | Copy options | -| `options.forceUpload`? | `true` | - | -| `options.mode`? | `number` | - | -| `options.resolveSymlinks`? | `boolean` | - | -| `options.user`? | `string` | - | - -###### Returns - -`TemplateBuilder` - -###### Example - -```ts -template.copy('requirements.txt', '/home/user/') -template.copy(['app.ts', 'config.ts'], '/app/', { mode: 0o755 }) -``` - -###### Implementation of - -`TemplateBuilder`.`copy` - -### copyItems() - -```ts -copyItems(items: CopyItem[]): TemplateBuilder -``` - -Copy multiple items with individual options. - -###### Parameters - -| Parameter | Type | Description | -| ------ | ------ | ------ | -| `items` | `CopyItem`[] | Array of copy items | - -###### Returns - -`TemplateBuilder` - -###### Example - -```ts -template.copyItems([ - { src: 'app.ts', dest: '/app/' }, - { src: 'config.ts', dest: '/app/', mode: 0o644 } -]) -``` - -###### Implementation of - -`TemplateBuilder`.`copyItems` - -### fromAWSRegistry() - -```ts -fromAWSRegistry(image: string, credentials: object): TemplateBuilder -``` - -Start from a Docker image in AWS ECR. - -###### Parameters - -| Parameter | Type | Description | -| ------ | ------ | ------ | -| `image` | `string` | Full ECR image path | -| `credentials` | `object` | AWS credentials | -| `credentials.accessKeyId` | `string` | - | -| `credentials.region` | `string` | - | -| `credentials.secretAccessKey` | `string` | - | - -###### Returns - -`TemplateBuilder` - -###### Example - -```ts -Template().fromAWSRegistry( - '123456789.dkr.ecr.us-west-2.amazonaws.com/myimage:latest', - { - accessKeyId: 'AKIA...', - secretAccessKey: '...', - region: 'us-west-2' - } -) -``` - -###### Implementation of - -`TemplateFromImage.fromAWSRegistry` - -### fromBaseImage() - -```ts -fromBaseImage(): TemplateBuilder -``` - -Start from E2B's default base image (e2bdev/base:latest). - -###### Returns - -`TemplateBuilder` - -###### Example - -```ts -Template().fromBaseImage() -``` - -###### Implementation of - -`TemplateFromImage.fromBaseImage` - -### fromBunImage() - -```ts -fromBunImage(variant: string): TemplateBuilder -``` - -Start from a Bun-based Docker image. - -###### Parameters - -| Parameter | Type | Default value | Description | -| ------ | ------ | ------ | ------ | -| `variant` | `string` | `'latest'` | Bun variant (default: 'latest') | - -###### Returns - -`TemplateBuilder` - -###### Example - -```ts -Template().fromBunImage('1.3') -``` - -###### Implementation of - -`TemplateFromImage.fromBunImage` - -### fromDebianImage() - -```ts -fromDebianImage(variant: string): TemplateBuilder -``` - -Start from a Debian-based Docker image. - -###### Parameters - -| Parameter | Type | Default value | Description | -| ------ | ------ | ------ | ------ | -| `variant` | `string` | `'stable'` | Debian variant (default: 'stable') | - -###### Returns - -`TemplateBuilder` - -###### Example - -```ts -Template().fromDebianImage('bookworm') -``` - -###### Implementation of - -`TemplateFromImage.fromDebianImage` - -### fromDockerfile() - -```ts -fromDockerfile(dockerfileContentOrPath: string): TemplateBuilder -``` - -Parse a Dockerfile and convert it to Template SDK format. - -###### Parameters - -| Parameter | Type | Description | -| ------ | ------ | ------ | -| `dockerfileContentOrPath` | `string` | Dockerfile content or path | - -###### Returns - -`TemplateBuilder` - -###### Example - -```ts -Template().fromDockerfile('Dockerfile') -Template().fromDockerfile('FROM python:3\nRUN pip install numpy') -``` - -###### Implementation of - -`TemplateFromImage.fromDockerfile` - -### fromGCPRegistry() - -```ts -fromGCPRegistry(image: string, credentials: object): TemplateBuilder -``` - -Start from a Docker image in Google Container Registry. - -###### Parameters - -| Parameter | Type | Description | -| ------ | ------ | ------ | -| `image` | `string` | Full GCR/GAR image path | -| `credentials` | `object` | GCP service account credentials | -| `credentials.serviceAccountJSON` | `string` \| `object` | - | - -###### Returns - -`TemplateBuilder` - -###### Example - -```ts -Template().fromGCPRegistry( - 'gcr.io/myproject/myimage:latest', - { serviceAccountJSON: 'path/to/service-account.json' } -) -``` - -###### Implementation of - -`TemplateFromImage.fromGCPRegistry` - -### fromImage() - -```ts -fromImage(baseImage: string, credentials?: object): TemplateBuilder -``` - -Start from a custom Docker image. - -###### Parameters - -| Parameter | Type | Description | -| ------ | ------ | ------ | -| `baseImage` | `string` | Docker image name | -| `credentials`? | `object` | Optional credentials for private registries | -| `credentials.password`? | `string` | - | -| `credentials.username`? | `string` | - | - -###### Returns - -`TemplateBuilder` - -###### Example - -```ts -Template().fromImage('python:3') - -// With credentials (optional) -Template().fromImage('myregistry.com/myimage:latest', { - username: 'user', - password: 'pass' -}) -``` - -###### Implementation of - -`TemplateFromImage.fromImage` - -### fromNodeImage() - -```ts -fromNodeImage(variant: string): TemplateBuilder -``` - -Start from a Node.js-based Docker image. - -###### Parameters - -| Parameter | Type | Default value | Description | -| ------ | ------ | ------ | ------ | -| `variant` | `string` | `'lts'` | Node.js variant (default: 'lts') | - -###### Returns - -`TemplateBuilder` - -###### Example - -```ts -Template().fromNodeImage('24') -``` - -###### Implementation of - -`TemplateFromImage.fromNodeImage` - -### fromPythonImage() - -```ts -fromPythonImage(version: string): TemplateBuilder -``` - -Start from a Python-based Docker image. - -###### Parameters - -| Parameter | Type | Default value | Description | -| ------ | ------ | ------ | ------ | -| `version` | `string` | `'3'` | Python version (default: '3') | - -###### Returns - -`TemplateBuilder` - -###### Example - -```ts -Template().fromPythonImage('3') -``` - -###### Implementation of - -`TemplateFromImage.fromPythonImage` - -### fromTemplate() - -```ts -fromTemplate(template: string): TemplateBuilder -``` - -Start from an existing E2B template. - -###### Parameters - -| Parameter | Type | Description | -| ------ | ------ | ------ | -| `template` | `string` | E2B template ID or alias | - -###### Returns - -`TemplateBuilder` - -###### Example - -```ts -Template().fromTemplate('my-base-template') -``` - -###### Implementation of - -`TemplateFromImage.fromTemplate` - -### fromUbuntuImage() - -```ts -fromUbuntuImage(variant: string): TemplateBuilder -``` - -Start from an Ubuntu-based Docker image. - -###### Parameters - -| Parameter | Type | Default value | Description | -| ------ | ------ | ------ | ------ | -| `variant` | `string` | `'latest'` | Ubuntu variant (default: 'latest') | - -###### Returns - -`TemplateBuilder` - -###### Example - -```ts -Template().fromUbuntuImage('24.04') -``` - -###### Implementation of - -`TemplateFromImage.fromUbuntuImage` - -### gitClone() - -```ts -gitClone( - url: string, - path?: PathLike, - options?: object): TemplateBuilder -``` - -Clone a Git repository. - -###### Parameters - -| Parameter | Type | Description | -| ------ | ------ | ------ | -| `url` | `string` | Repository URL | -| `path`? | `PathLike` | Optional destination path | -| `options`? | `object` | Clone options | -| `options.branch`? | `string` | - | -| `options.depth`? | `number` | - | -| `options.user`? | `string` | - | - -###### Returns - -`TemplateBuilder` - -###### Example - -```ts -template.gitClone('https://github.com/user/repo.git', '/app/repo') -template.gitClone('https://github.com/user/repo.git', undefined, { - branch: 'main', - depth: 1 -}) -template.gitClone('https://github.com/user/repo.git', '/app/repo', { - user: 'root' -}) -``` - -###### Implementation of - -`TemplateBuilder`.`gitClone` - -### makeDir() - -```ts -makeDir(path: PathLike | PathLike[], options?: object): TemplateBuilder -``` - -Create directories. - -###### Parameters - -| Parameter | Type | Description | -| ------ | ------ | ------ | -| `path` | `PathLike` \| `PathLike`[] | Directory path(s) | -| `options`? | `object` | Directory options | -| `options.mode`? | `number` | - | -| `options.user`? | `string` | - | - -###### Returns - -`TemplateBuilder` - -###### Example - -```ts -template.makeDir('/app/data', { mode: 0o755 }) -template.makeDir(['/app/logs', '/app/cache']) -template.makeDir('/app/data', { mode: 0o755, user: 'root' }) -``` - -###### Implementation of - -`TemplateBuilder`.`makeDir` - -### makeSymlink() - -```ts -makeSymlink( - src: PathLike, - dest: PathLike, - options?: object): TemplateBuilder -``` - -Create a symbolic link. - -###### Parameters - -| Parameter | Type | Description | -| ------ | ------ | ------ | -| `src` | `PathLike` | Source path (target) | -| `dest` | `PathLike` | Destination path (symlink location) | -| `options`? | `object` | Symlink options | -| `options.force`? | `boolean` | - | -| `options.user`? | `string` | - | - -###### Returns - -`TemplateBuilder` - -###### Example - -```ts -template.makeSymlink('/usr/bin/python3', '/usr/bin/python') -template.makeSymlink('/usr/bin/python3', '/usr/bin/python', { user: 'root' }) -template.makeSymlink('/usr/bin/python3', '/usr/bin/python', { force: true }) -``` - -###### Implementation of - -`TemplateBuilder`.`makeSymlink` - -### npmInstall() - -```ts -npmInstall(packages?: string | string[], options?: object): TemplateBuilder -``` - -Install Node.js packages using npm. - -###### Parameters - -| Parameter | Type | Description | -| ------ | ------ | ------ | -| `packages`? | `string` \| `string`[] | Package name(s) or undefined for package.json | -| `options`? | `object` | Install options | -| `options.dev`? | `boolean` | - | -| `options.g`? | `boolean` | - | - -###### Returns - -`TemplateBuilder` - -###### Example - -```ts -template.npmInstall('express') -template.npmInstall(['lodash', 'axios']) -template.npmInstall('tsx', { g: true }) -template.npmInstall('typescript', { dev: true }) -template.npmInstall() // Installs from package.json -``` - -###### Implementation of - -`TemplateBuilder`.`npmInstall` - -### pipInstall() - -```ts -pipInstall(packages?: string | string[], options?: object): TemplateBuilder -``` - -Install Python packages using pip. - -###### Parameters - -| Parameter | Type | Description | -| ------ | ------ | ------ | -| `packages`? | `string` \| `string`[] | Package name(s) or undefined for current directory | -| `options`? | `object` | Install options | -| `options.g`? | `boolean` | Install globally as root (default: true). Set to false for user-only installation with --user flag | - -###### Returns - -`TemplateBuilder` - -###### Example - -```ts -template.pipInstall('numpy') // Installs globally (default) -template.pipInstall(['pandas', 'scikit-learn']) -template.pipInstall('numpy', { g: false }) // Install for user only -template.pipInstall() // Installs from current directory -``` - -###### Implementation of - -`TemplateBuilder`.`pipInstall` - -### remove() - -```ts -remove(path: PathLike | PathLike[], options?: object): TemplateBuilder -``` - -Remove files or directories. - -###### Parameters - -| Parameter | Type | Description | -| ------ | ------ | ------ | -| `path` | `PathLike` \| `PathLike`[] | Path(s) to remove | -| `options`? | `object` | Remove options | -| `options.force`? | `boolean` | - | -| `options.recursive`? | `boolean` | - | -| `options.user`? | `string` | - | - -###### Returns - -`TemplateBuilder` - -###### Example - -```ts -template.remove('/tmp/cache', { recursive: true, force: true }) -template.remove('/tmp/cache', { recursive: true, force: true, user: 'root' }) -``` - -###### Implementation of - -`TemplateBuilder`.`remove` - -### rename() - -```ts -rename( - src: PathLike, - dest: PathLike, - options?: object): TemplateBuilder -``` - -Rename or move a file or directory. - -###### Parameters - -| Parameter | Type | Description | -| ------ | ------ | ------ | -| `src` | `PathLike` | Source path | -| `dest` | `PathLike` | Destination path | -| `options`? | `object` | Rename options | -| `options.force`? | `boolean` | - | -| `options.user`? | `string` | - | - -###### Returns - -`TemplateBuilder` - -###### Example - -```ts -template.rename('/tmp/old.txt', '/tmp/new.txt') -template.rename('/tmp/old.txt', '/tmp/new.txt', { user: 'root' }) -``` - -###### Implementation of - -`TemplateBuilder`.`rename` - -### runCmd() - -###### runCmd(command, options) - -```ts -runCmd(command: string, options?: object): TemplateBuilder -``` - -Run a shell command. - -###### Parameters - -| Parameter | Type | Description | -| ------ | ------ | ------ | -| `command` | `string` | Command string | -| `options`? | `object` | Command options | -| `options.user`? | `string` | - | - -###### Returns - -`TemplateBuilder` - -###### Example - -```ts -template.runCmd('apt-get update') -template.runCmd(['pip install numpy', 'pip install pandas']) -template.runCmd('apt-get install vim', { user: 'root' }) -``` - -###### Implementation of - -`TemplateBuilder`.`runCmd` - -###### runCmd(commands, options) - -```ts -runCmd(commands: string[], options?: object): TemplateBuilder -``` - -Run a shell command. - -###### Parameters - -| Parameter | Type | Description | -| ------ | ------ | ------ | -| `commands` | `string`[] | - | -| `options`? | `object` | Command options | -| `options.user`? | `string` | - | - -###### Returns - -`TemplateBuilder` - -###### Example - -```ts -template.runCmd('apt-get update') -template.runCmd(['pip install numpy', 'pip install pandas']) -template.runCmd('apt-get install vim', { user: 'root' }) -``` - -###### Implementation of - -`TemplateBuilder`.`runCmd` - -### setEnvs() - -```ts -setEnvs(envs: Record): TemplateBuilder -``` - -Set environment variables. -Note: Environment variables defined here are available only during template build. - -###### Parameters - -| Parameter | Type | Description | -| ------ | ------ | ------ | -| `envs` | `Record`\<`string`, `string`\> | Environment variables | - -###### Returns - -`TemplateBuilder` - -###### Example - -```ts -template.setEnvs({ NODE_ENV: 'production', PORT: '8080' }) -``` - -###### Implementation of - -`TemplateBuilder`.`setEnvs` - -### setReadyCmd() - -```ts -setReadyCmd(readyCommand: string | ReadyCmd): TemplateFinal -``` - -Set or update the ready check command. - -###### Parameters - -| Parameter | Type | Description | -| ------ | ------ | ------ | -| `readyCommand` | `string` \| `ReadyCmd` | Command to check readiness | - -###### Returns - -`TemplateFinal` - -###### Example - -```ts -// Using a string command -template.setReadyCmd('curl http://localhost:8000/health') - -// Using ReadyCmd helpers -import { waitForPort, waitForFile, waitForProcess } from 'e2b' - -template.setReadyCmd(waitForPort(3000)) - -template.setReadyCmd(waitForFile('/tmp/ready')) - -template.setReadyCmd(waitForProcess('nginx')) -``` - -###### Implementation of - -`TemplateBuilder`.`setReadyCmd` - -### setStartCmd() - -```ts -setStartCmd(startCommand: string, readyCommand: string | ReadyCmd): TemplateFinal -``` - -Set the start command and ready check. - -###### Parameters - -| Parameter | Type | Description | -| ------ | ------ | ------ | -| `startCommand` | `string` | Command to run on startup | -| `readyCommand` | `string` \| `ReadyCmd` | Command to check readiness | - -###### Returns - -`TemplateFinal` - -###### Example - -```ts -// Using a string command -template.setStartCmd( - 'node app.js', - 'curl http://localhost:8000/health' -) - -// Using ReadyCmd helpers -import { waitForPort, waitForURL } from 'e2b' - -template.setStartCmd( - 'python -m http.server 8000', - waitForPort(8000) -) - -template.setStartCmd( - 'npm start', - waitForURL('http://localhost:3000/health', 200) -) -``` - -###### Implementation of - -`TemplateBuilder`.`setStartCmd` - -### setUser() - -```ts -setUser(user: string): TemplateBuilder -``` - -Set the user for subsequent commands. - -###### Parameters - -| Parameter | Type | Description | -| ------ | ------ | ------ | -| `user` | `string` | Username | - -###### Returns - -`TemplateBuilder` - -###### Example - -```ts -template.setUser('root') -``` - -###### Implementation of - -`TemplateBuilder`.`setUser` - -### setWorkdir() - -```ts -setWorkdir(workdir: PathLike): TemplateBuilder -``` - -Set the working directory. - -###### Parameters - -| Parameter | Type | Description | -| ------ | ------ | ------ | -| `workdir` | `PathLike` | Working directory path | - -###### Returns - -`TemplateBuilder` - -###### Example - -```ts -template.setWorkdir('/app') -``` - -###### Implementation of - -`TemplateBuilder`.`setWorkdir` - -### skipCache() - -```ts -skipCache(): this -``` - -Skip cache for all subsequent build instructions from this point. - -###### Returns - -`this` - -###### Example - -```ts -Template().skipCache().fromPythonImage('3') -``` - -###### Implementation of - -`TemplateBuilder`.`skipCache` - -### build() - -```ts -static build(template: TemplateClass, options: BuildOptions): Promise -``` - -Build and deploy a template to E2B infrastructure. - -###### Parameters - -| Parameter | Type | Description | -| ------ | ------ | ------ | -| `template` | `TemplateClass` | The template to build | -| `options` | `BuildOptions` | Build configuration options | - -###### Returns - -`Promise`\<`BuildInfo`\> - -###### Example - -```ts -const template = Template().fromPythonImage('3') -await Template.build(template, { - alias: 'my-python-env', - cpuCount: 2, - memoryMB: 1024 -}) -``` - -### buildInBackground() - -```ts -static buildInBackground(template: TemplateClass, options: BuildOptions): Promise -``` - -Build and deploy a template to E2B infrastructure. - -###### Parameters - -| Parameter | Type | Description | -| ------ | ------ | ------ | -| `template` | `TemplateClass` | The template to build | -| `options` | `BuildOptions` | Build configuration options | - -###### Returns - -`Promise`\<`BuildInfo`\> - -###### Example - -```ts -const template = Template().fromPythonImage('3') -const data = await Template.buildInBackground(template, { - alias: 'my-python-env', - cpuCount: 2, - memoryMB: 1024 -}) -``` - -### getBuildStatus() - -```ts -static getBuildStatus(data: Pick, options?: GetBuildStatusOptions): Promise -``` - -Get the status of a build. - -###### Parameters - -| Parameter | Type | Description | -| ------ | ------ | ------ | -| `data` | `Pick`\<`BuildInfo`, `"templateId"` \| `"buildId"`\> | Build identifiers | -| `options`? | `GetBuildStatusOptions` | Authentication options | - -###### Returns - -`Promise`\<`object`\> - -| Name | Type | Description | -| ------ | ------ | ------ | -| `buildID` | `string` | **Description** Identifier of the build | -| `logEntries` | `object`[] | **Description** Build logs structured **Default** `[]` | -| `logs` | `string`[] | **Description** Build logs **Default** `[]` | -| `reason`? | `object` | - | -| `reason.logEntries`? | `object`[] | **Description** Log entries related to the status reason **Default** `[]` | -| `reason.message` | `string` | **Description** Message with the status reason, currently reporting only for error status | -| `reason.step`? | `string` | **Description** Step that failed | -| `status` | `"error"` \| `"ready"` \| `"building"` \| `"waiting"` | - | -| `templateID` | `string` | **Description** Identifier of the template | - -###### Example - -```ts -const status = await Template.getBuildStatus(data, { logsOffset: 0 }) -``` - -### toDockerfile() - -```ts -static toDockerfile(template: TemplateClass): string -``` - -Convert a template to Dockerfile format. -Note: Templates based on other E2B templates cannot be converted to Dockerfile. - -###### Parameters - -| Parameter | Type | Description | -| ------ | ------ | ------ | -| `template` | `TemplateClass` | The template to convert | - -###### Returns - -`string` - -Dockerfile string representation - -###### Throws - -Error if the template is based on another E2B template - -### toJSON() - -```ts -static toJSON(template: TemplateClass, computeHashes: boolean): Promise -``` - -Convert a template to JSON representation. - -###### Parameters - -| Parameter | Type | Default value | Description | -| ------ | ------ | ------ | ------ | -| `template` | `TemplateClass` | `undefined` | The template to convert | -| `computeHashes` | `boolean` | `true` | Whether to compute file hashes for cache invalidation | - -###### Returns - -`Promise`\<`string`\> - -JSON string representation of the template - -## Interfaces - -### TemplateBuilder - -Main builder state for constructing templates. -Provides methods for customizing the template environment. - -#### Methods - -### addMcpServer() - -```ts -addMcpServer(servers: keyof McpServer | keyof McpServer[]): TemplateBuilder -``` - -Install MCP servers using mcp-gateway. -Note: Requires a base image with mcp-gateway pre-installed (e.g., mcp-gateway). - -###### Parameters - -| Parameter | Type | Description | -| ------ | ------ | ------ | -| `servers` | keyof McpServer \| keyof McpServer[] | MCP server name(s) | - -###### Returns - -`TemplateBuilder` - -###### Throws - -If the base template is not mcp-gateway - -###### Example - -```ts -template.addMcpServer('exa') -template.addMcpServer(['brave', 'firecrawl', 'duckduckgo']) -``` - -### aptInstall() - -```ts -aptInstall(packages: string | string[], options?: object): TemplateBuilder -``` - -Install Debian/Ubuntu packages using apt-get. - -###### Parameters - -| Parameter | Type | Description | -| ------ | ------ | ------ | -| `packages` | `string` \| `string`[] | Package name(s) | -| `options`? | `object` | - | -| `options.noInstallRecommends`? | `boolean` | - | - -###### Returns - -`TemplateBuilder` - -###### Example - -```ts -template.aptInstall('vim') -template.aptInstall(['git', 'curl', 'wget']) -template.aptInstall(['vim'], { noInstallRecommends: true }) -``` - -### betaDevContainerPrebuild() - -```ts -betaDevContainerPrebuild(devcontainerDirectory: string): TemplateBuilder -``` - -Prebuild a devcontainer from the specified directory. - -###### Parameters - -| Parameter | Type | Description | -| ------ | ------ | ------ | -| `devcontainerDirectory` | `string` | Path to the devcontainer directory | - -###### Returns - -`TemplateBuilder` - -###### Example - -```ts -template - .gitClone('https://myrepo.com/project.git', '/my-devcontainer') - .betaDevContainerPrebuild('/my-devcontainer') -``` - -### betaSetDevContainerStart() - -```ts -betaSetDevContainerStart(devcontainerDirectory: string): TemplateFinal -``` - -Start a devcontainer from the specified directory. - -###### Parameters - -| Parameter | Type | Description | -| ------ | ------ | ------ | -| `devcontainerDirectory` | `string` | Path to the devcontainer directory | - -###### Returns - -`TemplateFinal` - -###### Example - -```ts -template - .gitClone('https://myrepo.com/project.git', '/my-devcontainer') - .startDevcontainer('/my-devcontainer') - -// Prebuild and start -template - .gitClone('https://myrepo.com/project.git', '/my-devcontainer') - .betaDevContainerPrebuild('/my-devcontainer') - // Other instructions... - .betaSetDevContainerStart('/my-devcontainer') -``` - -### bunInstall() - -```ts -bunInstall(packages?: string | string[], options?: object): TemplateBuilder -``` - -Install Bun packages using bun. - -###### Parameters - -| Parameter | Type | Description | -| ------ | ------ | ------ | -| `packages`? | `string` \| `string`[] | Package name(s) or undefined for package.json | -| `options`? | `object` | Install options | -| `options.dev`? | `boolean` | - | -| `options.g`? | `boolean` | - | - -###### Returns - -`TemplateBuilder` - -###### Example - -```ts -template.bunInstall('express') -template.bunInstall(['lodash', 'axios']) -template.bunInstall('tsx', { g: true }) -template.bunInstall('typescript', { dev: true }) -template.bunInstall() // Installs from package.json -``` - -### copy() - -```ts -copy( - src: PathLike | PathLike[], - dest: PathLike, - options?: object): TemplateBuilder -``` - -Copy files or directories into the template. - -###### Parameters - -| Parameter | Type | Description | -| ------ | ------ | ------ | -| `src` | `PathLike` \| `PathLike`[] | Source path(s) | -| `dest` | `PathLike` | Destination path | -| `options`? | `object` | Copy options | -| `options.forceUpload`? | `true` | - | -| `options.mode`? | `number` | - | -| `options.resolveSymlinks`? | `boolean` | - | -| `options.user`? | `string` | - | - -###### Returns - -`TemplateBuilder` - -###### Example - -```ts -template.copy('requirements.txt', '/home/user/') -template.copy(['app.ts', 'config.ts'], '/app/', { mode: 0o755 }) -``` - -### copyItems() - -```ts -copyItems(items: CopyItem[]): TemplateBuilder -``` - -Copy multiple items with individual options. - -###### Parameters - -| Parameter | Type | Description | -| ------ | ------ | ------ | -| `items` | `CopyItem`[] | Array of copy items | - -###### Returns - -`TemplateBuilder` - -###### Example - -```ts -template.copyItems([ - { src: 'app.ts', dest: '/app/' }, - { src: 'config.ts', dest: '/app/', mode: 0o644 } -]) -``` - -### gitClone() - -```ts -gitClone( - url: string, - path?: PathLike, - options?: object): TemplateBuilder -``` - -Clone a Git repository. - -###### Parameters - -| Parameter | Type | Description | -| ------ | ------ | ------ | -| `url` | `string` | Repository URL | -| `path`? | `PathLike` | Optional destination path | -| `options`? | `object` | Clone options | -| `options.branch`? | `string` | - | -| `options.depth`? | `number` | - | -| `options.user`? | `string` | - | - -###### Returns - -`TemplateBuilder` - -###### Example - -```ts -template.gitClone('https://github.com/user/repo.git', '/app/repo') -template.gitClone('https://github.com/user/repo.git', undefined, { - branch: 'main', - depth: 1 -}) -template.gitClone('https://github.com/user/repo.git', '/app/repo', { - user: 'root' -}) -``` - -### makeDir() - -```ts -makeDir(path: PathLike | PathLike[], options?: object): TemplateBuilder -``` - -Create directories. - -###### Parameters - -| Parameter | Type | Description | -| ------ | ------ | ------ | -| `path` | `PathLike` \| `PathLike`[] | Directory path(s) | -| `options`? | `object` | Directory options | -| `options.mode`? | `number` | - | -| `options.user`? | `string` | - | - -###### Returns - -`TemplateBuilder` - -###### Example - -```ts -template.makeDir('/app/data', { mode: 0o755 }) -template.makeDir(['/app/logs', '/app/cache']) -template.makeDir('/app/data', { mode: 0o755, user: 'root' }) -``` - -### makeSymlink() - -```ts -makeSymlink( - src: PathLike, - dest: PathLike, - options?: object): TemplateBuilder -``` - -Create a symbolic link. - -###### Parameters - -| Parameter | Type | Description | -| ------ | ------ | ------ | -| `src` | `PathLike` | Source path (target) | -| `dest` | `PathLike` | Destination path (symlink location) | -| `options`? | `object` | Symlink options | -| `options.force`? | `boolean` | - | -| `options.user`? | `string` | - | - -###### Returns - -`TemplateBuilder` - -###### Example - -```ts -template.makeSymlink('/usr/bin/python3', '/usr/bin/python') -template.makeSymlink('/usr/bin/python3', '/usr/bin/python', { user: 'root' }) -template.makeSymlink('/usr/bin/python3', '/usr/bin/python', { force: true }) -``` - -### npmInstall() - -```ts -npmInstall(packages?: string | string[], options?: object): TemplateBuilder -``` - -Install Node.js packages using npm. - -###### Parameters - -| Parameter | Type | Description | -| ------ | ------ | ------ | -| `packages`? | `string` \| `string`[] | Package name(s) or undefined for package.json | -| `options`? | `object` | Install options | -| `options.dev`? | `boolean` | - | -| `options.g`? | `boolean` | - | - -###### Returns - -`TemplateBuilder` - -###### Example - -```ts -template.npmInstall('express') -template.npmInstall(['lodash', 'axios']) -template.npmInstall('tsx', { g: true }) -template.npmInstall('typescript', { dev: true }) -template.npmInstall() // Installs from package.json -``` - -### pipInstall() - -```ts -pipInstall(packages?: string | string[], options?: object): TemplateBuilder -``` - -Install Python packages using pip. - -###### Parameters - -| Parameter | Type | Description | -| ------ | ------ | ------ | -| `packages`? | `string` \| `string`[] | Package name(s) or undefined for current directory | -| `options`? | `object` | Install options | -| `options.g`? | `boolean` | Install globally as root (default: true). Set to false for user-only installation with --user flag | - -###### Returns - -`TemplateBuilder` - -###### Example - -```ts -template.pipInstall('numpy') // Installs globally (default) -template.pipInstall(['pandas', 'scikit-learn']) -template.pipInstall('numpy', { g: false }) // Install for user only -template.pipInstall() // Installs from current directory -``` - -### remove() - -```ts -remove(path: PathLike | PathLike[], options?: object): TemplateBuilder -``` - -Remove files or directories. - -###### Parameters - -| Parameter | Type | Description | -| ------ | ------ | ------ | -| `path` | `PathLike` \| `PathLike`[] | Path(s) to remove | -| `options`? | `object` | Remove options | -| `options.force`? | `boolean` | - | -| `options.recursive`? | `boolean` | - | -| `options.user`? | `string` | - | - -###### Returns - -`TemplateBuilder` - -###### Example - -```ts -template.remove('/tmp/cache', { recursive: true, force: true }) -template.remove('/tmp/cache', { recursive: true, force: true, user: 'root' }) -``` - -### rename() - -```ts -rename( - src: PathLike, - dest: PathLike, - options?: object): TemplateBuilder -``` - -Rename or move a file or directory. - -###### Parameters - -| Parameter | Type | Description | -| ------ | ------ | ------ | -| `src` | `PathLike` | Source path | -| `dest` | `PathLike` | Destination path | -| `options`? | `object` | Rename options | -| `options.force`? | `boolean` | - | -| `options.user`? | `string` | - | - -###### Returns - -`TemplateBuilder` - -###### Example - -```ts -template.rename('/tmp/old.txt', '/tmp/new.txt') -template.rename('/tmp/old.txt', '/tmp/new.txt', { user: 'root' }) -``` - -### runCmd() - -###### runCmd(command, options) - -```ts -runCmd(command: string, options?: object): TemplateBuilder -``` - -Run a shell command. - -###### Parameters - -| Parameter | Type | Description | -| ------ | ------ | ------ | -| `command` | `string` | Command string | -| `options`? | `object` | Command options | -| `options.user`? | `string` | - | - -###### Returns - -`TemplateBuilder` - -###### Example - -```ts -template.runCmd('apt-get update') -template.runCmd(['pip install numpy', 'pip install pandas']) -template.runCmd('apt-get install vim', { user: 'root' }) -``` - -###### runCmd(commands, options) - -```ts -runCmd(commands: string[], options?: object): TemplateBuilder -``` - -Run multiple shell commands. - -###### Parameters - -| Parameter | Type | Description | -| ------ | ------ | ------ | -| `commands` | `string`[] | Array of command strings | -| `options`? | `object` | Command options | -| `options.user`? | `string` | - | - -###### Returns - -`TemplateBuilder` - -###### runCmd(commandOrCommands, options) - -```ts -runCmd(commandOrCommands: string | string[], options?: object): TemplateBuilder -``` - -Run command(s). - -###### Parameters - -| Parameter | Type | Description | -| ------ | ------ | ------ | -| `commandOrCommands` | `string` \| `string`[] | Command or commands | -| `options`? | `object` | Command options | -| `options.user`? | `string` | - | - -###### Returns - -`TemplateBuilder` - -### setEnvs() - -```ts -setEnvs(envs: Record): TemplateBuilder -``` - -Set environment variables. -Note: Environment variables defined here are available only during template build. - -###### Parameters - -| Parameter | Type | Description | -| ------ | ------ | ------ | -| `envs` | `Record`\<`string`, `string`\> | Environment variables | - -###### Returns - -`TemplateBuilder` - -###### Example - -```ts -template.setEnvs({ NODE_ENV: 'production', PORT: '8080' }) -``` - -### setReadyCmd() - -```ts -setReadyCmd(readyCommand: string | ReadyCmd): TemplateFinal -``` - -Set or update the ready check command. - -###### Parameters - -| Parameter | Type | Description | -| ------ | ------ | ------ | -| `readyCommand` | `string` \| `ReadyCmd` | Command to check readiness | - -###### Returns - -`TemplateFinal` - -###### Example - -```ts -// Using a string command -template.setReadyCmd('curl http://localhost:8000/health') - -// Using ReadyCmd helpers -import { waitForPort, waitForFile, waitForProcess } from 'e2b' - -template.setReadyCmd(waitForPort(3000)) - -template.setReadyCmd(waitForFile('/tmp/ready')) - -template.setReadyCmd(waitForProcess('nginx')) -``` - -### setStartCmd() - -```ts -setStartCmd(startCommand: string, readyCommand: string | ReadyCmd): TemplateFinal -``` - -Set the start command and ready check. - -###### Parameters - -| Parameter | Type | Description | -| ------ | ------ | ------ | -| `startCommand` | `string` | Command to run on startup | -| `readyCommand` | `string` \| `ReadyCmd` | Command to check readiness | - -###### Returns - -`TemplateFinal` - -###### Example - -```ts -// Using a string command -template.setStartCmd( - 'node app.js', - 'curl http://localhost:8000/health' -) - -// Using ReadyCmd helpers -import { waitForPort, waitForURL } from 'e2b' - -template.setStartCmd( - 'python -m http.server 8000', - waitForPort(8000) -) - -template.setStartCmd( - 'npm start', - waitForURL('http://localhost:3000/health', 200) -) -``` - -### setUser() - -```ts -setUser(user: string): TemplateBuilder -``` - -Set the user for subsequent commands. - -###### Parameters - -| Parameter | Type | Description | -| ------ | ------ | ------ | -| `user` | `string` | Username | - -###### Returns - -`TemplateBuilder` - -###### Example - -```ts -template.setUser('root') -``` - -### setWorkdir() - -```ts -setWorkdir(workdir: PathLike): TemplateBuilder -``` - -Set the working directory. - -###### Parameters - -| Parameter | Type | Description | -| ------ | ------ | ------ | -| `workdir` | `PathLike` | Working directory path | - -###### Returns - -`TemplateBuilder` - -###### Example - -```ts -template.setWorkdir('/app') -``` - -### skipCache() - -```ts -skipCache(): this -``` - -Skip cache for all subsequent build instructions from this point. - -###### Returns - -`this` - -###### Example - -```ts -template.skipCache().runCmd('apt-get update') -``` - -## Type Aliases - -### BuildInfo - -```ts -type BuildInfo: object; -``` - -Information about a built template. - -#### Type declaration - -| Name | Type | -| ------ | ------ | -| `alias` | `string` | -| `buildId` | `string` | -| `templateId` | `string` | - -*** - -### BuildOptions - -```ts -type BuildOptions: AuthOptions & BasicBuildOptions; -``` - -Options for building a template with authentication. - -*** - -### CopyItem - -```ts -type CopyItem: object; -``` - -Configuration for a single file/directory copy operation. - -#### Type declaration - -| Name | Type | -| ------ | ------ | -| `dest` | `PathLike` | -| `forceUpload`? | `true` | -| `mode`? | `number` | -| `resolveSymlinks`? | `boolean` | -| `src` | `PathLike` \| `PathLike`[] | -| `user`? | `string` | - -*** - -### GetBuildStatusOptions - -```ts -type GetBuildStatusOptions: AuthOptions & object; -``` - -Response from getting build status. - -#### Type declaration - -| Name | Type | -| ------ | ------ | -| `logsOffset`? | `number` | - -*** - -### McpServerName - -```ts -type McpServerName: keyof McpServer; -``` - -MCP server names that can be installed. - -*** - -### TemplateClass - -```ts -type TemplateClass: TemplateBuilder | TemplateFinal; -``` - -Type representing a template in any state (builder or final). - -## Functions - -### Template() - -```ts -function Template(options?: TemplateOptions): TemplateFromImage -``` - -Create a new E2B template builder instance. - -#### Parameters - -| Parameter | Type | Description | -| ------ | ------ | ------ | -| `options`? | `TemplateOptions` | Optional configuration for the template builder | - -#### Returns - -`TemplateFromImage` - -A new template builder instance - -#### Example - -```ts -import { Template } from 'e2b' - -const template = Template() - .fromPythonImage('3') - .copy('requirements.txt', '/app/') - .pipInstall() - -await Template.build(template, { alias: 'my-python-app' }) -``` diff --git a/docs/sdk-reference/python-sdk/1.0.0/exceptions.mdx b/docs/sdk-reference/python-sdk/1.0.0/exceptions.mdx deleted file mode 100644 index fa9912e..0000000 --- a/docs/sdk-reference/python-sdk/1.0.0/exceptions.mdx +++ /dev/null @@ -1,87 +0,0 @@ ---- -sidebarTitle: "Exceptions" -mode: "center" ---- - - - - - - -## SandboxException - -```python -class SandboxException(Exception) -``` - -Base class for all sandbox errors. - -Raised when a general sandbox exception occurs. - - - -## TimeoutException - -```python -class TimeoutException(SandboxException) -``` - -Raised when a timeout occurs. - -The [unavailable] exception type is caused by sandbox timeout. - -The [canceled] exception type is caused by exceeding request timeout. - -The [deadline_exceeded] exception type is caused by exceeding the timeout for process, watch, etc. - -The [unknown] exception type is sometimes caused by the sandbox timeout when the request is not processed correctly. - - - -## InvalidArgumentException - -```python -class InvalidArgumentException(SandboxException) -``` - -Raised when an invalid argument is provided. - - - -## NotEnoughSpaceException - -```python -class NotEnoughSpaceException(SandboxException) -``` - -Raised when there is not enough disk space. - - - -## NotFoundException - -```python -class NotFoundException(SandboxException) -``` - -Raised when a resource is not found. - - - -## AuthenticationException - -```python -class AuthenticationException(SandboxException) -``` - -Raised when authentication fails. - - - -## TemplateException - -```python -class TemplateException(SandboxException) -``` - -Exception raised when the template uses old envd version. It isn't compatible with the new SDK. diff --git a/docs/sdk-reference/python-sdk/1.0.0/sandbox_async.mdx b/docs/sdk-reference/python-sdk/1.0.0/sandbox_async.mdx deleted file mode 100644 index b0bf4ab..0000000 --- a/docs/sdk-reference/python-sdk/1.0.0/sandbox_async.mdx +++ /dev/null @@ -1,985 +0,0 @@ ---- -sidebarTitle: "Sandbox Async" -mode: "center" ---- - - - - - - -## AsyncWatchHandle - -```python -class AsyncWatchHandle() -``` - -Handle for watching a directory in the sandbox filesystem. - -Use `.stop()` to stop watching the directory. - - - -### stop - -```python -async def stop() -``` - -Stop watching the directory. - - - - - - -## Filesystem - -```python -class Filesystem() -``` - -Module for interacting with the filesystem in the sandbox. - - - -### read - -```python -@overload -async def read(path: str, - format: Literal["text"] = "text", - user: Username = "user", - request_timeout: Optional[float] = None) -> str -``` - -Read file content as a `str`. - -**Arguments**: - -- `path`: Path to the file -- `user`: Run the operation as this user -- `format`: Format of the file content—`text` by default -- `request_timeout`: Timeout for the request in **seconds** - -**Returns**: - -File content as a `str` - - - -### read - -```python -@overload -async def read(path: str, - format: Literal["bytes"], - user: Username = "user", - request_timeout: Optional[float] = None) -> bytearray -``` - -Read file content as a `bytearray`. - -**Arguments**: - -- `path`: Path to the file -- `user`: Run the operation as this user -- `format`: Format of the file content—`bytes` -- `request_timeout`: Timeout for the request in **seconds** - -**Returns**: - -File content as a `bytearray` - - - -### read - -```python -@overload -async def read( - path: str, - format: Literal["stream"], - user: Username = "user", - request_timeout: Optional[float] = None) -> AsyncIterator[bytes] -``` - -Read file content as a `AsyncIterator[bytes]`. - -**Arguments**: - -- `path`: Path to the file -- `user`: Run the operation as this user -- `format`: Format of the file content—`stream` -- `request_timeout`: Timeout for the request in **seconds** - -**Returns**: - -File content as an `AsyncIterator[bytes]` - - - -### write - -```python -async def write(path: str, - data: Union[str, bytes, IO], - user: Username = "user", - request_timeout: Optional[float] = None) -> EntryInfo -``` - -Write content to a file on the path. - -Writing to a file that doesn't exist creates the file. - -Writing to a file that already exists overwrites the file. - -Writing to a file at path that doesn't exist creates the necessary directories. - -**Arguments**: - -- `path`: Path to the file -- `data`: Data to write to the file, can be a `str`, `bytes`, or `IO`. -- `user`: Run the operation as this user -- `request_timeout`: Timeout for the request in **seconds** - -**Returns**: - -Information about the written file - - - -### list - -```python -async def list(path: str, - user: Username = "user", - request_timeout: Optional[float] = None) -> List[EntryInfo] -``` - -List entries in a directory. - -**Arguments**: - -- `path`: Path to the directory -- `user`: Run the operation as this user -- `request_timeout`: Timeout for the request in **seconds** - -**Returns**: - -List of entries in the directory - - - -### exists - -```python -async def exists(path: str, - user: Username = "user", - request_timeout: Optional[float] = None) -> bool -``` - -Check if a file or a directory exists. - -**Arguments**: - -- `path`: Path to a file or a directory -- `user`: Run the operation as this user -- `request_timeout`: Timeout for the request in **seconds** - -**Returns**: - -`True` if the file or directory exists, `False` otherwise - - - -### remove - -```python -async def remove(path: str, - user: Username = "user", - request_timeout: Optional[float] = None) -> None -``` - -Remove a file or a directory. - -**Arguments**: - -- `path`: Path to a file or a directory -- `user`: Run the operation as this user -- `request_timeout`: Timeout for the request in **seconds** - - - -### rename - -```python -async def rename(old_path: str, - new_path: str, - user: Username = "user", - request_timeout: Optional[float] = None) -> EntryInfo -``` - -Rename a file or directory. - -**Arguments**: - -- `old_path`: Path to the file or directory to rename -- `new_path`: New path to the file or directory -- `user`: Run the operation as this user -- `request_timeout`: Timeout for the request in **seconds** - -**Returns**: - -Information about the renamed file or directory - - - -### make\_dir - -```python -async def make_dir(path: str, - user: Username = "user", - request_timeout: Optional[float] = None) -> bool -``` - -Create a new directory and all directories along the way if needed on the specified path. - -**Arguments**: - -- `path`: Path to a new directory. For example '/dirA/dirB' when creating 'dirB'. -- `user`: Run the operation as this user -- `request_timeout`: Timeout for the request in **seconds** - -**Returns**: - -`True` if the directory was created, `False` if the directory already exists - - - -### watch\_dir - -```python -async def watch_dir(path: str, - on_event: OutputHandler[FilesystemEvent], - on_exit: Optional[OutputHandler[Exception]] = None, - user: Username = "user", - request_timeout: Optional[float] = None, - timeout: Optional[float] = 60) -> AsyncWatchHandle -``` - -Watch directory for filesystem events. - -**Arguments**: - -- `path`: Path to a directory to watch -- `on_event`: Callback to call on each event in the directory -- `on_exit`: Callback to call when the watching ends -- `user`: Run the operation as this user -- `request_timeout`: Timeout for the request in **seconds** -- `timeout`: Timeout for the watch operation in **seconds**. Using `0` will not limit the watch time - -**Returns**: - -`AsyncWatchHandle` object for stopping watching directory - - - - - - - - - -## SandboxApi - -```python -class SandboxApi(SandboxApiBase) -``` - - - -### list - -```python -@classmethod -async def list(cls, - api_key: Optional[str] = None, - domain: Optional[str] = None, - debug: Optional[bool] = None, - request_timeout: Optional[float] = None) -> List[SandboxInfo] -``` - -List all running sandboxes. - -**Arguments**: - -- `api_key`: API key to use for authentication, defaults to `E2B_API_KEY` environment variable -- `request_timeout`: Timeout for the request in **seconds** - -**Returns**: - -List of running sandboxes - - - - - - -## Commands - -```python -class Commands() -``` - -Module for executing commands in the sandbox. - - - -### list - -```python -async def list(request_timeout: Optional[float] = None) -> List[ProcessInfo] -``` - -Lists all running commands and PTY sessions. - -**Arguments**: - -- `request_timeout`: Timeout for the request in **seconds** - -**Returns**: - -List of running commands and PTY sessions - - - -### kill - -```python -async def kill(pid: int, request_timeout: Optional[float] = None) -> bool -``` - -Kill a running command specified by its process ID. - -It uses `SIGKILL` signal to kill the command. - -**Arguments**: - -- `pid`: Process ID of the command. You can get the list of processes using `sandbox.commands.list()` -- `request_timeout`: Timeout for the request in **seconds** - -**Returns**: - -`True` if the command was killed, `False` if the command was not found - - - -### send\_stdin - -```python -async def send_stdin(pid: int, - data: str, - request_timeout: Optional[float] = None) -> None -``` - -Send data to command stdin. - -:param pid Process ID of the command. You can get the list of processes using `sandbox.commands.list()`. -:param data: Data to send to the command -:param request_timeout: Timeout for the request in **seconds** - - - - -### run - -```python -@overload -async def run(cmd: str, - background: Union[Literal[False], None] = None, - envs: Optional[Dict[str, str]] = None, - user: Username = "user", - cwd: Optional[str] = None, - on_stdout: Optional[OutputHandler[Stdout]] = None, - on_stderr: Optional[OutputHandler[Stderr]] = None, - timeout: Optional[float] = 60, - request_timeout: Optional[float] = None) -> CommandResult -``` - -Start a new command and wait until it finishes executing. - -**Arguments**: - -- `cmd`: Command to execute -- `background`: **`False` if the command should be executed in the foreground**, `True` if the command should be executed in the background -- `envs`: Environment variables used for the command -- `user`: User to run the command as -- `cwd`: Working directory to run the command -- `on_stdout`: Callback for command stdout output -- `on_stderr`: Callback for command stderr output -- `timeout`: Timeout for the command connection in **seconds**. Using `0` will not limit the command connection time -- `request_timeout`: Timeout for the request in **seconds** - -**Returns**: - -`CommandResult` result of the command execution - - - -### run - -```python -@overload -async def run(cmd: str, - background: Literal[True], - envs: Optional[Dict[str, str]] = None, - user: Username = "user", - cwd: Optional[str] = None, - on_stdout: Optional[OutputHandler[Stdout]] = None, - on_stderr: Optional[OutputHandler[Stderr]] = None, - timeout: Optional[float] = 60, - request_timeout: Optional[float] = None) -> AsyncCommandHandle -``` - -Start a new command and return a handle to interact with it. - -**Arguments**: - -- `cmd`: Command to execute -- `background`: `False` if the command should be executed in the foreground, **`True` if the command should be executed in the background** -- `envs`: Environment variables used for the command -- `user`: User to run the command as -- `cwd`: Working directory to run the command -- `on_stdout`: Callback for command stdout output -- `on_stderr`: Callback for command stderr output -- `timeout`: Timeout for the command connection in **seconds**. Using `0` will not limit the command connection time -- `request_timeout`: Timeout for the request in **seconds** - -**Returns**: - -`AsyncCommandHandle` handle to interact with the running command - - - -### connect - -```python -async def connect( - pid: int, - timeout: Optional[float] = 60, - request_timeout: Optional[float] = None, - on_stdout: Optional[OutputHandler[Stdout]] = None, - on_stderr: Optional[OutputHandler[Stderr]] = None -) -> AsyncCommandHandle -``` - -Connects to a running command. - -You can use `AsyncCommandHandle.wait()` to wait for the command to finish and get execution results. - -**Arguments**: - -- `pid`: Process ID of the command to connect to. You can get the list of processes using `sandbox.commands.list()` -- `request_timeout`: Request timeout in **seconds** -- `timeout`: Timeout for the command connection in **seconds**. Using `0` will not limit the command connection time -- `on_stdout`: Callback for command stdout output -- `on_stderr`: Callback for command stderr output - -**Returns**: - -`AsyncCommandHandle` handle to interact with the running command - - - - - - -## AsyncCommandHandle - -```python -class AsyncCommandHandle() -``` - -Command execution handle. - -It provides methods for waiting for the command to finish, retrieving stdout/stderr, and killing the command. - - - -### pid - -```python -@property -def pid() -``` - -Command process ID. - - - -### stdout - -```python -@property -def stdout() -``` - -Command stdout output. - - - -### stderr - -```python -@property -def stderr() -``` - -Command stderr output. - - - -### error - -```python -@property -def error() -``` - -Command execution error message. - - - -### exit\_code - -```python -@property -def exit_code() -``` - -Command execution exit code. - -`0` if the command finished successfully. - -It is `None` if the command is still running. - - - -### disconnect - -```python -async def disconnect() -> None -``` - -Disconnects from the command. - -The command is not killed, but SDK stops receiving events from the command. -You can reconnect to the command using `sandbox.commands.connect` method. - - - -### wait - -```python -async def wait() -> CommandResult -``` - -Wait for the command to finish and return the result. - -If the command exits with a non-zero exit code, it throws a `CommandExitException`. - -**Returns**: - -`CommandResult` result of command execution - - - -### kill - -```python -async def kill() -> bool -``` - -Kills the command. - -It uses `SIGKILL` signal to kill the command - -**Returns**: - -`True` if the command was killed successfully, `False` if the command was not found - - - - - - -## Pty - -```python -class Pty() -``` - -Module for interacting with PTYs (pseudo-terminals) in the sandbox. - - - -### kill - -```python -async def kill(pid: int, request_timeout: Optional[float] = None) -> bool -``` - -Kill PTY. - -**Arguments**: - -- `pid`: Process ID of the PTY -- `request_timeout`: Timeout for the request in **seconds** - -**Returns**: - -`true` if the PTY was killed, `false` if the PTY was not found - - - -### send\_stdin - -```python -async def send_stdin(pid: int, - data: bytes, - request_timeout: Optional[float] = None) -> None -``` - -Send input to a PTY. - -**Arguments**: - -- `pid`: Process ID of the PTY -- `data`: Input data to send -- `request_timeout`: Timeout for the request in **seconds** - - - -### create - -```python -async def create( - size: PtySize, - on_data: OutputHandler[PtyOutput], - user: Username = "user", - cwd: Optional[str] = None, - envs: Optional[Dict[str, str]] = None, - timeout: Optional[float] = 60, - request_timeout: Optional[float] = None) -> AsyncCommandHandle -``` - -Start a new PTY (pseudo-terminal). - -**Arguments**: - -- `size`: Size of the PTY -- `on_data`: Callback to handle PTY data -- `user`: User to use for the PTY -- `cwd`: Working directory for the PTY -- `envs`: Environment variables for the PTY -- `timeout`: Timeout for the PTY in **seconds** -- `request_timeout`: Timeout for the request in **seconds** - -**Returns**: - -Handle to interact with the PTY - - - -### resize - -```python -async def resize(pid: int, - size: PtySize, - request_timeout: Optional[float] = None) -``` - -Resize PTY. - -Call this when the terminal window is resized and the number of columns and rows has changed. - -**Arguments**: - -- `pid`: Process ID of the PTY -- `size`: New size of the PTY -- `request_timeout`: Timeout for the request in **seconds** - - - - - - -## AsyncSandbox - -```python -class AsyncSandbox(SandboxSetup, SandboxApi) -``` - -E2B cloud sandbox is a secure and isolated cloud environment. - -The sandbox allows you to: -- Access Linux OS -- Create, list, and delete files and directories -- Run commands -- Run isolated code -- Access the internet - -Check docs [here](https://e2b.dev/docs). - -Use the `AsyncSandbox.create()` to create a new sandbox. - -**Example**: - -```python -from e2b import AsyncSandbox - -sandbox = await AsyncSandbox.create() -``` - - - -### files - -```python -@property -def files() -> Filesystem -``` - -Module for interacting with the sandbox filesystem. - - - -### commands - -```python -@property -def commands() -> Commands -``` - -Module for running commands in the sandbox. - - - -### pty - -```python -@property -def pty() -> Pty -``` - -Module for interacting with the sandbox pseudo-terminal. - - - -### sandbox\_id - -```python -@property -def sandbox_id() -> str -``` - -Unique identifier of the sandbox. - - - -### \_\_init\_\_ - -```python -def __init__(**opts: Unpack[AsyncSandboxOpts]) -``` - -Use `AsyncSandbox.create()` to create a new sandbox instead. - - - -### is\_running - -```python -async def is_running(request_timeout: Optional[float] = None) -> bool -``` - -Check if the sandbox is running. - -**Arguments**: - -- `request_timeout`: Timeout for the request in **seconds** - -**Returns**: - -`True` if the sandbox is running, `False` otherwise -Example -```python -sandbox = await AsyncSandbox.create() -await sandbox.is_running() # Returns True - -await sandbox.kill() -await sandbox.is_running() # Returns False -``` - - - -### create - -```python -@classmethod -async def create(cls, - template: Optional[str] = None, - timeout: Optional[int] = None, - metadata: Optional[Dict[str, str]] = None, - envs: Optional[Dict[str, str]] = None, - api_key: Optional[str] = None, - domain: Optional[str] = None, - debug: Optional[bool] = None, - request_timeout: Optional[float] = None) -``` - -Create a new sandbox. - -By default, the sandbox is created from the default `base` sandbox template. - -**Arguments**: - -- `template`: Sandbox template name or ID -- `timeout`: Timeout for the sandbox in **seconds**, default to 300 seconds. Maximum time a sandbox can be kept alive is 24 hours (86_400 seconds) for Pro users and 1 hour (3_600 seconds) for Hobby users. -- `metadata`: Custom metadata for the sandbox -- `envs`: Custom environment variables for the sandbox -- `api_key`: E2B API Key to use for authentication, defaults to `E2B_API_KEY` environment variable -- `request_timeout`: Timeout for the request in **seconds** - -**Returns**: - -sandbox instance for the new sandbox -Use this method instead of using the constructor to create a new sandbox. - - - -### connect - -```python -@classmethod -async def connect(cls, - sandbox_id: str, - api_key: Optional[str] = None, - domain: Optional[str] = None, - debug: Optional[bool] = None) -``` - -Connect to an existing sandbox. - -With sandbox ID you can connect to the same sandbox from different places or environments (serverless functions, etc). - -**Arguments**: - -- `sandbox_id`: Sandbox ID -- `api_key`: E2B API Key to use for authentication, defaults to `E2B_API_KEY` environment variable - -**Returns**: - -sandbox instance for the existing sandbox -@example -```python -sandbox = await AsyncSandbox.create() -sandbox_id = sandbox.sandbox_id - -same_sandbox = await AsyncSandbox.connect(sandbox_id) - - - -### kill - -```python -@overload -async def kill(request_timeout: Optional[float] = None) -> bool -``` - -Kill the sandbox. - -**Arguments**: - -- `request_timeout`: Timeout for the request in **seconds** - -**Returns**: - -`True` if the sandbox was killed, `False` if the sandbox was not found - - - -### kill - -```python -@overload -@staticmethod -async def kill(sandbox_id: str, - api_key: Optional[str] = None, - domain: Optional[str] = None, - debug: Optional[bool] = None, - request_timeout: Optional[float] = None) -> bool -``` - -Kill the sandbox specified by sandbox ID. - -**Arguments**: - -- `sandbox_id`: Sandbox ID -- `api_key`: E2B API Key to use for authentication, defaults to `E2B_API_KEY` environment variable -- `request_timeout`: Timeout for the request in **seconds** - -**Returns**: - -`True` if the sandbox was killed, `False` if the sandbox was not found - - - -### set\_timeout - -```python -@overload -async def set_timeout(timeout: int, - request_timeout: Optional[float] = None) -> None -``` - -Set the timeout of the sandbox. - -After the timeout expires the sandbox will be automatically killed. -This method can extend or reduce the sandbox timeout set when creating the sandbox or from the last call to `.set_timeout`. - -Maximum time a sandbox can be kept alive is 24 hours (86_400 seconds) for Pro users and 1 hour (3_600 seconds) for Hobby users. - -**Arguments**: - -- `timeout`: Timeout for the sandbox in **seconds** -- `request_timeout`: Timeout for the request in **seconds** - - - -### set\_timeout - -```python -@overload -@staticmethod -async def set_timeout(sandbox_id: str, - timeout: int, - api_key: Optional[str] = None, - domain: Optional[str] = None, - debug: Optional[bool] = None, - request_timeout: Optional[float] = None) -> None -``` - -Set the timeout of the specified sandbox. - -After the timeout expires the sandbox will be automatically killed. -This method can extend or reduce the sandbox timeout set when creating the sandbox or from the last call to `.set_timeout`. - -Maximum time a sandbox can be kept alive is 24 hours (86_400 seconds) for Pro users and 1 hour (3_600 seconds) for Hobby users. - -**Arguments**: - -- `sandbox_id`: Sandbox ID -- `timeout`: Timeout for the sandbox in **seconds** -- `request_timeout`: Timeout for the request in **seconds** diff --git a/docs/sdk-reference/python-sdk/1.0.0/sandbox_sync.mdx b/docs/sdk-reference/python-sdk/1.0.0/sandbox_sync.mdx deleted file mode 100644 index c94bb48..0000000 --- a/docs/sdk-reference/python-sdk/1.0.0/sandbox_sync.mdx +++ /dev/null @@ -1,959 +0,0 @@ ---- -sidebarTitle: "Sandbox Sync" -mode: "center" ---- - - - - - - -## WatchHandle - -```python -class WatchHandle() -``` - -Handle for watching filesystem events. -It is used to get the latest events that have occurred in the watched directory. - -Use `.stop()` to stop watching the directory. - - - -### stop - -```python -def stop() -``` - -Stop watching the directory. -After you stop the watcher you won't be able to get the events anymore. - - - -### get\_new\_events - -```python -def get_new_events() -> List[FilesystemEvent] -``` - -Get the latest events that have occurred in the watched directory since the last call, or from the beginning of the watching, up until now. - -**Returns**: - -List of filesystem events - - - - - - -## Filesystem - -```python -class Filesystem() -``` - -Module for interacting with the filesystem in the sandbox. - - - -### read - -```python -@overload -def read(path: str, - format: Literal["text"] = "text", - user: Username = "user", - request_timeout: Optional[float] = None) -> str -``` - -Read file content as a `str`. - -**Arguments**: - -- `path`: Path to the file -- `user`: Run the operation as this user -- `format`: Format of the file content—`text` by default -- `request_timeout`: Timeout for the request in **seconds** - -**Returns**: - -File content as a `str` - - - -### read - -```python -@overload -def read(path: str, - format: Literal["bytes"], - user: Username = "user", - request_timeout: Optional[float] = None) -> bytearray -``` - -Read file content as a `bytearray`. - -**Arguments**: - -- `path`: Path to the file -- `user`: Run the operation as this user -- `format`: Format of the file content—`bytes` -- `request_timeout`: Timeout for the request in **seconds** - -**Returns**: - -File content as a `bytearray` - - - -### read - -```python -@overload -def read(path: str, - format: Literal["stream"], - user: Username = "user", - request_timeout: Optional[float] = None) -> Iterator[bytes] -``` - -Read file content as a `Iterator[bytes]`. - -**Arguments**: - -- `path`: Path to the file -- `user`: Run the operation as this user -- `format`: Format of the file content—`stream` -- `request_timeout`: Timeout for the request in **seconds** - -**Returns**: - -File content as an `Iterator[bytes]` - - - -### write - -```python -def write(path: str, - data: Union[str, bytes, IO], - user: Username = "user", - request_timeout: Optional[float] = None) -> EntryInfo -``` - -Write content to a file on the path. - -Writing to a file that doesn't exist creates the file. - -Writing to a file that already exists overwrites the file. - -Writing to a file at path that doesn't exist creates the necessary directories. - -**Arguments**: - -- `path`: Path to the file -- `data`: Data to write to the file, can be a `str`, `bytes`, or `IO`. -- `user`: Run the operation as this user -- `request_timeout`: Timeout for the request in **seconds** - -**Returns**: - -Information about the written file - - - -### list - -```python -def list(path: str, - user: Username = "user", - request_timeout: Optional[float] = None) -> List[EntryInfo] -``` - -List entries in a directory. - -**Arguments**: - -- `path`: Path to the directory -- `user`: Run the operation as this user -- `request_timeout`: Timeout for the request in **seconds** - -**Returns**: - -List of entries in the directory - - - -### exists - -```python -def exists(path: str, - user: Username = "user", - request_timeout: Optional[float] = None) -> bool -``` - -Check if a file or a directory exists. - -**Arguments**: - -- `path`: Path to a file or a directory -- `user`: Run the operation as this user -- `request_timeout`: Timeout for the request in **seconds** - -**Returns**: - -`True` if the file or directory exists, `False` otherwise - - - -### remove - -```python -def remove(path: str, - user: Username = "user", - request_timeout: Optional[float] = None) -> None -``` - -Remove a file or a directory. - -**Arguments**: - -- `path`: Path to a file or a directory -- `user`: Run the operation as this user -- `request_timeout`: Timeout for the request in **seconds** - - - -### rename - -```python -def rename(old_path: str, - new_path: str, - user: Username = "user", - request_timeout: Optional[float] = None) -> EntryInfo -``` - -Rename a file or directory. - -**Arguments**: - -- `old_path`: Path to the file or directory to rename -- `new_path`: New path to the file or directory -- `user`: Run the operation as this user -- `request_timeout`: Timeout for the request in **seconds** - -**Returns**: - -Information about the renamed file or directory - - - -### make\_dir - -```python -def make_dir(path: str, - user: Username = "user", - request_timeout: Optional[float] = None) -> bool -``` - -Create a new directory and all directories along the way if needed on the specified path. - -**Arguments**: - -- `path`: Path to a new directory. For example '/dirA/dirB' when creating 'dirB'. -- `user`: Run the operation as this user -- `request_timeout`: Timeout for the request in **seconds** - -**Returns**: - -`True` if the directory was created, `False` if the directory already exists - - - -### watch\_dir - -```python -def watch_dir(path: str, - user: Username = "user", - request_timeout: Optional[float] = None) -> WatchHandle -``` - -Watch directory for filesystem events. - -**Arguments**: - -- `path`: Path to a directory to watch -- `user`: Run the operation as this user -- `request_timeout`: Timeout for the request in **seconds** - -**Returns**: - -`WatchHandle` object for stopping watching directory - - - - - - -## SandboxApi - -```python -class SandboxApi(SandboxApiBase) -``` - - - -### list - -```python -@classmethod -def list(cls, - api_key: Optional[str] = None, - domain: Optional[str] = None, - debug: Optional[bool] = None, - request_timeout: Optional[float] = None) -> List[SandboxInfo] -``` - -List all running sandboxes. - -**Arguments**: - -- `api_key`: API key to use for authentication, defaults to `E2B_API_KEY` environment variable -- `request_timeout`: Timeout for the request in **seconds** - -**Returns**: - -List of sandbox info - - - - - - -## Commands - -```python -class Commands() -``` - -Module for executing commands in the sandbox. - - - -### list - -```python -def list(request_timeout: Optional[float] = None) -> List[ProcessInfo] -``` - -Lists all running commands and PTY sessions. - -**Arguments**: - -- `request_timeout`: Timeout for the request in **seconds** - -**Returns**: - -List of running commands and PTY sessions - - - -### kill - -```python -def kill(pid: int, request_timeout: Optional[float] = None) -> bool -``` - -Kills a running command specified by its process ID. - -It uses `SIGKILL` signal to kill the command. - -**Arguments**: - -- `pid`: Process ID of the command. You can get the list of processes using `sandbox.commands.list()` -- `request_timeout`: Timeout for the request in **seconds** - -**Returns**: - -`True` if the command was killed, `False` if the command was not found - - - -### send\_stdin - -```python -def send_stdin(pid: int, data: str, request_timeout: Optional[float] = None) -``` - -Send data to command stdin. - -:param pid Process ID of the command. You can get the list of processes using `sandbox.commands.list()`. -:param data: Data to send to the command -:param request_timeout: Timeout for the request in **seconds** - - - - -### run - -```python -@overload -def run(cmd: str, - background: Union[Literal[False], None] = None, - envs: Optional[Dict[str, str]] = None, - user: Username = "user", - cwd: Optional[str] = None, - on_stdout: Optional[Callable[[str], None]] = None, - on_stderr: Optional[Callable[[str], None]] = None, - timeout: Optional[float] = 60, - request_timeout: Optional[float] = None) -> CommandResult -``` - -Start a new command and wait until it finishes executing. - -**Arguments**: - -- `cmd`: Command to execute -- `background`: **`False` if the command should be executed in the foreground**, `True` if the command should be executed in the background -- `envs`: Environment variables used for the command -- `user`: User to run the command as -- `cwd`: Working directory to run the command -- `on_stdout`: Callback for command stdout output -- `on_stderr`: Callback for command stderr output -- `timeout`: Timeout for the command connection in **seconds**. Using `0` will not limit the command connection time -- `request_timeout`: Timeout for the request in **seconds** - -**Returns**: - -`CommandResult` result of the command execution - - - -### run - -```python -@overload -def run(cmd: str, - background: Literal[True], - envs: Optional[Dict[str, str]] = None, - user: Username = "user", - cwd: Optional[str] = None, - on_stdout: None = None, - on_stderr: None = None, - timeout: Optional[float] = 60, - request_timeout: Optional[float] = None) -> CommandHandle -``` - -Start a new command and return a handle to interact with it. - -**Arguments**: - -- `cmd`: Command to execute -- `background`: `False` if the command should be executed in the foreground, **`True` if the command should be executed in the background** -- `envs`: Environment variables used for the command -- `user`: User to run the command as -- `cwd`: Working directory to run the command -- `timeout`: Timeout for the command connection in **seconds**. Using `0` will not limit the command connection time -- `request_timeout`: Timeout for the request in **seconds** - -**Returns**: - -`CommandHandle` handle to interact with the running command - - - -### connect - -```python -def connect(pid: int, - timeout: Optional[float] = 60, - request_timeout: Optional[float] = None) -``` - -Connects to a running command. - -You can use `CommandHandle.wait()` to wait for the command to finish and get execution results. - -**Arguments**: - -- `pid`: Process ID of the command to connect to. You can get the list of processes using `sandbox.commands.list()` -- `timeout`: Timeout for the connection in **seconds**. Using `0` will not limit the connection time -- `request_timeout`: Timeout for the request in **seconds** - -**Returns**: - -`CommandHandle` handle to interact with the running command - - - - - - -## CommandHandle - -```python -class CommandHandle() -``` - -Command execution handle. - -It provides methods for waiting for the command to finish, retrieving stdout/stderr, and killing the command. - - - -### pid - -```python -@property -def pid() -``` - -Command process ID. - - - -### \_\_iter\_\_ - -```python -def __iter__() -``` - -Iterate over the command output. - -**Returns**: - -Generator of command outputs - - - -### disconnect - -```python -def disconnect() -> None -``` - -Disconnect from the command. - -The command is not killed, but SDK stops receiving events from the command. -You can reconnect to the command using `sandbox.commands.connect` method. - - - -### wait - -```python -def wait(on_pty: Optional[Callable[[PtyOutput], None]] = None, - on_stdout: Optional[Callable[[str], None]] = None, - on_stderr: Optional[Callable[[str], None]] = None) -> CommandResult -``` - -Wait for the command to finish and returns the result. - -If the command exits with a non-zero exit code, it throws a `CommandExitException`. - -**Arguments**: - -- `on_pty`: Callback for pty output -- `on_stdout`: Callback for stdout output -- `on_stderr`: Callback for stderr output - -**Returns**: - -`CommandResult` result of command execution - - - -### kill - -```python -def kill() -> bool -``` - -Kills the command. - -It uses `SIGKILL` signal to kill the command. - -**Returns**: - -Whether the command was killed successfully - - - - - - -## Pty - -```python -class Pty() -``` - -Module for interacting with PTYs (pseudo-terminals) in the sandbox. - - - -### kill - -```python -def kill(pid: int, request_timeout: Optional[float] = None) -> bool -``` - -Kill PTY. - -**Arguments**: - -- `pid`: Process ID of the PTY -- `request_timeout`: Timeout for the request in **seconds** - -**Returns**: - -`true` if the PTY was killed, `false` if the PTY was not found - - - -### send\_stdin - -```python -def send_stdin(pid: int, - data: bytes, - request_timeout: Optional[float] = None) -> None -``` - -Send input to a PTY. - -**Arguments**: - -- `pid`: Process ID of the PTY -- `data`: Input data to send -- `request_timeout`: Timeout for the request in **seconds** - - - -### create - -```python -def create(size: PtySize, - user: Username = "user", - cwd: Optional[str] = None, - envs: Optional[Dict[str, str]] = None, - timeout: Optional[float] = 60, - request_timeout: Optional[float] = None) -> CommandHandle -``` - -Start a new PTY (pseudo-terminal). - -**Arguments**: - -- `size`: Size of the PTY -- `user`: User to use for the PTY -- `cwd`: Working directory for the PTY -- `envs`: Environment variables for the PTY -- `timeout`: Timeout for the PTY in **seconds** -- `request_timeout`: Timeout for the request in **seconds** - -**Returns**: - -Handle to interact with the PTY - - - -### resize - -```python -def resize(pid: int, - size: PtySize, - request_timeout: Optional[float] = None) -> None -``` - -Resize PTY. - -Call this when the terminal window is resized and the number of columns and rows has changed. - -**Arguments**: - -- `pid`: Process ID of the PTY -- `size`: New size of the PTY -- `request_timeout`: Timeout for the request in **seconds**s - - - - - - -## Sandbox - -```python -class Sandbox(SandboxSetup, SandboxApi) -``` - -E2B cloud sandbox is a secure and isolated cloud environment. - -The sandbox allows you to: -- Access Linux OS -- Create, list, and delete files and directories -- Run commands -- Run isolated code -- Access the internet - -Check docs [here](https://e2b.dev/docs). - -Use the `Sandbox()` to create a new sandbox. - -**Example**: - -```python -from e2b import Sandbox - -sandbox = Sandbox() -``` - - - -### files - -```python -@property -def files() -> Filesystem -``` - -Module for interacting with the sandbox filesystem. - - - -### commands - -```python -@property -def commands() -> Commands -``` - -Module for running commands in the sandbox. - - - -### pty - -```python -@property -def pty() -> Pty -``` - -Module for interacting with the sandbox pseudo-terminal. - - - -### sandbox\_id - -```python -@property -def sandbox_id() -> str -``` - -Unique identifier of the sandbox - - - -### \_\_init\_\_ - -```python -def __init__(template: Optional[str] = None, - timeout: Optional[int] = None, - metadata: Optional[Dict[str, str]] = None, - envs: Optional[Dict[str, str]] = None, - api_key: Optional[str] = None, - domain: Optional[str] = None, - debug: Optional[bool] = None, - sandbox_id: Optional[str] = None, - request_timeout: Optional[float] = None) -``` - -Create a new sandbox. - -By default, the sandbox is created from the default `base` sandbox template. - -**Arguments**: - -- `template`: Sandbox template name or ID -- `timeout`: Timeout for the sandbox in **seconds**, default to 300 seconds. Maximum time a sandbox can be kept alive is 24 hours (86_400 seconds) for Pro users and 1 hour (3_600 seconds) for Hobby users -- `metadata`: Custom metadata for the sandbox -- `envs`: Custom environment variables for the sandbox -- `api_key`: E2B API Key to use for authentication, defaults to `E2B_API_KEY` environment variable -- `request_timeout`: Timeout for the request in **seconds** - -**Returns**: - -sandbox instance for the new sandbox - - - -### is\_running - -```python -def is_running(request_timeout: Optional[float] = None) -> bool -``` - -Check if the sandbox is running. - -**Arguments**: - -- `request_timeout`: Timeout for the request in **seconds** - -**Returns**: - -`True` if the sandbox is running, `False` otherwise -Example -```python -sandbox = Sandbox() -sandbox.is_running() # Returns True - -sandbox.kill() -sandbox.is_running() # Returns False -``` - - - -### connect - -```python -@classmethod -def connect(cls, - sandbox_id: str, - api_key: Optional[str] = None, - domain: Optional[str] = None, - debug: Optional[bool] = None) -``` - -Connects to an existing Sandbox. - -With sandbox ID you can connect to the same sandbox from different places or environments (serverless functions, etc). - -**Arguments**: - -- `sandbox_id`: Sandbox ID -- `api_key`: E2B API Key to use for authentication, defaults to `E2B_API_KEY` environment variable - -**Returns**: - -sandbox instance for the existing sandbox -@example -```python -sandbox = Sandbox() -sandbox_id = sandbox.sandbox_id - -same_sandbox = Sandbox.connect(sandbox_id) - - - -### kill - -```python -@overload -def kill(request_timeout: Optional[float] = None) -> bool -``` - -Kill the sandbox. - -**Arguments**: - -- `request_timeout`: Timeout for the request in **seconds** - -**Returns**: - -`True` if the sandbox was killed, `False` if the sandbox was not found - - - -### kill - -```python -@overload -@staticmethod -def kill(sandbox_id: str, - api_key: Optional[str] = None, - domain: Optional[str] = None, - debug: Optional[bool] = None, - request_timeout: Optional[float] = None) -> bool -``` - -Kill the sandbox specified by sandbox ID. - -**Arguments**: - -- `sandbox_id`: Sandbox ID -- `api_key`: E2B API Key to use for authentication, defaults to `E2B_API_KEY` environment variable -- `request_timeout`: Timeout for the request in **seconds** - -**Returns**: - -`True` if the sandbox was killed, `False` if the sandbox was not found - - - -### kill - -```python -@class_method_variant("_cls_kill") -def kill(request_timeout: Optional[float] = None) -> bool -``` - -Kill the sandbox. - -**Arguments**: - -- `request_timeout`: Timeout for the request - -**Returns**: - -`True` if the sandbox was killed, `False` if the sandbox was not found - - - -### set\_timeout - -```python -@overload -def set_timeout(timeout: int, request_timeout: Optional[float] = None) -> None -``` - -Set the timeout of the sandbox. - -After the timeout expires the sandbox will be automatically killed. -This method can extend or reduce the sandbox timeout set when creating the sandbox or from the last call to `.set_timeout`. - -Maximum time a sandbox can be kept alive is 24 hours (86_400 seconds) for Pro users and 1 hour (3_600 seconds) for Hobby users. - -**Arguments**: - -- `timeout`: Timeout for the sandbox in **seconds** -- `request_timeout`: Timeout for the request in **seconds** - - - -### set\_timeout - -```python -@overload -@staticmethod -def set_timeout(sandbox_id: str, - timeout: int, - api_key: Optional[str] = None, - domain: Optional[str] = None, - debug: Optional[bool] = None, - request_timeout: Optional[float] = None) -> None -``` - -Set the timeout of the sandbox specified by sandbox ID. - -After the timeout expires the sandbox will be automatically killed. -This method can extend or reduce the sandbox timeout set when creating the sandbox or from the last call to `.set_timeout`. - -Maximum time a sandbox can be kept alive is 24 hours (86_400 seconds) for Pro users and 1 hour (3_600 seconds) for Hobby users. - -**Arguments**: - -- `sandbox_id`: Sandbox ID -- `timeout`: Timeout for the sandbox in **seconds** -- `api_key`: E2B API Key to use for authentication, defaults to `E2B_API_KEY` environment variable -- `request_timeout`: Timeout for the request in **seconds** diff --git a/docs/sdk-reference/python-sdk/v2.7.0/exceptions.mdx b/docs/sdk-reference/python-sdk/v2.7.0/exceptions.mdx deleted file mode 100644 index d66f786..0000000 --- a/docs/sdk-reference/python-sdk/v2.7.0/exceptions.mdx +++ /dev/null @@ -1,117 +0,0 @@ ---- -sidebarTitle: "Exceptions" -mode: "center" ---- - - - - - - -## SandboxException - -```python -class SandboxException(Exception) -``` - -Base class for all sandbox errors. - -Raised when a general sandbox exception occurs. - - - -## TimeoutException - -```python -class TimeoutException(SandboxException) -``` - -Raised when a timeout occurs. - -The `unavailable` exception type is caused by sandbox timeout. - -The `canceled` exception type is caused by exceeding request timeout. - -The `deadline_exceeded` exception type is caused by exceeding the timeout for process, watch, etc. - -The `unknown` exception type is sometimes caused by the sandbox timeout when the request is not processed correctly. - - - -## InvalidArgumentException - -```python -class InvalidArgumentException(SandboxException) -``` - -Raised when an invalid argument is provided. - - - -## NotEnoughSpaceException - -```python -class NotEnoughSpaceException(SandboxException) -``` - -Raised when there is not enough disk space. - - - -## NotFoundException - -```python -class NotFoundException(SandboxException) -``` - -Raised when a resource is not found. - - - -## AuthenticationException - -```python -class AuthenticationException(Exception) -``` - -Raised when authentication fails. - - - -## TemplateException - -```python -class TemplateException(SandboxException) -``` - -Exception raised when the template uses old envd version. It isn't compatible with the new SDK. - - - -## RateLimitException - -```python -class RateLimitException(SandboxException) -``` - -Raised when the API rate limit is exceeded. - - - -## BuildException - -```python -class BuildException(Exception) -``` - -Raised when the build fails. - - - -## FileUploadException - -```python -class FileUploadException(BuildException) -``` - -Raised when the file upload fails. diff --git a/docs/sdk-reference/python-sdk/v2.7.0/logger.mdx b/docs/sdk-reference/python-sdk/v2.7.0/logger.mdx deleted file mode 100644 index 9fa3b18..0000000 --- a/docs/sdk-reference/python-sdk/v2.7.0/logger.mdx +++ /dev/null @@ -1,106 +0,0 @@ ---- -sidebarTitle: "Logger" -mode: "center" ---- - - - - - - -## LogEntry - -```python -@dataclass -class LogEntry() -``` - -Represents a single log entry from the template build process. - - - -## LogEntryStart - -```python -@dataclass -class LogEntryStart(LogEntry) -``` - -Special log entry indicating the start of a build process. - - - -## LogEntryEnd - -```python -@dataclass -class LogEntryEnd(LogEntry) -``` - -Special log entry indicating the end of a build process. - - - -### TIMER\_UPDATE\_INTERVAL\_MS - -Default minimum log level to display. - - - -### DEFAULT\_LEVEL - -Colored labels for each log level. - - - -### levels - -Numeric ordering of log levels for comparison (lower = less severe). - - - -### set\_interval - -```python -def set_interval(func, interval) -``` - -Returns a stop function that can be called to cancel the interval. - -Similar to JavaScript's setInterval. - -**Arguments**: - -- `func`: Function to execute at each interval -- `interval`: Interval duration in **seconds** - -**Returns**: - -Stop function that can be called to cancel the interval - - - -### default\_build\_logger - -```python -def default_build_logger( - min_level: Optional[LogEntryLevel] = None -) -> Callable[[LogEntry], None] -``` - -Create a default build logger with animated timer display. - -**Arguments**: - -- `min_level`: Minimum log level to display (default: 'info') - -**Returns**: - -Logger function that accepts LogEntry instances -Example -```python -from e2b import Template, default_build_logger - -template = Template().from_python_image() - -``` diff --git a/docs/sdk-reference/python-sdk/v2.7.0/readycmd.mdx b/docs/sdk-reference/python-sdk/v2.7.0/readycmd.mdx deleted file mode 100644 index 8eabda6..0000000 --- a/docs/sdk-reference/python-sdk/v2.7.0/readycmd.mdx +++ /dev/null @@ -1,168 +0,0 @@ ---- -sidebarTitle: "Readycmd" -mode: "center" ---- - - - - - - -## ReadyCmd - -```python -class ReadyCmd() -``` - -Wrapper class for ready check commands. - - - -### wait\_for\_port - -```python -def wait_for_port(port: int) -``` - -Wait for a port to be listening. - -Uses `ss` command to check if a port is open and listening. - -**Arguments**: - -- `port`: Port number to wait for - -**Returns**: - -ReadyCmd that checks for the port -Example -```python -from e2b import Template, wait_for_port - -template = ( - Template() - .from_python_image() - .set_start_cmd('python -m http.server 8000', wait_for_port(8000)) -) -``` - - - -### wait\_for\_url - -```python -def wait_for_url(url: str, status_code: int = 200) -``` - -Wait for a URL to return a specific HTTP status code. - -Uses `curl` to make HTTP requests and check the response status. - -**Arguments**: - -- `url`: URL to check (e.g., 'http://localhost:3000/health') -- `status_code`: Expected HTTP status code (default: 200) - -**Returns**: - -ReadyCmd that checks the URL -Example -```python -from e2b import Template, wait_for_url - -template = ( - Template() - .from_node_image() - .set_start_cmd('npm start', wait_for_url('http://localhost:3000/health')) -) -``` - - - -### wait\_for\_process - -```python -def wait_for_process(process_name: str) -``` - -Wait for a process with a specific name to be running. - -Uses `pgrep` to check if a process exists. - -**Arguments**: - -- `process_name`: Name of the process to wait for - -**Returns**: - -ReadyCmd that checks for the process -Example -```python -from e2b import Template, wait_for_process - -template = ( - Template() - .from_base_image() - .set_start_cmd('./my-daemon', wait_for_process('my-daemon')) -) -``` - - - -### wait\_for\_file - -```python -def wait_for_file(filename: str) -``` - -Wait for a file to exist. - -Uses shell test command to check file existence. - -**Arguments**: - -- `filename`: Path to the file to wait for - -**Returns**: - -ReadyCmd that checks for the file -Example -```python -from e2b import Template, wait_for_file - -template = ( - Template() - .from_base_image() - .set_start_cmd('./init.sh', wait_for_file('/tmp/ready')) -) -``` - - - -### wait\_for\_timeout - -```python -def wait_for_timeout(timeout: int) -``` - -Wait for a specified timeout before considering the sandbox ready. - -Uses `sleep` command to wait for a fixed duration. - -**Arguments**: - -- `timeout`: Time to wait in **milliseconds** (minimum: 1000ms / 1 second) - -**Returns**: - -ReadyCmd that waits for the specified duration -Example -```python -from e2b import Template, wait_for_timeout - -template = ( - Template() - .from_node_image() - .set_start_cmd('npm start', wait_for_timeout(5000)) # Wait 5 seconds -) -``` diff --git a/docs/sdk-reference/python-sdk/v2.7.0/sandbox_async.mdx b/docs/sdk-reference/python-sdk/v2.7.0/sandbox_async.mdx deleted file mode 100644 index b636b1a..0000000 --- a/docs/sdk-reference/python-sdk/v2.7.0/sandbox_async.mdx +++ /dev/null @@ -1,1387 +0,0 @@ ---- -sidebarTitle: "Sandbox Async" -mode: "center" ---- - - - - - - -## AsyncWatchHandle - -```python -class AsyncWatchHandle() -``` - -Handle for watching a directory in the sandbox filesystem. - -Use `.stop()` to stop watching the directory. - - - -### stop - -```python -async def stop() -``` - -Stop watching the directory. - - - - - - -## Filesystem - -```python -class Filesystem() -``` - -Module for interacting with the filesystem in the sandbox. - - - -### read - -```python -@overload -async def read(path: str, - format: Literal["text"] = "text", - user: Optional[Username] = None, - request_timeout: Optional[float] = None) -> str -``` - -Read file content as a `str`. - -**Arguments**: - -- `path`: Path to the file -- `user`: Run the operation as this user -- `format`: Format of the file content—`text` by default -- `request_timeout`: Timeout for the request in **seconds** - -**Returns**: - -File content as a `str` - - - -### read - -```python -@overload -async def read(path: str, - format: Literal["bytes"], - user: Optional[Username] = None, - request_timeout: Optional[float] = None) -> bytearray -``` - -Read file content as a `bytearray`. - -**Arguments**: - -- `path`: Path to the file -- `user`: Run the operation as this user -- `format`: Format of the file content—`bytes` -- `request_timeout`: Timeout for the request in **seconds** - -**Returns**: - -File content as a `bytearray` - - - -### read - -```python -@overload -async def read( - path: str, - format: Literal["stream"], - user: Optional[Username] = None, - request_timeout: Optional[float] = None) -> AsyncIterator[bytes] -``` - -Read file content as a `AsyncIterator[bytes]`. - -**Arguments**: - -- `path`: Path to the file -- `user`: Run the operation as this user -- `format`: Format of the file content—`stream` -- `request_timeout`: Timeout for the request in **seconds** - -**Returns**: - -File content as an `AsyncIterator[bytes]` - - - -### write - -```python -async def write(path: str, - data: Union[str, bytes, IO], - user: Optional[Username] = None, - request_timeout: Optional[float] = None) -> WriteInfo -``` - -Write content to a file on the path. - -Writing to a file that doesn't exist creates the file. -Writing to a file that already exists overwrites the file. -Writing to a file at path that doesn't exist creates the necessary directories. - -**Arguments**: - -- `path`: Path to the file -- `data`: Data to write to the file, can be a `str`, `bytes`, or `IO`. -- `user`: Run the operation as this user -- `request_timeout`: Timeout for the request in **seconds** - -**Returns**: - -Information about the written file - - - -### write\_files - -```python -async def write_files( - files: List[WriteEntry], - user: Optional[Username] = None, - request_timeout: Optional[float] = None) -> List[WriteInfo] -``` - -Writes multiple files. - -Writes a list of files to the filesystem. -When writing to a file that doesn't exist, the file will get created. -When writing to a file that already exists, the file will get overwritten. -When writing to a file that's in a directory that doesn't exist, you'll get an error. - -**Arguments**: - -- `files`: list of files to write as `WriteEntry` objects, each containing `path` and `data` -- `user`: Run the operation as this user -- `request_timeout`: Timeout for the request - -**Returns**: - -Information about the written files - - - -### list - -```python -async def list(path: str, - depth: Optional[int] = 1, - user: Optional[Username] = None, - request_timeout: Optional[float] = None) -> List[EntryInfo] -``` - -List entries in a directory. - -**Arguments**: - -- `path`: Path to the directory -- `depth`: Depth of the directory to list -- `user`: Run the operation as this user -- `request_timeout`: Timeout for the request in **seconds** - -**Returns**: - -List of entries in the directory - - - -### exists - -```python -async def exists(path: str, - user: Optional[Username] = None, - request_timeout: Optional[float] = None) -> bool -``` - -Check if a file or a directory exists. - -**Arguments**: - -- `path`: Path to a file or a directory -- `user`: Run the operation as this user -- `request_timeout`: Timeout for the request in **seconds** - -**Returns**: - -`True` if the file or directory exists, `False` otherwise - - - -### get\_info - -```python -async def get_info(path: str, - user: Optional[Username] = None, - request_timeout: Optional[float] = None) -> EntryInfo -``` - -Get information about a file or directory. - -**Arguments**: - -- `path`: Path to a file or a directory -- `user`: Run the operation as this user -- `request_timeout`: Timeout for the request in **seconds** - -**Returns**: - -Information about the file or directory like name, type, and path - - - -### remove - -```python -async def remove(path: str, - user: Optional[Username] = None, - request_timeout: Optional[float] = None) -> None -``` - -Remove a file or a directory. - -**Arguments**: - -- `path`: Path to a file or a directory -- `user`: Run the operation as this user -- `request_timeout`: Timeout for the request in **seconds** - - - -### rename - -```python -async def rename(old_path: str, - new_path: str, - user: Optional[Username] = None, - request_timeout: Optional[float] = None) -> EntryInfo -``` - -Rename a file or directory. - -**Arguments**: - -- `old_path`: Path to the file or directory to rename -- `new_path`: New path to the file or directory -- `user`: Run the operation as this user -- `request_timeout`: Timeout for the request in **seconds** - -**Returns**: - -Information about the renamed file or directory - - - -### make\_dir - -```python -async def make_dir(path: str, - user: Optional[Username] = None, - request_timeout: Optional[float] = None) -> bool -``` - -Create a new directory and all directories along the way if needed on the specified path. - -**Arguments**: - -- `path`: Path to a new directory. For example '/dirA/dirB' when creating 'dirB'. -- `user`: Run the operation as this user -- `request_timeout`: Timeout for the request in **seconds** - -**Returns**: - -`True` if the directory was created, `False` if the directory already exists - - - -### watch\_dir - -```python -async def watch_dir(path: str, - on_event: OutputHandler[FilesystemEvent], - on_exit: Optional[OutputHandler[Exception]] = None, - user: Optional[Username] = None, - request_timeout: Optional[float] = None, - timeout: Optional[float] = 60, - recursive: bool = False) -> AsyncWatchHandle -``` - -Watch directory for filesystem events. - -**Arguments**: - -- `path`: Path to a directory to watch -- `on_event`: Callback to call on each event in the directory -- `on_exit`: Callback to call when the watching ends -- `user`: Run the operation as this user -- `request_timeout`: Timeout for the request in **seconds** -- `timeout`: Timeout for the watch operation in **seconds**. Using `0` will not limit the watch time -- `recursive`: Watch directory recursively - -**Returns**: - -`AsyncWatchHandle` object for stopping watching directory - - - - - - -## AsyncSandboxPaginator - -```python -class AsyncSandboxPaginator(SandboxPaginatorBase) -``` - -Paginator for listing sandboxes. - -**Example**: - -```python -paginator = AsyncSandbox.list() - -while paginator.has_next: - sandboxes = await paginator.next_items() - print(sandboxes) -``` - - - -### next\_items - -```python -async def next_items() -> List[SandboxInfo] -``` - -Returns the next page of sandboxes. - -Call this method only if `has_next` is `True`, otherwise it will raise an exception. - -**Returns**: - -List of sandboxes - - - - - - - - - -## SandboxApi - -```python -class SandboxApi(SandboxBase) -``` - - - -### list - -```python -@staticmethod -def list(query: Optional[SandboxQuery] = None, - limit: Optional[int] = None, - next_token: Optional[str] = None, - **opts: Unpack[ApiParams]) -> AsyncSandboxPaginator -``` - -List all running sandboxes. - -**Arguments**: - -- `query`: Filter the list of sandboxes by metadata or state, e.g. `SandboxListQuery(metadata={"key": "value"})` or `SandboxListQuery(state=[SandboxState.RUNNING])` -- `limit`: Maximum number of sandboxes to return per page -- `next_token`: Token for pagination - -**Returns**: - -List of running sandboxes - - - - - - -## Commands - -```python -class Commands() -``` - -Module for executing commands in the sandbox. - - - -### list - -```python -async def list(request_timeout: Optional[float] = None) -> List[ProcessInfo] -``` - -Lists all running commands and PTY sessions. - -**Arguments**: - -- `request_timeout`: Timeout for the request in **seconds** - -**Returns**: - -List of running commands and PTY sessions - - - -### kill - -```python -async def kill(pid: int, request_timeout: Optional[float] = None) -> bool -``` - -Kill a running command specified by its process ID. - -It uses `SIGKILL` signal to kill the command. - -**Arguments**: - -- `pid`: Process ID of the command. You can get the list of processes using `sandbox.commands.list()` -- `request_timeout`: Timeout for the request in **seconds** - -**Returns**: - -`True` if the command was killed, `False` if the command was not found - - - -### send\_stdin - -```python -async def send_stdin(pid: int, - data: str, - request_timeout: Optional[float] = None) -> None -``` - -Send data to command stdin. - -:param pid Process ID of the command. You can get the list of processes using `sandbox.commands.list()`. -:param data: Data to send to the command -:param request_timeout: Timeout for the request in **seconds** - - - - -### run - -```python -@overload -async def run(cmd: str, - background: Union[Literal[False], None] = None, - envs: Optional[Dict[str, str]] = None, - user: Optional[Username] = None, - cwd: Optional[str] = None, - on_stdout: Optional[OutputHandler[Stdout]] = None, - on_stderr: Optional[OutputHandler[Stderr]] = None, - stdin: Optional[bool] = None, - timeout: Optional[float] = 60, - request_timeout: Optional[float] = None) -> CommandResult -``` - -Start a new command and wait until it finishes executing. - -**Arguments**: - -- `cmd`: Command to execute -- `background`: **`False` if the command should be executed in the foreground**, `True` if the command should be executed in the background -- `envs`: Environment variables used for the command -- `user`: User to run the command as -- `cwd`: Working directory to run the command -- `on_stdout`: Callback for command stdout output -- `on_stderr`: Callback for command stderr output -- `stdin`: If `True`, the command will have a stdin stream that you can send data to using `sandbox.commands.send_stdin()` -- `timeout`: Timeout for the command connection in **seconds**. Using `0` will not limit the command connection time -- `request_timeout`: Timeout for the request in **seconds** - -**Returns**: - -`CommandResult` result of the command execution - - - -### run - -```python -@overload -async def run(cmd: str, - background: Literal[True], - envs: Optional[Dict[str, str]] = None, - user: Optional[Username] = None, - cwd: Optional[str] = None, - on_stdout: Optional[OutputHandler[Stdout]] = None, - on_stderr: Optional[OutputHandler[Stderr]] = None, - stdin: Optional[bool] = None, - timeout: Optional[float] = 60, - request_timeout: Optional[float] = None) -> AsyncCommandHandle -``` - -Start a new command and return a handle to interact with it. - -**Arguments**: - -- `cmd`: Command to execute -- `background`: `False` if the command should be executed in the foreground, **`True` if the command should be executed in the background** -- `envs`: Environment variables used for the command -- `user`: User to run the command as -- `cwd`: Working directory to run the command -- `on_stdout`: Callback for command stdout output -- `on_stderr`: Callback for command stderr output -- `stdin`: If `True`, the command will have a stdin stream that you can send data to using `sandbox.commands.send_stdin()` -- `timeout`: Timeout for the command connection in **seconds**. Using `0` will not limit the command connection time -- `request_timeout`: Timeout for the request in **seconds** - -**Returns**: - -`AsyncCommandHandle` handle to interact with the running command - - - -### connect - -```python -async def connect( - pid: int, - timeout: Optional[float] = 60, - request_timeout: Optional[float] = None, - on_stdout: Optional[OutputHandler[Stdout]] = None, - on_stderr: Optional[OutputHandler[Stderr]] = None -) -> AsyncCommandHandle -``` - -Connects to a running command. - -You can use `AsyncCommandHandle.wait()` to wait for the command to finish and get execution results. - -**Arguments**: - -- `pid`: Process ID of the command to connect to. You can get the list of processes using `sandbox.commands.list()` -- `request_timeout`: Request timeout in **seconds** -- `timeout`: Timeout for the command connection in **seconds**. Using `0` will not limit the command connection time -- `on_stdout`: Callback for command stdout output -- `on_stderr`: Callback for command stderr output - -**Returns**: - -`AsyncCommandHandle` handle to interact with the running command - - - - - - -## AsyncCommandHandle - -```python -class AsyncCommandHandle() -``` - -Command execution handle. - -It provides methods for waiting for the command to finish, retrieving stdout/stderr, and killing the command. - - - -### pid - -```python -@property -def pid() -``` - -Command process ID. - - - -### stdout - -```python -@property -def stdout() -``` - -Command stdout output. - - - -### stderr - -```python -@property -def stderr() -``` - -Command stderr output. - - - -### error - -```python -@property -def error() -``` - -Command execution error message. - - - -### exit\_code - -```python -@property -def exit_code() -``` - -Command execution exit code. - -`0` if the command finished successfully. - -It is `None` if the command is still running. - - - -### disconnect - -```python -async def disconnect() -> None -``` - -Disconnects from the command. - -The command is not killed, but SDK stops receiving events from the command. -You can reconnect to the command using `sandbox.commands.connect` method. - - - -### wait - -```python -async def wait() -> CommandResult -``` - -Wait for the command to finish and return the result. - -If the command exits with a non-zero exit code, it throws a `CommandExitException`. - -**Returns**: - -`CommandResult` result of command execution - - - -### kill - -```python -async def kill() -> bool -``` - -Kills the command. - -It uses `SIGKILL` signal to kill the command - -**Returns**: - -`True` if the command was killed successfully, `False` if the command was not found - - - - - - -## Pty - -```python -class Pty() -``` - -Module for interacting with PTYs (pseudo-terminals) in the sandbox. - - - -### kill - -```python -async def kill(pid: int, request_timeout: Optional[float] = None) -> bool -``` - -Kill PTY. - -**Arguments**: - -- `pid`: Process ID of the PTY -- `request_timeout`: Timeout for the request in **seconds** - -**Returns**: - -`true` if the PTY was killed, `false` if the PTY was not found - - - -### send\_stdin - -```python -async def send_stdin(pid: int, - data: bytes, - request_timeout: Optional[float] = None) -> None -``` - -Send input to a PTY. - -**Arguments**: - -- `pid`: Process ID of the PTY -- `data`: Input data to send -- `request_timeout`: Timeout for the request in **seconds** - - - -### create - -```python -async def create( - size: PtySize, - on_data: OutputHandler[PtyOutput], - user: Optional[Username] = None, - cwd: Optional[str] = None, - envs: Optional[Dict[str, str]] = None, - timeout: Optional[float] = 60, - request_timeout: Optional[float] = None) -> AsyncCommandHandle -``` - -Start a new PTY (pseudo-terminal). - -**Arguments**: - -- `size`: Size of the PTY -- `on_data`: Callback to handle PTY data -- `user`: User to use for the PTY -- `cwd`: Working directory for the PTY -- `envs`: Environment variables for the PTY -- `timeout`: Timeout for the PTY in **seconds** -- `request_timeout`: Timeout for the request in **seconds** - -**Returns**: - -Handle to interact with the PTY - - - -### resize - -```python -async def resize(pid: int, - size: PtySize, - request_timeout: Optional[float] = None) -``` - -Resize PTY. - -Call this when the terminal window is resized and the number of columns and rows has changed. - -**Arguments**: - -- `pid`: Process ID of the PTY -- `size`: New size of the PTY -- `request_timeout`: Timeout for the request in **seconds** - - - - - - -## AsyncSandbox - -```python -class AsyncSandbox(SandboxApi) -``` - -E2B cloud sandbox is a secure and isolated cloud environment. - -The sandbox allows you to: -- Access Linux OS -- Create, list, and delete files and directories -- Run commands -- Run isolated code -- Access the internet - -Check docs [here](https://e2b.dev/docs). - -Use the `AsyncSandbox.create()` to create a new sandbox. - -**Example**: - -```python -from e2b import AsyncSandbox - -sandbox = await AsyncSandbox.create() -``` - - - -### files - -```python -@property -def files() -> Filesystem -``` - -Module for interacting with the sandbox filesystem. - - - -### commands - -```python -@property -def commands() -> Commands -``` - -Module for running commands in the sandbox. - - - -### pty - -```python -@property -def pty() -> Pty -``` - -Module for interacting with the sandbox pseudo-terminal. - - - -### \_\_init\_\_ - -```python -def __init__(**opts: Unpack[SandboxOpts]) -``` - -Use `AsyncSandbox.create()` to create a new sandbox instead. - - - -### is\_running - -```python -async def is_running(request_timeout: Optional[float] = None) -> bool -``` - -Check if the sandbox is running. - -**Arguments**: - -- `request_timeout`: Timeout for the request in **seconds** - -**Returns**: - -`True` if the sandbox is running, `False` otherwise -Example -```python -sandbox = await AsyncSandbox.create() -await sandbox.is_running() # Returns True - -await sandbox.kill() -await sandbox.is_running() # Returns False -``` - - - -### create - -```python -@classmethod -async def create(cls, - template: Optional[str] = None, - timeout: Optional[int] = None, - metadata: Optional[Dict[str, str]] = None, - envs: Optional[Dict[str, str]] = None, - secure: bool = True, - allow_internet_access: bool = True, - mcp: Optional[McpServer] = None, - network: Optional[SandboxNetworkOpts] = None, - **opts: Unpack[ApiParams]) -> Self -``` - -Create a new sandbox. - -By default, the sandbox is created from the default `base` sandbox template. - -**Arguments**: - -- `template`: Sandbox template name or ID -- `timeout`: Timeout for the sandbox in **seconds**, default to 300 seconds. The maximum time a sandbox can be kept alive is 24 hours (86_400 seconds) for Pro users and 1 hour (3_600 seconds) for Hobby users. -- `metadata`: Custom metadata for the sandbox -- `envs`: Custom environment variables for the sandbox -- `secure`: Envd is secured with access token and cannot be used without it, defaults to `True`. -- `allow_internet_access`: Allow sandbox to access the internet, defaults to `True`. If set to `False`, it works the same as setting network `deny_out` to `[0.0.0.0/0]`. -- `mcp`: MCP server to enable in the sandbox -- `network`: Sandbox network configuration - -**Returns**: - -A Sandbox instance for the new sandbox -Use this method instead of using the constructor to create a new sandbox. - - - -### connect - -```python -@overload -async def connect(timeout: Optional[int] = None, - **opts: Unpack[ApiParams]) -> Self -``` - -Connect to a sandbox. If the sandbox is paused, it will be automatically resumed. - -Sandbox must be either running or be paused. - -With sandbox ID you can connect to the same sandbox from different places or environments (serverless functions, etc). - -**Arguments**: - -- `timeout`: Timeout for the sandbox in **seconds** -For running sandboxes, the timeout will update only if the new timeout is longer than the existing one. - -**Returns**: - -A running sandbox instance -@example -```python -sandbox = await AsyncSandbox.create() -await sandbox.beta_pause() - -same_sandbox = await sandbox.connect() -``` - - - -### connect - -```python -@overload -@classmethod -async def connect(cls, - sandbox_id: str, - timeout: Optional[int] = None, - **opts: Unpack[ApiParams]) -> Self -``` - -Connect to a sandbox. If the sandbox is paused, it will be automatically resumed. - -Sandbox must be either running or be paused. - -With sandbox ID you can connect to the same sandbox from different places or environments (serverless functions, etc). - -**Arguments**: - -- `sandbox_id`: Sandbox ID -- `timeout`: Timeout for the sandbox in **seconds** -For running sandboxes, the timeout will update only if the new timeout is longer than the existing one. - -**Returns**: - -A running sandbox instance -@example -```python -sandbox = await AsyncSandbox.create() -await AsyncSandbox.beta_pause(sandbox.sandbox_id) - -same_sandbox = await AsyncSandbox.connect(sandbox.sandbox_id)) -``` - - - -### connect - -```python -@class_method_variant("_cls_connect") -async def connect(timeout: Optional[int] = None, - **opts: Unpack[ApiParams]) -> Self -``` - -Connect to a sandbox. If the sandbox is paused, it will be automatically resumed. - -Sandbox must be either running or be paused. - -With sandbox ID you can connect to the same sandbox from different places or environments (serverless functions, etc). - -**Arguments**: - -- `timeout`: Timeout for the sandbox in **seconds** -For running sandboxes, the timeout will update only if the new timeout is longer than the existing one. - -**Returns**: - -A running sandbox instance -@example -```python -sandbox = await AsyncSandbox.create() -await sandbox.beta_pause() - -same_sandbox = await sandbox.connect() -``` - - - -### kill - -```python -@overload -async def kill(**opts: Unpack[ApiParams]) -> bool -``` - -Kill the sandbox. - -**Returns**: - -`True` if the sandbox was killed, `False` if the sandbox was not found - - - -### kill - -```python -@overload -@staticmethod -async def kill(sandbox_id: str, **opts: Unpack[ApiParams]) -> bool -``` - -Kill the sandbox specified by sandbox ID. - -**Arguments**: - -- `sandbox_id`: Sandbox ID - -**Returns**: - -`True` if the sandbox was killed, `False` if the sandbox was not found - - - -### kill - -```python -@class_method_variant("_cls_kill") -async def kill(**opts: Unpack[ApiParams]) -> bool -``` - -Kill the sandbox specified by sandbox ID. - -**Returns**: - -`True` if the sandbox was killed, `False` if the sandbox was not found - - - -### set\_timeout - -```python -@overload -async def set_timeout(timeout: int, **opts: Unpack[ApiParams]) -> None -``` - -Set the timeout of the sandbox. - -After the timeout expires, the sandbox will be automatically killed. -This method can extend or reduce the sandbox timeout set when creating the sandbox or from the last call to `.set_timeout`. - -The maximum time a sandbox can be kept alive is 24 hours (86_400 seconds) for Pro users and 1 hour (3_600 seconds) for Hobby users. - -**Arguments**: - -- `timeout`: Timeout for the sandbox in **seconds** - - - -### set\_timeout - -```python -@overload -@staticmethod -async def set_timeout(sandbox_id: str, timeout: int, - **opts: Unpack[ApiParams]) -> None -``` - -Set the timeout of the specified sandbox. - -After the timeout expires, the sandbox will be automatically killed. -This method can extend or reduce the sandbox timeout set when creating the sandbox or from the last call to `.set_timeout`. - -The maximum time a sandbox can be kept alive is 24 hours (86_400 seconds) for Pro users and 1 hour (3_600 seconds) for Hobby users. - -**Arguments**: - -- `sandbox_id`: Sandbox ID -- `timeout`: Timeout for the sandbox in **seconds** - - - -### set\_timeout - -```python -@class_method_variant("_cls_set_timeout") -async def set_timeout(timeout: int, **opts: Unpack[ApiParams]) -> None -``` - -Set the timeout of the specified sandbox. - -After the timeout expires, the sandbox will be automatically killed. -This method can extend or reduce the sandbox timeout set when creating the sandbox or from the last call to `.set_timeout`. - -The maximum time a sandbox can be kept alive is 24 hours (86_400 seconds) for Pro users and 1 hour (3_600 seconds) for Hobby users. - -**Arguments**: - -- `timeout`: Timeout for the sandbox in **seconds** - - - -### get\_info - -```python -@overload -async def get_info(**opts: Unpack[ApiParams]) -> SandboxInfo -``` - -Get sandbox information like sandbox ID, template, metadata, started at/end at date. - -**Returns**: - -Sandbox info - - - -### get\_info - -```python -@overload -@staticmethod -async def get_info(sandbox_id: str, **opts: Unpack[ApiParams]) -> SandboxInfo -``` - -Get sandbox information like sandbox ID, template, metadata, started at/end at date. - -**Arguments**: - -- `sandbox_id`: Sandbox ID - -**Returns**: - -Sandbox info - - - -### get\_info - -```python -@class_method_variant("_cls_get_info") -async def get_info(**opts: Unpack[ApiParams]) -> SandboxInfo -``` - -Get sandbox information like sandbox ID, template, metadata, started at/end at date. - -**Returns**: - -Sandbox info - - - -### get\_metrics - -```python -@overload -async def get_metrics(start: Optional[datetime.datetime] = None, - end: Optional[datetime.datetime] = None, - **opts: Unpack[ApiParams]) -> List[SandboxMetrics] -``` - -Get the metrics of the current sandbox. - -**Arguments**: - -- `start`: Start time for the metrics, defaults to the start of the sandbox -- `end`: End time for the metrics, defaults to the current time - -**Returns**: - -List of sandbox metrics containing CPU, memory and disk usage information - - - -### get\_metrics - -```python -@overload -@staticmethod -async def get_metrics(sandbox_id: str, - start: Optional[datetime.datetime] = None, - end: Optional[datetime.datetime] = None, - **opts: Unpack[ApiParams]) -> List[SandboxMetrics] -``` - -Get the metrics of the sandbox specified by sandbox ID. - -**Arguments**: - -- `sandbox_id`: Sandbox ID -- `start`: Start time for the metrics, defaults to the start of the sandbox -- `end`: End time for the metrics, defaults to the current time - -**Returns**: - -List of sandbox metrics containing CPU, memory and disk usage information - - - -### get\_metrics - -```python -@class_method_variant("_cls_get_metrics") -async def get_metrics(start: Optional[datetime.datetime] = None, - end: Optional[datetime.datetime] = None, - **opts: Unpack[ApiParams]) -> List[SandboxMetrics] -``` - -Get the metrics of the current sandbox. - -**Arguments**: - -- `start`: Start time for the metrics, defaults to the start of the sandbox -- `end`: End time for the metrics, defaults to the current time - -**Returns**: - -List of sandbox metrics containing CPU, memory and disk usage information - - - -### beta\_create - -```python -@classmethod -async def beta_create(cls, - template: Optional[str] = None, - timeout: Optional[int] = None, - auto_pause: bool = False, - metadata: Optional[Dict[str, str]] = None, - envs: Optional[Dict[str, str]] = None, - secure: bool = True, - allow_internet_access: bool = True, - mcp: Optional[McpServer] = None, - **opts: Unpack[ApiParams]) -> Self -``` - -[BETA] This feature is in beta and may change in the future. - -Create a new sandbox. - -By default, the sandbox is created from the default `base` sandbox template. - -**Arguments**: - -- `template`: Sandbox template name or ID -- `timeout`: Timeout for the sandbox in **seconds**, default to 300 seconds. The maximum time a sandbox can be kept alive is 24 hours (86_400 seconds) for Pro users and 1 hour (3_600 seconds) for Hobby users. -- `auto_pause`: Automatically pause the sandbox after the timeout expires. Defaults to `False`. -- `metadata`: Custom metadata for the sandbox -- `envs`: Custom environment variables for the sandbox -- `secure`: Envd is secured with access token and cannot be used without it, defaults to `True`. -- `allow_internet_access`: Allow sandbox to access the internet, defaults to `True`. -- `mcp`: MCP server to enable in the sandbox - -**Returns**: - -A Sandbox instance for the new sandbox -Use this method instead of using the constructor to create a new sandbox. - - - -### beta\_pause - -```python -@overload -async def beta_pause(**opts: Unpack[ApiParams]) -> None -``` - -[BETA] This feature is in beta and may change in the future. - -Pause the sandbox. - -**Returns**: - -Sandbox ID that can be used to resume the sandbox - - - -### beta\_pause - -```python -@overload -@staticmethod -async def beta_pause(sandbox_id: str, **opts: Unpack[ApiParams]) -> None -``` - -[BETA] This feature is in beta and may change in the future. - -Pause the sandbox specified by sandbox ID. - -**Arguments**: - -- `sandbox_id`: Sandbox ID - -**Returns**: - -Sandbox ID that can be used to resume the sandbox - - - -### beta\_pause - -```python -@class_method_variant("_cls_pause") -async def beta_pause(**opts: Unpack[ApiParams]) -> None -``` - -[BETA] This feature is in beta and may change in the future. - -Pause the sandbox. - -**Returns**: - -Sandbox ID that can be used to resume the sandbox - - - -### get\_mcp\_token - -```python -async def get_mcp_token() -> Optional[str] -``` - -Get the MCP token for the sandbox. - -**Returns**: - -MCP token for the sandbox, or None if MCP is not enabled. diff --git a/docs/sdk-reference/python-sdk/v2.7.0/sandbox_sync.mdx b/docs/sdk-reference/python-sdk/v2.7.0/sandbox_sync.mdx deleted file mode 100644 index 04927a8..0000000 --- a/docs/sdk-reference/python-sdk/v2.7.0/sandbox_sync.mdx +++ /dev/null @@ -1,1343 +0,0 @@ ---- -sidebarTitle: "Sandbox Sync" -mode: "center" ---- - - - - - - -## WatchHandle - -```python -class WatchHandle() -``` - -Handle for watching filesystem events. -It is used to get the latest events that have occurred in the watched directory. - -Use `.stop()` to stop watching the directory. - - - -### stop - -```python -def stop() -``` - -Stop watching the directory. -After you stop the watcher you won't be able to get the events anymore. - - - -### get\_new\_events - -```python -def get_new_events() -> List[FilesystemEvent] -``` - -Get the latest events that have occurred in the watched directory since the last call, or from the beginning of the watching, up until now. - -**Returns**: - -List of filesystem events - - - - - - -## Filesystem - -```python -class Filesystem() -``` - -Module for interacting with the filesystem in the sandbox. - - - -### read - -```python -@overload -def read(path: str, - format: Literal["text"] = "text", - user: Optional[Username] = None, - request_timeout: Optional[float] = None) -> str -``` - -Read file content as a `str`. - -**Arguments**: - -- `path`: Path to the file -- `user`: Run the operation as this user -- `format`: Format of the file content—`text` by default -- `request_timeout`: Timeout for the request in **seconds** - -**Returns**: - -File content as a `str` - - - -### read - -```python -@overload -def read(path: str, - format: Literal["bytes"], - user: Optional[Username] = None, - request_timeout: Optional[float] = None) -> bytearray -``` - -Read file content as a `bytearray`. - -**Arguments**: - -- `path`: Path to the file -- `user`: Run the operation as this user -- `format`: Format of the file content—`bytes` -- `request_timeout`: Timeout for the request in **seconds** - -**Returns**: - -File content as a `bytearray` - - - -### read - -```python -@overload -def read(path: str, - format: Literal["stream"], - user: Optional[Username] = None, - request_timeout: Optional[float] = None) -> Iterator[bytes] -``` - -Read file content as a `Iterator[bytes]`. - -**Arguments**: - -- `path`: Path to the file -- `user`: Run the operation as this user -- `format`: Format of the file content—`stream` -- `request_timeout`: Timeout for the request in **seconds** - -**Returns**: - -File content as an `Iterator[bytes]` - - - -### write - -```python -def write(path: str, - data: Union[str, bytes, IO], - user: Optional[Username] = None, - request_timeout: Optional[float] = None) -> WriteInfo -``` - -Write content to a file on the path. - -Writing to a file that doesn't exist creates the file. -Writing to a file that already exists overwrites the file. -Writing to a file at path that doesn't exist creates the necessary directories. - -**Arguments**: - -- `path`: Path to the file -- `data`: Data to write to the file, can be a `str`, `bytes`, or `IO`. -- `user`: Run the operation as this user -- `request_timeout`: Timeout for the request in **seconds** - -**Returns**: - -Information about the written file - - - -### write\_files - -```python -def write_files(files: List[WriteEntry], - user: Optional[Username] = None, - request_timeout: Optional[float] = None) -> List[WriteInfo] -``` - -Writes a list of files to the filesystem. - -When writing to a file that doesn't exist, the file will get created. -When writing to a file that already exists, the file will get overwritten. -When writing to a file that's in a directory that doesn't exist, you'll get an error. - -**Arguments**: - -- `files`: list of files to write as `WriteEntry` objects, each containing `path` and `data` -- `user`: Run the operation as this user -- `request_timeout`: Timeout for the request - -**Returns**: - -Information about the written files - - - -### list - -```python -def list(path: str, - depth: Optional[int] = 1, - user: Optional[Username] = None, - request_timeout: Optional[float] = None) -> List[EntryInfo] -``` - -List entries in a directory. - -**Arguments**: - -- `path`: Path to the directory -- `depth`: Depth of the directory to list -- `user`: Run the operation as this user -- `request_timeout`: Timeout for the request in **seconds** - -**Returns**: - -List of entries in the directory - - - -### exists - -```python -def exists(path: str, - user: Optional[Username] = None, - request_timeout: Optional[float] = None) -> bool -``` - -Check if a file or a directory exists. - -**Arguments**: - -- `path`: Path to a file or a directory -- `user`: Run the operation as this user -- `request_timeout`: Timeout for the request in **seconds** - -**Returns**: - -`True` if the file or directory exists, `False` otherwise - - - -### get\_info - -```python -def get_info(path: str, - user: Optional[Username] = None, - request_timeout: Optional[float] = None) -> EntryInfo -``` - -Get information about a file or directory. - -**Arguments**: - -- `path`: Path to a file or a directory -- `user`: Run the operation as this user -- `request_timeout`: Timeout for the request in **seconds** - -**Returns**: - -Information about the file or directory like name, type, and path - - - -### remove - -```python -def remove(path: str, - user: Optional[Username] = None, - request_timeout: Optional[float] = None) -> None -``` - -Remove a file or a directory. - -**Arguments**: - -- `path`: Path to a file or a directory -- `user`: Run the operation as this user -- `request_timeout`: Timeout for the request in **seconds** - - - -### rename - -```python -def rename(old_path: str, - new_path: str, - user: Optional[Username] = None, - request_timeout: Optional[float] = None) -> EntryInfo -``` - -Rename a file or directory. - -**Arguments**: - -- `old_path`: Path to the file or directory to rename -- `new_path`: New path to the file or directory -- `user`: Run the operation as this user -- `request_timeout`: Timeout for the request in **seconds** - -**Returns**: - -Information about the renamed file or directory - - - -### make\_dir - -```python -def make_dir(path: str, - user: Optional[Username] = None, - request_timeout: Optional[float] = None) -> bool -``` - -Create a new directory and all directories along the way if needed on the specified path. - -**Arguments**: - -- `path`: Path to a new directory. For example '/dirA/dirB' when creating 'dirB'. -- `user`: Run the operation as this user -- `request_timeout`: Timeout for the request in **seconds** - -**Returns**: - -`True` if the directory was created, `False` if the directory already exists - - - -### watch\_dir - -```python -def watch_dir(path: str, - user: Optional[Username] = None, - request_timeout: Optional[float] = None, - recursive: bool = False) -> WatchHandle -``` - -Watch directory for filesystem events. - -**Arguments**: - -- `path`: Path to a directory to watch -- `user`: Run the operation as this user -- `request_timeout`: Timeout for the request in **seconds** -- `recursive`: Watch directory recursively - -**Returns**: - -`WatchHandle` object for stopping watching directory - - - - - - -## SandboxPaginator - -```python -class SandboxPaginator(SandboxPaginatorBase) -``` - -Paginator for listing sandboxes. - -**Example**: - -```python -paginator = Sandbox.list() - -while paginator.has_next: - sandboxes = paginator.next_items() - print(sandboxes) -``` - - - -### next\_items - -```python -def next_items() -> List[SandboxInfo] -``` - -Returns the next page of sandboxes. - -Call this method only if `has_next` is `True`, otherwise it will raise an exception. - -**Returns**: - -List of sandboxes - - - - - - -## SandboxApi - -```python -class SandboxApi(SandboxBase) -``` - - - -### list - -```python -@staticmethod -def list(query: Optional[SandboxQuery] = None, - limit: Optional[int] = None, - next_token: Optional[str] = None, - **opts: Unpack[ApiParams]) -> SandboxPaginator -``` - -List all running sandboxes. - -**Arguments**: - -- `query`: Filter the list of sandboxes by metadata or state, e.g. `SandboxListQuery(metadata={"key": "value"})` or `SandboxListQuery(state=[SandboxState.RUNNING])` -- `limit`: Maximum number of sandboxes to return per page -- `next_token`: Token for pagination - -**Returns**: - -List of running sandboxes - - - - - - -## Commands - -```python -class Commands() -``` - -Module for executing commands in the sandbox. - - - -### list - -```python -def list(request_timeout: Optional[float] = None) -> List[ProcessInfo] -``` - -Lists all running commands and PTY sessions. - -**Arguments**: - -- `request_timeout`: Timeout for the request in **seconds** - -**Returns**: - -List of running commands and PTY sessions - - - -### kill - -```python -def kill(pid: int, request_timeout: Optional[float] = None) -> bool -``` - -Kills a running command specified by its process ID. - -It uses `SIGKILL` signal to kill the command. - -**Arguments**: - -- `pid`: Process ID of the command. You can get the list of processes using `sandbox.commands.list()` -- `request_timeout`: Timeout for the request in **seconds** - -**Returns**: - -`True` if the command was killed, `False` if the command was not found - - - -### send\_stdin - -```python -def send_stdin(pid: int, data: str, request_timeout: Optional[float] = None) -``` - -Send data to command stdin. - -:param pid Process ID of the command. You can get the list of processes using `sandbox.commands.list()`. -:param data: Data to send to the command -:param request_timeout: Timeout for the request in **seconds** - - - - -### run - -```python -@overload -def run(cmd: str, - background: Union[Literal[False], None] = None, - envs: Optional[Dict[str, str]] = None, - user: Optional[Username] = None, - cwd: Optional[str] = None, - on_stdout: Optional[Callable[[str], None]] = None, - on_stderr: Optional[Callable[[str], None]] = None, - stdin: Optional[bool] = None, - timeout: Optional[float] = 60, - request_timeout: Optional[float] = None) -> CommandResult -``` - -Start a new command and wait until it finishes executing. - -**Arguments**: - -- `cmd`: Command to execute -- `background`: **`False` if the command should be executed in the foreground**, `True` if the command should be executed in the background -- `envs`: Environment variables used for the command -- `user`: User to run the command as -- `cwd`: Working directory to run the command -- `on_stdout`: Callback for command stdout output -- `on_stderr`: Callback for command stderr output -- `stdin`: If `True`, the command will have a stdin stream that you can send data to using `sandbox.commands.send_stdin()` -- `timeout`: Timeout for the command connection in **seconds**. Using `0` will not limit the command connection time -- `request_timeout`: Timeout for the request in **seconds** - -**Returns**: - -`CommandResult` result of the command execution - - - -### run - -```python -@overload -def run(cmd: str, - background: Literal[True], - envs: Optional[Dict[str, str]] = None, - user: Optional[Username] = None, - cwd: Optional[str] = None, - on_stdout: None = None, - on_stderr: None = None, - stdin: Optional[bool] = None, - timeout: Optional[float] = 60, - request_timeout: Optional[float] = None) -> CommandHandle -``` - -Start a new command and return a handle to interact with it. - -**Arguments**: - -- `cmd`: Command to execute -- `background`: `False` if the command should be executed in the foreground, **`True` if the command should be executed in the background** -- `envs`: Environment variables used for the command -- `user`: User to run the command as -- `cwd`: Working directory to run the command -- `stdin`: If `True`, the command will have a stdin stream that you can send data to using `sandbox.commands.send_stdin()` -- `timeout`: Timeout for the command connection in **seconds**. Using `0` will not limit the command connection time -- `request_timeout`: Timeout for the request in **seconds** - -**Returns**: - -`CommandHandle` handle to interact with the running command - - - -### connect - -```python -def connect(pid: int, - timeout: Optional[float] = 60, - request_timeout: Optional[float] = None) -``` - -Connects to a running command. - -You can use `CommandHandle.wait()` to wait for the command to finish and get execution results. - -**Arguments**: - -- `pid`: Process ID of the command to connect to. You can get the list of processes using `sandbox.commands.list()` -- `timeout`: Timeout for the connection in **seconds**. Using `0` will not limit the connection time -- `request_timeout`: Timeout for the request in **seconds** - -**Returns**: - -`CommandHandle` handle to interact with the running command - - - - - - -## CommandHandle - -```python -class CommandHandle() -``` - -Command execution handle. - -It provides methods for waiting for the command to finish, retrieving stdout/stderr, and killing the command. - - - -### pid - -```python -@property -def pid() -``` - -Command process ID. - - - -### \_\_iter\_\_ - -```python -def __iter__() -``` - -Iterate over the command output. - -**Returns**: - -Generator of command outputs - - - -### disconnect - -```python -def disconnect() -> None -``` - -Disconnect from the command. - -The command is not killed, but SDK stops receiving events from the command. -You can reconnect to the command using `sandbox.commands.connect` method. - - - -### wait - -```python -def wait(on_pty: Optional[Callable[[PtyOutput], None]] = None, - on_stdout: Optional[Callable[[str], None]] = None, - on_stderr: Optional[Callable[[str], None]] = None) -> CommandResult -``` - -Wait for the command to finish and returns the result. - -If the command exits with a non-zero exit code, it throws a `CommandExitException`. - -**Arguments**: - -- `on_pty`: Callback for pty output -- `on_stdout`: Callback for stdout output -- `on_stderr`: Callback for stderr output - -**Returns**: - -`CommandResult` result of command execution - - - -### kill - -```python -def kill() -> bool -``` - -Kills the command. - -It uses `SIGKILL` signal to kill the command. - -**Returns**: - -Whether the command was killed successfully - - - - - - -## Pty - -```python -class Pty() -``` - -Module for interacting with PTYs (pseudo-terminals) in the sandbox. - - - -### kill - -```python -def kill(pid: int, request_timeout: Optional[float] = None) -> bool -``` - -Kill PTY. - -**Arguments**: - -- `pid`: Process ID of the PTY -- `request_timeout`: Timeout for the request in **seconds** - -**Returns**: - -`true` if the PTY was killed, `false` if the PTY was not found - - - -### send\_stdin - -```python -def send_stdin(pid: int, - data: bytes, - request_timeout: Optional[float] = None) -> None -``` - -Send input to a PTY. - -**Arguments**: - -- `pid`: Process ID of the PTY -- `data`: Input data to send -- `request_timeout`: Timeout for the request in **seconds** - - - -### create - -```python -def create(size: PtySize, - user: Optional[Username] = None, - cwd: Optional[str] = None, - envs: Optional[Dict[str, str]] = None, - timeout: Optional[float] = 60, - request_timeout: Optional[float] = None) -> CommandHandle -``` - -Start a new PTY (pseudo-terminal). - -**Arguments**: - -- `size`: Size of the PTY -- `user`: User to use for the PTY -- `cwd`: Working directory for the PTY -- `envs`: Environment variables for the PTY -- `timeout`: Timeout for the PTY in **seconds** -- `request_timeout`: Timeout for the request in **seconds** - -**Returns**: - -Handle to interact with the PTY - - - -### resize - -```python -def resize(pid: int, - size: PtySize, - request_timeout: Optional[float] = None) -> None -``` - -Resize PTY. - -Call this when the terminal window is resized and the number of columns and rows has changed. - -**Arguments**: - -- `pid`: Process ID of the PTY -- `size`: New size of the PTY -- `request_timeout`: Timeout for the request in **seconds**s - - - - - - -## Sandbox - -```python -class Sandbox(SandboxApi) -``` - -E2B cloud sandbox is a secure and isolated cloud environment. - -The sandbox allows you to: -- Access Linux OS -- Create, list, and delete files and directories -- Run commands -- Run isolated code -- Access the internet - -Check docs [here](https://e2b.dev/docs). - -Use the `Sandbox.create()` to create a new sandbox. - -**Example**: - -```python -from e2b import Sandbox - -sandbox = Sandbox.create() -``` - - - -### files - -```python -@property -def files() -> Filesystem -``` - -Module for interacting with the sandbox filesystem. - - - -### commands - -```python -@property -def commands() -> Commands -``` - -Module for running commands in the sandbox. - - - -### pty - -```python -@property -def pty() -> Pty -``` - -Module for interacting with the sandbox pseudo-terminal. - - - -### \_\_init\_\_ - -```python -def __init__(**opts: Unpack[SandboxOpts]) -``` - -:deprecated: This constructor is deprecated - -Use `Sandbox.create()` to create a new sandbox instead. - - - -### is\_running - -```python -def is_running(request_timeout: Optional[float] = None) -> bool -``` - -Check if the sandbox is running. - -**Arguments**: - -- `request_timeout`: Timeout for the request in **seconds** - -**Returns**: - -`True` if the sandbox is running, `False` otherwise -Example -```python -sandbox = Sandbox.create() -sandbox.is_running() # Returns True - -sandbox.kill() -sandbox.is_running() # Returns False -``` - - - -### create - -```python -@classmethod -def create(cls, - template: Optional[str] = None, - timeout: Optional[int] = None, - metadata: Optional[Dict[str, str]] = None, - envs: Optional[Dict[str, str]] = None, - secure: bool = True, - allow_internet_access: bool = True, - mcp: Optional[McpServer] = None, - network: Optional[SandboxNetworkOpts] = None, - **opts: Unpack[ApiParams]) -> Self -``` - -Create a new sandbox. - -By default, the sandbox is created from the default `base` sandbox template. - -**Arguments**: - -- `template`: Sandbox template name or ID -- `timeout`: Timeout for the sandbox in **seconds**, default to 300 seconds. The maximum time a sandbox can be kept alive is 24 hours (86_400 seconds) for Pro users and 1 hour (3_600 seconds) for Hobby users. -- `metadata`: Custom metadata for the sandbox -- `envs`: Custom environment variables for the sandbox -- `secure`: Envd is secured with access token and cannot be used without it, defaults to `True`. -- `allow_internet_access`: Allow sandbox to access the internet, defaults to `True`. If set to `False`, it works the same as setting network `deny_out` to `[0.0.0.0/0]`. -- `mcp`: MCP server to enable in the sandbox -- `network`: Sandbox network configuration - -**Returns**: - -A Sandbox instance for the new sandbox -Use this method instead of using the constructor to create a new sandbox. - - - -### connect - -```python -@overload -def connect(timeout: Optional[int] = None, **opts: Unpack[ApiParams]) -> Self -``` - -Connect to a sandbox. If the sandbox is paused, it will be automatically resumed. - -Sandbox must be either running or be paused. - -With sandbox ID you can connect to the same sandbox from different places or environments (serverless functions, etc). - -**Arguments**: - -- `timeout`: Timeout for the sandbox in **seconds** -For running sandboxes, the timeout will update only if the new timeout is longer than the existing one. - -**Returns**: - -A running sandbox instance -@example -```python -sandbox = Sandbox.create() -sandbox.beta_pause() - -same_sandbox = sandbox.connect() - - - -### connect - -```python -@overload -@classmethod -def connect(cls, - sandbox_id: str, - timeout: Optional[int] = None, - **opts: Unpack[ApiParams]) -> Self -``` - -Connect to a sandbox. If the sandbox is paused, it will be automatically resumed. - -Sandbox must be either running or be paused. - -With sandbox ID you can connect to the same sandbox from different places or environments (serverless functions, etc). - -**Arguments**: - -- `sandbox_id`: Sandbox ID -- `timeout`: Timeout for the sandbox in **seconds**. -For running sandboxes, the timeout will update only if the new timeout is longer than the existing one. - -**Returns**: - -A running sandbox instance -@example -```python -sandbox = Sandbox.create() -Sandbox.beta_pause(sandbox.sandbox_id) - -same_sandbox = Sandbox.connect(sandbox.sandbox_id) -``` - - - -### connect - -```python -@class_method_variant("_cls_connect") -def connect(timeout: Optional[int] = None, **opts: Unpack[ApiParams]) -> Self -``` - -Connect to a sandbox. If the sandbox is paused, it will be automatically resumed. - -Sandbox must be either running or be paused. - -With sandbox ID you can connect to the same sandbox from different places or environments (serverless functions, etc). - -**Arguments**: - -- `timeout`: Timeout for the sandbox in **seconds**. -For running sandboxes, the timeout will update only if the new timeout is longer than the existing one. - -**Returns**: - -A running sandbox instance -@example -```python -sandbox = Sandbox.create() -sandbox.beta_pause() - -same_sandbox = sandbox.connect() -``` - - - -### kill - -```python -@overload -def kill(**opts: Unpack[ApiParams]) -> bool -``` - -Kill the sandbox. - -**Returns**: - -`True` if the sandbox was killed, `False` if the sandbox was not found - - - -### kill - -```python -@overload -@staticmethod -def kill(sandbox_id: str, **opts: Unpack[ApiParams]) -> bool -``` - -Kill the sandbox specified by sandbox ID. - -**Arguments**: - -- `sandbox_id`: Sandbox ID - -**Returns**: - -`True` if the sandbox was killed, `False` if the sandbox was not found - - - -### kill - -```python -@class_method_variant("_cls_kill") -def kill(**opts: Unpack[ApiParams]) -> bool -``` - -Kill the sandbox specified by sandbox ID. - -**Returns**: - -`True` if the sandbox was killed, `False` if the sandbox was not found - - - -### set\_timeout - -```python -@overload -def set_timeout(timeout: int, **opts: Unpack[ApiParams]) -> None -``` - -Set the timeout of the sandbox. - -After the timeout expires, the sandbox will be automatically killed. -This method can extend or reduce the sandbox timeout set when creating the sandbox or from the last call to `.set_timeout`. - -The maximum time a sandbox can be kept alive is 24 hours (86_400 seconds) for Pro users and 1 hour (3_600 seconds) for Hobby users. - -**Arguments**: - -- `timeout`: Timeout for the sandbox in **seconds** - - - -### set\_timeout - -```python -@overload -@staticmethod -def set_timeout(sandbox_id: str, timeout: int, - **opts: Unpack[ApiParams]) -> None -``` - -Set the timeout of the sandbox specified by sandbox ID. - -After the timeout expires, the sandbox will be automatically killed. -This method can extend or reduce the sandbox timeout set when creating the sandbox or from the last call to `.set_timeout`. - -The maximum time a sandbox can be kept alive is 24 hours (86_400 seconds) for Pro users and 1 hour (3_600 seconds) for Hobby users. - -**Arguments**: - -- `sandbox_id`: Sandbox ID -- `timeout`: Timeout for the sandbox in **seconds** - - - -### set\_timeout - -```python -@class_method_variant("_cls_set_timeout") -def set_timeout(timeout: int, **opts: Unpack[ApiParams]) -> None -``` - -Set the timeout of the sandbox. - -After the timeout expires, the sandbox will be automatically killed. -This method can extend or reduce the sandbox timeout set when creating the sandbox or from the last call to `.set_timeout`. - -The maximum time a sandbox can be kept alive is 24 hours (86_400 seconds) for Pro users and 1 hour (3_600 seconds) for Hobby users. - -**Arguments**: - -- `timeout`: Timeout for the sandbox in **seconds** - - - -### get\_info - -```python -@overload -def get_info(**opts: Unpack[ApiParams]) -> SandboxInfo -``` - -Get sandbox information like sandbox ID, template, metadata, started at/end at date. - -**Returns**: - -Sandbox info - - - -### get\_info - -```python -@overload -@staticmethod -def get_info(sandbox_id: str, **opts: Unpack[ApiParams]) -> SandboxInfo -``` - -Get sandbox information like sandbox ID, template, metadata, started at/end at date. - -**Arguments**: - -- `sandbox_id`: Sandbox ID - -**Returns**: - -Sandbox info - - - -### get\_info - -```python -@class_method_variant("_cls_get_info") -def get_info(**opts: Unpack[ApiParams]) -> SandboxInfo -``` - -Get sandbox information like sandbox ID, template, metadata, started at/end at date. - -**Returns**: - -Sandbox info - - - -### get\_metrics - -```python -@overload -def get_metrics(start: Optional[datetime.datetime] = None, - end: Optional[datetime.datetime] = None, - **opts: Unpack[ApiParams]) -> List[SandboxMetrics] -``` - -Get the metrics of the current sandbox. - -**Arguments**: - -- `start`: Start time for the metrics, defaults to the start of the sandbox -- `end`: End time for the metrics, defaults to the current time - -**Returns**: - -List of sandbox metrics containing CPU, memory and disk usage information - - - -### get\_metrics - -```python -@overload -@staticmethod -def get_metrics(sandbox_id: str, - start: Optional[datetime.datetime] = None, - end: Optional[datetime.datetime] = None, - **opts: Unpack[ApiParams]) -> List[SandboxMetrics] -``` - -Get the metrics of the sandbox specified by sandbox ID. - -**Arguments**: - -- `sandbox_id`: Sandbox ID -- `start`: Start time for the metrics, defaults to the start of the sandbox -- `end`: End time for the metrics, defaults to the current time - -**Returns**: - -List of sandbox metrics containing CPU, memory and disk usage information - - - -### get\_metrics - -```python -@class_method_variant("_cls_get_metrics") -def get_metrics(start: Optional[datetime.datetime] = None, - end: Optional[datetime.datetime] = None, - **opts: Unpack[ApiParams]) -> List[SandboxMetrics] -``` - -Get the metrics of the sandbox specified by sandbox ID. - -**Arguments**: - -- `start`: Start time for the metrics, defaults to the start of the sandbox -- `end`: End time for the metrics, defaults to the current time - -**Returns**: - -List of sandbox metrics containing CPU, memory and disk usage information - - - -### beta\_create - -```python -@classmethod -def beta_create(cls, - template: Optional[str] = None, - timeout: Optional[int] = None, - auto_pause: bool = False, - metadata: Optional[Dict[str, str]] = None, - envs: Optional[Dict[str, str]] = None, - secure: bool = True, - allow_internet_access: bool = True, - mcp: Optional[McpServer] = None, - **opts: Unpack[ApiParams]) -> Self -``` - -[BETA] This feature is in beta and may change in the future. - -Create a new sandbox. - -By default, the sandbox is created from the default `base` sandbox template. - -**Arguments**: - -- `template`: Sandbox template name or ID -- `timeout`: Timeout for the sandbox in **seconds**, default to 300 seconds. The maximum time a sandbox can be kept alive is 24 hours (86_400 seconds) for Pro users and 1 hour (3_600 seconds) for Hobby users. -- `auto_pause`: Automatically pause the sandbox after the timeout expires. Defaults to `False`. -- `metadata`: Custom metadata for the sandbox -- `envs`: Custom environment variables for the sandbox -- `secure`: Envd is secured with access token and cannot be used without it, defaults to `True`. -- `allow_internet_access`: Allow sandbox to access the internet, defaults to `True`. -- `mcp`: MCP server to enable in the sandbox - -**Returns**: - -A Sandbox instance for the new sandbox -Use this method instead of using the constructor to create a new sandbox. - - - -### beta\_pause - -```python -@overload -def beta_pause(**opts: Unpack[ApiParams]) -> None -``` - -[BETA] This feature is in beta and may change in the future. - -Pause the sandbox. - - - -### beta\_pause - -```python -@overload -@classmethod -def beta_pause(cls, sandbox_id: str, **opts: Unpack[ApiParams]) -> None -``` - -[BETA] This feature is in beta and may change in the future. - -Pause the sandbox specified by sandbox ID. - -**Arguments**: - -- `sandbox_id`: Sandbox ID - - - -### beta\_pause - -```python -@class_method_variant("_cls_pause") -def beta_pause(**opts: Unpack[ApiParams]) -> None -``` - -[BETA] This feature is in beta and may change in the future. - -Pause the sandbox. - -**Returns**: - -Sandbox ID that can be used to resume the sandbox - - - -### get\_mcp\_token - -```python -def get_mcp_token() -> Optional[str] -``` - -Get the MCP token for the sandbox. - -**Returns**: - -MCP token for the sandbox, or None if MCP is not enabled. diff --git a/docs/sdk-reference/python-sdk/v2.7.0/template.mdx b/docs/sdk-reference/python-sdk/v2.7.0/template.mdx deleted file mode 100644 index 9ac3cc8..0000000 --- a/docs/sdk-reference/python-sdk/v2.7.0/template.mdx +++ /dev/null @@ -1,1686 +0,0 @@ ---- -sidebarTitle: "Template" -mode: "center" ---- - - - - - - -## DockerfFileFinalParserInterface - -```python -class DockerfFileFinalParserInterface(Protocol) -``` - -Protocol defining the final interface for Dockerfile parsing callbacks. - - - -## DockerfileParserInterface - -```python -class DockerfileParserInterface(Protocol) -``` - -Protocol defining the interface for Dockerfile parsing callbacks. - - - -### run\_cmd - -```python -def run_cmd(command: Union[str, List[str]], - user: Optional[str] = None) -> "DockerfileParserInterface" -``` - -Handle RUN instruction. - - - -### copy - -```python -def copy(src: Union[str, List[CopyItem]], - dest: Optional[str] = None, - force_upload: Optional[Literal[True]] = None, - resolve_symlinks: Optional[bool] = None, - user: Optional[str] = None, - mode: Optional[int] = None) -> "DockerfileParserInterface" -``` - -Handle COPY instruction. - - - -### set\_workdir - -```python -def set_workdir(workdir: str) -> "DockerfileParserInterface" -``` - -Handle WORKDIR instruction. - - - -### set\_user - -```python -def set_user(user: str) -> "DockerfileParserInterface" -``` - -Handle USER instruction. - - - -### set\_envs - -```python -def set_envs(envs: Dict[str, str]) -> "DockerfileParserInterface" -``` - -Handle ENV instruction. - - - -### set\_start\_cmd - -```python -def set_start_cmd(start_cmd: str, - ready_cmd: str) -> "DockerfFileFinalParserInterface" -``` - -Handle CMD/ENTRYPOINT instruction. - - - -### parse\_dockerfile - -```python -def parse_dockerfile(dockerfile_content_or_path: str, - template_builder: DockerfileParserInterface) -> str -``` - -Parse a Dockerfile and convert it to Template SDK format. - -**Arguments**: - -- `dockerfile_content_or_path`: Either the Dockerfile content as a string, or a path to a Dockerfile file -- `template_builder`: Interface providing template builder methods - -**Raises**: - -- `ValueError`: If the Dockerfile is invalid or unsupported - -**Returns**: - -The base image from the Dockerfile - - - - - - -## InstructionType - -```python -class InstructionType(str, Enum) -``` - -Types of instructions that can be used in a template. - - - -## CopyItem - -```python -class CopyItem(TypedDict) -``` - -Configuration for a single file/directory copy operation. - - - -## Instruction - -```python -class Instruction(TypedDict) -``` - -Represents a single instruction in the template build process. - - - -## GenericDockerRegistry - -```python -class GenericDockerRegistry(TypedDict) -``` - -Configuration for a generic Docker registry with basic authentication. - - - -## AWSRegistry - -```python -class AWSRegistry(TypedDict) -``` - -Configuration for AWS Elastic Container Registry (ECR). - - - -## GCPRegistry - -```python -class GCPRegistry(TypedDict) -``` - -Configuration for Google Container Registry (GCR) or Artifact Registry. - - - -## TemplateType - -```python -class TemplateType(TypedDict) -``` - -Internal representation of a template for the E2B build API. - - - -## BuildInfo - -```python -@dataclass -class BuildInfo() -``` - -Information about a built template. - - - - - - -## LogEntry - -```python -@dataclass -class LogEntry() -``` - -Represents a single log entry from the template build process. - - - -## LogEntryStart - -```python -@dataclass -class LogEntryStart(LogEntry) -``` - -Special log entry indicating the start of a build process. - - - -## LogEntryEnd - -```python -@dataclass -class LogEntryEnd(LogEntry) -``` - -Special log entry indicating the end of a build process. - - - -### TIMER\_UPDATE\_INTERVAL\_MS - -Default minimum log level to display. - - - -### DEFAULT\_LEVEL - -Colored labels for each log level. - - - -### levels - -Numeric ordering of log levels for comparison (lower = less severe). - - - -### set\_interval - -```python -def set_interval(func, interval) -``` - -Returns a stop function that can be called to cancel the interval. - -Similar to JavaScript's setInterval. - -**Arguments**: - -- `func`: Function to execute at each interval -- `interval`: Interval duration in **seconds** - -**Returns**: - -Stop function that can be called to cancel the interval - - - -### default\_build\_logger - -```python -def default_build_logger( - min_level: Optional[LogEntryLevel] = None -) -> Callable[[LogEntry], None] -``` - -Create a default build logger with animated timer display. - -**Arguments**: - -- `min_level`: Minimum log level to display (default: 'info') - -**Returns**: - -Logger function that accepts LogEntry instances -Example -```python -from e2b import Template, default_build_logger - -template = Template().from_python_image() - -``` - - - - -Special step name for the finalization phase of template building. -This is the last step that runs after all user-defined instructions. - - - -### FINALIZE\_STEP\_NAME - -Special step name for the base image phase of template building. -This is the first step that sets up the base image. - - - -### BASE\_STEP\_NAME - -Stack trace depth for capturing caller information. - -Depth levels: -1. TemplateClass -2. Caller method (e.g., copy(), from_image(), etc.) - -This depth is used to determine the original caller's location -for stack traces. - - - -### STACK\_TRACE\_DEPTH - -Default setting for whether to resolve symbolic links when copying files. -When False, symlinks are copied as symlinks rather than following them. - - - - - - -## ReadyCmd - -```python -class ReadyCmd() -``` - -Wrapper class for ready check commands. - - - -### wait\_for\_port - -```python -def wait_for_port(port: int) -``` - -Wait for a port to be listening. - -Uses `ss` command to check if a port is open and listening. - -**Arguments**: - -- `port`: Port number to wait for - -**Returns**: - -ReadyCmd that checks for the port -Example -```python -from e2b import Template, wait_for_port - -template = ( - Template() - .from_python_image() - .set_start_cmd('python -m http.server 8000', wait_for_port(8000)) -) -``` - - - -### wait\_for\_url - -```python -def wait_for_url(url: str, status_code: int = 200) -``` - -Wait for a URL to return a specific HTTP status code. - -Uses `curl` to make HTTP requests and check the response status. - -**Arguments**: - -- `url`: URL to check (e.g., 'http://localhost:3000/health') -- `status_code`: Expected HTTP status code (default: 200) - -**Returns**: - -ReadyCmd that checks the URL -Example -```python -from e2b import Template, wait_for_url - -template = ( - Template() - .from_node_image() - .set_start_cmd('npm start', wait_for_url('http://localhost:3000/health')) -) -``` - - - -### wait\_for\_process - -```python -def wait_for_process(process_name: str) -``` - -Wait for a process with a specific name to be running. - -Uses `pgrep` to check if a process exists. - -**Arguments**: - -- `process_name`: Name of the process to wait for - -**Returns**: - -ReadyCmd that checks for the process -Example -```python -from e2b import Template, wait_for_process - -template = ( - Template() - .from_base_image() - .set_start_cmd('./my-daemon', wait_for_process('my-daemon')) -) -``` - - - -### wait\_for\_file - -```python -def wait_for_file(filename: str) -``` - -Wait for a file to exist. - -Uses shell test command to check file existence. - -**Arguments**: - -- `filename`: Path to the file to wait for - -**Returns**: - -ReadyCmd that checks for the file -Example -```python -from e2b import Template, wait_for_file - -template = ( - Template() - .from_base_image() - .set_start_cmd('./init.sh', wait_for_file('/tmp/ready')) -) -``` - - - -### wait\_for\_timeout - -```python -def wait_for_timeout(timeout: int) -``` - -Wait for a specified timeout before considering the sandbox ready. - -Uses `sleep` command to wait for a fixed duration. - -**Arguments**: - -- `timeout`: Time to wait in **milliseconds** (minimum: 1000ms / 1 second) - -**Returns**: - -ReadyCmd that waits for the specified duration -Example -```python -from e2b import Template, wait_for_timeout - -template = ( - Template() - .from_node_image() - .set_start_cmd('npm start', wait_for_timeout(5000)) # Wait 5 seconds -) -``` - - - - - - -### read\_dockerignore - -```python -def read_dockerignore(context_path: str) -> List[str] -``` - -Read and parse a .dockerignore file. - -**Arguments**: - -- `context_path`: Directory path containing the .dockerignore file - -**Returns**: - -Array of ignore patterns (empty lines and comments are filtered out) - - - -### get\_all\_files\_in\_path - -```python -def get_all_files_in_path(src: str, - context_path: str, - ignore_patterns: List[str], - include_directories: bool = True) -> List[str] -``` - -Get all files for a given path and ignore patterns. - -**Arguments**: - -- `src`: Path to the source directory -- `context_path`: Base directory for resolving relative paths -- `ignore_patterns`: Ignore patterns -- `include_directories`: Whether to include directories - -**Returns**: - -Array of files - - - -### calculate\_files\_hash - -```python -def calculate_files_hash(src: str, dest: str, context_path: str, - ignore_patterns: List[str], resolve_symlinks: bool, - stack_trace: Optional[TracebackType]) -> str -``` - -Calculate a hash of files being copied to detect changes for cache invalidation. - -The hash includes file content, metadata (mode, size), and relative paths. -Note: uid, gid, and mtime are excluded to ensure stable hashes across environments. - -**Arguments**: - -- `src`: Source path pattern for files to copy -- `dest`: Destination path where files will be copied -- `context_path`: Base directory for resolving relative paths -- `ignore_patterns`: Glob patterns to ignore -- `resolve_symlinks`: Whether to resolve symbolic links when hashing -- `stack_trace`: Optional stack trace for error reporting - -**Raises**: - -- `ValueError`: If no files match the source pattern - -**Returns**: - -Hex string hash of all files - - - -### tar\_file\_stream - -```python -def tar_file_stream(file_name: str, file_context_path: str, - ignore_patterns: List[str], - resolve_symlinks: bool) -> io.BytesIO -``` - -Create a tar stream of files matching a pattern. - -**Arguments**: - -- `file_name`: Glob pattern for files to include -- `file_context_path`: Base directory for resolving file paths -- `ignore_patterns`: Ignore patterns -- `resolve_symlinks`: Whether to resolve symbolic links - -**Returns**: - -Tar stream - - - -### strip\_ansi\_escape\_codes - -```python -def strip_ansi_escape_codes(text: str) -> str -``` - -Strip ANSI escape codes from a string. - -Source: https://github.com/chalk/ansi-regex/blob/main/index.js - -**Arguments**: - -- `text`: String with ANSI escape codes - -**Returns**: - -String without ANSI escape codes - - - -### get\_caller\_frame - -```python -def get_caller_frame(depth: int) -> Optional[FrameType] -``` - -Get the caller's stack frame at a specific depth. - -This is used to provide better error messages and debugging information -by tracking where template methods were called from in user code. - -**Arguments**: - -- `depth`: The depth of the stack trace to retrieve - -**Returns**: - -The caller frame, or None if not available - - - -### get\_caller\_directory - -```python -def get_caller_directory(depth: int) -> Optional[str] -``` - -Get the directory of the caller at a specific stack depth. - -This is used to determine the file_context_path when creating a template, -so file paths are resolved relative to the user's template file location. - -**Arguments**: - -- `depth`: The depth of the stack trace - -**Returns**: - -The caller's directory path, or None if not available - - - -### pad\_octal - -```python -def pad_octal(mode: int) -> str -``` - -Convert a numeric file mode to a zero-padded octal string. - -**Arguments**: - -- `mode`: File mode as a number (e.g., 493 for 0o755) - -**Returns**: - -Zero-padded 4-digit octal string (e.g., "0755") -Example -```python -pad_octal(0o755) # Returns "0755" -pad_octal(0o644) # Returns "0644" -``` - - - -### get\_build\_step\_index - -```python -def get_build_step_index(step: str, stack_traces_length: int) -> int -``` - -Get the array index for a build step based on its name. - -Special steps: -- BASE_STEP_NAME: Returns 0 (first step) -- FINALIZE_STEP_NAME: Returns the last index -- Numeric strings: Converted to number - -**Arguments**: - -- `step`: Build step name or number as string -- `stack_traces_length`: Total number of stack traces (used for FINALIZE_STEP_NAME) - -**Returns**: - -Index for the build step - - - -### read\_gcp\_service\_account\_json - -```python -def read_gcp_service_account_json(context_path: str, - path_or_content: Union[str, dict]) -> str -``` - -Read GCP service account JSON from a file or object. - -**Arguments**: - -- `context_path`: Base directory for resolving relative file paths -- `path_or_content`: Either a path to a JSON file or a service account object - -**Returns**: - -Service account JSON as a string - - - - - - -## TemplateBuilder - -```python -class TemplateBuilder() -``` - -Builder class for adding instructions to an E2B template. - -All methods return self to allow method chaining. - - - -### copy - -```python -def copy(src: Union[Union[str, Path], List[Union[str, Path]]], - dest: Union[str, Path], - force_upload: Optional[Literal[True]] = None, - user: Optional[str] = None, - mode: Optional[int] = None, - resolve_symlinks: Optional[bool] = None) -> "TemplateBuilder" -``` - -Copy files or directories from the local filesystem into the template. - -**Arguments**: - -- `src`: Source file(s) or directory path(s) to copy -- `dest`: Destination path in the template -- `force_upload`: Force upload even if files are cached -- `user`: User and optionally group (user:group) to own the files -- `mode`: File permissions in octal format (e.g., 0o755) -- `resolve_symlinks`: Whether to resolve symlinks - -**Returns**: - -`TemplateBuilder` class -Example -```python -template.copy('requirements.txt', '/home/user/') -template.copy(['app.py', 'config.py'], '/app/', mode=0o755) -``` - - - -### copy\_items - -```python -def copy_items(items: List[CopyItem]) -> "TemplateBuilder" -``` - -Copy multiple files or directories using a list of copy items. - -**Arguments**: - -- `items`: List of CopyItem dictionaries with src, dest, and optional parameters - -**Returns**: - -`TemplateBuilder` class -Example -```python -template.copy_items([ - {'src': 'app.py', 'dest': '/app/'}, - {'src': 'config.py', 'dest': '/app/', 'mode': 0o644} -]) -``` - - - -### remove - -```python -def remove(path: Union[Union[str, Path], List[Union[str, Path]]], - force: bool = False, - recursive: bool = False, - user: Optional[str] = None) -> "TemplateBuilder" -``` - -Remove files or directories in the template. - -**Arguments**: - -- `path`: File(s) or directory path(s) to remove -- `force`: Force removal without prompting -- `recursive`: Remove directories recursively -- `user`: User to run the command as - -**Returns**: - -`TemplateBuilder` class -Example -```python -template.remove('/tmp/cache', recursive=True, force=True) -template.remove('/tmp/cache', recursive=True, force=True, user='root') -``` - - - -### rename - -```python -def rename(src: Union[str, Path], - dest: Union[str, Path], - force: bool = False, - user: Optional[str] = None) -> "TemplateBuilder" -``` - -Rename or move a file or directory in the template. - -**Arguments**: - -- `src`: Source path -- `dest`: Destination path -- `force`: Force rename without prompting -- `user`: User to run the command as - -**Returns**: - -`TemplateBuilder` class -Example -```python -template.rename('/tmp/old.txt', '/tmp/new.txt') -template.rename('/tmp/old.txt', '/tmp/new.txt', user='root') -``` - - - -### make\_dir - -```python -def make_dir(path: Union[Union[str, Path], List[Union[str, Path]]], - mode: Optional[int] = None, - user: Optional[str] = None) -> "TemplateBuilder" -``` - -Create directory(ies) in the template. - -**Arguments**: - -- `path`: Directory path(s) to create -- `mode`: Directory permissions in octal format (e.g., 0o755) -- `user`: User to run the command as - -**Returns**: - -`TemplateBuilder` class -Example -```python -template.make_dir('/app/data', mode=0o755) -template.make_dir(['/app/logs', '/app/cache']) -template.make_dir('/app/data', mode=0o755, user='root') -``` - - - -### make\_symlink - -```python -def make_symlink(src: Union[str, Path], - dest: Union[str, Path], - user: Optional[str] = None, - force: bool = False) -> "TemplateBuilder" -``` - -Create a symbolic link in the template. - -**Arguments**: - -- `src`: Source path (target of the symlink) -- `dest`: Destination path (location of the symlink) -- `user`: User to run the command as -- `force`: Force symlink without prompting - -**Returns**: - -`TemplateBuilder` class -Example -```python -template.make_symlink('/usr/bin/python3', '/usr/bin/python') -template.make_symlink('/usr/bin/python3', '/usr/bin/python', user='root') -template.make_symlink('/usr/bin/python3', '/usr/bin/python', force=True) -``` - - - -### run\_cmd - -```python -def run_cmd(command: Union[str, List[str]], - user: Optional[str] = None) -> "TemplateBuilder" -``` - -Run a shell command during template build. - -**Arguments**: - -- `command`: Command string or list of commands to run (joined with &&) -- `user`: User to run the command as - -**Returns**: - -`TemplateBuilder` class -Example -```python -template.run_cmd('apt-get update') -template.run_cmd(['pip install numpy', 'pip install pandas']) -template.run_cmd('apt-get install vim', user='root') -``` - - - -### set\_workdir - -```python -def set_workdir(workdir: Union[str, Path]) -> "TemplateBuilder" -``` - -Set the working directory for subsequent commands in the template. - -**Arguments**: - -- `workdir`: Path to set as the working directory - -**Returns**: - -`TemplateBuilder` class -Example -```python -template.set_workdir('/app') -``` - - - -### set\_user - -```python -def set_user(user: str) -> "TemplateBuilder" -``` - -Set the user for subsequent commands in the template. - -**Arguments**: - -- `user`: Username to set - -**Returns**: - -`TemplateBuilder` class -Example -```python -template.set_user('root') -``` - - - -### pip\_install - -```python -def pip_install(packages: Optional[Union[str, List[str]]] = None, - g: bool = True) -> "TemplateBuilder" -``` - -Install Python packages using pip. - -**Arguments**: - -- `packages`: Package name(s) to install. If None, runs 'pip install .' in the current directory -- `g`: Install packages globally (default: True). If False, installs for user only - -**Returns**: - -`TemplateBuilder` class -Example -```python -template.pip_install('numpy') -template.pip_install(['pandas', 'scikit-learn']) -template.pip_install('numpy', g=False) # Install for user only -template.pip_install() # Installs from current directory -``` - - - -### npm\_install - -```python -def npm_install(packages: Optional[Union[str, List[str]]] = None, - g: Optional[bool] = False, - dev: Optional[bool] = False) -> "TemplateBuilder" -``` - -Install Node.js packages using npm. - -**Arguments**: - -- `packages`: Package name(s) to install. If None, installs from package.json -- `g`: Install packages globally -- `dev`: Install packages as dev dependencies - -**Returns**: - -`TemplateBuilder` class -Example -```python -template.npm_install('express') -template.npm_install(['lodash', 'axios']) -template.npm_install('typescript', g=True) -template.npm_install() # Installs from package.json -``` - - - -### bun\_install - -```python -def bun_install(packages: Optional[Union[str, List[str]]] = None, - g: Optional[bool] = False, - dev: Optional[bool] = False) -> "TemplateBuilder" -``` - -Install Bun packages using bun. - -**Arguments**: - -- `packages`: Package name(s) to install. If None, installs from package.json -- `g`: Install packages globally -- `dev`: Install packages as dev dependencies - -**Returns**: - -`TemplateBuilder` class -Example -```python -template.bun_install('express') -template.bun_install(['lodash', 'axios']) -template.bun_install('tsx', g=True) -template.bun_install('typescript', dev=True) -template.bun_install() // Installs from package.json -``` - - - -### apt\_install - -```python -def apt_install(packages: Union[str, List[str]], - no_install_recommends: bool = False) -> "TemplateBuilder" -``` - -Install system packages using apt-get. - -**Arguments**: - -- `packages`: Package name(s) to install -- `no_install_recommends`: Whether to install recommended packages - -**Returns**: - -`TemplateBuilder` class -Example -```python -template.apt_install('vim') -template.apt_install(['git', 'curl', 'wget']) -``` - - - -### add\_mcp\_server - -```python -def add_mcp_server(servers: Union[str, List[str]]) -> "TemplateBuilder" -``` - -Install MCP servers using mcp-gateway. - -Note: Requires a base image with mcp-gateway pre-installed (e.g., mcp-gateway). - -**Arguments**: - -- `servers`: MCP server name(s) - -**Returns**: - -`TemplateBuilder` class -Example -```python -template.add_mcp_server('exa') -template.add_mcp_server(['brave', 'firecrawl', 'duckduckgo']) -``` - - - -### git\_clone - -```python -def git_clone(url: str, - path: Optional[Union[str, Path]] = None, - branch: Optional[str] = None, - depth: Optional[int] = None, - user: Optional[str] = None) -> "TemplateBuilder" -``` - -Clone a git repository into the template. - -**Arguments**: - -- `url`: Git repository URL -- `path`: Destination path for the clone -- `branch`: Branch to clone -- `depth`: Clone depth for shallow clones -- `user`: User to run the command as - -**Returns**: - -`TemplateBuilder` class -Example -```python -template.git_clone('https://github.com/user/repo.git', '/app/repo') -template.git_clone('https://github.com/user/repo.git', branch='main', depth=1) -template.git_clone('https://github.com/user/repo.git', '/app/repo', user='root') -``` - - - -### beta\_dev\_container\_prebuild - -```python -def beta_dev_container_prebuild( - devcontainer_directory: Union[str, Path]) -> "TemplateBuilder" -``` - -Prebuild a devcontainer from the specified directory during the build process. - -**Arguments**: - -- `devcontainer_directory`: Path to the devcontainer directory - -**Returns**: - -`TemplateBuilder` class -Example -```python -template.git_clone('https://myrepo.com/project.git', '/my-devcontainer') -template.beta_dev_container_prebuild('/my-devcontainer') -``` - - - -### beta\_set\_dev\_container\_start - -```python -def beta_set_dev_container_start( - devcontainer_directory: Union[str, Path]) -> "TemplateFinal" -``` - -Start a devcontainer from the specified directory and set it as the start command. - -This method returns `TemplateFinal`, which means it must be the last method in the chain. - -**Arguments**: - -- `devcontainer_directory`: Path to the devcontainer directory - -**Returns**: - -`TemplateFinal` class -Example -```python -template.git_clone('https://myrepo.com/project.git', '/my-devcontainer') -template.beta_set_devcontainer_start('/my-devcontainer') - -template.git_clone('https://myrepo.com/project.git', '/my-devcontainer') -template.beta_dev_container_prebuild('/my-devcontainer') -template.beta_set_dev_container_start('/my-devcontainer') -``` - - - -### set\_envs - -```python -def set_envs(envs: Dict[str, str]) -> "TemplateBuilder" -``` - -Set environment variables in the template. - -**Arguments**: - -- `envs`: Dictionary of environment variable names and values - -**Returns**: - -`TemplateBuilder` class -Example -```python -template.set_envs({'NODE_ENV': 'production', 'PORT': '8080'}) -``` - - - -### skip\_cache - -```python -def skip_cache() -> "TemplateBuilder" -``` - -Skip cache for all subsequent build instructions from this point. - -Call this before any instruction to force it and all following layers -to be rebuilt, ignoring any cached layers. - -**Returns**: - -`TemplateBuilder` class -Example -```python -template.skip_cache().run_cmd('apt-get update') -``` - - - -### set\_start\_cmd - -```python -def set_start_cmd(start_cmd: str, - ready_cmd: Union[str, ReadyCmd]) -> "TemplateFinal" -``` - -Set the command to start when the sandbox launches and the ready check command. - -**Arguments**: - -- `start_cmd`: Command to run when the sandbox starts -- `ready_cmd`: Command or ReadyCmd to check if the sandbox is ready - -**Returns**: - -`TemplateFinal` class -Example -```python -template.set_start_cmd( - 'python app.py', - 'curl http://localhost:8000/health' -) - -from e2b import wait_for_port, wait_for_url - -template.set_start_cmd( - 'python -m http.server 8000', - wait_for_port(8000) -) - -template.set_start_cmd( - 'npm start', - wait_for_url('http://localhost:3000/health', 200) -) -``` - - - -### set\_ready\_cmd - -```python -def set_ready_cmd(ready_cmd: Union[str, ReadyCmd]) -> "TemplateFinal" -``` - -Set the command to check if the sandbox is ready. - -**Arguments**: - -- `ready_cmd`: Command or ReadyCmd to check if the sandbox is ready - -**Returns**: - -`TemplateFinal` class -Example -```python -template.set_ready_cmd('curl http://localhost:8000/health') - -from e2b import wait_for_port, wait_for_file, wait_for_process - -template.set_ready_cmd(wait_for_port(3000)) - -template.set_ready_cmd(wait_for_file('/tmp/ready')) - -template.set_ready_cmd(wait_for_process('nginx')) -``` - - - -## TemplateFinal - -```python -class TemplateFinal() -``` - -Final template state after start/ready commands are set. - - - -## TemplateBase - -```python -class TemplateBase() -``` - -Base class for building E2B sandbox templates. - - - -### \_\_init\_\_ - -```python -def __init__(file_context_path: Optional[Union[str, Path]] = None, - file_ignore_patterns: Optional[List[str]] = None) -``` - -Create a new template builder instance. - -**Arguments**: - -- `file_context_path`: Base path for resolving relative file paths in copy operations -- `file_ignore_patterns`: List of glob patterns to ignore when copying files - - - -### skip\_cache - -```python -def skip_cache() -> "TemplateBase" -``` - -Skip cache for all subsequent build instructions from this point. - -**Returns**: - -`TemplateBase` class -Example -```python -template.skip_cache().from_python_image('3.11') -``` - - - -### from\_debian\_image - -```python -def from_debian_image(variant: str = "stable") -> TemplateBuilder -``` - -Start template from a Debian base image. - -**Arguments**: - -- `variant`: Debian image variant - -**Returns**: - -`TemplateBuilder` class -Example -```python -Template().from_debian_image('bookworm') -``` - - - -### from\_ubuntu\_image - -```python -def from_ubuntu_image(variant: str = "latest") -> TemplateBuilder -``` - -Start template from an Ubuntu base image. - -**Arguments**: - -- `variant`: Ubuntu image variant (default: 'latest') - -**Returns**: - -`TemplateBuilder` class -Example -```python -Template().from_ubuntu_image('24.04') -``` - - - -### from\_python\_image - -```python -def from_python_image(version: str = "3") -> TemplateBuilder -``` - -Start template from a Python base image. - -**Arguments**: - -- `version`: Python version (default: '3') - -**Returns**: - -`TemplateBuilder` class -Example -```python -Template().from_python_image('3') -``` - - - -### from\_node\_image - -```python -def from_node_image(variant: str = "lts") -> TemplateBuilder -``` - -Start template from a Node.js base image. - -**Arguments**: - -- `variant`: Node.js image variant (default: 'lts') - -**Returns**: - -`TemplateBuilder` class -Example -```python -Template().from_node_image('24') -``` - - - -### from\_bun\_image - -```python -def from_bun_image(variant: str = "latest") -> TemplateBuilder -``` - -Start template from a Bun base image. - -**Arguments**: - -- `variant`: Bun image variant (default: 'latest') - -**Returns**: - -`TemplateBuilder` class - - - -### from\_base\_image - -```python -def from_base_image() -> TemplateBuilder -``` - -Start template from the E2B base image (e2bdev/base:latest). - -**Returns**: - -`TemplateBuilder` class -Example -```python -Template().from_base_image() -``` - - - -### from\_image - -```python -def from_image(image: str, - username: Optional[str] = None, - password: Optional[str] = None) -> TemplateBuilder -``` - -Start template from a Docker image. - -**Arguments**: - -- `image`: Docker image name (e.g., 'ubuntu:24.04') -- `username`: Username for private registry authentication -- `password`: Password for private registry authentication - -**Returns**: - -`TemplateBuilder` class -Example -```python -Template().from_image('python:3') - -Template().from_image('myregistry.com/myimage:latest', username='user', password='pass') -``` - - - -### from\_template - -```python -def from_template(template: str) -> TemplateBuilder -``` - -Start template from an existing E2B template. - -**Arguments**: - -- `template`: E2B template ID or alias - -**Returns**: - -`TemplateBuilder` class -Example -```python -Template().from_template('my-base-template') -``` - - - -### from\_dockerfile - -```python -def from_dockerfile(dockerfile_content_or_path: str) -> TemplateBuilder -``` - -Parse a Dockerfile and convert it to Template SDK format. - -**Arguments**: - -- `dockerfile_content_or_path`: Either the Dockerfile content as a string, or a path to a Dockerfile file - -**Returns**: - -`TemplateBuilder` class -Example -```python -Template().from_dockerfile('Dockerfile') -Template().from_dockerfile('FROM python:3\nRUN pip install numpy') -``` - - - -### from\_aws\_registry - -```python -def from_aws_registry(image: str, access_key_id: str, secret_access_key: str, - region: str) -> TemplateBuilder -``` - -Start template from an AWS ECR registry image. - -**Arguments**: - -- `image`: Docker image name from AWS ECR -- `access_key_id`: AWS access key ID -- `secret_access_key`: AWS secret access key -- `region`: AWS region - -**Returns**: - -`TemplateBuilder` class -Example -```python -Template().from_aws_registry( - '123456789.dkr.ecr.us-west-2.amazonaws.com/myimage:latest', - access_key_id='AKIA...', - secret_access_key='...', - region='us-west-2' -) -``` - - - -### from\_gcp\_registry - -```python -def from_gcp_registry( - image: str, service_account_json: Union[str, dict]) -> TemplateBuilder -``` - -Start template from a GCP Artifact Registry or Container Registry image. - -**Arguments**: - -- `image`: Docker image name from GCP registry -- `service_account_json`: Service account JSON string, dict, or path to JSON file - -**Returns**: - -`TemplateBuilder` class -Example -```python -Template().from_gcp_registry( - 'gcr.io/myproject/myimage:latest', - service_account_json='path/to/service-account.json' -) -``` - - - -### to\_json - -```python -@staticmethod -def to_json(template: "TemplateClass") -> str -``` - -Convert a template to JSON representation. - -**Arguments**: - -- `template`: The template to convert (TemplateBuilder or TemplateFinal instance) - -**Returns**: - -JSON string representation of the template -Example -```python -template = Template().from_python_image('3').copy('app.py', '/app/') -json_str = TemplateBase.to_json(template) -``` - - - -### to\_dockerfile - -```python -@staticmethod -def to_dockerfile(template: "TemplateClass") -> str -``` - -Convert a template to Dockerfile format. - -Note: Templates based on other E2B templates cannot be converted to Dockerfile. - -**Arguments**: - -- `template`: The template to convert (TemplateBuilder or TemplateFinal instance) - -**Raises**: - -- `ValueError`: If the template is based on another E2B template or has no base image -Example -```python -template = Template().from_python_image('3').copy('app.py', '/app/') -dockerfile = TemplateBase.to_dockerfile(template) -``` - -**Returns**: - -Dockerfile string representation diff --git a/docs/sdk-reference/python-sdk/v2.7.0/template_async.mdx b/docs/sdk-reference/python-sdk/v2.7.0/template_async.mdx deleted file mode 100644 index 950d066..0000000 --- a/docs/sdk-reference/python-sdk/v2.7.0/template_async.mdx +++ /dev/null @@ -1,150 +0,0 @@ ---- -sidebarTitle: "Template Async" -mode: "center" ---- - - - - - - - - - -## AsyncTemplate - -```python -class AsyncTemplate(TemplateBase) -``` - -Asynchronous template builder for E2B sandboxes. - - - -### build - -```python -@staticmethod -async def build(template: TemplateClass, - alias: str, - cpu_count: int = 2, - memory_mb: int = 1024, - skip_cache: bool = False, - on_build_logs: Optional[Callable[[LogEntry], None]] = None, - api_key: Optional[str] = None, - domain: Optional[str] = None) -> BuildInfo -``` - -Build and deploy a template to E2B infrastructure. - -**Arguments**: - -- `template`: The template to build -- `alias`: Alias name for the template -- `cpu_count`: Number of CPUs allocated to the sandbox -- `memory_mb`: Amount of memory in MB allocated to the sandbox -- `skip_cache`: If True, forces a complete rebuild ignoring cache -- `on_build_logs`: Callback function to receive build logs during the build process -- `api_key`: E2B API key for authentication -- `domain`: Domain of the E2B API -Example -```python -from e2b import AsyncTemplate - -template = ( - AsyncTemplate() - .from_python_image('3') - .copy('requirements.txt', '/home/user/') - .run_cmd('pip install -r /home/user/requirements.txt') -) - -await AsyncTemplate.build( - template, - alias='my-python-env', - cpu_count=2, - memory_mb=1024 -) -``` - - - -### build\_in\_background - -```python -@staticmethod -async def build_in_background(template: TemplateClass, - alias: str, - cpu_count: int = 2, - memory_mb: int = 1024, - skip_cache: bool = False, - on_build_logs: Optional[Callable[[LogEntry], - None]] = None, - api_key: Optional[str] = None, - domain: Optional[str] = None) -> BuildInfo -``` - -Build and deploy a template to E2B infrastructure without waiting for completion. - -**Arguments**: - -- `template`: The template to build -- `alias`: Alias name for the template -- `cpu_count`: Number of CPUs allocated to the sandbox -- `memory_mb`: Amount of memory in MB allocated to the sandbox -- `skip_cache`: If True, forces a complete rebuild ignoring cache -- `api_key`: E2B API key for authentication -- `domain`: Domain of the E2B API - -**Returns**: - -BuildInfo containing the template ID and build ID -Example -```python -from e2b import AsyncTemplate - -template = ( - AsyncTemplate() - .from_python_image('3') - .run_cmd('echo "test"') - .set_start_cmd('echo "Hello"', 'sleep 1') -) - -build_info = await AsyncTemplate.build_in_background( - template, - alias='my-python-env', - cpu_count=2, - memory_mb=1024 -) -``` - - - -### get\_build\_status - -```python -@staticmethod -async def get_build_status(build_info: BuildInfo, - logs_offset: int = 0, - api_key: Optional[str] = None, - domain: Optional[str] = None) -``` - -Get the status of a build. - -**Arguments**: - -- `build_info`: Build identifiers returned from build_in_background -- `logs_offset`: Offset for fetching logs -- `api_key`: E2B API key for authentication -- `domain`: Domain of the E2B API - -**Returns**: - -TemplateBuild containing the build status and logs -Example -```python -from e2b import AsyncTemplate - -build_info = await AsyncTemplate.build_in_background(template, alias='my-template') -status = await AsyncTemplate.get_build_status(build_info, logs_offset=0) -``` diff --git a/docs/sdk-reference/python-sdk/v2.7.0/template_sync.mdx b/docs/sdk-reference/python-sdk/v2.7.0/template_sync.mdx deleted file mode 100644 index 6387438..0000000 --- a/docs/sdk-reference/python-sdk/v2.7.0/template_sync.mdx +++ /dev/null @@ -1,150 +0,0 @@ ---- -sidebarTitle: "Template Sync" -mode: "center" ---- - - - - - - - - - -## Template - -```python -class Template(TemplateBase) -``` - -Synchronous template builder for E2B sandboxes. - - - -### build - -```python -@staticmethod -def build(template: TemplateClass, - alias: str, - cpu_count: int = 2, - memory_mb: int = 1024, - skip_cache: bool = False, - on_build_logs: Optional[Callable[[LogEntry], None]] = None, - api_key: Optional[str] = None, - domain: Optional[str] = None) -> BuildInfo -``` - -Build and deploy a template to E2B infrastructure. - -**Arguments**: - -- `template`: The template to build -- `alias`: Alias name for the template -- `cpu_count`: Number of CPUs allocated to the sandbox -- `memory_mb`: Amount of memory in MB allocated to the sandbox -- `skip_cache`: If True, forces a complete rebuild ignoring cache -- `on_build_logs`: Callback function to receive build logs during the build process -- `api_key`: E2B API key for authentication -- `domain`: Domain of the E2B API -Example -```python -from e2b import Template - -template = ( - Template() - .from_python_image('3') - .copy('requirements.txt', '/home/user/') - .run_cmd('pip install -r /home/user/requirements.txt') -) - -Template.build( - template, - alias='my-python-env', - cpu_count=2, - memory_mb=1024 -) -``` - - - -### build\_in\_background - -```python -@staticmethod -def build_in_background(template: TemplateClass, - alias: str, - cpu_count: int = 2, - memory_mb: int = 1024, - skip_cache: bool = False, - on_build_logs: Optional[Callable[[LogEntry], - None]] = None, - api_key: Optional[str] = None, - domain: Optional[str] = None) -> BuildInfo -``` - -Build and deploy a template to E2B infrastructure without waiting for completion. - -**Arguments**: - -- `template`: The template to build -- `alias`: Alias name for the template -- `cpu_count`: Number of CPUs allocated to the sandbox -- `memory_mb`: Amount of memory in MB allocated to the sandbox -- `skip_cache`: If True, forces a complete rebuild ignoring cache -- `api_key`: E2B API key for authentication -- `domain`: Domain of the E2B API - -**Returns**: - -BuildInfo containing the template ID and build ID -Example -```python -from e2b import Template - -template = ( - Template() - .from_python_image('3') - .run_cmd('echo "test"') - .set_start_cmd('echo "Hello"', 'sleep 1') -) - -build_info = Template.build_in_background( - template, - alias='my-python-env', - cpu_count=2, - memory_mb=1024 -) -``` - - - -### get\_build\_status - -```python -@staticmethod -def get_build_status(build_info: BuildInfo, - logs_offset: int = 0, - api_key: Optional[str] = None, - domain: Optional[str] = None) -``` - -Get the status of a build. - -**Arguments**: - -- `build_info`: Build identifiers returned from build_in_background -- `logs_offset`: Offset for fetching logs -- `api_key`: E2B API key for authentication -- `domain`: Domain of the E2B API - -**Returns**: - -TemplateBuild containing the build status and logs -Example -```python -from e2b import Template - -build_info = Template.build_in_background(template, alias='my-template') -status = Template.get_build_status(build_info, logs_offset=0) -``` diff --git a/docs/sdk-reference/python-sdk/v2.8.0/exceptions.mdx b/docs/sdk-reference/python-sdk/v2.8.0/exceptions.mdx deleted file mode 100644 index d66f786..0000000 --- a/docs/sdk-reference/python-sdk/v2.8.0/exceptions.mdx +++ /dev/null @@ -1,117 +0,0 @@ ---- -sidebarTitle: "Exceptions" -mode: "center" ---- - - - - - - -## SandboxException - -```python -class SandboxException(Exception) -``` - -Base class for all sandbox errors. - -Raised when a general sandbox exception occurs. - - - -## TimeoutException - -```python -class TimeoutException(SandboxException) -``` - -Raised when a timeout occurs. - -The `unavailable` exception type is caused by sandbox timeout. - -The `canceled` exception type is caused by exceeding request timeout. - -The `deadline_exceeded` exception type is caused by exceeding the timeout for process, watch, etc. - -The `unknown` exception type is sometimes caused by the sandbox timeout when the request is not processed correctly. - - - -## InvalidArgumentException - -```python -class InvalidArgumentException(SandboxException) -``` - -Raised when an invalid argument is provided. - - - -## NotEnoughSpaceException - -```python -class NotEnoughSpaceException(SandboxException) -``` - -Raised when there is not enough disk space. - - - -## NotFoundException - -```python -class NotFoundException(SandboxException) -``` - -Raised when a resource is not found. - - - -## AuthenticationException - -```python -class AuthenticationException(Exception) -``` - -Raised when authentication fails. - - - -## TemplateException - -```python -class TemplateException(SandboxException) -``` - -Exception raised when the template uses old envd version. It isn't compatible with the new SDK. - - - -## RateLimitException - -```python -class RateLimitException(SandboxException) -``` - -Raised when the API rate limit is exceeded. - - - -## BuildException - -```python -class BuildException(Exception) -``` - -Raised when the build fails. - - - -## FileUploadException - -```python -class FileUploadException(BuildException) -``` - -Raised when the file upload fails. diff --git a/docs/sdk-reference/python-sdk/v2.8.0/logger.mdx b/docs/sdk-reference/python-sdk/v2.8.0/logger.mdx deleted file mode 100644 index 9fa3b18..0000000 --- a/docs/sdk-reference/python-sdk/v2.8.0/logger.mdx +++ /dev/null @@ -1,106 +0,0 @@ ---- -sidebarTitle: "Logger" -mode: "center" ---- - - - - - - -## LogEntry - -```python -@dataclass -class LogEntry() -``` - -Represents a single log entry from the template build process. - - - -## LogEntryStart - -```python -@dataclass -class LogEntryStart(LogEntry) -``` - -Special log entry indicating the start of a build process. - - - -## LogEntryEnd - -```python -@dataclass -class LogEntryEnd(LogEntry) -``` - -Special log entry indicating the end of a build process. - - - -### TIMER\_UPDATE\_INTERVAL\_MS - -Default minimum log level to display. - - - -### DEFAULT\_LEVEL - -Colored labels for each log level. - - - -### levels - -Numeric ordering of log levels for comparison (lower = less severe). - - - -### set\_interval - -```python -def set_interval(func, interval) -``` - -Returns a stop function that can be called to cancel the interval. - -Similar to JavaScript's setInterval. - -**Arguments**: - -- `func`: Function to execute at each interval -- `interval`: Interval duration in **seconds** - -**Returns**: - -Stop function that can be called to cancel the interval - - - -### default\_build\_logger - -```python -def default_build_logger( - min_level: Optional[LogEntryLevel] = None -) -> Callable[[LogEntry], None] -``` - -Create a default build logger with animated timer display. - -**Arguments**: - -- `min_level`: Minimum log level to display (default: 'info') - -**Returns**: - -Logger function that accepts LogEntry instances -Example -```python -from e2b import Template, default_build_logger - -template = Template().from_python_image() - -``` diff --git a/docs/sdk-reference/python-sdk/v2.8.0/readycmd.mdx b/docs/sdk-reference/python-sdk/v2.8.0/readycmd.mdx deleted file mode 100644 index 8eabda6..0000000 --- a/docs/sdk-reference/python-sdk/v2.8.0/readycmd.mdx +++ /dev/null @@ -1,168 +0,0 @@ ---- -sidebarTitle: "Readycmd" -mode: "center" ---- - - - - - - -## ReadyCmd - -```python -class ReadyCmd() -``` - -Wrapper class for ready check commands. - - - -### wait\_for\_port - -```python -def wait_for_port(port: int) -``` - -Wait for a port to be listening. - -Uses `ss` command to check if a port is open and listening. - -**Arguments**: - -- `port`: Port number to wait for - -**Returns**: - -ReadyCmd that checks for the port -Example -```python -from e2b import Template, wait_for_port - -template = ( - Template() - .from_python_image() - .set_start_cmd('python -m http.server 8000', wait_for_port(8000)) -) -``` - - - -### wait\_for\_url - -```python -def wait_for_url(url: str, status_code: int = 200) -``` - -Wait for a URL to return a specific HTTP status code. - -Uses `curl` to make HTTP requests and check the response status. - -**Arguments**: - -- `url`: URL to check (e.g., 'http://localhost:3000/health') -- `status_code`: Expected HTTP status code (default: 200) - -**Returns**: - -ReadyCmd that checks the URL -Example -```python -from e2b import Template, wait_for_url - -template = ( - Template() - .from_node_image() - .set_start_cmd('npm start', wait_for_url('http://localhost:3000/health')) -) -``` - - - -### wait\_for\_process - -```python -def wait_for_process(process_name: str) -``` - -Wait for a process with a specific name to be running. - -Uses `pgrep` to check if a process exists. - -**Arguments**: - -- `process_name`: Name of the process to wait for - -**Returns**: - -ReadyCmd that checks for the process -Example -```python -from e2b import Template, wait_for_process - -template = ( - Template() - .from_base_image() - .set_start_cmd('./my-daemon', wait_for_process('my-daemon')) -) -``` - - - -### wait\_for\_file - -```python -def wait_for_file(filename: str) -``` - -Wait for a file to exist. - -Uses shell test command to check file existence. - -**Arguments**: - -- `filename`: Path to the file to wait for - -**Returns**: - -ReadyCmd that checks for the file -Example -```python -from e2b import Template, wait_for_file - -template = ( - Template() - .from_base_image() - .set_start_cmd('./init.sh', wait_for_file('/tmp/ready')) -) -``` - - - -### wait\_for\_timeout - -```python -def wait_for_timeout(timeout: int) -``` - -Wait for a specified timeout before considering the sandbox ready. - -Uses `sleep` command to wait for a fixed duration. - -**Arguments**: - -- `timeout`: Time to wait in **milliseconds** (minimum: 1000ms / 1 second) - -**Returns**: - -ReadyCmd that waits for the specified duration -Example -```python -from e2b import Template, wait_for_timeout - -template = ( - Template() - .from_node_image() - .set_start_cmd('npm start', wait_for_timeout(5000)) # Wait 5 seconds -) -``` diff --git a/docs/sdk-reference/python-sdk/v2.8.0/sandbox_async.mdx b/docs/sdk-reference/python-sdk/v2.8.0/sandbox_async.mdx deleted file mode 100644 index b636b1a..0000000 --- a/docs/sdk-reference/python-sdk/v2.8.0/sandbox_async.mdx +++ /dev/null @@ -1,1387 +0,0 @@ ---- -sidebarTitle: "Sandbox Async" -mode: "center" ---- - - - - - - -## AsyncWatchHandle - -```python -class AsyncWatchHandle() -``` - -Handle for watching a directory in the sandbox filesystem. - -Use `.stop()` to stop watching the directory. - - - -### stop - -```python -async def stop() -``` - -Stop watching the directory. - - - - - - -## Filesystem - -```python -class Filesystem() -``` - -Module for interacting with the filesystem in the sandbox. - - - -### read - -```python -@overload -async def read(path: str, - format: Literal["text"] = "text", - user: Optional[Username] = None, - request_timeout: Optional[float] = None) -> str -``` - -Read file content as a `str`. - -**Arguments**: - -- `path`: Path to the file -- `user`: Run the operation as this user -- `format`: Format of the file content—`text` by default -- `request_timeout`: Timeout for the request in **seconds** - -**Returns**: - -File content as a `str` - - - -### read - -```python -@overload -async def read(path: str, - format: Literal["bytes"], - user: Optional[Username] = None, - request_timeout: Optional[float] = None) -> bytearray -``` - -Read file content as a `bytearray`. - -**Arguments**: - -- `path`: Path to the file -- `user`: Run the operation as this user -- `format`: Format of the file content—`bytes` -- `request_timeout`: Timeout for the request in **seconds** - -**Returns**: - -File content as a `bytearray` - - - -### read - -```python -@overload -async def read( - path: str, - format: Literal["stream"], - user: Optional[Username] = None, - request_timeout: Optional[float] = None) -> AsyncIterator[bytes] -``` - -Read file content as a `AsyncIterator[bytes]`. - -**Arguments**: - -- `path`: Path to the file -- `user`: Run the operation as this user -- `format`: Format of the file content—`stream` -- `request_timeout`: Timeout for the request in **seconds** - -**Returns**: - -File content as an `AsyncIterator[bytes]` - - - -### write - -```python -async def write(path: str, - data: Union[str, bytes, IO], - user: Optional[Username] = None, - request_timeout: Optional[float] = None) -> WriteInfo -``` - -Write content to a file on the path. - -Writing to a file that doesn't exist creates the file. -Writing to a file that already exists overwrites the file. -Writing to a file at path that doesn't exist creates the necessary directories. - -**Arguments**: - -- `path`: Path to the file -- `data`: Data to write to the file, can be a `str`, `bytes`, or `IO`. -- `user`: Run the operation as this user -- `request_timeout`: Timeout for the request in **seconds** - -**Returns**: - -Information about the written file - - - -### write\_files - -```python -async def write_files( - files: List[WriteEntry], - user: Optional[Username] = None, - request_timeout: Optional[float] = None) -> List[WriteInfo] -``` - -Writes multiple files. - -Writes a list of files to the filesystem. -When writing to a file that doesn't exist, the file will get created. -When writing to a file that already exists, the file will get overwritten. -When writing to a file that's in a directory that doesn't exist, you'll get an error. - -**Arguments**: - -- `files`: list of files to write as `WriteEntry` objects, each containing `path` and `data` -- `user`: Run the operation as this user -- `request_timeout`: Timeout for the request - -**Returns**: - -Information about the written files - - - -### list - -```python -async def list(path: str, - depth: Optional[int] = 1, - user: Optional[Username] = None, - request_timeout: Optional[float] = None) -> List[EntryInfo] -``` - -List entries in a directory. - -**Arguments**: - -- `path`: Path to the directory -- `depth`: Depth of the directory to list -- `user`: Run the operation as this user -- `request_timeout`: Timeout for the request in **seconds** - -**Returns**: - -List of entries in the directory - - - -### exists - -```python -async def exists(path: str, - user: Optional[Username] = None, - request_timeout: Optional[float] = None) -> bool -``` - -Check if a file or a directory exists. - -**Arguments**: - -- `path`: Path to a file or a directory -- `user`: Run the operation as this user -- `request_timeout`: Timeout for the request in **seconds** - -**Returns**: - -`True` if the file or directory exists, `False` otherwise - - - -### get\_info - -```python -async def get_info(path: str, - user: Optional[Username] = None, - request_timeout: Optional[float] = None) -> EntryInfo -``` - -Get information about a file or directory. - -**Arguments**: - -- `path`: Path to a file or a directory -- `user`: Run the operation as this user -- `request_timeout`: Timeout for the request in **seconds** - -**Returns**: - -Information about the file or directory like name, type, and path - - - -### remove - -```python -async def remove(path: str, - user: Optional[Username] = None, - request_timeout: Optional[float] = None) -> None -``` - -Remove a file or a directory. - -**Arguments**: - -- `path`: Path to a file or a directory -- `user`: Run the operation as this user -- `request_timeout`: Timeout for the request in **seconds** - - - -### rename - -```python -async def rename(old_path: str, - new_path: str, - user: Optional[Username] = None, - request_timeout: Optional[float] = None) -> EntryInfo -``` - -Rename a file or directory. - -**Arguments**: - -- `old_path`: Path to the file or directory to rename -- `new_path`: New path to the file or directory -- `user`: Run the operation as this user -- `request_timeout`: Timeout for the request in **seconds** - -**Returns**: - -Information about the renamed file or directory - - - -### make\_dir - -```python -async def make_dir(path: str, - user: Optional[Username] = None, - request_timeout: Optional[float] = None) -> bool -``` - -Create a new directory and all directories along the way if needed on the specified path. - -**Arguments**: - -- `path`: Path to a new directory. For example '/dirA/dirB' when creating 'dirB'. -- `user`: Run the operation as this user -- `request_timeout`: Timeout for the request in **seconds** - -**Returns**: - -`True` if the directory was created, `False` if the directory already exists - - - -### watch\_dir - -```python -async def watch_dir(path: str, - on_event: OutputHandler[FilesystemEvent], - on_exit: Optional[OutputHandler[Exception]] = None, - user: Optional[Username] = None, - request_timeout: Optional[float] = None, - timeout: Optional[float] = 60, - recursive: bool = False) -> AsyncWatchHandle -``` - -Watch directory for filesystem events. - -**Arguments**: - -- `path`: Path to a directory to watch -- `on_event`: Callback to call on each event in the directory -- `on_exit`: Callback to call when the watching ends -- `user`: Run the operation as this user -- `request_timeout`: Timeout for the request in **seconds** -- `timeout`: Timeout for the watch operation in **seconds**. Using `0` will not limit the watch time -- `recursive`: Watch directory recursively - -**Returns**: - -`AsyncWatchHandle` object for stopping watching directory - - - - - - -## AsyncSandboxPaginator - -```python -class AsyncSandboxPaginator(SandboxPaginatorBase) -``` - -Paginator for listing sandboxes. - -**Example**: - -```python -paginator = AsyncSandbox.list() - -while paginator.has_next: - sandboxes = await paginator.next_items() - print(sandboxes) -``` - - - -### next\_items - -```python -async def next_items() -> List[SandboxInfo] -``` - -Returns the next page of sandboxes. - -Call this method only if `has_next` is `True`, otherwise it will raise an exception. - -**Returns**: - -List of sandboxes - - - - - - - - - -## SandboxApi - -```python -class SandboxApi(SandboxBase) -``` - - - -### list - -```python -@staticmethod -def list(query: Optional[SandboxQuery] = None, - limit: Optional[int] = None, - next_token: Optional[str] = None, - **opts: Unpack[ApiParams]) -> AsyncSandboxPaginator -``` - -List all running sandboxes. - -**Arguments**: - -- `query`: Filter the list of sandboxes by metadata or state, e.g. `SandboxListQuery(metadata={"key": "value"})` or `SandboxListQuery(state=[SandboxState.RUNNING])` -- `limit`: Maximum number of sandboxes to return per page -- `next_token`: Token for pagination - -**Returns**: - -List of running sandboxes - - - - - - -## Commands - -```python -class Commands() -``` - -Module for executing commands in the sandbox. - - - -### list - -```python -async def list(request_timeout: Optional[float] = None) -> List[ProcessInfo] -``` - -Lists all running commands and PTY sessions. - -**Arguments**: - -- `request_timeout`: Timeout for the request in **seconds** - -**Returns**: - -List of running commands and PTY sessions - - - -### kill - -```python -async def kill(pid: int, request_timeout: Optional[float] = None) -> bool -``` - -Kill a running command specified by its process ID. - -It uses `SIGKILL` signal to kill the command. - -**Arguments**: - -- `pid`: Process ID of the command. You can get the list of processes using `sandbox.commands.list()` -- `request_timeout`: Timeout for the request in **seconds** - -**Returns**: - -`True` if the command was killed, `False` if the command was not found - - - -### send\_stdin - -```python -async def send_stdin(pid: int, - data: str, - request_timeout: Optional[float] = None) -> None -``` - -Send data to command stdin. - -:param pid Process ID of the command. You can get the list of processes using `sandbox.commands.list()`. -:param data: Data to send to the command -:param request_timeout: Timeout for the request in **seconds** - - - - -### run - -```python -@overload -async def run(cmd: str, - background: Union[Literal[False], None] = None, - envs: Optional[Dict[str, str]] = None, - user: Optional[Username] = None, - cwd: Optional[str] = None, - on_stdout: Optional[OutputHandler[Stdout]] = None, - on_stderr: Optional[OutputHandler[Stderr]] = None, - stdin: Optional[bool] = None, - timeout: Optional[float] = 60, - request_timeout: Optional[float] = None) -> CommandResult -``` - -Start a new command and wait until it finishes executing. - -**Arguments**: - -- `cmd`: Command to execute -- `background`: **`False` if the command should be executed in the foreground**, `True` if the command should be executed in the background -- `envs`: Environment variables used for the command -- `user`: User to run the command as -- `cwd`: Working directory to run the command -- `on_stdout`: Callback for command stdout output -- `on_stderr`: Callback for command stderr output -- `stdin`: If `True`, the command will have a stdin stream that you can send data to using `sandbox.commands.send_stdin()` -- `timeout`: Timeout for the command connection in **seconds**. Using `0` will not limit the command connection time -- `request_timeout`: Timeout for the request in **seconds** - -**Returns**: - -`CommandResult` result of the command execution - - - -### run - -```python -@overload -async def run(cmd: str, - background: Literal[True], - envs: Optional[Dict[str, str]] = None, - user: Optional[Username] = None, - cwd: Optional[str] = None, - on_stdout: Optional[OutputHandler[Stdout]] = None, - on_stderr: Optional[OutputHandler[Stderr]] = None, - stdin: Optional[bool] = None, - timeout: Optional[float] = 60, - request_timeout: Optional[float] = None) -> AsyncCommandHandle -``` - -Start a new command and return a handle to interact with it. - -**Arguments**: - -- `cmd`: Command to execute -- `background`: `False` if the command should be executed in the foreground, **`True` if the command should be executed in the background** -- `envs`: Environment variables used for the command -- `user`: User to run the command as -- `cwd`: Working directory to run the command -- `on_stdout`: Callback for command stdout output -- `on_stderr`: Callback for command stderr output -- `stdin`: If `True`, the command will have a stdin stream that you can send data to using `sandbox.commands.send_stdin()` -- `timeout`: Timeout for the command connection in **seconds**. Using `0` will not limit the command connection time -- `request_timeout`: Timeout for the request in **seconds** - -**Returns**: - -`AsyncCommandHandle` handle to interact with the running command - - - -### connect - -```python -async def connect( - pid: int, - timeout: Optional[float] = 60, - request_timeout: Optional[float] = None, - on_stdout: Optional[OutputHandler[Stdout]] = None, - on_stderr: Optional[OutputHandler[Stderr]] = None -) -> AsyncCommandHandle -``` - -Connects to a running command. - -You can use `AsyncCommandHandle.wait()` to wait for the command to finish and get execution results. - -**Arguments**: - -- `pid`: Process ID of the command to connect to. You can get the list of processes using `sandbox.commands.list()` -- `request_timeout`: Request timeout in **seconds** -- `timeout`: Timeout for the command connection in **seconds**. Using `0` will not limit the command connection time -- `on_stdout`: Callback for command stdout output -- `on_stderr`: Callback for command stderr output - -**Returns**: - -`AsyncCommandHandle` handle to interact with the running command - - - - - - -## AsyncCommandHandle - -```python -class AsyncCommandHandle() -``` - -Command execution handle. - -It provides methods for waiting for the command to finish, retrieving stdout/stderr, and killing the command. - - - -### pid - -```python -@property -def pid() -``` - -Command process ID. - - - -### stdout - -```python -@property -def stdout() -``` - -Command stdout output. - - - -### stderr - -```python -@property -def stderr() -``` - -Command stderr output. - - - -### error - -```python -@property -def error() -``` - -Command execution error message. - - - -### exit\_code - -```python -@property -def exit_code() -``` - -Command execution exit code. - -`0` if the command finished successfully. - -It is `None` if the command is still running. - - - -### disconnect - -```python -async def disconnect() -> None -``` - -Disconnects from the command. - -The command is not killed, but SDK stops receiving events from the command. -You can reconnect to the command using `sandbox.commands.connect` method. - - - -### wait - -```python -async def wait() -> CommandResult -``` - -Wait for the command to finish and return the result. - -If the command exits with a non-zero exit code, it throws a `CommandExitException`. - -**Returns**: - -`CommandResult` result of command execution - - - -### kill - -```python -async def kill() -> bool -``` - -Kills the command. - -It uses `SIGKILL` signal to kill the command - -**Returns**: - -`True` if the command was killed successfully, `False` if the command was not found - - - - - - -## Pty - -```python -class Pty() -``` - -Module for interacting with PTYs (pseudo-terminals) in the sandbox. - - - -### kill - -```python -async def kill(pid: int, request_timeout: Optional[float] = None) -> bool -``` - -Kill PTY. - -**Arguments**: - -- `pid`: Process ID of the PTY -- `request_timeout`: Timeout for the request in **seconds** - -**Returns**: - -`true` if the PTY was killed, `false` if the PTY was not found - - - -### send\_stdin - -```python -async def send_stdin(pid: int, - data: bytes, - request_timeout: Optional[float] = None) -> None -``` - -Send input to a PTY. - -**Arguments**: - -- `pid`: Process ID of the PTY -- `data`: Input data to send -- `request_timeout`: Timeout for the request in **seconds** - - - -### create - -```python -async def create( - size: PtySize, - on_data: OutputHandler[PtyOutput], - user: Optional[Username] = None, - cwd: Optional[str] = None, - envs: Optional[Dict[str, str]] = None, - timeout: Optional[float] = 60, - request_timeout: Optional[float] = None) -> AsyncCommandHandle -``` - -Start a new PTY (pseudo-terminal). - -**Arguments**: - -- `size`: Size of the PTY -- `on_data`: Callback to handle PTY data -- `user`: User to use for the PTY -- `cwd`: Working directory for the PTY -- `envs`: Environment variables for the PTY -- `timeout`: Timeout for the PTY in **seconds** -- `request_timeout`: Timeout for the request in **seconds** - -**Returns**: - -Handle to interact with the PTY - - - -### resize - -```python -async def resize(pid: int, - size: PtySize, - request_timeout: Optional[float] = None) -``` - -Resize PTY. - -Call this when the terminal window is resized and the number of columns and rows has changed. - -**Arguments**: - -- `pid`: Process ID of the PTY -- `size`: New size of the PTY -- `request_timeout`: Timeout for the request in **seconds** - - - - - - -## AsyncSandbox - -```python -class AsyncSandbox(SandboxApi) -``` - -E2B cloud sandbox is a secure and isolated cloud environment. - -The sandbox allows you to: -- Access Linux OS -- Create, list, and delete files and directories -- Run commands -- Run isolated code -- Access the internet - -Check docs [here](https://e2b.dev/docs). - -Use the `AsyncSandbox.create()` to create a new sandbox. - -**Example**: - -```python -from e2b import AsyncSandbox - -sandbox = await AsyncSandbox.create() -``` - - - -### files - -```python -@property -def files() -> Filesystem -``` - -Module for interacting with the sandbox filesystem. - - - -### commands - -```python -@property -def commands() -> Commands -``` - -Module for running commands in the sandbox. - - - -### pty - -```python -@property -def pty() -> Pty -``` - -Module for interacting with the sandbox pseudo-terminal. - - - -### \_\_init\_\_ - -```python -def __init__(**opts: Unpack[SandboxOpts]) -``` - -Use `AsyncSandbox.create()` to create a new sandbox instead. - - - -### is\_running - -```python -async def is_running(request_timeout: Optional[float] = None) -> bool -``` - -Check if the sandbox is running. - -**Arguments**: - -- `request_timeout`: Timeout for the request in **seconds** - -**Returns**: - -`True` if the sandbox is running, `False` otherwise -Example -```python -sandbox = await AsyncSandbox.create() -await sandbox.is_running() # Returns True - -await sandbox.kill() -await sandbox.is_running() # Returns False -``` - - - -### create - -```python -@classmethod -async def create(cls, - template: Optional[str] = None, - timeout: Optional[int] = None, - metadata: Optional[Dict[str, str]] = None, - envs: Optional[Dict[str, str]] = None, - secure: bool = True, - allow_internet_access: bool = True, - mcp: Optional[McpServer] = None, - network: Optional[SandboxNetworkOpts] = None, - **opts: Unpack[ApiParams]) -> Self -``` - -Create a new sandbox. - -By default, the sandbox is created from the default `base` sandbox template. - -**Arguments**: - -- `template`: Sandbox template name or ID -- `timeout`: Timeout for the sandbox in **seconds**, default to 300 seconds. The maximum time a sandbox can be kept alive is 24 hours (86_400 seconds) for Pro users and 1 hour (3_600 seconds) for Hobby users. -- `metadata`: Custom metadata for the sandbox -- `envs`: Custom environment variables for the sandbox -- `secure`: Envd is secured with access token and cannot be used without it, defaults to `True`. -- `allow_internet_access`: Allow sandbox to access the internet, defaults to `True`. If set to `False`, it works the same as setting network `deny_out` to `[0.0.0.0/0]`. -- `mcp`: MCP server to enable in the sandbox -- `network`: Sandbox network configuration - -**Returns**: - -A Sandbox instance for the new sandbox -Use this method instead of using the constructor to create a new sandbox. - - - -### connect - -```python -@overload -async def connect(timeout: Optional[int] = None, - **opts: Unpack[ApiParams]) -> Self -``` - -Connect to a sandbox. If the sandbox is paused, it will be automatically resumed. - -Sandbox must be either running or be paused. - -With sandbox ID you can connect to the same sandbox from different places or environments (serverless functions, etc). - -**Arguments**: - -- `timeout`: Timeout for the sandbox in **seconds** -For running sandboxes, the timeout will update only if the new timeout is longer than the existing one. - -**Returns**: - -A running sandbox instance -@example -```python -sandbox = await AsyncSandbox.create() -await sandbox.beta_pause() - -same_sandbox = await sandbox.connect() -``` - - - -### connect - -```python -@overload -@classmethod -async def connect(cls, - sandbox_id: str, - timeout: Optional[int] = None, - **opts: Unpack[ApiParams]) -> Self -``` - -Connect to a sandbox. If the sandbox is paused, it will be automatically resumed. - -Sandbox must be either running or be paused. - -With sandbox ID you can connect to the same sandbox from different places or environments (serverless functions, etc). - -**Arguments**: - -- `sandbox_id`: Sandbox ID -- `timeout`: Timeout for the sandbox in **seconds** -For running sandboxes, the timeout will update only if the new timeout is longer than the existing one. - -**Returns**: - -A running sandbox instance -@example -```python -sandbox = await AsyncSandbox.create() -await AsyncSandbox.beta_pause(sandbox.sandbox_id) - -same_sandbox = await AsyncSandbox.connect(sandbox.sandbox_id)) -``` - - - -### connect - -```python -@class_method_variant("_cls_connect") -async def connect(timeout: Optional[int] = None, - **opts: Unpack[ApiParams]) -> Self -``` - -Connect to a sandbox. If the sandbox is paused, it will be automatically resumed. - -Sandbox must be either running or be paused. - -With sandbox ID you can connect to the same sandbox from different places or environments (serverless functions, etc). - -**Arguments**: - -- `timeout`: Timeout for the sandbox in **seconds** -For running sandboxes, the timeout will update only if the new timeout is longer than the existing one. - -**Returns**: - -A running sandbox instance -@example -```python -sandbox = await AsyncSandbox.create() -await sandbox.beta_pause() - -same_sandbox = await sandbox.connect() -``` - - - -### kill - -```python -@overload -async def kill(**opts: Unpack[ApiParams]) -> bool -``` - -Kill the sandbox. - -**Returns**: - -`True` if the sandbox was killed, `False` if the sandbox was not found - - - -### kill - -```python -@overload -@staticmethod -async def kill(sandbox_id: str, **opts: Unpack[ApiParams]) -> bool -``` - -Kill the sandbox specified by sandbox ID. - -**Arguments**: - -- `sandbox_id`: Sandbox ID - -**Returns**: - -`True` if the sandbox was killed, `False` if the sandbox was not found - - - -### kill - -```python -@class_method_variant("_cls_kill") -async def kill(**opts: Unpack[ApiParams]) -> bool -``` - -Kill the sandbox specified by sandbox ID. - -**Returns**: - -`True` if the sandbox was killed, `False` if the sandbox was not found - - - -### set\_timeout - -```python -@overload -async def set_timeout(timeout: int, **opts: Unpack[ApiParams]) -> None -``` - -Set the timeout of the sandbox. - -After the timeout expires, the sandbox will be automatically killed. -This method can extend or reduce the sandbox timeout set when creating the sandbox or from the last call to `.set_timeout`. - -The maximum time a sandbox can be kept alive is 24 hours (86_400 seconds) for Pro users and 1 hour (3_600 seconds) for Hobby users. - -**Arguments**: - -- `timeout`: Timeout for the sandbox in **seconds** - - - -### set\_timeout - -```python -@overload -@staticmethod -async def set_timeout(sandbox_id: str, timeout: int, - **opts: Unpack[ApiParams]) -> None -``` - -Set the timeout of the specified sandbox. - -After the timeout expires, the sandbox will be automatically killed. -This method can extend or reduce the sandbox timeout set when creating the sandbox or from the last call to `.set_timeout`. - -The maximum time a sandbox can be kept alive is 24 hours (86_400 seconds) for Pro users and 1 hour (3_600 seconds) for Hobby users. - -**Arguments**: - -- `sandbox_id`: Sandbox ID -- `timeout`: Timeout for the sandbox in **seconds** - - - -### set\_timeout - -```python -@class_method_variant("_cls_set_timeout") -async def set_timeout(timeout: int, **opts: Unpack[ApiParams]) -> None -``` - -Set the timeout of the specified sandbox. - -After the timeout expires, the sandbox will be automatically killed. -This method can extend or reduce the sandbox timeout set when creating the sandbox or from the last call to `.set_timeout`. - -The maximum time a sandbox can be kept alive is 24 hours (86_400 seconds) for Pro users and 1 hour (3_600 seconds) for Hobby users. - -**Arguments**: - -- `timeout`: Timeout for the sandbox in **seconds** - - - -### get\_info - -```python -@overload -async def get_info(**opts: Unpack[ApiParams]) -> SandboxInfo -``` - -Get sandbox information like sandbox ID, template, metadata, started at/end at date. - -**Returns**: - -Sandbox info - - - -### get\_info - -```python -@overload -@staticmethod -async def get_info(sandbox_id: str, **opts: Unpack[ApiParams]) -> SandboxInfo -``` - -Get sandbox information like sandbox ID, template, metadata, started at/end at date. - -**Arguments**: - -- `sandbox_id`: Sandbox ID - -**Returns**: - -Sandbox info - - - -### get\_info - -```python -@class_method_variant("_cls_get_info") -async def get_info(**opts: Unpack[ApiParams]) -> SandboxInfo -``` - -Get sandbox information like sandbox ID, template, metadata, started at/end at date. - -**Returns**: - -Sandbox info - - - -### get\_metrics - -```python -@overload -async def get_metrics(start: Optional[datetime.datetime] = None, - end: Optional[datetime.datetime] = None, - **opts: Unpack[ApiParams]) -> List[SandboxMetrics] -``` - -Get the metrics of the current sandbox. - -**Arguments**: - -- `start`: Start time for the metrics, defaults to the start of the sandbox -- `end`: End time for the metrics, defaults to the current time - -**Returns**: - -List of sandbox metrics containing CPU, memory and disk usage information - - - -### get\_metrics - -```python -@overload -@staticmethod -async def get_metrics(sandbox_id: str, - start: Optional[datetime.datetime] = None, - end: Optional[datetime.datetime] = None, - **opts: Unpack[ApiParams]) -> List[SandboxMetrics] -``` - -Get the metrics of the sandbox specified by sandbox ID. - -**Arguments**: - -- `sandbox_id`: Sandbox ID -- `start`: Start time for the metrics, defaults to the start of the sandbox -- `end`: End time for the metrics, defaults to the current time - -**Returns**: - -List of sandbox metrics containing CPU, memory and disk usage information - - - -### get\_metrics - -```python -@class_method_variant("_cls_get_metrics") -async def get_metrics(start: Optional[datetime.datetime] = None, - end: Optional[datetime.datetime] = None, - **opts: Unpack[ApiParams]) -> List[SandboxMetrics] -``` - -Get the metrics of the current sandbox. - -**Arguments**: - -- `start`: Start time for the metrics, defaults to the start of the sandbox -- `end`: End time for the metrics, defaults to the current time - -**Returns**: - -List of sandbox metrics containing CPU, memory and disk usage information - - - -### beta\_create - -```python -@classmethod -async def beta_create(cls, - template: Optional[str] = None, - timeout: Optional[int] = None, - auto_pause: bool = False, - metadata: Optional[Dict[str, str]] = None, - envs: Optional[Dict[str, str]] = None, - secure: bool = True, - allow_internet_access: bool = True, - mcp: Optional[McpServer] = None, - **opts: Unpack[ApiParams]) -> Self -``` - -[BETA] This feature is in beta and may change in the future. - -Create a new sandbox. - -By default, the sandbox is created from the default `base` sandbox template. - -**Arguments**: - -- `template`: Sandbox template name or ID -- `timeout`: Timeout for the sandbox in **seconds**, default to 300 seconds. The maximum time a sandbox can be kept alive is 24 hours (86_400 seconds) for Pro users and 1 hour (3_600 seconds) for Hobby users. -- `auto_pause`: Automatically pause the sandbox after the timeout expires. Defaults to `False`. -- `metadata`: Custom metadata for the sandbox -- `envs`: Custom environment variables for the sandbox -- `secure`: Envd is secured with access token and cannot be used without it, defaults to `True`. -- `allow_internet_access`: Allow sandbox to access the internet, defaults to `True`. -- `mcp`: MCP server to enable in the sandbox - -**Returns**: - -A Sandbox instance for the new sandbox -Use this method instead of using the constructor to create a new sandbox. - - - -### beta\_pause - -```python -@overload -async def beta_pause(**opts: Unpack[ApiParams]) -> None -``` - -[BETA] This feature is in beta and may change in the future. - -Pause the sandbox. - -**Returns**: - -Sandbox ID that can be used to resume the sandbox - - - -### beta\_pause - -```python -@overload -@staticmethod -async def beta_pause(sandbox_id: str, **opts: Unpack[ApiParams]) -> None -``` - -[BETA] This feature is in beta and may change in the future. - -Pause the sandbox specified by sandbox ID. - -**Arguments**: - -- `sandbox_id`: Sandbox ID - -**Returns**: - -Sandbox ID that can be used to resume the sandbox - - - -### beta\_pause - -```python -@class_method_variant("_cls_pause") -async def beta_pause(**opts: Unpack[ApiParams]) -> None -``` - -[BETA] This feature is in beta and may change in the future. - -Pause the sandbox. - -**Returns**: - -Sandbox ID that can be used to resume the sandbox - - - -### get\_mcp\_token - -```python -async def get_mcp_token() -> Optional[str] -``` - -Get the MCP token for the sandbox. - -**Returns**: - -MCP token for the sandbox, or None if MCP is not enabled. diff --git a/docs/sdk-reference/python-sdk/v2.8.0/sandbox_sync.mdx b/docs/sdk-reference/python-sdk/v2.8.0/sandbox_sync.mdx deleted file mode 100644 index 04927a8..0000000 --- a/docs/sdk-reference/python-sdk/v2.8.0/sandbox_sync.mdx +++ /dev/null @@ -1,1343 +0,0 @@ ---- -sidebarTitle: "Sandbox Sync" -mode: "center" ---- - - - - - - -## WatchHandle - -```python -class WatchHandle() -``` - -Handle for watching filesystem events. -It is used to get the latest events that have occurred in the watched directory. - -Use `.stop()` to stop watching the directory. - - - -### stop - -```python -def stop() -``` - -Stop watching the directory. -After you stop the watcher you won't be able to get the events anymore. - - - -### get\_new\_events - -```python -def get_new_events() -> List[FilesystemEvent] -``` - -Get the latest events that have occurred in the watched directory since the last call, or from the beginning of the watching, up until now. - -**Returns**: - -List of filesystem events - - - - - - -## Filesystem - -```python -class Filesystem() -``` - -Module for interacting with the filesystem in the sandbox. - - - -### read - -```python -@overload -def read(path: str, - format: Literal["text"] = "text", - user: Optional[Username] = None, - request_timeout: Optional[float] = None) -> str -``` - -Read file content as a `str`. - -**Arguments**: - -- `path`: Path to the file -- `user`: Run the operation as this user -- `format`: Format of the file content—`text` by default -- `request_timeout`: Timeout for the request in **seconds** - -**Returns**: - -File content as a `str` - - - -### read - -```python -@overload -def read(path: str, - format: Literal["bytes"], - user: Optional[Username] = None, - request_timeout: Optional[float] = None) -> bytearray -``` - -Read file content as a `bytearray`. - -**Arguments**: - -- `path`: Path to the file -- `user`: Run the operation as this user -- `format`: Format of the file content—`bytes` -- `request_timeout`: Timeout for the request in **seconds** - -**Returns**: - -File content as a `bytearray` - - - -### read - -```python -@overload -def read(path: str, - format: Literal["stream"], - user: Optional[Username] = None, - request_timeout: Optional[float] = None) -> Iterator[bytes] -``` - -Read file content as a `Iterator[bytes]`. - -**Arguments**: - -- `path`: Path to the file -- `user`: Run the operation as this user -- `format`: Format of the file content—`stream` -- `request_timeout`: Timeout for the request in **seconds** - -**Returns**: - -File content as an `Iterator[bytes]` - - - -### write - -```python -def write(path: str, - data: Union[str, bytes, IO], - user: Optional[Username] = None, - request_timeout: Optional[float] = None) -> WriteInfo -``` - -Write content to a file on the path. - -Writing to a file that doesn't exist creates the file. -Writing to a file that already exists overwrites the file. -Writing to a file at path that doesn't exist creates the necessary directories. - -**Arguments**: - -- `path`: Path to the file -- `data`: Data to write to the file, can be a `str`, `bytes`, or `IO`. -- `user`: Run the operation as this user -- `request_timeout`: Timeout for the request in **seconds** - -**Returns**: - -Information about the written file - - - -### write\_files - -```python -def write_files(files: List[WriteEntry], - user: Optional[Username] = None, - request_timeout: Optional[float] = None) -> List[WriteInfo] -``` - -Writes a list of files to the filesystem. - -When writing to a file that doesn't exist, the file will get created. -When writing to a file that already exists, the file will get overwritten. -When writing to a file that's in a directory that doesn't exist, you'll get an error. - -**Arguments**: - -- `files`: list of files to write as `WriteEntry` objects, each containing `path` and `data` -- `user`: Run the operation as this user -- `request_timeout`: Timeout for the request - -**Returns**: - -Information about the written files - - - -### list - -```python -def list(path: str, - depth: Optional[int] = 1, - user: Optional[Username] = None, - request_timeout: Optional[float] = None) -> List[EntryInfo] -``` - -List entries in a directory. - -**Arguments**: - -- `path`: Path to the directory -- `depth`: Depth of the directory to list -- `user`: Run the operation as this user -- `request_timeout`: Timeout for the request in **seconds** - -**Returns**: - -List of entries in the directory - - - -### exists - -```python -def exists(path: str, - user: Optional[Username] = None, - request_timeout: Optional[float] = None) -> bool -``` - -Check if a file or a directory exists. - -**Arguments**: - -- `path`: Path to a file or a directory -- `user`: Run the operation as this user -- `request_timeout`: Timeout for the request in **seconds** - -**Returns**: - -`True` if the file or directory exists, `False` otherwise - - - -### get\_info - -```python -def get_info(path: str, - user: Optional[Username] = None, - request_timeout: Optional[float] = None) -> EntryInfo -``` - -Get information about a file or directory. - -**Arguments**: - -- `path`: Path to a file or a directory -- `user`: Run the operation as this user -- `request_timeout`: Timeout for the request in **seconds** - -**Returns**: - -Information about the file or directory like name, type, and path - - - -### remove - -```python -def remove(path: str, - user: Optional[Username] = None, - request_timeout: Optional[float] = None) -> None -``` - -Remove a file or a directory. - -**Arguments**: - -- `path`: Path to a file or a directory -- `user`: Run the operation as this user -- `request_timeout`: Timeout for the request in **seconds** - - - -### rename - -```python -def rename(old_path: str, - new_path: str, - user: Optional[Username] = None, - request_timeout: Optional[float] = None) -> EntryInfo -``` - -Rename a file or directory. - -**Arguments**: - -- `old_path`: Path to the file or directory to rename -- `new_path`: New path to the file or directory -- `user`: Run the operation as this user -- `request_timeout`: Timeout for the request in **seconds** - -**Returns**: - -Information about the renamed file or directory - - - -### make\_dir - -```python -def make_dir(path: str, - user: Optional[Username] = None, - request_timeout: Optional[float] = None) -> bool -``` - -Create a new directory and all directories along the way if needed on the specified path. - -**Arguments**: - -- `path`: Path to a new directory. For example '/dirA/dirB' when creating 'dirB'. -- `user`: Run the operation as this user -- `request_timeout`: Timeout for the request in **seconds** - -**Returns**: - -`True` if the directory was created, `False` if the directory already exists - - - -### watch\_dir - -```python -def watch_dir(path: str, - user: Optional[Username] = None, - request_timeout: Optional[float] = None, - recursive: bool = False) -> WatchHandle -``` - -Watch directory for filesystem events. - -**Arguments**: - -- `path`: Path to a directory to watch -- `user`: Run the operation as this user -- `request_timeout`: Timeout for the request in **seconds** -- `recursive`: Watch directory recursively - -**Returns**: - -`WatchHandle` object for stopping watching directory - - - - - - -## SandboxPaginator - -```python -class SandboxPaginator(SandboxPaginatorBase) -``` - -Paginator for listing sandboxes. - -**Example**: - -```python -paginator = Sandbox.list() - -while paginator.has_next: - sandboxes = paginator.next_items() - print(sandboxes) -``` - - - -### next\_items - -```python -def next_items() -> List[SandboxInfo] -``` - -Returns the next page of sandboxes. - -Call this method only if `has_next` is `True`, otherwise it will raise an exception. - -**Returns**: - -List of sandboxes - - - - - - -## SandboxApi - -```python -class SandboxApi(SandboxBase) -``` - - - -### list - -```python -@staticmethod -def list(query: Optional[SandboxQuery] = None, - limit: Optional[int] = None, - next_token: Optional[str] = None, - **opts: Unpack[ApiParams]) -> SandboxPaginator -``` - -List all running sandboxes. - -**Arguments**: - -- `query`: Filter the list of sandboxes by metadata or state, e.g. `SandboxListQuery(metadata={"key": "value"})` or `SandboxListQuery(state=[SandboxState.RUNNING])` -- `limit`: Maximum number of sandboxes to return per page -- `next_token`: Token for pagination - -**Returns**: - -List of running sandboxes - - - - - - -## Commands - -```python -class Commands() -``` - -Module for executing commands in the sandbox. - - - -### list - -```python -def list(request_timeout: Optional[float] = None) -> List[ProcessInfo] -``` - -Lists all running commands and PTY sessions. - -**Arguments**: - -- `request_timeout`: Timeout for the request in **seconds** - -**Returns**: - -List of running commands and PTY sessions - - - -### kill - -```python -def kill(pid: int, request_timeout: Optional[float] = None) -> bool -``` - -Kills a running command specified by its process ID. - -It uses `SIGKILL` signal to kill the command. - -**Arguments**: - -- `pid`: Process ID of the command. You can get the list of processes using `sandbox.commands.list()` -- `request_timeout`: Timeout for the request in **seconds** - -**Returns**: - -`True` if the command was killed, `False` if the command was not found - - - -### send\_stdin - -```python -def send_stdin(pid: int, data: str, request_timeout: Optional[float] = None) -``` - -Send data to command stdin. - -:param pid Process ID of the command. You can get the list of processes using `sandbox.commands.list()`. -:param data: Data to send to the command -:param request_timeout: Timeout for the request in **seconds** - - - - -### run - -```python -@overload -def run(cmd: str, - background: Union[Literal[False], None] = None, - envs: Optional[Dict[str, str]] = None, - user: Optional[Username] = None, - cwd: Optional[str] = None, - on_stdout: Optional[Callable[[str], None]] = None, - on_stderr: Optional[Callable[[str], None]] = None, - stdin: Optional[bool] = None, - timeout: Optional[float] = 60, - request_timeout: Optional[float] = None) -> CommandResult -``` - -Start a new command and wait until it finishes executing. - -**Arguments**: - -- `cmd`: Command to execute -- `background`: **`False` if the command should be executed in the foreground**, `True` if the command should be executed in the background -- `envs`: Environment variables used for the command -- `user`: User to run the command as -- `cwd`: Working directory to run the command -- `on_stdout`: Callback for command stdout output -- `on_stderr`: Callback for command stderr output -- `stdin`: If `True`, the command will have a stdin stream that you can send data to using `sandbox.commands.send_stdin()` -- `timeout`: Timeout for the command connection in **seconds**. Using `0` will not limit the command connection time -- `request_timeout`: Timeout for the request in **seconds** - -**Returns**: - -`CommandResult` result of the command execution - - - -### run - -```python -@overload -def run(cmd: str, - background: Literal[True], - envs: Optional[Dict[str, str]] = None, - user: Optional[Username] = None, - cwd: Optional[str] = None, - on_stdout: None = None, - on_stderr: None = None, - stdin: Optional[bool] = None, - timeout: Optional[float] = 60, - request_timeout: Optional[float] = None) -> CommandHandle -``` - -Start a new command and return a handle to interact with it. - -**Arguments**: - -- `cmd`: Command to execute -- `background`: `False` if the command should be executed in the foreground, **`True` if the command should be executed in the background** -- `envs`: Environment variables used for the command -- `user`: User to run the command as -- `cwd`: Working directory to run the command -- `stdin`: If `True`, the command will have a stdin stream that you can send data to using `sandbox.commands.send_stdin()` -- `timeout`: Timeout for the command connection in **seconds**. Using `0` will not limit the command connection time -- `request_timeout`: Timeout for the request in **seconds** - -**Returns**: - -`CommandHandle` handle to interact with the running command - - - -### connect - -```python -def connect(pid: int, - timeout: Optional[float] = 60, - request_timeout: Optional[float] = None) -``` - -Connects to a running command. - -You can use `CommandHandle.wait()` to wait for the command to finish and get execution results. - -**Arguments**: - -- `pid`: Process ID of the command to connect to. You can get the list of processes using `sandbox.commands.list()` -- `timeout`: Timeout for the connection in **seconds**. Using `0` will not limit the connection time -- `request_timeout`: Timeout for the request in **seconds** - -**Returns**: - -`CommandHandle` handle to interact with the running command - - - - - - -## CommandHandle - -```python -class CommandHandle() -``` - -Command execution handle. - -It provides methods for waiting for the command to finish, retrieving stdout/stderr, and killing the command. - - - -### pid - -```python -@property -def pid() -``` - -Command process ID. - - - -### \_\_iter\_\_ - -```python -def __iter__() -``` - -Iterate over the command output. - -**Returns**: - -Generator of command outputs - - - -### disconnect - -```python -def disconnect() -> None -``` - -Disconnect from the command. - -The command is not killed, but SDK stops receiving events from the command. -You can reconnect to the command using `sandbox.commands.connect` method. - - - -### wait - -```python -def wait(on_pty: Optional[Callable[[PtyOutput], None]] = None, - on_stdout: Optional[Callable[[str], None]] = None, - on_stderr: Optional[Callable[[str], None]] = None) -> CommandResult -``` - -Wait for the command to finish and returns the result. - -If the command exits with a non-zero exit code, it throws a `CommandExitException`. - -**Arguments**: - -- `on_pty`: Callback for pty output -- `on_stdout`: Callback for stdout output -- `on_stderr`: Callback for stderr output - -**Returns**: - -`CommandResult` result of command execution - - - -### kill - -```python -def kill() -> bool -``` - -Kills the command. - -It uses `SIGKILL` signal to kill the command. - -**Returns**: - -Whether the command was killed successfully - - - - - - -## Pty - -```python -class Pty() -``` - -Module for interacting with PTYs (pseudo-terminals) in the sandbox. - - - -### kill - -```python -def kill(pid: int, request_timeout: Optional[float] = None) -> bool -``` - -Kill PTY. - -**Arguments**: - -- `pid`: Process ID of the PTY -- `request_timeout`: Timeout for the request in **seconds** - -**Returns**: - -`true` if the PTY was killed, `false` if the PTY was not found - - - -### send\_stdin - -```python -def send_stdin(pid: int, - data: bytes, - request_timeout: Optional[float] = None) -> None -``` - -Send input to a PTY. - -**Arguments**: - -- `pid`: Process ID of the PTY -- `data`: Input data to send -- `request_timeout`: Timeout for the request in **seconds** - - - -### create - -```python -def create(size: PtySize, - user: Optional[Username] = None, - cwd: Optional[str] = None, - envs: Optional[Dict[str, str]] = None, - timeout: Optional[float] = 60, - request_timeout: Optional[float] = None) -> CommandHandle -``` - -Start a new PTY (pseudo-terminal). - -**Arguments**: - -- `size`: Size of the PTY -- `user`: User to use for the PTY -- `cwd`: Working directory for the PTY -- `envs`: Environment variables for the PTY -- `timeout`: Timeout for the PTY in **seconds** -- `request_timeout`: Timeout for the request in **seconds** - -**Returns**: - -Handle to interact with the PTY - - - -### resize - -```python -def resize(pid: int, - size: PtySize, - request_timeout: Optional[float] = None) -> None -``` - -Resize PTY. - -Call this when the terminal window is resized and the number of columns and rows has changed. - -**Arguments**: - -- `pid`: Process ID of the PTY -- `size`: New size of the PTY -- `request_timeout`: Timeout for the request in **seconds**s - - - - - - -## Sandbox - -```python -class Sandbox(SandboxApi) -``` - -E2B cloud sandbox is a secure and isolated cloud environment. - -The sandbox allows you to: -- Access Linux OS -- Create, list, and delete files and directories -- Run commands -- Run isolated code -- Access the internet - -Check docs [here](https://e2b.dev/docs). - -Use the `Sandbox.create()` to create a new sandbox. - -**Example**: - -```python -from e2b import Sandbox - -sandbox = Sandbox.create() -``` - - - -### files - -```python -@property -def files() -> Filesystem -``` - -Module for interacting with the sandbox filesystem. - - - -### commands - -```python -@property -def commands() -> Commands -``` - -Module for running commands in the sandbox. - - - -### pty - -```python -@property -def pty() -> Pty -``` - -Module for interacting with the sandbox pseudo-terminal. - - - -### \_\_init\_\_ - -```python -def __init__(**opts: Unpack[SandboxOpts]) -``` - -:deprecated: This constructor is deprecated - -Use `Sandbox.create()` to create a new sandbox instead. - - - -### is\_running - -```python -def is_running(request_timeout: Optional[float] = None) -> bool -``` - -Check if the sandbox is running. - -**Arguments**: - -- `request_timeout`: Timeout for the request in **seconds** - -**Returns**: - -`True` if the sandbox is running, `False` otherwise -Example -```python -sandbox = Sandbox.create() -sandbox.is_running() # Returns True - -sandbox.kill() -sandbox.is_running() # Returns False -``` - - - -### create - -```python -@classmethod -def create(cls, - template: Optional[str] = None, - timeout: Optional[int] = None, - metadata: Optional[Dict[str, str]] = None, - envs: Optional[Dict[str, str]] = None, - secure: bool = True, - allow_internet_access: bool = True, - mcp: Optional[McpServer] = None, - network: Optional[SandboxNetworkOpts] = None, - **opts: Unpack[ApiParams]) -> Self -``` - -Create a new sandbox. - -By default, the sandbox is created from the default `base` sandbox template. - -**Arguments**: - -- `template`: Sandbox template name or ID -- `timeout`: Timeout for the sandbox in **seconds**, default to 300 seconds. The maximum time a sandbox can be kept alive is 24 hours (86_400 seconds) for Pro users and 1 hour (3_600 seconds) for Hobby users. -- `metadata`: Custom metadata for the sandbox -- `envs`: Custom environment variables for the sandbox -- `secure`: Envd is secured with access token and cannot be used without it, defaults to `True`. -- `allow_internet_access`: Allow sandbox to access the internet, defaults to `True`. If set to `False`, it works the same as setting network `deny_out` to `[0.0.0.0/0]`. -- `mcp`: MCP server to enable in the sandbox -- `network`: Sandbox network configuration - -**Returns**: - -A Sandbox instance for the new sandbox -Use this method instead of using the constructor to create a new sandbox. - - - -### connect - -```python -@overload -def connect(timeout: Optional[int] = None, **opts: Unpack[ApiParams]) -> Self -``` - -Connect to a sandbox. If the sandbox is paused, it will be automatically resumed. - -Sandbox must be either running or be paused. - -With sandbox ID you can connect to the same sandbox from different places or environments (serverless functions, etc). - -**Arguments**: - -- `timeout`: Timeout for the sandbox in **seconds** -For running sandboxes, the timeout will update only if the new timeout is longer than the existing one. - -**Returns**: - -A running sandbox instance -@example -```python -sandbox = Sandbox.create() -sandbox.beta_pause() - -same_sandbox = sandbox.connect() - - - -### connect - -```python -@overload -@classmethod -def connect(cls, - sandbox_id: str, - timeout: Optional[int] = None, - **opts: Unpack[ApiParams]) -> Self -``` - -Connect to a sandbox. If the sandbox is paused, it will be automatically resumed. - -Sandbox must be either running or be paused. - -With sandbox ID you can connect to the same sandbox from different places or environments (serverless functions, etc). - -**Arguments**: - -- `sandbox_id`: Sandbox ID -- `timeout`: Timeout for the sandbox in **seconds**. -For running sandboxes, the timeout will update only if the new timeout is longer than the existing one. - -**Returns**: - -A running sandbox instance -@example -```python -sandbox = Sandbox.create() -Sandbox.beta_pause(sandbox.sandbox_id) - -same_sandbox = Sandbox.connect(sandbox.sandbox_id) -``` - - - -### connect - -```python -@class_method_variant("_cls_connect") -def connect(timeout: Optional[int] = None, **opts: Unpack[ApiParams]) -> Self -``` - -Connect to a sandbox. If the sandbox is paused, it will be automatically resumed. - -Sandbox must be either running or be paused. - -With sandbox ID you can connect to the same sandbox from different places or environments (serverless functions, etc). - -**Arguments**: - -- `timeout`: Timeout for the sandbox in **seconds**. -For running sandboxes, the timeout will update only if the new timeout is longer than the existing one. - -**Returns**: - -A running sandbox instance -@example -```python -sandbox = Sandbox.create() -sandbox.beta_pause() - -same_sandbox = sandbox.connect() -``` - - - -### kill - -```python -@overload -def kill(**opts: Unpack[ApiParams]) -> bool -``` - -Kill the sandbox. - -**Returns**: - -`True` if the sandbox was killed, `False` if the sandbox was not found - - - -### kill - -```python -@overload -@staticmethod -def kill(sandbox_id: str, **opts: Unpack[ApiParams]) -> bool -``` - -Kill the sandbox specified by sandbox ID. - -**Arguments**: - -- `sandbox_id`: Sandbox ID - -**Returns**: - -`True` if the sandbox was killed, `False` if the sandbox was not found - - - -### kill - -```python -@class_method_variant("_cls_kill") -def kill(**opts: Unpack[ApiParams]) -> bool -``` - -Kill the sandbox specified by sandbox ID. - -**Returns**: - -`True` if the sandbox was killed, `False` if the sandbox was not found - - - -### set\_timeout - -```python -@overload -def set_timeout(timeout: int, **opts: Unpack[ApiParams]) -> None -``` - -Set the timeout of the sandbox. - -After the timeout expires, the sandbox will be automatically killed. -This method can extend or reduce the sandbox timeout set when creating the sandbox or from the last call to `.set_timeout`. - -The maximum time a sandbox can be kept alive is 24 hours (86_400 seconds) for Pro users and 1 hour (3_600 seconds) for Hobby users. - -**Arguments**: - -- `timeout`: Timeout for the sandbox in **seconds** - - - -### set\_timeout - -```python -@overload -@staticmethod -def set_timeout(sandbox_id: str, timeout: int, - **opts: Unpack[ApiParams]) -> None -``` - -Set the timeout of the sandbox specified by sandbox ID. - -After the timeout expires, the sandbox will be automatically killed. -This method can extend or reduce the sandbox timeout set when creating the sandbox or from the last call to `.set_timeout`. - -The maximum time a sandbox can be kept alive is 24 hours (86_400 seconds) for Pro users and 1 hour (3_600 seconds) for Hobby users. - -**Arguments**: - -- `sandbox_id`: Sandbox ID -- `timeout`: Timeout for the sandbox in **seconds** - - - -### set\_timeout - -```python -@class_method_variant("_cls_set_timeout") -def set_timeout(timeout: int, **opts: Unpack[ApiParams]) -> None -``` - -Set the timeout of the sandbox. - -After the timeout expires, the sandbox will be automatically killed. -This method can extend or reduce the sandbox timeout set when creating the sandbox or from the last call to `.set_timeout`. - -The maximum time a sandbox can be kept alive is 24 hours (86_400 seconds) for Pro users and 1 hour (3_600 seconds) for Hobby users. - -**Arguments**: - -- `timeout`: Timeout for the sandbox in **seconds** - - - -### get\_info - -```python -@overload -def get_info(**opts: Unpack[ApiParams]) -> SandboxInfo -``` - -Get sandbox information like sandbox ID, template, metadata, started at/end at date. - -**Returns**: - -Sandbox info - - - -### get\_info - -```python -@overload -@staticmethod -def get_info(sandbox_id: str, **opts: Unpack[ApiParams]) -> SandboxInfo -``` - -Get sandbox information like sandbox ID, template, metadata, started at/end at date. - -**Arguments**: - -- `sandbox_id`: Sandbox ID - -**Returns**: - -Sandbox info - - - -### get\_info - -```python -@class_method_variant("_cls_get_info") -def get_info(**opts: Unpack[ApiParams]) -> SandboxInfo -``` - -Get sandbox information like sandbox ID, template, metadata, started at/end at date. - -**Returns**: - -Sandbox info - - - -### get\_metrics - -```python -@overload -def get_metrics(start: Optional[datetime.datetime] = None, - end: Optional[datetime.datetime] = None, - **opts: Unpack[ApiParams]) -> List[SandboxMetrics] -``` - -Get the metrics of the current sandbox. - -**Arguments**: - -- `start`: Start time for the metrics, defaults to the start of the sandbox -- `end`: End time for the metrics, defaults to the current time - -**Returns**: - -List of sandbox metrics containing CPU, memory and disk usage information - - - -### get\_metrics - -```python -@overload -@staticmethod -def get_metrics(sandbox_id: str, - start: Optional[datetime.datetime] = None, - end: Optional[datetime.datetime] = None, - **opts: Unpack[ApiParams]) -> List[SandboxMetrics] -``` - -Get the metrics of the sandbox specified by sandbox ID. - -**Arguments**: - -- `sandbox_id`: Sandbox ID -- `start`: Start time for the metrics, defaults to the start of the sandbox -- `end`: End time for the metrics, defaults to the current time - -**Returns**: - -List of sandbox metrics containing CPU, memory and disk usage information - - - -### get\_metrics - -```python -@class_method_variant("_cls_get_metrics") -def get_metrics(start: Optional[datetime.datetime] = None, - end: Optional[datetime.datetime] = None, - **opts: Unpack[ApiParams]) -> List[SandboxMetrics] -``` - -Get the metrics of the sandbox specified by sandbox ID. - -**Arguments**: - -- `start`: Start time for the metrics, defaults to the start of the sandbox -- `end`: End time for the metrics, defaults to the current time - -**Returns**: - -List of sandbox metrics containing CPU, memory and disk usage information - - - -### beta\_create - -```python -@classmethod -def beta_create(cls, - template: Optional[str] = None, - timeout: Optional[int] = None, - auto_pause: bool = False, - metadata: Optional[Dict[str, str]] = None, - envs: Optional[Dict[str, str]] = None, - secure: bool = True, - allow_internet_access: bool = True, - mcp: Optional[McpServer] = None, - **opts: Unpack[ApiParams]) -> Self -``` - -[BETA] This feature is in beta and may change in the future. - -Create a new sandbox. - -By default, the sandbox is created from the default `base` sandbox template. - -**Arguments**: - -- `template`: Sandbox template name or ID -- `timeout`: Timeout for the sandbox in **seconds**, default to 300 seconds. The maximum time a sandbox can be kept alive is 24 hours (86_400 seconds) for Pro users and 1 hour (3_600 seconds) for Hobby users. -- `auto_pause`: Automatically pause the sandbox after the timeout expires. Defaults to `False`. -- `metadata`: Custom metadata for the sandbox -- `envs`: Custom environment variables for the sandbox -- `secure`: Envd is secured with access token and cannot be used without it, defaults to `True`. -- `allow_internet_access`: Allow sandbox to access the internet, defaults to `True`. -- `mcp`: MCP server to enable in the sandbox - -**Returns**: - -A Sandbox instance for the new sandbox -Use this method instead of using the constructor to create a new sandbox. - - - -### beta\_pause - -```python -@overload -def beta_pause(**opts: Unpack[ApiParams]) -> None -``` - -[BETA] This feature is in beta and may change in the future. - -Pause the sandbox. - - - -### beta\_pause - -```python -@overload -@classmethod -def beta_pause(cls, sandbox_id: str, **opts: Unpack[ApiParams]) -> None -``` - -[BETA] This feature is in beta and may change in the future. - -Pause the sandbox specified by sandbox ID. - -**Arguments**: - -- `sandbox_id`: Sandbox ID - - - -### beta\_pause - -```python -@class_method_variant("_cls_pause") -def beta_pause(**opts: Unpack[ApiParams]) -> None -``` - -[BETA] This feature is in beta and may change in the future. - -Pause the sandbox. - -**Returns**: - -Sandbox ID that can be used to resume the sandbox - - - -### get\_mcp\_token - -```python -def get_mcp_token() -> Optional[str] -``` - -Get the MCP token for the sandbox. - -**Returns**: - -MCP token for the sandbox, or None if MCP is not enabled. diff --git a/docs/sdk-reference/python-sdk/v2.8.0/template.mdx b/docs/sdk-reference/python-sdk/v2.8.0/template.mdx deleted file mode 100644 index 9ac3cc8..0000000 --- a/docs/sdk-reference/python-sdk/v2.8.0/template.mdx +++ /dev/null @@ -1,1686 +0,0 @@ ---- -sidebarTitle: "Template" -mode: "center" ---- - - - - - - -## DockerfFileFinalParserInterface - -```python -class DockerfFileFinalParserInterface(Protocol) -``` - -Protocol defining the final interface for Dockerfile parsing callbacks. - - - -## DockerfileParserInterface - -```python -class DockerfileParserInterface(Protocol) -``` - -Protocol defining the interface for Dockerfile parsing callbacks. - - - -### run\_cmd - -```python -def run_cmd(command: Union[str, List[str]], - user: Optional[str] = None) -> "DockerfileParserInterface" -``` - -Handle RUN instruction. - - - -### copy - -```python -def copy(src: Union[str, List[CopyItem]], - dest: Optional[str] = None, - force_upload: Optional[Literal[True]] = None, - resolve_symlinks: Optional[bool] = None, - user: Optional[str] = None, - mode: Optional[int] = None) -> "DockerfileParserInterface" -``` - -Handle COPY instruction. - - - -### set\_workdir - -```python -def set_workdir(workdir: str) -> "DockerfileParserInterface" -``` - -Handle WORKDIR instruction. - - - -### set\_user - -```python -def set_user(user: str) -> "DockerfileParserInterface" -``` - -Handle USER instruction. - - - -### set\_envs - -```python -def set_envs(envs: Dict[str, str]) -> "DockerfileParserInterface" -``` - -Handle ENV instruction. - - - -### set\_start\_cmd - -```python -def set_start_cmd(start_cmd: str, - ready_cmd: str) -> "DockerfFileFinalParserInterface" -``` - -Handle CMD/ENTRYPOINT instruction. - - - -### parse\_dockerfile - -```python -def parse_dockerfile(dockerfile_content_or_path: str, - template_builder: DockerfileParserInterface) -> str -``` - -Parse a Dockerfile and convert it to Template SDK format. - -**Arguments**: - -- `dockerfile_content_or_path`: Either the Dockerfile content as a string, or a path to a Dockerfile file -- `template_builder`: Interface providing template builder methods - -**Raises**: - -- `ValueError`: If the Dockerfile is invalid or unsupported - -**Returns**: - -The base image from the Dockerfile - - - - - - -## InstructionType - -```python -class InstructionType(str, Enum) -``` - -Types of instructions that can be used in a template. - - - -## CopyItem - -```python -class CopyItem(TypedDict) -``` - -Configuration for a single file/directory copy operation. - - - -## Instruction - -```python -class Instruction(TypedDict) -``` - -Represents a single instruction in the template build process. - - - -## GenericDockerRegistry - -```python -class GenericDockerRegistry(TypedDict) -``` - -Configuration for a generic Docker registry with basic authentication. - - - -## AWSRegistry - -```python -class AWSRegistry(TypedDict) -``` - -Configuration for AWS Elastic Container Registry (ECR). - - - -## GCPRegistry - -```python -class GCPRegistry(TypedDict) -``` - -Configuration for Google Container Registry (GCR) or Artifact Registry. - - - -## TemplateType - -```python -class TemplateType(TypedDict) -``` - -Internal representation of a template for the E2B build API. - - - -## BuildInfo - -```python -@dataclass -class BuildInfo() -``` - -Information about a built template. - - - - - - -## LogEntry - -```python -@dataclass -class LogEntry() -``` - -Represents a single log entry from the template build process. - - - -## LogEntryStart - -```python -@dataclass -class LogEntryStart(LogEntry) -``` - -Special log entry indicating the start of a build process. - - - -## LogEntryEnd - -```python -@dataclass -class LogEntryEnd(LogEntry) -``` - -Special log entry indicating the end of a build process. - - - -### TIMER\_UPDATE\_INTERVAL\_MS - -Default minimum log level to display. - - - -### DEFAULT\_LEVEL - -Colored labels for each log level. - - - -### levels - -Numeric ordering of log levels for comparison (lower = less severe). - - - -### set\_interval - -```python -def set_interval(func, interval) -``` - -Returns a stop function that can be called to cancel the interval. - -Similar to JavaScript's setInterval. - -**Arguments**: - -- `func`: Function to execute at each interval -- `interval`: Interval duration in **seconds** - -**Returns**: - -Stop function that can be called to cancel the interval - - - -### default\_build\_logger - -```python -def default_build_logger( - min_level: Optional[LogEntryLevel] = None -) -> Callable[[LogEntry], None] -``` - -Create a default build logger with animated timer display. - -**Arguments**: - -- `min_level`: Minimum log level to display (default: 'info') - -**Returns**: - -Logger function that accepts LogEntry instances -Example -```python -from e2b import Template, default_build_logger - -template = Template().from_python_image() - -``` - - - - -Special step name for the finalization phase of template building. -This is the last step that runs after all user-defined instructions. - - - -### FINALIZE\_STEP\_NAME - -Special step name for the base image phase of template building. -This is the first step that sets up the base image. - - - -### BASE\_STEP\_NAME - -Stack trace depth for capturing caller information. - -Depth levels: -1. TemplateClass -2. Caller method (e.g., copy(), from_image(), etc.) - -This depth is used to determine the original caller's location -for stack traces. - - - -### STACK\_TRACE\_DEPTH - -Default setting for whether to resolve symbolic links when copying files. -When False, symlinks are copied as symlinks rather than following them. - - - - - - -## ReadyCmd - -```python -class ReadyCmd() -``` - -Wrapper class for ready check commands. - - - -### wait\_for\_port - -```python -def wait_for_port(port: int) -``` - -Wait for a port to be listening. - -Uses `ss` command to check if a port is open and listening. - -**Arguments**: - -- `port`: Port number to wait for - -**Returns**: - -ReadyCmd that checks for the port -Example -```python -from e2b import Template, wait_for_port - -template = ( - Template() - .from_python_image() - .set_start_cmd('python -m http.server 8000', wait_for_port(8000)) -) -``` - - - -### wait\_for\_url - -```python -def wait_for_url(url: str, status_code: int = 200) -``` - -Wait for a URL to return a specific HTTP status code. - -Uses `curl` to make HTTP requests and check the response status. - -**Arguments**: - -- `url`: URL to check (e.g., 'http://localhost:3000/health') -- `status_code`: Expected HTTP status code (default: 200) - -**Returns**: - -ReadyCmd that checks the URL -Example -```python -from e2b import Template, wait_for_url - -template = ( - Template() - .from_node_image() - .set_start_cmd('npm start', wait_for_url('http://localhost:3000/health')) -) -``` - - - -### wait\_for\_process - -```python -def wait_for_process(process_name: str) -``` - -Wait for a process with a specific name to be running. - -Uses `pgrep` to check if a process exists. - -**Arguments**: - -- `process_name`: Name of the process to wait for - -**Returns**: - -ReadyCmd that checks for the process -Example -```python -from e2b import Template, wait_for_process - -template = ( - Template() - .from_base_image() - .set_start_cmd('./my-daemon', wait_for_process('my-daemon')) -) -``` - - - -### wait\_for\_file - -```python -def wait_for_file(filename: str) -``` - -Wait for a file to exist. - -Uses shell test command to check file existence. - -**Arguments**: - -- `filename`: Path to the file to wait for - -**Returns**: - -ReadyCmd that checks for the file -Example -```python -from e2b import Template, wait_for_file - -template = ( - Template() - .from_base_image() - .set_start_cmd('./init.sh', wait_for_file('/tmp/ready')) -) -``` - - - -### wait\_for\_timeout - -```python -def wait_for_timeout(timeout: int) -``` - -Wait for a specified timeout before considering the sandbox ready. - -Uses `sleep` command to wait for a fixed duration. - -**Arguments**: - -- `timeout`: Time to wait in **milliseconds** (minimum: 1000ms / 1 second) - -**Returns**: - -ReadyCmd that waits for the specified duration -Example -```python -from e2b import Template, wait_for_timeout - -template = ( - Template() - .from_node_image() - .set_start_cmd('npm start', wait_for_timeout(5000)) # Wait 5 seconds -) -``` - - - - - - -### read\_dockerignore - -```python -def read_dockerignore(context_path: str) -> List[str] -``` - -Read and parse a .dockerignore file. - -**Arguments**: - -- `context_path`: Directory path containing the .dockerignore file - -**Returns**: - -Array of ignore patterns (empty lines and comments are filtered out) - - - -### get\_all\_files\_in\_path - -```python -def get_all_files_in_path(src: str, - context_path: str, - ignore_patterns: List[str], - include_directories: bool = True) -> List[str] -``` - -Get all files for a given path and ignore patterns. - -**Arguments**: - -- `src`: Path to the source directory -- `context_path`: Base directory for resolving relative paths -- `ignore_patterns`: Ignore patterns -- `include_directories`: Whether to include directories - -**Returns**: - -Array of files - - - -### calculate\_files\_hash - -```python -def calculate_files_hash(src: str, dest: str, context_path: str, - ignore_patterns: List[str], resolve_symlinks: bool, - stack_trace: Optional[TracebackType]) -> str -``` - -Calculate a hash of files being copied to detect changes for cache invalidation. - -The hash includes file content, metadata (mode, size), and relative paths. -Note: uid, gid, and mtime are excluded to ensure stable hashes across environments. - -**Arguments**: - -- `src`: Source path pattern for files to copy -- `dest`: Destination path where files will be copied -- `context_path`: Base directory for resolving relative paths -- `ignore_patterns`: Glob patterns to ignore -- `resolve_symlinks`: Whether to resolve symbolic links when hashing -- `stack_trace`: Optional stack trace for error reporting - -**Raises**: - -- `ValueError`: If no files match the source pattern - -**Returns**: - -Hex string hash of all files - - - -### tar\_file\_stream - -```python -def tar_file_stream(file_name: str, file_context_path: str, - ignore_patterns: List[str], - resolve_symlinks: bool) -> io.BytesIO -``` - -Create a tar stream of files matching a pattern. - -**Arguments**: - -- `file_name`: Glob pattern for files to include -- `file_context_path`: Base directory for resolving file paths -- `ignore_patterns`: Ignore patterns -- `resolve_symlinks`: Whether to resolve symbolic links - -**Returns**: - -Tar stream - - - -### strip\_ansi\_escape\_codes - -```python -def strip_ansi_escape_codes(text: str) -> str -``` - -Strip ANSI escape codes from a string. - -Source: https://github.com/chalk/ansi-regex/blob/main/index.js - -**Arguments**: - -- `text`: String with ANSI escape codes - -**Returns**: - -String without ANSI escape codes - - - -### get\_caller\_frame - -```python -def get_caller_frame(depth: int) -> Optional[FrameType] -``` - -Get the caller's stack frame at a specific depth. - -This is used to provide better error messages and debugging information -by tracking where template methods were called from in user code. - -**Arguments**: - -- `depth`: The depth of the stack trace to retrieve - -**Returns**: - -The caller frame, or None if not available - - - -### get\_caller\_directory - -```python -def get_caller_directory(depth: int) -> Optional[str] -``` - -Get the directory of the caller at a specific stack depth. - -This is used to determine the file_context_path when creating a template, -so file paths are resolved relative to the user's template file location. - -**Arguments**: - -- `depth`: The depth of the stack trace - -**Returns**: - -The caller's directory path, or None if not available - - - -### pad\_octal - -```python -def pad_octal(mode: int) -> str -``` - -Convert a numeric file mode to a zero-padded octal string. - -**Arguments**: - -- `mode`: File mode as a number (e.g., 493 for 0o755) - -**Returns**: - -Zero-padded 4-digit octal string (e.g., "0755") -Example -```python -pad_octal(0o755) # Returns "0755" -pad_octal(0o644) # Returns "0644" -``` - - - -### get\_build\_step\_index - -```python -def get_build_step_index(step: str, stack_traces_length: int) -> int -``` - -Get the array index for a build step based on its name. - -Special steps: -- BASE_STEP_NAME: Returns 0 (first step) -- FINALIZE_STEP_NAME: Returns the last index -- Numeric strings: Converted to number - -**Arguments**: - -- `step`: Build step name or number as string -- `stack_traces_length`: Total number of stack traces (used for FINALIZE_STEP_NAME) - -**Returns**: - -Index for the build step - - - -### read\_gcp\_service\_account\_json - -```python -def read_gcp_service_account_json(context_path: str, - path_or_content: Union[str, dict]) -> str -``` - -Read GCP service account JSON from a file or object. - -**Arguments**: - -- `context_path`: Base directory for resolving relative file paths -- `path_or_content`: Either a path to a JSON file or a service account object - -**Returns**: - -Service account JSON as a string - - - - - - -## TemplateBuilder - -```python -class TemplateBuilder() -``` - -Builder class for adding instructions to an E2B template. - -All methods return self to allow method chaining. - - - -### copy - -```python -def copy(src: Union[Union[str, Path], List[Union[str, Path]]], - dest: Union[str, Path], - force_upload: Optional[Literal[True]] = None, - user: Optional[str] = None, - mode: Optional[int] = None, - resolve_symlinks: Optional[bool] = None) -> "TemplateBuilder" -``` - -Copy files or directories from the local filesystem into the template. - -**Arguments**: - -- `src`: Source file(s) or directory path(s) to copy -- `dest`: Destination path in the template -- `force_upload`: Force upload even if files are cached -- `user`: User and optionally group (user:group) to own the files -- `mode`: File permissions in octal format (e.g., 0o755) -- `resolve_symlinks`: Whether to resolve symlinks - -**Returns**: - -`TemplateBuilder` class -Example -```python -template.copy('requirements.txt', '/home/user/') -template.copy(['app.py', 'config.py'], '/app/', mode=0o755) -``` - - - -### copy\_items - -```python -def copy_items(items: List[CopyItem]) -> "TemplateBuilder" -``` - -Copy multiple files or directories using a list of copy items. - -**Arguments**: - -- `items`: List of CopyItem dictionaries with src, dest, and optional parameters - -**Returns**: - -`TemplateBuilder` class -Example -```python -template.copy_items([ - {'src': 'app.py', 'dest': '/app/'}, - {'src': 'config.py', 'dest': '/app/', 'mode': 0o644} -]) -``` - - - -### remove - -```python -def remove(path: Union[Union[str, Path], List[Union[str, Path]]], - force: bool = False, - recursive: bool = False, - user: Optional[str] = None) -> "TemplateBuilder" -``` - -Remove files or directories in the template. - -**Arguments**: - -- `path`: File(s) or directory path(s) to remove -- `force`: Force removal without prompting -- `recursive`: Remove directories recursively -- `user`: User to run the command as - -**Returns**: - -`TemplateBuilder` class -Example -```python -template.remove('/tmp/cache', recursive=True, force=True) -template.remove('/tmp/cache', recursive=True, force=True, user='root') -``` - - - -### rename - -```python -def rename(src: Union[str, Path], - dest: Union[str, Path], - force: bool = False, - user: Optional[str] = None) -> "TemplateBuilder" -``` - -Rename or move a file or directory in the template. - -**Arguments**: - -- `src`: Source path -- `dest`: Destination path -- `force`: Force rename without prompting -- `user`: User to run the command as - -**Returns**: - -`TemplateBuilder` class -Example -```python -template.rename('/tmp/old.txt', '/tmp/new.txt') -template.rename('/tmp/old.txt', '/tmp/new.txt', user='root') -``` - - - -### make\_dir - -```python -def make_dir(path: Union[Union[str, Path], List[Union[str, Path]]], - mode: Optional[int] = None, - user: Optional[str] = None) -> "TemplateBuilder" -``` - -Create directory(ies) in the template. - -**Arguments**: - -- `path`: Directory path(s) to create -- `mode`: Directory permissions in octal format (e.g., 0o755) -- `user`: User to run the command as - -**Returns**: - -`TemplateBuilder` class -Example -```python -template.make_dir('/app/data', mode=0o755) -template.make_dir(['/app/logs', '/app/cache']) -template.make_dir('/app/data', mode=0o755, user='root') -``` - - - -### make\_symlink - -```python -def make_symlink(src: Union[str, Path], - dest: Union[str, Path], - user: Optional[str] = None, - force: bool = False) -> "TemplateBuilder" -``` - -Create a symbolic link in the template. - -**Arguments**: - -- `src`: Source path (target of the symlink) -- `dest`: Destination path (location of the symlink) -- `user`: User to run the command as -- `force`: Force symlink without prompting - -**Returns**: - -`TemplateBuilder` class -Example -```python -template.make_symlink('/usr/bin/python3', '/usr/bin/python') -template.make_symlink('/usr/bin/python3', '/usr/bin/python', user='root') -template.make_symlink('/usr/bin/python3', '/usr/bin/python', force=True) -``` - - - -### run\_cmd - -```python -def run_cmd(command: Union[str, List[str]], - user: Optional[str] = None) -> "TemplateBuilder" -``` - -Run a shell command during template build. - -**Arguments**: - -- `command`: Command string or list of commands to run (joined with &&) -- `user`: User to run the command as - -**Returns**: - -`TemplateBuilder` class -Example -```python -template.run_cmd('apt-get update') -template.run_cmd(['pip install numpy', 'pip install pandas']) -template.run_cmd('apt-get install vim', user='root') -``` - - - -### set\_workdir - -```python -def set_workdir(workdir: Union[str, Path]) -> "TemplateBuilder" -``` - -Set the working directory for subsequent commands in the template. - -**Arguments**: - -- `workdir`: Path to set as the working directory - -**Returns**: - -`TemplateBuilder` class -Example -```python -template.set_workdir('/app') -``` - - - -### set\_user - -```python -def set_user(user: str) -> "TemplateBuilder" -``` - -Set the user for subsequent commands in the template. - -**Arguments**: - -- `user`: Username to set - -**Returns**: - -`TemplateBuilder` class -Example -```python -template.set_user('root') -``` - - - -### pip\_install - -```python -def pip_install(packages: Optional[Union[str, List[str]]] = None, - g: bool = True) -> "TemplateBuilder" -``` - -Install Python packages using pip. - -**Arguments**: - -- `packages`: Package name(s) to install. If None, runs 'pip install .' in the current directory -- `g`: Install packages globally (default: True). If False, installs for user only - -**Returns**: - -`TemplateBuilder` class -Example -```python -template.pip_install('numpy') -template.pip_install(['pandas', 'scikit-learn']) -template.pip_install('numpy', g=False) # Install for user only -template.pip_install() # Installs from current directory -``` - - - -### npm\_install - -```python -def npm_install(packages: Optional[Union[str, List[str]]] = None, - g: Optional[bool] = False, - dev: Optional[bool] = False) -> "TemplateBuilder" -``` - -Install Node.js packages using npm. - -**Arguments**: - -- `packages`: Package name(s) to install. If None, installs from package.json -- `g`: Install packages globally -- `dev`: Install packages as dev dependencies - -**Returns**: - -`TemplateBuilder` class -Example -```python -template.npm_install('express') -template.npm_install(['lodash', 'axios']) -template.npm_install('typescript', g=True) -template.npm_install() # Installs from package.json -``` - - - -### bun\_install - -```python -def bun_install(packages: Optional[Union[str, List[str]]] = None, - g: Optional[bool] = False, - dev: Optional[bool] = False) -> "TemplateBuilder" -``` - -Install Bun packages using bun. - -**Arguments**: - -- `packages`: Package name(s) to install. If None, installs from package.json -- `g`: Install packages globally -- `dev`: Install packages as dev dependencies - -**Returns**: - -`TemplateBuilder` class -Example -```python -template.bun_install('express') -template.bun_install(['lodash', 'axios']) -template.bun_install('tsx', g=True) -template.bun_install('typescript', dev=True) -template.bun_install() // Installs from package.json -``` - - - -### apt\_install - -```python -def apt_install(packages: Union[str, List[str]], - no_install_recommends: bool = False) -> "TemplateBuilder" -``` - -Install system packages using apt-get. - -**Arguments**: - -- `packages`: Package name(s) to install -- `no_install_recommends`: Whether to install recommended packages - -**Returns**: - -`TemplateBuilder` class -Example -```python -template.apt_install('vim') -template.apt_install(['git', 'curl', 'wget']) -``` - - - -### add\_mcp\_server - -```python -def add_mcp_server(servers: Union[str, List[str]]) -> "TemplateBuilder" -``` - -Install MCP servers using mcp-gateway. - -Note: Requires a base image with mcp-gateway pre-installed (e.g., mcp-gateway). - -**Arguments**: - -- `servers`: MCP server name(s) - -**Returns**: - -`TemplateBuilder` class -Example -```python -template.add_mcp_server('exa') -template.add_mcp_server(['brave', 'firecrawl', 'duckduckgo']) -``` - - - -### git\_clone - -```python -def git_clone(url: str, - path: Optional[Union[str, Path]] = None, - branch: Optional[str] = None, - depth: Optional[int] = None, - user: Optional[str] = None) -> "TemplateBuilder" -``` - -Clone a git repository into the template. - -**Arguments**: - -- `url`: Git repository URL -- `path`: Destination path for the clone -- `branch`: Branch to clone -- `depth`: Clone depth for shallow clones -- `user`: User to run the command as - -**Returns**: - -`TemplateBuilder` class -Example -```python -template.git_clone('https://github.com/user/repo.git', '/app/repo') -template.git_clone('https://github.com/user/repo.git', branch='main', depth=1) -template.git_clone('https://github.com/user/repo.git', '/app/repo', user='root') -``` - - - -### beta\_dev\_container\_prebuild - -```python -def beta_dev_container_prebuild( - devcontainer_directory: Union[str, Path]) -> "TemplateBuilder" -``` - -Prebuild a devcontainer from the specified directory during the build process. - -**Arguments**: - -- `devcontainer_directory`: Path to the devcontainer directory - -**Returns**: - -`TemplateBuilder` class -Example -```python -template.git_clone('https://myrepo.com/project.git', '/my-devcontainer') -template.beta_dev_container_prebuild('/my-devcontainer') -``` - - - -### beta\_set\_dev\_container\_start - -```python -def beta_set_dev_container_start( - devcontainer_directory: Union[str, Path]) -> "TemplateFinal" -``` - -Start a devcontainer from the specified directory and set it as the start command. - -This method returns `TemplateFinal`, which means it must be the last method in the chain. - -**Arguments**: - -- `devcontainer_directory`: Path to the devcontainer directory - -**Returns**: - -`TemplateFinal` class -Example -```python -template.git_clone('https://myrepo.com/project.git', '/my-devcontainer') -template.beta_set_devcontainer_start('/my-devcontainer') - -template.git_clone('https://myrepo.com/project.git', '/my-devcontainer') -template.beta_dev_container_prebuild('/my-devcontainer') -template.beta_set_dev_container_start('/my-devcontainer') -``` - - - -### set\_envs - -```python -def set_envs(envs: Dict[str, str]) -> "TemplateBuilder" -``` - -Set environment variables in the template. - -**Arguments**: - -- `envs`: Dictionary of environment variable names and values - -**Returns**: - -`TemplateBuilder` class -Example -```python -template.set_envs({'NODE_ENV': 'production', 'PORT': '8080'}) -``` - - - -### skip\_cache - -```python -def skip_cache() -> "TemplateBuilder" -``` - -Skip cache for all subsequent build instructions from this point. - -Call this before any instruction to force it and all following layers -to be rebuilt, ignoring any cached layers. - -**Returns**: - -`TemplateBuilder` class -Example -```python -template.skip_cache().run_cmd('apt-get update') -``` - - - -### set\_start\_cmd - -```python -def set_start_cmd(start_cmd: str, - ready_cmd: Union[str, ReadyCmd]) -> "TemplateFinal" -``` - -Set the command to start when the sandbox launches and the ready check command. - -**Arguments**: - -- `start_cmd`: Command to run when the sandbox starts -- `ready_cmd`: Command or ReadyCmd to check if the sandbox is ready - -**Returns**: - -`TemplateFinal` class -Example -```python -template.set_start_cmd( - 'python app.py', - 'curl http://localhost:8000/health' -) - -from e2b import wait_for_port, wait_for_url - -template.set_start_cmd( - 'python -m http.server 8000', - wait_for_port(8000) -) - -template.set_start_cmd( - 'npm start', - wait_for_url('http://localhost:3000/health', 200) -) -``` - - - -### set\_ready\_cmd - -```python -def set_ready_cmd(ready_cmd: Union[str, ReadyCmd]) -> "TemplateFinal" -``` - -Set the command to check if the sandbox is ready. - -**Arguments**: - -- `ready_cmd`: Command or ReadyCmd to check if the sandbox is ready - -**Returns**: - -`TemplateFinal` class -Example -```python -template.set_ready_cmd('curl http://localhost:8000/health') - -from e2b import wait_for_port, wait_for_file, wait_for_process - -template.set_ready_cmd(wait_for_port(3000)) - -template.set_ready_cmd(wait_for_file('/tmp/ready')) - -template.set_ready_cmd(wait_for_process('nginx')) -``` - - - -## TemplateFinal - -```python -class TemplateFinal() -``` - -Final template state after start/ready commands are set. - - - -## TemplateBase - -```python -class TemplateBase() -``` - -Base class for building E2B sandbox templates. - - - -### \_\_init\_\_ - -```python -def __init__(file_context_path: Optional[Union[str, Path]] = None, - file_ignore_patterns: Optional[List[str]] = None) -``` - -Create a new template builder instance. - -**Arguments**: - -- `file_context_path`: Base path for resolving relative file paths in copy operations -- `file_ignore_patterns`: List of glob patterns to ignore when copying files - - - -### skip\_cache - -```python -def skip_cache() -> "TemplateBase" -``` - -Skip cache for all subsequent build instructions from this point. - -**Returns**: - -`TemplateBase` class -Example -```python -template.skip_cache().from_python_image('3.11') -``` - - - -### from\_debian\_image - -```python -def from_debian_image(variant: str = "stable") -> TemplateBuilder -``` - -Start template from a Debian base image. - -**Arguments**: - -- `variant`: Debian image variant - -**Returns**: - -`TemplateBuilder` class -Example -```python -Template().from_debian_image('bookworm') -``` - - - -### from\_ubuntu\_image - -```python -def from_ubuntu_image(variant: str = "latest") -> TemplateBuilder -``` - -Start template from an Ubuntu base image. - -**Arguments**: - -- `variant`: Ubuntu image variant (default: 'latest') - -**Returns**: - -`TemplateBuilder` class -Example -```python -Template().from_ubuntu_image('24.04') -``` - - - -### from\_python\_image - -```python -def from_python_image(version: str = "3") -> TemplateBuilder -``` - -Start template from a Python base image. - -**Arguments**: - -- `version`: Python version (default: '3') - -**Returns**: - -`TemplateBuilder` class -Example -```python -Template().from_python_image('3') -``` - - - -### from\_node\_image - -```python -def from_node_image(variant: str = "lts") -> TemplateBuilder -``` - -Start template from a Node.js base image. - -**Arguments**: - -- `variant`: Node.js image variant (default: 'lts') - -**Returns**: - -`TemplateBuilder` class -Example -```python -Template().from_node_image('24') -``` - - - -### from\_bun\_image - -```python -def from_bun_image(variant: str = "latest") -> TemplateBuilder -``` - -Start template from a Bun base image. - -**Arguments**: - -- `variant`: Bun image variant (default: 'latest') - -**Returns**: - -`TemplateBuilder` class - - - -### from\_base\_image - -```python -def from_base_image() -> TemplateBuilder -``` - -Start template from the E2B base image (e2bdev/base:latest). - -**Returns**: - -`TemplateBuilder` class -Example -```python -Template().from_base_image() -``` - - - -### from\_image - -```python -def from_image(image: str, - username: Optional[str] = None, - password: Optional[str] = None) -> TemplateBuilder -``` - -Start template from a Docker image. - -**Arguments**: - -- `image`: Docker image name (e.g., 'ubuntu:24.04') -- `username`: Username for private registry authentication -- `password`: Password for private registry authentication - -**Returns**: - -`TemplateBuilder` class -Example -```python -Template().from_image('python:3') - -Template().from_image('myregistry.com/myimage:latest', username='user', password='pass') -``` - - - -### from\_template - -```python -def from_template(template: str) -> TemplateBuilder -``` - -Start template from an existing E2B template. - -**Arguments**: - -- `template`: E2B template ID or alias - -**Returns**: - -`TemplateBuilder` class -Example -```python -Template().from_template('my-base-template') -``` - - - -### from\_dockerfile - -```python -def from_dockerfile(dockerfile_content_or_path: str) -> TemplateBuilder -``` - -Parse a Dockerfile and convert it to Template SDK format. - -**Arguments**: - -- `dockerfile_content_or_path`: Either the Dockerfile content as a string, or a path to a Dockerfile file - -**Returns**: - -`TemplateBuilder` class -Example -```python -Template().from_dockerfile('Dockerfile') -Template().from_dockerfile('FROM python:3\nRUN pip install numpy') -``` - - - -### from\_aws\_registry - -```python -def from_aws_registry(image: str, access_key_id: str, secret_access_key: str, - region: str) -> TemplateBuilder -``` - -Start template from an AWS ECR registry image. - -**Arguments**: - -- `image`: Docker image name from AWS ECR -- `access_key_id`: AWS access key ID -- `secret_access_key`: AWS secret access key -- `region`: AWS region - -**Returns**: - -`TemplateBuilder` class -Example -```python -Template().from_aws_registry( - '123456789.dkr.ecr.us-west-2.amazonaws.com/myimage:latest', - access_key_id='AKIA...', - secret_access_key='...', - region='us-west-2' -) -``` - - - -### from\_gcp\_registry - -```python -def from_gcp_registry( - image: str, service_account_json: Union[str, dict]) -> TemplateBuilder -``` - -Start template from a GCP Artifact Registry or Container Registry image. - -**Arguments**: - -- `image`: Docker image name from GCP registry -- `service_account_json`: Service account JSON string, dict, or path to JSON file - -**Returns**: - -`TemplateBuilder` class -Example -```python -Template().from_gcp_registry( - 'gcr.io/myproject/myimage:latest', - service_account_json='path/to/service-account.json' -) -``` - - - -### to\_json - -```python -@staticmethod -def to_json(template: "TemplateClass") -> str -``` - -Convert a template to JSON representation. - -**Arguments**: - -- `template`: The template to convert (TemplateBuilder or TemplateFinal instance) - -**Returns**: - -JSON string representation of the template -Example -```python -template = Template().from_python_image('3').copy('app.py', '/app/') -json_str = TemplateBase.to_json(template) -``` - - - -### to\_dockerfile - -```python -@staticmethod -def to_dockerfile(template: "TemplateClass") -> str -``` - -Convert a template to Dockerfile format. - -Note: Templates based on other E2B templates cannot be converted to Dockerfile. - -**Arguments**: - -- `template`: The template to convert (TemplateBuilder or TemplateFinal instance) - -**Raises**: - -- `ValueError`: If the template is based on another E2B template or has no base image -Example -```python -template = Template().from_python_image('3').copy('app.py', '/app/') -dockerfile = TemplateBase.to_dockerfile(template) -``` - -**Returns**: - -Dockerfile string representation diff --git a/docs/sdk-reference/python-sdk/v2.8.0/template_async.mdx b/docs/sdk-reference/python-sdk/v2.8.0/template_async.mdx deleted file mode 100644 index 950d066..0000000 --- a/docs/sdk-reference/python-sdk/v2.8.0/template_async.mdx +++ /dev/null @@ -1,150 +0,0 @@ ---- -sidebarTitle: "Template Async" -mode: "center" ---- - - - - - - - - - -## AsyncTemplate - -```python -class AsyncTemplate(TemplateBase) -``` - -Asynchronous template builder for E2B sandboxes. - - - -### build - -```python -@staticmethod -async def build(template: TemplateClass, - alias: str, - cpu_count: int = 2, - memory_mb: int = 1024, - skip_cache: bool = False, - on_build_logs: Optional[Callable[[LogEntry], None]] = None, - api_key: Optional[str] = None, - domain: Optional[str] = None) -> BuildInfo -``` - -Build and deploy a template to E2B infrastructure. - -**Arguments**: - -- `template`: The template to build -- `alias`: Alias name for the template -- `cpu_count`: Number of CPUs allocated to the sandbox -- `memory_mb`: Amount of memory in MB allocated to the sandbox -- `skip_cache`: If True, forces a complete rebuild ignoring cache -- `on_build_logs`: Callback function to receive build logs during the build process -- `api_key`: E2B API key for authentication -- `domain`: Domain of the E2B API -Example -```python -from e2b import AsyncTemplate - -template = ( - AsyncTemplate() - .from_python_image('3') - .copy('requirements.txt', '/home/user/') - .run_cmd('pip install -r /home/user/requirements.txt') -) - -await AsyncTemplate.build( - template, - alias='my-python-env', - cpu_count=2, - memory_mb=1024 -) -``` - - - -### build\_in\_background - -```python -@staticmethod -async def build_in_background(template: TemplateClass, - alias: str, - cpu_count: int = 2, - memory_mb: int = 1024, - skip_cache: bool = False, - on_build_logs: Optional[Callable[[LogEntry], - None]] = None, - api_key: Optional[str] = None, - domain: Optional[str] = None) -> BuildInfo -``` - -Build and deploy a template to E2B infrastructure without waiting for completion. - -**Arguments**: - -- `template`: The template to build -- `alias`: Alias name for the template -- `cpu_count`: Number of CPUs allocated to the sandbox -- `memory_mb`: Amount of memory in MB allocated to the sandbox -- `skip_cache`: If True, forces a complete rebuild ignoring cache -- `api_key`: E2B API key for authentication -- `domain`: Domain of the E2B API - -**Returns**: - -BuildInfo containing the template ID and build ID -Example -```python -from e2b import AsyncTemplate - -template = ( - AsyncTemplate() - .from_python_image('3') - .run_cmd('echo "test"') - .set_start_cmd('echo "Hello"', 'sleep 1') -) - -build_info = await AsyncTemplate.build_in_background( - template, - alias='my-python-env', - cpu_count=2, - memory_mb=1024 -) -``` - - - -### get\_build\_status - -```python -@staticmethod -async def get_build_status(build_info: BuildInfo, - logs_offset: int = 0, - api_key: Optional[str] = None, - domain: Optional[str] = None) -``` - -Get the status of a build. - -**Arguments**: - -- `build_info`: Build identifiers returned from build_in_background -- `logs_offset`: Offset for fetching logs -- `api_key`: E2B API key for authentication -- `domain`: Domain of the E2B API - -**Returns**: - -TemplateBuild containing the build status and logs -Example -```python -from e2b import AsyncTemplate - -build_info = await AsyncTemplate.build_in_background(template, alias='my-template') -status = await AsyncTemplate.get_build_status(build_info, logs_offset=0) -``` diff --git a/docs/sdk-reference/python-sdk/v2.8.0/template_sync.mdx b/docs/sdk-reference/python-sdk/v2.8.0/template_sync.mdx deleted file mode 100644 index 6387438..0000000 --- a/docs/sdk-reference/python-sdk/v2.8.0/template_sync.mdx +++ /dev/null @@ -1,150 +0,0 @@ ---- -sidebarTitle: "Template Sync" -mode: "center" ---- - - - - - - - - - -## Template - -```python -class Template(TemplateBase) -``` - -Synchronous template builder for E2B sandboxes. - - - -### build - -```python -@staticmethod -def build(template: TemplateClass, - alias: str, - cpu_count: int = 2, - memory_mb: int = 1024, - skip_cache: bool = False, - on_build_logs: Optional[Callable[[LogEntry], None]] = None, - api_key: Optional[str] = None, - domain: Optional[str] = None) -> BuildInfo -``` - -Build and deploy a template to E2B infrastructure. - -**Arguments**: - -- `template`: The template to build -- `alias`: Alias name for the template -- `cpu_count`: Number of CPUs allocated to the sandbox -- `memory_mb`: Amount of memory in MB allocated to the sandbox -- `skip_cache`: If True, forces a complete rebuild ignoring cache -- `on_build_logs`: Callback function to receive build logs during the build process -- `api_key`: E2B API key for authentication -- `domain`: Domain of the E2B API -Example -```python -from e2b import Template - -template = ( - Template() - .from_python_image('3') - .copy('requirements.txt', '/home/user/') - .run_cmd('pip install -r /home/user/requirements.txt') -) - -Template.build( - template, - alias='my-python-env', - cpu_count=2, - memory_mb=1024 -) -``` - - - -### build\_in\_background - -```python -@staticmethod -def build_in_background(template: TemplateClass, - alias: str, - cpu_count: int = 2, - memory_mb: int = 1024, - skip_cache: bool = False, - on_build_logs: Optional[Callable[[LogEntry], - None]] = None, - api_key: Optional[str] = None, - domain: Optional[str] = None) -> BuildInfo -``` - -Build and deploy a template to E2B infrastructure without waiting for completion. - -**Arguments**: - -- `template`: The template to build -- `alias`: Alias name for the template -- `cpu_count`: Number of CPUs allocated to the sandbox -- `memory_mb`: Amount of memory in MB allocated to the sandbox -- `skip_cache`: If True, forces a complete rebuild ignoring cache -- `api_key`: E2B API key for authentication -- `domain`: Domain of the E2B API - -**Returns**: - -BuildInfo containing the template ID and build ID -Example -```python -from e2b import Template - -template = ( - Template() - .from_python_image('3') - .run_cmd('echo "test"') - .set_start_cmd('echo "Hello"', 'sleep 1') -) - -build_info = Template.build_in_background( - template, - alias='my-python-env', - cpu_count=2, - memory_mb=1024 -) -``` - - - -### get\_build\_status - -```python -@staticmethod -def get_build_status(build_info: BuildInfo, - logs_offset: int = 0, - api_key: Optional[str] = None, - domain: Optional[str] = None) -``` - -Get the status of a build. - -**Arguments**: - -- `build_info`: Build identifiers returned from build_in_background -- `logs_offset`: Offset for fetching logs -- `api_key`: E2B API key for authentication -- `domain`: Domain of the E2B API - -**Returns**: - -TemplateBuild containing the build status and logs -Example -```python -from e2b import Template - -build_info = Template.build_in_background(template, alias='my-template') -status = Template.get_build_status(build_info, logs_offset=0) -``` diff --git a/docs/sdk-reference/python-sdk/v2.8.1/exceptions.mdx b/docs/sdk-reference/python-sdk/v2.8.1/exceptions.mdx deleted file mode 100644 index d66f786..0000000 --- a/docs/sdk-reference/python-sdk/v2.8.1/exceptions.mdx +++ /dev/null @@ -1,117 +0,0 @@ ---- -sidebarTitle: "Exceptions" -mode: "center" ---- - - - - - - -## SandboxException - -```python -class SandboxException(Exception) -``` - -Base class for all sandbox errors. - -Raised when a general sandbox exception occurs. - - - -## TimeoutException - -```python -class TimeoutException(SandboxException) -``` - -Raised when a timeout occurs. - -The `unavailable` exception type is caused by sandbox timeout. - -The `canceled` exception type is caused by exceeding request timeout. - -The `deadline_exceeded` exception type is caused by exceeding the timeout for process, watch, etc. - -The `unknown` exception type is sometimes caused by the sandbox timeout when the request is not processed correctly. - - - -## InvalidArgumentException - -```python -class InvalidArgumentException(SandboxException) -``` - -Raised when an invalid argument is provided. - - - -## NotEnoughSpaceException - -```python -class NotEnoughSpaceException(SandboxException) -``` - -Raised when there is not enough disk space. - - - -## NotFoundException - -```python -class NotFoundException(SandboxException) -``` - -Raised when a resource is not found. - - - -## AuthenticationException - -```python -class AuthenticationException(Exception) -``` - -Raised when authentication fails. - - - -## TemplateException - -```python -class TemplateException(SandboxException) -``` - -Exception raised when the template uses old envd version. It isn't compatible with the new SDK. - - - -## RateLimitException - -```python -class RateLimitException(SandboxException) -``` - -Raised when the API rate limit is exceeded. - - - -## BuildException - -```python -class BuildException(Exception) -``` - -Raised when the build fails. - - - -## FileUploadException - -```python -class FileUploadException(BuildException) -``` - -Raised when the file upload fails. diff --git a/docs/sdk-reference/python-sdk/v2.8.1/logger.mdx b/docs/sdk-reference/python-sdk/v2.8.1/logger.mdx deleted file mode 100644 index 9fa3b18..0000000 --- a/docs/sdk-reference/python-sdk/v2.8.1/logger.mdx +++ /dev/null @@ -1,106 +0,0 @@ ---- -sidebarTitle: "Logger" -mode: "center" ---- - - - - - - -## LogEntry - -```python -@dataclass -class LogEntry() -``` - -Represents a single log entry from the template build process. - - - -## LogEntryStart - -```python -@dataclass -class LogEntryStart(LogEntry) -``` - -Special log entry indicating the start of a build process. - - - -## LogEntryEnd - -```python -@dataclass -class LogEntryEnd(LogEntry) -``` - -Special log entry indicating the end of a build process. - - - -### TIMER\_UPDATE\_INTERVAL\_MS - -Default minimum log level to display. - - - -### DEFAULT\_LEVEL - -Colored labels for each log level. - - - -### levels - -Numeric ordering of log levels for comparison (lower = less severe). - - - -### set\_interval - -```python -def set_interval(func, interval) -``` - -Returns a stop function that can be called to cancel the interval. - -Similar to JavaScript's setInterval. - -**Arguments**: - -- `func`: Function to execute at each interval -- `interval`: Interval duration in **seconds** - -**Returns**: - -Stop function that can be called to cancel the interval - - - -### default\_build\_logger - -```python -def default_build_logger( - min_level: Optional[LogEntryLevel] = None -) -> Callable[[LogEntry], None] -``` - -Create a default build logger with animated timer display. - -**Arguments**: - -- `min_level`: Minimum log level to display (default: 'info') - -**Returns**: - -Logger function that accepts LogEntry instances -Example -```python -from e2b import Template, default_build_logger - -template = Template().from_python_image() - -``` diff --git a/docs/sdk-reference/python-sdk/v2.8.1/readycmd.mdx b/docs/sdk-reference/python-sdk/v2.8.1/readycmd.mdx deleted file mode 100644 index 8eabda6..0000000 --- a/docs/sdk-reference/python-sdk/v2.8.1/readycmd.mdx +++ /dev/null @@ -1,168 +0,0 @@ ---- -sidebarTitle: "Readycmd" -mode: "center" ---- - - - - - - -## ReadyCmd - -```python -class ReadyCmd() -``` - -Wrapper class for ready check commands. - - - -### wait\_for\_port - -```python -def wait_for_port(port: int) -``` - -Wait for a port to be listening. - -Uses `ss` command to check if a port is open and listening. - -**Arguments**: - -- `port`: Port number to wait for - -**Returns**: - -ReadyCmd that checks for the port -Example -```python -from e2b import Template, wait_for_port - -template = ( - Template() - .from_python_image() - .set_start_cmd('python -m http.server 8000', wait_for_port(8000)) -) -``` - - - -### wait\_for\_url - -```python -def wait_for_url(url: str, status_code: int = 200) -``` - -Wait for a URL to return a specific HTTP status code. - -Uses `curl` to make HTTP requests and check the response status. - -**Arguments**: - -- `url`: URL to check (e.g., 'http://localhost:3000/health') -- `status_code`: Expected HTTP status code (default: 200) - -**Returns**: - -ReadyCmd that checks the URL -Example -```python -from e2b import Template, wait_for_url - -template = ( - Template() - .from_node_image() - .set_start_cmd('npm start', wait_for_url('http://localhost:3000/health')) -) -``` - - - -### wait\_for\_process - -```python -def wait_for_process(process_name: str) -``` - -Wait for a process with a specific name to be running. - -Uses `pgrep` to check if a process exists. - -**Arguments**: - -- `process_name`: Name of the process to wait for - -**Returns**: - -ReadyCmd that checks for the process -Example -```python -from e2b import Template, wait_for_process - -template = ( - Template() - .from_base_image() - .set_start_cmd('./my-daemon', wait_for_process('my-daemon')) -) -``` - - - -### wait\_for\_file - -```python -def wait_for_file(filename: str) -``` - -Wait for a file to exist. - -Uses shell test command to check file existence. - -**Arguments**: - -- `filename`: Path to the file to wait for - -**Returns**: - -ReadyCmd that checks for the file -Example -```python -from e2b import Template, wait_for_file - -template = ( - Template() - .from_base_image() - .set_start_cmd('./init.sh', wait_for_file('/tmp/ready')) -) -``` - - - -### wait\_for\_timeout - -```python -def wait_for_timeout(timeout: int) -``` - -Wait for a specified timeout before considering the sandbox ready. - -Uses `sleep` command to wait for a fixed duration. - -**Arguments**: - -- `timeout`: Time to wait in **milliseconds** (minimum: 1000ms / 1 second) - -**Returns**: - -ReadyCmd that waits for the specified duration -Example -```python -from e2b import Template, wait_for_timeout - -template = ( - Template() - .from_node_image() - .set_start_cmd('npm start', wait_for_timeout(5000)) # Wait 5 seconds -) -``` diff --git a/docs/sdk-reference/python-sdk/v2.8.1/sandbox_async.mdx b/docs/sdk-reference/python-sdk/v2.8.1/sandbox_async.mdx deleted file mode 100644 index b636b1a..0000000 --- a/docs/sdk-reference/python-sdk/v2.8.1/sandbox_async.mdx +++ /dev/null @@ -1,1387 +0,0 @@ ---- -sidebarTitle: "Sandbox Async" -mode: "center" ---- - - - - - - -## AsyncWatchHandle - -```python -class AsyncWatchHandle() -``` - -Handle for watching a directory in the sandbox filesystem. - -Use `.stop()` to stop watching the directory. - - - -### stop - -```python -async def stop() -``` - -Stop watching the directory. - - - - - - -## Filesystem - -```python -class Filesystem() -``` - -Module for interacting with the filesystem in the sandbox. - - - -### read - -```python -@overload -async def read(path: str, - format: Literal["text"] = "text", - user: Optional[Username] = None, - request_timeout: Optional[float] = None) -> str -``` - -Read file content as a `str`. - -**Arguments**: - -- `path`: Path to the file -- `user`: Run the operation as this user -- `format`: Format of the file content—`text` by default -- `request_timeout`: Timeout for the request in **seconds** - -**Returns**: - -File content as a `str` - - - -### read - -```python -@overload -async def read(path: str, - format: Literal["bytes"], - user: Optional[Username] = None, - request_timeout: Optional[float] = None) -> bytearray -``` - -Read file content as a `bytearray`. - -**Arguments**: - -- `path`: Path to the file -- `user`: Run the operation as this user -- `format`: Format of the file content—`bytes` -- `request_timeout`: Timeout for the request in **seconds** - -**Returns**: - -File content as a `bytearray` - - - -### read - -```python -@overload -async def read( - path: str, - format: Literal["stream"], - user: Optional[Username] = None, - request_timeout: Optional[float] = None) -> AsyncIterator[bytes] -``` - -Read file content as a `AsyncIterator[bytes]`. - -**Arguments**: - -- `path`: Path to the file -- `user`: Run the operation as this user -- `format`: Format of the file content—`stream` -- `request_timeout`: Timeout for the request in **seconds** - -**Returns**: - -File content as an `AsyncIterator[bytes]` - - - -### write - -```python -async def write(path: str, - data: Union[str, bytes, IO], - user: Optional[Username] = None, - request_timeout: Optional[float] = None) -> WriteInfo -``` - -Write content to a file on the path. - -Writing to a file that doesn't exist creates the file. -Writing to a file that already exists overwrites the file. -Writing to a file at path that doesn't exist creates the necessary directories. - -**Arguments**: - -- `path`: Path to the file -- `data`: Data to write to the file, can be a `str`, `bytes`, or `IO`. -- `user`: Run the operation as this user -- `request_timeout`: Timeout for the request in **seconds** - -**Returns**: - -Information about the written file - - - -### write\_files - -```python -async def write_files( - files: List[WriteEntry], - user: Optional[Username] = None, - request_timeout: Optional[float] = None) -> List[WriteInfo] -``` - -Writes multiple files. - -Writes a list of files to the filesystem. -When writing to a file that doesn't exist, the file will get created. -When writing to a file that already exists, the file will get overwritten. -When writing to a file that's in a directory that doesn't exist, you'll get an error. - -**Arguments**: - -- `files`: list of files to write as `WriteEntry` objects, each containing `path` and `data` -- `user`: Run the operation as this user -- `request_timeout`: Timeout for the request - -**Returns**: - -Information about the written files - - - -### list - -```python -async def list(path: str, - depth: Optional[int] = 1, - user: Optional[Username] = None, - request_timeout: Optional[float] = None) -> List[EntryInfo] -``` - -List entries in a directory. - -**Arguments**: - -- `path`: Path to the directory -- `depth`: Depth of the directory to list -- `user`: Run the operation as this user -- `request_timeout`: Timeout for the request in **seconds** - -**Returns**: - -List of entries in the directory - - - -### exists - -```python -async def exists(path: str, - user: Optional[Username] = None, - request_timeout: Optional[float] = None) -> bool -``` - -Check if a file or a directory exists. - -**Arguments**: - -- `path`: Path to a file or a directory -- `user`: Run the operation as this user -- `request_timeout`: Timeout for the request in **seconds** - -**Returns**: - -`True` if the file or directory exists, `False` otherwise - - - -### get\_info - -```python -async def get_info(path: str, - user: Optional[Username] = None, - request_timeout: Optional[float] = None) -> EntryInfo -``` - -Get information about a file or directory. - -**Arguments**: - -- `path`: Path to a file or a directory -- `user`: Run the operation as this user -- `request_timeout`: Timeout for the request in **seconds** - -**Returns**: - -Information about the file or directory like name, type, and path - - - -### remove - -```python -async def remove(path: str, - user: Optional[Username] = None, - request_timeout: Optional[float] = None) -> None -``` - -Remove a file or a directory. - -**Arguments**: - -- `path`: Path to a file or a directory -- `user`: Run the operation as this user -- `request_timeout`: Timeout for the request in **seconds** - - - -### rename - -```python -async def rename(old_path: str, - new_path: str, - user: Optional[Username] = None, - request_timeout: Optional[float] = None) -> EntryInfo -``` - -Rename a file or directory. - -**Arguments**: - -- `old_path`: Path to the file or directory to rename -- `new_path`: New path to the file or directory -- `user`: Run the operation as this user -- `request_timeout`: Timeout for the request in **seconds** - -**Returns**: - -Information about the renamed file or directory - - - -### make\_dir - -```python -async def make_dir(path: str, - user: Optional[Username] = None, - request_timeout: Optional[float] = None) -> bool -``` - -Create a new directory and all directories along the way if needed on the specified path. - -**Arguments**: - -- `path`: Path to a new directory. For example '/dirA/dirB' when creating 'dirB'. -- `user`: Run the operation as this user -- `request_timeout`: Timeout for the request in **seconds** - -**Returns**: - -`True` if the directory was created, `False` if the directory already exists - - - -### watch\_dir - -```python -async def watch_dir(path: str, - on_event: OutputHandler[FilesystemEvent], - on_exit: Optional[OutputHandler[Exception]] = None, - user: Optional[Username] = None, - request_timeout: Optional[float] = None, - timeout: Optional[float] = 60, - recursive: bool = False) -> AsyncWatchHandle -``` - -Watch directory for filesystem events. - -**Arguments**: - -- `path`: Path to a directory to watch -- `on_event`: Callback to call on each event in the directory -- `on_exit`: Callback to call when the watching ends -- `user`: Run the operation as this user -- `request_timeout`: Timeout for the request in **seconds** -- `timeout`: Timeout for the watch operation in **seconds**. Using `0` will not limit the watch time -- `recursive`: Watch directory recursively - -**Returns**: - -`AsyncWatchHandle` object for stopping watching directory - - - - - - -## AsyncSandboxPaginator - -```python -class AsyncSandboxPaginator(SandboxPaginatorBase) -``` - -Paginator for listing sandboxes. - -**Example**: - -```python -paginator = AsyncSandbox.list() - -while paginator.has_next: - sandboxes = await paginator.next_items() - print(sandboxes) -``` - - - -### next\_items - -```python -async def next_items() -> List[SandboxInfo] -``` - -Returns the next page of sandboxes. - -Call this method only if `has_next` is `True`, otherwise it will raise an exception. - -**Returns**: - -List of sandboxes - - - - - - - - - -## SandboxApi - -```python -class SandboxApi(SandboxBase) -``` - - - -### list - -```python -@staticmethod -def list(query: Optional[SandboxQuery] = None, - limit: Optional[int] = None, - next_token: Optional[str] = None, - **opts: Unpack[ApiParams]) -> AsyncSandboxPaginator -``` - -List all running sandboxes. - -**Arguments**: - -- `query`: Filter the list of sandboxes by metadata or state, e.g. `SandboxListQuery(metadata={"key": "value"})` or `SandboxListQuery(state=[SandboxState.RUNNING])` -- `limit`: Maximum number of sandboxes to return per page -- `next_token`: Token for pagination - -**Returns**: - -List of running sandboxes - - - - - - -## Commands - -```python -class Commands() -``` - -Module for executing commands in the sandbox. - - - -### list - -```python -async def list(request_timeout: Optional[float] = None) -> List[ProcessInfo] -``` - -Lists all running commands and PTY sessions. - -**Arguments**: - -- `request_timeout`: Timeout for the request in **seconds** - -**Returns**: - -List of running commands and PTY sessions - - - -### kill - -```python -async def kill(pid: int, request_timeout: Optional[float] = None) -> bool -``` - -Kill a running command specified by its process ID. - -It uses `SIGKILL` signal to kill the command. - -**Arguments**: - -- `pid`: Process ID of the command. You can get the list of processes using `sandbox.commands.list()` -- `request_timeout`: Timeout for the request in **seconds** - -**Returns**: - -`True` if the command was killed, `False` if the command was not found - - - -### send\_stdin - -```python -async def send_stdin(pid: int, - data: str, - request_timeout: Optional[float] = None) -> None -``` - -Send data to command stdin. - -:param pid Process ID of the command. You can get the list of processes using `sandbox.commands.list()`. -:param data: Data to send to the command -:param request_timeout: Timeout for the request in **seconds** - - - - -### run - -```python -@overload -async def run(cmd: str, - background: Union[Literal[False], None] = None, - envs: Optional[Dict[str, str]] = None, - user: Optional[Username] = None, - cwd: Optional[str] = None, - on_stdout: Optional[OutputHandler[Stdout]] = None, - on_stderr: Optional[OutputHandler[Stderr]] = None, - stdin: Optional[bool] = None, - timeout: Optional[float] = 60, - request_timeout: Optional[float] = None) -> CommandResult -``` - -Start a new command and wait until it finishes executing. - -**Arguments**: - -- `cmd`: Command to execute -- `background`: **`False` if the command should be executed in the foreground**, `True` if the command should be executed in the background -- `envs`: Environment variables used for the command -- `user`: User to run the command as -- `cwd`: Working directory to run the command -- `on_stdout`: Callback for command stdout output -- `on_stderr`: Callback for command stderr output -- `stdin`: If `True`, the command will have a stdin stream that you can send data to using `sandbox.commands.send_stdin()` -- `timeout`: Timeout for the command connection in **seconds**. Using `0` will not limit the command connection time -- `request_timeout`: Timeout for the request in **seconds** - -**Returns**: - -`CommandResult` result of the command execution - - - -### run - -```python -@overload -async def run(cmd: str, - background: Literal[True], - envs: Optional[Dict[str, str]] = None, - user: Optional[Username] = None, - cwd: Optional[str] = None, - on_stdout: Optional[OutputHandler[Stdout]] = None, - on_stderr: Optional[OutputHandler[Stderr]] = None, - stdin: Optional[bool] = None, - timeout: Optional[float] = 60, - request_timeout: Optional[float] = None) -> AsyncCommandHandle -``` - -Start a new command and return a handle to interact with it. - -**Arguments**: - -- `cmd`: Command to execute -- `background`: `False` if the command should be executed in the foreground, **`True` if the command should be executed in the background** -- `envs`: Environment variables used for the command -- `user`: User to run the command as -- `cwd`: Working directory to run the command -- `on_stdout`: Callback for command stdout output -- `on_stderr`: Callback for command stderr output -- `stdin`: If `True`, the command will have a stdin stream that you can send data to using `sandbox.commands.send_stdin()` -- `timeout`: Timeout for the command connection in **seconds**. Using `0` will not limit the command connection time -- `request_timeout`: Timeout for the request in **seconds** - -**Returns**: - -`AsyncCommandHandle` handle to interact with the running command - - - -### connect - -```python -async def connect( - pid: int, - timeout: Optional[float] = 60, - request_timeout: Optional[float] = None, - on_stdout: Optional[OutputHandler[Stdout]] = None, - on_stderr: Optional[OutputHandler[Stderr]] = None -) -> AsyncCommandHandle -``` - -Connects to a running command. - -You can use `AsyncCommandHandle.wait()` to wait for the command to finish and get execution results. - -**Arguments**: - -- `pid`: Process ID of the command to connect to. You can get the list of processes using `sandbox.commands.list()` -- `request_timeout`: Request timeout in **seconds** -- `timeout`: Timeout for the command connection in **seconds**. Using `0` will not limit the command connection time -- `on_stdout`: Callback for command stdout output -- `on_stderr`: Callback for command stderr output - -**Returns**: - -`AsyncCommandHandle` handle to interact with the running command - - - - - - -## AsyncCommandHandle - -```python -class AsyncCommandHandle() -``` - -Command execution handle. - -It provides methods for waiting for the command to finish, retrieving stdout/stderr, and killing the command. - - - -### pid - -```python -@property -def pid() -``` - -Command process ID. - - - -### stdout - -```python -@property -def stdout() -``` - -Command stdout output. - - - -### stderr - -```python -@property -def stderr() -``` - -Command stderr output. - - - -### error - -```python -@property -def error() -``` - -Command execution error message. - - - -### exit\_code - -```python -@property -def exit_code() -``` - -Command execution exit code. - -`0` if the command finished successfully. - -It is `None` if the command is still running. - - - -### disconnect - -```python -async def disconnect() -> None -``` - -Disconnects from the command. - -The command is not killed, but SDK stops receiving events from the command. -You can reconnect to the command using `sandbox.commands.connect` method. - - - -### wait - -```python -async def wait() -> CommandResult -``` - -Wait for the command to finish and return the result. - -If the command exits with a non-zero exit code, it throws a `CommandExitException`. - -**Returns**: - -`CommandResult` result of command execution - - - -### kill - -```python -async def kill() -> bool -``` - -Kills the command. - -It uses `SIGKILL` signal to kill the command - -**Returns**: - -`True` if the command was killed successfully, `False` if the command was not found - - - - - - -## Pty - -```python -class Pty() -``` - -Module for interacting with PTYs (pseudo-terminals) in the sandbox. - - - -### kill - -```python -async def kill(pid: int, request_timeout: Optional[float] = None) -> bool -``` - -Kill PTY. - -**Arguments**: - -- `pid`: Process ID of the PTY -- `request_timeout`: Timeout for the request in **seconds** - -**Returns**: - -`true` if the PTY was killed, `false` if the PTY was not found - - - -### send\_stdin - -```python -async def send_stdin(pid: int, - data: bytes, - request_timeout: Optional[float] = None) -> None -``` - -Send input to a PTY. - -**Arguments**: - -- `pid`: Process ID of the PTY -- `data`: Input data to send -- `request_timeout`: Timeout for the request in **seconds** - - - -### create - -```python -async def create( - size: PtySize, - on_data: OutputHandler[PtyOutput], - user: Optional[Username] = None, - cwd: Optional[str] = None, - envs: Optional[Dict[str, str]] = None, - timeout: Optional[float] = 60, - request_timeout: Optional[float] = None) -> AsyncCommandHandle -``` - -Start a new PTY (pseudo-terminal). - -**Arguments**: - -- `size`: Size of the PTY -- `on_data`: Callback to handle PTY data -- `user`: User to use for the PTY -- `cwd`: Working directory for the PTY -- `envs`: Environment variables for the PTY -- `timeout`: Timeout for the PTY in **seconds** -- `request_timeout`: Timeout for the request in **seconds** - -**Returns**: - -Handle to interact with the PTY - - - -### resize - -```python -async def resize(pid: int, - size: PtySize, - request_timeout: Optional[float] = None) -``` - -Resize PTY. - -Call this when the terminal window is resized and the number of columns and rows has changed. - -**Arguments**: - -- `pid`: Process ID of the PTY -- `size`: New size of the PTY -- `request_timeout`: Timeout for the request in **seconds** - - - - - - -## AsyncSandbox - -```python -class AsyncSandbox(SandboxApi) -``` - -E2B cloud sandbox is a secure and isolated cloud environment. - -The sandbox allows you to: -- Access Linux OS -- Create, list, and delete files and directories -- Run commands -- Run isolated code -- Access the internet - -Check docs [here](https://e2b.dev/docs). - -Use the `AsyncSandbox.create()` to create a new sandbox. - -**Example**: - -```python -from e2b import AsyncSandbox - -sandbox = await AsyncSandbox.create() -``` - - - -### files - -```python -@property -def files() -> Filesystem -``` - -Module for interacting with the sandbox filesystem. - - - -### commands - -```python -@property -def commands() -> Commands -``` - -Module for running commands in the sandbox. - - - -### pty - -```python -@property -def pty() -> Pty -``` - -Module for interacting with the sandbox pseudo-terminal. - - - -### \_\_init\_\_ - -```python -def __init__(**opts: Unpack[SandboxOpts]) -``` - -Use `AsyncSandbox.create()` to create a new sandbox instead. - - - -### is\_running - -```python -async def is_running(request_timeout: Optional[float] = None) -> bool -``` - -Check if the sandbox is running. - -**Arguments**: - -- `request_timeout`: Timeout for the request in **seconds** - -**Returns**: - -`True` if the sandbox is running, `False` otherwise -Example -```python -sandbox = await AsyncSandbox.create() -await sandbox.is_running() # Returns True - -await sandbox.kill() -await sandbox.is_running() # Returns False -``` - - - -### create - -```python -@classmethod -async def create(cls, - template: Optional[str] = None, - timeout: Optional[int] = None, - metadata: Optional[Dict[str, str]] = None, - envs: Optional[Dict[str, str]] = None, - secure: bool = True, - allow_internet_access: bool = True, - mcp: Optional[McpServer] = None, - network: Optional[SandboxNetworkOpts] = None, - **opts: Unpack[ApiParams]) -> Self -``` - -Create a new sandbox. - -By default, the sandbox is created from the default `base` sandbox template. - -**Arguments**: - -- `template`: Sandbox template name or ID -- `timeout`: Timeout for the sandbox in **seconds**, default to 300 seconds. The maximum time a sandbox can be kept alive is 24 hours (86_400 seconds) for Pro users and 1 hour (3_600 seconds) for Hobby users. -- `metadata`: Custom metadata for the sandbox -- `envs`: Custom environment variables for the sandbox -- `secure`: Envd is secured with access token and cannot be used without it, defaults to `True`. -- `allow_internet_access`: Allow sandbox to access the internet, defaults to `True`. If set to `False`, it works the same as setting network `deny_out` to `[0.0.0.0/0]`. -- `mcp`: MCP server to enable in the sandbox -- `network`: Sandbox network configuration - -**Returns**: - -A Sandbox instance for the new sandbox -Use this method instead of using the constructor to create a new sandbox. - - - -### connect - -```python -@overload -async def connect(timeout: Optional[int] = None, - **opts: Unpack[ApiParams]) -> Self -``` - -Connect to a sandbox. If the sandbox is paused, it will be automatically resumed. - -Sandbox must be either running or be paused. - -With sandbox ID you can connect to the same sandbox from different places or environments (serverless functions, etc). - -**Arguments**: - -- `timeout`: Timeout for the sandbox in **seconds** -For running sandboxes, the timeout will update only if the new timeout is longer than the existing one. - -**Returns**: - -A running sandbox instance -@example -```python -sandbox = await AsyncSandbox.create() -await sandbox.beta_pause() - -same_sandbox = await sandbox.connect() -``` - - - -### connect - -```python -@overload -@classmethod -async def connect(cls, - sandbox_id: str, - timeout: Optional[int] = None, - **opts: Unpack[ApiParams]) -> Self -``` - -Connect to a sandbox. If the sandbox is paused, it will be automatically resumed. - -Sandbox must be either running or be paused. - -With sandbox ID you can connect to the same sandbox from different places or environments (serverless functions, etc). - -**Arguments**: - -- `sandbox_id`: Sandbox ID -- `timeout`: Timeout for the sandbox in **seconds** -For running sandboxes, the timeout will update only if the new timeout is longer than the existing one. - -**Returns**: - -A running sandbox instance -@example -```python -sandbox = await AsyncSandbox.create() -await AsyncSandbox.beta_pause(sandbox.sandbox_id) - -same_sandbox = await AsyncSandbox.connect(sandbox.sandbox_id)) -``` - - - -### connect - -```python -@class_method_variant("_cls_connect") -async def connect(timeout: Optional[int] = None, - **opts: Unpack[ApiParams]) -> Self -``` - -Connect to a sandbox. If the sandbox is paused, it will be automatically resumed. - -Sandbox must be either running or be paused. - -With sandbox ID you can connect to the same sandbox from different places or environments (serverless functions, etc). - -**Arguments**: - -- `timeout`: Timeout for the sandbox in **seconds** -For running sandboxes, the timeout will update only if the new timeout is longer than the existing one. - -**Returns**: - -A running sandbox instance -@example -```python -sandbox = await AsyncSandbox.create() -await sandbox.beta_pause() - -same_sandbox = await sandbox.connect() -``` - - - -### kill - -```python -@overload -async def kill(**opts: Unpack[ApiParams]) -> bool -``` - -Kill the sandbox. - -**Returns**: - -`True` if the sandbox was killed, `False` if the sandbox was not found - - - -### kill - -```python -@overload -@staticmethod -async def kill(sandbox_id: str, **opts: Unpack[ApiParams]) -> bool -``` - -Kill the sandbox specified by sandbox ID. - -**Arguments**: - -- `sandbox_id`: Sandbox ID - -**Returns**: - -`True` if the sandbox was killed, `False` if the sandbox was not found - - - -### kill - -```python -@class_method_variant("_cls_kill") -async def kill(**opts: Unpack[ApiParams]) -> bool -``` - -Kill the sandbox specified by sandbox ID. - -**Returns**: - -`True` if the sandbox was killed, `False` if the sandbox was not found - - - -### set\_timeout - -```python -@overload -async def set_timeout(timeout: int, **opts: Unpack[ApiParams]) -> None -``` - -Set the timeout of the sandbox. - -After the timeout expires, the sandbox will be automatically killed. -This method can extend or reduce the sandbox timeout set when creating the sandbox or from the last call to `.set_timeout`. - -The maximum time a sandbox can be kept alive is 24 hours (86_400 seconds) for Pro users and 1 hour (3_600 seconds) for Hobby users. - -**Arguments**: - -- `timeout`: Timeout for the sandbox in **seconds** - - - -### set\_timeout - -```python -@overload -@staticmethod -async def set_timeout(sandbox_id: str, timeout: int, - **opts: Unpack[ApiParams]) -> None -``` - -Set the timeout of the specified sandbox. - -After the timeout expires, the sandbox will be automatically killed. -This method can extend or reduce the sandbox timeout set when creating the sandbox or from the last call to `.set_timeout`. - -The maximum time a sandbox can be kept alive is 24 hours (86_400 seconds) for Pro users and 1 hour (3_600 seconds) for Hobby users. - -**Arguments**: - -- `sandbox_id`: Sandbox ID -- `timeout`: Timeout for the sandbox in **seconds** - - - -### set\_timeout - -```python -@class_method_variant("_cls_set_timeout") -async def set_timeout(timeout: int, **opts: Unpack[ApiParams]) -> None -``` - -Set the timeout of the specified sandbox. - -After the timeout expires, the sandbox will be automatically killed. -This method can extend or reduce the sandbox timeout set when creating the sandbox or from the last call to `.set_timeout`. - -The maximum time a sandbox can be kept alive is 24 hours (86_400 seconds) for Pro users and 1 hour (3_600 seconds) for Hobby users. - -**Arguments**: - -- `timeout`: Timeout for the sandbox in **seconds** - - - -### get\_info - -```python -@overload -async def get_info(**opts: Unpack[ApiParams]) -> SandboxInfo -``` - -Get sandbox information like sandbox ID, template, metadata, started at/end at date. - -**Returns**: - -Sandbox info - - - -### get\_info - -```python -@overload -@staticmethod -async def get_info(sandbox_id: str, **opts: Unpack[ApiParams]) -> SandboxInfo -``` - -Get sandbox information like sandbox ID, template, metadata, started at/end at date. - -**Arguments**: - -- `sandbox_id`: Sandbox ID - -**Returns**: - -Sandbox info - - - -### get\_info - -```python -@class_method_variant("_cls_get_info") -async def get_info(**opts: Unpack[ApiParams]) -> SandboxInfo -``` - -Get sandbox information like sandbox ID, template, metadata, started at/end at date. - -**Returns**: - -Sandbox info - - - -### get\_metrics - -```python -@overload -async def get_metrics(start: Optional[datetime.datetime] = None, - end: Optional[datetime.datetime] = None, - **opts: Unpack[ApiParams]) -> List[SandboxMetrics] -``` - -Get the metrics of the current sandbox. - -**Arguments**: - -- `start`: Start time for the metrics, defaults to the start of the sandbox -- `end`: End time for the metrics, defaults to the current time - -**Returns**: - -List of sandbox metrics containing CPU, memory and disk usage information - - - -### get\_metrics - -```python -@overload -@staticmethod -async def get_metrics(sandbox_id: str, - start: Optional[datetime.datetime] = None, - end: Optional[datetime.datetime] = None, - **opts: Unpack[ApiParams]) -> List[SandboxMetrics] -``` - -Get the metrics of the sandbox specified by sandbox ID. - -**Arguments**: - -- `sandbox_id`: Sandbox ID -- `start`: Start time for the metrics, defaults to the start of the sandbox -- `end`: End time for the metrics, defaults to the current time - -**Returns**: - -List of sandbox metrics containing CPU, memory and disk usage information - - - -### get\_metrics - -```python -@class_method_variant("_cls_get_metrics") -async def get_metrics(start: Optional[datetime.datetime] = None, - end: Optional[datetime.datetime] = None, - **opts: Unpack[ApiParams]) -> List[SandboxMetrics] -``` - -Get the metrics of the current sandbox. - -**Arguments**: - -- `start`: Start time for the metrics, defaults to the start of the sandbox -- `end`: End time for the metrics, defaults to the current time - -**Returns**: - -List of sandbox metrics containing CPU, memory and disk usage information - - - -### beta\_create - -```python -@classmethod -async def beta_create(cls, - template: Optional[str] = None, - timeout: Optional[int] = None, - auto_pause: bool = False, - metadata: Optional[Dict[str, str]] = None, - envs: Optional[Dict[str, str]] = None, - secure: bool = True, - allow_internet_access: bool = True, - mcp: Optional[McpServer] = None, - **opts: Unpack[ApiParams]) -> Self -``` - -[BETA] This feature is in beta and may change in the future. - -Create a new sandbox. - -By default, the sandbox is created from the default `base` sandbox template. - -**Arguments**: - -- `template`: Sandbox template name or ID -- `timeout`: Timeout for the sandbox in **seconds**, default to 300 seconds. The maximum time a sandbox can be kept alive is 24 hours (86_400 seconds) for Pro users and 1 hour (3_600 seconds) for Hobby users. -- `auto_pause`: Automatically pause the sandbox after the timeout expires. Defaults to `False`. -- `metadata`: Custom metadata for the sandbox -- `envs`: Custom environment variables for the sandbox -- `secure`: Envd is secured with access token and cannot be used without it, defaults to `True`. -- `allow_internet_access`: Allow sandbox to access the internet, defaults to `True`. -- `mcp`: MCP server to enable in the sandbox - -**Returns**: - -A Sandbox instance for the new sandbox -Use this method instead of using the constructor to create a new sandbox. - - - -### beta\_pause - -```python -@overload -async def beta_pause(**opts: Unpack[ApiParams]) -> None -``` - -[BETA] This feature is in beta and may change in the future. - -Pause the sandbox. - -**Returns**: - -Sandbox ID that can be used to resume the sandbox - - - -### beta\_pause - -```python -@overload -@staticmethod -async def beta_pause(sandbox_id: str, **opts: Unpack[ApiParams]) -> None -``` - -[BETA] This feature is in beta and may change in the future. - -Pause the sandbox specified by sandbox ID. - -**Arguments**: - -- `sandbox_id`: Sandbox ID - -**Returns**: - -Sandbox ID that can be used to resume the sandbox - - - -### beta\_pause - -```python -@class_method_variant("_cls_pause") -async def beta_pause(**opts: Unpack[ApiParams]) -> None -``` - -[BETA] This feature is in beta and may change in the future. - -Pause the sandbox. - -**Returns**: - -Sandbox ID that can be used to resume the sandbox - - - -### get\_mcp\_token - -```python -async def get_mcp_token() -> Optional[str] -``` - -Get the MCP token for the sandbox. - -**Returns**: - -MCP token for the sandbox, or None if MCP is not enabled. diff --git a/docs/sdk-reference/python-sdk/v2.8.1/sandbox_sync.mdx b/docs/sdk-reference/python-sdk/v2.8.1/sandbox_sync.mdx deleted file mode 100644 index 04927a8..0000000 --- a/docs/sdk-reference/python-sdk/v2.8.1/sandbox_sync.mdx +++ /dev/null @@ -1,1343 +0,0 @@ ---- -sidebarTitle: "Sandbox Sync" -mode: "center" ---- - - - - - - -## WatchHandle - -```python -class WatchHandle() -``` - -Handle for watching filesystem events. -It is used to get the latest events that have occurred in the watched directory. - -Use `.stop()` to stop watching the directory. - - - -### stop - -```python -def stop() -``` - -Stop watching the directory. -After you stop the watcher you won't be able to get the events anymore. - - - -### get\_new\_events - -```python -def get_new_events() -> List[FilesystemEvent] -``` - -Get the latest events that have occurred in the watched directory since the last call, or from the beginning of the watching, up until now. - -**Returns**: - -List of filesystem events - - - - - - -## Filesystem - -```python -class Filesystem() -``` - -Module for interacting with the filesystem in the sandbox. - - - -### read - -```python -@overload -def read(path: str, - format: Literal["text"] = "text", - user: Optional[Username] = None, - request_timeout: Optional[float] = None) -> str -``` - -Read file content as a `str`. - -**Arguments**: - -- `path`: Path to the file -- `user`: Run the operation as this user -- `format`: Format of the file content—`text` by default -- `request_timeout`: Timeout for the request in **seconds** - -**Returns**: - -File content as a `str` - - - -### read - -```python -@overload -def read(path: str, - format: Literal["bytes"], - user: Optional[Username] = None, - request_timeout: Optional[float] = None) -> bytearray -``` - -Read file content as a `bytearray`. - -**Arguments**: - -- `path`: Path to the file -- `user`: Run the operation as this user -- `format`: Format of the file content—`bytes` -- `request_timeout`: Timeout for the request in **seconds** - -**Returns**: - -File content as a `bytearray` - - - -### read - -```python -@overload -def read(path: str, - format: Literal["stream"], - user: Optional[Username] = None, - request_timeout: Optional[float] = None) -> Iterator[bytes] -``` - -Read file content as a `Iterator[bytes]`. - -**Arguments**: - -- `path`: Path to the file -- `user`: Run the operation as this user -- `format`: Format of the file content—`stream` -- `request_timeout`: Timeout for the request in **seconds** - -**Returns**: - -File content as an `Iterator[bytes]` - - - -### write - -```python -def write(path: str, - data: Union[str, bytes, IO], - user: Optional[Username] = None, - request_timeout: Optional[float] = None) -> WriteInfo -``` - -Write content to a file on the path. - -Writing to a file that doesn't exist creates the file. -Writing to a file that already exists overwrites the file. -Writing to a file at path that doesn't exist creates the necessary directories. - -**Arguments**: - -- `path`: Path to the file -- `data`: Data to write to the file, can be a `str`, `bytes`, or `IO`. -- `user`: Run the operation as this user -- `request_timeout`: Timeout for the request in **seconds** - -**Returns**: - -Information about the written file - - - -### write\_files - -```python -def write_files(files: List[WriteEntry], - user: Optional[Username] = None, - request_timeout: Optional[float] = None) -> List[WriteInfo] -``` - -Writes a list of files to the filesystem. - -When writing to a file that doesn't exist, the file will get created. -When writing to a file that already exists, the file will get overwritten. -When writing to a file that's in a directory that doesn't exist, you'll get an error. - -**Arguments**: - -- `files`: list of files to write as `WriteEntry` objects, each containing `path` and `data` -- `user`: Run the operation as this user -- `request_timeout`: Timeout for the request - -**Returns**: - -Information about the written files - - - -### list - -```python -def list(path: str, - depth: Optional[int] = 1, - user: Optional[Username] = None, - request_timeout: Optional[float] = None) -> List[EntryInfo] -``` - -List entries in a directory. - -**Arguments**: - -- `path`: Path to the directory -- `depth`: Depth of the directory to list -- `user`: Run the operation as this user -- `request_timeout`: Timeout for the request in **seconds** - -**Returns**: - -List of entries in the directory - - - -### exists - -```python -def exists(path: str, - user: Optional[Username] = None, - request_timeout: Optional[float] = None) -> bool -``` - -Check if a file or a directory exists. - -**Arguments**: - -- `path`: Path to a file or a directory -- `user`: Run the operation as this user -- `request_timeout`: Timeout for the request in **seconds** - -**Returns**: - -`True` if the file or directory exists, `False` otherwise - - - -### get\_info - -```python -def get_info(path: str, - user: Optional[Username] = None, - request_timeout: Optional[float] = None) -> EntryInfo -``` - -Get information about a file or directory. - -**Arguments**: - -- `path`: Path to a file or a directory -- `user`: Run the operation as this user -- `request_timeout`: Timeout for the request in **seconds** - -**Returns**: - -Information about the file or directory like name, type, and path - - - -### remove - -```python -def remove(path: str, - user: Optional[Username] = None, - request_timeout: Optional[float] = None) -> None -``` - -Remove a file or a directory. - -**Arguments**: - -- `path`: Path to a file or a directory -- `user`: Run the operation as this user -- `request_timeout`: Timeout for the request in **seconds** - - - -### rename - -```python -def rename(old_path: str, - new_path: str, - user: Optional[Username] = None, - request_timeout: Optional[float] = None) -> EntryInfo -``` - -Rename a file or directory. - -**Arguments**: - -- `old_path`: Path to the file or directory to rename -- `new_path`: New path to the file or directory -- `user`: Run the operation as this user -- `request_timeout`: Timeout for the request in **seconds** - -**Returns**: - -Information about the renamed file or directory - - - -### make\_dir - -```python -def make_dir(path: str, - user: Optional[Username] = None, - request_timeout: Optional[float] = None) -> bool -``` - -Create a new directory and all directories along the way if needed on the specified path. - -**Arguments**: - -- `path`: Path to a new directory. For example '/dirA/dirB' when creating 'dirB'. -- `user`: Run the operation as this user -- `request_timeout`: Timeout for the request in **seconds** - -**Returns**: - -`True` if the directory was created, `False` if the directory already exists - - - -### watch\_dir - -```python -def watch_dir(path: str, - user: Optional[Username] = None, - request_timeout: Optional[float] = None, - recursive: bool = False) -> WatchHandle -``` - -Watch directory for filesystem events. - -**Arguments**: - -- `path`: Path to a directory to watch -- `user`: Run the operation as this user -- `request_timeout`: Timeout for the request in **seconds** -- `recursive`: Watch directory recursively - -**Returns**: - -`WatchHandle` object for stopping watching directory - - - - - - -## SandboxPaginator - -```python -class SandboxPaginator(SandboxPaginatorBase) -``` - -Paginator for listing sandboxes. - -**Example**: - -```python -paginator = Sandbox.list() - -while paginator.has_next: - sandboxes = paginator.next_items() - print(sandboxes) -``` - - - -### next\_items - -```python -def next_items() -> List[SandboxInfo] -``` - -Returns the next page of sandboxes. - -Call this method only if `has_next` is `True`, otherwise it will raise an exception. - -**Returns**: - -List of sandboxes - - - - - - -## SandboxApi - -```python -class SandboxApi(SandboxBase) -``` - - - -### list - -```python -@staticmethod -def list(query: Optional[SandboxQuery] = None, - limit: Optional[int] = None, - next_token: Optional[str] = None, - **opts: Unpack[ApiParams]) -> SandboxPaginator -``` - -List all running sandboxes. - -**Arguments**: - -- `query`: Filter the list of sandboxes by metadata or state, e.g. `SandboxListQuery(metadata={"key": "value"})` or `SandboxListQuery(state=[SandboxState.RUNNING])` -- `limit`: Maximum number of sandboxes to return per page -- `next_token`: Token for pagination - -**Returns**: - -List of running sandboxes - - - - - - -## Commands - -```python -class Commands() -``` - -Module for executing commands in the sandbox. - - - -### list - -```python -def list(request_timeout: Optional[float] = None) -> List[ProcessInfo] -``` - -Lists all running commands and PTY sessions. - -**Arguments**: - -- `request_timeout`: Timeout for the request in **seconds** - -**Returns**: - -List of running commands and PTY sessions - - - -### kill - -```python -def kill(pid: int, request_timeout: Optional[float] = None) -> bool -``` - -Kills a running command specified by its process ID. - -It uses `SIGKILL` signal to kill the command. - -**Arguments**: - -- `pid`: Process ID of the command. You can get the list of processes using `sandbox.commands.list()` -- `request_timeout`: Timeout for the request in **seconds** - -**Returns**: - -`True` if the command was killed, `False` if the command was not found - - - -### send\_stdin - -```python -def send_stdin(pid: int, data: str, request_timeout: Optional[float] = None) -``` - -Send data to command stdin. - -:param pid Process ID of the command. You can get the list of processes using `sandbox.commands.list()`. -:param data: Data to send to the command -:param request_timeout: Timeout for the request in **seconds** - - - - -### run - -```python -@overload -def run(cmd: str, - background: Union[Literal[False], None] = None, - envs: Optional[Dict[str, str]] = None, - user: Optional[Username] = None, - cwd: Optional[str] = None, - on_stdout: Optional[Callable[[str], None]] = None, - on_stderr: Optional[Callable[[str], None]] = None, - stdin: Optional[bool] = None, - timeout: Optional[float] = 60, - request_timeout: Optional[float] = None) -> CommandResult -``` - -Start a new command and wait until it finishes executing. - -**Arguments**: - -- `cmd`: Command to execute -- `background`: **`False` if the command should be executed in the foreground**, `True` if the command should be executed in the background -- `envs`: Environment variables used for the command -- `user`: User to run the command as -- `cwd`: Working directory to run the command -- `on_stdout`: Callback for command stdout output -- `on_stderr`: Callback for command stderr output -- `stdin`: If `True`, the command will have a stdin stream that you can send data to using `sandbox.commands.send_stdin()` -- `timeout`: Timeout for the command connection in **seconds**. Using `0` will not limit the command connection time -- `request_timeout`: Timeout for the request in **seconds** - -**Returns**: - -`CommandResult` result of the command execution - - - -### run - -```python -@overload -def run(cmd: str, - background: Literal[True], - envs: Optional[Dict[str, str]] = None, - user: Optional[Username] = None, - cwd: Optional[str] = None, - on_stdout: None = None, - on_stderr: None = None, - stdin: Optional[bool] = None, - timeout: Optional[float] = 60, - request_timeout: Optional[float] = None) -> CommandHandle -``` - -Start a new command and return a handle to interact with it. - -**Arguments**: - -- `cmd`: Command to execute -- `background`: `False` if the command should be executed in the foreground, **`True` if the command should be executed in the background** -- `envs`: Environment variables used for the command -- `user`: User to run the command as -- `cwd`: Working directory to run the command -- `stdin`: If `True`, the command will have a stdin stream that you can send data to using `sandbox.commands.send_stdin()` -- `timeout`: Timeout for the command connection in **seconds**. Using `0` will not limit the command connection time -- `request_timeout`: Timeout for the request in **seconds** - -**Returns**: - -`CommandHandle` handle to interact with the running command - - - -### connect - -```python -def connect(pid: int, - timeout: Optional[float] = 60, - request_timeout: Optional[float] = None) -``` - -Connects to a running command. - -You can use `CommandHandle.wait()` to wait for the command to finish and get execution results. - -**Arguments**: - -- `pid`: Process ID of the command to connect to. You can get the list of processes using `sandbox.commands.list()` -- `timeout`: Timeout for the connection in **seconds**. Using `0` will not limit the connection time -- `request_timeout`: Timeout for the request in **seconds** - -**Returns**: - -`CommandHandle` handle to interact with the running command - - - - - - -## CommandHandle - -```python -class CommandHandle() -``` - -Command execution handle. - -It provides methods for waiting for the command to finish, retrieving stdout/stderr, and killing the command. - - - -### pid - -```python -@property -def pid() -``` - -Command process ID. - - - -### \_\_iter\_\_ - -```python -def __iter__() -``` - -Iterate over the command output. - -**Returns**: - -Generator of command outputs - - - -### disconnect - -```python -def disconnect() -> None -``` - -Disconnect from the command. - -The command is not killed, but SDK stops receiving events from the command. -You can reconnect to the command using `sandbox.commands.connect` method. - - - -### wait - -```python -def wait(on_pty: Optional[Callable[[PtyOutput], None]] = None, - on_stdout: Optional[Callable[[str], None]] = None, - on_stderr: Optional[Callable[[str], None]] = None) -> CommandResult -``` - -Wait for the command to finish and returns the result. - -If the command exits with a non-zero exit code, it throws a `CommandExitException`. - -**Arguments**: - -- `on_pty`: Callback for pty output -- `on_stdout`: Callback for stdout output -- `on_stderr`: Callback for stderr output - -**Returns**: - -`CommandResult` result of command execution - - - -### kill - -```python -def kill() -> bool -``` - -Kills the command. - -It uses `SIGKILL` signal to kill the command. - -**Returns**: - -Whether the command was killed successfully - - - - - - -## Pty - -```python -class Pty() -``` - -Module for interacting with PTYs (pseudo-terminals) in the sandbox. - - - -### kill - -```python -def kill(pid: int, request_timeout: Optional[float] = None) -> bool -``` - -Kill PTY. - -**Arguments**: - -- `pid`: Process ID of the PTY -- `request_timeout`: Timeout for the request in **seconds** - -**Returns**: - -`true` if the PTY was killed, `false` if the PTY was not found - - - -### send\_stdin - -```python -def send_stdin(pid: int, - data: bytes, - request_timeout: Optional[float] = None) -> None -``` - -Send input to a PTY. - -**Arguments**: - -- `pid`: Process ID of the PTY -- `data`: Input data to send -- `request_timeout`: Timeout for the request in **seconds** - - - -### create - -```python -def create(size: PtySize, - user: Optional[Username] = None, - cwd: Optional[str] = None, - envs: Optional[Dict[str, str]] = None, - timeout: Optional[float] = 60, - request_timeout: Optional[float] = None) -> CommandHandle -``` - -Start a new PTY (pseudo-terminal). - -**Arguments**: - -- `size`: Size of the PTY -- `user`: User to use for the PTY -- `cwd`: Working directory for the PTY -- `envs`: Environment variables for the PTY -- `timeout`: Timeout for the PTY in **seconds** -- `request_timeout`: Timeout for the request in **seconds** - -**Returns**: - -Handle to interact with the PTY - - - -### resize - -```python -def resize(pid: int, - size: PtySize, - request_timeout: Optional[float] = None) -> None -``` - -Resize PTY. - -Call this when the terminal window is resized and the number of columns and rows has changed. - -**Arguments**: - -- `pid`: Process ID of the PTY -- `size`: New size of the PTY -- `request_timeout`: Timeout for the request in **seconds**s - - - - - - -## Sandbox - -```python -class Sandbox(SandboxApi) -``` - -E2B cloud sandbox is a secure and isolated cloud environment. - -The sandbox allows you to: -- Access Linux OS -- Create, list, and delete files and directories -- Run commands -- Run isolated code -- Access the internet - -Check docs [here](https://e2b.dev/docs). - -Use the `Sandbox.create()` to create a new sandbox. - -**Example**: - -```python -from e2b import Sandbox - -sandbox = Sandbox.create() -``` - - - -### files - -```python -@property -def files() -> Filesystem -``` - -Module for interacting with the sandbox filesystem. - - - -### commands - -```python -@property -def commands() -> Commands -``` - -Module for running commands in the sandbox. - - - -### pty - -```python -@property -def pty() -> Pty -``` - -Module for interacting with the sandbox pseudo-terminal. - - - -### \_\_init\_\_ - -```python -def __init__(**opts: Unpack[SandboxOpts]) -``` - -:deprecated: This constructor is deprecated - -Use `Sandbox.create()` to create a new sandbox instead. - - - -### is\_running - -```python -def is_running(request_timeout: Optional[float] = None) -> bool -``` - -Check if the sandbox is running. - -**Arguments**: - -- `request_timeout`: Timeout for the request in **seconds** - -**Returns**: - -`True` if the sandbox is running, `False` otherwise -Example -```python -sandbox = Sandbox.create() -sandbox.is_running() # Returns True - -sandbox.kill() -sandbox.is_running() # Returns False -``` - - - -### create - -```python -@classmethod -def create(cls, - template: Optional[str] = None, - timeout: Optional[int] = None, - metadata: Optional[Dict[str, str]] = None, - envs: Optional[Dict[str, str]] = None, - secure: bool = True, - allow_internet_access: bool = True, - mcp: Optional[McpServer] = None, - network: Optional[SandboxNetworkOpts] = None, - **opts: Unpack[ApiParams]) -> Self -``` - -Create a new sandbox. - -By default, the sandbox is created from the default `base` sandbox template. - -**Arguments**: - -- `template`: Sandbox template name or ID -- `timeout`: Timeout for the sandbox in **seconds**, default to 300 seconds. The maximum time a sandbox can be kept alive is 24 hours (86_400 seconds) for Pro users and 1 hour (3_600 seconds) for Hobby users. -- `metadata`: Custom metadata for the sandbox -- `envs`: Custom environment variables for the sandbox -- `secure`: Envd is secured with access token and cannot be used without it, defaults to `True`. -- `allow_internet_access`: Allow sandbox to access the internet, defaults to `True`. If set to `False`, it works the same as setting network `deny_out` to `[0.0.0.0/0]`. -- `mcp`: MCP server to enable in the sandbox -- `network`: Sandbox network configuration - -**Returns**: - -A Sandbox instance for the new sandbox -Use this method instead of using the constructor to create a new sandbox. - - - -### connect - -```python -@overload -def connect(timeout: Optional[int] = None, **opts: Unpack[ApiParams]) -> Self -``` - -Connect to a sandbox. If the sandbox is paused, it will be automatically resumed. - -Sandbox must be either running or be paused. - -With sandbox ID you can connect to the same sandbox from different places or environments (serverless functions, etc). - -**Arguments**: - -- `timeout`: Timeout for the sandbox in **seconds** -For running sandboxes, the timeout will update only if the new timeout is longer than the existing one. - -**Returns**: - -A running sandbox instance -@example -```python -sandbox = Sandbox.create() -sandbox.beta_pause() - -same_sandbox = sandbox.connect() - - - -### connect - -```python -@overload -@classmethod -def connect(cls, - sandbox_id: str, - timeout: Optional[int] = None, - **opts: Unpack[ApiParams]) -> Self -``` - -Connect to a sandbox. If the sandbox is paused, it will be automatically resumed. - -Sandbox must be either running or be paused. - -With sandbox ID you can connect to the same sandbox from different places or environments (serverless functions, etc). - -**Arguments**: - -- `sandbox_id`: Sandbox ID -- `timeout`: Timeout for the sandbox in **seconds**. -For running sandboxes, the timeout will update only if the new timeout is longer than the existing one. - -**Returns**: - -A running sandbox instance -@example -```python -sandbox = Sandbox.create() -Sandbox.beta_pause(sandbox.sandbox_id) - -same_sandbox = Sandbox.connect(sandbox.sandbox_id) -``` - - - -### connect - -```python -@class_method_variant("_cls_connect") -def connect(timeout: Optional[int] = None, **opts: Unpack[ApiParams]) -> Self -``` - -Connect to a sandbox. If the sandbox is paused, it will be automatically resumed. - -Sandbox must be either running or be paused. - -With sandbox ID you can connect to the same sandbox from different places or environments (serverless functions, etc). - -**Arguments**: - -- `timeout`: Timeout for the sandbox in **seconds**. -For running sandboxes, the timeout will update only if the new timeout is longer than the existing one. - -**Returns**: - -A running sandbox instance -@example -```python -sandbox = Sandbox.create() -sandbox.beta_pause() - -same_sandbox = sandbox.connect() -``` - - - -### kill - -```python -@overload -def kill(**opts: Unpack[ApiParams]) -> bool -``` - -Kill the sandbox. - -**Returns**: - -`True` if the sandbox was killed, `False` if the sandbox was not found - - - -### kill - -```python -@overload -@staticmethod -def kill(sandbox_id: str, **opts: Unpack[ApiParams]) -> bool -``` - -Kill the sandbox specified by sandbox ID. - -**Arguments**: - -- `sandbox_id`: Sandbox ID - -**Returns**: - -`True` if the sandbox was killed, `False` if the sandbox was not found - - - -### kill - -```python -@class_method_variant("_cls_kill") -def kill(**opts: Unpack[ApiParams]) -> bool -``` - -Kill the sandbox specified by sandbox ID. - -**Returns**: - -`True` if the sandbox was killed, `False` if the sandbox was not found - - - -### set\_timeout - -```python -@overload -def set_timeout(timeout: int, **opts: Unpack[ApiParams]) -> None -``` - -Set the timeout of the sandbox. - -After the timeout expires, the sandbox will be automatically killed. -This method can extend or reduce the sandbox timeout set when creating the sandbox or from the last call to `.set_timeout`. - -The maximum time a sandbox can be kept alive is 24 hours (86_400 seconds) for Pro users and 1 hour (3_600 seconds) for Hobby users. - -**Arguments**: - -- `timeout`: Timeout for the sandbox in **seconds** - - - -### set\_timeout - -```python -@overload -@staticmethod -def set_timeout(sandbox_id: str, timeout: int, - **opts: Unpack[ApiParams]) -> None -``` - -Set the timeout of the sandbox specified by sandbox ID. - -After the timeout expires, the sandbox will be automatically killed. -This method can extend or reduce the sandbox timeout set when creating the sandbox or from the last call to `.set_timeout`. - -The maximum time a sandbox can be kept alive is 24 hours (86_400 seconds) for Pro users and 1 hour (3_600 seconds) for Hobby users. - -**Arguments**: - -- `sandbox_id`: Sandbox ID -- `timeout`: Timeout for the sandbox in **seconds** - - - -### set\_timeout - -```python -@class_method_variant("_cls_set_timeout") -def set_timeout(timeout: int, **opts: Unpack[ApiParams]) -> None -``` - -Set the timeout of the sandbox. - -After the timeout expires, the sandbox will be automatically killed. -This method can extend or reduce the sandbox timeout set when creating the sandbox or from the last call to `.set_timeout`. - -The maximum time a sandbox can be kept alive is 24 hours (86_400 seconds) for Pro users and 1 hour (3_600 seconds) for Hobby users. - -**Arguments**: - -- `timeout`: Timeout for the sandbox in **seconds** - - - -### get\_info - -```python -@overload -def get_info(**opts: Unpack[ApiParams]) -> SandboxInfo -``` - -Get sandbox information like sandbox ID, template, metadata, started at/end at date. - -**Returns**: - -Sandbox info - - - -### get\_info - -```python -@overload -@staticmethod -def get_info(sandbox_id: str, **opts: Unpack[ApiParams]) -> SandboxInfo -``` - -Get sandbox information like sandbox ID, template, metadata, started at/end at date. - -**Arguments**: - -- `sandbox_id`: Sandbox ID - -**Returns**: - -Sandbox info - - - -### get\_info - -```python -@class_method_variant("_cls_get_info") -def get_info(**opts: Unpack[ApiParams]) -> SandboxInfo -``` - -Get sandbox information like sandbox ID, template, metadata, started at/end at date. - -**Returns**: - -Sandbox info - - - -### get\_metrics - -```python -@overload -def get_metrics(start: Optional[datetime.datetime] = None, - end: Optional[datetime.datetime] = None, - **opts: Unpack[ApiParams]) -> List[SandboxMetrics] -``` - -Get the metrics of the current sandbox. - -**Arguments**: - -- `start`: Start time for the metrics, defaults to the start of the sandbox -- `end`: End time for the metrics, defaults to the current time - -**Returns**: - -List of sandbox metrics containing CPU, memory and disk usage information - - - -### get\_metrics - -```python -@overload -@staticmethod -def get_metrics(sandbox_id: str, - start: Optional[datetime.datetime] = None, - end: Optional[datetime.datetime] = None, - **opts: Unpack[ApiParams]) -> List[SandboxMetrics] -``` - -Get the metrics of the sandbox specified by sandbox ID. - -**Arguments**: - -- `sandbox_id`: Sandbox ID -- `start`: Start time for the metrics, defaults to the start of the sandbox -- `end`: End time for the metrics, defaults to the current time - -**Returns**: - -List of sandbox metrics containing CPU, memory and disk usage information - - - -### get\_metrics - -```python -@class_method_variant("_cls_get_metrics") -def get_metrics(start: Optional[datetime.datetime] = None, - end: Optional[datetime.datetime] = None, - **opts: Unpack[ApiParams]) -> List[SandboxMetrics] -``` - -Get the metrics of the sandbox specified by sandbox ID. - -**Arguments**: - -- `start`: Start time for the metrics, defaults to the start of the sandbox -- `end`: End time for the metrics, defaults to the current time - -**Returns**: - -List of sandbox metrics containing CPU, memory and disk usage information - - - -### beta\_create - -```python -@classmethod -def beta_create(cls, - template: Optional[str] = None, - timeout: Optional[int] = None, - auto_pause: bool = False, - metadata: Optional[Dict[str, str]] = None, - envs: Optional[Dict[str, str]] = None, - secure: bool = True, - allow_internet_access: bool = True, - mcp: Optional[McpServer] = None, - **opts: Unpack[ApiParams]) -> Self -``` - -[BETA] This feature is in beta and may change in the future. - -Create a new sandbox. - -By default, the sandbox is created from the default `base` sandbox template. - -**Arguments**: - -- `template`: Sandbox template name or ID -- `timeout`: Timeout for the sandbox in **seconds**, default to 300 seconds. The maximum time a sandbox can be kept alive is 24 hours (86_400 seconds) for Pro users and 1 hour (3_600 seconds) for Hobby users. -- `auto_pause`: Automatically pause the sandbox after the timeout expires. Defaults to `False`. -- `metadata`: Custom metadata for the sandbox -- `envs`: Custom environment variables for the sandbox -- `secure`: Envd is secured with access token and cannot be used without it, defaults to `True`. -- `allow_internet_access`: Allow sandbox to access the internet, defaults to `True`. -- `mcp`: MCP server to enable in the sandbox - -**Returns**: - -A Sandbox instance for the new sandbox -Use this method instead of using the constructor to create a new sandbox. - - - -### beta\_pause - -```python -@overload -def beta_pause(**opts: Unpack[ApiParams]) -> None -``` - -[BETA] This feature is in beta and may change in the future. - -Pause the sandbox. - - - -### beta\_pause - -```python -@overload -@classmethod -def beta_pause(cls, sandbox_id: str, **opts: Unpack[ApiParams]) -> None -``` - -[BETA] This feature is in beta and may change in the future. - -Pause the sandbox specified by sandbox ID. - -**Arguments**: - -- `sandbox_id`: Sandbox ID - - - -### beta\_pause - -```python -@class_method_variant("_cls_pause") -def beta_pause(**opts: Unpack[ApiParams]) -> None -``` - -[BETA] This feature is in beta and may change in the future. - -Pause the sandbox. - -**Returns**: - -Sandbox ID that can be used to resume the sandbox - - - -### get\_mcp\_token - -```python -def get_mcp_token() -> Optional[str] -``` - -Get the MCP token for the sandbox. - -**Returns**: - -MCP token for the sandbox, or None if MCP is not enabled. diff --git a/docs/sdk-reference/python-sdk/v2.8.1/template.mdx b/docs/sdk-reference/python-sdk/v2.8.1/template.mdx deleted file mode 100644 index e93bb10..0000000 --- a/docs/sdk-reference/python-sdk/v2.8.1/template.mdx +++ /dev/null @@ -1,1704 +0,0 @@ ---- -sidebarTitle: "Template" -mode: "center" ---- - - - - - - -## DockerfFileFinalParserInterface - -```python -class DockerfFileFinalParserInterface(Protocol) -``` - -Protocol defining the final interface for Dockerfile parsing callbacks. - - - -## DockerfileParserInterface - -```python -class DockerfileParserInterface(Protocol) -``` - -Protocol defining the interface for Dockerfile parsing callbacks. - - - -### run\_cmd - -```python -def run_cmd(command: Union[str, List[str]], - user: Optional[str] = None) -> "DockerfileParserInterface" -``` - -Handle RUN instruction. - - - -### copy - -```python -def copy(src: Union[str, List[CopyItem]], - dest: Optional[str] = None, - force_upload: Optional[Literal[True]] = None, - resolve_symlinks: Optional[bool] = None, - user: Optional[str] = None, - mode: Optional[int] = None) -> "DockerfileParserInterface" -``` - -Handle COPY instruction. - - - -### set\_workdir - -```python -def set_workdir(workdir: str) -> "DockerfileParserInterface" -``` - -Handle WORKDIR instruction. - - - -### set\_user - -```python -def set_user(user: str) -> "DockerfileParserInterface" -``` - -Handle USER instruction. - - - -### set\_envs - -```python -def set_envs(envs: Dict[str, str]) -> "DockerfileParserInterface" -``` - -Handle ENV instruction. - - - -### set\_start\_cmd - -```python -def set_start_cmd(start_cmd: str, - ready_cmd: str) -> "DockerfFileFinalParserInterface" -``` - -Handle CMD/ENTRYPOINT instruction. - - - -### parse\_dockerfile - -```python -def parse_dockerfile(dockerfile_content_or_path: str, - template_builder: DockerfileParserInterface) -> str -``` - -Parse a Dockerfile and convert it to Template SDK format. - -**Arguments**: - -- `dockerfile_content_or_path`: Either the Dockerfile content as a string, or a path to a Dockerfile file -- `template_builder`: Interface providing template builder methods - -**Raises**: - -- `ValueError`: If the Dockerfile is invalid or unsupported - -**Returns**: - -The base image from the Dockerfile - - - - - - -## InstructionType - -```python -class InstructionType(str, Enum) -``` - -Types of instructions that can be used in a template. - - - -## CopyItem - -```python -class CopyItem(TypedDict) -``` - -Configuration for a single file/directory copy operation. - - - -## Instruction - -```python -class Instruction(TypedDict) -``` - -Represents a single instruction in the template build process. - - - -## GenericDockerRegistry - -```python -class GenericDockerRegistry(TypedDict) -``` - -Configuration for a generic Docker registry with basic authentication. - - - -## AWSRegistry - -```python -class AWSRegistry(TypedDict) -``` - -Configuration for AWS Elastic Container Registry (ECR). - - - -## GCPRegistry - -```python -class GCPRegistry(TypedDict) -``` - -Configuration for Google Container Registry (GCR) or Artifact Registry. - - - -## TemplateType - -```python -class TemplateType(TypedDict) -``` - -Internal representation of a template for the E2B build API. - - - -## BuildInfo - -```python -@dataclass -class BuildInfo() -``` - -Information about a built template. - - - - - - -## LogEntry - -```python -@dataclass -class LogEntry() -``` - -Represents a single log entry from the template build process. - - - -## LogEntryStart - -```python -@dataclass -class LogEntryStart(LogEntry) -``` - -Special log entry indicating the start of a build process. - - - -## LogEntryEnd - -```python -@dataclass -class LogEntryEnd(LogEntry) -``` - -Special log entry indicating the end of a build process. - - - -### TIMER\_UPDATE\_INTERVAL\_MS - -Default minimum log level to display. - - - -### DEFAULT\_LEVEL - -Colored labels for each log level. - - - -### levels - -Numeric ordering of log levels for comparison (lower = less severe). - - - -### set\_interval - -```python -def set_interval(func, interval) -``` - -Returns a stop function that can be called to cancel the interval. - -Similar to JavaScript's setInterval. - -**Arguments**: - -- `func`: Function to execute at each interval -- `interval`: Interval duration in **seconds** - -**Returns**: - -Stop function that can be called to cancel the interval - - - -### default\_build\_logger - -```python -def default_build_logger( - min_level: Optional[LogEntryLevel] = None -) -> Callable[[LogEntry], None] -``` - -Create a default build logger with animated timer display. - -**Arguments**: - -- `min_level`: Minimum log level to display (default: 'info') - -**Returns**: - -Logger function that accepts LogEntry instances -Example -```python -from e2b import Template, default_build_logger - -template = Template().from_python_image() - -``` - - - - -Special step name for the finalization phase of template building. -This is the last step that runs after all user-defined instructions. - - - -### FINALIZE\_STEP\_NAME - -Special step name for the base image phase of template building. -This is the first step that sets up the base image. - - - -### BASE\_STEP\_NAME - -Stack trace depth for capturing caller information. - -Depth levels: -1. TemplateClass -2. Caller method (e.g., copy(), from_image(), etc.) - -This depth is used to determine the original caller's location -for stack traces. - - - -### STACK\_TRACE\_DEPTH - -Default setting for whether to resolve symbolic links when copying files. -When False, symlinks are copied as symlinks rather than following them. - - - - - - -## ReadyCmd - -```python -class ReadyCmd() -``` - -Wrapper class for ready check commands. - - - -### wait\_for\_port - -```python -def wait_for_port(port: int) -``` - -Wait for a port to be listening. - -Uses `ss` command to check if a port is open and listening. - -**Arguments**: - -- `port`: Port number to wait for - -**Returns**: - -ReadyCmd that checks for the port -Example -```python -from e2b import Template, wait_for_port - -template = ( - Template() - .from_python_image() - .set_start_cmd('python -m http.server 8000', wait_for_port(8000)) -) -``` - - - -### wait\_for\_url - -```python -def wait_for_url(url: str, status_code: int = 200) -``` - -Wait for a URL to return a specific HTTP status code. - -Uses `curl` to make HTTP requests and check the response status. - -**Arguments**: - -- `url`: URL to check (e.g., 'http://localhost:3000/health') -- `status_code`: Expected HTTP status code (default: 200) - -**Returns**: - -ReadyCmd that checks the URL -Example -```python -from e2b import Template, wait_for_url - -template = ( - Template() - .from_node_image() - .set_start_cmd('npm start', wait_for_url('http://localhost:3000/health')) -) -``` - - - -### wait\_for\_process - -```python -def wait_for_process(process_name: str) -``` - -Wait for a process with a specific name to be running. - -Uses `pgrep` to check if a process exists. - -**Arguments**: - -- `process_name`: Name of the process to wait for - -**Returns**: - -ReadyCmd that checks for the process -Example -```python -from e2b import Template, wait_for_process - -template = ( - Template() - .from_base_image() - .set_start_cmd('./my-daemon', wait_for_process('my-daemon')) -) -``` - - - -### wait\_for\_file - -```python -def wait_for_file(filename: str) -``` - -Wait for a file to exist. - -Uses shell test command to check file existence. - -**Arguments**: - -- `filename`: Path to the file to wait for - -**Returns**: - -ReadyCmd that checks for the file -Example -```python -from e2b import Template, wait_for_file - -template = ( - Template() - .from_base_image() - .set_start_cmd('./init.sh', wait_for_file('/tmp/ready')) -) -``` - - - -### wait\_for\_timeout - -```python -def wait_for_timeout(timeout: int) -``` - -Wait for a specified timeout before considering the sandbox ready. - -Uses `sleep` command to wait for a fixed duration. - -**Arguments**: - -- `timeout`: Time to wait in **milliseconds** (minimum: 1000ms / 1 second) - -**Returns**: - -ReadyCmd that waits for the specified duration -Example -```python -from e2b import Template, wait_for_timeout - -template = ( - Template() - .from_node_image() - .set_start_cmd('npm start', wait_for_timeout(5000)) # Wait 5 seconds -) -``` - - - - - - -### read\_dockerignore - -```python -def read_dockerignore(context_path: str) -> List[str] -``` - -Read and parse a .dockerignore file. - -**Arguments**: - -- `context_path`: Directory path containing the .dockerignore file - -**Returns**: - -Array of ignore patterns (empty lines and comments are filtered out) - - - -### normalize\_path - -```python -def normalize_path(path: str) -> str -``` - -Normalize path separators to forward slashes for glob patterns (glob expects / even on Windows). - -**Arguments**: - -- `path`: The path to normalize - -**Returns**: - -The normalized path - - - -### get\_all\_files\_in\_path - -```python -def get_all_files_in_path(src: str, - context_path: str, - ignore_patterns: List[str], - include_directories: bool = True) -> List[str] -``` - -Get all files for a given path and ignore patterns. - -**Arguments**: - -- `src`: Path to the source directory -- `context_path`: Base directory for resolving relative paths -- `ignore_patterns`: Ignore patterns -- `include_directories`: Whether to include directories - -**Returns**: - -Array of files - - - -### calculate\_files\_hash - -```python -def calculate_files_hash(src: str, dest: str, context_path: str, - ignore_patterns: List[str], resolve_symlinks: bool, - stack_trace: Optional[TracebackType]) -> str -``` - -Calculate a hash of files being copied to detect changes for cache invalidation. - -The hash includes file content, metadata (mode, size), and relative paths. -Note: uid, gid, and mtime are excluded to ensure stable hashes across environments. - -**Arguments**: - -- `src`: Source path pattern for files to copy -- `dest`: Destination path where files will be copied -- `context_path`: Base directory for resolving relative paths -- `ignore_patterns`: Glob patterns to ignore -- `resolve_symlinks`: Whether to resolve symbolic links when hashing -- `stack_trace`: Optional stack trace for error reporting - -**Raises**: - -- `ValueError`: If no files match the source pattern - -**Returns**: - -Hex string hash of all files - - - -### tar\_file\_stream - -```python -def tar_file_stream(file_name: str, file_context_path: str, - ignore_patterns: List[str], - resolve_symlinks: bool) -> io.BytesIO -``` - -Create a tar stream of files matching a pattern. - -**Arguments**: - -- `file_name`: Glob pattern for files to include -- `file_context_path`: Base directory for resolving file paths -- `ignore_patterns`: Ignore patterns -- `resolve_symlinks`: Whether to resolve symbolic links - -**Returns**: - -Tar stream - - - -### strip\_ansi\_escape\_codes - -```python -def strip_ansi_escape_codes(text: str) -> str -``` - -Strip ANSI escape codes from a string. - -Source: https://github.com/chalk/ansi-regex/blob/main/index.js - -**Arguments**: - -- `text`: String with ANSI escape codes - -**Returns**: - -String without ANSI escape codes - - - -### get\_caller\_frame - -```python -def get_caller_frame(depth: int) -> Optional[FrameType] -``` - -Get the caller's stack frame at a specific depth. - -This is used to provide better error messages and debugging information -by tracking where template methods were called from in user code. - -**Arguments**: - -- `depth`: The depth of the stack trace to retrieve - -**Returns**: - -The caller frame, or None if not available - - - -### get\_caller\_directory - -```python -def get_caller_directory(depth: int) -> Optional[str] -``` - -Get the directory of the caller at a specific stack depth. - -This is used to determine the file_context_path when creating a template, -so file paths are resolved relative to the user's template file location. - -**Arguments**: - -- `depth`: The depth of the stack trace - -**Returns**: - -The caller's directory path, or None if not available - - - -### pad\_octal - -```python -def pad_octal(mode: int) -> str -``` - -Convert a numeric file mode to a zero-padded octal string. - -**Arguments**: - -- `mode`: File mode as a number (e.g., 493 for 0o755) - -**Returns**: - -Zero-padded 4-digit octal string (e.g., "0755") -Example -```python -pad_octal(0o755) # Returns "0755" -pad_octal(0o644) # Returns "0644" -``` - - - -### get\_build\_step\_index - -```python -def get_build_step_index(step: str, stack_traces_length: int) -> int -``` - -Get the array index for a build step based on its name. - -Special steps: -- BASE_STEP_NAME: Returns 0 (first step) -- FINALIZE_STEP_NAME: Returns the last index -- Numeric strings: Converted to number - -**Arguments**: - -- `step`: Build step name or number as string -- `stack_traces_length`: Total number of stack traces (used for FINALIZE_STEP_NAME) - -**Returns**: - -Index for the build step - - - -### read\_gcp\_service\_account\_json - -```python -def read_gcp_service_account_json(context_path: str, - path_or_content: Union[str, dict]) -> str -``` - -Read GCP service account JSON from a file or object. - -**Arguments**: - -- `context_path`: Base directory for resolving relative file paths -- `path_or_content`: Either a path to a JSON file or a service account object - -**Returns**: - -Service account JSON as a string - - - - - - -## TemplateBuilder - -```python -class TemplateBuilder() -``` - -Builder class for adding instructions to an E2B template. - -All methods return self to allow method chaining. - - - -### copy - -```python -def copy(src: Union[Union[str, Path], List[Union[str, Path]]], - dest: Union[str, Path], - force_upload: Optional[Literal[True]] = None, - user: Optional[str] = None, - mode: Optional[int] = None, - resolve_symlinks: Optional[bool] = None) -> "TemplateBuilder" -``` - -Copy files or directories from the local filesystem into the template. - -**Arguments**: - -- `src`: Source file(s) or directory path(s) to copy -- `dest`: Destination path in the template -- `force_upload`: Force upload even if files are cached -- `user`: User and optionally group (user:group) to own the files -- `mode`: File permissions in octal format (e.g., 0o755) -- `resolve_symlinks`: Whether to resolve symlinks - -**Returns**: - -`TemplateBuilder` class -Example -```python -template.copy('requirements.txt', '/home/user/') -template.copy(['app.py', 'config.py'], '/app/', mode=0o755) -``` - - - -### copy\_items - -```python -def copy_items(items: List[CopyItem]) -> "TemplateBuilder" -``` - -Copy multiple files or directories using a list of copy items. - -**Arguments**: - -- `items`: List of CopyItem dictionaries with src, dest, and optional parameters - -**Returns**: - -`TemplateBuilder` class -Example -```python -template.copy_items([ - {'src': 'app.py', 'dest': '/app/'}, - {'src': 'config.py', 'dest': '/app/', 'mode': 0o644} -]) -``` - - - -### remove - -```python -def remove(path: Union[Union[str, Path], List[Union[str, Path]]], - force: bool = False, - recursive: bool = False, - user: Optional[str] = None) -> "TemplateBuilder" -``` - -Remove files or directories in the template. - -**Arguments**: - -- `path`: File(s) or directory path(s) to remove -- `force`: Force removal without prompting -- `recursive`: Remove directories recursively -- `user`: User to run the command as - -**Returns**: - -`TemplateBuilder` class -Example -```python -template.remove('/tmp/cache', recursive=True, force=True) -template.remove('/tmp/cache', recursive=True, force=True, user='root') -``` - - - -### rename - -```python -def rename(src: Union[str, Path], - dest: Union[str, Path], - force: bool = False, - user: Optional[str] = None) -> "TemplateBuilder" -``` - -Rename or move a file or directory in the template. - -**Arguments**: - -- `src`: Source path -- `dest`: Destination path -- `force`: Force rename without prompting -- `user`: User to run the command as - -**Returns**: - -`TemplateBuilder` class -Example -```python -template.rename('/tmp/old.txt', '/tmp/new.txt') -template.rename('/tmp/old.txt', '/tmp/new.txt', user='root') -``` - - - -### make\_dir - -```python -def make_dir(path: Union[Union[str, Path], List[Union[str, Path]]], - mode: Optional[int] = None, - user: Optional[str] = None) -> "TemplateBuilder" -``` - -Create directory(ies) in the template. - -**Arguments**: - -- `path`: Directory path(s) to create -- `mode`: Directory permissions in octal format (e.g., 0o755) -- `user`: User to run the command as - -**Returns**: - -`TemplateBuilder` class -Example -```python -template.make_dir('/app/data', mode=0o755) -template.make_dir(['/app/logs', '/app/cache']) -template.make_dir('/app/data', mode=0o755, user='root') -``` - - - -### make\_symlink - -```python -def make_symlink(src: Union[str, Path], - dest: Union[str, Path], - user: Optional[str] = None, - force: bool = False) -> "TemplateBuilder" -``` - -Create a symbolic link in the template. - -**Arguments**: - -- `src`: Source path (target of the symlink) -- `dest`: Destination path (location of the symlink) -- `user`: User to run the command as -- `force`: Force symlink without prompting - -**Returns**: - -`TemplateBuilder` class -Example -```python -template.make_symlink('/usr/bin/python3', '/usr/bin/python') -template.make_symlink('/usr/bin/python3', '/usr/bin/python', user='root') -template.make_symlink('/usr/bin/python3', '/usr/bin/python', force=True) -``` - - - -### run\_cmd - -```python -def run_cmd(command: Union[str, List[str]], - user: Optional[str] = None) -> "TemplateBuilder" -``` - -Run a shell command during template build. - -**Arguments**: - -- `command`: Command string or list of commands to run (joined with &&) -- `user`: User to run the command as - -**Returns**: - -`TemplateBuilder` class -Example -```python -template.run_cmd('apt-get update') -template.run_cmd(['pip install numpy', 'pip install pandas']) -template.run_cmd('apt-get install vim', user='root') -``` - - - -### set\_workdir - -```python -def set_workdir(workdir: Union[str, Path]) -> "TemplateBuilder" -``` - -Set the working directory for subsequent commands in the template. - -**Arguments**: - -- `workdir`: Path to set as the working directory - -**Returns**: - -`TemplateBuilder` class -Example -```python -template.set_workdir('/app') -``` - - - -### set\_user - -```python -def set_user(user: str) -> "TemplateBuilder" -``` - -Set the user for subsequent commands in the template. - -**Arguments**: - -- `user`: Username to set - -**Returns**: - -`TemplateBuilder` class -Example -```python -template.set_user('root') -``` - - - -### pip\_install - -```python -def pip_install(packages: Optional[Union[str, List[str]]] = None, - g: bool = True) -> "TemplateBuilder" -``` - -Install Python packages using pip. - -**Arguments**: - -- `packages`: Package name(s) to install. If None, runs 'pip install .' in the current directory -- `g`: Install packages globally (default: True). If False, installs for user only - -**Returns**: - -`TemplateBuilder` class -Example -```python -template.pip_install('numpy') -template.pip_install(['pandas', 'scikit-learn']) -template.pip_install('numpy', g=False) # Install for user only -template.pip_install() # Installs from current directory -``` - - - -### npm\_install - -```python -def npm_install(packages: Optional[Union[str, List[str]]] = None, - g: Optional[bool] = False, - dev: Optional[bool] = False) -> "TemplateBuilder" -``` - -Install Node.js packages using npm. - -**Arguments**: - -- `packages`: Package name(s) to install. If None, installs from package.json -- `g`: Install packages globally -- `dev`: Install packages as dev dependencies - -**Returns**: - -`TemplateBuilder` class -Example -```python -template.npm_install('express') -template.npm_install(['lodash', 'axios']) -template.npm_install('typescript', g=True) -template.npm_install() # Installs from package.json -``` - - - -### bun\_install - -```python -def bun_install(packages: Optional[Union[str, List[str]]] = None, - g: Optional[bool] = False, - dev: Optional[bool] = False) -> "TemplateBuilder" -``` - -Install Bun packages using bun. - -**Arguments**: - -- `packages`: Package name(s) to install. If None, installs from package.json -- `g`: Install packages globally -- `dev`: Install packages as dev dependencies - -**Returns**: - -`TemplateBuilder` class -Example -```python -template.bun_install('express') -template.bun_install(['lodash', 'axios']) -template.bun_install('tsx', g=True) -template.bun_install('typescript', dev=True) -template.bun_install() // Installs from package.json -``` - - - -### apt\_install - -```python -def apt_install(packages: Union[str, List[str]], - no_install_recommends: bool = False) -> "TemplateBuilder" -``` - -Install system packages using apt-get. - -**Arguments**: - -- `packages`: Package name(s) to install -- `no_install_recommends`: Whether to install recommended packages - -**Returns**: - -`TemplateBuilder` class -Example -```python -template.apt_install('vim') -template.apt_install(['git', 'curl', 'wget']) -``` - - - -### add\_mcp\_server - -```python -def add_mcp_server(servers: Union[str, List[str]]) -> "TemplateBuilder" -``` - -Install MCP servers using mcp-gateway. - -Note: Requires a base image with mcp-gateway pre-installed (e.g., mcp-gateway). - -**Arguments**: - -- `servers`: MCP server name(s) - -**Returns**: - -`TemplateBuilder` class -Example -```python -template.add_mcp_server('exa') -template.add_mcp_server(['brave', 'firecrawl', 'duckduckgo']) -``` - - - -### git\_clone - -```python -def git_clone(url: str, - path: Optional[Union[str, Path]] = None, - branch: Optional[str] = None, - depth: Optional[int] = None, - user: Optional[str] = None) -> "TemplateBuilder" -``` - -Clone a git repository into the template. - -**Arguments**: - -- `url`: Git repository URL -- `path`: Destination path for the clone -- `branch`: Branch to clone -- `depth`: Clone depth for shallow clones -- `user`: User to run the command as - -**Returns**: - -`TemplateBuilder` class -Example -```python -template.git_clone('https://github.com/user/repo.git', '/app/repo') -template.git_clone('https://github.com/user/repo.git', branch='main', depth=1) -template.git_clone('https://github.com/user/repo.git', '/app/repo', user='root') -``` - - - -### beta\_dev\_container\_prebuild - -```python -def beta_dev_container_prebuild( - devcontainer_directory: Union[str, Path]) -> "TemplateBuilder" -``` - -Prebuild a devcontainer from the specified directory during the build process. - -**Arguments**: - -- `devcontainer_directory`: Path to the devcontainer directory - -**Returns**: - -`TemplateBuilder` class -Example -```python -template.git_clone('https://myrepo.com/project.git', '/my-devcontainer') -template.beta_dev_container_prebuild('/my-devcontainer') -``` - - - -### beta\_set\_dev\_container\_start - -```python -def beta_set_dev_container_start( - devcontainer_directory: Union[str, Path]) -> "TemplateFinal" -``` - -Start a devcontainer from the specified directory and set it as the start command. - -This method returns `TemplateFinal`, which means it must be the last method in the chain. - -**Arguments**: - -- `devcontainer_directory`: Path to the devcontainer directory - -**Returns**: - -`TemplateFinal` class -Example -```python -template.git_clone('https://myrepo.com/project.git', '/my-devcontainer') -template.beta_set_devcontainer_start('/my-devcontainer') - -template.git_clone('https://myrepo.com/project.git', '/my-devcontainer') -template.beta_dev_container_prebuild('/my-devcontainer') -template.beta_set_dev_container_start('/my-devcontainer') -``` - - - -### set\_envs - -```python -def set_envs(envs: Dict[str, str]) -> "TemplateBuilder" -``` - -Set environment variables in the template. - -**Arguments**: - -- `envs`: Dictionary of environment variable names and values - -**Returns**: - -`TemplateBuilder` class -Example -```python -template.set_envs({'NODE_ENV': 'production', 'PORT': '8080'}) -``` - - - -### skip\_cache - -```python -def skip_cache() -> "TemplateBuilder" -``` - -Skip cache for all subsequent build instructions from this point. - -Call this before any instruction to force it and all following layers -to be rebuilt, ignoring any cached layers. - -**Returns**: - -`TemplateBuilder` class -Example -```python -template.skip_cache().run_cmd('apt-get update') -``` - - - -### set\_start\_cmd - -```python -def set_start_cmd(start_cmd: str, - ready_cmd: Union[str, ReadyCmd]) -> "TemplateFinal" -``` - -Set the command to start when the sandbox launches and the ready check command. - -**Arguments**: - -- `start_cmd`: Command to run when the sandbox starts -- `ready_cmd`: Command or ReadyCmd to check if the sandbox is ready - -**Returns**: - -`TemplateFinal` class -Example -```python -template.set_start_cmd( - 'python app.py', - 'curl http://localhost:8000/health' -) - -from e2b import wait_for_port, wait_for_url - -template.set_start_cmd( - 'python -m http.server 8000', - wait_for_port(8000) -) - -template.set_start_cmd( - 'npm start', - wait_for_url('http://localhost:3000/health', 200) -) -``` - - - -### set\_ready\_cmd - -```python -def set_ready_cmd(ready_cmd: Union[str, ReadyCmd]) -> "TemplateFinal" -``` - -Set the command to check if the sandbox is ready. - -**Arguments**: - -- `ready_cmd`: Command or ReadyCmd to check if the sandbox is ready - -**Returns**: - -`TemplateFinal` class -Example -```python -template.set_ready_cmd('curl http://localhost:8000/health') - -from e2b import wait_for_port, wait_for_file, wait_for_process - -template.set_ready_cmd(wait_for_port(3000)) - -template.set_ready_cmd(wait_for_file('/tmp/ready')) - -template.set_ready_cmd(wait_for_process('nginx')) -``` - - - -## TemplateFinal - -```python -class TemplateFinal() -``` - -Final template state after start/ready commands are set. - - - -## TemplateBase - -```python -class TemplateBase() -``` - -Base class for building E2B sandbox templates. - - - -### \_\_init\_\_ - -```python -def __init__(file_context_path: Optional[Union[str, Path]] = None, - file_ignore_patterns: Optional[List[str]] = None) -``` - -Create a new template builder instance. - -**Arguments**: - -- `file_context_path`: Base path for resolving relative file paths in copy operations -- `file_ignore_patterns`: List of glob patterns to ignore when copying files - - - -### skip\_cache - -```python -def skip_cache() -> "TemplateBase" -``` - -Skip cache for all subsequent build instructions from this point. - -**Returns**: - -`TemplateBase` class -Example -```python -template.skip_cache().from_python_image('3.11') -``` - - - -### from\_debian\_image - -```python -def from_debian_image(variant: str = "stable") -> TemplateBuilder -``` - -Start template from a Debian base image. - -**Arguments**: - -- `variant`: Debian image variant - -**Returns**: - -`TemplateBuilder` class -Example -```python -Template().from_debian_image('bookworm') -``` - - - -### from\_ubuntu\_image - -```python -def from_ubuntu_image(variant: str = "latest") -> TemplateBuilder -``` - -Start template from an Ubuntu base image. - -**Arguments**: - -- `variant`: Ubuntu image variant (default: 'latest') - -**Returns**: - -`TemplateBuilder` class -Example -```python -Template().from_ubuntu_image('24.04') -``` - - - -### from\_python\_image - -```python -def from_python_image(version: str = "3") -> TemplateBuilder -``` - -Start template from a Python base image. - -**Arguments**: - -- `version`: Python version (default: '3') - -**Returns**: - -`TemplateBuilder` class -Example -```python -Template().from_python_image('3') -``` - - - -### from\_node\_image - -```python -def from_node_image(variant: str = "lts") -> TemplateBuilder -``` - -Start template from a Node.js base image. - -**Arguments**: - -- `variant`: Node.js image variant (default: 'lts') - -**Returns**: - -`TemplateBuilder` class -Example -```python -Template().from_node_image('24') -``` - - - -### from\_bun\_image - -```python -def from_bun_image(variant: str = "latest") -> TemplateBuilder -``` - -Start template from a Bun base image. - -**Arguments**: - -- `variant`: Bun image variant (default: 'latest') - -**Returns**: - -`TemplateBuilder` class - - - -### from\_base\_image - -```python -def from_base_image() -> TemplateBuilder -``` - -Start template from the E2B base image (e2bdev/base:latest). - -**Returns**: - -`TemplateBuilder` class -Example -```python -Template().from_base_image() -``` - - - -### from\_image - -```python -def from_image(image: str, - username: Optional[str] = None, - password: Optional[str] = None) -> TemplateBuilder -``` - -Start template from a Docker image. - -**Arguments**: - -- `image`: Docker image name (e.g., 'ubuntu:24.04') -- `username`: Username for private registry authentication -- `password`: Password for private registry authentication - -**Returns**: - -`TemplateBuilder` class -Example -```python -Template().from_image('python:3') - -Template().from_image('myregistry.com/myimage:latest', username='user', password='pass') -``` - - - -### from\_template - -```python -def from_template(template: str) -> TemplateBuilder -``` - -Start template from an existing E2B template. - -**Arguments**: - -- `template`: E2B template ID or alias - -**Returns**: - -`TemplateBuilder` class -Example -```python -Template().from_template('my-base-template') -``` - - - -### from\_dockerfile - -```python -def from_dockerfile(dockerfile_content_or_path: str) -> TemplateBuilder -``` - -Parse a Dockerfile and convert it to Template SDK format. - -**Arguments**: - -- `dockerfile_content_or_path`: Either the Dockerfile content as a string, or a path to a Dockerfile file - -**Returns**: - -`TemplateBuilder` class -Example -```python -Template().from_dockerfile('Dockerfile') -Template().from_dockerfile('FROM python:3\nRUN pip install numpy') -``` - - - -### from\_aws\_registry - -```python -def from_aws_registry(image: str, access_key_id: str, secret_access_key: str, - region: str) -> TemplateBuilder -``` - -Start template from an AWS ECR registry image. - -**Arguments**: - -- `image`: Docker image name from AWS ECR -- `access_key_id`: AWS access key ID -- `secret_access_key`: AWS secret access key -- `region`: AWS region - -**Returns**: - -`TemplateBuilder` class -Example -```python -Template().from_aws_registry( - '123456789.dkr.ecr.us-west-2.amazonaws.com/myimage:latest', - access_key_id='AKIA...', - secret_access_key='...', - region='us-west-2' -) -``` - - - -### from\_gcp\_registry - -```python -def from_gcp_registry( - image: str, service_account_json: Union[str, dict]) -> TemplateBuilder -``` - -Start template from a GCP Artifact Registry or Container Registry image. - -**Arguments**: - -- `image`: Docker image name from GCP registry -- `service_account_json`: Service account JSON string, dict, or path to JSON file - -**Returns**: - -`TemplateBuilder` class -Example -```python -Template().from_gcp_registry( - 'gcr.io/myproject/myimage:latest', - service_account_json='path/to/service-account.json' -) -``` - - - -### to\_json - -```python -@staticmethod -def to_json(template: "TemplateClass") -> str -``` - -Convert a template to JSON representation. - -**Arguments**: - -- `template`: The template to convert (TemplateBuilder or TemplateFinal instance) - -**Returns**: - -JSON string representation of the template -Example -```python -template = Template().from_python_image('3').copy('app.py', '/app/') -json_str = TemplateBase.to_json(template) -``` - - - -### to\_dockerfile - -```python -@staticmethod -def to_dockerfile(template: "TemplateClass") -> str -``` - -Convert a template to Dockerfile format. - -Note: Templates based on other E2B templates cannot be converted to Dockerfile. - -**Arguments**: - -- `template`: The template to convert (TemplateBuilder or TemplateFinal instance) - -**Raises**: - -- `ValueError`: If the template is based on another E2B template or has no base image -Example -```python -template = Template().from_python_image('3').copy('app.py', '/app/') -dockerfile = TemplateBase.to_dockerfile(template) -``` - -**Returns**: - -Dockerfile string representation diff --git a/docs/sdk-reference/python-sdk/v2.8.1/template_async.mdx b/docs/sdk-reference/python-sdk/v2.8.1/template_async.mdx deleted file mode 100644 index 950d066..0000000 --- a/docs/sdk-reference/python-sdk/v2.8.1/template_async.mdx +++ /dev/null @@ -1,150 +0,0 @@ ---- -sidebarTitle: "Template Async" -mode: "center" ---- - - - - - - - - - -## AsyncTemplate - -```python -class AsyncTemplate(TemplateBase) -``` - -Asynchronous template builder for E2B sandboxes. - - - -### build - -```python -@staticmethod -async def build(template: TemplateClass, - alias: str, - cpu_count: int = 2, - memory_mb: int = 1024, - skip_cache: bool = False, - on_build_logs: Optional[Callable[[LogEntry], None]] = None, - api_key: Optional[str] = None, - domain: Optional[str] = None) -> BuildInfo -``` - -Build and deploy a template to E2B infrastructure. - -**Arguments**: - -- `template`: The template to build -- `alias`: Alias name for the template -- `cpu_count`: Number of CPUs allocated to the sandbox -- `memory_mb`: Amount of memory in MB allocated to the sandbox -- `skip_cache`: If True, forces a complete rebuild ignoring cache -- `on_build_logs`: Callback function to receive build logs during the build process -- `api_key`: E2B API key for authentication -- `domain`: Domain of the E2B API -Example -```python -from e2b import AsyncTemplate - -template = ( - AsyncTemplate() - .from_python_image('3') - .copy('requirements.txt', '/home/user/') - .run_cmd('pip install -r /home/user/requirements.txt') -) - -await AsyncTemplate.build( - template, - alias='my-python-env', - cpu_count=2, - memory_mb=1024 -) -``` - - - -### build\_in\_background - -```python -@staticmethod -async def build_in_background(template: TemplateClass, - alias: str, - cpu_count: int = 2, - memory_mb: int = 1024, - skip_cache: bool = False, - on_build_logs: Optional[Callable[[LogEntry], - None]] = None, - api_key: Optional[str] = None, - domain: Optional[str] = None) -> BuildInfo -``` - -Build and deploy a template to E2B infrastructure without waiting for completion. - -**Arguments**: - -- `template`: The template to build -- `alias`: Alias name for the template -- `cpu_count`: Number of CPUs allocated to the sandbox -- `memory_mb`: Amount of memory in MB allocated to the sandbox -- `skip_cache`: If True, forces a complete rebuild ignoring cache -- `api_key`: E2B API key for authentication -- `domain`: Domain of the E2B API - -**Returns**: - -BuildInfo containing the template ID and build ID -Example -```python -from e2b import AsyncTemplate - -template = ( - AsyncTemplate() - .from_python_image('3') - .run_cmd('echo "test"') - .set_start_cmd('echo "Hello"', 'sleep 1') -) - -build_info = await AsyncTemplate.build_in_background( - template, - alias='my-python-env', - cpu_count=2, - memory_mb=1024 -) -``` - - - -### get\_build\_status - -```python -@staticmethod -async def get_build_status(build_info: BuildInfo, - logs_offset: int = 0, - api_key: Optional[str] = None, - domain: Optional[str] = None) -``` - -Get the status of a build. - -**Arguments**: - -- `build_info`: Build identifiers returned from build_in_background -- `logs_offset`: Offset for fetching logs -- `api_key`: E2B API key for authentication -- `domain`: Domain of the E2B API - -**Returns**: - -TemplateBuild containing the build status and logs -Example -```python -from e2b import AsyncTemplate - -build_info = await AsyncTemplate.build_in_background(template, alias='my-template') -status = await AsyncTemplate.get_build_status(build_info, logs_offset=0) -``` diff --git a/docs/sdk-reference/python-sdk/v2.8.1/template_sync.mdx b/docs/sdk-reference/python-sdk/v2.8.1/template_sync.mdx deleted file mode 100644 index 6387438..0000000 --- a/docs/sdk-reference/python-sdk/v2.8.1/template_sync.mdx +++ /dev/null @@ -1,150 +0,0 @@ ---- -sidebarTitle: "Template Sync" -mode: "center" ---- - - - - - - - - - -## Template - -```python -class Template(TemplateBase) -``` - -Synchronous template builder for E2B sandboxes. - - - -### build - -```python -@staticmethod -def build(template: TemplateClass, - alias: str, - cpu_count: int = 2, - memory_mb: int = 1024, - skip_cache: bool = False, - on_build_logs: Optional[Callable[[LogEntry], None]] = None, - api_key: Optional[str] = None, - domain: Optional[str] = None) -> BuildInfo -``` - -Build and deploy a template to E2B infrastructure. - -**Arguments**: - -- `template`: The template to build -- `alias`: Alias name for the template -- `cpu_count`: Number of CPUs allocated to the sandbox -- `memory_mb`: Amount of memory in MB allocated to the sandbox -- `skip_cache`: If True, forces a complete rebuild ignoring cache -- `on_build_logs`: Callback function to receive build logs during the build process -- `api_key`: E2B API key for authentication -- `domain`: Domain of the E2B API -Example -```python -from e2b import Template - -template = ( - Template() - .from_python_image('3') - .copy('requirements.txt', '/home/user/') - .run_cmd('pip install -r /home/user/requirements.txt') -) - -Template.build( - template, - alias='my-python-env', - cpu_count=2, - memory_mb=1024 -) -``` - - - -### build\_in\_background - -```python -@staticmethod -def build_in_background(template: TemplateClass, - alias: str, - cpu_count: int = 2, - memory_mb: int = 1024, - skip_cache: bool = False, - on_build_logs: Optional[Callable[[LogEntry], - None]] = None, - api_key: Optional[str] = None, - domain: Optional[str] = None) -> BuildInfo -``` - -Build and deploy a template to E2B infrastructure without waiting for completion. - -**Arguments**: - -- `template`: The template to build -- `alias`: Alias name for the template -- `cpu_count`: Number of CPUs allocated to the sandbox -- `memory_mb`: Amount of memory in MB allocated to the sandbox -- `skip_cache`: If True, forces a complete rebuild ignoring cache -- `api_key`: E2B API key for authentication -- `domain`: Domain of the E2B API - -**Returns**: - -BuildInfo containing the template ID and build ID -Example -```python -from e2b import Template - -template = ( - Template() - .from_python_image('3') - .run_cmd('echo "test"') - .set_start_cmd('echo "Hello"', 'sleep 1') -) - -build_info = Template.build_in_background( - template, - alias='my-python-env', - cpu_count=2, - memory_mb=1024 -) -``` - - - -### get\_build\_status - -```python -@staticmethod -def get_build_status(build_info: BuildInfo, - logs_offset: int = 0, - api_key: Optional[str] = None, - domain: Optional[str] = None) -``` - -Get the status of a build. - -**Arguments**: - -- `build_info`: Build identifiers returned from build_in_background -- `logs_offset`: Offset for fetching logs -- `api_key`: E2B API key for authentication -- `domain`: Domain of the E2B API - -**Returns**: - -TemplateBuild containing the build status and logs -Example -```python -from e2b import Template - -build_info = Template.build_in_background(template, alias='my-template') -status = Template.get_build_status(build_info, logs_offset=0) -``` diff --git a/docs/sdk-reference/python-sdk/v2.9.0/exceptions.mdx b/docs/sdk-reference/python-sdk/v2.9.0/exceptions.mdx deleted file mode 100644 index d66f786..0000000 --- a/docs/sdk-reference/python-sdk/v2.9.0/exceptions.mdx +++ /dev/null @@ -1,117 +0,0 @@ ---- -sidebarTitle: "Exceptions" -mode: "center" ---- - - - - - - -## SandboxException - -```python -class SandboxException(Exception) -``` - -Base class for all sandbox errors. - -Raised when a general sandbox exception occurs. - - - -## TimeoutException - -```python -class TimeoutException(SandboxException) -``` - -Raised when a timeout occurs. - -The `unavailable` exception type is caused by sandbox timeout. - -The `canceled` exception type is caused by exceeding request timeout. - -The `deadline_exceeded` exception type is caused by exceeding the timeout for process, watch, etc. - -The `unknown` exception type is sometimes caused by the sandbox timeout when the request is not processed correctly. - - - -## InvalidArgumentException - -```python -class InvalidArgumentException(SandboxException) -``` - -Raised when an invalid argument is provided. - - - -## NotEnoughSpaceException - -```python -class NotEnoughSpaceException(SandboxException) -``` - -Raised when there is not enough disk space. - - - -## NotFoundException - -```python -class NotFoundException(SandboxException) -``` - -Raised when a resource is not found. - - - -## AuthenticationException - -```python -class AuthenticationException(Exception) -``` - -Raised when authentication fails. - - - -## TemplateException - -```python -class TemplateException(SandboxException) -``` - -Exception raised when the template uses old envd version. It isn't compatible with the new SDK. - - - -## RateLimitException - -```python -class RateLimitException(SandboxException) -``` - -Raised when the API rate limit is exceeded. - - - -## BuildException - -```python -class BuildException(Exception) -``` - -Raised when the build fails. - - - -## FileUploadException - -```python -class FileUploadException(BuildException) -``` - -Raised when the file upload fails. diff --git a/docs/sdk-reference/python-sdk/v2.9.0/logger.mdx b/docs/sdk-reference/python-sdk/v2.9.0/logger.mdx deleted file mode 100644 index 9fa3b18..0000000 --- a/docs/sdk-reference/python-sdk/v2.9.0/logger.mdx +++ /dev/null @@ -1,106 +0,0 @@ ---- -sidebarTitle: "Logger" -mode: "center" ---- - - - - - - -## LogEntry - -```python -@dataclass -class LogEntry() -``` - -Represents a single log entry from the template build process. - - - -## LogEntryStart - -```python -@dataclass -class LogEntryStart(LogEntry) -``` - -Special log entry indicating the start of a build process. - - - -## LogEntryEnd - -```python -@dataclass -class LogEntryEnd(LogEntry) -``` - -Special log entry indicating the end of a build process. - - - -### TIMER\_UPDATE\_INTERVAL\_MS - -Default minimum log level to display. - - - -### DEFAULT\_LEVEL - -Colored labels for each log level. - - - -### levels - -Numeric ordering of log levels for comparison (lower = less severe). - - - -### set\_interval - -```python -def set_interval(func, interval) -``` - -Returns a stop function that can be called to cancel the interval. - -Similar to JavaScript's setInterval. - -**Arguments**: - -- `func`: Function to execute at each interval -- `interval`: Interval duration in **seconds** - -**Returns**: - -Stop function that can be called to cancel the interval - - - -### default\_build\_logger - -```python -def default_build_logger( - min_level: Optional[LogEntryLevel] = None -) -> Callable[[LogEntry], None] -``` - -Create a default build logger with animated timer display. - -**Arguments**: - -- `min_level`: Minimum log level to display (default: 'info') - -**Returns**: - -Logger function that accepts LogEntry instances -Example -```python -from e2b import Template, default_build_logger - -template = Template().from_python_image() - -``` diff --git a/docs/sdk-reference/python-sdk/v2.9.0/readycmd.mdx b/docs/sdk-reference/python-sdk/v2.9.0/readycmd.mdx deleted file mode 100644 index 8eabda6..0000000 --- a/docs/sdk-reference/python-sdk/v2.9.0/readycmd.mdx +++ /dev/null @@ -1,168 +0,0 @@ ---- -sidebarTitle: "Readycmd" -mode: "center" ---- - - - - - - -## ReadyCmd - -```python -class ReadyCmd() -``` - -Wrapper class for ready check commands. - - - -### wait\_for\_port - -```python -def wait_for_port(port: int) -``` - -Wait for a port to be listening. - -Uses `ss` command to check if a port is open and listening. - -**Arguments**: - -- `port`: Port number to wait for - -**Returns**: - -ReadyCmd that checks for the port -Example -```python -from e2b import Template, wait_for_port - -template = ( - Template() - .from_python_image() - .set_start_cmd('python -m http.server 8000', wait_for_port(8000)) -) -``` - - - -### wait\_for\_url - -```python -def wait_for_url(url: str, status_code: int = 200) -``` - -Wait for a URL to return a specific HTTP status code. - -Uses `curl` to make HTTP requests and check the response status. - -**Arguments**: - -- `url`: URL to check (e.g., 'http://localhost:3000/health') -- `status_code`: Expected HTTP status code (default: 200) - -**Returns**: - -ReadyCmd that checks the URL -Example -```python -from e2b import Template, wait_for_url - -template = ( - Template() - .from_node_image() - .set_start_cmd('npm start', wait_for_url('http://localhost:3000/health')) -) -``` - - - -### wait\_for\_process - -```python -def wait_for_process(process_name: str) -``` - -Wait for a process with a specific name to be running. - -Uses `pgrep` to check if a process exists. - -**Arguments**: - -- `process_name`: Name of the process to wait for - -**Returns**: - -ReadyCmd that checks for the process -Example -```python -from e2b import Template, wait_for_process - -template = ( - Template() - .from_base_image() - .set_start_cmd('./my-daemon', wait_for_process('my-daemon')) -) -``` - - - -### wait\_for\_file - -```python -def wait_for_file(filename: str) -``` - -Wait for a file to exist. - -Uses shell test command to check file existence. - -**Arguments**: - -- `filename`: Path to the file to wait for - -**Returns**: - -ReadyCmd that checks for the file -Example -```python -from e2b import Template, wait_for_file - -template = ( - Template() - .from_base_image() - .set_start_cmd('./init.sh', wait_for_file('/tmp/ready')) -) -``` - - - -### wait\_for\_timeout - -```python -def wait_for_timeout(timeout: int) -``` - -Wait for a specified timeout before considering the sandbox ready. - -Uses `sleep` command to wait for a fixed duration. - -**Arguments**: - -- `timeout`: Time to wait in **milliseconds** (minimum: 1000ms / 1 second) - -**Returns**: - -ReadyCmd that waits for the specified duration -Example -```python -from e2b import Template, wait_for_timeout - -template = ( - Template() - .from_node_image() - .set_start_cmd('npm start', wait_for_timeout(5000)) # Wait 5 seconds -) -``` diff --git a/docs/sdk-reference/python-sdk/v2.9.0/sandbox_async.mdx b/docs/sdk-reference/python-sdk/v2.9.0/sandbox_async.mdx deleted file mode 100644 index ea19a01..0000000 --- a/docs/sdk-reference/python-sdk/v2.9.0/sandbox_async.mdx +++ /dev/null @@ -1,1412 +0,0 @@ ---- -sidebarTitle: "Sandbox Async" -mode: "center" ---- - - - - - - -## AsyncWatchHandle - -```python -class AsyncWatchHandle() -``` - -Handle for watching a directory in the sandbox filesystem. - -Use `.stop()` to stop watching the directory. - - - -### stop - -```python -async def stop() -``` - -Stop watching the directory. - - - - - - -## Filesystem - -```python -class Filesystem() -``` - -Module for interacting with the filesystem in the sandbox. - - - -### read - -```python -@overload -async def read(path: str, - format: Literal["text"] = "text", - user: Optional[Username] = None, - request_timeout: Optional[float] = None) -> str -``` - -Read file content as a `str`. - -**Arguments**: - -- `path`: Path to the file -- `user`: Run the operation as this user -- `format`: Format of the file content—`text` by default -- `request_timeout`: Timeout for the request in **seconds** - -**Returns**: - -File content as a `str` - - - -### read - -```python -@overload -async def read(path: str, - format: Literal["bytes"], - user: Optional[Username] = None, - request_timeout: Optional[float] = None) -> bytearray -``` - -Read file content as a `bytearray`. - -**Arguments**: - -- `path`: Path to the file -- `user`: Run the operation as this user -- `format`: Format of the file content—`bytes` -- `request_timeout`: Timeout for the request in **seconds** - -**Returns**: - -File content as a `bytearray` - - - -### read - -```python -@overload -async def read( - path: str, - format: Literal["stream"], - user: Optional[Username] = None, - request_timeout: Optional[float] = None) -> AsyncIterator[bytes] -``` - -Read file content as a `AsyncIterator[bytes]`. - -**Arguments**: - -- `path`: Path to the file -- `user`: Run the operation as this user -- `format`: Format of the file content—`stream` -- `request_timeout`: Timeout for the request in **seconds** - -**Returns**: - -File content as an `AsyncIterator[bytes]` - - - -### write - -```python -async def write(path: str, - data: Union[str, bytes, IO], - user: Optional[Username] = None, - request_timeout: Optional[float] = None) -> WriteInfo -``` - -Write content to a file on the path. - -Writing to a file that doesn't exist creates the file. -Writing to a file that already exists overwrites the file. -Writing to a file at path that doesn't exist creates the necessary directories. - -**Arguments**: - -- `path`: Path to the file -- `data`: Data to write to the file, can be a `str`, `bytes`, or `IO`. -- `user`: Run the operation as this user -- `request_timeout`: Timeout for the request in **seconds** - -**Returns**: - -Information about the written file - - - -### write\_files - -```python -async def write_files( - files: List[WriteEntry], - user: Optional[Username] = None, - request_timeout: Optional[float] = None) -> List[WriteInfo] -``` - -Writes multiple files. - -Writes a list of files to the filesystem. -When writing to a file that doesn't exist, the file will get created. -When writing to a file that already exists, the file will get overwritten. -When writing to a file that's in a directory that doesn't exist, you'll get an error. - -**Arguments**: - -- `files`: list of files to write as `WriteEntry` objects, each containing `path` and `data` -- `user`: Run the operation as this user -- `request_timeout`: Timeout for the request - -**Returns**: - -Information about the written files - - - -### list - -```python -async def list(path: str, - depth: Optional[int] = 1, - user: Optional[Username] = None, - request_timeout: Optional[float] = None) -> List[EntryInfo] -``` - -List entries in a directory. - -**Arguments**: - -- `path`: Path to the directory -- `depth`: Depth of the directory to list -- `user`: Run the operation as this user -- `request_timeout`: Timeout for the request in **seconds** - -**Returns**: - -List of entries in the directory - - - -### exists - -```python -async def exists(path: str, - user: Optional[Username] = None, - request_timeout: Optional[float] = None) -> bool -``` - -Check if a file or a directory exists. - -**Arguments**: - -- `path`: Path to a file or a directory -- `user`: Run the operation as this user -- `request_timeout`: Timeout for the request in **seconds** - -**Returns**: - -`True` if the file or directory exists, `False` otherwise - - - -### get\_info - -```python -async def get_info(path: str, - user: Optional[Username] = None, - request_timeout: Optional[float] = None) -> EntryInfo -``` - -Get information about a file or directory. - -**Arguments**: - -- `path`: Path to a file or a directory -- `user`: Run the operation as this user -- `request_timeout`: Timeout for the request in **seconds** - -**Returns**: - -Information about the file or directory like name, type, and path - - - -### remove - -```python -async def remove(path: str, - user: Optional[Username] = None, - request_timeout: Optional[float] = None) -> None -``` - -Remove a file or a directory. - -**Arguments**: - -- `path`: Path to a file or a directory -- `user`: Run the operation as this user -- `request_timeout`: Timeout for the request in **seconds** - - - -### rename - -```python -async def rename(old_path: str, - new_path: str, - user: Optional[Username] = None, - request_timeout: Optional[float] = None) -> EntryInfo -``` - -Rename a file or directory. - -**Arguments**: - -- `old_path`: Path to the file or directory to rename -- `new_path`: New path to the file or directory -- `user`: Run the operation as this user -- `request_timeout`: Timeout for the request in **seconds** - -**Returns**: - -Information about the renamed file or directory - - - -### make\_dir - -```python -async def make_dir(path: str, - user: Optional[Username] = None, - request_timeout: Optional[float] = None) -> bool -``` - -Create a new directory and all directories along the way if needed on the specified path. - -**Arguments**: - -- `path`: Path to a new directory. For example '/dirA/dirB' when creating 'dirB'. -- `user`: Run the operation as this user -- `request_timeout`: Timeout for the request in **seconds** - -**Returns**: - -`True` if the directory was created, `False` if the directory already exists - - - -### watch\_dir - -```python -async def watch_dir(path: str, - on_event: OutputHandler[FilesystemEvent], - on_exit: Optional[OutputHandler[Exception]] = None, - user: Optional[Username] = None, - request_timeout: Optional[float] = None, - timeout: Optional[float] = 60, - recursive: bool = False) -> AsyncWatchHandle -``` - -Watch directory for filesystem events. - -**Arguments**: - -- `path`: Path to a directory to watch -- `on_event`: Callback to call on each event in the directory -- `on_exit`: Callback to call when the watching ends -- `user`: Run the operation as this user -- `request_timeout`: Timeout for the request in **seconds** -- `timeout`: Timeout for the watch operation in **seconds**. Using `0` will not limit the watch time -- `recursive`: Watch directory recursively - -**Returns**: - -`AsyncWatchHandle` object for stopping watching directory - - - - - - -## AsyncSandboxPaginator - -```python -class AsyncSandboxPaginator(SandboxPaginatorBase) -``` - -Paginator for listing sandboxes. - -**Example**: - -```python -paginator = AsyncSandbox.list() - -while paginator.has_next: - sandboxes = await paginator.next_items() - print(sandboxes) -``` - - - -### next\_items - -```python -async def next_items() -> List[SandboxInfo] -``` - -Returns the next page of sandboxes. - -Call this method only if `has_next` is `True`, otherwise it will raise an exception. - -**Returns**: - -List of sandboxes - - - - - - - - - -## SandboxApi - -```python -class SandboxApi(SandboxBase) -``` - - - -### list - -```python -@staticmethod -def list(query: Optional[SandboxQuery] = None, - limit: Optional[int] = None, - next_token: Optional[str] = None, - **opts: Unpack[ApiParams]) -> AsyncSandboxPaginator -``` - -List all running sandboxes. - -**Arguments**: - -- `query`: Filter the list of sandboxes by metadata or state, e.g. `SandboxListQuery(metadata={"key": "value"})` or `SandboxListQuery(state=[SandboxState.RUNNING])` -- `limit`: Maximum number of sandboxes to return per page -- `next_token`: Token for pagination - -**Returns**: - -List of running sandboxes - - - - - - -## Commands - -```python -class Commands() -``` - -Module for executing commands in the sandbox. - - - -### list - -```python -async def list(request_timeout: Optional[float] = None) -> List[ProcessInfo] -``` - -Lists all running commands and PTY sessions. - -**Arguments**: - -- `request_timeout`: Timeout for the request in **seconds** - -**Returns**: - -List of running commands and PTY sessions - - - -### kill - -```python -async def kill(pid: int, request_timeout: Optional[float] = None) -> bool -``` - -Kill a running command specified by its process ID. - -It uses `SIGKILL` signal to kill the command. - -**Arguments**: - -- `pid`: Process ID of the command. You can get the list of processes using `sandbox.commands.list()` -- `request_timeout`: Timeout for the request in **seconds** - -**Returns**: - -`True` if the command was killed, `False` if the command was not found - - - -### send\_stdin - -```python -async def send_stdin(pid: int, - data: str, - request_timeout: Optional[float] = None) -> None -``` - -Send data to command stdin. - -:param pid Process ID of the command. You can get the list of processes using `sandbox.commands.list()`. -:param data: Data to send to the command -:param request_timeout: Timeout for the request in **seconds** - - - - -### run - -```python -@overload -async def run(cmd: str, - background: Union[Literal[False], None] = None, - envs: Optional[Dict[str, str]] = None, - user: Optional[Username] = None, - cwd: Optional[str] = None, - on_stdout: Optional[OutputHandler[Stdout]] = None, - on_stderr: Optional[OutputHandler[Stderr]] = None, - stdin: Optional[bool] = None, - timeout: Optional[float] = 60, - request_timeout: Optional[float] = None) -> CommandResult -``` - -Start a new command and wait until it finishes executing. - -**Arguments**: - -- `cmd`: Command to execute -- `background`: **`False` if the command should be executed in the foreground**, `True` if the command should be executed in the background -- `envs`: Environment variables used for the command -- `user`: User to run the command as -- `cwd`: Working directory to run the command -- `on_stdout`: Callback for command stdout output -- `on_stderr`: Callback for command stderr output -- `stdin`: If `True`, the command will have a stdin stream that you can send data to using `sandbox.commands.send_stdin()` -- `timeout`: Timeout for the command connection in **seconds**. Using `0` will not limit the command connection time -- `request_timeout`: Timeout for the request in **seconds** - -**Returns**: - -`CommandResult` result of the command execution - - - -### run - -```python -@overload -async def run(cmd: str, - background: Literal[True], - envs: Optional[Dict[str, str]] = None, - user: Optional[Username] = None, - cwd: Optional[str] = None, - on_stdout: Optional[OutputHandler[Stdout]] = None, - on_stderr: Optional[OutputHandler[Stderr]] = None, - stdin: Optional[bool] = None, - timeout: Optional[float] = 60, - request_timeout: Optional[float] = None) -> AsyncCommandHandle -``` - -Start a new command and return a handle to interact with it. - -**Arguments**: - -- `cmd`: Command to execute -- `background`: `False` if the command should be executed in the foreground, **`True` if the command should be executed in the background** -- `envs`: Environment variables used for the command -- `user`: User to run the command as -- `cwd`: Working directory to run the command -- `on_stdout`: Callback for command stdout output -- `on_stderr`: Callback for command stderr output -- `stdin`: If `True`, the command will have a stdin stream that you can send data to using `sandbox.commands.send_stdin()` -- `timeout`: Timeout for the command connection in **seconds**. Using `0` will not limit the command connection time -- `request_timeout`: Timeout for the request in **seconds** - -**Returns**: - -`AsyncCommandHandle` handle to interact with the running command - - - -### connect - -```python -async def connect( - pid: int, - timeout: Optional[float] = 60, - request_timeout: Optional[float] = None, - on_stdout: Optional[OutputHandler[Stdout]] = None, - on_stderr: Optional[OutputHandler[Stderr]] = None -) -> AsyncCommandHandle -``` - -Connects to a running command. - -You can use `AsyncCommandHandle.wait()` to wait for the command to finish and get execution results. - -**Arguments**: - -- `pid`: Process ID of the command to connect to. You can get the list of processes using `sandbox.commands.list()` -- `request_timeout`: Request timeout in **seconds** -- `timeout`: Timeout for the command connection in **seconds**. Using `0` will not limit the command connection time -- `on_stdout`: Callback for command stdout output -- `on_stderr`: Callback for command stderr output - -**Returns**: - -`AsyncCommandHandle` handle to interact with the running command - - - - - - -## AsyncCommandHandle - -```python -class AsyncCommandHandle() -``` - -Command execution handle. - -It provides methods for waiting for the command to finish, retrieving stdout/stderr, and killing the command. - - - -### pid - -```python -@property -def pid() -``` - -Command process ID. - - - -### stdout - -```python -@property -def stdout() -``` - -Command stdout output. - - - -### stderr - -```python -@property -def stderr() -``` - -Command stderr output. - - - -### error - -```python -@property -def error() -``` - -Command execution error message. - - - -### exit\_code - -```python -@property -def exit_code() -``` - -Command execution exit code. - -`0` if the command finished successfully. - -It is `None` if the command is still running. - - - -### disconnect - -```python -async def disconnect() -> None -``` - -Disconnects from the command. - -The command is not killed, but SDK stops receiving events from the command. -You can reconnect to the command using `sandbox.commands.connect` method. - - - -### wait - -```python -async def wait() -> CommandResult -``` - -Wait for the command to finish and return the result. - -If the command exits with a non-zero exit code, it throws a `CommandExitException`. - -**Returns**: - -`CommandResult` result of command execution - - - -### kill - -```python -async def kill() -> bool -``` - -Kills the command. - -It uses `SIGKILL` signal to kill the command - -**Returns**: - -`True` if the command was killed successfully, `False` if the command was not found - - - - - - -## Pty - -```python -class Pty() -``` - -Module for interacting with PTYs (pseudo-terminals) in the sandbox. - - - -### kill - -```python -async def kill(pid: int, request_timeout: Optional[float] = None) -> bool -``` - -Kill PTY. - -**Arguments**: - -- `pid`: Process ID of the PTY -- `request_timeout`: Timeout for the request in **seconds** - -**Returns**: - -`true` if the PTY was killed, `false` if the PTY was not found - - - -### send\_stdin - -```python -async def send_stdin(pid: int, - data: bytes, - request_timeout: Optional[float] = None) -> None -``` - -Send input to a PTY. - -**Arguments**: - -- `pid`: Process ID of the PTY -- `data`: Input data to send -- `request_timeout`: Timeout for the request in **seconds** - - - -### create - -```python -async def create( - size: PtySize, - on_data: OutputHandler[PtyOutput], - user: Optional[Username] = None, - cwd: Optional[str] = None, - envs: Optional[Dict[str, str]] = None, - timeout: Optional[float] = 60, - request_timeout: Optional[float] = None) -> AsyncCommandHandle -``` - -Start a new PTY (pseudo-terminal). - -**Arguments**: - -- `size`: Size of the PTY -- `on_data`: Callback to handle PTY data -- `user`: User to use for the PTY -- `cwd`: Working directory for the PTY -- `envs`: Environment variables for the PTY -- `timeout`: Timeout for the PTY in **seconds** -- `request_timeout`: Timeout for the request in **seconds** - -**Returns**: - -Handle to interact with the PTY - - - -### connect - -```python -async def connect( - pid: int, - on_data: OutputHandler[PtyOutput], - timeout: Optional[float] = 60, - request_timeout: Optional[float] = None) -> AsyncCommandHandle -``` - -Connect to a running PTY. - -**Arguments**: - -- `pid`: Process ID of the PTY to connect to. You can get the list of running PTYs using `sandbox.pty.list()`. -- `on_data`: Callback to handle PTY data -- `timeout`: Timeout for the PTY connection in **seconds**. Using `0` will not limit the connection time -- `request_timeout`: Timeout for the request in **seconds** - -**Returns**: - -Handle to interact with the PTY - - - -### resize - -```python -async def resize(pid: int, - size: PtySize, - request_timeout: Optional[float] = None) -``` - -Resize PTY. - -Call this when the terminal window is resized and the number of columns and rows has changed. - -**Arguments**: - -- `pid`: Process ID of the PTY -- `size`: New size of the PTY -- `request_timeout`: Timeout for the request in **seconds** - - - - - - -## AsyncSandbox - -```python -class AsyncSandbox(SandboxApi) -``` - -E2B cloud sandbox is a secure and isolated cloud environment. - -The sandbox allows you to: -- Access Linux OS -- Create, list, and delete files and directories -- Run commands -- Run isolated code -- Access the internet - -Check docs [here](https://e2b.dev/docs). - -Use the `AsyncSandbox.create()` to create a new sandbox. - -**Example**: - -```python -from e2b import AsyncSandbox - -sandbox = await AsyncSandbox.create() -``` - - - -### files - -```python -@property -def files() -> Filesystem -``` - -Module for interacting with the sandbox filesystem. - - - -### commands - -```python -@property -def commands() -> Commands -``` - -Module for running commands in the sandbox. - - - -### pty - -```python -@property -def pty() -> Pty -``` - -Module for interacting with the sandbox pseudo-terminal. - - - -### \_\_init\_\_ - -```python -def __init__(**opts: Unpack[SandboxOpts]) -``` - -Use `AsyncSandbox.create()` to create a new sandbox instead. - - - -### is\_running - -```python -async def is_running(request_timeout: Optional[float] = None) -> bool -``` - -Check if the sandbox is running. - -**Arguments**: - -- `request_timeout`: Timeout for the request in **seconds** - -**Returns**: - -`True` if the sandbox is running, `False` otherwise -Example -```python -sandbox = await AsyncSandbox.create() -await sandbox.is_running() # Returns True - -await sandbox.kill() -await sandbox.is_running() # Returns False -``` - - - -### create - -```python -@classmethod -async def create(cls, - template: Optional[str] = None, - timeout: Optional[int] = None, - metadata: Optional[Dict[str, str]] = None, - envs: Optional[Dict[str, str]] = None, - secure: bool = True, - allow_internet_access: bool = True, - mcp: Optional[McpServer] = None, - network: Optional[SandboxNetworkOpts] = None, - **opts: Unpack[ApiParams]) -> Self -``` - -Create a new sandbox. - -By default, the sandbox is created from the default `base` sandbox template. - -**Arguments**: - -- `template`: Sandbox template name or ID -- `timeout`: Timeout for the sandbox in **seconds**, default to 300 seconds. The maximum time a sandbox can be kept alive is 24 hours (86_400 seconds) for Pro users and 1 hour (3_600 seconds) for Hobby users. -- `metadata`: Custom metadata for the sandbox -- `envs`: Custom environment variables for the sandbox -- `secure`: Envd is secured with access token and cannot be used without it, defaults to `True`. -- `allow_internet_access`: Allow sandbox to access the internet, defaults to `True`. If set to `False`, it works the same as setting network `deny_out` to `[0.0.0.0/0]`. -- `mcp`: MCP server to enable in the sandbox -- `network`: Sandbox network configuration - -**Returns**: - -A Sandbox instance for the new sandbox -Use this method instead of using the constructor to create a new sandbox. - - - -### connect - -```python -@overload -async def connect(timeout: Optional[int] = None, - **opts: Unpack[ApiParams]) -> Self -``` - -Connect to a sandbox. If the sandbox is paused, it will be automatically resumed. - -Sandbox must be either running or be paused. - -With sandbox ID you can connect to the same sandbox from different places or environments (serverless functions, etc). - -**Arguments**: - -- `timeout`: Timeout for the sandbox in **seconds** -For running sandboxes, the timeout will update only if the new timeout is longer than the existing one. - -**Returns**: - -A running sandbox instance -@example -```python -sandbox = await AsyncSandbox.create() -await sandbox.beta_pause() - -same_sandbox = await sandbox.connect() -``` - - - -### connect - -```python -@overload -@classmethod -async def connect(cls, - sandbox_id: str, - timeout: Optional[int] = None, - **opts: Unpack[ApiParams]) -> Self -``` - -Connect to a sandbox. If the sandbox is paused, it will be automatically resumed. - -Sandbox must be either running or be paused. - -With sandbox ID you can connect to the same sandbox from different places or environments (serverless functions, etc). - -**Arguments**: - -- `sandbox_id`: Sandbox ID -- `timeout`: Timeout for the sandbox in **seconds** -For running sandboxes, the timeout will update only if the new timeout is longer than the existing one. - -**Returns**: - -A running sandbox instance -@example -```python -sandbox = await AsyncSandbox.create() -await AsyncSandbox.beta_pause(sandbox.sandbox_id) - -same_sandbox = await AsyncSandbox.connect(sandbox.sandbox_id)) -``` - - - -### connect - -```python -@class_method_variant("_cls_connect") -async def connect(timeout: Optional[int] = None, - **opts: Unpack[ApiParams]) -> Self -``` - -Connect to a sandbox. If the sandbox is paused, it will be automatically resumed. - -Sandbox must be either running or be paused. - -With sandbox ID you can connect to the same sandbox from different places or environments (serverless functions, etc). - -**Arguments**: - -- `timeout`: Timeout for the sandbox in **seconds** -For running sandboxes, the timeout will update only if the new timeout is longer than the existing one. - -**Returns**: - -A running sandbox instance -@example -```python -sandbox = await AsyncSandbox.create() -await sandbox.beta_pause() - -same_sandbox = await sandbox.connect() -``` - - - -### kill - -```python -@overload -async def kill(**opts: Unpack[ApiParams]) -> bool -``` - -Kill the sandbox. - -**Returns**: - -`True` if the sandbox was killed, `False` if the sandbox was not found - - - -### kill - -```python -@overload -@staticmethod -async def kill(sandbox_id: str, **opts: Unpack[ApiParams]) -> bool -``` - -Kill the sandbox specified by sandbox ID. - -**Arguments**: - -- `sandbox_id`: Sandbox ID - -**Returns**: - -`True` if the sandbox was killed, `False` if the sandbox was not found - - - -### kill - -```python -@class_method_variant("_cls_kill") -async def kill(**opts: Unpack[ApiParams]) -> bool -``` - -Kill the sandbox specified by sandbox ID. - -**Returns**: - -`True` if the sandbox was killed, `False` if the sandbox was not found - - - -### set\_timeout - -```python -@overload -async def set_timeout(timeout: int, **opts: Unpack[ApiParams]) -> None -``` - -Set the timeout of the sandbox. - -After the timeout expires, the sandbox will be automatically killed. -This method can extend or reduce the sandbox timeout set when creating the sandbox or from the last call to `.set_timeout`. - -The maximum time a sandbox can be kept alive is 24 hours (86_400 seconds) for Pro users and 1 hour (3_600 seconds) for Hobby users. - -**Arguments**: - -- `timeout`: Timeout for the sandbox in **seconds** - - - -### set\_timeout - -```python -@overload -@staticmethod -async def set_timeout(sandbox_id: str, timeout: int, - **opts: Unpack[ApiParams]) -> None -``` - -Set the timeout of the specified sandbox. - -After the timeout expires, the sandbox will be automatically killed. -This method can extend or reduce the sandbox timeout set when creating the sandbox or from the last call to `.set_timeout`. - -The maximum time a sandbox can be kept alive is 24 hours (86_400 seconds) for Pro users and 1 hour (3_600 seconds) for Hobby users. - -**Arguments**: - -- `sandbox_id`: Sandbox ID -- `timeout`: Timeout for the sandbox in **seconds** - - - -### set\_timeout - -```python -@class_method_variant("_cls_set_timeout") -async def set_timeout(timeout: int, **opts: Unpack[ApiParams]) -> None -``` - -Set the timeout of the specified sandbox. - -After the timeout expires, the sandbox will be automatically killed. -This method can extend or reduce the sandbox timeout set when creating the sandbox or from the last call to `.set_timeout`. - -The maximum time a sandbox can be kept alive is 24 hours (86_400 seconds) for Pro users and 1 hour (3_600 seconds) for Hobby users. - -**Arguments**: - -- `timeout`: Timeout for the sandbox in **seconds** - - - -### get\_info - -```python -@overload -async def get_info(**opts: Unpack[ApiParams]) -> SandboxInfo -``` - -Get sandbox information like sandbox ID, template, metadata, started at/end at date. - -**Returns**: - -Sandbox info - - - -### get\_info - -```python -@overload -@staticmethod -async def get_info(sandbox_id: str, **opts: Unpack[ApiParams]) -> SandboxInfo -``` - -Get sandbox information like sandbox ID, template, metadata, started at/end at date. - -**Arguments**: - -- `sandbox_id`: Sandbox ID - -**Returns**: - -Sandbox info - - - -### get\_info - -```python -@class_method_variant("_cls_get_info") -async def get_info(**opts: Unpack[ApiParams]) -> SandboxInfo -``` - -Get sandbox information like sandbox ID, template, metadata, started at/end at date. - -**Returns**: - -Sandbox info - - - -### get\_metrics - -```python -@overload -async def get_metrics(start: Optional[datetime.datetime] = None, - end: Optional[datetime.datetime] = None, - **opts: Unpack[ApiParams]) -> List[SandboxMetrics] -``` - -Get the metrics of the current sandbox. - -**Arguments**: - -- `start`: Start time for the metrics, defaults to the start of the sandbox -- `end`: End time for the metrics, defaults to the current time - -**Returns**: - -List of sandbox metrics containing CPU, memory and disk usage information - - - -### get\_metrics - -```python -@overload -@staticmethod -async def get_metrics(sandbox_id: str, - start: Optional[datetime.datetime] = None, - end: Optional[datetime.datetime] = None, - **opts: Unpack[ApiParams]) -> List[SandboxMetrics] -``` - -Get the metrics of the sandbox specified by sandbox ID. - -**Arguments**: - -- `sandbox_id`: Sandbox ID -- `start`: Start time for the metrics, defaults to the start of the sandbox -- `end`: End time for the metrics, defaults to the current time - -**Returns**: - -List of sandbox metrics containing CPU, memory and disk usage information - - - -### get\_metrics - -```python -@class_method_variant("_cls_get_metrics") -async def get_metrics(start: Optional[datetime.datetime] = None, - end: Optional[datetime.datetime] = None, - **opts: Unpack[ApiParams]) -> List[SandboxMetrics] -``` - -Get the metrics of the current sandbox. - -**Arguments**: - -- `start`: Start time for the metrics, defaults to the start of the sandbox -- `end`: End time for the metrics, defaults to the current time - -**Returns**: - -List of sandbox metrics containing CPU, memory and disk usage information - - - -### beta\_create - -```python -@classmethod -async def beta_create(cls, - template: Optional[str] = None, - timeout: Optional[int] = None, - auto_pause: bool = False, - metadata: Optional[Dict[str, str]] = None, - envs: Optional[Dict[str, str]] = None, - secure: bool = True, - allow_internet_access: bool = True, - mcp: Optional[McpServer] = None, - **opts: Unpack[ApiParams]) -> Self -``` - -[BETA] This feature is in beta and may change in the future. - -Create a new sandbox. - -By default, the sandbox is created from the default `base` sandbox template. - -**Arguments**: - -- `template`: Sandbox template name or ID -- `timeout`: Timeout for the sandbox in **seconds**, default to 300 seconds. The maximum time a sandbox can be kept alive is 24 hours (86_400 seconds) for Pro users and 1 hour (3_600 seconds) for Hobby users. -- `auto_pause`: Automatically pause the sandbox after the timeout expires. Defaults to `False`. -- `metadata`: Custom metadata for the sandbox -- `envs`: Custom environment variables for the sandbox -- `secure`: Envd is secured with access token and cannot be used without it, defaults to `True`. -- `allow_internet_access`: Allow sandbox to access the internet, defaults to `True`. -- `mcp`: MCP server to enable in the sandbox - -**Returns**: - -A Sandbox instance for the new sandbox -Use this method instead of using the constructor to create a new sandbox. - - - -### beta\_pause - -```python -@overload -async def beta_pause(**opts: Unpack[ApiParams]) -> None -``` - -[BETA] This feature is in beta and may change in the future. - -Pause the sandbox. - -**Returns**: - -Sandbox ID that can be used to resume the sandbox - - - -### beta\_pause - -```python -@overload -@staticmethod -async def beta_pause(sandbox_id: str, **opts: Unpack[ApiParams]) -> None -``` - -[BETA] This feature is in beta and may change in the future. - -Pause the sandbox specified by sandbox ID. - -**Arguments**: - -- `sandbox_id`: Sandbox ID - -**Returns**: - -Sandbox ID that can be used to resume the sandbox - - - -### beta\_pause - -```python -@class_method_variant("_cls_pause") -async def beta_pause(**opts: Unpack[ApiParams]) -> None -``` - -[BETA] This feature is in beta and may change in the future. - -Pause the sandbox. - -**Returns**: - -Sandbox ID that can be used to resume the sandbox - - - -### get\_mcp\_token - -```python -async def get_mcp_token() -> Optional[str] -``` - -Get the MCP token for the sandbox. - -**Returns**: - -MCP token for the sandbox, or None if MCP is not enabled. diff --git a/docs/sdk-reference/python-sdk/v2.9.0/sandbox_sync.mdx b/docs/sdk-reference/python-sdk/v2.9.0/sandbox_sync.mdx deleted file mode 100644 index 729fad1..0000000 --- a/docs/sdk-reference/python-sdk/v2.9.0/sandbox_sync.mdx +++ /dev/null @@ -1,1365 +0,0 @@ ---- -sidebarTitle: "Sandbox Sync" -mode: "center" ---- - - - - - - -## WatchHandle - -```python -class WatchHandle() -``` - -Handle for watching filesystem events. -It is used to get the latest events that have occurred in the watched directory. - -Use `.stop()` to stop watching the directory. - - - -### stop - -```python -def stop() -``` - -Stop watching the directory. -After you stop the watcher you won't be able to get the events anymore. - - - -### get\_new\_events - -```python -def get_new_events() -> List[FilesystemEvent] -``` - -Get the latest events that have occurred in the watched directory since the last call, or from the beginning of the watching, up until now. - -**Returns**: - -List of filesystem events - - - - - - -## Filesystem - -```python -class Filesystem() -``` - -Module for interacting with the filesystem in the sandbox. - - - -### read - -```python -@overload -def read(path: str, - format: Literal["text"] = "text", - user: Optional[Username] = None, - request_timeout: Optional[float] = None) -> str -``` - -Read file content as a `str`. - -**Arguments**: - -- `path`: Path to the file -- `user`: Run the operation as this user -- `format`: Format of the file content—`text` by default -- `request_timeout`: Timeout for the request in **seconds** - -**Returns**: - -File content as a `str` - - - -### read - -```python -@overload -def read(path: str, - format: Literal["bytes"], - user: Optional[Username] = None, - request_timeout: Optional[float] = None) -> bytearray -``` - -Read file content as a `bytearray`. - -**Arguments**: - -- `path`: Path to the file -- `user`: Run the operation as this user -- `format`: Format of the file content—`bytes` -- `request_timeout`: Timeout for the request in **seconds** - -**Returns**: - -File content as a `bytearray` - - - -### read - -```python -@overload -def read(path: str, - format: Literal["stream"], - user: Optional[Username] = None, - request_timeout: Optional[float] = None) -> Iterator[bytes] -``` - -Read file content as a `Iterator[bytes]`. - -**Arguments**: - -- `path`: Path to the file -- `user`: Run the operation as this user -- `format`: Format of the file content—`stream` -- `request_timeout`: Timeout for the request in **seconds** - -**Returns**: - -File content as an `Iterator[bytes]` - - - -### write - -```python -def write(path: str, - data: Union[str, bytes, IO], - user: Optional[Username] = None, - request_timeout: Optional[float] = None) -> WriteInfo -``` - -Write content to a file on the path. - -Writing to a file that doesn't exist creates the file. -Writing to a file that already exists overwrites the file. -Writing to a file at path that doesn't exist creates the necessary directories. - -**Arguments**: - -- `path`: Path to the file -- `data`: Data to write to the file, can be a `str`, `bytes`, or `IO`. -- `user`: Run the operation as this user -- `request_timeout`: Timeout for the request in **seconds** - -**Returns**: - -Information about the written file - - - -### write\_files - -```python -def write_files(files: List[WriteEntry], - user: Optional[Username] = None, - request_timeout: Optional[float] = None) -> List[WriteInfo] -``` - -Writes a list of files to the filesystem. - -When writing to a file that doesn't exist, the file will get created. -When writing to a file that already exists, the file will get overwritten. -When writing to a file that's in a directory that doesn't exist, you'll get an error. - -**Arguments**: - -- `files`: list of files to write as `WriteEntry` objects, each containing `path` and `data` -- `user`: Run the operation as this user -- `request_timeout`: Timeout for the request - -**Returns**: - -Information about the written files - - - -### list - -```python -def list(path: str, - depth: Optional[int] = 1, - user: Optional[Username] = None, - request_timeout: Optional[float] = None) -> List[EntryInfo] -``` - -List entries in a directory. - -**Arguments**: - -- `path`: Path to the directory -- `depth`: Depth of the directory to list -- `user`: Run the operation as this user -- `request_timeout`: Timeout for the request in **seconds** - -**Returns**: - -List of entries in the directory - - - -### exists - -```python -def exists(path: str, - user: Optional[Username] = None, - request_timeout: Optional[float] = None) -> bool -``` - -Check if a file or a directory exists. - -**Arguments**: - -- `path`: Path to a file or a directory -- `user`: Run the operation as this user -- `request_timeout`: Timeout for the request in **seconds** - -**Returns**: - -`True` if the file or directory exists, `False` otherwise - - - -### get\_info - -```python -def get_info(path: str, - user: Optional[Username] = None, - request_timeout: Optional[float] = None) -> EntryInfo -``` - -Get information about a file or directory. - -**Arguments**: - -- `path`: Path to a file or a directory -- `user`: Run the operation as this user -- `request_timeout`: Timeout for the request in **seconds** - -**Returns**: - -Information about the file or directory like name, type, and path - - - -### remove - -```python -def remove(path: str, - user: Optional[Username] = None, - request_timeout: Optional[float] = None) -> None -``` - -Remove a file or a directory. - -**Arguments**: - -- `path`: Path to a file or a directory -- `user`: Run the operation as this user -- `request_timeout`: Timeout for the request in **seconds** - - - -### rename - -```python -def rename(old_path: str, - new_path: str, - user: Optional[Username] = None, - request_timeout: Optional[float] = None) -> EntryInfo -``` - -Rename a file or directory. - -**Arguments**: - -- `old_path`: Path to the file or directory to rename -- `new_path`: New path to the file or directory -- `user`: Run the operation as this user -- `request_timeout`: Timeout for the request in **seconds** - -**Returns**: - -Information about the renamed file or directory - - - -### make\_dir - -```python -def make_dir(path: str, - user: Optional[Username] = None, - request_timeout: Optional[float] = None) -> bool -``` - -Create a new directory and all directories along the way if needed on the specified path. - -**Arguments**: - -- `path`: Path to a new directory. For example '/dirA/dirB' when creating 'dirB'. -- `user`: Run the operation as this user -- `request_timeout`: Timeout for the request in **seconds** - -**Returns**: - -`True` if the directory was created, `False` if the directory already exists - - - -### watch\_dir - -```python -def watch_dir(path: str, - user: Optional[Username] = None, - request_timeout: Optional[float] = None, - recursive: bool = False) -> WatchHandle -``` - -Watch directory for filesystem events. - -**Arguments**: - -- `path`: Path to a directory to watch -- `user`: Run the operation as this user -- `request_timeout`: Timeout for the request in **seconds** -- `recursive`: Watch directory recursively - -**Returns**: - -`WatchHandle` object for stopping watching directory - - - - - - -## SandboxPaginator - -```python -class SandboxPaginator(SandboxPaginatorBase) -``` - -Paginator for listing sandboxes. - -**Example**: - -```python -paginator = Sandbox.list() - -while paginator.has_next: - sandboxes = paginator.next_items() - print(sandboxes) -``` - - - -### next\_items - -```python -def next_items() -> List[SandboxInfo] -``` - -Returns the next page of sandboxes. - -Call this method only if `has_next` is `True`, otherwise it will raise an exception. - -**Returns**: - -List of sandboxes - - - - - - -## SandboxApi - -```python -class SandboxApi(SandboxBase) -``` - - - -### list - -```python -@staticmethod -def list(query: Optional[SandboxQuery] = None, - limit: Optional[int] = None, - next_token: Optional[str] = None, - **opts: Unpack[ApiParams]) -> SandboxPaginator -``` - -List all running sandboxes. - -**Arguments**: - -- `query`: Filter the list of sandboxes by metadata or state, e.g. `SandboxListQuery(metadata={"key": "value"})` or `SandboxListQuery(state=[SandboxState.RUNNING])` -- `limit`: Maximum number of sandboxes to return per page -- `next_token`: Token for pagination - -**Returns**: - -List of running sandboxes - - - - - - -## Commands - -```python -class Commands() -``` - -Module for executing commands in the sandbox. - - - -### list - -```python -def list(request_timeout: Optional[float] = None) -> List[ProcessInfo] -``` - -Lists all running commands and PTY sessions. - -**Arguments**: - -- `request_timeout`: Timeout for the request in **seconds** - -**Returns**: - -List of running commands and PTY sessions - - - -### kill - -```python -def kill(pid: int, request_timeout: Optional[float] = None) -> bool -``` - -Kills a running command specified by its process ID. - -It uses `SIGKILL` signal to kill the command. - -**Arguments**: - -- `pid`: Process ID of the command. You can get the list of processes using `sandbox.commands.list()` -- `request_timeout`: Timeout for the request in **seconds** - -**Returns**: - -`True` if the command was killed, `False` if the command was not found - - - -### send\_stdin - -```python -def send_stdin(pid: int, data: str, request_timeout: Optional[float] = None) -``` - -Send data to command stdin. - -:param pid Process ID of the command. You can get the list of processes using `sandbox.commands.list()`. -:param data: Data to send to the command -:param request_timeout: Timeout for the request in **seconds** - - - - -### run - -```python -@overload -def run(cmd: str, - background: Union[Literal[False], None] = None, - envs: Optional[Dict[str, str]] = None, - user: Optional[Username] = None, - cwd: Optional[str] = None, - on_stdout: Optional[Callable[[str], None]] = None, - on_stderr: Optional[Callable[[str], None]] = None, - stdin: Optional[bool] = None, - timeout: Optional[float] = 60, - request_timeout: Optional[float] = None) -> CommandResult -``` - -Start a new command and wait until it finishes executing. - -**Arguments**: - -- `cmd`: Command to execute -- `background`: **`False` if the command should be executed in the foreground**, `True` if the command should be executed in the background -- `envs`: Environment variables used for the command -- `user`: User to run the command as -- `cwd`: Working directory to run the command -- `on_stdout`: Callback for command stdout output -- `on_stderr`: Callback for command stderr output -- `stdin`: If `True`, the command will have a stdin stream that you can send data to using `sandbox.commands.send_stdin()` -- `timeout`: Timeout for the command connection in **seconds**. Using `0` will not limit the command connection time -- `request_timeout`: Timeout for the request in **seconds** - -**Returns**: - -`CommandResult` result of the command execution - - - -### run - -```python -@overload -def run(cmd: str, - background: Literal[True], - envs: Optional[Dict[str, str]] = None, - user: Optional[Username] = None, - cwd: Optional[str] = None, - on_stdout: None = None, - on_stderr: None = None, - stdin: Optional[bool] = None, - timeout: Optional[float] = 60, - request_timeout: Optional[float] = None) -> CommandHandle -``` - -Start a new command and return a handle to interact with it. - -**Arguments**: - -- `cmd`: Command to execute -- `background`: `False` if the command should be executed in the foreground, **`True` if the command should be executed in the background** -- `envs`: Environment variables used for the command -- `user`: User to run the command as -- `cwd`: Working directory to run the command -- `stdin`: If `True`, the command will have a stdin stream that you can send data to using `sandbox.commands.send_stdin()` -- `timeout`: Timeout for the command connection in **seconds**. Using `0` will not limit the command connection time -- `request_timeout`: Timeout for the request in **seconds** - -**Returns**: - -`CommandHandle` handle to interact with the running command - - - -### connect - -```python -def connect(pid: int, - timeout: Optional[float] = 60, - request_timeout: Optional[float] = None) -``` - -Connects to a running command. - -You can use `CommandHandle.wait()` to wait for the command to finish and get execution results. - -**Arguments**: - -- `pid`: Process ID of the command to connect to. You can get the list of processes using `sandbox.commands.list()` -- `timeout`: Timeout for the connection in **seconds**. Using `0` will not limit the connection time -- `request_timeout`: Timeout for the request in **seconds** - -**Returns**: - -`CommandHandle` handle to interact with the running command - - - - - - -## CommandHandle - -```python -class CommandHandle() -``` - -Command execution handle. - -It provides methods for waiting for the command to finish, retrieving stdout/stderr, and killing the command. - - - -### pid - -```python -@property -def pid() -``` - -Command process ID. - - - -### \_\_iter\_\_ - -```python -def __iter__() -``` - -Iterate over the command output. - -**Returns**: - -Generator of command outputs - - - -### disconnect - -```python -def disconnect() -> None -``` - -Disconnect from the command. - -The command is not killed, but SDK stops receiving events from the command. -You can reconnect to the command using `sandbox.commands.connect` method. - - - -### wait - -```python -def wait(on_pty: Optional[Callable[[PtyOutput], None]] = None, - on_stdout: Optional[Callable[[str], None]] = None, - on_stderr: Optional[Callable[[str], None]] = None) -> CommandResult -``` - -Wait for the command to finish and returns the result. - -If the command exits with a non-zero exit code, it throws a `CommandExitException`. - -**Arguments**: - -- `on_pty`: Callback for pty output -- `on_stdout`: Callback for stdout output -- `on_stderr`: Callback for stderr output - -**Returns**: - -`CommandResult` result of command execution - - - -### kill - -```python -def kill() -> bool -``` - -Kills the command. - -It uses `SIGKILL` signal to kill the command. - -**Returns**: - -Whether the command was killed successfully - - - - - - -## Pty - -```python -class Pty() -``` - -Module for interacting with PTYs (pseudo-terminals) in the sandbox. - - - -### kill - -```python -def kill(pid: int, request_timeout: Optional[float] = None) -> bool -``` - -Kill PTY. - -**Arguments**: - -- `pid`: Process ID of the PTY -- `request_timeout`: Timeout for the request in **seconds** - -**Returns**: - -`true` if the PTY was killed, `false` if the PTY was not found - - - -### send\_stdin - -```python -def send_stdin(pid: int, - data: bytes, - request_timeout: Optional[float] = None) -> None -``` - -Send input to a PTY. - -**Arguments**: - -- `pid`: Process ID of the PTY -- `data`: Input data to send -- `request_timeout`: Timeout for the request in **seconds** - - - -### create - -```python -def create(size: PtySize, - user: Optional[Username] = None, - cwd: Optional[str] = None, - envs: Optional[Dict[str, str]] = None, - timeout: Optional[float] = 60, - request_timeout: Optional[float] = None) -> CommandHandle -``` - -Start a new PTY (pseudo-terminal). - -**Arguments**: - -- `size`: Size of the PTY -- `user`: User to use for the PTY -- `cwd`: Working directory for the PTY -- `envs`: Environment variables for the PTY -- `timeout`: Timeout for the PTY in **seconds** -- `request_timeout`: Timeout for the request in **seconds** - -**Returns**: - -Handle to interact with the PTY - - - -### connect - -```python -def connect(pid: int, - timeout: Optional[float] = 60, - request_timeout: Optional[float] = None) -> CommandHandle -``` - -Connect to a running PTY. - -**Arguments**: - -- `pid`: Process ID of the PTY to connect to. You can get the list of running PTYs using `sandbox.pty.list()`. -- `timeout`: Timeout for the PTY connection in **seconds**. Using `0` will not limit the connection time -- `request_timeout`: Timeout for the request in **seconds** - -**Returns**: - -Handle to interact with the PTY - - - -### resize - -```python -def resize(pid: int, - size: PtySize, - request_timeout: Optional[float] = None) -> None -``` - -Resize PTY. - -Call this when the terminal window is resized and the number of columns and rows has changed. - -**Arguments**: - -- `pid`: Process ID of the PTY -- `size`: New size of the PTY -- `request_timeout`: Timeout for the request in **seconds**s - - - - - - -## Sandbox - -```python -class Sandbox(SandboxApi) -``` - -E2B cloud sandbox is a secure and isolated cloud environment. - -The sandbox allows you to: -- Access Linux OS -- Create, list, and delete files and directories -- Run commands -- Run isolated code -- Access the internet - -Check docs [here](https://e2b.dev/docs). - -Use the `Sandbox.create()` to create a new sandbox. - -**Example**: - -```python -from e2b import Sandbox - -sandbox = Sandbox.create() -``` - - - -### files - -```python -@property -def files() -> Filesystem -``` - -Module for interacting with the sandbox filesystem. - - - -### commands - -```python -@property -def commands() -> Commands -``` - -Module for running commands in the sandbox. - - - -### pty - -```python -@property -def pty() -> Pty -``` - -Module for interacting with the sandbox pseudo-terminal. - - - -### \_\_init\_\_ - -```python -def __init__(**opts: Unpack[SandboxOpts]) -``` - -:deprecated: This constructor is deprecated - -Use `Sandbox.create()` to create a new sandbox instead. - - - -### is\_running - -```python -def is_running(request_timeout: Optional[float] = None) -> bool -``` - -Check if the sandbox is running. - -**Arguments**: - -- `request_timeout`: Timeout for the request in **seconds** - -**Returns**: - -`True` if the sandbox is running, `False` otherwise -Example -```python -sandbox = Sandbox.create() -sandbox.is_running() # Returns True - -sandbox.kill() -sandbox.is_running() # Returns False -``` - - - -### create - -```python -@classmethod -def create(cls, - template: Optional[str] = None, - timeout: Optional[int] = None, - metadata: Optional[Dict[str, str]] = None, - envs: Optional[Dict[str, str]] = None, - secure: bool = True, - allow_internet_access: bool = True, - mcp: Optional[McpServer] = None, - network: Optional[SandboxNetworkOpts] = None, - **opts: Unpack[ApiParams]) -> Self -``` - -Create a new sandbox. - -By default, the sandbox is created from the default `base` sandbox template. - -**Arguments**: - -- `template`: Sandbox template name or ID -- `timeout`: Timeout for the sandbox in **seconds**, default to 300 seconds. The maximum time a sandbox can be kept alive is 24 hours (86_400 seconds) for Pro users and 1 hour (3_600 seconds) for Hobby users. -- `metadata`: Custom metadata for the sandbox -- `envs`: Custom environment variables for the sandbox -- `secure`: Envd is secured with access token and cannot be used without it, defaults to `True`. -- `allow_internet_access`: Allow sandbox to access the internet, defaults to `True`. If set to `False`, it works the same as setting network `deny_out` to `[0.0.0.0/0]`. -- `mcp`: MCP server to enable in the sandbox -- `network`: Sandbox network configuration - -**Returns**: - -A Sandbox instance for the new sandbox -Use this method instead of using the constructor to create a new sandbox. - - - -### connect - -```python -@overload -def connect(timeout: Optional[int] = None, **opts: Unpack[ApiParams]) -> Self -``` - -Connect to a sandbox. If the sandbox is paused, it will be automatically resumed. - -Sandbox must be either running or be paused. - -With sandbox ID you can connect to the same sandbox from different places or environments (serverless functions, etc). - -**Arguments**: - -- `timeout`: Timeout for the sandbox in **seconds** -For running sandboxes, the timeout will update only if the new timeout is longer than the existing one. - -**Returns**: - -A running sandbox instance -@example -```python -sandbox = Sandbox.create() -sandbox.beta_pause() - -same_sandbox = sandbox.connect() - - - -### connect - -```python -@overload -@classmethod -def connect(cls, - sandbox_id: str, - timeout: Optional[int] = None, - **opts: Unpack[ApiParams]) -> Self -``` - -Connect to a sandbox. If the sandbox is paused, it will be automatically resumed. - -Sandbox must be either running or be paused. - -With sandbox ID you can connect to the same sandbox from different places or environments (serverless functions, etc). - -**Arguments**: - -- `sandbox_id`: Sandbox ID -- `timeout`: Timeout for the sandbox in **seconds**. -For running sandboxes, the timeout will update only if the new timeout is longer than the existing one. - -**Returns**: - -A running sandbox instance -@example -```python -sandbox = Sandbox.create() -Sandbox.beta_pause(sandbox.sandbox_id) - -same_sandbox = Sandbox.connect(sandbox.sandbox_id) -``` - - - -### connect - -```python -@class_method_variant("_cls_connect") -def connect(timeout: Optional[int] = None, **opts: Unpack[ApiParams]) -> Self -``` - -Connect to a sandbox. If the sandbox is paused, it will be automatically resumed. - -Sandbox must be either running or be paused. - -With sandbox ID you can connect to the same sandbox from different places or environments (serverless functions, etc). - -**Arguments**: - -- `timeout`: Timeout for the sandbox in **seconds**. -For running sandboxes, the timeout will update only if the new timeout is longer than the existing one. - -**Returns**: - -A running sandbox instance -@example -```python -sandbox = Sandbox.create() -sandbox.beta_pause() - -same_sandbox = sandbox.connect() -``` - - - -### kill - -```python -@overload -def kill(**opts: Unpack[ApiParams]) -> bool -``` - -Kill the sandbox. - -**Returns**: - -`True` if the sandbox was killed, `False` if the sandbox was not found - - - -### kill - -```python -@overload -@staticmethod -def kill(sandbox_id: str, **opts: Unpack[ApiParams]) -> bool -``` - -Kill the sandbox specified by sandbox ID. - -**Arguments**: - -- `sandbox_id`: Sandbox ID - -**Returns**: - -`True` if the sandbox was killed, `False` if the sandbox was not found - - - -### kill - -```python -@class_method_variant("_cls_kill") -def kill(**opts: Unpack[ApiParams]) -> bool -``` - -Kill the sandbox specified by sandbox ID. - -**Returns**: - -`True` if the sandbox was killed, `False` if the sandbox was not found - - - -### set\_timeout - -```python -@overload -def set_timeout(timeout: int, **opts: Unpack[ApiParams]) -> None -``` - -Set the timeout of the sandbox. - -After the timeout expires, the sandbox will be automatically killed. -This method can extend or reduce the sandbox timeout set when creating the sandbox or from the last call to `.set_timeout`. - -The maximum time a sandbox can be kept alive is 24 hours (86_400 seconds) for Pro users and 1 hour (3_600 seconds) for Hobby users. - -**Arguments**: - -- `timeout`: Timeout for the sandbox in **seconds** - - - -### set\_timeout - -```python -@overload -@staticmethod -def set_timeout(sandbox_id: str, timeout: int, - **opts: Unpack[ApiParams]) -> None -``` - -Set the timeout of the sandbox specified by sandbox ID. - -After the timeout expires, the sandbox will be automatically killed. -This method can extend or reduce the sandbox timeout set when creating the sandbox or from the last call to `.set_timeout`. - -The maximum time a sandbox can be kept alive is 24 hours (86_400 seconds) for Pro users and 1 hour (3_600 seconds) for Hobby users. - -**Arguments**: - -- `sandbox_id`: Sandbox ID -- `timeout`: Timeout for the sandbox in **seconds** - - - -### set\_timeout - -```python -@class_method_variant("_cls_set_timeout") -def set_timeout(timeout: int, **opts: Unpack[ApiParams]) -> None -``` - -Set the timeout of the sandbox. - -After the timeout expires, the sandbox will be automatically killed. -This method can extend or reduce the sandbox timeout set when creating the sandbox or from the last call to `.set_timeout`. - -The maximum time a sandbox can be kept alive is 24 hours (86_400 seconds) for Pro users and 1 hour (3_600 seconds) for Hobby users. - -**Arguments**: - -- `timeout`: Timeout for the sandbox in **seconds** - - - -### get\_info - -```python -@overload -def get_info(**opts: Unpack[ApiParams]) -> SandboxInfo -``` - -Get sandbox information like sandbox ID, template, metadata, started at/end at date. - -**Returns**: - -Sandbox info - - - -### get\_info - -```python -@overload -@staticmethod -def get_info(sandbox_id: str, **opts: Unpack[ApiParams]) -> SandboxInfo -``` - -Get sandbox information like sandbox ID, template, metadata, started at/end at date. - -**Arguments**: - -- `sandbox_id`: Sandbox ID - -**Returns**: - -Sandbox info - - - -### get\_info - -```python -@class_method_variant("_cls_get_info") -def get_info(**opts: Unpack[ApiParams]) -> SandboxInfo -``` - -Get sandbox information like sandbox ID, template, metadata, started at/end at date. - -**Returns**: - -Sandbox info - - - -### get\_metrics - -```python -@overload -def get_metrics(start: Optional[datetime.datetime] = None, - end: Optional[datetime.datetime] = None, - **opts: Unpack[ApiParams]) -> List[SandboxMetrics] -``` - -Get the metrics of the current sandbox. - -**Arguments**: - -- `start`: Start time for the metrics, defaults to the start of the sandbox -- `end`: End time for the metrics, defaults to the current time - -**Returns**: - -List of sandbox metrics containing CPU, memory and disk usage information - - - -### get\_metrics - -```python -@overload -@staticmethod -def get_metrics(sandbox_id: str, - start: Optional[datetime.datetime] = None, - end: Optional[datetime.datetime] = None, - **opts: Unpack[ApiParams]) -> List[SandboxMetrics] -``` - -Get the metrics of the sandbox specified by sandbox ID. - -**Arguments**: - -- `sandbox_id`: Sandbox ID -- `start`: Start time for the metrics, defaults to the start of the sandbox -- `end`: End time for the metrics, defaults to the current time - -**Returns**: - -List of sandbox metrics containing CPU, memory and disk usage information - - - -### get\_metrics - -```python -@class_method_variant("_cls_get_metrics") -def get_metrics(start: Optional[datetime.datetime] = None, - end: Optional[datetime.datetime] = None, - **opts: Unpack[ApiParams]) -> List[SandboxMetrics] -``` - -Get the metrics of the sandbox specified by sandbox ID. - -**Arguments**: - -- `start`: Start time for the metrics, defaults to the start of the sandbox -- `end`: End time for the metrics, defaults to the current time - -**Returns**: - -List of sandbox metrics containing CPU, memory and disk usage information - - - -### beta\_create - -```python -@classmethod -def beta_create(cls, - template: Optional[str] = None, - timeout: Optional[int] = None, - auto_pause: bool = False, - metadata: Optional[Dict[str, str]] = None, - envs: Optional[Dict[str, str]] = None, - secure: bool = True, - allow_internet_access: bool = True, - mcp: Optional[McpServer] = None, - **opts: Unpack[ApiParams]) -> Self -``` - -[BETA] This feature is in beta and may change in the future. - -Create a new sandbox. - -By default, the sandbox is created from the default `base` sandbox template. - -**Arguments**: - -- `template`: Sandbox template name or ID -- `timeout`: Timeout for the sandbox in **seconds**, default to 300 seconds. The maximum time a sandbox can be kept alive is 24 hours (86_400 seconds) for Pro users and 1 hour (3_600 seconds) for Hobby users. -- `auto_pause`: Automatically pause the sandbox after the timeout expires. Defaults to `False`. -- `metadata`: Custom metadata for the sandbox -- `envs`: Custom environment variables for the sandbox -- `secure`: Envd is secured with access token and cannot be used without it, defaults to `True`. -- `allow_internet_access`: Allow sandbox to access the internet, defaults to `True`. -- `mcp`: MCP server to enable in the sandbox - -**Returns**: - -A Sandbox instance for the new sandbox -Use this method instead of using the constructor to create a new sandbox. - - - -### beta\_pause - -```python -@overload -def beta_pause(**opts: Unpack[ApiParams]) -> None -``` - -[BETA] This feature is in beta and may change in the future. - -Pause the sandbox. - - - -### beta\_pause - -```python -@overload -@classmethod -def beta_pause(cls, sandbox_id: str, **opts: Unpack[ApiParams]) -> None -``` - -[BETA] This feature is in beta and may change in the future. - -Pause the sandbox specified by sandbox ID. - -**Arguments**: - -- `sandbox_id`: Sandbox ID - - - -### beta\_pause - -```python -@class_method_variant("_cls_pause") -def beta_pause(**opts: Unpack[ApiParams]) -> None -``` - -[BETA] This feature is in beta and may change in the future. - -Pause the sandbox. - -**Returns**: - -Sandbox ID that can be used to resume the sandbox - - - -### get\_mcp\_token - -```python -def get_mcp_token() -> Optional[str] -``` - -Get the MCP token for the sandbox. - -**Returns**: - -MCP token for the sandbox, or None if MCP is not enabled. diff --git a/docs/sdk-reference/python-sdk/v2.9.0/template.mdx b/docs/sdk-reference/python-sdk/v2.9.0/template.mdx deleted file mode 100644 index 644bd22..0000000 --- a/docs/sdk-reference/python-sdk/v2.9.0/template.mdx +++ /dev/null @@ -1,1706 +0,0 @@ ---- -sidebarTitle: "Template" -mode: "center" ---- - - - - - - -## DockerfFileFinalParserInterface - -```python -class DockerfFileFinalParserInterface(Protocol) -``` - -Protocol defining the final interface for Dockerfile parsing callbacks. - - - -## DockerfileParserInterface - -```python -class DockerfileParserInterface(Protocol) -``` - -Protocol defining the interface for Dockerfile parsing callbacks. - - - -### run\_cmd - -```python -def run_cmd(command: Union[str, List[str]], - user: Optional[str] = None) -> "DockerfileParserInterface" -``` - -Handle RUN instruction. - - - -### copy - -```python -def copy(src: Union[str, List[CopyItem]], - dest: Optional[str] = None, - force_upload: Optional[Literal[True]] = None, - resolve_symlinks: Optional[bool] = None, - user: Optional[str] = None, - mode: Optional[int] = None) -> "DockerfileParserInterface" -``` - -Handle COPY instruction. - - - -### set\_workdir - -```python -def set_workdir(workdir: str) -> "DockerfileParserInterface" -``` - -Handle WORKDIR instruction. - - - -### set\_user - -```python -def set_user(user: str) -> "DockerfileParserInterface" -``` - -Handle USER instruction. - - - -### set\_envs - -```python -def set_envs(envs: Dict[str, str]) -> "DockerfileParserInterface" -``` - -Handle ENV instruction. - - - -### set\_start\_cmd - -```python -def set_start_cmd(start_cmd: str, - ready_cmd: str) -> "DockerfFileFinalParserInterface" -``` - -Handle CMD/ENTRYPOINT instruction. - - - -### parse\_dockerfile - -```python -def parse_dockerfile(dockerfile_content_or_path: str, - template_builder: DockerfileParserInterface) -> str -``` - -Parse a Dockerfile and convert it to Template SDK format. - -**Arguments**: - -- `dockerfile_content_or_path`: Either the Dockerfile content as a string, or a path to a Dockerfile file -- `template_builder`: Interface providing template builder methods - -**Raises**: - -- `ValueError`: If the Dockerfile is invalid or unsupported - -**Returns**: - -The base image from the Dockerfile - - - - - - -## InstructionType - -```python -class InstructionType(str, Enum) -``` - -Types of instructions that can be used in a template. - - - -## CopyItem - -```python -class CopyItem(TypedDict) -``` - -Configuration for a single file/directory copy operation. - - - -## Instruction - -```python -class Instruction(TypedDict) -``` - -Represents a single instruction in the template build process. - - - -## GenericDockerRegistry - -```python -class GenericDockerRegistry(TypedDict) -``` - -Configuration for a generic Docker registry with basic authentication. - - - -## AWSRegistry - -```python -class AWSRegistry(TypedDict) -``` - -Configuration for AWS Elastic Container Registry (ECR). - - - -## GCPRegistry - -```python -class GCPRegistry(TypedDict) -``` - -Configuration for Google Container Registry (GCR) or Artifact Registry. - - - -## TemplateType - -```python -class TemplateType(TypedDict) -``` - -Internal representation of a template for the E2B build API. - - - -## BuildInfo - -```python -@dataclass -class BuildInfo() -``` - -Information about a built template. - - - - - - -## LogEntry - -```python -@dataclass -class LogEntry() -``` - -Represents a single log entry from the template build process. - - - -## LogEntryStart - -```python -@dataclass -class LogEntryStart(LogEntry) -``` - -Special log entry indicating the start of a build process. - - - -## LogEntryEnd - -```python -@dataclass -class LogEntryEnd(LogEntry) -``` - -Special log entry indicating the end of a build process. - - - -### TIMER\_UPDATE\_INTERVAL\_MS - -Default minimum log level to display. - - - -### DEFAULT\_LEVEL - -Colored labels for each log level. - - - -### levels - -Numeric ordering of log levels for comparison (lower = less severe). - - - -### set\_interval - -```python -def set_interval(func, interval) -``` - -Returns a stop function that can be called to cancel the interval. - -Similar to JavaScript's setInterval. - -**Arguments**: - -- `func`: Function to execute at each interval -- `interval`: Interval duration in **seconds** - -**Returns**: - -Stop function that can be called to cancel the interval - - - -### default\_build\_logger - -```python -def default_build_logger( - min_level: Optional[LogEntryLevel] = None -) -> Callable[[LogEntry], None] -``` - -Create a default build logger with animated timer display. - -**Arguments**: - -- `min_level`: Minimum log level to display (default: 'info') - -**Returns**: - -Logger function that accepts LogEntry instances -Example -```python -from e2b import Template, default_build_logger - -template = Template().from_python_image() - -``` - - - - -Special step name for the finalization phase of template building. -This is the last step that runs after all user-defined instructions. - - - -### FINALIZE\_STEP\_NAME - -Special step name for the base image phase of template building. -This is the first step that sets up the base image. - - - -### BASE\_STEP\_NAME - -Stack trace depth for capturing caller information. - -Depth levels: -1. TemplateClass -2. Caller method (e.g., copy(), from_image(), etc.) - -This depth is used to determine the original caller's location -for stack traces. - - - -### STACK\_TRACE\_DEPTH - -Default setting for whether to resolve symbolic links when copying files. -When False, symlinks are copied as symlinks rather than following them. - - - - - - -## ReadyCmd - -```python -class ReadyCmd() -``` - -Wrapper class for ready check commands. - - - -### wait\_for\_port - -```python -def wait_for_port(port: int) -``` - -Wait for a port to be listening. - -Uses `ss` command to check if a port is open and listening. - -**Arguments**: - -- `port`: Port number to wait for - -**Returns**: - -ReadyCmd that checks for the port -Example -```python -from e2b import Template, wait_for_port - -template = ( - Template() - .from_python_image() - .set_start_cmd('python -m http.server 8000', wait_for_port(8000)) -) -``` - - - -### wait\_for\_url - -```python -def wait_for_url(url: str, status_code: int = 200) -``` - -Wait for a URL to return a specific HTTP status code. - -Uses `curl` to make HTTP requests and check the response status. - -**Arguments**: - -- `url`: URL to check (e.g., 'http://localhost:3000/health') -- `status_code`: Expected HTTP status code (default: 200) - -**Returns**: - -ReadyCmd that checks the URL -Example -```python -from e2b import Template, wait_for_url - -template = ( - Template() - .from_node_image() - .set_start_cmd('npm start', wait_for_url('http://localhost:3000/health')) -) -``` - - - -### wait\_for\_process - -```python -def wait_for_process(process_name: str) -``` - -Wait for a process with a specific name to be running. - -Uses `pgrep` to check if a process exists. - -**Arguments**: - -- `process_name`: Name of the process to wait for - -**Returns**: - -ReadyCmd that checks for the process -Example -```python -from e2b import Template, wait_for_process - -template = ( - Template() - .from_base_image() - .set_start_cmd('./my-daemon', wait_for_process('my-daemon')) -) -``` - - - -### wait\_for\_file - -```python -def wait_for_file(filename: str) -``` - -Wait for a file to exist. - -Uses shell test command to check file existence. - -**Arguments**: - -- `filename`: Path to the file to wait for - -**Returns**: - -ReadyCmd that checks for the file -Example -```python -from e2b import Template, wait_for_file - -template = ( - Template() - .from_base_image() - .set_start_cmd('./init.sh', wait_for_file('/tmp/ready')) -) -``` - - - -### wait\_for\_timeout - -```python -def wait_for_timeout(timeout: int) -``` - -Wait for a specified timeout before considering the sandbox ready. - -Uses `sleep` command to wait for a fixed duration. - -**Arguments**: - -- `timeout`: Time to wait in **milliseconds** (minimum: 1000ms / 1 second) - -**Returns**: - -ReadyCmd that waits for the specified duration -Example -```python -from e2b import Template, wait_for_timeout - -template = ( - Template() - .from_node_image() - .set_start_cmd('npm start', wait_for_timeout(5000)) # Wait 5 seconds -) -``` - - - - - - -### read\_dockerignore - -```python -def read_dockerignore(context_path: str) -> List[str] -``` - -Read and parse a .dockerignore file. - -**Arguments**: - -- `context_path`: Directory path containing the .dockerignore file - -**Returns**: - -Array of ignore patterns (empty lines and comments are filtered out) - - - -### normalize\_path - -```python -def normalize_path(path: str) -> str -``` - -Normalize path separators to forward slashes for glob patterns (glob expects / even on Windows). - -**Arguments**: - -- `path`: The path to normalize - -**Returns**: - -The normalized path - - - -### get\_all\_files\_in\_path - -```python -def get_all_files_in_path(src: str, - context_path: str, - ignore_patterns: List[str], - include_directories: bool = True) -> List[str] -``` - -Get all files for a given path and ignore patterns. - -**Arguments**: - -- `src`: Path to the source directory -- `context_path`: Base directory for resolving relative paths -- `ignore_patterns`: Ignore patterns -- `include_directories`: Whether to include directories - -**Returns**: - -Array of files - - - -### calculate\_files\_hash - -```python -def calculate_files_hash(src: str, dest: str, context_path: str, - ignore_patterns: List[str], resolve_symlinks: bool, - stack_trace: Optional[TracebackType]) -> str -``` - -Calculate a hash of files being copied to detect changes for cache invalidation. - -The hash includes file content, metadata (mode, size), and relative paths. -Note: uid, gid, and mtime are excluded to ensure stable hashes across environments. - -**Arguments**: - -- `src`: Source path pattern for files to copy -- `dest`: Destination path where files will be copied -- `context_path`: Base directory for resolving relative paths -- `ignore_patterns`: Glob patterns to ignore -- `resolve_symlinks`: Whether to resolve symbolic links when hashing -- `stack_trace`: Optional stack trace for error reporting - -**Raises**: - -- `ValueError`: If no files match the source pattern - -**Returns**: - -Hex string hash of all files - - - -### tar\_file\_stream - -```python -def tar_file_stream(file_name: str, file_context_path: str, - ignore_patterns: List[str], - resolve_symlinks: bool) -> io.BytesIO -``` - -Create a tar stream of files matching a pattern. - -**Arguments**: - -- `file_name`: Glob pattern for files to include -- `file_context_path`: Base directory for resolving file paths -- `ignore_patterns`: Ignore patterns -- `resolve_symlinks`: Whether to resolve symbolic links - -**Returns**: - -Tar stream - - - -### strip\_ansi\_escape\_codes - -```python -def strip_ansi_escape_codes(text: str) -> str -``` - -Strip ANSI escape codes from a string. - -Source: https://github.com/chalk/ansi-regex/blob/main/index.js - -**Arguments**: - -- `text`: String with ANSI escape codes - -**Returns**: - -String without ANSI escape codes - - - -### get\_caller\_frame - -```python -def get_caller_frame(depth: int) -> Optional[FrameType] -``` - -Get the caller's stack frame at a specific depth. - -This is used to provide better error messages and debugging information -by tracking where template methods were called from in user code. - -**Arguments**: - -- `depth`: The depth of the stack trace to retrieve - -**Returns**: - -The caller frame, or None if not available - - - -### get\_caller\_directory - -```python -def get_caller_directory(depth: int) -> Optional[str] -``` - -Get the directory of the caller at a specific stack depth. - -This is used to determine the file_context_path when creating a template, -so file paths are resolved relative to the user's template file location. - -**Arguments**: - -- `depth`: The depth of the stack trace - -**Returns**: - -The caller's directory path, or None if not available - - - -### pad\_octal - -```python -def pad_octal(mode: int) -> str -``` - -Convert a numeric file mode to a zero-padded octal string. - -**Arguments**: - -- `mode`: File mode as a number (e.g., 493 for 0o755) - -**Returns**: - -Zero-padded 4-digit octal string (e.g., "0755") -Example -```python -pad_octal(0o755) # Returns "0755" -pad_octal(0o644) # Returns "0644" -``` - - - -### get\_build\_step\_index - -```python -def get_build_step_index(step: str, stack_traces_length: int) -> int -``` - -Get the array index for a build step based on its name. - -Special steps: -- BASE_STEP_NAME: Returns 0 (first step) -- FINALIZE_STEP_NAME: Returns the last index -- Numeric strings: Converted to number - -**Arguments**: - -- `step`: Build step name or number as string -- `stack_traces_length`: Total number of stack traces (used for FINALIZE_STEP_NAME) - -**Returns**: - -Index for the build step - - - -### read\_gcp\_service\_account\_json - -```python -def read_gcp_service_account_json(context_path: str, - path_or_content: Union[str, dict]) -> str -``` - -Read GCP service account JSON from a file or object. - -**Arguments**: - -- `context_path`: Base directory for resolving relative file paths -- `path_or_content`: Either a path to a JSON file or a service account object - -**Returns**: - -Service account JSON as a string - - - - - - -## TemplateBuilder - -```python -class TemplateBuilder() -``` - -Builder class for adding instructions to an E2B template. - -All methods return self to allow method chaining. - - - -### copy - -```python -def copy(src: Union[Union[str, Path], List[Union[str, Path]]], - dest: Union[str, Path], - force_upload: Optional[Literal[True]] = None, - user: Optional[str] = None, - mode: Optional[int] = None, - resolve_symlinks: Optional[bool] = None) -> "TemplateBuilder" -``` - -Copy files or directories from the local filesystem into the template. - -**Arguments**: - -- `src`: Source file(s) or directory path(s) to copy -- `dest`: Destination path in the template -- `force_upload`: Force upload even if files are cached -- `user`: User and optionally group (user:group) to own the files -- `mode`: File permissions in octal format (e.g., 0o755) -- `resolve_symlinks`: Whether to resolve symlinks - -**Returns**: - -`TemplateBuilder` class -Example -```python -template.copy('requirements.txt', '/home/user/') -template.copy(['app.py', 'config.py'], '/app/', mode=0o755) -``` - - - -### copy\_items - -```python -def copy_items(items: List[CopyItem]) -> "TemplateBuilder" -``` - -Copy multiple files or directories using a list of copy items. - -**Arguments**: - -- `items`: List of CopyItem dictionaries with src, dest, and optional parameters - -**Returns**: - -`TemplateBuilder` class -Example -```python -template.copy_items([ - {'src': 'app.py', 'dest': '/app/'}, - {'src': 'config.py', 'dest': '/app/', 'mode': 0o644} -]) -``` - - - -### remove - -```python -def remove(path: Union[Union[str, Path], List[Union[str, Path]]], - force: bool = False, - recursive: bool = False, - user: Optional[str] = None) -> "TemplateBuilder" -``` - -Remove files or directories in the template. - -**Arguments**: - -- `path`: File(s) or directory path(s) to remove -- `force`: Force removal without prompting -- `recursive`: Remove directories recursively -- `user`: User to run the command as - -**Returns**: - -`TemplateBuilder` class -Example -```python -template.remove('/tmp/cache', recursive=True, force=True) -template.remove('/tmp/cache', recursive=True, force=True, user='root') -``` - - - -### rename - -```python -def rename(src: Union[str, Path], - dest: Union[str, Path], - force: bool = False, - user: Optional[str] = None) -> "TemplateBuilder" -``` - -Rename or move a file or directory in the template. - -**Arguments**: - -- `src`: Source path -- `dest`: Destination path -- `force`: Force rename without prompting -- `user`: User to run the command as - -**Returns**: - -`TemplateBuilder` class -Example -```python -template.rename('/tmp/old.txt', '/tmp/new.txt') -template.rename('/tmp/old.txt', '/tmp/new.txt', user='root') -``` - - - -### make\_dir - -```python -def make_dir(path: Union[Union[str, Path], List[Union[str, Path]]], - mode: Optional[int] = None, - user: Optional[str] = None) -> "TemplateBuilder" -``` - -Create directory(ies) in the template. - -**Arguments**: - -- `path`: Directory path(s) to create -- `mode`: Directory permissions in octal format (e.g., 0o755) -- `user`: User to run the command as - -**Returns**: - -`TemplateBuilder` class -Example -```python -template.make_dir('/app/data', mode=0o755) -template.make_dir(['/app/logs', '/app/cache']) -template.make_dir('/app/data', mode=0o755, user='root') -``` - - - -### make\_symlink - -```python -def make_symlink(src: Union[str, Path], - dest: Union[str, Path], - user: Optional[str] = None, - force: bool = False) -> "TemplateBuilder" -``` - -Create a symbolic link in the template. - -**Arguments**: - -- `src`: Source path (target of the symlink) -- `dest`: Destination path (location of the symlink) -- `user`: User to run the command as -- `force`: Force symlink without prompting - -**Returns**: - -`TemplateBuilder` class -Example -```python -template.make_symlink('/usr/bin/python3', '/usr/bin/python') -template.make_symlink('/usr/bin/python3', '/usr/bin/python', user='root') -template.make_symlink('/usr/bin/python3', '/usr/bin/python', force=True) -``` - - - -### run\_cmd - -```python -def run_cmd(command: Union[str, List[str]], - user: Optional[str] = None) -> "TemplateBuilder" -``` - -Run a shell command during template build. - -**Arguments**: - -- `command`: Command string or list of commands to run (joined with &&) -- `user`: User to run the command as - -**Returns**: - -`TemplateBuilder` class -Example -```python -template.run_cmd('apt-get update') -template.run_cmd(['pip install numpy', 'pip install pandas']) -template.run_cmd('apt-get install vim', user='root') -``` - - - -### set\_workdir - -```python -def set_workdir(workdir: Union[str, Path]) -> "TemplateBuilder" -``` - -Set the working directory for subsequent commands in the template. - -**Arguments**: - -- `workdir`: Path to set as the working directory - -**Returns**: - -`TemplateBuilder` class -Example -```python -template.set_workdir('/app') -``` - - - -### set\_user - -```python -def set_user(user: str) -> "TemplateBuilder" -``` - -Set the user for subsequent commands in the template. - -**Arguments**: - -- `user`: Username to set - -**Returns**: - -`TemplateBuilder` class -Example -```python -template.set_user('root') -``` - - - -### pip\_install - -```python -def pip_install(packages: Optional[Union[str, List[str]]] = None, - g: bool = True) -> "TemplateBuilder" -``` - -Install Python packages using pip. - -**Arguments**: - -- `packages`: Package name(s) to install. If None, runs 'pip install .' in the current directory -- `g`: Install packages globally (default: True). If False, installs for user only - -**Returns**: - -`TemplateBuilder` class -Example -```python -template.pip_install('numpy') -template.pip_install(['pandas', 'scikit-learn']) -template.pip_install('numpy', g=False) # Install for user only -template.pip_install() # Installs from current directory -``` - - - -### npm\_install - -```python -def npm_install(packages: Optional[Union[str, List[str]]] = None, - g: Optional[bool] = False, - dev: Optional[bool] = False) -> "TemplateBuilder" -``` - -Install Node.js packages using npm. - -**Arguments**: - -- `packages`: Package name(s) to install. If None, installs from package.json -- `g`: Install packages globally -- `dev`: Install packages as dev dependencies - -**Returns**: - -`TemplateBuilder` class -Example -```python -template.npm_install('express') -template.npm_install(['lodash', 'axios']) -template.npm_install('typescript', g=True) -template.npm_install() # Installs from package.json -``` - - - -### bun\_install - -```python -def bun_install(packages: Optional[Union[str, List[str]]] = None, - g: Optional[bool] = False, - dev: Optional[bool] = False) -> "TemplateBuilder" -``` - -Install Bun packages using bun. - -**Arguments**: - -- `packages`: Package name(s) to install. If None, installs from package.json -- `g`: Install packages globally -- `dev`: Install packages as dev dependencies - -**Returns**: - -`TemplateBuilder` class -Example -```python -template.bun_install('express') -template.bun_install(['lodash', 'axios']) -template.bun_install('tsx', g=True) -template.bun_install('typescript', dev=True) -template.bun_install() // Installs from package.json -``` - - - -### apt\_install - -```python -def apt_install(packages: Union[str, List[str]], - no_install_recommends: bool = False) -> "TemplateBuilder" -``` - -Install system packages using apt-get. - -**Arguments**: - -- `packages`: Package name(s) to install -- `no_install_recommends`: Whether to install recommended packages - -**Returns**: - -`TemplateBuilder` class -Example -```python -template.apt_install('vim') -template.apt_install(['git', 'curl', 'wget']) -``` - - - -### add\_mcp\_server - -```python -def add_mcp_server(servers: Union[str, List[str]]) -> "TemplateBuilder" -``` - -Install MCP servers using mcp-gateway. - -Note: Requires a base image with mcp-gateway pre-installed (e.g., mcp-gateway). - -**Arguments**: - -- `servers`: MCP server name(s) - -**Returns**: - -`TemplateBuilder` class -Example -```python -template.add_mcp_server('exa') -template.add_mcp_server(['brave', 'firecrawl', 'duckduckgo']) -``` - - - -### git\_clone - -```python -def git_clone(url: str, - path: Optional[Union[str, Path]] = None, - branch: Optional[str] = None, - depth: Optional[int] = None, - user: Optional[str] = None) -> "TemplateBuilder" -``` - -Clone a git repository into the template. - -**Arguments**: - -- `url`: Git repository URL -- `path`: Destination path for the clone -- `branch`: Branch to clone -- `depth`: Clone depth for shallow clones -- `user`: User to run the command as - -**Returns**: - -`TemplateBuilder` class -Example -```python -template.git_clone('https://github.com/user/repo.git', '/app/repo') -template.git_clone('https://github.com/user/repo.git', branch='main', depth=1) -template.git_clone('https://github.com/user/repo.git', '/app/repo', user='root') -``` - - - -### beta\_dev\_container\_prebuild - -```python -def beta_dev_container_prebuild( - devcontainer_directory: Union[str, Path]) -> "TemplateBuilder" -``` - -Prebuild a devcontainer from the specified directory during the build process. - -**Arguments**: - -- `devcontainer_directory`: Path to the devcontainer directory - -**Returns**: - -`TemplateBuilder` class -Example -```python -template.git_clone('https://myrepo.com/project.git', '/my-devcontainer') -template.beta_dev_container_prebuild('/my-devcontainer') -``` - - - -### beta\_set\_dev\_container\_start - -```python -def beta_set_dev_container_start( - devcontainer_directory: Union[str, Path]) -> "TemplateFinal" -``` - -Start a devcontainer from the specified directory and set it as the start command. - -This method returns `TemplateFinal`, which means it must be the last method in the chain. - -**Arguments**: - -- `devcontainer_directory`: Path to the devcontainer directory - -**Returns**: - -`TemplateFinal` class -Example -```python -template.git_clone('https://myrepo.com/project.git', '/my-devcontainer') -template.beta_set_devcontainer_start('/my-devcontainer') - -template.git_clone('https://myrepo.com/project.git', '/my-devcontainer') -template.beta_dev_container_prebuild('/my-devcontainer') -template.beta_set_dev_container_start('/my-devcontainer') -``` - - - -### set\_envs - -```python -def set_envs(envs: Dict[str, str]) -> "TemplateBuilder" -``` - -Set environment variables. - -Note: Environment variables defined here are available only during template build. - -**Arguments**: - -- `envs`: Dictionary of environment variable names and values - -**Returns**: - -`TemplateBuilder` class -Example -```python -template.set_envs({'NODE_ENV': 'production', 'PORT': '8080'}) -``` - - - -### skip\_cache - -```python -def skip_cache() -> "TemplateBuilder" -``` - -Skip cache for all subsequent build instructions from this point. - -Call this before any instruction to force it and all following layers -to be rebuilt, ignoring any cached layers. - -**Returns**: - -`TemplateBuilder` class -Example -```python -template.skip_cache().run_cmd('apt-get update') -``` - - - -### set\_start\_cmd - -```python -def set_start_cmd(start_cmd: str, - ready_cmd: Union[str, ReadyCmd]) -> "TemplateFinal" -``` - -Set the command to start when the sandbox launches and the ready check command. - -**Arguments**: - -- `start_cmd`: Command to run when the sandbox starts -- `ready_cmd`: Command or ReadyCmd to check if the sandbox is ready - -**Returns**: - -`TemplateFinal` class -Example -```python -template.set_start_cmd( - 'python app.py', - 'curl http://localhost:8000/health' -) - -from e2b import wait_for_port, wait_for_url - -template.set_start_cmd( - 'python -m http.server 8000', - wait_for_port(8000) -) - -template.set_start_cmd( - 'npm start', - wait_for_url('http://localhost:3000/health', 200) -) -``` - - - -### set\_ready\_cmd - -```python -def set_ready_cmd(ready_cmd: Union[str, ReadyCmd]) -> "TemplateFinal" -``` - -Set the command to check if the sandbox is ready. - -**Arguments**: - -- `ready_cmd`: Command or ReadyCmd to check if the sandbox is ready - -**Returns**: - -`TemplateFinal` class -Example -```python -template.set_ready_cmd('curl http://localhost:8000/health') - -from e2b import wait_for_port, wait_for_file, wait_for_process - -template.set_ready_cmd(wait_for_port(3000)) - -template.set_ready_cmd(wait_for_file('/tmp/ready')) - -template.set_ready_cmd(wait_for_process('nginx')) -``` - - - -## TemplateFinal - -```python -class TemplateFinal() -``` - -Final template state after start/ready commands are set. - - - -## TemplateBase - -```python -class TemplateBase() -``` - -Base class for building E2B sandbox templates. - - - -### \_\_init\_\_ - -```python -def __init__(file_context_path: Optional[Union[str, Path]] = None, - file_ignore_patterns: Optional[List[str]] = None) -``` - -Create a new template builder instance. - -**Arguments**: - -- `file_context_path`: Base path for resolving relative file paths in copy operations -- `file_ignore_patterns`: List of glob patterns to ignore when copying files - - - -### skip\_cache - -```python -def skip_cache() -> "TemplateBase" -``` - -Skip cache for all subsequent build instructions from this point. - -**Returns**: - -`TemplateBase` class -Example -```python -template.skip_cache().from_python_image('3.11') -``` - - - -### from\_debian\_image - -```python -def from_debian_image(variant: str = "stable") -> TemplateBuilder -``` - -Start template from a Debian base image. - -**Arguments**: - -- `variant`: Debian image variant - -**Returns**: - -`TemplateBuilder` class -Example -```python -Template().from_debian_image('bookworm') -``` - - - -### from\_ubuntu\_image - -```python -def from_ubuntu_image(variant: str = "latest") -> TemplateBuilder -``` - -Start template from an Ubuntu base image. - -**Arguments**: - -- `variant`: Ubuntu image variant (default: 'latest') - -**Returns**: - -`TemplateBuilder` class -Example -```python -Template().from_ubuntu_image('24.04') -``` - - - -### from\_python\_image - -```python -def from_python_image(version: str = "3") -> TemplateBuilder -``` - -Start template from a Python base image. - -**Arguments**: - -- `version`: Python version (default: '3') - -**Returns**: - -`TemplateBuilder` class -Example -```python -Template().from_python_image('3') -``` - - - -### from\_node\_image - -```python -def from_node_image(variant: str = "lts") -> TemplateBuilder -``` - -Start template from a Node.js base image. - -**Arguments**: - -- `variant`: Node.js image variant (default: 'lts') - -**Returns**: - -`TemplateBuilder` class -Example -```python -Template().from_node_image('24') -``` - - - -### from\_bun\_image - -```python -def from_bun_image(variant: str = "latest") -> TemplateBuilder -``` - -Start template from a Bun base image. - -**Arguments**: - -- `variant`: Bun image variant (default: 'latest') - -**Returns**: - -`TemplateBuilder` class - - - -### from\_base\_image - -```python -def from_base_image() -> TemplateBuilder -``` - -Start template from the E2B base image (e2bdev/base:latest). - -**Returns**: - -`TemplateBuilder` class -Example -```python -Template().from_base_image() -``` - - - -### from\_image - -```python -def from_image(image: str, - username: Optional[str] = None, - password: Optional[str] = None) -> TemplateBuilder -``` - -Start template from a Docker image. - -**Arguments**: - -- `image`: Docker image name (e.g., 'ubuntu:24.04') -- `username`: Username for private registry authentication -- `password`: Password for private registry authentication - -**Returns**: - -`TemplateBuilder` class -Example -```python -Template().from_image('python:3') - -Template().from_image('myregistry.com/myimage:latest', username='user', password='pass') -``` - - - -### from\_template - -```python -def from_template(template: str) -> TemplateBuilder -``` - -Start template from an existing E2B template. - -**Arguments**: - -- `template`: E2B template ID or alias - -**Returns**: - -`TemplateBuilder` class -Example -```python -Template().from_template('my-base-template') -``` - - - -### from\_dockerfile - -```python -def from_dockerfile(dockerfile_content_or_path: str) -> TemplateBuilder -``` - -Parse a Dockerfile and convert it to Template SDK format. - -**Arguments**: - -- `dockerfile_content_or_path`: Either the Dockerfile content as a string, or a path to a Dockerfile file - -**Returns**: - -`TemplateBuilder` class -Example -```python -Template().from_dockerfile('Dockerfile') -Template().from_dockerfile('FROM python:3\nRUN pip install numpy') -``` - - - -### from\_aws\_registry - -```python -def from_aws_registry(image: str, access_key_id: str, secret_access_key: str, - region: str) -> TemplateBuilder -``` - -Start template from an AWS ECR registry image. - -**Arguments**: - -- `image`: Docker image name from AWS ECR -- `access_key_id`: AWS access key ID -- `secret_access_key`: AWS secret access key -- `region`: AWS region - -**Returns**: - -`TemplateBuilder` class -Example -```python -Template().from_aws_registry( - '123456789.dkr.ecr.us-west-2.amazonaws.com/myimage:latest', - access_key_id='AKIA...', - secret_access_key='...', - region='us-west-2' -) -``` - - - -### from\_gcp\_registry - -```python -def from_gcp_registry( - image: str, service_account_json: Union[str, dict]) -> TemplateBuilder -``` - -Start template from a GCP Artifact Registry or Container Registry image. - -**Arguments**: - -- `image`: Docker image name from GCP registry -- `service_account_json`: Service account JSON string, dict, or path to JSON file - -**Returns**: - -`TemplateBuilder` class -Example -```python -Template().from_gcp_registry( - 'gcr.io/myproject/myimage:latest', - service_account_json='path/to/service-account.json' -) -``` - - - -### to\_json - -```python -@staticmethod -def to_json(template: "TemplateClass") -> str -``` - -Convert a template to JSON representation. - -**Arguments**: - -- `template`: The template to convert (TemplateBuilder or TemplateFinal instance) - -**Returns**: - -JSON string representation of the template -Example -```python -template = Template().from_python_image('3').copy('app.py', '/app/') -json_str = TemplateBase.to_json(template) -``` - - - -### to\_dockerfile - -```python -@staticmethod -def to_dockerfile(template: "TemplateClass") -> str -``` - -Convert a template to Dockerfile format. - -Note: Templates based on other E2B templates cannot be converted to Dockerfile. - -**Arguments**: - -- `template`: The template to convert (TemplateBuilder or TemplateFinal instance) - -**Raises**: - -- `ValueError`: If the template is based on another E2B template or has no base image -Example -```python -template = Template().from_python_image('3').copy('app.py', '/app/') -dockerfile = TemplateBase.to_dockerfile(template) -``` - -**Returns**: - -Dockerfile string representation diff --git a/docs/sdk-reference/python-sdk/v2.9.0/template_async.mdx b/docs/sdk-reference/python-sdk/v2.9.0/template_async.mdx deleted file mode 100644 index 950d066..0000000 --- a/docs/sdk-reference/python-sdk/v2.9.0/template_async.mdx +++ /dev/null @@ -1,150 +0,0 @@ ---- -sidebarTitle: "Template Async" -mode: "center" ---- - - - - - - - - - -## AsyncTemplate - -```python -class AsyncTemplate(TemplateBase) -``` - -Asynchronous template builder for E2B sandboxes. - - - -### build - -```python -@staticmethod -async def build(template: TemplateClass, - alias: str, - cpu_count: int = 2, - memory_mb: int = 1024, - skip_cache: bool = False, - on_build_logs: Optional[Callable[[LogEntry], None]] = None, - api_key: Optional[str] = None, - domain: Optional[str] = None) -> BuildInfo -``` - -Build and deploy a template to E2B infrastructure. - -**Arguments**: - -- `template`: The template to build -- `alias`: Alias name for the template -- `cpu_count`: Number of CPUs allocated to the sandbox -- `memory_mb`: Amount of memory in MB allocated to the sandbox -- `skip_cache`: If True, forces a complete rebuild ignoring cache -- `on_build_logs`: Callback function to receive build logs during the build process -- `api_key`: E2B API key for authentication -- `domain`: Domain of the E2B API -Example -```python -from e2b import AsyncTemplate - -template = ( - AsyncTemplate() - .from_python_image('3') - .copy('requirements.txt', '/home/user/') - .run_cmd('pip install -r /home/user/requirements.txt') -) - -await AsyncTemplate.build( - template, - alias='my-python-env', - cpu_count=2, - memory_mb=1024 -) -``` - - - -### build\_in\_background - -```python -@staticmethod -async def build_in_background(template: TemplateClass, - alias: str, - cpu_count: int = 2, - memory_mb: int = 1024, - skip_cache: bool = False, - on_build_logs: Optional[Callable[[LogEntry], - None]] = None, - api_key: Optional[str] = None, - domain: Optional[str] = None) -> BuildInfo -``` - -Build and deploy a template to E2B infrastructure without waiting for completion. - -**Arguments**: - -- `template`: The template to build -- `alias`: Alias name for the template -- `cpu_count`: Number of CPUs allocated to the sandbox -- `memory_mb`: Amount of memory in MB allocated to the sandbox -- `skip_cache`: If True, forces a complete rebuild ignoring cache -- `api_key`: E2B API key for authentication -- `domain`: Domain of the E2B API - -**Returns**: - -BuildInfo containing the template ID and build ID -Example -```python -from e2b import AsyncTemplate - -template = ( - AsyncTemplate() - .from_python_image('3') - .run_cmd('echo "test"') - .set_start_cmd('echo "Hello"', 'sleep 1') -) - -build_info = await AsyncTemplate.build_in_background( - template, - alias='my-python-env', - cpu_count=2, - memory_mb=1024 -) -``` - - - -### get\_build\_status - -```python -@staticmethod -async def get_build_status(build_info: BuildInfo, - logs_offset: int = 0, - api_key: Optional[str] = None, - domain: Optional[str] = None) -``` - -Get the status of a build. - -**Arguments**: - -- `build_info`: Build identifiers returned from build_in_background -- `logs_offset`: Offset for fetching logs -- `api_key`: E2B API key for authentication -- `domain`: Domain of the E2B API - -**Returns**: - -TemplateBuild containing the build status and logs -Example -```python -from e2b import AsyncTemplate - -build_info = await AsyncTemplate.build_in_background(template, alias='my-template') -status = await AsyncTemplate.get_build_status(build_info, logs_offset=0) -``` diff --git a/docs/sdk-reference/python-sdk/v2.9.0/template_sync.mdx b/docs/sdk-reference/python-sdk/v2.9.0/template_sync.mdx deleted file mode 100644 index 6387438..0000000 --- a/docs/sdk-reference/python-sdk/v2.9.0/template_sync.mdx +++ /dev/null @@ -1,150 +0,0 @@ ---- -sidebarTitle: "Template Sync" -mode: "center" ---- - - - - - - - - - -## Template - -```python -class Template(TemplateBase) -``` - -Synchronous template builder for E2B sandboxes. - - - -### build - -```python -@staticmethod -def build(template: TemplateClass, - alias: str, - cpu_count: int = 2, - memory_mb: int = 1024, - skip_cache: bool = False, - on_build_logs: Optional[Callable[[LogEntry], None]] = None, - api_key: Optional[str] = None, - domain: Optional[str] = None) -> BuildInfo -``` - -Build and deploy a template to E2B infrastructure. - -**Arguments**: - -- `template`: The template to build -- `alias`: Alias name for the template -- `cpu_count`: Number of CPUs allocated to the sandbox -- `memory_mb`: Amount of memory in MB allocated to the sandbox -- `skip_cache`: If True, forces a complete rebuild ignoring cache -- `on_build_logs`: Callback function to receive build logs during the build process -- `api_key`: E2B API key for authentication -- `domain`: Domain of the E2B API -Example -```python -from e2b import Template - -template = ( - Template() - .from_python_image('3') - .copy('requirements.txt', '/home/user/') - .run_cmd('pip install -r /home/user/requirements.txt') -) - -Template.build( - template, - alias='my-python-env', - cpu_count=2, - memory_mb=1024 -) -``` - - - -### build\_in\_background - -```python -@staticmethod -def build_in_background(template: TemplateClass, - alias: str, - cpu_count: int = 2, - memory_mb: int = 1024, - skip_cache: bool = False, - on_build_logs: Optional[Callable[[LogEntry], - None]] = None, - api_key: Optional[str] = None, - domain: Optional[str] = None) -> BuildInfo -``` - -Build and deploy a template to E2B infrastructure without waiting for completion. - -**Arguments**: - -- `template`: The template to build -- `alias`: Alias name for the template -- `cpu_count`: Number of CPUs allocated to the sandbox -- `memory_mb`: Amount of memory in MB allocated to the sandbox -- `skip_cache`: If True, forces a complete rebuild ignoring cache -- `api_key`: E2B API key for authentication -- `domain`: Domain of the E2B API - -**Returns**: - -BuildInfo containing the template ID and build ID -Example -```python -from e2b import Template - -template = ( - Template() - .from_python_image('3') - .run_cmd('echo "test"') - .set_start_cmd('echo "Hello"', 'sleep 1') -) - -build_info = Template.build_in_background( - template, - alias='my-python-env', - cpu_count=2, - memory_mb=1024 -) -``` - - - -### get\_build\_status - -```python -@staticmethod -def get_build_status(build_info: BuildInfo, - logs_offset: int = 0, - api_key: Optional[str] = None, - domain: Optional[str] = None) -``` - -Get the status of a build. - -**Arguments**: - -- `build_info`: Build identifiers returned from build_in_background -- `logs_offset`: Offset for fetching logs -- `api_key`: E2B API key for authentication -- `domain`: Domain of the E2B API - -**Returns**: - -TemplateBuild containing the build status and logs -Example -```python -from e2b import Template - -build_info = Template.build_in_background(template, alias='my-template') -status = Template.get_build_status(build_info, logs_offset=0) -``` From 07d46d4502ab3104f82880ceb57734808aea9238 Mon Sep 17 00:00:00 2001 From: ben-fornefeld Date: Mon, 12 Jan 2026 13:09:28 +0100 Subject: [PATCH 25/39] add: limit as input --- .github/workflows/sdk-reference-sync.yml | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/.github/workflows/sdk-reference-sync.yml b/.github/workflows/sdk-reference-sync.yml index b2f5906..bd89dac 100644 --- a/.github/workflows/sdk-reference-sync.yml +++ b/.github/workflows/sdk-reference-sync.yml @@ -15,6 +15,12 @@ on: default: "all" type: string + limit: + description: "Limit number of versions to generate (default: 5)" + required: false + default: 5 + type: number + # triggered from e2b-dev/e2b repo on release repository_dispatch: types: [sdk-release] From 4d0ce3f537610719047f0229051acf0632e89931 Mon Sep 17 00:00:00 2001 From: ben-fornefeld Date: Mon, 12 Jan 2026 13:15:56 +0100 Subject: [PATCH 26/39] fix: infer limit input correctly in workflow --- .github/workflows/sdk-reference-sync.yml | 3 +++ 1 file changed, 3 insertions(+) diff --git a/.github/workflows/sdk-reference-sync.yml b/.github/workflows/sdk-reference-sync.yml index bd89dac..0d3a0fc 100644 --- a/.github/workflows/sdk-reference-sync.yml +++ b/.github/workflows/sdk-reference-sync.yml @@ -74,9 +74,11 @@ jobs: if [[ "$EVENT_NAME" == "workflow_dispatch" ]]; then SDK="$INPUT_SDK" VERSION="$INPUT_VERSION" + LIMIT="${INPUT_LIMIT:-5}" elif [[ "$EVENT_NAME" == "repository_dispatch" ]]; then SDK="$PAYLOAD_SDK" VERSION="${PAYLOAD_VERSION:-all}" + LIMIT="${PAYLOAD_LIMIT:-5}" fi echo "sdk=${SDK:-all}" >> $GITHUB_OUTPUT @@ -91,6 +93,7 @@ jobs: pnpm run generate \ --sdk "$SDK_NAME" \ --version "$SDK_VERSION" + --limit "$LIMIT" - name: Verify generated files run: | From 3a1d58ffba52bdf1b7383e6d4fbfbd596c69c49a Mon Sep 17 00:00:00 2001 From: ben-fornefeld Date: Mon, 12 Jan 2026 13:20:23 +0100 Subject: [PATCH 27/39] fix: limit --- .github/workflows/sdk-reference-sync.yml | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/.github/workflows/sdk-reference-sync.yml b/.github/workflows/sdk-reference-sync.yml index 0d3a0fc..d3a5406 100644 --- a/.github/workflows/sdk-reference-sync.yml +++ b/.github/workflows/sdk-reference-sync.yml @@ -89,6 +89,7 @@ jobs: env: SDK_NAME: ${{ steps.params.outputs.sdk }} SDK_VERSION: ${{ steps.params.outputs.version }} + LIMIT: ${{ steps.params.outputs.limit }} run: | pnpm run generate \ --sdk "$SDK_NAME" \ @@ -104,6 +105,7 @@ jobs: env: SDK_NAME: ${{ steps.params.outputs.sdk }} SDK_VERSION: ${{ steps.params.outputs.version }} + LIMIT: ${{ steps.params.outputs.limit }} run: | git config user.name "github-actions[bot]" git config user.email "github-actions[bot]@users.noreply.github.com" @@ -114,7 +116,7 @@ jobs: if git diff --staged --quiet; then echo "No changes to commit" else - git commit -m "[skip ci] Update SDK reference: $SDK_NAME $SDK_VERSION" + git commit -m "[skip ci] Update SDK reference: $SDK_NAME $SDK_VERSION $LIMIT" git push fi @@ -122,11 +124,13 @@ jobs: env: SDK_NAME: ${{ steps.params.outputs.sdk }} SDK_VERSION: ${{ steps.params.outputs.version }} + LIMIT: ${{ steps.params.outputs.limit }} run: | echo "## SDK Reference Generation Complete" >> $GITHUB_STEP_SUMMARY echo "" >> $GITHUB_STEP_SUMMARY echo "- **SDK**: $SDK_NAME" >> $GITHUB_STEP_SUMMARY echo "- **Version**: $SDK_VERSION" >> $GITHUB_STEP_SUMMARY + echo "- **Limit**: $LIMIT" >> $GITHUB_STEP_SUMMARY echo "" >> $GITHUB_STEP_SUMMARY echo "### Generated Files" >> $GITHUB_STEP_SUMMARY echo '```' >> $GITHUB_STEP_SUMMARY From a7a75f811dfa96a68c21e95bf7e632927f7f29c8 Mon Sep 17 00:00:00 2001 From: ben-fornefeld Date: Mon, 12 Jan 2026 13:22:50 +0100 Subject: [PATCH 28/39] fix limit --- .github/workflows/sdk-reference-sync.yml | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) diff --git a/.github/workflows/sdk-reference-sync.yml b/.github/workflows/sdk-reference-sync.yml index d3a5406..6364b63 100644 --- a/.github/workflows/sdk-reference-sync.yml +++ b/.github/workflows/sdk-reference-sync.yml @@ -68,8 +68,10 @@ jobs: EVENT_NAME: ${{ github.event_name }} INPUT_SDK: ${{ github.event.inputs.sdk }} INPUT_VERSION: ${{ github.event.inputs.version }} + INPUT_LIMIT: ${{ github.event.inputs.limit }} PAYLOAD_SDK: ${{ github.event.client_payload.sdk }} PAYLOAD_VERSION: ${{ github.event.client_payload.version }} + PAYLOAD_LIMIT: ${{ github.event.client_payload.limit }} run: | if [[ "$EVENT_NAME" == "workflow_dispatch" ]]; then SDK="$INPUT_SDK" @@ -83,6 +85,7 @@ jobs: echo "sdk=${SDK:-all}" >> $GITHUB_OUTPUT echo "version=${VERSION:-all}" >> $GITHUB_OUTPUT + echo "limit=${LIMIT:-5}" >> $GITHUB_OUTPUT - name: Generate SDK Reference working-directory: sdk-reference-generator @@ -93,7 +96,7 @@ jobs: run: | pnpm run generate \ --sdk "$SDK_NAME" \ - --version "$SDK_VERSION" + --version "$SDK_VERSION" \ --limit "$LIMIT" - name: Verify generated files @@ -116,7 +119,7 @@ jobs: if git diff --staged --quiet; then echo "No changes to commit" else - git commit -m "[skip ci] Update SDK reference: $SDK_NAME $SDK_VERSION $LIMIT" + git commit -m "[skip ci] Update SDK reference: $SDK_NAME $SDK_VERSION (limit: $LIMIT)" git push fi From 09a27fa533714721ec623b996f71a3dd5ff80e4b Mon Sep 17 00:00:00 2001 From: ben-fornefeld Date: Mon, 12 Jan 2026 13:28:01 +0100 Subject: [PATCH 29/39] chore: force color --- .github/workflows/sdk-reference-sync.yml | 1 + 1 file changed, 1 insertion(+) diff --git a/.github/workflows/sdk-reference-sync.yml b/.github/workflows/sdk-reference-sync.yml index 6364b63..6049478 100644 --- a/.github/workflows/sdk-reference-sync.yml +++ b/.github/workflows/sdk-reference-sync.yml @@ -93,6 +93,7 @@ jobs: SDK_NAME: ${{ steps.params.outputs.sdk }} SDK_VERSION: ${{ steps.params.outputs.version }} LIMIT: ${{ steps.params.outputs.limit }} + FORCE_COLOR: 2 run: | pnpm run generate \ --sdk "$SDK_NAME" \ From 15ff8e3d4dced844867b54bfaac3577270ccac52 Mon Sep 17 00:00:00 2001 From: ben-fornefeld Date: Mon, 12 Jan 2026 13:33:46 +0100 Subject: [PATCH 30/39] cleanup: action --- .github/workflows/sdk-reference-sync.yml | 89 ++++++++++++++++-------- 1 file changed, 60 insertions(+), 29 deletions(-) diff --git a/.github/workflows/sdk-reference-sync.yml b/.github/workflows/sdk-reference-sync.yml index 6049478..796a507 100644 --- a/.github/workflows/sdk-reference-sync.yml +++ b/.github/workflows/sdk-reference-sync.yml @@ -1,7 +1,6 @@ name: Sync SDK Reference Documentation on: - # manual trigger with inputs workflow_dispatch: inputs: sdk: @@ -12,22 +11,31 @@ on: version: description: "Version to generate (all, latest, or specific like v2.9.0)" required: true - default: "all" + default: "latest" type: string - limit: description: "Limit number of versions to generate (default: 5)" required: false default: 5 type: number + force: + description: "Force regeneration of existing versions" + required: false + default: false + type: boolean - # triggered from e2b-dev/e2b repo on release repository_dispatch: types: [sdk-release] +# prevent concurrent runs that could conflict +concurrency: + group: sdk-reference-${{ github.ref }} + cancel-in-progress: false + jobs: generate: runs-on: ubuntu-latest + timeout-minutes: 30 permissions: contents: write @@ -47,10 +55,21 @@ jobs: with: version: 9 + - name: Cache pnpm dependencies + uses: actions/cache@v4 + with: + path: | + ~/.pnpm-store + sdk-reference-generator/node_modules + key: ${{ runner.os }}-pnpm-${{ hashFiles('sdk-reference-generator/pnpm-lock.yaml') }} + restore-keys: | + ${{ runner.os }}-pnpm- + - name: Setup Python uses: actions/setup-python@v5 with: python-version: "3.11" + cache: "pip" - name: Install generator dependencies working-directory: sdk-reference-generator @@ -59,9 +78,6 @@ jobs: - name: Install Python dependencies run: pip install -r requirements.txt - - name: Install Poetry - run: pip install poetry - - name: Determine SDK and Version id: params env: @@ -69,6 +85,7 @@ jobs: INPUT_SDK: ${{ github.event.inputs.sdk }} INPUT_VERSION: ${{ github.event.inputs.version }} INPUT_LIMIT: ${{ github.event.inputs.limit }} + INPUT_FORCE: ${{ github.event.inputs.force }} PAYLOAD_SDK: ${{ github.event.client_payload.sdk }} PAYLOAD_VERSION: ${{ github.event.client_payload.version }} PAYLOAD_LIMIT: ${{ github.event.client_payload.limit }} @@ -76,16 +93,19 @@ jobs: if [[ "$EVENT_NAME" == "workflow_dispatch" ]]; then SDK="$INPUT_SDK" VERSION="$INPUT_VERSION" - LIMIT="${INPUT_LIMIT:-5}" + LIMIT="$INPUT_LIMIT" + FORCE="$INPUT_FORCE" elif [[ "$EVENT_NAME" == "repository_dispatch" ]]; then SDK="$PAYLOAD_SDK" - VERSION="${PAYLOAD_VERSION:-all}" + VERSION="${PAYLOAD_VERSION:-latest}" LIMIT="${PAYLOAD_LIMIT:-5}" + FORCE="false" fi echo "sdk=${SDK:-all}" >> $GITHUB_OUTPUT - echo "version=${VERSION:-all}" >> $GITHUB_OUTPUT + echo "version=${VERSION:-latest}" >> $GITHUB_OUTPUT echo "limit=${LIMIT:-5}" >> $GITHUB_OUTPUT + echo "force=${FORCE:-false}" >> $GITHUB_OUTPUT - name: Generate SDK Reference working-directory: sdk-reference-generator @@ -93,23 +113,26 @@ jobs: SDK_NAME: ${{ steps.params.outputs.sdk }} SDK_VERSION: ${{ steps.params.outputs.version }} LIMIT: ${{ steps.params.outputs.limit }} - FORCE_COLOR: 2 + FORCE: ${{ steps.params.outputs.force }} + FORCE_COLOR: "2" run: | - pnpm run generate \ - --sdk "$SDK_NAME" \ - --version "$SDK_VERSION" \ - --limit "$LIMIT" + ARGS="--sdk $SDK_NAME --version $SDK_VERSION" - - name: Verify generated files - run: | - echo "Generated SDK reference files:" - find docs/sdk-reference -type f -name "*.mdx" 2>/dev/null | head -20 || echo "No MDX files found" + if [[ -n "$LIMIT" && "$LIMIT" != "0" ]]; then + ARGS="$ARGS --limit $LIMIT" + fi + + if [[ "$FORCE" == "true" ]]; then + ARGS="$ARGS --force" + fi + + pnpm run generate $ARGS - name: Commit and push changes + id: commit env: SDK_NAME: ${{ steps.params.outputs.sdk }} SDK_VERSION: ${{ steps.params.outputs.version }} - LIMIT: ${{ steps.params.outputs.limit }} run: | git config user.name "github-actions[bot]" git config user.email "github-actions[bot]@users.noreply.github.com" @@ -119,9 +142,11 @@ jobs: if git diff --staged --quiet; then echo "No changes to commit" + echo "changes=false" >> $GITHUB_OUTPUT else - git commit -m "[skip ci] Update SDK reference: $SDK_NAME $SDK_VERSION (limit: $LIMIT)" + git commit -m "docs: update SDK reference for $SDK_NAME $SDK_VERSION" git push + echo "changes=true" >> $GITHUB_OUTPUT fi - name: Summary @@ -129,15 +154,21 @@ jobs: SDK_NAME: ${{ steps.params.outputs.sdk }} SDK_VERSION: ${{ steps.params.outputs.version }} LIMIT: ${{ steps.params.outputs.limit }} + CHANGES: ${{ steps.commit.outputs.changes }} run: | echo "## SDK Reference Generation Complete" >> $GITHUB_STEP_SUMMARY echo "" >> $GITHUB_STEP_SUMMARY - echo "- **SDK**: $SDK_NAME" >> $GITHUB_STEP_SUMMARY - echo "- **Version**: $SDK_VERSION" >> $GITHUB_STEP_SUMMARY - echo "- **Limit**: $LIMIT" >> $GITHUB_STEP_SUMMARY + echo "| Parameter | Value |" >> $GITHUB_STEP_SUMMARY + echo "|-----------|-------|" >> $GITHUB_STEP_SUMMARY + echo "| SDK | $SDK_NAME |" >> $GITHUB_STEP_SUMMARY + echo "| Version | $SDK_VERSION |" >> $GITHUB_STEP_SUMMARY + echo "| Limit | ${LIMIT:-No limit} |" >> $GITHUB_STEP_SUMMARY + echo "| Changes committed | $CHANGES |" >> $GITHUB_STEP_SUMMARY echo "" >> $GITHUB_STEP_SUMMARY - echo "### Generated Files" >> $GITHUB_STEP_SUMMARY - echo '```' >> $GITHUB_STEP_SUMMARY - find docs/sdk-reference -type f -name "*.mdx" | wc -l | xargs echo "Total MDX files:" >> $GITHUB_STEP_SUMMARY - find docs/sdk-reference -type f -name "*.mdx" >> $GITHUB_STEP_SUMMARY || true - echo '```' >> $GITHUB_STEP_SUMMARY + + if [[ "$CHANGES" == "true" ]]; then + echo "### Generated Files" >> $GITHUB_STEP_SUMMARY + echo '```' >> $GITHUB_STEP_SUMMARY + echo "Total MDX files: $(find docs/sdk-reference -type f -name '*.mdx' | wc -l)" >> $GITHUB_STEP_SUMMARY + echo '```' >> $GITHUB_STEP_SUMMARY + fi From ca5cedbb37605fbd84de0f0ff6a246c784091788 Mon Sep 17 00:00:00 2001 From: ben-fornefeld Date: Mon, 12 Jan 2026 13:44:14 +0100 Subject: [PATCH 31/39] refactor: replace process.exit with error throwing for better error handling --- .../src/__tests__/versions.test.ts | 89 ++++++++++--------- sdk-reference-generator/src/cli.ts | 4 +- sdk-reference-generator/src/generator.ts | 8 +- sdk-reference-generator/src/lib/versions.ts | 44 ++++++--- sdk-reference-generator/src/navigation.ts | 6 +- 5 files changed, 87 insertions(+), 64 deletions(-) diff --git a/sdk-reference-generator/src/__tests__/versions.test.ts b/sdk-reference-generator/src/__tests__/versions.test.ts index 912dba1..6a928a2 100644 --- a/sdk-reference-generator/src/__tests__/versions.test.ts +++ b/sdk-reference-generator/src/__tests__/versions.test.ts @@ -1,74 +1,81 @@ -import { describe, it, expect } from 'vitest'; +import { describe, it, expect } from "vitest"; import { isValidVersion, versionGte, filterByMinVersion, diffVersions, -} from '../lib/versions.js'; +} from "../lib/versions.js"; -describe('isValidVersion', () => { - it('accepts valid semver versions', () => { - expect(isValidVersion('1.0.0')).toBe(true); - expect(isValidVersion('v1.0.0')).toBe(true); - expect(isValidVersion('v2.9.0')).toBe(true); - expect(isValidVersion('10.20.30')).toBe(true); +describe("isValidVersion", () => { + it("accepts valid semver versions", () => { + expect(isValidVersion("1.0.0")).toBe(true); + expect(isValidVersion("v1.0.0")).toBe(true); + expect(isValidVersion("v2.9.0")).toBe(true); + expect(isValidVersion("10.20.30")).toBe(true); }); - it('rejects invalid versions', () => { - expect(isValidVersion('main')).toBe(false); - expect(isValidVersion('latest')).toBe(false); - expect(isValidVersion('1.0')).toBe(false); - expect(isValidVersion('')).toBe(false); + it("rejects invalid versions", () => { + expect(isValidVersion("main")).toBe(false); + expect(isValidVersion("latest")).toBe(false); + expect(isValidVersion("1.0")).toBe(false); + expect(isValidVersion("")).toBe(false); }); }); -describe('versionGte', () => { - it('compares versions correctly', () => { - expect(versionGte('2.0.0', '1.0.0')).toBe(true); - expect(versionGte('1.0.0', '1.0.0')).toBe(true); - expect(versionGte('1.0.0', '2.0.0')).toBe(false); +describe("versionGte", () => { + it("compares versions correctly", () => { + expect(versionGte("2.0.0", "1.0.0")).toBe(true); + expect(versionGte("1.0.0", "1.0.0")).toBe(true); + expect(versionGte("1.0.0", "2.0.0")).toBe(false); }); - it('handles v prefix', () => { - expect(versionGte('v2.0.0', '1.0.0')).toBe(true); - expect(versionGte('2.0.0', 'v1.0.0')).toBe(true); - expect(versionGte('v2.0.0', 'v1.0.0')).toBe(true); + it("handles v prefix", () => { + expect(versionGte("v2.0.0", "1.0.0")).toBe(true); + expect(versionGte("2.0.0", "v1.0.0")).toBe(true); + expect(versionGte("v2.0.0", "v1.0.0")).toBe(true); }); }); -describe('filterByMinVersion', () => { - it('filters versions below minimum', () => { - const versions = ['v0.9.0', 'v1.0.0', 'v1.5.0', 'v2.0.0']; - const result = filterByMinVersion(versions, '1.0.0'); - expect(result).toEqual(['v1.0.0', 'v1.5.0', 'v2.0.0']); +describe("filterByMinVersion", () => { + it("filters versions below minimum", () => { + const versions = ["v0.9.0", "v1.0.0", "v1.5.0", "v2.0.0"]; + const result = filterByMinVersion(versions, "1.0.0"); + expect(result).toEqual(["v1.0.0", "v1.5.0", "v2.0.0"]); }); - it('returns all versions when no minimum specified', () => { - const versions = ['v0.9.0', 'v1.0.0', 'v2.0.0']; + it("returns all versions when no minimum specified", () => { + const versions = ["v0.9.0", "v1.0.0", "v2.0.0"]; const result = filterByMinVersion(versions); expect(result).toEqual(versions); }); - it('handles empty array', () => { - expect(filterByMinVersion([], '1.0.0')).toEqual([]); + it("handles empty array", () => { + expect(filterByMinVersion([], "1.0.0")).toEqual([]); }); }); -describe('diffVersions', () => { - it('finds versions in remote not in local', () => { - const remote = ['v1.0.0', 'v2.0.0', 'v3.0.0']; - const local = ['v1.0.0', 'v3.0.0']; - expect(diffVersions(remote, local)).toEqual(['v2.0.0']); +describe("diffVersions", () => { + it("finds versions in remote not in local", () => { + const remote = ["v1.0.0", "v2.0.0", "v3.0.0"]; + const local = ["v1.0.0", "v3.0.0"]; + expect(diffVersions(remote, local)).toEqual(["v2.0.0"]); }); - it('returns all remote when local is empty', () => { - const remote = ['v1.0.0', 'v2.0.0']; + it("returns all remote when local is empty", () => { + const remote = ["v1.0.0", "v2.0.0"]; expect(diffVersions(remote, [])).toEqual(remote); }); - it('returns empty when all versions exist locally', () => { - const versions = ['v1.0.0', 'v2.0.0']; + it("returns empty when all versions exist locally", () => { + const versions = ["v1.0.0", "v2.0.0"]; expect(diffVersions(versions, versions)).toEqual([]); }); -}); + it("matches normalized local versions (both have v prefix after normalization)", () => { + // fetchLocalVersions now normalizes all versions to have "v" prefix + // so local versions like "1.0.0" become "v1.0.0" before diffVersions is called + const remote = ["v1.0.0", "v2.0.0"]; + const local = ["v1.0.0"]; // normalized from "1.0.0" by fetchLocalVersions + expect(diffVersions(remote, local)).toEqual(["v2.0.0"]); + }); +}); diff --git a/sdk-reference-generator/src/cli.ts b/sdk-reference-generator/src/cli.ts index c935684..4c8381e 100644 --- a/sdk-reference-generator/src/cli.ts +++ b/sdk-reference-generator/src/cli.ts @@ -100,8 +100,8 @@ async function main(): Promise { } if (!verification.docsJsonValid) { log.error("docs.json validation failed"); - } - process.exit(1); + } + throw new Error("Documentation verification failed"); } log.blank(); diff --git a/sdk-reference-generator/src/generator.ts b/sdk-reference-generator/src/generator.ts index 6a5eed9..1a3cc7f 100644 --- a/sdk-reference-generator/src/generator.ts +++ b/sdk-reference-generator/src/generator.ts @@ -110,8 +110,7 @@ async function discoverAllVersions( if (remote.length === 0) { if (config.required) { - log.error("No tags found", 1); - process.exit(1); + throw new Error(`No tags found for required SDK: ${sdkKey}`); } log.warn("No tags found, skipping...", 1); return []; @@ -178,8 +177,7 @@ async function resolveSpecificVersion( if (!resolved) { if (config.required) { - log.error("No tags found", 1); - process.exit(1); + throw new Error(`No tags found for required SDK: ${sdkKey}`); } log.warn("No tags found, skipping...", 1); return []; @@ -278,7 +276,7 @@ function handleGenerationFailures( : "All versions failed"; log.error(`WORKFLOW ABORTED: ${reason}`, 1); log.error(`Failed: ${failedVersions.join(" ")}`, 1); - process.exit(1); + throw new Error(`Generation aborted: ${reason}`); } } diff --git a/sdk-reference-generator/src/lib/versions.ts b/sdk-reference-generator/src/lib/versions.ts index 595cf8c..2bbf4f6 100644 --- a/sdk-reference-generator/src/lib/versions.ts +++ b/sdk-reference-generator/src/lib/versions.ts @@ -1,8 +1,13 @@ -import fs from 'fs-extra'; -import path from 'path'; -import semver from 'semver'; -import { stripVersionPrefix, sortVersionsDescending, isValidVersion } from './utils.js'; -import { CONSTANTS } from './constants.js'; +import fs from "fs-extra"; +import path from "path"; +import semver from "semver"; +import { + stripVersionPrefix, + sortVersionsDescending, + isValidVersion, + normalizeVersion, +} from "./utils.js"; +import { CONSTANTS } from "./constants.js"; export { isValidVersion }; @@ -44,7 +49,8 @@ export async function fetchLocalVersions( const hasMdx = files.some((f) => f.endsWith(CONSTANTS.MDX_EXTENSION)); if (hasMdx) { - versions.push(entry.name); + // normalize to "v" prefix for consistent comparison with remote versions + versions.push(normalizeVersion(entry.name)); } } @@ -61,13 +67,27 @@ export async function versionExists( version: string, docsDir: string ): Promise { - const versionDir = path.join(docsDir, CONSTANTS.DOCS_SDK_REF_PATH, sdkKey, version); + const normalized = normalizeVersion(version); + const stripped = stripVersionPrefix(version); - if (!(await fs.pathExists(versionDir))) { - return false; + // check both "v1.0.0" and "1.0.0" directories for backward compatibility + const candidates = [normalized, stripped]; + + for (const candidate of candidates) { + const versionDir = path.join( + docsDir, + CONSTANTS.DOCS_SDK_REF_PATH, + sdkKey, + candidate + ); + + if (await fs.pathExists(versionDir)) { + const files = await fs.readdir(versionDir); + if (files.some((f) => f.endsWith(CONSTANTS.MDX_EXTENSION))) { + return true; + } + } } - const files = await fs.readdir(versionDir); - return files.some((f) => f.endsWith(CONSTANTS.MDX_EXTENSION)); + return false; } - diff --git a/sdk-reference-generator/src/navigation.ts b/sdk-reference-generator/src/navigation.ts index 0a2145b..a04ac66 100644 --- a/sdk-reference-generator/src/navigation.ts +++ b/sdk-reference-generator/src/navigation.ts @@ -103,16 +103,14 @@ export async function mergeNavigation( const docsJsonPath = path.join(docsDir, "docs.json"); if (!(await fs.pathExists(docsJsonPath))) { - log.error("docs.json not found"); - process.exit(1); + throw new Error("docs.json not found"); } const docsJson = await fs.readJSON(docsJsonPath); const anchors = docsJson.navigation?.anchors; if (!anchors) { - log.error("No anchors found in docs.json"); - process.exit(1); + throw new Error("No anchors found in docs.json"); } const validDropdowns = navigation.filter( From 5748e311f73fb77246166358b7c2b499bc29c941 Mon Sep 17 00:00:00 2001 From: ben-fornefeld Date: Mon, 12 Jan 2026 14:12:20 +0100 Subject: [PATCH 32/39] add: tests --- .../src/__tests__/files-processing.test.ts | 366 ++++++++++++++++ .../src/__tests__/generator-failures.test.ts | 366 ++++++++++++++++ .../src/__tests__/navigation.test.ts | 413 ++++++++++++++++++ .../src/__tests__/utils.test.ts | 190 ++++++++ sdk-reference-generator/src/generator.ts | 2 +- 5 files changed, 1336 insertions(+), 1 deletion(-) create mode 100644 sdk-reference-generator/src/__tests__/files-processing.test.ts create mode 100644 sdk-reference-generator/src/__tests__/generator-failures.test.ts create mode 100644 sdk-reference-generator/src/__tests__/navigation.test.ts create mode 100644 sdk-reference-generator/src/__tests__/utils.test.ts diff --git a/sdk-reference-generator/src/__tests__/files-processing.test.ts b/sdk-reference-generator/src/__tests__/files-processing.test.ts new file mode 100644 index 0000000..408e6e4 --- /dev/null +++ b/sdk-reference-generator/src/__tests__/files-processing.test.ts @@ -0,0 +1,366 @@ +import { describe, it, expect, beforeEach, afterEach } from "vitest"; +import fs from "fs-extra"; +import path from "path"; +import os from "os"; +import { flattenMarkdown, copyToDocs, locateSDKDir } from "../lib/files.js"; +import { CONSTANTS } from "../lib/constants.js"; + +describe("flattenMarkdown", () => { + let tempDir: string; + + beforeEach(async () => { + tempDir = await fs.mkdtemp(path.join(os.tmpdir(), "flatten-test-")); + }); + + afterEach(async () => { + await fs.remove(tempDir); + }); + + describe("removeUnwantedFiles", () => { + it("removes README.md, index.md, and index.mdx", async () => { + await fs.writeFile(path.join(tempDir, "README.md"), "# Readme"); + await fs.writeFile(path.join(tempDir, "index.md"), "# Index"); + await fs.writeFile(path.join(tempDir, "index.mdx"), "# Index MDX"); + await fs.writeFile(path.join(tempDir, "Sandbox.md"), "# Keep this"); + + await flattenMarkdown(tempDir); + + expect(await fs.pathExists(path.join(tempDir, "README.md"))).toBe(false); + expect(await fs.pathExists(path.join(tempDir, "index.md"))).toBe(false); + expect(await fs.pathExists(path.join(tempDir, "index.mdx"))).toBe(false); + expect(await fs.pathExists(path.join(tempDir, "Sandbox.mdx"))).toBe(true); + }); + }); + + describe("flattenNestedFiles", () => { + it("flattens nested md files to top level", async () => { + const nestedDir = path.join(tempDir, "modules", "sandbox"); + await fs.ensureDir(nestedDir); + await fs.writeFile(path.join(nestedDir, "Sandbox.md"), "# Sandbox"); + + await flattenMarkdown(tempDir); + + // nested file should be flattened with path prefix + expect( + await fs.pathExists( + path.join(tempDir, "modules-sandbox-Sandbox.mdx") + ) + ).toBe(true); + // original nested directory should be removed + expect(await fs.pathExists(nestedDir)).toBe(false); + }); + + it("renames page.md to parent directory name", async () => { + const nestedDir = path.join(tempDir, "sandbox"); + await fs.ensureDir(nestedDir); + await fs.writeFile(path.join(nestedDir, "page.md"), "# Page content"); + + await flattenMarkdown(tempDir); + + expect(await fs.pathExists(path.join(tempDir, "sandbox.mdx"))).toBe(true); + }); + + it("renames index.md in nested dirs to parent directory name", async () => { + const nestedDir = path.join(tempDir, "filesystem"); + await fs.ensureDir(nestedDir); + await fs.writeFile( + path.join(nestedDir, "index.md"), + "# Filesystem index" + ); + + await flattenMarkdown(tempDir); + + expect(await fs.pathExists(path.join(tempDir, "filesystem.mdx"))).toBe( + true + ); + }); + + it("handles deeply nested files", async () => { + const deepDir = path.join(tempDir, "a", "b", "c"); + await fs.ensureDir(deepDir); + await fs.writeFile(path.join(deepDir, "Deep.md"), "# Deep file"); + + await flattenMarkdown(tempDir); + + expect(await fs.pathExists(path.join(tempDir, "a-b-c-Deep.mdx"))).toBe( + true + ); + }); + }); + + describe("convertMdToMdx", () => { + it("converts .md files to .mdx with frontmatter", async () => { + await fs.writeFile(path.join(tempDir, "Test.md"), "# Test content"); + + await flattenMarkdown(tempDir); + + const mdxPath = path.join(tempDir, "Test.mdx"); + expect(await fs.pathExists(mdxPath)).toBe(true); + expect(await fs.pathExists(path.join(tempDir, "Test.md"))).toBe(false); + + const content = await fs.readFile(mdxPath, "utf-8"); + expect(content).toContain("---"); + expect(content).toContain('sidebarTitle: "Test"'); + expect(content).toContain("# Test content"); + }); + + it("generates correct title from snake_case filenames", async () => { + await fs.writeFile( + path.join(tempDir, "sandbox_sync.md"), + "# Content" + ); + + await flattenMarkdown(tempDir); + + const content = await fs.readFile( + path.join(tempDir, "sandbox_sync.mdx"), + "utf-8" + ); + expect(content).toContain('sidebarTitle: "Sandbox Sync"'); + }); + }); + + describe("ensureFrontmatter", () => { + it("adds frontmatter to mdx files without it", async () => { + // create mdx file without frontmatter + await fs.writeFile( + path.join(tempDir, "NeedsFrontmatter.mdx"), + "# No frontmatter" + ); + + await flattenMarkdown(tempDir); + + const content = await fs.readFile( + path.join(tempDir, "NeedsFrontmatter.mdx"), + "utf-8" + ); + expect(content.startsWith("---")).toBe(true); + expect(content).toContain('sidebarTitle: "NeedsFrontmatter"'); + }); + + it("does not duplicate frontmatter if already present", async () => { + const existingFrontmatter = `--- +sidebarTitle: "Existing" +--- + +# Content`; + await fs.writeFile( + path.join(tempDir, "HasFrontmatter.mdx"), + existingFrontmatter + ); + + await flattenMarkdown(tempDir); + + const content = await fs.readFile( + path.join(tempDir, "HasFrontmatter.mdx"), + "utf-8" + ); + // should still have exactly one frontmatter block + const frontmatterCount = (content.match(/---/g) || []).length; + expect(frontmatterCount).toBe(2); // opening and closing --- + expect(content).toContain('sidebarTitle: "Existing"'); + }); + }); + + describe("full workflow", () => { + it("processes complex directory structure correctly", async () => { + // create complex structure + await fs.writeFile(path.join(tempDir, "README.md"), "# Remove me"); + await fs.writeFile(path.join(tempDir, "TopLevel.md"), "# Top level"); + + const modulesDir = path.join(tempDir, "modules"); + await fs.ensureDir(modulesDir); + await fs.writeFile(path.join(modulesDir, "page.md"), "# Modules page"); + await fs.writeFile(path.join(modulesDir, "Helper.md"), "# Helper"); + + const sandboxDir = path.join(modulesDir, "sandbox"); + await fs.ensureDir(sandboxDir); + await fs.writeFile(path.join(sandboxDir, "Sandbox.md"), "# Sandbox class"); + + await flattenMarkdown(tempDir); + + // check results + expect(await fs.pathExists(path.join(tempDir, "README.md"))).toBe(false); + expect(await fs.pathExists(path.join(tempDir, "TopLevel.mdx"))).toBe(true); + expect(await fs.pathExists(path.join(tempDir, "modules.mdx"))).toBe(true); + expect(await fs.pathExists(path.join(tempDir, "modules-Helper.mdx"))).toBe( + true + ); + expect( + await fs.pathExists(path.join(tempDir, "modules-sandbox-Sandbox.mdx")) + ).toBe(true); + + // verify all have frontmatter + const files = await fs.readdir(tempDir); + for (const file of files) { + if (file.endsWith(".mdx")) { + const content = await fs.readFile(path.join(tempDir, file), "utf-8"); + expect(content.startsWith("---")).toBe(true); + } + } + + // verify directories are removed + expect(await fs.pathExists(modulesDir)).toBe(false); + }); + }); +}); + +describe("locateSDKDir", () => { + let tempDir: string; + + beforeEach(async () => { + tempDir = await fs.mkdtemp(path.join(os.tmpdir(), "locate-sdk-test-")); + }); + + afterEach(async () => { + await fs.remove(tempDir); + }); + + it("returns sdkPath when it exists", async () => { + const sdkDir = path.join(tempDir, "packages", "sdk"); + await fs.ensureDir(sdkDir); + + const result = await locateSDKDir(tempDir, "packages/sdk"); + + expect(result).toBe(sdkDir); + }); + + it("returns null when sdkPath does not exist", async () => { + const result = await locateSDKDir(tempDir, "nonexistent/path"); + + expect(result).toBeNull(); + }); + + it("returns first existing path from sdkPaths array", async () => { + const secondPath = path.join(tempDir, "js"); + await fs.ensureDir(secondPath); + + const result = await locateSDKDir(tempDir, undefined, [ + "python", + "js", + "go", + ]); + + expect(result).toBe(secondPath); + }); + + it("returns null when no sdkPaths exist", async () => { + const result = await locateSDKDir(tempDir, undefined, [ + "nonexistent1", + "nonexistent2", + ]); + + expect(result).toBeNull(); + }); + + it("returns repoDir when no paths specified", async () => { + const result = await locateSDKDir(tempDir); + + expect(result).toBe(tempDir); + }); + + it("sdkPath takes priority over sdkPaths", async () => { + const sdkPathDir = path.join(tempDir, "primary"); + const sdkPathsDir = path.join(tempDir, "fallback"); + await fs.ensureDir(sdkPathDir); + await fs.ensureDir(sdkPathsDir); + + const result = await locateSDKDir(tempDir, "primary", ["fallback"]); + + expect(result).toBe(sdkPathDir); + }); +}); + +describe("copyToDocs", () => { + let srcDir: string; + let destDir: string; + + beforeEach(async () => { + srcDir = await fs.mkdtemp(path.join(os.tmpdir(), "copy-src-")); + destDir = await fs.mkdtemp(path.join(os.tmpdir(), "copy-dest-")); + }); + + afterEach(async () => { + await fs.remove(srcDir); + await fs.remove(destDir); + }); + + it("copies non-empty mdx files to destination", async () => { + await fs.writeFile( + path.join(srcDir, "Test.mdx"), + '---\nsidebarTitle: "Test"\n---\n\n# Content' + ); + await fs.writeFile( + path.join(srcDir, "Another.mdx"), + '---\nsidebarTitle: "Another"\n---\n\n# More' + ); + + const result = await copyToDocs(srcDir, destDir, "SDK", "v1.0.0"); + + expect(result).toBe(true); + expect(await fs.pathExists(path.join(destDir, "Test.mdx"))).toBe(true); + expect(await fs.pathExists(path.join(destDir, "Another.mdx"))).toBe(true); + }); + + it("returns false when no mdx files exist", async () => { + // srcDir is empty + + const result = await copyToDocs(srcDir, destDir, "SDK", "v1.0.0"); + + expect(result).toBe(false); + }); + + it("skips empty mdx files", async () => { + await fs.writeFile(path.join(srcDir, "Empty.mdx"), ""); + await fs.writeFile( + path.join(srcDir, "Valid.mdx"), + '---\nsidebarTitle: "Valid"\n---\n\n# Content' + ); + + const result = await copyToDocs(srcDir, destDir, "SDK", "v1.0.0"); + + expect(result).toBe(true); + expect(await fs.pathExists(path.join(destDir, "Valid.mdx"))).toBe(true); + expect(await fs.pathExists(path.join(destDir, "Empty.mdx"))).toBe(false); + }); + + it("returns false when only empty mdx files exist", async () => { + await fs.writeFile(path.join(srcDir, "Empty1.mdx"), ""); + await fs.writeFile(path.join(srcDir, "Empty2.mdx"), ""); + + const result = await copyToDocs(srcDir, destDir, "SDK", "v1.0.0"); + + expect(result).toBe(false); + }); + + it("creates destination directory if it does not exist", async () => { + const newDest = path.join(destDir, "nested", "path"); + await fs.writeFile( + path.join(srcDir, "Test.mdx"), + '---\nsidebarTitle: "Test"\n---\n\n# Content' + ); + + const result = await copyToDocs(srcDir, newDest, "SDK", "v1.0.0"); + + expect(result).toBe(true); + expect(await fs.pathExists(newDest)).toBe(true); + expect(await fs.pathExists(path.join(newDest, "Test.mdx"))).toBe(true); + }); + + it("ignores non-mdx files", async () => { + await fs.writeFile(path.join(srcDir, "readme.txt"), "text file"); + await fs.writeFile(path.join(srcDir, "config.json"), "{}"); + await fs.writeFile( + path.join(srcDir, "Valid.mdx"), + '---\nsidebarTitle: "Valid"\n---\n\n# Content' + ); + + const result = await copyToDocs(srcDir, destDir, "SDK", "v1.0.0"); + + expect(result).toBe(true); + expect(await fs.pathExists(path.join(destDir, "Valid.mdx"))).toBe(true); + expect(await fs.pathExists(path.join(destDir, "readme.txt"))).toBe(false); + expect(await fs.pathExists(path.join(destDir, "config.json"))).toBe(false); + }); +}); + diff --git a/sdk-reference-generator/src/__tests__/generator-failures.test.ts b/sdk-reference-generator/src/__tests__/generator-failures.test.ts new file mode 100644 index 0000000..359a8ec --- /dev/null +++ b/sdk-reference-generator/src/__tests__/generator-failures.test.ts @@ -0,0 +1,366 @@ +import { describe, it, expect, vi, beforeEach, afterEach } from "vitest"; +import fs from "fs-extra"; +import path from "path"; +import os from "os"; +import type { SDKConfig, GenerationResult } from "../types.js"; +import { handleGenerationFailures } from "../generator.js"; +import { CONSTANTS } from "../lib/constants.js"; + +describe("handleGenerationFailures", () => { + // required SDK config + const requiredConfig: SDKConfig = { + displayName: "Required SDK", + icon: "square-js", + order: 1, + repo: "https://github.com/test/repo.git", + tagPattern: "test@", + tagFormat: "test@{version}", + generator: "typedoc", + required: true, + }; + + // optional SDK config + const optionalConfig: SDKConfig = { + displayName: "Optional SDK", + icon: "python", + order: 2, + repo: "https://github.com/test/repo.git", + tagPattern: "@test/python@", + tagFormat: "@test/python@{version}", + generator: "typedoc", + required: false, + }; + + describe("required SDK", () => { + it("throws error when any version fails", () => { + const result: GenerationResult = { + generated: 5, + failed: 1, + failedVersions: ["v1.0.0"], + }; + + expect(() => handleGenerationFailures(requiredConfig, result)).toThrow( + "Generation aborted: Required SDK has failures" + ); + }); + + it("throws error when all versions fail", () => { + const result: GenerationResult = { + generated: 0, + failed: 3, + failedVersions: ["v1.0.0", "v2.0.0", "v3.0.0"], + }; + + expect(() => handleGenerationFailures(requiredConfig, result)).toThrow( + "Generation aborted: Required SDK has failures" + ); + }); + + it("does not throw when no failures", () => { + const result: GenerationResult = { + generated: 3, + failed: 0, + failedVersions: [], + }; + + expect(() => + handleGenerationFailures(requiredConfig, result) + ).not.toThrow(); + }); + }); + + describe("optional SDK", () => { + it("throws error when all versions fail (generated === 0)", () => { + const result: GenerationResult = { + generated: 0, + failed: 3, + failedVersions: ["v1.0.0", "v2.0.0", "v3.0.0"], + }; + + expect(() => handleGenerationFailures(optionalConfig, result)).toThrow( + "Generation aborted: All versions failed" + ); + }); + + it("does not throw when partial success (some generated)", () => { + const result: GenerationResult = { + generated: 2, + failed: 1, + failedVersions: ["v1.0.0"], + }; + + expect(() => + handleGenerationFailures(optionalConfig, result) + ).not.toThrow(); + }); + + it("does not throw when no failures", () => { + const result: GenerationResult = { + generated: 3, + failed: 0, + failedVersions: [], + }; + + expect(() => + handleGenerationFailures(optionalConfig, result) + ).not.toThrow(); + }); + }); + + describe("edge cases", () => { + it("does not throw for zero generated and zero failed", () => { + const result: GenerationResult = { + generated: 0, + failed: 0, + failedVersions: [], + }; + + // no failures means nothing to abort + expect(() => + handleGenerationFailures(optionalConfig, result) + ).not.toThrow(); + expect(() => + handleGenerationFailures(requiredConfig, result) + ).not.toThrow(); + }); + }); +}); + +describe("version discovery integration", () => { + let tempDir: string; + + // mock the config and git modules + vi.mock("../../sdks.config.js", () => ({ + default: { + "test-sdk": { + displayName: "Test SDK", + icon: "square-js", + order: 1, + repo: "https://github.com/test/repo.git", + tagPattern: "test@", + tagFormat: "test@{version}", + generator: "typedoc", + required: true, + minVersion: "1.0.0", + }, + "optional-sdk": { + displayName: "Optional SDK", + icon: "python", + order: 2, + repo: "https://github.com/test/optional.git", + tagPattern: "@optional@", + tagFormat: "@optional@{version}", + generator: "typedoc", + required: false, + }, + }, + })); + + beforeEach(async () => { + tempDir = await fs.mkdtemp(path.join(os.tmpdir(), "gen-test-")); + }); + + afterEach(async () => { + await fs.remove(tempDir); + vi.restoreAllMocks(); + }); + + describe("generateSDK with unknown SDK", () => { + it("returns failure result for unknown SDK key", async () => { + const { generateSDK } = await import("../generator.js"); + + const result = await generateSDK("unknown-sdk", "v1.0.0", { + tempDir, + docsDir: tempDir, + configsDir: tempDir, + }); + + expect(result.generated).toBe(0); + expect(result.failed).toBe(1); + expect(result.failedVersions).toContain("unknown-sdk"); + }); + }); +}); + +describe("versionExists", () => { + let tempDir: string; + + beforeEach(async () => { + tempDir = await fs.mkdtemp(path.join(os.tmpdir(), "version-exists-test-")); + }); + + afterEach(async () => { + await fs.remove(tempDir); + }); + + it("returns true for existing version with mdx files", async () => { + const { versionExists } = await import("../lib/versions.js"); + + const versionDir = path.join( + tempDir, + CONSTANTS.DOCS_SDK_REF_PATH, + "test-sdk", + "v1.0.0" + ); + await fs.ensureDir(versionDir); + await fs.writeFile(path.join(versionDir, "Test.mdx"), "# Content"); + + const result = await versionExists("test-sdk", "v1.0.0", tempDir); + + expect(result).toBe(true); + }); + + it("returns true for version without v prefix", async () => { + const { versionExists } = await import("../lib/versions.js"); + + // create directory without "v" prefix + const versionDir = path.join( + tempDir, + CONSTANTS.DOCS_SDK_REF_PATH, + "test-sdk", + "1.0.0" + ); + await fs.ensureDir(versionDir); + await fs.writeFile(path.join(versionDir, "Test.mdx"), "# Content"); + + // query with "v" prefix + const result = await versionExists("test-sdk", "v1.0.0", tempDir); + + expect(result).toBe(true); + }); + + it("returns false for non-existing version", async () => { + const { versionExists } = await import("../lib/versions.js"); + + const result = await versionExists("test-sdk", "v99.0.0", tempDir); + + expect(result).toBe(false); + }); + + it("returns false for version directory without mdx files", async () => { + const { versionExists } = await import("../lib/versions.js"); + + const versionDir = path.join( + tempDir, + CONSTANTS.DOCS_SDK_REF_PATH, + "test-sdk", + "v1.0.0" + ); + await fs.ensureDir(versionDir); + // no mdx files, only other files + await fs.writeFile(path.join(versionDir, "readme.txt"), "text"); + + const result = await versionExists("test-sdk", "v1.0.0", tempDir); + + expect(result).toBe(false); + }); +}); + +describe("fetchLocalVersions", () => { + let tempDir: string; + + beforeEach(async () => { + tempDir = await fs.mkdtemp(path.join(os.tmpdir(), "local-versions-test-")); + }); + + afterEach(async () => { + await fs.remove(tempDir); + }); + + it("returns empty array when SDK directory does not exist", async () => { + const { fetchLocalVersions } = await import("../lib/versions.js"); + + const result = await fetchLocalVersions("nonexistent-sdk", tempDir); + + expect(result).toEqual([]); + }); + + it("returns versions sorted descending", async () => { + const { fetchLocalVersions } = await import("../lib/versions.js"); + + const sdkDir = path.join( + tempDir, + CONSTANTS.DOCS_SDK_REF_PATH, + "test-sdk" + ); + + // create versions in random order + for (const version of ["v1.0.0", "v2.0.0", "v1.5.0"]) { + const versionDir = path.join(sdkDir, version); + await fs.ensureDir(versionDir); + await fs.writeFile(path.join(versionDir, "Test.mdx"), "# Content"); + } + + const result = await fetchLocalVersions("test-sdk", tempDir); + + expect(result).toEqual(["v2.0.0", "v1.5.0", "v1.0.0"]); + }); + + it("normalizes versions without v prefix", async () => { + const { fetchLocalVersions } = await import("../lib/versions.js"); + + const sdkDir = path.join( + tempDir, + CONSTANTS.DOCS_SDK_REF_PATH, + "test-sdk" + ); + + // create version without "v" prefix + const versionDir = path.join(sdkDir, "1.0.0"); + await fs.ensureDir(versionDir); + await fs.writeFile(path.join(versionDir, "Test.mdx"), "# Content"); + + const result = await fetchLocalVersions("test-sdk", tempDir); + + expect(result).toEqual(["v1.0.0"]); + }); + + it("ignores non-version directories", async () => { + const { fetchLocalVersions } = await import("../lib/versions.js"); + + const sdkDir = path.join( + tempDir, + CONSTANTS.DOCS_SDK_REF_PATH, + "test-sdk" + ); + + // valid version + const validDir = path.join(sdkDir, "v1.0.0"); + await fs.ensureDir(validDir); + await fs.writeFile(path.join(validDir, "Test.mdx"), "# Content"); + + // invalid versions + await fs.ensureDir(path.join(sdkDir, "main")); + await fs.writeFile(path.join(sdkDir, "main", "Test.mdx"), "# Content"); + await fs.ensureDir(path.join(sdkDir, "latest")); + + const result = await fetchLocalVersions("test-sdk", tempDir); + + expect(result).toEqual(["v1.0.0"]); + }); + + it("ignores version directories without mdx files", async () => { + const { fetchLocalVersions } = await import("../lib/versions.js"); + + const sdkDir = path.join( + tempDir, + CONSTANTS.DOCS_SDK_REF_PATH, + "test-sdk" + ); + + // version with mdx files + const withMdx = path.join(sdkDir, "v2.0.0"); + await fs.ensureDir(withMdx); + await fs.writeFile(path.join(withMdx, "Test.mdx"), "# Content"); + + // version without mdx files + const withoutMdx = path.join(sdkDir, "v1.0.0"); + await fs.ensureDir(withoutMdx); + await fs.writeFile(path.join(withoutMdx, "readme.txt"), "text"); + + const result = await fetchLocalVersions("test-sdk", tempDir); + + expect(result).toEqual(["v2.0.0"]); + }); +}); + diff --git a/sdk-reference-generator/src/__tests__/navigation.test.ts b/sdk-reference-generator/src/__tests__/navigation.test.ts new file mode 100644 index 0000000..9a2a58d --- /dev/null +++ b/sdk-reference-generator/src/__tests__/navigation.test.ts @@ -0,0 +1,413 @@ +import { describe, it, expect, beforeEach, afterEach, vi } from "vitest"; +import fs from "fs-extra"; +import path from "path"; +import os from "os"; +import { CONSTANTS } from "../lib/constants.js"; + +// mock the sdks config before importing navigation +vi.mock("../../sdks.config.js", () => ({ + default: { + "test-js-sdk": { + displayName: "Test SDK (JavaScript)", + icon: "square-js", + order: 1, + repo: "https://github.com/test/repo.git", + tagPattern: "test@", + tagFormat: "test@{version}", + generator: "typedoc", + required: true, + }, + "test-py-sdk": { + displayName: "Test SDK (Python)", + icon: "python", + order: 2, + repo: "https://github.com/test/repo.git", + tagPattern: "@test/python@", + tagFormat: "@test/python@{version}", + generator: "pydoc", + required: false, + }, + }, +})); + +// import after mocking +const { buildNavigation, mergeNavigation } = await import("../navigation.js"); + +describe("buildNavigation", () => { + let tempDir: string; + let sdkRefDir: string; + + beforeEach(async () => { + tempDir = await fs.mkdtemp(path.join(os.tmpdir(), "nav-test-")); + sdkRefDir = path.join(tempDir, CONSTANTS.DOCS_SDK_REF_PATH); + }); + + afterEach(async () => { + await fs.remove(tempDir); + }); + + it("returns empty array when sdk-reference directory does not exist", async () => { + const result = await buildNavigation(tempDir); + + expect(result).toEqual([]); + }); + + it("skips SDKs that have no directory", async () => { + await fs.ensureDir(sdkRefDir); + // don't create any SDK directories + + const result = await buildNavigation(tempDir); + + expect(result).toEqual([]); + }); + + it("skips SDKs with no valid versions", async () => { + const sdkDir = path.join(sdkRefDir, "test-js-sdk"); + await fs.ensureDir(sdkDir); + // create invalid version directories + await fs.ensureDir(path.join(sdkDir, "main")); + await fs.ensureDir(path.join(sdkDir, "latest")); + + const result = await buildNavigation(tempDir); + + expect(result).toEqual([]); + }); + + it("builds navigation for SDKs with valid versions", async () => { + const sdkDir = path.join(sdkRefDir, "test-js-sdk"); + const versionDir = path.join(sdkDir, "v1.0.0"); + await fs.ensureDir(versionDir); + await fs.writeFile( + path.join(versionDir, "Sandbox.mdx"), + '---\nsidebarTitle: "Sandbox"\n---\n\n# Content' + ); + + const result = await buildNavigation(tempDir); + + expect(result).toHaveLength(1); + expect(result[0].dropdown).toBe("Test SDK (JavaScript)"); + expect(result[0].icon).toBe("square-js"); + expect(result[0].versions).toHaveLength(1); + expect(result[0].versions[0].version).toBe("v1.0.0"); + expect(result[0].versions[0].default).toBe(true); + expect(result[0].versions[0].pages).toContain( + "docs/sdk-reference/test-js-sdk/v1.0.0/Sandbox" + ); + }); + + it("sorts versions descending (latest first)", async () => { + const sdkDir = path.join(sdkRefDir, "test-js-sdk"); + + // create multiple versions + for (const version of ["v1.0.0", "v2.0.0", "v1.5.0"]) { + const versionDir = path.join(sdkDir, version); + await fs.ensureDir(versionDir); + await fs.writeFile( + path.join(versionDir, "Test.mdx"), + '---\nsidebarTitle: "Test"\n---\n\n# Content' + ); + } + + const result = await buildNavigation(tempDir); + + expect(result[0].versions[0].version).toBe("v2.0.0"); + expect(result[0].versions[1].version).toBe("v1.5.0"); + expect(result[0].versions[2].version).toBe("v1.0.0"); + }); + + it("marks first version as default", async () => { + const sdkDir = path.join(sdkRefDir, "test-js-sdk"); + + for (const version of ["v1.0.0", "v2.0.0"]) { + const versionDir = path.join(sdkDir, version); + await fs.ensureDir(versionDir); + await fs.writeFile(path.join(versionDir, "Test.mdx"), "# Content"); + } + + const result = await buildNavigation(tempDir); + + expect(result[0].versions[0].default).toBe(true); + expect(result[0].versions[1].default).toBe(false); + }); + + it("normalizes versions without v prefix", async () => { + const sdkDir = path.join(sdkRefDir, "test-js-sdk"); + const versionDir = path.join(sdkDir, "1.0.0"); // no "v" prefix + await fs.ensureDir(versionDir); + await fs.writeFile(path.join(versionDir, "Test.mdx"), "# Content"); + + const result = await buildNavigation(tempDir); + + expect(result[0].versions[0].version).toBe("v1.0.0"); + }); + + it("sorts SDKs by order from config", async () => { + // create both SDKs + for (const sdk of ["test-js-sdk", "test-py-sdk"]) { + const versionDir = path.join(sdkRefDir, sdk, "v1.0.0"); + await fs.ensureDir(versionDir); + await fs.writeFile(path.join(versionDir, "Test.mdx"), "# Content"); + } + + const result = await buildNavigation(tempDir); + + expect(result).toHaveLength(2); + expect(result[0].dropdown).toBe("Test SDK (JavaScript)"); // order: 1 + expect(result[1].dropdown).toBe("Test SDK (Python)"); // order: 2 + }); + + it("builds correct page paths with multiple modules", async () => { + const versionDir = path.join(sdkRefDir, "test-js-sdk", "v1.0.0"); + await fs.ensureDir(versionDir); + await fs.writeFile(path.join(versionDir, "Sandbox.mdx"), "# Sandbox"); + await fs.writeFile(path.join(versionDir, "Filesystem.mdx"), "# Filesystem"); + await fs.writeFile(path.join(versionDir, "Commands.mdx"), "# Commands"); + + const result = await buildNavigation(tempDir); + + const pages = result[0].versions[0].pages; + expect(pages).toHaveLength(3); + // pages should be sorted alphabetically + expect(pages[0]).toBe("docs/sdk-reference/test-js-sdk/v1.0.0/Commands"); + expect(pages[1]).toBe("docs/sdk-reference/test-js-sdk/v1.0.0/Filesystem"); + expect(pages[2]).toBe("docs/sdk-reference/test-js-sdk/v1.0.0/Sandbox"); + }); + + it("ignores non-mdx files in version directories", async () => { + const versionDir = path.join(sdkRefDir, "test-js-sdk", "v1.0.0"); + await fs.ensureDir(versionDir); + await fs.writeFile(path.join(versionDir, "Valid.mdx"), "# Valid"); + await fs.writeFile(path.join(versionDir, "readme.md"), "# Readme"); + await fs.writeFile(path.join(versionDir, "config.json"), "{}"); + + const result = await buildNavigation(tempDir); + + expect(result[0].versions[0].pages).toHaveLength(1); + expect(result[0].versions[0].pages[0]).toContain("Valid"); + }); + + it("filters out invalid version directories", async () => { + const sdkDir = path.join(sdkRefDir, "test-js-sdk"); + + // valid versions + await fs.ensureDir(path.join(sdkDir, "v1.0.0")); + await fs.writeFile(path.join(sdkDir, "v1.0.0", "Test.mdx"), "# Content"); + + // invalid versions + await fs.ensureDir(path.join(sdkDir, "main")); + await fs.writeFile(path.join(sdkDir, "main", "Test.mdx"), "# Content"); + await fs.ensureDir(path.join(sdkDir, "latest")); + await fs.writeFile(path.join(sdkDir, "latest", "Test.mdx"), "# Content"); + + const result = await buildNavigation(tempDir); + + expect(result[0].versions).toHaveLength(1); + expect(result[0].versions[0].version).toBe("v1.0.0"); + }); +}); + +describe("mergeNavigation", () => { + let tempDir: string; + let docsJsonPath: string; + + beforeEach(async () => { + tempDir = await fs.mkdtemp(path.join(os.tmpdir(), "merge-nav-test-")); + docsJsonPath = path.join(tempDir, "docs.json"); + }); + + afterEach(async () => { + await fs.remove(tempDir); + }); + + it("throws when docs.json does not exist", async () => { + const navigation = [ + { + dropdown: "Test SDK", + icon: "square-js", + versions: [{ version: "v1.0.0", default: true, pages: ["test"] }], + }, + ]; + + await expect(mergeNavigation(navigation, tempDir)).rejects.toThrow( + "docs.json not found" + ); + }); + + it("throws when docs.json has no anchors", async () => { + await fs.writeJSON(docsJsonPath, { navigation: {} }); + + const navigation = [ + { + dropdown: "Test SDK", + icon: "square-js", + versions: [{ version: "v1.0.0", default: true, pages: ["test"] }], + }, + ]; + + await expect(mergeNavigation(navigation, tempDir)).rejects.toThrow( + "No anchors found" + ); + }); + + it("creates new SDK Reference anchor when missing", async () => { + await fs.writeJSON(docsJsonPath, { + navigation: { + anchors: [{ anchor: "Documentation", groups: [] }], + }, + }); + + const navigation = [ + { + dropdown: "Test SDK", + icon: "square-js", + versions: [{ version: "v1.0.0", default: true, pages: ["test/page"] }], + }, + ]; + + await mergeNavigation(navigation, tempDir); + + const result = await fs.readJSON(docsJsonPath); + expect(result.navigation.anchors).toHaveLength(2); + expect(result.navigation.anchors[1].anchor).toBe("SDK Reference"); + expect(result.navigation.anchors[1].dropdowns).toHaveLength(1); + }); + + it("updates existing SDK Reference anchor", async () => { + await fs.writeJSON(docsJsonPath, { + navigation: { + anchors: [ + { anchor: "Documentation", groups: [] }, + { anchor: "SDK Reference", icon: "brackets-curly", dropdowns: [] }, + ], + }, + }); + + const navigation = [ + { + dropdown: "Test SDK", + icon: "square-js", + versions: [{ version: "v1.0.0", default: true, pages: ["test/page"] }], + }, + ]; + + await mergeNavigation(navigation, tempDir); + + const result = await fs.readJSON(docsJsonPath); + expect(result.navigation.anchors).toHaveLength(2); + expect(result.navigation.anchors[1].dropdowns).toHaveLength(1); + expect(result.navigation.anchors[1].dropdowns[0].dropdown).toBe("Test SDK"); + }); + + it("preserves other anchors in docs.json", async () => { + await fs.writeJSON(docsJsonPath, { + navigation: { + anchors: [ + { anchor: "Documentation", groups: ["group1"] }, + { anchor: "API Reference", groups: ["group2"] }, + ], + }, + }); + + const navigation = [ + { + dropdown: "Test SDK", + icon: "square-js", + versions: [{ version: "v1.0.0", default: true, pages: ["test/page"] }], + }, + ]; + + await mergeNavigation(navigation, tempDir); + + const result = await fs.readJSON(docsJsonPath); + expect(result.navigation.anchors).toHaveLength(3); + expect(result.navigation.anchors[0].anchor).toBe("Documentation"); + expect(result.navigation.anchors[0].groups).toEqual(["group1"]); + expect(result.navigation.anchors[1].anchor).toBe("API Reference"); + }); + + it("filters out SDKs with empty versions", async () => { + await fs.writeJSON(docsJsonPath, { + navigation: { anchors: [] }, + }); + + const navigation = [ + { + dropdown: "Valid SDK", + icon: "square-js", + versions: [{ version: "v1.0.0", default: true, pages: ["page"] }], + }, + { + dropdown: "Empty SDK", + icon: "python", + versions: [], + }, + ]; + + await mergeNavigation(navigation, tempDir); + + const result = await fs.readJSON(docsJsonPath); + const sdkRefAnchor = result.navigation.anchors.find( + (a: { anchor: string }) => a.anchor === "SDK Reference" + ); + expect(sdkRefAnchor.dropdowns).toHaveLength(1); + expect(sdkRefAnchor.dropdowns[0].dropdown).toBe("Valid SDK"); + }); + + it("does not modify docs.json when no valid SDK versions exist", async () => { + const originalContent = { + navigation: { + anchors: [{ anchor: "Documentation", groups: [] }], + }, + }; + await fs.writeJSON(docsJsonPath, originalContent); + + const navigation = [ + { dropdown: "Empty SDK", icon: "square-js", versions: [] }, + ]; + + await mergeNavigation(navigation, tempDir); + + const result = await fs.readJSON(docsJsonPath); + expect(result).toEqual(originalContent); + }); + + it("writes JSON with proper formatting (2 spaces)", async () => { + await fs.writeJSON(docsJsonPath, { + navigation: { anchors: [] }, + }); + + const navigation = [ + { + dropdown: "Test SDK", + icon: "square-js", + versions: [{ version: "v1.0.0", default: true, pages: ["page"] }], + }, + ]; + + await mergeNavigation(navigation, tempDir); + + const content = await fs.readFile(docsJsonPath, "utf-8"); + // check for 2-space indentation + expect(content).toContain(' "navigation"'); + }); + + it("ensures newline at end of file", async () => { + await fs.writeJSON(docsJsonPath, { + navigation: { anchors: [] }, + }); + + const navigation = [ + { + dropdown: "Test SDK", + icon: "square-js", + versions: [{ version: "v1.0.0", default: true, pages: ["page"] }], + }, + ]; + + await mergeNavigation(navigation, tempDir); + + const content = await fs.readFile(docsJsonPath, "utf-8"); + expect(content.endsWith("\n")).toBe(true); + }); +}); + diff --git a/sdk-reference-generator/src/__tests__/utils.test.ts b/sdk-reference-generator/src/__tests__/utils.test.ts new file mode 100644 index 0000000..63ec626 --- /dev/null +++ b/sdk-reference-generator/src/__tests__/utils.test.ts @@ -0,0 +1,190 @@ +import { describe, it, expect } from "vitest"; +import path from "path"; +import { + normalizeVersion, + stripVersionPrefix, + isValidVersion, + sortVersionsDescending, + createFrontmatter, + buildSDKPath, +} from "../lib/utils.js"; +import { CONSTANTS } from "../lib/constants.js"; + +describe("normalizeVersion", () => { + it("adds v prefix when missing", () => { + expect(normalizeVersion("1.0.0")).toBe("v1.0.0"); + expect(normalizeVersion("2.5.3")).toBe("v2.5.3"); + expect(normalizeVersion("10.20.30")).toBe("v10.20.30"); + }); + + it("keeps v prefix when already present", () => { + expect(normalizeVersion("v1.0.0")).toBe("v1.0.0"); + expect(normalizeVersion("v2.5.3")).toBe("v2.5.3"); + }); + + it("handles prerelease versions", () => { + expect(normalizeVersion("1.0.0-beta.1")).toBe("v1.0.0-beta.1"); + expect(normalizeVersion("v1.0.0-rc.2")).toBe("v1.0.0-rc.2"); + }); +}); + +describe("stripVersionPrefix", () => { + it("removes v prefix when present", () => { + expect(stripVersionPrefix("v1.0.0")).toBe("1.0.0"); + expect(stripVersionPrefix("v2.5.3")).toBe("2.5.3"); + }); + + it("keeps version unchanged when no v prefix", () => { + expect(stripVersionPrefix("1.0.0")).toBe("1.0.0"); + expect(stripVersionPrefix("10.20.30")).toBe("10.20.30"); + }); + + it("only removes leading v", () => { + expect(stripVersionPrefix("vvv1.0.0")).toBe("vv1.0.0"); + expect(stripVersionPrefix("1.0.0-v2")).toBe("1.0.0-v2"); + }); +}); + +describe("isValidVersion", () => { + it("accepts valid semver versions", () => { + expect(isValidVersion("1.0.0")).toBe(true); + expect(isValidVersion("v1.0.0")).toBe(true); + expect(isValidVersion("v2.9.0")).toBe(true); + expect(isValidVersion("10.20.30")).toBe(true); + expect(isValidVersion("v0.0.1")).toBe(true); + }); + + it("accepts versions with prerelease tags", () => { + expect(isValidVersion("1.0.0-beta")).toBe(true); + expect(isValidVersion("v2.0.0-rc.1")).toBe(true); + expect(isValidVersion("1.0.0-alpha.2.3")).toBe(true); + }); + + it("rejects non-semver strings", () => { + expect(isValidVersion("main")).toBe(false); + expect(isValidVersion("latest")).toBe(false); + expect(isValidVersion("develop")).toBe(false); + expect(isValidVersion("")).toBe(false); + }); + + it("rejects partial versions", () => { + expect(isValidVersion("1.0")).toBe(false); + expect(isValidVersion("1")).toBe(false); + expect(isValidVersion("v1")).toBe(false); + }); +}); + +describe("sortVersionsDescending", () => { + it("sorts versions from newest to oldest", () => { + const versions = ["v1.0.0", "v2.0.0", "v1.5.0"]; + const result = sortVersionsDescending(versions); + expect(result).toEqual(["v2.0.0", "v1.5.0", "v1.0.0"]); + }); + + it("handles versions without v prefix", () => { + const versions = ["1.0.0", "2.0.0", "1.5.0"]; + const result = sortVersionsDescending(versions); + expect(result).toEqual(["2.0.0", "1.5.0", "1.0.0"]); + }); + + it("handles mixed prefix versions", () => { + const versions = ["v1.0.0", "2.0.0", "v1.5.0"]; + const result = sortVersionsDescending(versions); + expect(result).toEqual(["2.0.0", "v1.5.0", "v1.0.0"]); + }); + + it("correctly sorts double-digit versions", () => { + const versions = ["v1.9.0", "v1.10.0", "v1.2.0"]; + const result = sortVersionsDescending(versions); + // semver sorts 1.10.0 > 1.9.0 > 1.2.0 + expect(result).toEqual(["v1.10.0", "v1.9.0", "v1.2.0"]); + }); + + it("handles empty array", () => { + expect(sortVersionsDescending([])).toEqual([]); + }); + + it("handles single version", () => { + expect(sortVersionsDescending(["v1.0.0"])).toEqual(["v1.0.0"]); + }); + + it("sorts prerelease versions correctly", () => { + const versions = ["v1.0.0", "v1.0.0-beta.1", "v1.0.0-alpha"]; + const result = sortVersionsDescending(versions); + // stable > beta > alpha + expect(result).toEqual(["v1.0.0", "v1.0.0-beta.1", "v1.0.0-alpha"]); + }); + + it("uses string comparison fallback for invalid semver", () => { + const versions = ["invalid", "also-invalid", "z-last"]; + const result = sortVersionsDescending(versions); + // lexicographic descending + expect(result).toEqual(["z-last", "invalid", "also-invalid"]); + }); +}); + +describe("createFrontmatter", () => { + it("creates frontmatter with title", () => { + const result = createFrontmatter("My Title"); + expect(result).toBe(`--- +sidebarTitle: "My Title" +--- + +`); + }); + + it("handles empty title", () => { + const result = createFrontmatter(""); + expect(result).toBe(`--- +sidebarTitle: "" +--- + +`); + }); + + it("handles titles with special characters", () => { + const result = createFrontmatter('Title "with" quotes'); + // the function doesn't escape - this is fine for most use cases + expect(result).toContain('sidebarTitle: "Title "with" quotes"'); + }); + + it("includes trailing newlines for content concatenation", () => { + const result = createFrontmatter("Test"); + // should end with double newline for clean content concatenation + expect(result.endsWith("\n\n")).toBe(true); + }); +}); + +describe("buildSDKPath", () => { + it("builds correct path with all components", () => { + const result = buildSDKPath("/docs", "js-sdk", "v1.0.0"); + expect(result).toBe( + path.join("/docs", CONSTANTS.DOCS_SDK_REF_PATH, "js-sdk", "v1.0.0") + ); + }); + + it("uses DOCS_SDK_REF_PATH constant", () => { + const result = buildSDKPath("/root", "test", "v2.0.0"); + expect(result).toContain("docs/sdk-reference"); + expect(result).toContain("test"); + expect(result).toContain("v2.0.0"); + }); + + it("handles nested docsDir paths", () => { + const result = buildSDKPath("/home/user/project/docs", "cli", "v3.0.0"); + expect(result).toBe( + path.join( + "/home/user/project/docs", + CONSTANTS.DOCS_SDK_REF_PATH, + "cli", + "v3.0.0" + ) + ); + }); + + it("handles SDK keys with hyphens", () => { + const result = buildSDKPath("/docs", "code-interpreter-js-sdk", "v1.0.0"); + expect(result).toContain("code-interpreter-js-sdk"); + }); +}); + diff --git a/sdk-reference-generator/src/generator.ts b/sdk-reference-generator/src/generator.ts index 1a3cc7f..9b1496a 100644 --- a/sdk-reference-generator/src/generator.ts +++ b/sdk-reference-generator/src/generator.ts @@ -243,7 +243,7 @@ async function processVersionBatch( return { generated, failed, failedVersions }; } -function handleGenerationFailures( +export function handleGenerationFailures( config: SDKConfig, result: GenerationResult ): void { From 9eb05fcff76ec5375828ac94cf7b08b9511eaa80 Mon Sep 17 00:00:00 2001 From: ben-fornefeld Date: Mon, 12 Jan 2026 15:38:00 +0100 Subject: [PATCH 33/39] feat: enhance SDK configuration with version-specific overrides and add versioning documentation --- sdk-reference-generator/VERSIONING.md | 159 +++++++++++++++ sdk-reference-generator/configs/typedoc.json | 35 ---- sdk-reference-generator/sdks.config.ts | 86 ++++++-- .../src/__tests__/config.test.ts | 187 ++++++++++++++++++ .../src/__tests__/generator-failures.test.ts | 12 ++ .../src/__tests__/sdks-config.test.ts | 138 +++++++++++++ .../src/__tests__/utils.test.ts | 1 - sdk-reference-generator/src/generator.ts | 27 ++- .../src/generators/pydoc.ts | 5 +- .../src/generators/typedoc.ts | 106 +++++----- sdk-reference-generator/src/lib/config.ts | 64 ++++++ sdk-reference-generator/src/types.ts | 18 +- 12 files changed, 727 insertions(+), 111 deletions(-) create mode 100644 sdk-reference-generator/VERSIONING.md delete mode 100644 sdk-reference-generator/configs/typedoc.json create mode 100644 sdk-reference-generator/src/__tests__/config.test.ts create mode 100644 sdk-reference-generator/src/__tests__/sdks-config.test.ts create mode 100644 sdk-reference-generator/src/lib/config.ts diff --git a/sdk-reference-generator/VERSIONING.md b/sdk-reference-generator/VERSIONING.md new file mode 100644 index 0000000..71755f3 --- /dev/null +++ b/sdk-reference-generator/VERSIONING.md @@ -0,0 +1,159 @@ +# SDK Versioning Documentation + +This document tracks the version-specific configuration changes for each SDK. + +## JavaScript SDK (js-sdk) + +### Verified Version History + +All version ranges have been verified by checking actual git tags and TypeDoc configurations. + +| Version Range | Entry Points | Notes | +|--------------|-------------|--------| +| `1.0.0` | sandbox/index.ts, filesystem/index.ts, process/index.ts, **pty.ts**, errors.ts | Used pty.ts instead of commands.ts | +| `>=1.1.0 <2.3.0` | sandbox/index.ts, filesystem/index.ts, process/index.ts, **commands/index.ts**, errors.ts | Standard sandbox APIs | +| `>=2.3.0` | + **template/index.ts**, **template/readycmd.ts**, **template/logger.ts** | Added template build support | + +### Configuration in sdks.config.ts + +```typescript +"js-sdk": { + defaultConfig: { + entryPoints: [ + // v2.3.0+ configuration (with template modules) + "src/sandbox/index.ts", + "src/sandbox/filesystem/index.ts", + "src/sandbox/process/index.ts", + "src/sandbox/commands/index.ts", + "src/errors.ts", + "src/template/index.ts", + "src/template/readycmd.ts", + "src/template/logger.ts", + ], + }, + configOverrides: { + "1.0.0": { + entryPoints: [/* pty.ts version */], + }, + ">=1.1.0 <2.3.0": { + entryPoints: [/* without template */], + }, + }, +} +``` + +## Python SDK (python-sdk) + +### Verified Version History + +All version ranges have been verified by checking actual git tags and package structure. + +| Version Range | Allowed Packages | Notes | +|--------------|-----------------|--------| +| `>=1.0.0 <2.1.0` | e2b.sandbox_sync, e2b.sandbox_async, e2b.exceptions | Basic sandbox APIs only | +| `>=2.1.0` | + e2b.template, e2b.template_sync, e2b.template_async, e2b.template.logger, e2b.template.readycmd | Template SDK added in v2.1.0 (PR #871) | + +### Configuration in sdks.config.ts + +```typescript +"python-sdk": { + defaultConfig: { + allowedPackages: [ + // v2.1.0+ configuration (with template modules) + "e2b.sandbox_sync", + "e2b.sandbox_async", + "e2b.exceptions", + "e2b.template", + "e2b.template_sync", + "e2b.template_async", + "e2b.template.logger", + "e2b.template.readycmd", + ], + }, + configOverrides: { + ">=1.0.0 <2.1.0": { + allowedPackages: [ + "e2b.sandbox_sync", + "e2b.sandbox_async", + "e2b.exceptions", + ], + }, + }, +} +``` + +## Code Interpreter SDKs + +### code-interpreter-js-sdk + +**Current Configuration**: Single entry point (`src/index.ts`) + +No version-specific overrides needed - the SDK has a simple, stable structure since v1.0.0. The code-interpreter is a focused wrapper around the base E2B SDK for code execution. + +### code-interpreter-python-sdk + +**Current Configuration**: Single package (`e2b_code_interpreter`) + +No version-specific overrides needed - the Python package structure has remained consistent. + +## Desktop SDKs + +### desktop-js-sdk & desktop-python-sdk + +**Current Configuration**: Simple defaults (`src/index.ts` and `e2b_desktop`) + +No version-specific overrides needed yet. These SDKs are relatively new and haven't had breaking structural changes requiring versioned configs. + +**Note**: If any of these SDKs introduce breaking changes in future versions (e.g., new modules, renamed packages), add appropriate `configOverrides` following the same pattern used for js-sdk and python-sdk. + +## Adding New Version Overrides + +When you discover that a specific version range needs different configuration: + +1. **Identify the version range** using semver syntax (e.g., `>=1.5.0 <2.0.0`) +2. **Add to configOverrides** with partial config (only override what changed) +3. **Add tests** in `src/__tests__/sdks-config.test.ts` +4. **Document here** with notes on what changed and why + +### Example: Adding a new override + +```typescript +configOverrides: { + ">=1.0.0 <1.5.0": { + // Old structure + }, + ">=1.5.0 <2.0.0": { + // New structure introduced in 1.5.0 + }, + ">=2.0.0": { + // Breaking changes in 2.0.0 + }, +} +``` + +## Resolution Logic + +The config resolution follows these rules: + +1. Start with `defaultConfig` +2. Find the **first matching** semver range in `configOverrides` +3. Shallow merge override into default (override wins) +4. Return merged config + +This means: +- `defaultConfig` should represent the **latest/current** structure +- `configOverrides` handles older versions or special cases +- Order matters when multiple ranges could match (first match wins) + +## Testing + +Tests in `src/__tests__/sdks-config.test.ts` verify: +- Correct packages/entry points for each version range +- Proper semver range matching +- Expected counts of items per version + +Run tests with: +```bash +pnpm test src/__tests__/sdks-config.test.ts +``` + diff --git a/sdk-reference-generator/configs/typedoc.json b/sdk-reference-generator/configs/typedoc.json deleted file mode 100644 index 29c1a4b..0000000 --- a/sdk-reference-generator/configs/typedoc.json +++ /dev/null @@ -1,35 +0,0 @@ -{ - "out": "sdk_ref", - "plugin": ["typedoc-plugin-markdown"], - "exclude": ["**/*.spec.ts"], - "entryPoints": [ - "src/sandbox/index.ts", - "src/sandbox/filesystem/index.ts", - "src/sandbox/process/index.ts", - "src/sandbox/commands/index.ts", - "src/errors.ts", - "src/template/index.ts", - "src/template/readycmd.ts", - "src/template/logger.ts" - ], - "excludeExternals": true, - "excludeInternal": true, - "excludePrivate": true, - "excludeProtected": true, - "navigation": { - "includeGroups": false, - "includeCategories": false - }, - "outputFileStrategy": "modules", - "readme": "none", - "disableSources": true, - "classPropertiesFormat": "table", - "typeDeclarationFormat": "table", - "enumMembersFormat": "table", - "parametersFormat": "table", - "expandParameters": true, - "useCodeBlocks": true, - "hidePageTitle": true, - "hideBreadcrumbs": true -} - diff --git a/sdk-reference-generator/sdks.config.ts b/sdk-reference-generator/sdks.config.ts index 28cc667..e2ed4d4 100644 --- a/sdk-reference-generator/sdks.config.ts +++ b/sdk-reference-generator/sdks.config.ts @@ -25,6 +25,41 @@ const sdks = { generator: "typedoc", required: true, minVersion: "1.0.0", + + defaultConfig: { + entryPoints: [ + "src/sandbox/index.ts", + "src/sandbox/filesystem/index.ts", + "src/sandbox/process/index.ts", + "src/sandbox/commands/index.ts", + "src/errors.ts", + "src/template/index.ts", + "src/template/readycmd.ts", + "src/template/logger.ts", + ], + }, + + configOverrides: { + "1.0.0": { + entryPoints: [ + "src/sandbox/index.ts", + "src/sandbox/filesystem/index.ts", + "src/sandbox/process/index.ts", + "src/sandbox/pty.ts", + "src/errors.ts", + ], + }, + + ">=1.1.0 <2.3.0": { + entryPoints: [ + "src/sandbox/index.ts", + "src/sandbox/filesystem/index.ts", + "src/sandbox/process/index.ts", + "src/sandbox/commands/index.ts", + "src/errors.ts", + ], + }, + }, }, "python-sdk": { @@ -38,16 +73,29 @@ const sdks = { generator: "pydoc", required: true, minVersion: "1.0.0", - allowedPackages: [ - "e2b.sandbox_sync", - "e2b.sandbox_async", - "e2b.exceptions", - "e2b.template", - "e2b.template_sync", - "e2b.template_async", - "e2b.template.logger", - "e2b.template.readycmd", - ], + + defaultConfig: { + allowedPackages: [ + "e2b.sandbox_sync", + "e2b.sandbox_async", + "e2b.exceptions", + "e2b.template", + "e2b.template_sync", + "e2b.template_async", + "e2b.template.logger", + "e2b.template.readycmd", + ], + }, + + configOverrides: { + ">=1.0.0 <2.1.0": { + allowedPackages: [ + "e2b.sandbox_sync", + "e2b.sandbox_async", + "e2b.exceptions", + ], + }, + }, }, "code-interpreter-js-sdk": { @@ -61,6 +109,10 @@ const sdks = { generator: "typedoc", required: false, minVersion: "1.0.0", + + defaultConfig: { + entryPoints: ["src/index.ts"], + }, }, "code-interpreter-python-sdk": { @@ -74,7 +126,10 @@ const sdks = { generator: "pydoc", required: false, minVersion: "1.0.0", - allowedPackages: ["e2b_code_interpreter"], + + defaultConfig: { + allowedPackages: ["e2b_code_interpreter"], + }, }, "desktop-js-sdk": { @@ -88,6 +143,10 @@ const sdks = { generator: "typedoc", required: false, minVersion: "1.0.0", + + defaultConfig: { + entryPoints: ["src/index.ts"], + }, }, "desktop-python-sdk": { @@ -101,7 +160,10 @@ const sdks = { generator: "pydoc", required: false, minVersion: "1.0.0", - allowedPackages: ["e2b_desktop"], + + defaultConfig: { + allowedPackages: ["e2b_desktop"], + }, }, } as const satisfies Record; diff --git a/sdk-reference-generator/src/__tests__/config.test.ts b/sdk-reference-generator/src/__tests__/config.test.ts new file mode 100644 index 0000000..66b5e9d --- /dev/null +++ b/sdk-reference-generator/src/__tests__/config.test.ts @@ -0,0 +1,187 @@ +import { describe, it, expect } from "vitest"; +import { resolveConfig, buildTypedocConfig, TYPEDOC_FORMATTING } from "../lib/config.js"; +import type { TypedocConfig, PydocConfig } from "../types.js"; + +describe("resolveConfig", () => { + describe("with TypedocConfig", () => { + const defaultConfig: TypedocConfig = { + entryPoints: ["src/index.ts"], + }; + + it("returns defaultConfig when no overrides", () => { + const result = resolveConfig(defaultConfig, undefined, "v1.0.0"); + expect(result).toEqual(defaultConfig); + }); + + it("returns defaultConfig when no matching range", () => { + const overrides = { + ">=2.0.0": { entryPoints: ["src/v2/index.ts"] }, + }; + const result = resolveConfig(defaultConfig, overrides, "v1.5.0"); + expect(result).toEqual(defaultConfig); + }); + + it("returns merged config when version matches range", () => { + const overrides = { + ">=1.0.0 <2.0.0": { entryPoints: ["src/v1/index.ts"] }, + }; + const result = resolveConfig(defaultConfig, overrides, "v1.5.0"); + expect(result).toEqual({ entryPoints: ["src/v1/index.ts"] }); + }); + + it("handles version with v prefix", () => { + const overrides = { + ">=1.0.0": { entryPoints: ["src/new/index.ts"] }, + }; + const result = resolveConfig(defaultConfig, overrides, "v1.2.3"); + expect(result).toEqual({ entryPoints: ["src/new/index.ts"] }); + }); + + it("handles version without v prefix", () => { + const overrides = { + ">=1.0.0": { entryPoints: ["src/new/index.ts"] }, + }; + const result = resolveConfig(defaultConfig, overrides, "1.2.3"); + expect(result).toEqual({ entryPoints: ["src/new/index.ts"] }); + }); + + it("uses first matching range when multiple match", () => { + const overrides = { + ">=1.0.0 <1.5.0": { entryPoints: ["src/v1-early/index.ts"] }, + ">=1.0.0": { entryPoints: ["src/v1/index.ts"] }, + }; + const result = resolveConfig(defaultConfig, overrides, "v1.2.0"); + expect(result).toEqual({ entryPoints: ["src/v1-early/index.ts"] }); + }); + + it("merges partial overrides with defaults", () => { + const configWithExclude: TypedocConfig = { + entryPoints: ["src/index.ts"], + exclude: ["**/*.test.ts"], + }; + const overrides = { + ">=1.0.0": { entryPoints: ["src/new/index.ts"] }, + }; + const result = resolveConfig(configWithExclude, overrides, "v1.0.0"); + expect(result).toEqual({ + entryPoints: ["src/new/index.ts"], + exclude: ["**/*.test.ts"], + }); + }); + }); + + describe("with PydocConfig", () => { + const defaultConfig: PydocConfig = { + allowedPackages: ["e2b"], + }; + + it("returns defaultConfig when no overrides", () => { + const result = resolveConfig(defaultConfig, undefined, "v1.0.0"); + expect(result).toEqual(defaultConfig); + }); + + it("returns merged config when version matches range", () => { + const overrides = { + ">=1.0.0": { allowedPackages: ["e2b.sandbox_sync", "e2b.sandbox_async"] as const }, + }; + const result = resolveConfig(defaultConfig, overrides, "v1.5.0"); + expect(result.allowedPackages).toEqual(["e2b.sandbox_sync", "e2b.sandbox_async"]); + }); + }); + + describe("semver range matching", () => { + const defaultConfig: TypedocConfig = { entryPoints: ["default.ts"] }; + + it("matches exact version", () => { + const overrides = { "1.0.0": { entryPoints: ["exact.ts"] } }; + const result = resolveConfig(defaultConfig, overrides, "v1.0.0"); + expect(result.entryPoints).toEqual(["exact.ts"]); + }); + + it("matches >= range", () => { + const overrides = { ">=1.0.0": { entryPoints: ["gte.ts"] } }; + expect(resolveConfig(defaultConfig, overrides, "v1.0.0").entryPoints).toEqual(["gte.ts"]); + expect(resolveConfig(defaultConfig, overrides, "v2.0.0").entryPoints).toEqual(["gte.ts"]); + expect(resolveConfig(defaultConfig, overrides, "v0.9.0").entryPoints).toEqual(["default.ts"]); + }); + + it("matches < range", () => { + const overrides = { "<2.0.0": { entryPoints: ["lt.ts"] } }; + expect(resolveConfig(defaultConfig, overrides, "v1.9.9").entryPoints).toEqual(["lt.ts"]); + expect(resolveConfig(defaultConfig, overrides, "v2.0.0").entryPoints).toEqual(["default.ts"]); + }); + + it("matches compound range", () => { + const overrides = { ">=1.0.0 <2.0.0": { entryPoints: ["compound.ts"] } }; + expect(resolveConfig(defaultConfig, overrides, "v1.0.0").entryPoints).toEqual(["compound.ts"]); + expect(resolveConfig(defaultConfig, overrides, "v1.9.9").entryPoints).toEqual(["compound.ts"]); + expect(resolveConfig(defaultConfig, overrides, "v0.9.9").entryPoints).toEqual(["default.ts"]); + expect(resolveConfig(defaultConfig, overrides, "v2.0.0").entryPoints).toEqual(["default.ts"]); + }); + + it("matches tilde range", () => { + const overrides = { "~1.2.0": { entryPoints: ["tilde.ts"] } }; + expect(resolveConfig(defaultConfig, overrides, "v1.2.0").entryPoints).toEqual(["tilde.ts"]); + expect(resolveConfig(defaultConfig, overrides, "v1.2.9").entryPoints).toEqual(["tilde.ts"]); + expect(resolveConfig(defaultConfig, overrides, "v1.3.0").entryPoints).toEqual(["default.ts"]); + }); + + it("matches caret range", () => { + const overrides = { "^1.2.0": { entryPoints: ["caret.ts"] } }; + expect(resolveConfig(defaultConfig, overrides, "v1.2.0").entryPoints).toEqual(["caret.ts"]); + expect(resolveConfig(defaultConfig, overrides, "v1.9.9").entryPoints).toEqual(["caret.ts"]); + expect(resolveConfig(defaultConfig, overrides, "v2.0.0").entryPoints).toEqual(["default.ts"]); + }); + }); +}); + +describe("buildTypedocConfig", () => { + it("merges TYPEDOC_FORMATTING with resolved config", () => { + const resolved: TypedocConfig = { + entryPoints: ["src/sandbox/index.ts"], + }; + const result = buildTypedocConfig(resolved); + + expect(result.entryPoints).toEqual(["src/sandbox/index.ts"]); + expect(result.out).toBe(TYPEDOC_FORMATTING.out); + expect(result.excludeExternals).toBe(true); + expect(result.hidePageTitle).toBe(true); + }); + + it("includes exclude when provided", () => { + const resolved: TypedocConfig = { + entryPoints: ["src/index.ts"], + exclude: ["**/*.test.ts", "**/__tests__/**"], + }; + const result = buildTypedocConfig(resolved); + + expect(result.exclude).toEqual(["**/*.test.ts", "**/__tests__/**"]); + }); + + it("does not include exclude when not provided", () => { + const resolved: TypedocConfig = { + entryPoints: ["src/index.ts"], + }; + const result = buildTypedocConfig(resolved); + + // exclude comes from TYPEDOC_FORMATTING default + expect(result.exclude).toEqual(TYPEDOC_FORMATTING.exclude); + }); +}); + +describe("TYPEDOC_FORMATTING", () => { + it("has all required formatting options", () => { + expect(TYPEDOC_FORMATTING.out).toBe("sdk_ref"); + expect(TYPEDOC_FORMATTING.excludeExternals).toBe(true); + expect(TYPEDOC_FORMATTING.excludeInternal).toBe(true); + expect(TYPEDOC_FORMATTING.excludePrivate).toBe(true); + expect(TYPEDOC_FORMATTING.excludeProtected).toBe(true); + expect(TYPEDOC_FORMATTING.outputFileStrategy).toBe("modules"); + expect(TYPEDOC_FORMATTING.readme).toBe("none"); + expect(TYPEDOC_FORMATTING.disableSources).toBe(true); + expect(TYPEDOC_FORMATTING.classPropertiesFormat).toBe("table"); + expect(TYPEDOC_FORMATTING.hidePageTitle).toBe(true); + expect(TYPEDOC_FORMATTING.hideBreadcrumbs).toBe(true); + }); +}); + diff --git a/sdk-reference-generator/src/__tests__/generator-failures.test.ts b/sdk-reference-generator/src/__tests__/generator-failures.test.ts index 359a8ec..2c27d7d 100644 --- a/sdk-reference-generator/src/__tests__/generator-failures.test.ts +++ b/sdk-reference-generator/src/__tests__/generator-failures.test.ts @@ -17,6 +17,9 @@ describe("handleGenerationFailures", () => { tagFormat: "test@{version}", generator: "typedoc", required: true, + defaultConfig: { + entryPoints: ["src/index.ts"], + }, }; // optional SDK config @@ -29,6 +32,9 @@ describe("handleGenerationFailures", () => { tagFormat: "@test/python@{version}", generator: "typedoc", required: false, + defaultConfig: { + entryPoints: ["src/index.ts"], + }, }; describe("required SDK", () => { @@ -142,6 +148,9 @@ describe("version discovery integration", () => { generator: "typedoc", required: true, minVersion: "1.0.0", + defaultConfig: { + entryPoints: ["src/index.ts"], + }, }, "optional-sdk": { displayName: "Optional SDK", @@ -152,6 +161,9 @@ describe("version discovery integration", () => { tagFormat: "@optional@{version}", generator: "typedoc", required: false, + defaultConfig: { + entryPoints: ["src/index.ts"], + }, }, }, })); diff --git a/sdk-reference-generator/src/__tests__/sdks-config.test.ts b/sdk-reference-generator/src/__tests__/sdks-config.test.ts new file mode 100644 index 0000000..ec11357 --- /dev/null +++ b/sdk-reference-generator/src/__tests__/sdks-config.test.ts @@ -0,0 +1,138 @@ +import { describe, it, expect } from "vitest"; +import sdks from "../../sdks.config.js"; +import { resolveConfig } from "../lib/config.js"; +import type { TypedocSDKConfig, PydocSDKConfig } from "../types.js"; + +describe("sdks.config - js-sdk version overrides", () => { + const jsSdkConfig = sdks["js-sdk"] as TypedocSDKConfig; + + it("should use pty.ts for v1.0.0", () => { + const resolved = resolveConfig( + jsSdkConfig.defaultConfig, + jsSdkConfig.configOverrides, + "v1.0.0" + ); + + expect(resolved.entryPoints).toContain("src/sandbox/pty.ts"); + expect(resolved.entryPoints).not.toContain("src/sandbox/commands/index.ts"); + expect(resolved.entryPoints).not.toContain("src/template/index.ts"); + }); + + it("should use commands.ts without template for v1.1.0 - v2.2.x", () => { + const versions = ["v1.1.0", "v1.5.0", "v2.0.0", "v2.2.10"]; + + for (const version of versions) { + const resolved = resolveConfig( + jsSdkConfig.defaultConfig, + jsSdkConfig.configOverrides, + version + ); + + expect(resolved.entryPoints).toContain("src/sandbox/commands/index.ts"); + expect(resolved.entryPoints).not.toContain("src/sandbox/pty.ts"); + expect(resolved.entryPoints).not.toContain("src/template/index.ts"); + } + }); + + it("should include template modules for v2.3.0+", () => { + const versions = ["v2.3.0", "v2.5.0", "v2.10.1"]; + + for (const version of versions) { + const resolved = resolveConfig( + jsSdkConfig.defaultConfig, + jsSdkConfig.configOverrides, + version + ); + + expect(resolved.entryPoints).toContain("src/sandbox/commands/index.ts"); + expect(resolved.entryPoints).toContain("src/template/index.ts"); + expect(resolved.entryPoints).toContain("src/template/readycmd.ts"); + expect(resolved.entryPoints).toContain("src/template/logger.ts"); + expect(resolved.entryPoints).not.toContain("src/sandbox/pty.ts"); + } + }); + + it("should have correct entry point counts per version range", () => { + const v1_0_0 = resolveConfig( + jsSdkConfig.defaultConfig, + jsSdkConfig.configOverrides, + "v1.0.0" + ); + expect(v1_0_0.entryPoints).toHaveLength(5); // sandbox, filesystem, process, pty, errors + + const v1_5_0 = resolveConfig( + jsSdkConfig.defaultConfig, + jsSdkConfig.configOverrides, + "v1.5.0" + ); + expect(v1_5_0.entryPoints).toHaveLength(5); // sandbox, filesystem, process, commands, errors + + const v2_10_1 = resolveConfig( + jsSdkConfig.defaultConfig, + jsSdkConfig.configOverrides, + "v2.10.1" + ); + expect(v2_10_1.entryPoints).toHaveLength(8); // + 3 template modules + }); +}); + +describe("sdks.config - python-sdk version overrides", () => { + const pythonSdkConfig = sdks["python-sdk"] as PydocSDKConfig; + + it("should only include basic sandbox packages for v1.0.0 - v2.0.x", () => { + const versions = ["v1.0.0", "v1.5.0", "v2.0.0", "v2.0.3"]; + + for (const version of versions) { + const resolved = resolveConfig( + pythonSdkConfig.defaultConfig, + pythonSdkConfig.configOverrides, + version + ); + + expect(resolved.allowedPackages).toContain("e2b.sandbox_sync"); + expect(resolved.allowedPackages).toContain("e2b.sandbox_async"); + expect(resolved.allowedPackages).toContain("e2b.exceptions"); + expect(resolved.allowedPackages).not.toContain("e2b.template"); + expect(resolved.allowedPackages).not.toContain("e2b.template_sync"); + expect(resolved.allowedPackages).toHaveLength(3); + } + }); + + it("should include template packages for v2.1.0+", () => { + const versions = ["v2.1.0", "v2.3.0", "v2.5.0", "v2.10.1"]; + + for (const version of versions) { + const resolved = resolveConfig( + pythonSdkConfig.defaultConfig, + pythonSdkConfig.configOverrides, + version + ); + + expect(resolved.allowedPackages).toContain("e2b.sandbox_sync"); + expect(resolved.allowedPackages).toContain("e2b.sandbox_async"); + expect(resolved.allowedPackages).toContain("e2b.exceptions"); + expect(resolved.allowedPackages).toContain("e2b.template"); + expect(resolved.allowedPackages).toContain("e2b.template_sync"); + expect(resolved.allowedPackages).toContain("e2b.template_async"); + expect(resolved.allowedPackages).toContain("e2b.template.logger"); + expect(resolved.allowedPackages).toContain("e2b.template.readycmd"); + expect(resolved.allowedPackages).toHaveLength(8); + } + }); + + it("should have correct package counts per version range", () => { + const v1_5_0 = resolveConfig( + pythonSdkConfig.defaultConfig, + pythonSdkConfig.configOverrides, + "v1.5.0" + ); + expect(v1_5_0.allowedPackages).toHaveLength(3); // basic sandbox packages only + + const v2_10_1 = resolveConfig( + pythonSdkConfig.defaultConfig, + pythonSdkConfig.configOverrides, + "v2.10.1" + ); + expect(v2_10_1.allowedPackages).toHaveLength(8); // + 5 template packages + }); +}); diff --git a/sdk-reference-generator/src/__tests__/utils.test.ts b/sdk-reference-generator/src/__tests__/utils.test.ts index 63ec626..8b91d1d 100644 --- a/sdk-reference-generator/src/__tests__/utils.test.ts +++ b/sdk-reference-generator/src/__tests__/utils.test.ts @@ -187,4 +187,3 @@ describe("buildSDKPath", () => { expect(result).toContain("code-interpreter-js-sdk"); }); }); - diff --git a/sdk-reference-generator/src/generator.ts b/sdk-reference-generator/src/generator.ts index 9b1496a..2e67560 100644 --- a/sdk-reference-generator/src/generator.ts +++ b/sdk-reference-generator/src/generator.ts @@ -4,6 +4,8 @@ import type { SDKConfig, GenerationContext, GenerationResult, + TypedocConfig, + PydocConfig, } from "./types.js"; import sdks from "../sdks.config.js"; import { log } from "./lib/log.js"; @@ -22,6 +24,7 @@ import { generateCli } from "./generators/cli.js"; import { buildSDKPath } from "./lib/utils.js"; import { CONSTANTS } from "./lib/constants.js"; import { CheckoutManager } from "./lib/checkout.js"; +import { resolveConfig } from "./lib/config.js"; async function generateVersion( sdkKey: string, @@ -64,16 +67,32 @@ async function generateVersion( let generatedDocsDir: string; switch (config.generator) { - case "typedoc": - generatedDocsDir = await generateTypedoc(sdkDir, context.configsDir); + case "typedoc": { + const resolvedConfig = resolveConfig( + config.defaultConfig, + config.configOverrides, + version + ); + generatedDocsDir = await generateTypedoc( + sdkDir, + resolvedConfig, + context.configsDir + ); break; - case "pydoc": + } + case "pydoc": { + const resolvedConfig = resolveConfig( + config.defaultConfig, + config.configOverrides, + version + ); generatedDocsDir = await generatePydoc( sdkDir, - config.allowedPackages, + resolvedConfig, installResult.usePoetryRun ); break; + } case "cli": generatedDocsDir = await generateCli(sdkDir); break; diff --git a/sdk-reference-generator/src/generators/pydoc.ts b/sdk-reference-generator/src/generators/pydoc.ts index 75f0e51..8c60d96 100644 --- a/sdk-reference-generator/src/generators/pydoc.ts +++ b/sdk-reference-generator/src/generators/pydoc.ts @@ -3,6 +3,7 @@ import fs from "fs-extra"; import path from "path"; import { CONSTANTS } from "../lib/constants.js"; import { log } from "../lib/log.js"; +import type { PydocConfig } from "../types.js"; async function processMdx(file: string): Promise { let content = await fs.readFile(file, "utf-8"); @@ -72,9 +73,10 @@ async function processPackage( export async function generatePydoc( sdkDir: string, - allowedPackages: readonly string[], + resolvedConfig: PydocConfig, usePoetryRun: boolean ): Promise { + const { allowedPackages } = resolvedConfig; const outputDir = path.join(sdkDir, CONSTANTS.SDK_REF_DIR); await fs.ensureDir(outputDir); @@ -82,6 +84,7 @@ export async function generatePydoc( `Attempting to generate docs for ${allowedPackages.length} packages`, 1 ); + log.data(`Packages: ${allowedPackages.join(", ")}`, 1); let successful = 0; for (const pkg of allowedPackages) { diff --git a/sdk-reference-generator/src/generators/typedoc.ts b/sdk-reference-generator/src/generators/typedoc.ts index 565d31b..ff0fd01 100644 --- a/sdk-reference-generator/src/generators/typedoc.ts +++ b/sdk-reference-generator/src/generators/typedoc.ts @@ -1,70 +1,62 @@ -import { execa } from 'execa'; -import fs from 'fs-extra'; -import path from 'path'; -import { log } from '../lib/log.js'; +import { execa } from "execa"; +import fs from "fs-extra"; +import path from "path"; +import { log } from "../lib/log.js"; +import { buildTypedocConfig } from "../lib/config.js"; +import { CONSTANTS } from "../lib/constants.js"; +import type { TypedocConfig } from "../types.js"; -async function getTypedocOutputDir(sdkDir: string): Promise { - const configPath = path.join(sdkDir, 'typedoc.json'); - - if (await fs.pathExists(configPath)) { - try { - const config = await fs.readJSON(configPath); - return config.out || 'sdk_ref'; - } catch { - return 'sdk_ref'; +const GENERATED_CONFIG_NAME = "typedoc.generated.json"; + +/** + * Removes any existing typedoc config from the repo to prevent interference. + */ +async function cleanRepoConfigs(sdkDir: string): Promise { + const configFiles = ["typedoc.json", "typedoc.config.js", "typedoc.config.cjs"]; + + for (const file of configFiles) { + const filePath = path.join(sdkDir, file); + if (await fs.pathExists(filePath)) { + log.info(`Removing repo config: ${file}`, 1); + await fs.remove(filePath); } } - - return 'sdk_ref'; } export async function generateTypedoc( sdkDir: string, + resolvedConfig: TypedocConfig, configsDir: string ): Promise { - const hasRepoConfig = await fs.pathExists(path.join(sdkDir, 'typedoc.json')); - const outputDir = await getTypedocOutputDir(sdkDir); + // remove any existing repo configs to force our config + await cleanRepoConfigs(sdkDir); - if (hasRepoConfig) { - log.info('Running TypeDoc with repo config...', 1); - await execa( - 'npx', - [ - 'typedoc', - '--plugin', - 'typedoc-plugin-markdown', - '--plugin', - path.join(configsDir, 'typedoc-theme.cjs'), - ], - { - cwd: sdkDir, - stdio: 'inherit', - } - ); - } else { - log.info('Running TypeDoc with default config...', 1); - await fs.copy( - path.join(configsDir, 'typedoc.json'), - path.join(sdkDir, 'typedoc.docs.json') - ); + // build full config with formatting defaults + SDK-specific settings + const fullConfig = buildTypedocConfig(resolvedConfig); - await execa( - 'npx', - [ - 'typedoc', - '--options', - './typedoc.docs.json', - '--plugin', - 'typedoc-plugin-markdown', - '--plugin', - path.join(configsDir, 'typedoc-theme.cjs'), - ], - { - cwd: sdkDir, - stdio: 'inherit', - } - ); - } + // write our generated config + const configPath = path.join(sdkDir, GENERATED_CONFIG_NAME); + await fs.writeJSON(configPath, fullConfig, { spaces: 2 }); + + log.info("Running TypeDoc with generated config...", 1); + log.data(`Entry points: ${resolvedConfig.entryPoints.join(", ")}`, 1); + + await execa( + "npx", + [ + "typedoc", + "--options", + `./${GENERATED_CONFIG_NAME}`, + "--plugin", + "typedoc-plugin-markdown", + "--plugin", + path.join(configsDir, "typedoc-theme.cjs"), + ], + { + cwd: sdkDir, + stdio: "inherit", + } + ); - return path.join(sdkDir, outputDir); + return path.join(sdkDir, CONSTANTS.SDK_REF_DIR); } diff --git a/sdk-reference-generator/src/lib/config.ts b/sdk-reference-generator/src/lib/config.ts new file mode 100644 index 0000000..254aee6 --- /dev/null +++ b/sdk-reference-generator/src/lib/config.ts @@ -0,0 +1,64 @@ +import semver from "semver"; +import { stripVersionPrefix } from "./utils.js"; +import type { TypedocConfig, PydocConfig } from "../types.js"; + +// shared typedoc formatting settings (applied to all typedoc SDKs) +export const TYPEDOC_FORMATTING = { + out: "sdk_ref", + plugin: ["typedoc-plugin-markdown"], + exclude: ["**/*.spec.ts"], + excludeExternals: true, + excludeInternal: true, + excludePrivate: true, + excludeProtected: true, + navigation: { + includeGroups: false, + includeCategories: false, + }, + outputFileStrategy: "modules", + readme: "none", + disableSources: true, + classPropertiesFormat: "table", + typeDeclarationFormat: "table", + enumMembersFormat: "table", + parametersFormat: "table", + expandParameters: true, + useCodeBlocks: true, + hidePageTitle: true, + hideBreadcrumbs: true, +} as const; + +/** + * Resolves config by matching version against semver ranges in configOverrides. + * Returns merged defaultConfig with matching override, or defaultConfig if no match. + */ +export function resolveConfig( + defaultConfig: T, + configOverrides: Record> | undefined, + version: string +): T { + if (!configOverrides) return defaultConfig; + + const cleanVersion = stripVersionPrefix(version); + + for (const [range, override] of Object.entries(configOverrides)) { + if (semver.satisfies(cleanVersion, range)) { + return { ...defaultConfig, ...override } as T; + } + } + + return defaultConfig; +} + +/** + * Builds the full typedoc config by merging formatting defaults with SDK-specific settings. + */ +export function buildTypedocConfig( + resolved: TypedocConfig +): Record { + return { + ...TYPEDOC_FORMATTING, + entryPoints: resolved.entryPoints, + ...(resolved.exclude && { exclude: resolved.exclude }), + }; +} diff --git a/sdk-reference-generator/src/types.ts b/sdk-reference-generator/src/types.ts index a2d636e..21cb977 100644 --- a/sdk-reference-generator/src/types.ts +++ b/sdk-reference-generator/src/types.ts @@ -11,20 +11,36 @@ type BaseSDKConfig = { sdkPaths?: string[]; }; +// generator-specific config shapes +export type TypedocConfig = { + entryPoints: string[]; + exclude?: string[]; +}; + +export type PydocConfig = { + allowedPackages: readonly string[]; +}; + +// discriminated union - defaultConfig and configOverrides typed by generator type TypedocSDKConfig = BaseSDKConfig & { generator: "typedoc"; + defaultConfig: TypedocConfig; + configOverrides?: Record>; }; type PydocSDKConfig = BaseSDKConfig & { generator: "pydoc"; - allowedPackages: readonly string[]; + defaultConfig: PydocConfig; + configOverrides?: Record>; }; type CLISDKConfig = BaseSDKConfig & { generator: "cli"; + // no defaultConfig/configOverrides - CLI is self-contained }; export type SDKConfig = TypedocSDKConfig | PydocSDKConfig | CLISDKConfig; +export type { TypedocSDKConfig, PydocSDKConfig, CLISDKConfig }; export type GeneratorType = SDKConfig["generator"]; export type ConfigFile = { From 1df3c3ac226b7e3f172bbd4e8e10e8a8ebdf02c1 Mon Sep 17 00:00:00 2001 From: ben-fornefeld Date: Mon, 12 Jan 2026 16:00:10 +0100 Subject: [PATCH 34/39] fix: versioning config --- sdk-reference-generator/VERSIONING.md | 159 ---------------------- sdk-reference-generator/sdks.config.ts | 10 +- sdk-reference-generator/src/lib/config.ts | 11 +- 3 files changed, 18 insertions(+), 162 deletions(-) delete mode 100644 sdk-reference-generator/VERSIONING.md diff --git a/sdk-reference-generator/VERSIONING.md b/sdk-reference-generator/VERSIONING.md deleted file mode 100644 index 71755f3..0000000 --- a/sdk-reference-generator/VERSIONING.md +++ /dev/null @@ -1,159 +0,0 @@ -# SDK Versioning Documentation - -This document tracks the version-specific configuration changes for each SDK. - -## JavaScript SDK (js-sdk) - -### Verified Version History - -All version ranges have been verified by checking actual git tags and TypeDoc configurations. - -| Version Range | Entry Points | Notes | -|--------------|-------------|--------| -| `1.0.0` | sandbox/index.ts, filesystem/index.ts, process/index.ts, **pty.ts**, errors.ts | Used pty.ts instead of commands.ts | -| `>=1.1.0 <2.3.0` | sandbox/index.ts, filesystem/index.ts, process/index.ts, **commands/index.ts**, errors.ts | Standard sandbox APIs | -| `>=2.3.0` | + **template/index.ts**, **template/readycmd.ts**, **template/logger.ts** | Added template build support | - -### Configuration in sdks.config.ts - -```typescript -"js-sdk": { - defaultConfig: { - entryPoints: [ - // v2.3.0+ configuration (with template modules) - "src/sandbox/index.ts", - "src/sandbox/filesystem/index.ts", - "src/sandbox/process/index.ts", - "src/sandbox/commands/index.ts", - "src/errors.ts", - "src/template/index.ts", - "src/template/readycmd.ts", - "src/template/logger.ts", - ], - }, - configOverrides: { - "1.0.0": { - entryPoints: [/* pty.ts version */], - }, - ">=1.1.0 <2.3.0": { - entryPoints: [/* without template */], - }, - }, -} -``` - -## Python SDK (python-sdk) - -### Verified Version History - -All version ranges have been verified by checking actual git tags and package structure. - -| Version Range | Allowed Packages | Notes | -|--------------|-----------------|--------| -| `>=1.0.0 <2.1.0` | e2b.sandbox_sync, e2b.sandbox_async, e2b.exceptions | Basic sandbox APIs only | -| `>=2.1.0` | + e2b.template, e2b.template_sync, e2b.template_async, e2b.template.logger, e2b.template.readycmd | Template SDK added in v2.1.0 (PR #871) | - -### Configuration in sdks.config.ts - -```typescript -"python-sdk": { - defaultConfig: { - allowedPackages: [ - // v2.1.0+ configuration (with template modules) - "e2b.sandbox_sync", - "e2b.sandbox_async", - "e2b.exceptions", - "e2b.template", - "e2b.template_sync", - "e2b.template_async", - "e2b.template.logger", - "e2b.template.readycmd", - ], - }, - configOverrides: { - ">=1.0.0 <2.1.0": { - allowedPackages: [ - "e2b.sandbox_sync", - "e2b.sandbox_async", - "e2b.exceptions", - ], - }, - }, -} -``` - -## Code Interpreter SDKs - -### code-interpreter-js-sdk - -**Current Configuration**: Single entry point (`src/index.ts`) - -No version-specific overrides needed - the SDK has a simple, stable structure since v1.0.0. The code-interpreter is a focused wrapper around the base E2B SDK for code execution. - -### code-interpreter-python-sdk - -**Current Configuration**: Single package (`e2b_code_interpreter`) - -No version-specific overrides needed - the Python package structure has remained consistent. - -## Desktop SDKs - -### desktop-js-sdk & desktop-python-sdk - -**Current Configuration**: Simple defaults (`src/index.ts` and `e2b_desktop`) - -No version-specific overrides needed yet. These SDKs are relatively new and haven't had breaking structural changes requiring versioned configs. - -**Note**: If any of these SDKs introduce breaking changes in future versions (e.g., new modules, renamed packages), add appropriate `configOverrides` following the same pattern used for js-sdk and python-sdk. - -## Adding New Version Overrides - -When you discover that a specific version range needs different configuration: - -1. **Identify the version range** using semver syntax (e.g., `>=1.5.0 <2.0.0`) -2. **Add to configOverrides** with partial config (only override what changed) -3. **Add tests** in `src/__tests__/sdks-config.test.ts` -4. **Document here** with notes on what changed and why - -### Example: Adding a new override - -```typescript -configOverrides: { - ">=1.0.0 <1.5.0": { - // Old structure - }, - ">=1.5.0 <2.0.0": { - // New structure introduced in 1.5.0 - }, - ">=2.0.0": { - // Breaking changes in 2.0.0 - }, -} -``` - -## Resolution Logic - -The config resolution follows these rules: - -1. Start with `defaultConfig` -2. Find the **first matching** semver range in `configOverrides` -3. Shallow merge override into default (override wins) -4. Return merged config - -This means: -- `defaultConfig` should represent the **latest/current** structure -- `configOverrides` handles older versions or special cases -- Order matters when multiple ranges could match (first match wins) - -## Testing - -Tests in `src/__tests__/sdks-config.test.ts` verify: -- Correct packages/entry points for each version range -- Proper semver range matching -- Expected counts of items per version - -Run tests with: -```bash -pnpm test src/__tests__/sdks-config.test.ts -``` - diff --git a/sdk-reference-generator/sdks.config.ts b/sdk-reference-generator/sdks.config.ts index e2ed4d4..f69ea37 100644 --- a/sdk-reference-generator/sdks.config.ts +++ b/sdk-reference-generator/sdks.config.ts @@ -111,7 +111,13 @@ const sdks = { minVersion: "1.0.0", defaultConfig: { - entryPoints: ["src/index.ts"], + entryPoints: [ + "src/index.ts", + "src/charts.ts", + "src/consts.ts", + "src/messaging.ts", + "src/sandbox.ts", + ], }, }, @@ -145,7 +151,7 @@ const sdks = { minVersion: "1.0.0", defaultConfig: { - entryPoints: ["src/index.ts"], + entryPoints: ["src/index.ts", "src/sandbox.ts"], }, }, diff --git a/sdk-reference-generator/src/lib/config.ts b/sdk-reference-generator/src/lib/config.ts index 254aee6..4a7ac3a 100644 --- a/sdk-reference-generator/src/lib/config.ts +++ b/sdk-reference-generator/src/lib/config.ts @@ -1,5 +1,6 @@ import semver from "semver"; import { stripVersionPrefix } from "./utils.js"; +import { log } from "./log.js"; import type { TypedocConfig, PydocConfig } from "../types.js"; // shared typedoc formatting settings (applied to all typedoc SDKs) @@ -37,16 +38,24 @@ export function resolveConfig( configOverrides: Record> | undefined, version: string ): T { - if (!configOverrides) return defaultConfig; + if (!configOverrides) { + log.info(`Using default config for ${version}`, 1); + return defaultConfig; + } const cleanVersion = stripVersionPrefix(version); for (const [range, override] of Object.entries(configOverrides)) { if (semver.satisfies(cleanVersion, range)) { + log.info( + `Using config override for ${version} (matched range: ${range})`, + 1 + ); return { ...defaultConfig, ...override } as T; } } + log.info(`Using default config for ${version} (no override match)`, 1); return defaultConfig; } From b46a60397d82061d2d1d94877675bc93d819d79f Mon Sep 17 00:00:00 2001 From: ben-fornefeld Date: Mon, 12 Jan 2026 16:05:34 +0100 Subject: [PATCH 35/39] fix: silent fs move issues --- sdk-reference-generator/src/lib/files.ts | 18 ++++++++++++++---- 1 file changed, 14 insertions(+), 4 deletions(-) diff --git a/sdk-reference-generator/src/lib/files.ts b/sdk-reference-generator/src/lib/files.ts index 0ae9e3f..68e4227 100644 --- a/sdk-reference-generator/src/lib/files.ts +++ b/sdk-reference-generator/src/lib/files.ts @@ -64,6 +64,7 @@ async function flattenNestedFiles(refDir: string): Promise { const targetFiles = new Set(); const collisions: string[] = []; + const moves: Array<{ from: string; to: string }> = []; for (const file of nestedFiles) { const filename = path.basename(file); @@ -84,16 +85,25 @@ async function flattenNestedFiles(refDir: string): Promise { } targetFiles.add(targetName); - await fs.move(path.join(refDir, file), path.join(refDir, targetName), { - overwrite: false, + moves.push({ + from: path.join(refDir, file), + to: path.join(refDir, targetName), }); } if (collisions.length > 0) { log.warn(`Detected ${collisions.length} filename collision(s):`, 1); collisions.forEach((c) => log.data(c, 2)); + throw new Error( + `Cannot flatten files: ${collisions.length} filename collision(s) detected. ` + + `Different source files would overwrite each other.` + ); } + + for (const { from, to } of moves) { + await fs.move(from, to, { overwrite: false }); } +} async function removeEmptyDirectories(refDir: string): Promise { const dirs = await glob("**/", { cwd: refDir }); @@ -106,7 +116,7 @@ async function removeEmptyDirectories(refDir: string): Promise { } } catch {} } - } +} async function convertMdToMdx(refDir: string): Promise { const mdFiles = await glob("*.md", { cwd: refDir }); @@ -123,7 +133,7 @@ async function convertMdToMdx(refDir: string): Promise { await fs.writeFile(mdxPath, createFrontmatter(title) + content); await fs.remove(fullPath); } - } +} async function ensureFrontmatter(refDir: string): Promise { const mdxFiles = await glob(`*${CONSTANTS.MDX_EXTENSION}`, { cwd: refDir }); From cfaa83a23804f8f33c839436c63703f77ccd3f2d Mon Sep 17 00:00:00 2001 From: ben-fornefeld Date: Mon, 12 Jan 2026 16:23:40 +0100 Subject: [PATCH 36/39] fix: pip installs --- sdk-reference-generator/src/lib/install.ts | 11 ++++++++++- 1 file changed, 10 insertions(+), 1 deletion(-) diff --git a/sdk-reference-generator/src/lib/install.ts b/sdk-reference-generator/src/lib/install.ts index 4a82342..9fce918 100644 --- a/sdk-reference-generator/src/lib/install.ts +++ b/sdk-reference-generator/src/lib/install.ts @@ -43,7 +43,15 @@ export async function installDependencies( }); return { usePoetryRun: true }; } catch { - log.warn("poetry failed, using global pydoc-markdown...", 1); + log.warn("poetry failed, falling back to pip...", 1); + + log.info("Installing SDK package from local directory...", 1); + await execa("pip", ["install", "--break-system-packages", "."], { + cwd: sdkDir, + stdio: "inherit", + }); + + log.info("Installing pydoc-markdown...", 1); await execa( "pip", ["install", "--break-system-packages", "pydoc-markdown"], @@ -52,6 +60,7 @@ export async function installDependencies( stdio: "inherit", } ); + return { usePoetryRun: false }; } } From a3dd778d7a9d23526e2c6b64d02e96810e0fdff6 Mon Sep 17 00:00:00 2001 From: ben-fornefeld Date: Mon, 12 Jan 2026 17:23:55 +0100 Subject: [PATCH 37/39] cleanup files before force regeneration --- .../src/__tests__/files-processing.test.ts | 92 ++++++++++++++++--- sdk-reference-generator/src/lib/files.ts | 2 + 2 files changed, 82 insertions(+), 12 deletions(-) diff --git a/sdk-reference-generator/src/__tests__/files-processing.test.ts b/sdk-reference-generator/src/__tests__/files-processing.test.ts index 408e6e4..217c0ed 100644 --- a/sdk-reference-generator/src/__tests__/files-processing.test.ts +++ b/sdk-reference-generator/src/__tests__/files-processing.test.ts @@ -42,9 +42,7 @@ describe("flattenMarkdown", () => { // nested file should be flattened with path prefix expect( - await fs.pathExists( - path.join(tempDir, "modules-sandbox-Sandbox.mdx") - ) + await fs.pathExists(path.join(tempDir, "modules-sandbox-Sandbox.mdx")) ).toBe(true); // original nested directory should be removed expect(await fs.pathExists(nestedDir)).toBe(false); @@ -105,10 +103,7 @@ describe("flattenMarkdown", () => { }); it("generates correct title from snake_case filenames", async () => { - await fs.writeFile( - path.join(tempDir, "sandbox_sync.md"), - "# Content" - ); + await fs.writeFile(path.join(tempDir, "sandbox_sync.md"), "# Content"); await flattenMarkdown(tempDir); @@ -175,17 +170,22 @@ sidebarTitle: "Existing" const sandboxDir = path.join(modulesDir, "sandbox"); await fs.ensureDir(sandboxDir); - await fs.writeFile(path.join(sandboxDir, "Sandbox.md"), "# Sandbox class"); + await fs.writeFile( + path.join(sandboxDir, "Sandbox.md"), + "# Sandbox class" + ); await flattenMarkdown(tempDir); // check results expect(await fs.pathExists(path.join(tempDir, "README.md"))).toBe(false); - expect(await fs.pathExists(path.join(tempDir, "TopLevel.mdx"))).toBe(true); - expect(await fs.pathExists(path.join(tempDir, "modules.mdx"))).toBe(true); - expect(await fs.pathExists(path.join(tempDir, "modules-Helper.mdx"))).toBe( + expect(await fs.pathExists(path.join(tempDir, "TopLevel.mdx"))).toBe( true ); + expect(await fs.pathExists(path.join(tempDir, "modules.mdx"))).toBe(true); + expect( + await fs.pathExists(path.join(tempDir, "modules-Helper.mdx")) + ).toBe(true); expect( await fs.pathExists(path.join(tempDir, "modules-sandbox-Sandbox.mdx")) ).toBe(true); @@ -362,5 +362,73 @@ describe("copyToDocs", () => { expect(await fs.pathExists(path.join(destDir, "readme.txt"))).toBe(false); expect(await fs.pathExists(path.join(destDir, "config.json"))).toBe(false); }); -}); + it("removes stale files from previous generation", async () => { + // simulate previous generation with 3 files + await fs.writeFile( + path.join(destDir, "Sandbox.mdx"), + '---\nsidebarTitle: "Sandbox"\n---\n\n# Old content' + ); + await fs.writeFile( + path.join(destDir, "Template.mdx"), + '---\nsidebarTitle: "Template"\n---\n\n# Old content' + ); + await fs.writeFile( + path.join(destDir, "OldAPI.mdx"), + '---\nsidebarTitle: "Old API"\n---\n\n# Removed in new version' + ); + + // new generation only has 2 files (OldAPI.mdx was removed) + await fs.writeFile( + path.join(srcDir, "Sandbox.mdx"), + '---\nsidebarTitle: "Sandbox"\n---\n\n# New content' + ); + await fs.writeFile( + path.join(srcDir, "Template.mdx"), + '---\nsidebarTitle: "Template"\n---\n\n# New content' + ); + + const result = await copyToDocs(srcDir, destDir, "SDK", "v2.0.0"); + + expect(result).toBe(true); + expect(await fs.pathExists(path.join(destDir, "Sandbox.mdx"))).toBe(true); + expect(await fs.pathExists(path.join(destDir, "Template.mdx"))).toBe(true); + // stale file should be removed + expect(await fs.pathExists(path.join(destDir, "OldAPI.mdx"))).toBe(false); + + // verify content was updated (not just appended) + const sandboxContent = await fs.readFile( + path.join(destDir, "Sandbox.mdx"), + "utf-8" + ); + expect(sandboxContent).toContain("New content"); + expect(sandboxContent).not.toContain("Old content"); + }); + + it("cleans entire destination directory before copying", async () => { + // create various files and subdirectories in destination + await fs.writeFile(path.join(destDir, "File1.mdx"), "content"); + await fs.writeFile(path.join(destDir, "File2.mdx"), "content"); + await fs.writeFile(path.join(destDir, "random.txt"), "text"); + const subdir = path.join(destDir, "subdir"); + await fs.ensureDir(subdir); + await fs.writeFile(path.join(subdir, "nested.mdx"), "nested"); + + // new generation has different files + await fs.writeFile( + path.join(srcDir, "NewFile.mdx"), + '---\nsidebarTitle: "New"\n---\n\n# Content' + ); + + const result = await copyToDocs(srcDir, destDir, "SDK", "v1.0.0"); + + expect(result).toBe(true); + // only new file should exist + expect(await fs.pathExists(path.join(destDir, "NewFile.mdx"))).toBe(true); + // all old files should be gone + expect(await fs.pathExists(path.join(destDir, "File1.mdx"))).toBe(false); + expect(await fs.pathExists(path.join(destDir, "File2.mdx"))).toBe(false); + expect(await fs.pathExists(path.join(destDir, "random.txt"))).toBe(false); + expect(await fs.pathExists(subdir)).toBe(false); + }); +}); diff --git a/sdk-reference-generator/src/lib/files.ts b/sdk-reference-generator/src/lib/files.ts index 68e4227..9b8e630 100644 --- a/sdk-reference-generator/src/lib/files.ts +++ b/sdk-reference-generator/src/lib/files.ts @@ -184,7 +184,9 @@ export async function copyToDocs( return false; } + await fs.remove(destDir); await fs.ensureDir(destDir); + log.info(`Copying ${files.length} files to ${destDir}`, 1); for (const file of files) { From 9670c3966c4eb97aa45eb09f8b3738d00d88da5c Mon Sep 17 00:00:00 2001 From: ben-fornefeld Date: Mon, 12 Jan 2026 19:49:22 +0100 Subject: [PATCH 38/39] fix: normailze versioning --- sdk-reference-generator/src/lib/git.ts | 4 ++-- sdk-reference-generator/src/navigation.ts | 5 +++-- 2 files changed, 5 insertions(+), 4 deletions(-) diff --git a/sdk-reference-generator/src/lib/git.ts b/sdk-reference-generator/src/lib/git.ts index 6fa8468..06d0f8e 100644 --- a/sdk-reference-generator/src/lib/git.ts +++ b/sdk-reference-generator/src/lib/git.ts @@ -1,5 +1,5 @@ import { simpleGit, SimpleGit } from "simple-git"; -import { sortVersionsDescending } from "./utils.js"; +import { sortVersionsDescending, normalizeVersion } from "./utils.js"; import { log } from "./log.js"; const git: SimpleGit = simpleGit(); @@ -87,7 +87,7 @@ export async function resolveLatestVersion( version: string ): Promise { if (version !== "latest") { - return version; + return normalizeVersion(version); } const versions = await fetchRemoteTags(repo, tagPattern); diff --git a/sdk-reference-generator/src/navigation.ts b/sdk-reference-generator/src/navigation.ts index a04ac66..c6f39f5 100644 --- a/sdk-reference-generator/src/navigation.ts +++ b/sdk-reference-generator/src/navigation.ts @@ -74,13 +74,14 @@ export async function buildNavigation( versions.map(async (version, index) => { const versionDir = path.join(sdkDir, version); const modules = await getModules(versionDir); + const normalizedVersion = normalizeVersion(version); return { - version: normalizeVersion(version), + version: normalizedVersion, default: index === 0, pages: modules.map( (module) => - `${CONSTANTS.DOCS_SDK_REF_PATH}/${sdkKey}/${version}/${module}` + `${CONSTANTS.DOCS_SDK_REF_PATH}/${sdkKey}/${normalizedVersion}/${module}` ), }; }) From 4eaca6fce61a2b95f3d73bbdc1466dcc597ab3a7 Mon Sep 17 00:00:00 2001 From: Ben Fornefeld Date: Tue, 13 Jan 2026 20:12:22 +0100 Subject: [PATCH 39/39] improve: pr test workflow + chore: cleanup docs.json --- sdk-reference-generator/package.json | 2 +- .../src/rebuild-docs-json.ts | 68 +++++++++++++++++++ 2 files changed, 69 insertions(+), 1 deletion(-) create mode 100644 sdk-reference-generator/src/rebuild-docs-json.ts diff --git a/sdk-reference-generator/package.json b/sdk-reference-generator/package.json index bf988ba..5692b09 100644 --- a/sdk-reference-generator/package.json +++ b/sdk-reference-generator/package.json @@ -4,6 +4,7 @@ "type": "module", "scripts": { "generate": "tsx src/cli.ts", + "rebuild-docs-json": "tsx src/rebuild-docs-json.ts", "test": "vitest run", "test:watch": "vitest" }, @@ -26,4 +27,3 @@ "vitest": "^2.1.8" } } - diff --git a/sdk-reference-generator/src/rebuild-docs-json.ts b/sdk-reference-generator/src/rebuild-docs-json.ts new file mode 100644 index 0000000..8547647 --- /dev/null +++ b/sdk-reference-generator/src/rebuild-docs-json.ts @@ -0,0 +1,68 @@ +#!/usr/bin/env node + +import path from "path"; +import { fileURLToPath } from "url"; +import { buildNavigation, mergeNavigation } from "./navigation.js"; +import { verifyGeneratedDocs } from "./lib/verify.js"; +import { log } from "./lib/log.js"; + +const __filename = fileURLToPath(import.meta.url); +const __dirname = path.dirname(__filename); + +const SCRIPT_DIR = path.resolve(__dirname, ".."); +const DOCS_DIR = path.resolve(SCRIPT_DIR, ".."); + +async function main(): Promise { + log.header("Rebuild docs.json from local SDK references"); + + log.section("Building navigation"); + const navigation = await buildNavigation(DOCS_DIR); + + if (navigation.length === 0) { + log.warn("No SDK references found locally"); + process.exit(1); + } + + log.blank(); + log.section("Merging into docs.json"); + await mergeNavigation(navigation, DOCS_DIR); + + log.blank(); + log.section("Verifying documentation"); + const verification = await verifyGeneratedDocs(DOCS_DIR); + + if (verification.warnings.length > 0) { + log.warn("Warnings detected:"); + for (const warning of verification.warnings) { + log.data(`- ${warning}`, 1); + } + } + + if (!verification.valid) { + log.blank(); + log.error("Verification failed:"); + for (const error of verification.errors) { + log.data(`- ${error}`, 1); + } + if (!verification.docsJsonValid) { + log.error("docs.json validation failed"); + } + process.exit(1); + } + + log.blank(); + log.success("docs.json rebuilt successfully"); + log.stats( + [ + { label: "Total SDKs", value: verification.stats.totalSDKs }, + { label: "Total versions", value: verification.stats.totalVersions }, + { label: "Total MDX files", value: verification.stats.totalMdxFiles }, + ], + 0 + ); +} + +main().catch((error) => { + log.error(`Fatal error: ${error.message}`); + process.exit(1); +});