Skip to content

Commit 99c717e

Browse files
Add docs for Sandbox SDK (#25791)
* Add landing page for sandbox SDK * Add first turorial * Start with API reference * Complete v1 of API reference * Use TypeScriptExample component * Fix broken code snippets * Update codeowners * Add how-to guides * Add concepts * Fix syntax errors * Add tutorials * Simplify configuration reference * Simplify guides * Remove unnecessary prerequisites * Simplify concepts * Cleanup API reference * Update icons * Simplify getting started page * Update code executor example * Update tutorials * Fix frontmatter * Fix links
1 parent db9b73f commit 99c717e

35 files changed

+5304
-0
lines changed

.github/CODEOWNERS

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -138,6 +138,7 @@
138138
/src/content/docs/workers/observability/ @irvinebroque @mikenomitch @rohinlohe @kodster28 @cloudflare/pcx-technical-writing
139139
/src/content/docs/workers/static-assets @irvinebroque @GregBrimble @WalshyDev @kodster28 @cloudflare/deploy-config @cloudflare/pcx-technical-writing
140140
/src/content/docs/workflows/ @elithrar @celso @cloudflare/pcx-technical-writing
141+
/src/content/docs/sandbox/ @whoiskatrin @ghostwriternr @cloudflare/pcx-technical-writing @ai-agents
141142

142143
# DDoS Protection
143144

Lines changed: 219 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,219 @@
1+
---
2+
title: Commands
3+
pcx_content_type: concept
4+
sidebar:
5+
order: 1
6+
---
7+
8+
import { Details, TypeScriptExample } from "~/components";
9+
10+
Execute commands and manage background processes in the sandbox's isolated container environment.
11+
12+
## Methods
13+
14+
### `exec()`
15+
16+
Execute a command and return the complete result.
17+
18+
```ts
19+
const result = await sandbox.exec(command: string, options?: ExecOptions): Promise<ExecuteResponse>
20+
```
21+
22+
**Parameters**:
23+
- `command` - The command to execute (can include arguments)
24+
- `options` (optional):
25+
- `stream` - Enable streaming callbacks (default: `false`)
26+
- `onOutput` - Callback for real-time output: `(stream: 'stdout' | 'stderr', data: string) => void`
27+
- `timeout` - Maximum execution time in milliseconds
28+
29+
**Returns**: `Promise<ExecuteResponse>` with `success`, `stdout`, `stderr`, `exitCode`
30+
31+
<TypeScriptExample>
32+
```
33+
const result = await sandbox.exec('npm run build');
34+
35+
if (result.success) {
36+
console.log('Build output:', result.stdout);
37+
} else {
38+
console.error('Build failed:', result.stderr);
39+
}
40+
41+
// With streaming
42+
await sandbox.exec('npm install', {
43+
stream: true,
44+
onOutput: (stream, data) => console.log(`[${stream}] ${data}`)
45+
});
46+
```
47+
</TypeScriptExample>
48+
49+
### `execStream()`
50+
51+
Execute a command and return a Server-Sent Events stream for real-time processing.
52+
53+
```ts
54+
const stream = await sandbox.execStream(command: string, options?: ExecOptions): Promise<ReadableStream>
55+
```
56+
57+
**Parameters**:
58+
- `command` - The command to execute
59+
- `options` - Same as `exec()`
60+
61+
**Returns**: `Promise<ReadableStream>` emitting `ExecEvent` objects (`start`, `stdout`, `stderr`, `complete`, `error`)
62+
63+
<TypeScriptExample>
64+
```
65+
import { parseSSEStream, type ExecEvent } from '@cloudflare/sandbox';
66+
67+
const stream = await sandbox.execStream('npm run build');
68+
69+
for await (const event of parseSSEStream<ExecEvent>(stream)) {
70+
switch (event.type) {
71+
case 'stdout':
72+
console.log('Output:', event.data);
73+
break;
74+
case 'complete':
75+
console.log('Exit code:', event.exitCode);
76+
break;
77+
case 'error':
78+
console.error('Failed:', event.error);
79+
break;
80+
}
81+
}
82+
```
83+
</TypeScriptExample>
84+
85+
### `startProcess()`
86+
87+
Start a long-running background process.
88+
89+
```ts
90+
const process = await sandbox.startProcess(command: string, options?: ProcessOptions): Promise<ProcessInfo>
91+
```
92+
93+
**Parameters**:
94+
- `command` - The command to start as a background process
95+
- `options` (optional):
96+
- `cwd` - Working directory
97+
- `env` - Environment variables
98+
99+
**Returns**: `Promise<ProcessInfo>` with `id`, `pid`, `command`, `status`
100+
101+
<TypeScriptExample>
102+
```
103+
const server = await sandbox.startProcess('python -m http.server 8000');
104+
console.log('Started with PID:', server.pid);
105+
106+
// With custom environment
107+
const app = await sandbox.startProcess('node app.js', {
108+
cwd: '/workspace/my-app',
109+
env: { NODE_ENV: 'production', PORT: '3000' }
110+
});
111+
```
112+
</TypeScriptExample>
113+
114+
### `listProcesses()`
115+
116+
List all running processes.
117+
118+
```ts
119+
const processes = await sandbox.listProcesses(): Promise<ProcessInfo[]>
120+
```
121+
122+
<TypeScriptExample>
123+
```
124+
const processes = await sandbox.listProcesses();
125+
126+
for (const proc of processes) {
127+
console.log(`${proc.id}: ${proc.command} (PID ${proc.pid})`);
128+
}
129+
```
130+
</TypeScriptExample>
131+
132+
### `killProcess()`
133+
134+
Terminate a specific process.
135+
136+
```ts
137+
await sandbox.killProcess(processId: string, signal?: string): Promise<void>
138+
```
139+
140+
**Parameters**:
141+
- `processId` - The process ID (from `startProcess()` or `listProcesses()`)
142+
- `signal` - Signal to send (default: `"SIGTERM"`)
143+
144+
<TypeScriptExample>
145+
```
146+
const server = await sandbox.startProcess('python -m http.server 8000');
147+
await sandbox.killProcess(server.id);
148+
```
149+
</TypeScriptExample>
150+
151+
### `killAllProcesses()`
152+
153+
Terminate all running processes.
154+
155+
```ts
156+
await sandbox.killAllProcesses(): Promise<void>
157+
```
158+
159+
<TypeScriptExample>
160+
```
161+
await sandbox.killAllProcesses();
162+
```
163+
</TypeScriptExample>
164+
165+
### `streamProcessLogs()`
166+
167+
Stream logs from a running process in real-time.
168+
169+
```ts
170+
const stream = await sandbox.streamProcessLogs(processId: string): Promise<ReadableStream>
171+
```
172+
173+
**Parameters**:
174+
- `processId` - The process ID
175+
176+
**Returns**: `Promise<ReadableStream>` emitting `LogEvent` objects
177+
178+
<TypeScriptExample>
179+
```
180+
import { parseSSEStream, type LogEvent } from '@cloudflare/sandbox';
181+
182+
const server = await sandbox.startProcess('node server.js');
183+
const logStream = await sandbox.streamProcessLogs(server.id);
184+
185+
for await (const log of parseSSEStream<LogEvent>(logStream)) {
186+
console.log(`[${log.timestamp}] ${log.data}`);
187+
188+
if (log.data.includes('Server started')) break;
189+
}
190+
```
191+
</TypeScriptExample>
192+
193+
### `getProcessLogs()`
194+
195+
Get accumulated logs from a process.
196+
197+
```ts
198+
const logs = await sandbox.getProcessLogs(processId: string): Promise<string>
199+
```
200+
201+
**Parameters**:
202+
- `processId` - The process ID
203+
204+
**Returns**: `Promise<string>` with all accumulated output
205+
206+
<TypeScriptExample>
207+
```
208+
const server = await sandbox.startProcess('node server.js');
209+
await new Promise(resolve => setTimeout(resolve, 5000));
210+
211+
const logs = await sandbox.getProcessLogs(server.id);
212+
console.log('Server logs:', logs);
213+
```
214+
</TypeScriptExample>
215+
216+
## Related resources
217+
218+
- [Background processes guide](/sandbox/guides/background-processes/) - Managing long-running processes
219+
- [Files API](/sandbox/api/files/) - File operations
Lines changed: 167 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,167 @@
1+
---
2+
title: Files
3+
pcx_content_type: concept
4+
sidebar:
5+
order: 2
6+
---
7+
8+
import { TypeScriptExample } from "~/components";
9+
10+
Read, write, and manage files in the sandbox filesystem. All paths are absolute (e.g., `/workspace/app.js`).
11+
12+
## Methods
13+
14+
### `writeFile()`
15+
16+
Write content to a file.
17+
18+
```ts
19+
await sandbox.writeFile(path: string, content: string, options?: WriteFileOptions): Promise<void>
20+
```
21+
22+
**Parameters**:
23+
- `path` - Absolute path to the file
24+
- `content` - Content to write
25+
- `options` (optional):
26+
- `encoding` - File encoding (default: `"utf-8"`)
27+
28+
<TypeScriptExample>
29+
```
30+
await sandbox.writeFile('/workspace/app.js', `console.log('Hello!');`);
31+
32+
// Binary data
33+
await sandbox.writeFile('/tmp/image.png', base64Data, { encoding: 'base64' });
34+
```
35+
</TypeScriptExample>
36+
37+
### `readFile()`
38+
39+
Read a file from the sandbox.
40+
41+
```ts
42+
const file = await sandbox.readFile(path: string, options?: ReadFileOptions): Promise<FileInfo>
43+
```
44+
45+
**Parameters**:
46+
- `path` - Absolute path to the file
47+
- `options` (optional):
48+
- `encoding` - File encoding (default: `"utf-8"`)
49+
50+
**Returns**: `Promise<FileInfo>` with `content` and `encoding`
51+
52+
<TypeScriptExample>
53+
```
54+
const file = await sandbox.readFile('/workspace/package.json');
55+
const pkg = JSON.parse(file.content);
56+
57+
// Binary data
58+
const image = await sandbox.readFile('/tmp/image.png', { encoding: 'base64' });
59+
```
60+
</TypeScriptExample>
61+
62+
### `mkdir()`
63+
64+
Create a directory.
65+
66+
```ts
67+
await sandbox.mkdir(path: string, options?: MkdirOptions): Promise<void>
68+
```
69+
70+
**Parameters**:
71+
- `path` - Absolute path to the directory
72+
- `options` (optional):
73+
- `recursive` - Create parent directories if needed (default: `false`)
74+
75+
<TypeScriptExample>
76+
```
77+
await sandbox.mkdir('/workspace/src');
78+
79+
// Nested directories
80+
await sandbox.mkdir('/workspace/src/components/ui', { recursive: true });
81+
```
82+
</TypeScriptExample>
83+
84+
### `deleteFile()`
85+
86+
Delete a file.
87+
88+
```ts
89+
await sandbox.deleteFile(path: string): Promise<void>
90+
```
91+
92+
**Parameters**:
93+
- `path` - Absolute path to the file
94+
95+
<TypeScriptExample>
96+
```
97+
await sandbox.deleteFile('/workspace/temp.txt');
98+
```
99+
</TypeScriptExample>
100+
101+
### `renameFile()`
102+
103+
Rename a file.
104+
105+
```ts
106+
await sandbox.renameFile(oldPath: string, newPath: string): Promise<void>
107+
```
108+
109+
**Parameters**:
110+
- `oldPath` - Current file path
111+
- `newPath` - New file path
112+
113+
<TypeScriptExample>
114+
```
115+
await sandbox.renameFile('/workspace/draft.txt', '/workspace/final.txt');
116+
```
117+
</TypeScriptExample>
118+
119+
### `moveFile()`
120+
121+
Move a file to a different directory.
122+
123+
```ts
124+
await sandbox.moveFile(sourcePath: string, destinationPath: string): Promise<void>
125+
```
126+
127+
**Parameters**:
128+
- `sourcePath` - Current file path
129+
- `destinationPath` - Destination path
130+
131+
<TypeScriptExample>
132+
```
133+
await sandbox.moveFile('/tmp/download.txt', '/workspace/data.txt');
134+
```
135+
</TypeScriptExample>
136+
137+
### `gitCheckout()`
138+
139+
Clone a git repository.
140+
141+
```ts
142+
await sandbox.gitCheckout(repoUrl: string, options?: GitCheckoutOptions): Promise<void>
143+
```
144+
145+
**Parameters**:
146+
- `repoUrl` - Git repository URL
147+
- `options` (optional):
148+
- `branch` - Branch to checkout (default: main branch)
149+
- `targetDir` - Directory to clone into (default: repo name)
150+
- `depth` - Clone depth for shallow clone
151+
152+
<TypeScriptExample>
153+
```
154+
await sandbox.gitCheckout('https://github.com/user/repo');
155+
156+
// Specific branch
157+
await sandbox.gitCheckout('https://github.com/user/repo', {
158+
branch: 'develop',
159+
targetDir: 'my-project'
160+
});
161+
```
162+
</TypeScriptExample>
163+
164+
## Related resources
165+
166+
- [Manage files guide](/sandbox/guides/manage-files/) - Detailed guide with best practices
167+
- [Commands API](/sandbox/api/commands/) - Execute commands

0 commit comments

Comments
 (0)