diff --git a/.github/workflows/sdk-reference-sync.yml b/.github/workflows/sdk-reference-sync.yml new file mode 100644 index 0000000..8b02db6 --- /dev/null +++ b/.github/workflows/sdk-reference-sync.yml @@ -0,0 +1,113 @@ +name: Sync SDK Reference Documentation + +on: + # manual trigger with inputs + workflow_dispatch: + inputs: + sdk: + description: "SDK to generate (see sdks.config.ts for available SDKs, or use 'all')" + required: true + default: "all" + type: string + version: + description: "Version to generate (all, latest, or specific like v2.9.0)" + required: true + default: "all" + 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 generator dependencies + working-directory: sdk-reference-generator + run: pnpm install --frozen-lockfile + + - 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: | + 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}" + fi + + echo "sdk=${SDK:-all}" >> $GITHUB_OUTPUT + echo "version=${VERSION:-all}" >> $GITHUB_OUTPUT + + - name: Generate SDK Reference + working-directory: sdk-reference-generator + run: | + pnpm run generate \ + --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" + + - name: Commit and push changes + run: | + git config user.name "github-actions[bot]" + git config user.email "github-actions[bot]@users.noreply.github.com" + + git add docs/sdk-reference/ + git add docs.json + + 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:" >> $GITHUB_STEP_SUMMARY + find docs/sdk-reference -type f -name "*.mdx" >> $GITHUB_STEP_SUMMARY || true + echo '```' >> $GITHUB_STEP_SUMMARY diff --git a/.gitignore b/.gitignore index 090a1f0..ac322bc 100644 --- a/.gitignore +++ b/.gitignore @@ -1,2 +1,7 @@ .idea .DS_Store + +node_modules + +# Generated SDK navigation (intermediate file) +sdk_navigation.json \ No newline at end of file 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/docs.json b/docs.json index f1410c9..04a7a24 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,359 @@ { "anchor": "SDK Reference", "icon": "brackets-curly", - "href": "https://e2b.dev/docs/sdk-reference" + "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/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/generate-mcp-servers.sh b/scripts/generate-mcp-servers.sh old mode 100644 new mode 100755 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/sdk-reference-generator/README.md b/sdk-reference-generator/README.md new file mode 100644 index 0000000..792ef07 --- /dev/null +++ b/sdk-reference-generator/README.md @@ -0,0 +1,166 @@ +# 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 +ā”œā”€ā”€ lib/ +│ ā”œā”€ā”€ constants.ts # Centralized magic strings +│ ā”œā”€ā”€ utils.ts # Pure utility functions +│ ā”œā”€ā”€ git.ts # Git operations (clone, tags) +│ ā”œā”€ā”€ checkout.ts # Manages repo checkouts and version switching +│ ā”œā”€ā”€ versions.ts # Version comparison and filtering +│ ā”œā”€ā”€ files.ts # Markdown processing and flattening +│ ā”œā”€ā”€ 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 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 both 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 + +- **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) + +## 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/configs/typedoc-theme.cjs b/sdk-reference-generator/configs/typedoc-theme.cjs new file mode 100644 index 0000000..b1cb1de --- /dev/null +++ b/sdk-reference-generator/configs/typedoc-theme.cjs @@ -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(lines[i]) + } + + return filteredLines.join('\n') +} + +module.exports = { load } + diff --git a/sdk-reference-generator/configs/typedoc.json b/sdk-reference-generator/configs/typedoc.json new file mode 100644 index 0000000..29c1a4b --- /dev/null +++ b/sdk-reference-generator/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/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/sdk-reference-generator/sdks.config.ts b/sdk-reference-generator/sdks.config.ts new file mode 100644 index 0000000..28cc667 --- /dev/null +++ b/sdk-reference-generator/sdks.config.ts @@ -0,0 +1,108 @@ +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", + allowedPackages: [ + "e2b.sandbox_sync", + "e2b.sandbox_async", + "e2b.exceptions", + "e2b.template", + "e2b.template_sync", + "e2b.template_async", + "e2b.template.logger", + "e2b.template.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", + allowedPackages: ["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", + allowedPackages: ["e2b_desktop"], + }, +} as const satisfies Record; + +export default sdks; 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/__tests__/files.test.ts b/sdk-reference-generator/src/__tests__/files.test.ts new file mode 100644 index 0000000..63ac8c4 --- /dev/null +++ b/sdk-reference-generator/src/__tests__/files.test.ts @@ -0,0 +1,64 @@ +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"); + }); + + 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"); + }); +}); + +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/__tests__/verify.test.ts b/sdk-reference-generator/src/__tests__/verify.test.ts new file mode 100644 index 0000000..c31ea49 --- /dev/null +++ b/sdk-reference-generator/src/__tests__/verify.test.ts @@ -0,0 +1,158 @@ +import { describe, it, expect, beforeEach, afterEach } from 'vitest'; +import fs from 'fs-extra'; +import path from 'path'; +import os from 'os'; +import { verifyGeneratedDocs } 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' + ); + + // 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); + 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 via 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 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: [ + { + 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.docsJsonValid).toBe(true); + expect(result.valid).toBe(true); + }); + + it('fails when docs.json 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 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: [] }], + }, + }; + + await fs.writeJSON(path.join(tempDir, 'docs.json'), docsJson); + + const result = await verifyGeneratedDocs(tempDir); + expect(result.docsJsonValid).toBe(false); + expect(result.valid).toBe(false); + }); +}); + 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..c935684 --- /dev/null +++ b/sdk-reference-generator/src/cli.ts @@ -0,0 +1,138 @@ +#!/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 sdks from "../sdks.config.js"; +import { generateSDK } from "./generator.js"; +import { buildNavigation, mergeNavigation } from "./navigation.js"; +import { verifyGeneratedDocs } 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 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) + .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-")); + + 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 context: GenerationContext = { + tempDir, + docsDir: DOCS_DIR, + configsDir: CONFIGS_DIR, + limit: opts.limit, + force: opts.force, + }; + + try { + const sdkKeys = opts.sdk === "all" ? Object.keys(sdks) : [opts.sdk]; + + const results: Map = new Map(); + + for (const sdkKey of sdkKeys) { + log.section(`Generating ${sdkKey}`); + const result = await generateSDK(sdkKey, opts.version, context); + results.set(sdkKey, result); + } + + log.blank(); + log.section("Building navigation"); + const navigation = await buildNavigation(DOCS_DIR); + + 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("SDK reference generation complete"); + + let totalGenerated = 0; + let totalFailed = 0; + + for (const [sdkKey, result] of results) { + totalGenerated += result.generated; + totalFailed += result.failed; + } + + 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) => { + 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 new file mode 100644 index 0000000..04aebb0 --- /dev/null +++ b/sdk-reference-generator/src/generator.ts @@ -0,0 +1,314 @@ +import fs from "fs-extra"; +import path from "path"; +import type { + SDKConfig, + GenerationContext, + GenerationResult, +} from "./types.js"; +import sdks from "../sdks.config.js"; +import { log } from "./lib/log.js"; +import { fetchRemoteTags, resolveLatestVersion } from "./lib/git.js"; +import { + fetchLocalVersions, + filterByMinVersion, + diffVersions, + versionExists, +} from "./lib/versions.js"; +import { flattenMarkdown, copyToDocs, locateSDKDir } from "./lib/files.js"; +import { installDependencies } from "./lib/install.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"; + +async function generateVersion( + sdkKey: string, + config: SDKConfig, + version: string, + context: GenerationContext, + checkoutMgr: CheckoutManager, + isFirstVersion: boolean +): Promise { + 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)!; + } + + 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 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); + break; + case "cli": + generatedDocsDir = await generateCli(sdkDir); + break; + } + + if (generatedDocsDir !== sdkRefDir) { + log.info(`Normalizing ${path.basename(generatedDocsDir)} to sdk_ref`, 1); + await fs.move(generatedDocsDir, sdkRefDir, { overwrite: true }); + } + + await flattenMarkdown(sdkRefDir); + + 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"); + } +} + +async function discoverAllVersions( + sdkKey: string, + config: SDKConfig, + context: GenerationContext +): Promise { + log.info("Discovering all versions...", 1); + + let remote = await fetchRemoteTags(config.repo, config.tagPattern); + + 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 (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, context.docsDir); + + log.blank(); + log.step("Version Discovery", 1); + log.stats( + [ + { label: "Remote", value: remote.length }, + { label: "Local", value: local.length }, + ], + 1 + ); + + const missing = context.force ? remote : diffVersions(remote, local); + + 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 []; + } + + if (context.force && local.length > 0) { + log.warn("FORCE MODE: Will regenerate existing versions", 1); + } + + return missing; +} + +async function resolveSpecificVersion( + sdkKey: string, + config: SDKConfig, + versionArg: string, + context: GenerationContext +): Promise { + const resolved = await resolveLatestVersion( + config.repo, + config.tagPattern, + versionArg + ); + + if (!resolved) { + if (config.required) { + log.error("No tags found", 1); + process.exit(1); + } + log.warn("No tags found, skipping...", 1); + return []; + } + + if ( + !context.force && + (await versionExists(sdkKey, resolved, context.docsDir)) + ) { + log.success(`${resolved} already exists`, 1); + return []; + } + + 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[] = []; + + 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 }; +} + +function handleGenerationFailures( + config: SDKConfig, + result: GenerationResult +): void { + const { generated, failed, failedVersions } = result; + + log.blank(); + log.step("Summary", 1); + log.stats( + [ + { label: "Generated", value: generated }, + ...(failed > 0 + ? [ + { + label: "Failed", + value: `${failed} (${failedVersions.join(" ")})`, + }, + ] + : []), + ], + 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); + } +} + +export async function generateSDK( + sdkKey: string, + versionArg: string, + context: GenerationContext +): Promise { + const config = sdks[sdkKey as keyof typeof sdks]; + + 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/cli.ts b/sdk-reference-generator/src/generators/cli.ts new file mode 100644 index 0000000..d6fc9d9 --- /dev/null +++ b/sdk-reference-generator/src/generators/cli.ts @@ -0,0 +1,71 @@ +import { execa } from "execa"; +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"; + +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); + + try { + await execa("pnpm", ["run", "build"], { + cwd: sdkDir, + stdio: "inherit", + }); + } catch (error) { + log.warn("pnpm build failed, trying tsup...", 1); + await execa("npx", ["tsup"], { + cwd: sdkDir, + stdio: "inherit", + }); + } + + log.info("Generating documentation...", 1); + + 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) { + 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/pydoc.ts b/sdk-reference-generator/src/generators/pydoc.ts new file mode 100644 index 0000000..0e10258 --- /dev/null +++ b/sdk-reference-generator/src/generators/pydoc.ts @@ -0,0 +1,88 @@ +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 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_/, ""); + + log.step(`Processing ${pkg}`, 2); + + 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", + }); + + 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 (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; + } +} + +export async function generatePydoc( + sdkDir: string, + allowedPackages: readonly string[] +): Promise { + const outputDir = path.join(sdkDir, CONSTANTS.SDK_REF_DIR); + await fs.ensureDir(outputDir); + + log.info( + `Attempting to generate docs for ${allowedPackages.length} packages`, + 1 + ); + + let successful = 0; + for (const pkg of allowedPackages) { + const result = await processPackage(pkg, sdkDir); + if (result) successful++; + } + + log.step( + `Generated docs for ${successful}/${allowedPackages.length} packages`, + 1 + ); + + return outputDir; +} diff --git a/sdk-reference-generator/src/generators/typedoc.ts b/sdk-reference-generator/src/generators/typedoc.ts new file mode 100644 index 0000000..565d31b --- /dev/null +++ b/sdk-reference-generator/src/generators/typedoc.ts @@ -0,0 +1,70 @@ +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 { + const hasRepoConfig = await fs.pathExists(path.join(sdkDir, 'typedoc.json')); + const outputDir = await getTypedocOutputDir(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') + ); + + await execa( + 'npx', + [ + 'typedoc', + '--options', + './typedoc.docs.json', + '--plugin', + 'typedoc-plugin-markdown', + '--plugin', + path.join(configsDir, 'typedoc-theme.cjs'), + ], + { + cwd: sdkDir, + stdio: 'inherit', + } + ); + } + + return path.join(sdkDir, outputDir); +} 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/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..0ae9e3f --- /dev/null +++ b/sdk-reference-generator/src/lib/files.ts @@ -0,0 +1,212 @@ +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 ""; + + return str + .split("_") + .map((word) => word.charAt(0).toUpperCase() + word.slice(1)) + .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 +): Promise { + const content = await fs.readFile(file, "utf-8"); + + if (content.startsWith("---")) { + return; + } + + await fs.writeFile(file, createFrontmatter(title) + content); +} + +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", + }); + + 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, "-"); + + let targetName: string; + + 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)); + } + } + +async function removeEmptyDirectories(refDir: string): Promise { + 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 {} + } + } + +async function convertMdToMdx(refDir: string): Promise { + const mdFiles = await glob("*.md", { cwd: refDir }); + + for (const file of mdFiles) { + const fullPath = path.join(refDir, file); + const title = extractTitle(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); + } + } + +async function ensureFrontmatter(refDir: string): Promise { + 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 = extractTitle(path.basename(file, CONSTANTS.MDX_EXTENSION)); + await addFrontmatter(fullPath, title); + } + } +} + +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 { + const allFiles = await glob(`*${CONSTANTS.MDX_EXTENSION}`, { cwd: dir }); + const nonEmptyFiles: string[] = []; + + for (const file of allFiles) { + const stat = await fs.stat(path.join(dir, file)); + if (stat.size > 0) { + nonEmptyFiles.push(file); + } + } + + return nonEmptyFiles; +} + +export async function copyToDocs( + srcDir: string, + destDir: string, + sdkName: string, + version: string +): Promise { + const files = await getNonEmptyMdxFiles(srcDir); + + if (files.length === 0) { + log.error("No MDX files generated - doc generator failed", 1); + return false; + } + + await fs.ensureDir(destDir); + 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)); + } + + log.success(`${sdkName} ${version} complete`, 1); + 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..6fa8468 --- /dev/null +++ b/sdk-reference-generator/src/lib/git.ts @@ -0,0 +1,110 @@ +import { simpleGit, SimpleGit } from "simple-git"; +import { sortVersionsDescending } from "./utils.js"; +import { log } from "./log.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); +} + +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 { + 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( + repo: string, + tagPattern: string, + version: string +): Promise { + if (version !== "latest") { + return version; + } + + const versions = await fetchRemoteTags(repo, tagPattern); + return versions[0] || null; +} + +export async function checkoutTag(repoDir: string, tag: string): Promise { + const repoGit = simpleGit(repoDir); + + await repoGit.fetch([ + "origin", + `refs/tags/${tag}:refs/tags/${tag}`, + "--depth", + "1", + ]); + + await repoGit.checkout(tag, ["--force"]); + + await repoGit.clean("f", ["-d"]); +} diff --git a/sdk-reference-generator/src/lib/install.ts b/sdk-reference-generator/src/lib/install.ts new file mode 100644 index 0000000..b6b2ee0 --- /dev/null +++ b/sdk-reference-generator/src/lib/install.ts @@ -0,0 +1,58 @@ +import { execa } from "execa"; +import type { GeneratorType } from "../types.js"; +import { log } from "./log.js"; + +export async function installDependencies( + sdkDir: string, + generator: GeneratorType +): Promise { + log.info("Installing dependencies...", 1); + + switch (generator) { + case "typedoc": + case "cli": { + const isTypedoc = generator === "typedoc"; + const pnpmArgs = isTypedoc + ? ["install", "--ignore-scripts", "--prefer-offline"] + : ["install", "--prefer-offline"]; + + try { + await execa("pnpm", pnpmArgs, { + cwd: sdkDir, + stdio: "inherit", + }); + } catch { + log.warn("pnpm failed, falling back to npm...", 1); + await execa( + "npm", + ["install", "--legacy-peer-deps", "--force", "--prefer-offline"], + { + cwd: sdkDir, + stdio: "inherit", + } + ); + } + break; + } + + case "pydoc": { + try { + await execa("poetry", ["install", "--no-interaction"], { + cwd: sdkDir, + stdio: "inherit", + }); + } catch { + log.warn("poetry failed, using global pydoc-markdown...", 1); + await execa( + "pip", + ["install", "--break-system-packages", "pydoc-markdown"], + { + cwd: sdkDir, + stdio: "inherit", + } + ); + } + break; + } + } +} 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/utils.ts b/sdk-reference-generator/src/lib/utils.ts new file mode 100644 index 0000000..ee8f112 --- /dev/null +++ b/sdk-reference-generator/src/lib/utils.ts @@ -0,0 +1,42 @@ +import semver from "semver"; +import path from "path"; +import { CONSTANTS } from "./constants.js"; + +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(stripVersionPrefix(a), stripVersionPrefix(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/verify.ts b/sdk-reference-generator/src/lib/verify.ts new file mode 100644 index 0000000..130ff9f --- /dev/null +++ b/sdk-reference-generator/src/lib/verify.ts @@ -0,0 +1,132 @@ +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; + }; + docsJsonValid: boolean; +} + +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, docsJsonValid: false }; + } + + 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}` + ); + } + } + } + } + } + + // verify docs.json + const docsJsonValid = await verifyDocsJson(docsDir); + + return { + valid: errors.length === 0 && docsJsonValid, + errors, + warnings, + stats, + docsJsonValid, + }; +} + +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/lib/versions.ts b/sdk-reference-generator/src/lib/versions.ts new file mode 100644 index 0000000..595cf8c --- /dev/null +++ b/sdk-reference-generator/src/lib/versions.ts @@ -0,0 +1,73 @@ +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'; + +export { isValidVersion }; + +export function versionGte(v1: string, v2: string): boolean { + try { + return semver.gte(stripVersionPrefix(v1), stripVersionPrefix(v2)); + } catch { + return stripVersionPrefix(v1) >= stripVersionPrefix(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..0a2145b --- /dev/null +++ b/sdk-reference-generator/src/navigation.ts @@ -0,0 +1,162 @@ +import fs from "fs-extra"; +import path from "path"; +import sdks from "../sdks.config.js"; +import { + sortVersionsDescending, + isValidVersion, + normalizeVersion, +} from "./lib/utils.js"; +import { CONSTANTS } from "./lib/constants.js"; +import { log } from "./lib/log.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) => e.isDirectory() && isValidVersion(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 sdkRefDir = path.join(docsDir, CONSTANTS.DOCS_SDK_REF_PATH); + + if (!(await fs.pathExists(sdkRefDir))) { + log.warn(`SDK reference directory not found: ${sdkRefDir}`); + return []; + } + + const navigation: NavigationDropdownWithOrder[] = []; + + for (const [sdkKey, sdkConfig] of Object.entries(sdks)) { + const sdkDir = path.join(sdkRefDir, sdkKey); + + if (!(await fs.pathExists(sdkDir))) { + log.data(`Skipping ${sdkKey} (not found)`); + continue; + } + + const versions = await getVersions(sdkDir); + if (versions.length === 0) { + log.data(`Skipping ${sdkKey} (no versions)`); + continue; + } + + log.data(`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); + + return { + version: normalizeVersion(version), + 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))) { + log.error("docs.json not found"); + process.exit(1); + } + + const docsJson = await fs.readJSON(docsJsonPath); + + const anchors = docsJson.navigation?.anchors; + if (!anchors) { + log.error("No anchors found in docs.json"); + process.exit(1); + } + + const validDropdowns = navigation.filter( + (d) => d.versions && d.versions.length > 0 + ); + + if (validDropdowns.length === 0) { + log.warn("No SDK versions found, keeping existing docs.json"); + return; + } + + 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"); + } + + log.success(`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 + ); + log.data( + `${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..2953b1e --- /dev/null +++ b/sdk-reference-generator/src/types.ts @@ -0,0 +1,62 @@ +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"; + allowedPackages: readonly string[]; +}; + +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; + docsDir: string; + configsDir: string; + limit?: number; + force?: boolean; +} + +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..33193b1 --- /dev/null +++ b/sdk-reference-generator/tsconfig.json @@ -0,0 +1,17 @@ +{ + "compilerOptions": { + "target": "ES2022", + "module": "NodeNext", + "moduleResolution": "NodeNext", + "esModuleInterop": true, + "strict": true, + "skipLibCheck": true, + "outDir": "dist", + "declaration": true, + "resolveJsonModule": true, + "allowSyntheticDefaultImports": true + }, + "include": ["src/**/*", "sdks.config.ts"], + "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', + }, +}); + diff --git a/style.css b/style.css index 490a779..e4c3329 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: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 */ + border-radius: 6px !important; + padding: 0.5rem 1rem !important; + font-weight: 500 !important; + transition: all 0.2s ease !important; +} + +#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: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: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; +}