Skip to content

Commit 8601b5c

Browse files
Fix type error when extending Sandbox class (#264)
* Make getSandbox and SandboxEnv generic for subclasses Fixes type error when extending Sandbox class. DurableObjectNamespace<T> is invariant, so getSandbox needed to be generic to accept subclass namespaces. * Add changeset
1 parent 204f9ac commit 8601b5c

File tree

3 files changed

+16
-11
lines changed

3 files changed

+16
-11
lines changed
Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
---
2+
'@cloudflare/sandbox': patch
3+
---
4+
5+
Fix type error when extending Sandbox class by making getSandbox and SandboxEnv generic

packages/sandbox/src/request-handler.ts

Lines changed: 6 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -3,8 +3,8 @@ import { createLogger, type LogContext, TraceContext } from '@repo/shared';
33
import { getSandbox, type Sandbox } from './sandbox';
44
import { sanitizeSandboxId, validatePort } from './security';
55

6-
export interface SandboxEnv {
7-
Sandbox: DurableObjectNamespace<Sandbox>;
6+
export interface SandboxEnv<T extends Sandbox<any> = Sandbox<any>> {
7+
Sandbox: DurableObjectNamespace<T>;
88
}
99

1010
export interface RouteInfo {
@@ -14,10 +14,10 @@ export interface RouteInfo {
1414
token: string;
1515
}
1616

17-
export async function proxyToSandbox<E extends SandboxEnv>(
18-
request: Request,
19-
env: E
20-
): Promise<Response | null> {
17+
export async function proxyToSandbox<
18+
T extends Sandbox<any>,
19+
E extends SandboxEnv<T>
20+
>(request: Request, env: E): Promise<Response | null> {
2121
// Create logger context for this request
2222
const traceId =
2323
TraceContext.fromHeaders(request.headers) || TraceContext.generate();

packages/sandbox/src/sandbox.ts

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -45,11 +45,11 @@ import {
4545
import type { MountInfo } from './storage-mount/types';
4646
import { SDK_VERSION } from './version';
4747

48-
export function getSandbox(
49-
ns: DurableObjectNamespace<Sandbox>,
48+
export function getSandbox<T extends Sandbox<any>>(
49+
ns: DurableObjectNamespace<T>,
5050
id: string,
5151
options?: SandboxOptions
52-
): Sandbox {
52+
): T {
5353
const sanitizedId = sanitizeSandboxId(id);
5454
const effectiveId = options?.normalizeId
5555
? sanitizedId.toLowerCase()
@@ -65,7 +65,7 @@ export function getSandbox(
6565
);
6666
}
6767

68-
const stub = getContainer(ns, effectiveId) as unknown as Sandbox;
68+
const stub = getContainer(ns, effectiveId);
6969

7070
stub.setSandboxName?.(effectiveId, options?.normalizeId);
7171

@@ -87,7 +87,7 @@ export function getSandbox(
8787

8888
return Object.assign(stub, {
8989
wsConnect: connect(stub)
90-
});
90+
}) as T;
9191
}
9292

9393
export function connect(stub: {

0 commit comments

Comments
 (0)