@cloudflare/sandbox 0.13.0-next.776.1 → 1.0.0-rc.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (63) hide show
  1. package/README.md +62 -219
  2. package/dist/index.d.mts +548 -0
  3. package/dist/index.mjs +2452 -0
  4. package/package.json +17 -118
  5. package/Dockerfile +0 -368
  6. package/dist/bridge/index.d.ts +0 -181
  7. package/dist/bridge/index.d.ts.map +0 -1
  8. package/dist/bridge/index.js +0 -3053
  9. package/dist/bridge/index.js.map +0 -1
  10. package/dist/contexts-1EsLHByO.d.ts +0 -463
  11. package/dist/contexts-1EsLHByO.d.ts.map +0 -1
  12. package/dist/dist-Duor5GbS.js +0 -752
  13. package/dist/dist-Duor5GbS.js.map +0 -1
  14. package/dist/errors/index.d.ts +0 -4
  15. package/dist/errors/index.js +0 -4
  16. package/dist/errors-CXR0xBpw.js +0 -285
  17. package/dist/errors-CXR0xBpw.js.map +0 -1
  18. package/dist/errors-QYlSkVGz.js +0 -893
  19. package/dist/errors-QYlSkVGz.js.map +0 -1
  20. package/dist/extensions/index.d.ts +0 -4
  21. package/dist/extensions/index.js +0 -6
  22. package/dist/extensions-CFB2xHqY.js +0 -1023
  23. package/dist/extensions-CFB2xHqY.js.map +0 -1
  24. package/dist/filesystem-BWAZCZER.d.ts +0 -732
  25. package/dist/filesystem-BWAZCZER.d.ts.map +0 -1
  26. package/dist/git/index.d.ts +0 -63
  27. package/dist/git/index.d.ts.map +0 -1
  28. package/dist/git/index.js +0 -338
  29. package/dist/git/index.js.map +0 -1
  30. package/dist/index-Bs4bqXDR.d.ts +0 -438
  31. package/dist/index-Bs4bqXDR.d.ts.map +0 -1
  32. package/dist/index-HNYBk-az.d.ts +0 -444
  33. package/dist/index-HNYBk-az.d.ts.map +0 -1
  34. package/dist/index.d.ts +0 -576
  35. package/dist/index.d.ts.map +0 -1
  36. package/dist/index.js +0 -33
  37. package/dist/index.js.map +0 -1
  38. package/dist/interpreter/index.d.ts +0 -311
  39. package/dist/interpreter/index.d.ts.map +0 -1
  40. package/dist/interpreter/index.js +0 -292
  41. package/dist/interpreter/index.js.map +0 -1
  42. package/dist/openai/index.d.ts +0 -68
  43. package/dist/openai/index.d.ts.map +0 -1
  44. package/dist/openai/index.js +0 -367
  45. package/dist/openai/index.js.map +0 -1
  46. package/dist/opencode/index.d.ts +0 -182
  47. package/dist/opencode/index.d.ts.map +0 -1
  48. package/dist/opencode/index.js +0 -454
  49. package/dist/opencode/index.js.map +0 -1
  50. package/dist/process-types-GStiZ8f8.d.ts +0 -73
  51. package/dist/process-types-GStiZ8f8.d.ts.map +0 -1
  52. package/dist/sandbox-BbAabq93.d.ts +0 -42
  53. package/dist/sandbox-BbAabq93.d.ts.map +0 -1
  54. package/dist/sandbox-cmlgGVYX.js +0 -10056
  55. package/dist/sandbox-cmlgGVYX.js.map +0 -1
  56. package/dist/sidecar/index.d.ts +0 -77
  57. package/dist/sidecar/index.d.ts.map +0 -1
  58. package/dist/sidecar/index.js +0 -201
  59. package/dist/sidecar/index.js.map +0 -1
  60. package/dist/xterm/index.d.ts +0 -93
  61. package/dist/xterm/index.d.ts.map +0 -1
  62. package/dist/xterm/index.js +0 -220
  63. package/dist/xterm/index.js.map +0 -1
