Skip to content

Commit 670b2e0

Browse files
Document generic types for extending Sandbox class
Update API documentation to reflect TypeScript generic type parameters added to getSandbox(), SandboxEnv, and proxyToSandbox(). These changes fix type errors when extending the Sandbox class with custom methods. Changes: - Update getSandbox() signature to show generic type parameter - Add section on extending Sandbox class with example - Document proxyToSandbox() function with generic types - Document SandboxEnv type helper for custom Sandbox classes Related to cloudflare/sandbox-sdk#264 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-Authored-By: Claude <noreply@anthropic.com>
1 parent 1b95f6e commit 670b2e0

File tree

2 files changed

+90
-4
lines changed

2 files changed

+90
-4
lines changed

src/content/docs/sandbox/api/lifecycle.mdx

Lines changed: 41 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -16,11 +16,11 @@ Create and manage sandbox containers. Get sandbox instances, configure options,
1616
Get or create a sandbox instance by ID.
1717

1818
```ts
19-
const sandbox = getSandbox(
20-
binding: DurableObjectNamespace<Sandbox>,
19+
function getSandbox<T extends Sandbox<any>>(
20+
binding: DurableObjectNamespace<T>,
2121
sandboxId: string,
2222
options?: SandboxOptions
23-
): Sandbox
23+
): T
2424
```
2525

2626
**Parameters**:
@@ -32,7 +32,10 @@ const sandbox = getSandbox(
3232
- `containerTimeouts` - Configure container startup timeouts
3333
- `normalizeId` - Lowercase sandbox IDs for preview URL compatibility (default: `false`)
3434

35-
**Returns**: `Sandbox` instance
35+
**Returns**: Sandbox instance (type `T`, which defaults to `Sandbox`)
36+
37+
**Type parameter**:
38+
- `T extends Sandbox<any>` - The Sandbox class type. Use this when extending the Sandbox class with custom methods to get proper type inference.
3639

3740
:::note
3841
The container starts lazily on first operation. Calling `getSandbox()` returns immediatelythe container only spins up when you execute a command, write a file, or perform other operations. See [Sandbox lifecycle](/sandbox/concepts/sandboxes/) for details.
@@ -56,6 +59,40 @@ export default {
5659
When using `keepAlive: true`, you **must** call `destroy()` when finished to prevent containers running indefinitely.
5760
:::
5861

62+
#### Extending the Sandbox class
63+
64+
You can extend the Sandbox class to add custom methods. The generic type parameter ensures proper type inference:
65+
66+
<TypeScriptExample>
67+
```
68+
import { getSandbox, Sandbox, type SandboxEnv } from '@cloudflare/sandbox';
69+
70+
// Define your extended Sandbox class
71+
export class CustomSandbox extends Sandbox<CustomSandbox> {
72+
async runTests(): Promise<{ passed: number; failed: number }> {
73+
const result = await this.exec('npm test');
74+
// Parse test output
75+
return { passed: 10, failed: 0 };
76+
}
77+
}
78+
79+
// Export your custom class as the Durable Object
80+
export { CustomSandbox as Sandbox };
81+
82+
// Define environment with your custom class
83+
type Env = SandboxEnv<CustomSandbox>;
84+
85+
export default {
86+
async fetch(request: Request, env: Env): Promise<Response> {
87+
// getSandbox now returns CustomSandbox type with runTests() available
88+
const sandbox = getSandbox(env.Sandbox, 'my-sandbox');
89+
const testResults = await sandbox.runTests();
90+
return Response.json(testResults);
91+
}
92+
};
93+
```
94+
</TypeScriptExample>
95+
5996
---
6097

6198
### `destroy()`

src/content/docs/sandbox/api/ports.mdx

Lines changed: 49 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -134,6 +134,55 @@ export default {
134134
```
135135
</TypeScriptExample>
136136

137+
### `proxyToSandbox()`
138+
139+
Route incoming requests to exposed sandbox ports via preview URLs. This function must be called first in your Worker's fetch handler to enable preview URL routing.
140+
141+
```ts
142+
function proxyToSandbox<
143+
T extends Sandbox<any>,
144+
E extends SandboxEnv<T>
145+
>(request: Request, env: E): Promise<Response | null>
146+
```
147+
148+
**Parameters**:
149+
150+
- `request` - Incoming request to potentially route
151+
- `env` - Worker environment binding with Sandbox namespace
152+
153+
**Returns**: `Promise<Response | null>` - Response if the request matches a preview URL pattern, or `null` if not a preview URL request
154+
155+
**Type parameters**:
156+
- `T extends Sandbox<any>` - The Sandbox class type (useful when extending Sandbox)
157+
- `E extends SandboxEnv<T>` - Environment type with Sandbox namespace binding
158+
159+
<TypeScriptExample>
160+
```ts
161+
import { getSandbox, proxyToSandbox, type SandboxEnv } from "@cloudflare/sandbox";
162+
163+
export { Sandbox } from "@cloudflare/sandbox";
164+
165+
type Env = SandboxEnv;
166+
167+
export default {
168+
async fetch(request: Request, env: Env): Promise<Response> {
169+
// Route preview URL requests first
170+
const proxyResponse = await proxyToSandbox(request, env);
171+
if (proxyResponse) return proxyResponse;
172+
173+
// Your application routes
174+
const sandbox = getSandbox(env.Sandbox, 'my-sandbox');
175+
// ...
176+
return new Response('OK');
177+
}
178+
};
179+
```
180+
</TypeScriptExample>
181+
182+
:::note
183+
When extending the Sandbox class, use the type parameters to maintain type safety. See [Extending the Sandbox class](/sandbox/api/lifecycle/#extending-the-sandbox-class) for examples.
184+
:::
185+
137186
## Related resources
138187

139188
- [Preview URLs concept](/sandbox/concepts/preview-urls/) - How preview URLs work

0 commit comments

Comments
 (0)