package/dist/index.d.ts DELETED
@@ -1,576 +0,0 @@
1
- import { H as RPCTransportErrorKind, V as RPCTransportContext, Z as ErrorCode } from "./contexts-1EsLHByO.js";
2
- import { c as WaitForLogResult, i as ProcessLogEvent, n as ProcessFailure, o as ProcessStatus, r as ProcessLogCursor, s as SandboxCommand, t as ProcessExit } from "./process-types-GStiZ8f8.js";
3
- import { A as CreateTerminalOptions, C as BucketCredentials, D as MountBucketOptions, E as LocalMountBucketOptions, F as TerminalOutputOptions, G as ProcessTextOutputOptions, H as ProcessLogsOptions, I as TerminalOutputSubscriptionAPI, J as WaitForExitOptions, K as SandboxOptions, L as TerminalSnapshot, M as Terminal, N as TerminalOutputCursor, O as RemoteMountBucketOptions, P as TerminalOutputEvent, R as ExecOptions, S as BackupOptions, T as DirectoryBackup, U as ProcessOutput, W as ProcessOutputOptions, X as WaitForPortOptions, Y as WaitForLogOptions, _ as RenameFileResult, a as FileChunk, b as WriteFileResult, c as FileMetadata, d as ListFilesOptions, f as ListFilesResult, g as ReadFileStreamResult, h as ReadFileResult, i as DeleteFileResult, k as RestoreBackupResult, l as FileStreamEvent, m as MoveFileResult, o as FileEncoding, p as MkdirResult, q as SandboxProcess, r as CheckChangesResult, s as FileExistsResult, t as CheckChangesOptions, u as FileWatchSSEEvent, v as WatchOptions, w as BucketProvider } from "./filesystem-BWAZCZER.js";
4
- import { t as ISandbox } from "./sandbox-BbAabq93.js";
5
- import { _ as QuickTunnelInfo, d as sandboxRuntimeCall, f as ProcessPullSubscriptionRPC, g as NamedTunnelInfo, n as ExtensionRuntimeCall, p as ProcessRPCDescriptor, s as HTTPAuthInterceptorParams, v as TunnelInfo, y as TunnelOptions } from "./index-Bs4bqXDR.js";
6
- import { $ as TerminalNotFoundError, G as ContainerUnavailableError, H as BackupExpiredError, J as InvalidTerminalCwdError, K as InvalidBackupConfigError, Q as TerminalControlError, U as BackupNotFoundError, V as BackupCreateError, W as BackupRestoreError, X as RPCTransportError, Y as OperationInterruptedError, Z as StaleTerminalHandleError, a as InvalidProcessCursorError, c as ProcessAbortedError, d as ProcessExitedBeforeReadyError, f as ProcessNotFoundError, g as StaleProcessHandleError, h as ProcessWaitTimeoutError, l as ProcessError, m as ProcessSpawnFailedError, n as RuntimeControlProtocolError, o as InvalidProcessCwdError, p as ProcessReadyTimeoutError, q as InvalidTerminalCursorError, s as InvalidProcessEnvironmentError, t as RuntimeIdentityInactiveError, u as ProcessExitedBeforeLogError } from "./index-HNYBk-az.js";
7
- import { Container, ContainerProxy as ContainerProxy$1, ContainerStartConfigOptions } from "@cloudflare/containers";
8
- import { RpcTarget, RpcTransport } from "capnweb";
9
-
10
- //#region src/file-stream.d.ts
11
-
12
- /**
13
- * Stream a file from the sandbox with automatic base64 decoding for binary files
14
- *
15
- * @param stream - The ReadableStream from readFileStream()
16
- * @returns AsyncGenerator that yields FileChunk (string for text, Uint8Array for binary)
17
- *
18
- * @example
19
- * ```ts
20
- * const stream = await sandbox.readFileStream('/path/to/file.png');
21
- * for await (const chunk of streamFile(stream)) {
22
- * if (chunk instanceof Uint8Array) {
23
- * // Binary chunk
24
- * console.log('Binary chunk:', chunk.length, 'bytes');
25
- * } else {
26
- * // Text chunk
27
- * console.log('Text chunk:', chunk);
28
- * }
29
- * }
30
- * ```
31
- */
32
- declare function streamFile(stream: ReadableStream<Uint8Array>): AsyncGenerator<FileChunk, FileMetadata>;
33
- /**
34
- * Collect an entire file into memory from a stream
35
- *
36
- * @param stream - The ReadableStream from readFileStream()
37
- * @returns Object containing the file content and metadata
38
- *
39
- * @example
40
- * ```ts
41
- * const stream = await sandbox.readFileStream('/path/to/file.txt');
42
- * const { content, metadata } = await collectFile(stream);
43
- * console.log('Content:', content);
44
- * console.log('MIME type:', metadata.mimeType);
45
- * ```
46
- */
47
- declare function collectFile(stream: ReadableStream<Uint8Array>): Promise<{
48
- content: string | Uint8Array;
49
- metadata: FileMetadata;
50
- }>;
51
- //#endregion
52
- //#region src/platform-errors.d.ts
53
- /**
54
- * Whether an error was raised because the current Durable Object isolate was
55
- * superseded by a deploy/code update. In-process retries are futile for this
56
- * class because the invocation keeps running on the old isolate; callers
57
- * should return control to the platform or retry from a fresh request.
58
- */
59
- declare function isDurableObjectCodeUpdateReset(error: unknown): boolean;
60
- /**
61
- * Whether an error represents a transient platform lifecycle/storage failure,
62
- * not an application-level sandbox failure.
63
- */
64
- declare function isPlatformTransientError(error: unknown): boolean;
65
- //#endregion
66
- //#region src/pty/rpc-types.d.ts
67
- interface TerminalCapabilityRPC {
68
- getSnapshot(): Promise<TerminalSnapshot | null>;
69
- openOutput(options?: Omit<TerminalOutputOptions, 'signal'>): Promise<ProcessPullSubscriptionRPC<TerminalOutputEvent>>;
70
- write(data: Uint8Array): Promise<void>;
71
- resize(cols: number, rows: number): Promise<void>;
72
- interrupt(): Promise<void>;
73
- terminate(): Promise<void>;
74
- authorizeConnection(): Promise<string>;
75
- }
76
- interface TerminalRPCDescriptor {
77
- snapshot: TerminalSnapshot;
78
- runtimeIncarnationID: string;
79
- capability: TerminalCapabilityRPC;
80
- }
81
- //#endregion
82
- //#region src/pty/proxy.d.ts
83
- interface TerminalHandleStub {
84
- get(id: string): Promise<TerminalSnapshot | null>;
85
- output(id: string, options?: Omit<TerminalOutputOptions, 'signal'>): Promise<TerminalOutputSubscriptionAPI | ProcessPullSubscriptionRPC<TerminalOutputEvent>>;
86
- write(id: string, data: Uint8Array): Promise<void>;
87
- resize(id: string, cols: number, rows: number): Promise<void>;
88
- interrupt(id: string): Promise<void>;
89
- terminate(id: string): Promise<void>;
90
- fetch(request: Request): Promise<Response>;
91
- }
92
- declare function proxyTerminal(stub: Pick<TerminalHandleStub, 'fetch'>, terminalId: string, request: Request, options: {
93
- cursor?: TerminalOutputCursor;
94
- cols?: number;
95
- rows?: number;
96
- runtimeIncarnationID: string;
97
- }): Promise<Response>;
98
- //#endregion
99
- //#region src/backup/restore-fault-injection.d.ts
100
- type BackupRestoreFaultPhase = 'after_archive_ready';
101
- type BackupRestoreTestFault = {
102
- phase: BackupRestoreFaultPhase;
103
- mode: 'transport_disposed';
104
- times: number;
105
- };
106
- //#endregion
107
- //#region src/storage-mount/errors.d.ts
108
- /**
109
- * Base error for bucket mounting operations
110
- */
111
- declare class BucketMountError extends Error {
112
- readonly code: ErrorCode;
113
- constructor(message: string, code?: ErrorCode);
114
- }
115
- /**
116
- * Thrown when S3FS mount command fails
117
- */
118
- declare class S3FSMountError extends BucketMountError {
119
- constructor(message: string);
120
- }
121
- /**
122
- * Thrown when fusermount -u fails to unmount a FUSE filesystem
123
- */
124
- declare class BucketUnmountError extends BucketMountError {
125
- constructor(message: string);
126
- }
127
- /**
128
- * Thrown when no credentials found in environment
129
- */
130
- declare class MissingCredentialsError extends BucketMountError {
131
- constructor(message: string);
132
- }
133
- /**
134
- * Thrown when bucket name, mount path, or options are invalid
135
- */
136
- declare class InvalidMountConfigError extends BucketMountError {
137
- constructor(message: string);
138
- }
139
- //#endregion
140
- //#region src/storage-mount/outbound/container-proxy.d.ts
141
- declare class ContainerProxy extends ContainerProxy$1 {
142
- fetch(request: Request): Promise<Response>;
143
- }
144
- //#endregion
145
- //#region src/tunnels/tunnel-service.d.ts
146
- interface TunnelsHandler {
147
- get(port: number, options?: TunnelOptions): Promise<TunnelInfo>;
148
- list(): Promise<TunnelInfo[]>;
149
- destroy(portOrInfo: number | TunnelInfo): Promise<void>;
150
- }
151
- //#endregion
152
- //#region src/sandbox.d.ts
153
- type SandboxConfiguration = {
154
- sandboxName?: {
155
- name: string;
156
- normalizeId?: boolean;
157
- };
158
- sleepAfter?: string | number;
159
- keepAlive?: boolean;
160
- containerTimeouts?: NonNullable<SandboxOptions['containerTimeouts']>;
161
- };
162
- type InternalSandboxRPCMethod = 'authorizePortRequest';
163
- type SandboxClient<T> = Omit<T, keyof ISandbox | InternalSandboxRPCMethod> & ISandbox;
164
- type CancellationOptions = {
165
- abort?: AbortSignal;
166
- instanceGetTimeoutMS?: number;
167
- portReadyTimeoutMS?: number;
168
- waitInterval?: number;
169
- };
170
- type StartAndWaitForPortsOptions = {
171
- startOptions?: ContainerStartConfigOptions;
172
- ports?: number | number[];
173
- cancellationOptions?: CancellationOptions;
174
- };
175
- declare function getSandbox<T extends Sandbox<any>>(ns: DurableObjectNamespace<T>, id: string, options?: SandboxOptions): SandboxClient<T>;
176
- declare class Sandbox<Env = unknown> extends Container<Env> {
177
- #private;
178
- defaultPort: number;
179
- sleepAfter: string | number;
180
- private runtimeSessions;
181
- private runtimeLifecycle;
182
- private runtimeRunner;
183
- private sandboxName;
184
- private tunnelServiceHandle;
185
- private tunnelsHandler;
186
- private tunnelExitHandler;
187
- private readonly controlCallback;
188
- private normalizeId;
189
- envVars: Record<string, string>;
190
- private readonly portRequestTokens;
191
- private logger;
192
- private keepAliveEnabled;
193
- private bucketMounts;
194
- private currentLifetime;
195
- private backupService;
196
- private previewService;
197
- private resourceActivityGate;
198
- private r2AccessKeyId;
199
- private r2SecretAccessKey;
200
- private namedTunnelConfigResolver;
201
- /**
202
- * Default container startup timeouts (conservative for production)
203
- * Based on Cloudflare docs: "Containers take several minutes to provision"
204
- */
205
- private readonly DEFAULT_CONTAINER_TIMEOUTS;
206
- /**
207
- * Active container timeout configuration
208
- * Can be set via options, env vars, or defaults
209
- */
210
- private containerTimeouts;
211
- /**
212
- * True once containerTimeouts has been written to storage at least once
213
- * (either via setContainerTimeouts or restored on cold start). Gates the
214
- * idempotency check in setContainerTimeouts so a first explicit call
215
- * persists even when the requested values already equal the in-memory
216
- * defaults, distinguishing "user intent recorded" from "running on
217
- * env/SDK defaults".
218
- */
219
- private hasStoredContainerTimeouts;
220
- /**
221
- * Dispatch method for tunnel operations.
222
- * Called by the client-side proxy created in getSandbox() to provide
223
- * the `sandbox.tunnels` API without relying on RPC pipelining through
224
- * property getters, which vite-plugin does not currently support. This
225
- * local method dispatch uses standard function application, so new
226
- * Workers RPC pipelining traits on `TunnelsRpcTarget` also need an
227
- * explicit path here before the proxy can expose them.
228
- */
229
- callTunnels(method: string, args: unknown[]): Promise<unknown>;
230
- callExtension(extensionName: string, method: string, args: unknown[]): Promise<unknown>;
231
- private renewActivityTimeoutIfAvailable;
232
- private getRuntimePortStub;
233
- constructor(ctx: DurableObjectState<{}>, env: Env);
234
- setSandboxName(name: string, normalizeId?: boolean): Promise<void>;
235
- configure(configuration: SandboxConfiguration): Promise<void>;
236
- setSleepAfter(sleepAfter: string | number): Promise<void>;
237
- setKeepAlive(keepAlive: boolean): Promise<void>;
238
- setEnvVars(envVars: Record<string, string | undefined>): Promise<void>;
239
- setContainerTimeouts(timeouts: NonNullable<SandboxOptions['containerTimeouts']>): Promise<void>;
240
- private validateTimeout;
241
- private getDefaultTimeouts;
242
- /**
243
- * Mount an S3-compatible bucket as a local directory.
244
- */
245
- mountBucket(bucket: string, mountPath: string, options: MountBucketOptions): Promise<void>;
246
- /**
247
- * Manually unmount a bucket filesystem.
248
- */
249
- unmountBucket(mountPath: string): Promise<void>;
250
- /**
251
- * In-flight `destroy()` promise. While set, concurrent callers coalesce
252
- * onto the same teardown instead of triggering a second one. Cleared when
253
- * the underlying work settles, so a later call that genuinely needs to
254
- * recreate a destroyed sandbox still runs.
255
- *
256
- * If the underlying teardown hangs (e.g. `super.destroy()` never resolves
257
- * because the Containers control plane is unresponsive), every coalesced
258
- * caller hangs on the same promise until the Durable Object is evicted.
259
- * This is deliberate: a second concurrent teardown would not make a stuck
260
- * control plane unstuck, and spawning one would defeat the point of
261
- * coalescing. Callers that need bounded waits must apply their own
262
- * timeout around `destroy()`.
263
- */
264
- private inflightDestroy;
265
- /**
266
- * Cleanup and destroy the sandbox container.
267
- *
268
- * Concurrent calls coalesce: if a previous `destroy()` is still in flight,
269
- * subsequent calls await the same underlying work instead of starting a
270
- * second teardown. A canonical `sandbox.destroy.coalesced` event is logged
271
- * per coalesced call so repeated destroy traffic is observable.
272
- */
273
- destroy(): Promise<void>;
274
- private doDestroy;
275
- private performRuntimeStop;
276
- private runBoundedDestroyRuntimeCleanup;
277
- private cleanupRuntimeBeforeDestroy;
278
- private createTeardownTunnelsHandle;
279
- private createDurableDestroyTunnelsHandle;
280
- private createDestroyTunnelsHandle;
281
- onStart(): Promise<void>;
282
- start(options?: Parameters<Container<Env>['start']>[0]): Promise<void>;
283
- startAndWaitForPorts(args: StartAndWaitForPortsOptions): Promise<void>;
284
- startAndWaitForPorts(portsOrArgs?: number | number[] | StartAndWaitForPortsOptions, cancellationOptions?: CancellationOptions, startOptions?: ContainerStartConfigOptions): Promise<void>;
285
- stop(signal?: Parameters<Container<Env>['stop']>[0]): Promise<void>;
286
- onStop(): Promise<void>;
287
- onError(error: unknown): void;
288
- /**
289
- * Override Container.containerFetch to route direct forwarding through runtime admission.
290
- */
291
- containerFetch(requestOrUrl: Request | string | URL, portOrInit?: number | RequestInit, portParam?: number): Promise<Response>;
292
- private containerStartupErrorResponse;
293
- /**
294
- * Helper: Check if error is "no container instance available"
295
- * This indicates the container VM is still being provisioned.
296
- */
297
- private isNoInstanceError;
298
- /**
299
- * Helper: Check if error is a transient startup error that should trigger retry
300
- *
301
- * These errors occur during normal container startup and are recoverable:
302
- * - Port not yet mapped (container starting, app not listening yet)
303
- * - Connection refused (port mapped but app not ready)
304
- * - Timeouts during startup (recoverable with retry)
305
- * - Network transients (temporary connectivity issues)
306
- *
307
- * Errors NOT included (permanent failures):
308
- * - "no such image" - missing Docker image
309
- * - "container already exists" - name collision
310
- * - Configuration errors
311
- */
312
- private isTransientStartupError;
313
- /**
314
- * Helper: Check if error is a permanent startup failure that will never recover
315
- *
316
- * These errors indicate resource exhaustion, misconfiguration, or missing images.
317
- * Retrying will never succeed, so the SDK should fail fast with HTTP 500.
318
- *
319
- * Error sources (traced from platform internals):
320
- * - Container runtime: OOM, PID limit
321
- * - Scheduling/provisioning: no matching app, no namespace configured
322
- * - workerd container-client.c++: no such image
323
- * - @cloudflare/containers: did not call start
324
- */
325
- private isPermanentStartupError;
326
- /**
327
- * Helper: Parse containerFetch arguments (supports multiple signatures)
328
- */
329
- private parseContainerFetchArgs;
330
- onActivityExpired(): Promise<void>;
331
- private getPreviewForwardingContainer;
332
- fetch(request: Request): Promise<Response>;
333
- wsConnect(request: Request, port: number): Promise<Response>;
334
- authorizePortRequest(port: number, path: string): Promise<string>;
335
- private connectWebSocket;
336
- createTerminal(options: CreateTerminalOptions): Promise<TerminalRPCDescriptor>;
337
- getTerminal(id: string): Promise<TerminalRPCDescriptor | null>;
338
- listTerminals(): Promise<TerminalRPCDescriptor[]>;
339
- private terminalDescriptor;
340
- private terminalStub;
341
- private determinePort;
342
- exec(command: SandboxCommand, options?: ExecOptions): Promise<ProcessRPCDescriptor>;
343
- private processDescriptor;
344
- private processCapabilityLifecycle;
345
- /** Internal bridge liveness read that neither starts nor renews a runtime. */
346
- isRuntimeActive(): Promise<boolean>;
347
- getProcess(id: string): Promise<ProcessRPCDescriptor | null>;
348
- listProcesses(): Promise<ProcessStatus[]>;
349
- mkdir(path: string, options?: {
350
- recursive?: boolean;
351
- }): Promise<MkdirResult>;
352
- writeFile(path: string, content: string | ReadableStream<Uint8Array>, options?: {
353
- encoding?: string;
354
- }): Promise<{
355
- success: boolean;
356
- path: string;
357
- bytesWritten: number;
358
- timestamp: string;
359
- } | WriteFileResult>;
360
- deleteFile(path: string): Promise<DeleteFileResult>;
361
- renameFile(oldPath: string, newPath: string): Promise<RenameFileResult>;
362
- moveFile(sourcePath: string, destinationPath: string): Promise<MoveFileResult>;
363
- /**
364
- * Read a file from the sandbox.
365
- *
366
- * @param encoding - How to encode the returned content:
367
- * - `undefined` (default): auto-detect from MIME type (text → UTF-8 string, binary → base64 string)
368
- * - `'utf-8'` / `'utf8'`: always return as UTF-8 string
369
- * - `'base64'`: always return as base64-encoded string
370
- * - `'none'`: return a result whose `content` is a raw binary `ReadableStream<Uint8Array>`
371
- * with no encoding overhead.
372
- */
373
- readFile(path: string, options: {
374
- encoding: 'none';
375
- }): Promise<ReadFileStreamResult>;
376
- readFile(path: string, options?: {
377
- encoding?: Exclude<FileEncoding, 'none'>;
378
- }): Promise<ReadFileResult>;
379
- /**
380
- * Stream a file from the sandbox using Server-Sent Events
381
- * Returns a ReadableStream that can be consumed with streamFile() or collectFile() utilities
382
- * @param path - Path to the file to stream
383
- */
384
- createWorkspaceArchive(options?: {
385
- root: string;
386
- excludes?: readonly string[];
387
- }): Promise<string>;
388
- extractWorkspaceArchive(options: {
389
- root: string;
390
- archivePath: string;
391
- }): Promise<void>;
392
- cleanupWorkspaceArchive(archivePath: string): Promise<void>;
393
- cleanupMountDirectory(mountPath: string): Promise<void>;
394
- readFileStream(path: string): Promise<ReadableStream<Uint8Array>>;
395
- listFiles(path: string, options?: ListFilesOptions): Promise<ListFilesResult>;
396
- exists(path: string): Promise<FileExistsResult>;
397
- /**
398
- * Watch a directory for file system changes using native inotify.
399
- *
400
- * The returned promise resolves only after the watcher is established on the
401
- * filesystem, so callers can immediately perform actions that depend on the
402
- * watch being active. The returned stream contains the full event sequence
403
- * starting with the `watching` event.
404
- *
405
- * Consume the stream with `parseSSEStream<FileWatchSSEEvent>(stream)`.
406
- *
407
- * @param path - Path to watch (absolute or relative to /workspace)
408
- * @param options - Watch options
409
- */
410
- watch(path: string, options?: WatchOptions): Promise<ReadableStream<Uint8Array>>;
411
- /**
412
- * Check whether a path changed while this caller was disconnected.
413
- *
414
- * Pass the `version` returned from a prior call in `options.since` to learn
415
- * whether the path is unchanged, changed, or needs a full resync because the
416
- * retained change state was reset.
417
- *
418
- * @param path - Path to check (absolute or relative to /workspace)
419
- * @param options - Change-check options
420
- */
421
- checkChanges(path: string, options?: CheckChangesOptions): Promise<CheckChangesResult>;
422
- /**
423
- * Expose a port and get a preview URL for accessing services running in the sandbox
424
- *
425
- * Preview URL authorization survives transient container restarts, but
426
- * forwarding is active only for the runtime where `exposePort()` was last
427
- * called. Call `exposePort()` again after a restart to reactivate an
428
- * existing URL for the current runtime.
429
- *
430
- * @param port - Port number to expose (1024-65535)
431
- * @param options - Configuration options
432
- * @param options.hostname - Your Worker's domain name (required for preview URL construction)
433
- * @param options.name - Optional friendly name for the port
434
- * @param options.token - Optional custom token for the preview URL (1-16 characters: lowercase letters, numbers, underscores)
435
- * If not provided, a random 16-character token will be generated automatically
436
- * @returns Preview URL information including the full URL, port number, and optional name
437
- *
438
- * @example
439
- * // With auto-generated token
440
- * const { url } = await sandbox.exposePort(8080, { hostname: 'example.com' });
441
- * // url: https://8080-sandbox-id-abc123random4567.example.com
442
- *
443
- * @example
444
- * // With custom token for stable URLs across deployments
445
- * const { url } = await sandbox.exposePort(8080, {
446
- * hostname: 'example.com',
447
- * token: 'my_token_v1'
448
- * });
449
- * // url: https://8080-sandbox-id-my_token_v1.example.com
450
- */
451
- private runWakingComposite;
452
- [sandboxRuntimeCall]: ExtensionRuntimeCall;
453
- exposePort(port: number, options: {
454
- name?: string;
455
- hostname: string;
456
- token?: string;
457
- }): Promise<{
458
- url: string;
459
- port: number;
460
- name?: string;
461
- }>;
462
- /**
463
- * Revoke preview URL authorization and current-runtime activation for a port.
464
- *
465
- * Revocation is idempotent: calling this for a port with no preview state is
466
- * still successful. The operation clears Durable Object-owned preview state
467
- * only and does not contact, probe, wake, or clean up the container runtime.
468
- */
469
- unexposePort(port: number): Promise<void>;
470
- /**
471
- * Returns preview URLs that are currently forwardable in the active runtime.
472
- * Durable authorization without current-runtime activation is omitted.
473
- */
474
- getExposedPorts(hostname: string): Promise<{
475
- url: string;
476
- port: number;
477
- status: "active";
478
- }[]>;
479
- /**
480
- * Returns whether a port is currently preview-forwardable.
481
- * This checks Durable Object-owned auth and runtime activation without
482
- * contacting or waking the container.
483
- */
484
- isPortExposed(port: number): Promise<boolean>;
485
- /**
486
- * Checks durable preview URL authorization for a port/token pair.
487
- *
488
- * This does not check whether the port is activated for the current runtime
489
- * and is not sufficient to decide whether preview traffic may forward.
490
- */
491
- validatePortToken(port: number, token: string): Promise<boolean>;
492
- /**
493
- * Namespaced tunnel API. Quick tunnels are zero-config preview URLs
494
- * backed by Cloudflare's trycloudflare service. Named tunnels bind a
495
- * stable hostname under the configured Cloudflare zone.
496
- *
497
- * - `tunnels.get(port)` — idempotent. Returns the cached tunnel for
498
- * `port` if one exists in DO storage, otherwise spawns a fresh
499
- * cloudflared process and persists the record.
500
- * - `tunnels.list()` — returns tunnels currently usable through this
501
- * sandbox runtime.
502
- * - `tunnels.destroy(portOrInfo)` — tear down by port number or by
503
- * the record returned from `get()`.
504
- *
505
- * Container restarts drop quick-tunnel records because their
506
- * `*.trycloudflare.com` URLs are tied to the dead cloudflared process.
507
- * Named-tunnel records stay in storage and are marked for respawn so the
508
- * next `get(port, { name })` call reuses the Cloudflare tunnel and DNS
509
- * record while starting a fresh cloudflared process.
510
- */
511
- get tunnels(): TunnelsHandler;
512
- /**
513
- * Lazily construct the tunnel subsystem handle. Called from the
514
- * `tunnels` getter on first access and from sandbox lifecycle hooks
515
- * when tunnel reconciliation or cleanup is needed.
516
- */
517
- private ensureTunnelsBuilt;
518
- /**
519
- * Create a backup of a directory and upload it to R2.
520
- *
521
- * The returned DirectoryBackup handle is serializable. Store it anywhere
522
- * (KV, D1, DO storage) and pass it to restoreBackup() later.
523
- *
524
- * Concurrent backup/restore calls on the same sandbox are serialized.
525
- */
526
- createBackup(options: BackupOptions): Promise<DirectoryBackup>;
527
- /**
528
- * Restore a backup from R2 into a directory.
529
- *
530
- * Production restores use a FUSE overlay mount. Local-bucket restores stream
531
- * the archive through the R2 binding and extract it with unsquashfs.
532
- *
533
- * Concurrent backup/restore calls on the same sandbox are serialized.
534
- */
535
- restoreBackup(backup: DirectoryBackup): Promise<RestoreBackupResult>;
536
- __setBackupRestoreFaultForTesting(fault: BackupRestoreTestFault | null): Promise<void>;
537
- registerGitAuthInterceptor(params: HTTPAuthInterceptorParams): Promise<void>;
538
- private getMountOutboundHost;
539
- }
540
- //#endregion
541
- //#region src/request-handler.d.ts
542
- interface SandboxEnv<T extends Sandbox<any> = Sandbox<any>> {
543
- Sandbox: DurableObjectNamespace<T>;
544
- }
545
- declare function proxyToSandbox<T extends Sandbox<any>, E extends SandboxEnv<T>>(request: Request, env: E): Promise<Response | null>;
546
- //#endregion
547
- //#region src/sse-parser.d.ts
548
- /**
549
- * Server-Sent Events (SSE) parser for streaming responses
550
- * Converts ReadableStream<Uint8Array> to typed AsyncIterable<T>
551
- */
552
- /**
553
- * Parse a ReadableStream of SSE events into typed AsyncIterable
554
- * @param stream - The ReadableStream from fetch response
555
- * @param signal - Optional AbortSignal for cancellation
556
- */
557
- declare function parseSSEStream<T>(stream: ReadableStream<Uint8Array>, signal?: AbortSignal): AsyncIterable<T>;
558
- /**
559
- * Helper to convert a Response with SSE stream directly to AsyncIterable
560
- * @param response - Response object with SSE stream
561
- * @param signal - Optional AbortSignal for cancellation
562
- */
563
- declare function responseToAsyncIterable<T>(response: Response, signal?: AbortSignal): AsyncIterable<T>;
564
- /**
565
- * Create an SSE-formatted ReadableStream from an AsyncIterable
566
- * (Useful for Worker endpoints that need to forward AsyncIterable as SSE)
567
- * @param events - AsyncIterable of events
568
- * @param options - Stream options
569
- */
570
- declare function asyncIterableToSSEStream<T>(events: AsyncIterable<T>, options?: {
571
- signal?: AbortSignal;
572
- serialize?: (event: T) => string;
573
- }): ReadableStream<Uint8Array>;
574
- //#endregion
575
- export { BackupCreateError, BackupExpiredError, BackupNotFoundError, type BackupOptions, BackupRestoreError, type BucketCredentials, BucketMountError, type BucketProvider, BucketUnmountError, type CheckChangesOptions, type CheckChangesResult, ContainerProxy, ContainerUnavailableError, type CreateTerminalOptions, type DirectoryBackup, type ExecOptions, type FileChunk, type FileMetadata, type FileStreamEvent, type FileWatchSSEEvent, type ISandbox, InvalidBackupConfigError, InvalidMountConfigError, InvalidProcessCursorError, InvalidProcessCwdError, InvalidProcessEnvironmentError, InvalidTerminalCursorError, InvalidTerminalCwdError, type ListFilesOptions, type LocalMountBucketOptions, MissingCredentialsError, type MountBucketOptions, type NamedTunnelInfo, OperationInterruptedError, ProcessAbortedError, ProcessError, type ProcessExit, ProcessExitedBeforeLogError, ProcessExitedBeforeReadyError, type ProcessFailure, type ProcessLogCursor, type ProcessLogEvent, type ProcessLogsOptions, ProcessNotFoundError, type ProcessOutput, type ProcessOutputOptions, ProcessReadyTimeoutError, ProcessSpawnFailedError, type ProcessStatus, type ProcessTextOutputOptions, ProcessWaitTimeoutError, type QuickTunnelInfo, type RPCTransportContext, RPCTransportError, type RPCTransportErrorKind, type RemoteMountBucketOptions, type RestoreBackupResult, RuntimeControlProtocolError, RuntimeIdentityInactiveError, S3FSMountError, Sandbox, type SandboxCommand, type SandboxEnv, type SandboxOptions, type SandboxProcess, StaleProcessHandleError, StaleTerminalHandleError, type Terminal, TerminalControlError, TerminalNotFoundError, type TerminalOutputCursor, type TerminalOutputEvent, type TerminalOutputOptions, type TerminalSnapshot, type TunnelInfo, type TunnelOptions, type WaitForExitOptions, type WaitForLogOptions, type WaitForLogResult, type WaitForPortOptions, type WatchOptions, asyncIterableToSSEStream, collectFile, getSandbox, isDurableObjectCodeUpdateReset, isPlatformTransientError, parseSSEStream, proxyTerminal, proxyToSandbox, responseToAsyncIterable, streamFile };
576
- //# sourceMappingURL=index.d.ts.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"index.d.ts","names":[],"sources":["../src/file-stream.ts","../src/platform-errors.ts","../src/pty/rpc-types.ts","../src/pty/proxy.ts","../src/backup/restore-fault-injection.ts","../src/storage-mount/errors.ts","../src/storage-mount/outbound/container-proxy.ts","../src/tunnels/tunnel-service.ts","../src/sandbox.ts","../src/request-handler.ts","../src/sse-parser.ts"],"sourcesContent":[],"mappings":";;;;;;;;;;;;;;;;;;;;AAmFA;;;;;;;AA+DA;;;;AAEY,iBAjEW,UAAA,CAiEX,MAAA,EAhEF,cAgEE,CAhEa,UAgEb,CAAA,CAAA,EA/DT,cA+DS,CA/DM,SA+DN,EA/DiB,YA+DjB,CAAA;;;;;;AC1GZ;AAaA;;;;AChDA;;;;AAGc,iBFwIQ,WAAA,CExIR,MAAA,EFwI4B,cExI5B,CFwI2C,UExI3C,CAAA,CAAA,EFwIyD,OExIzD,CAAA;EAC0B,OAAA,EAAA,MAAA,GFwIpB,UExIoB;EAA3B,QAAA,EFyID,YEzIC;CAAR,CAAA;;;;;;;;;iBD+BW,8BAAA;;;;ADyChB;AACyB,iBC7BT,wBAAA,CD6BS,KAAA,EAAA,OAAA,CAAA,EAAA,OAAA;;;UE7ER,qBAAA;iBACA,QAAQ;uBAEX,KAAK,mCACd,QAAQ,2BAA2B;cAC1B,aAAa;sCACW;eACvB;eACA;yBACU;AFmEzB;AACyB,UEjER,qBAAA,CFiEQ;EAAf,QAAA,EEhEE,gBFgEF;EACQ,oBAAA,EAAA,MAAA;EAAW,UAAA,EE/Df,qBF+De;;;;UG/DnB,kBAAA;mBACS,QAAQ;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wBAYxB,kBAAkB,QAAQ;2CAK7C,gCACN;qCAKO,4BACP;;;;;UCvoGY,qBAAqB,eAAe;WAC1C,uBAAuB;;iBAaZ,yBACV,wBACA,WAAW,aACZ,cAAc,IAAI,QAAQ;;;;;;;;;;;;iBCVd,0BACb,eAAe,sBACd,cACR,cAAc;AVoEjB;;;;;AAEG,iBUkBoB,uBVlBpB,CAAA,CAAA,CAAA,CAAA,QAAA,EUmBS,QVnBT,EAAA,MAAA,CAAA,EUoBQ,WVpBR,CAAA,EUqBA,aVrBA,CUqBc,CVrBd,CAAA;;AA6DH;;;;;AAAuE,iBUpBvD,wBVoBuD,CAAA,CAAA,CAAA,CAAA,MAAA,EUnB7D,aVmB6D,CUnB/C,CVmB+C,CAAA,EAAA,QAAA,EAAA;EAAO,MAAA,CAAA,EUjBjE,WViBiE;sBUhBtD;IAErB,eAAe"}
package/dist/index.js DELETED
@@ -1,33 +0,0 @@
1
- import "./errors-CXR0xBpw.js";
2
- import { $ as TerminalControlError, G as BackupRestoreError, H as BackupCreateError, J as InvalidTerminalCursorError, K as ContainerUnavailableError, Q as StaleTerminalHandleError, U as BackupExpiredError, W as BackupNotFoundError, X as OperationInterruptedError, Y as InvalidTerminalCwdError, Z as RPCTransportError, _ as StaleProcessHandleError, c as InvalidProcessEnvironmentError, d as ProcessExitedBeforeLogError, et as TerminalNotFoundError, f as ProcessExitedBeforeReadyError, g as ProcessWaitTimeoutError, h as ProcessSpawnFailedError, l as ProcessAbortedError, m as ProcessReadyTimeoutError, n as RuntimeIdentityInactiveError, o as InvalidProcessCursorError, p as ProcessNotFoundError, q as InvalidBackupConfigError, r as RuntimeControlProtocolError, s as InvalidProcessCwdError, u as ProcessError } from "./errors-QYlSkVGz.js";
3
- import { a as TraceContext, r as createLogger } from "./dist-Duor5GbS.js";
4
- import { _ as proxyTerminal, a as responseToAsyncIterable, b as collectFile, c as BucketUnmountError, d as S3FSMountError, f as parsePreviewRoute, i as parseSSEStream, l as InvalidMountConfigError, n as getSandbox, o as ContainerProxy, p as withPreviewProxyMetadata, r as asyncIterableToSSEStream, s as BucketMountError, t as Sandbox, u as MissingCredentialsError, v as isDurableObjectCodeUpdateReset, x as streamFile, y as isPlatformTransientError } from "./sandbox-cmlgGVYX.js";
5
- import "./extensions-CFB2xHqY.js";
6
-
7
- //#region src/request-handler.ts
8
- function createProxyLogger(request) {
9
- return createLogger({
10
- component: "sandbox-do",
11
- traceId: TraceContext.fromHeaders(request.headers) || TraceContext.generate(),
12
- operation: "proxy"
13
- });
14
- }
15
- async function proxyToSandbox(request, env) {
16
- try {
17
- const routeInfo = parsePreviewRoute(new URL(request.url));
18
- if (!routeInfo) return null;
19
- const { sandboxId, port, token } = routeInfo;
20
- return await getSandbox(env.Sandbox, sandboxId, { normalizeId: true }).fetch(withPreviewProxyMetadata(request, {
21
- port,
22
- token,
23
- sandboxId
24
- }));
25
- } catch (error) {
26
- createProxyLogger(request).error("Proxy routing error", error instanceof Error ? error : new Error(String(error)));
27
- return new Response("Proxy routing error", { status: 500 });
28
- }
29
- }
30
-
31
- //#endregion
32
- export { BackupCreateError, BackupExpiredError, BackupNotFoundError, BackupRestoreError, BucketMountError, BucketUnmountError, ContainerProxy, ContainerUnavailableError, InvalidBackupConfigError, InvalidMountConfigError, InvalidProcessCursorError, InvalidProcessCwdError, InvalidProcessEnvironmentError, InvalidTerminalCursorError, InvalidTerminalCwdError, MissingCredentialsError, OperationInterruptedError, ProcessAbortedError, ProcessError, ProcessExitedBeforeLogError, ProcessExitedBeforeReadyError, ProcessNotFoundError, ProcessReadyTimeoutError, ProcessSpawnFailedError, ProcessWaitTimeoutError, RPCTransportError, RuntimeControlProtocolError, RuntimeIdentityInactiveError, S3FSMountError, Sandbox, StaleProcessHandleError, StaleTerminalHandleError, TerminalControlError, TerminalNotFoundError, asyncIterableToSSEStream, collectFile, getSandbox, isDurableObjectCodeUpdateReset, isPlatformTransientError, parseSSEStream, proxyTerminal, proxyToSandbox, responseToAsyncIterable, streamFile };
33
- //# sourceMappingURL=index.js.map
package/dist/index.js.map DELETED
@@ -1 +0,0 @@
1
- {"version":3,"file":"index.js","names":[],"sources":["../src/request-handler.ts"],"sourcesContent":["import { createLogger, TraceContext } from '@repo/shared';\nimport { withPreviewProxyMetadata } from './preview/protocol';\nimport { parsePreviewRoute } from './preview/route';\nimport { getSandbox, type Sandbox } from './sandbox';\n\nexport interface SandboxEnv<T extends Sandbox<any> = Sandbox<any>> {\n Sandbox: DurableObjectNamespace<T>;\n}\n\nfunction createProxyLogger(request: Request) {\n const traceId =\n TraceContext.fromHeaders(request.headers) || TraceContext.generate();\n return createLogger({\n component: 'sandbox-do',\n traceId,\n operation: 'proxy'\n });\n}\n\nexport async function proxyToSandbox<\n T extends Sandbox<any>,\n E extends SandboxEnv<T>\n>(request: Request, env: E): Promise<Response | null> {\n try {\n const url = new URL(request.url);\n const routeInfo = parsePreviewRoute(url);\n\n if (!routeInfo) {\n return null; // Not a request to an exposed container port\n }\n\n const { sandboxId, port, token } = routeInfo;\n // Preview URLs always use normalized (lowercase) IDs\n const sandbox = getSandbox(env.Sandbox, sandboxId, { normalizeId: true });\n\n return await sandbox.fetch(\n withPreviewProxyMetadata(request, { port, token, sandboxId })\n );\n } catch (error) {\n const logger = createProxyLogger(request);\n logger.error(\n 'Proxy routing error',\n error instanceof Error ? error : new Error(String(error))\n );\n return new Response('Proxy routing error', { status: 500 });\n }\n}\n"],"mappings":";;;;;;;AASA,SAAS,kBAAkB,SAAkB;AAG3C,QAAO,aAAa;EAClB,WAAW;EACX,SAHA,aAAa,YAAY,QAAQ,QAAQ,IAAI,aAAa,UAAU;EAIpE,WAAW;EACZ,CAAC;;AAGJ,eAAsB,eAGpB,SAAkB,KAAkC;AACpD,KAAI;EAEF,MAAM,YAAY,kBADN,IAAI,IAAI,QAAQ,IAAI,CACQ;AAExC,MAAI,CAAC,UACH,QAAO;EAGT,MAAM,EAAE,WAAW,MAAM,UAAU;AAInC,SAAO,MAFS,WAAW,IAAI,SAAS,WAAW,EAAE,aAAa,MAAM,CAAC,CAEpD,MACnB,yBAAyB,SAAS;GAAE;GAAM;GAAO;GAAW,CAAC,CAC9D;UACM,OAAO;AAEd,EADe,kBAAkB,QAAQ,CAClC,MACL,uBACA,iBAAiB,QAAQ,QAAQ,IAAI,MAAM,OAAO,MAAM,CAAC,CAC1D;AACD,SAAO,IAAI,SAAS,uBAAuB,EAAE,QAAQ,KAAK,CAAC"}