@cloudflare/sandbox 0.0.0-af082ab → 0.0.0-b61841c

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 (105) hide show
  1. package/CHANGELOG.md +63 -6
  2. package/Dockerfile +91 -51
  3. package/README.md +88 -825
  4. package/dist/chunk-BFVUNTP4.js +104 -0
  5. package/dist/chunk-BFVUNTP4.js.map +1 -0
  6. package/dist/chunk-EKSWCBCA.js +86 -0
  7. package/dist/chunk-EKSWCBCA.js.map +1 -0
  8. package/dist/chunk-JXZMAU2C.js +559 -0
  9. package/dist/chunk-JXZMAU2C.js.map +1 -0
  10. package/dist/chunk-QHRFHK6X.js +7 -0
  11. package/dist/chunk-QHRFHK6X.js.map +1 -0
  12. package/dist/chunk-SFCV5YTY.js +2456 -0
  13. package/dist/chunk-SFCV5YTY.js.map +1 -0
  14. package/dist/chunk-Z532A7QC.js +78 -0
  15. package/dist/chunk-Z532A7QC.js.map +1 -0
  16. package/dist/file-stream.d.ts +43 -0
  17. package/dist/file-stream.js +9 -0
  18. package/dist/file-stream.js.map +1 -0
  19. package/dist/index.d.ts +9 -0
  20. package/dist/index.js +67 -0
  21. package/dist/index.js.map +1 -0
  22. package/dist/interpreter.d.ts +33 -0
  23. package/dist/interpreter.js +8 -0
  24. package/dist/interpreter.js.map +1 -0
  25. package/dist/request-handler.d.ts +18 -0
  26. package/dist/request-handler.js +13 -0
  27. package/dist/request-handler.js.map +1 -0
  28. package/dist/sandbox-DWQVgVTY.d.ts +603 -0
  29. package/dist/sandbox.d.ts +4 -0
  30. package/dist/sandbox.js +13 -0
  31. package/dist/sandbox.js.map +1 -0
  32. package/dist/security.d.ts +31 -0
  33. package/dist/security.js +13 -0
  34. package/dist/security.js.map +1 -0
  35. package/dist/sse-parser.d.ts +28 -0
  36. package/dist/sse-parser.js +11 -0
  37. package/dist/sse-parser.js.map +1 -0
  38. package/dist/version.d.ts +8 -0
  39. package/dist/version.js +7 -0
  40. package/dist/version.js.map +1 -0
  41. package/package.json +12 -4
  42. package/src/clients/base-client.ts +280 -0
  43. package/src/clients/command-client.ts +115 -0
  44. package/src/clients/file-client.ts +295 -0
  45. package/src/clients/git-client.ts +92 -0
  46. package/src/clients/index.ts +64 -0
  47. package/src/{interpreter-client.ts → clients/interpreter-client.ts} +148 -171
  48. package/src/clients/port-client.ts +105 -0
  49. package/src/clients/process-client.ts +177 -0
  50. package/src/clients/sandbox-client.ts +41 -0
  51. package/src/clients/types.ts +84 -0
  52. package/src/clients/utility-client.ts +119 -0
  53. package/src/errors/adapter.ts +180 -0
  54. package/src/errors/classes.ts +469 -0
  55. package/src/errors/index.ts +105 -0
  56. package/src/file-stream.ts +119 -117
  57. package/src/index.ts +81 -69
  58. package/src/interpreter.ts +17 -8
  59. package/src/request-handler.ts +80 -44
  60. package/src/sandbox.ts +794 -537
  61. package/src/security.ts +14 -23
  62. package/src/sse-parser.ts +4 -8
  63. package/src/version.ts +6 -0
  64. package/startup.sh +3 -0
  65. package/tests/base-client.test.ts +328 -0
  66. package/tests/command-client.test.ts +407 -0
  67. package/tests/file-client.test.ts +719 -0
  68. package/tests/file-stream.test.ts +306 -0
  69. package/tests/get-sandbox.test.ts +110 -0
  70. package/tests/git-client.test.ts +328 -0
  71. package/tests/port-client.test.ts +301 -0
  72. package/tests/process-client.test.ts +658 -0
  73. package/tests/request-handler.test.ts +240 -0
  74. package/tests/sandbox.test.ts +554 -0
  75. package/tests/sse-parser.test.ts +290 -0
  76. package/tests/utility-client.test.ts +332 -0
  77. package/tests/version.test.ts +16 -0
  78. package/tests/wrangler.jsonc +35 -0
  79. package/tsconfig.json +9 -1
  80. package/vitest.config.ts +31 -0
  81. package/container_src/bun.lock +0 -76
  82. package/container_src/circuit-breaker.ts +0 -121
  83. package/container_src/control-process.ts +0 -784
  84. package/container_src/handler/exec.ts +0 -185
  85. package/container_src/handler/file.ts +0 -457
  86. package/container_src/handler/git.ts +0 -130
  87. package/container_src/handler/ports.ts +0 -314
  88. package/container_src/handler/process.ts +0 -568
  89. package/container_src/handler/session.ts +0 -92
  90. package/container_src/index.ts +0 -601
  91. package/container_src/interpreter-service.ts +0 -276
  92. package/container_src/isolation.ts +0 -1213
  93. package/container_src/mime-processor.ts +0 -255
  94. package/container_src/package.json +0 -18
  95. package/container_src/runtime/executors/javascript/node_executor.ts +0 -123
  96. package/container_src/runtime/executors/python/ipython_executor.py +0 -338
  97. package/container_src/runtime/executors/typescript/ts_executor.ts +0 -138
  98. package/container_src/runtime/process-pool.ts +0 -464
  99. package/container_src/shell-escape.ts +0 -42
  100. package/container_src/startup.sh +0 -11
  101. package/container_src/types.ts +0 -131
  102. package/src/client.ts +0 -1048
  103. package/src/errors.ts +0 -219
  104. package/src/interpreter-types.ts +0 -390
  105. package/src/types.ts +0 -571
@@ -0,0 +1,554 @@
1
+ import type { DurableObjectState } from '@cloudflare/workers-types';
2
+ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
3
+ import { Sandbox } from '../src/sandbox';
4
+ import { Container } from '@cloudflare/containers';
5
+
6
+ // Mock dependencies before imports
7
+ vi.mock('./interpreter', () => ({
8
+ CodeInterpreter: vi.fn().mockImplementation(() => ({})),
9
+ }));
10
+
11
+ vi.mock('@cloudflare/containers', () => {
12
+ const MockContainer = class Container {
13
+ ctx: any;
14
+ env: any;
15
+ constructor(ctx: any, env: any) {
16
+ this.ctx = ctx;
17
+ this.env = env;
18
+ }
19
+ async fetch(request: Request): Promise<Response> {
20
+ // Mock implementation - will be spied on in tests
21
+ return new Response('Mock Container fetch');
22
+ }
23
+ async containerFetch(request: Request, port: number): Promise<Response> {
24
+ // Mock implementation for HTTP path
25
+ return new Response('Mock Container HTTP fetch');
26
+ }
27
+ };
28
+
29
+ return {
30
+ Container: MockContainer,
31
+ getContainer: vi.fn(),
32
+ };
33
+ });
34
+
35
+ describe('Sandbox - Automatic Session Management', () => {
36
+ let sandbox: Sandbox;
37
+ let mockCtx: Partial<DurableObjectState>;
38
+ let mockEnv: any;
39
+
40
+ beforeEach(async () => {
41
+ vi.clearAllMocks();
42
+
43
+ // Mock DurableObjectState
44
+ mockCtx = {
45
+ storage: {
46
+ get: vi.fn().mockResolvedValue(null),
47
+ put: vi.fn().mockResolvedValue(undefined),
48
+ delete: vi.fn().mockResolvedValue(undefined),
49
+ list: vi.fn().mockResolvedValue(new Map()),
50
+ } as any,
51
+ blockConcurrencyWhile: vi.fn((fn: () => Promise<void>) => fn()),
52
+ id: {
53
+ toString: () => 'test-sandbox-id',
54
+ equals: vi.fn(),
55
+ name: 'test-sandbox',
56
+ } as any,
57
+ };
58
+
59
+ mockEnv = {};
60
+
61
+ // Create Sandbox instance - SandboxClient is created internally
62
+ sandbox = new Sandbox(mockCtx as DurableObjectState, mockEnv);
63
+
64
+ // Wait for blockConcurrencyWhile to complete
65
+ await vi.waitFor(() => {
66
+ expect(mockCtx.blockConcurrencyWhile).toHaveBeenCalled();
67
+ });
68
+
69
+ // Now spy on the client methods that we need for testing
70
+ vi.spyOn(sandbox.client.utils, 'createSession').mockResolvedValue({
71
+ success: true,
72
+ id: 'sandbox-default',
73
+ message: 'Created',
74
+ } as any);
75
+
76
+ vi.spyOn(sandbox.client.commands, 'execute').mockResolvedValue({
77
+ success: true,
78
+ stdout: '',
79
+ stderr: '',
80
+ exitCode: 0,
81
+ command: '',
82
+ timestamp: new Date().toISOString(),
83
+ } as any);
84
+
85
+ vi.spyOn(sandbox.client.files, 'writeFile').mockResolvedValue({
86
+ success: true,
87
+ path: '/test.txt',
88
+ timestamp: new Date().toISOString(),
89
+ } as any);
90
+ });
91
+
92
+ afterEach(() => {
93
+ vi.restoreAllMocks();
94
+ });
95
+
96
+ describe('default session management', () => {
97
+ it('should create default session on first operation', async () => {
98
+ vi.mocked(sandbox.client.commands.execute).mockResolvedValueOnce({
99
+ success: true,
100
+ stdout: 'test output',
101
+ stderr: '',
102
+ exitCode: 0,
103
+ command: 'echo test',
104
+ timestamp: new Date().toISOString(),
105
+ } as any);
106
+
107
+ await sandbox.exec('echo test');
108
+
109
+ expect(sandbox.client.utils.createSession).toHaveBeenCalledTimes(1);
110
+ expect(sandbox.client.utils.createSession).toHaveBeenCalledWith({
111
+ id: expect.stringMatching(/^sandbox-/),
112
+ env: {},
113
+ cwd: '/workspace',
114
+ });
115
+
116
+ expect(sandbox.client.commands.execute).toHaveBeenCalledWith(
117
+ 'echo test',
118
+ expect.stringMatching(/^sandbox-/)
119
+ );
120
+ });
121
+
122
+ it('should reuse default session across multiple operations', async () => {
123
+ await sandbox.exec('echo test1');
124
+ await sandbox.writeFile('/test.txt', 'content');
125
+ await sandbox.exec('echo test2');
126
+
127
+ expect(sandbox.client.utils.createSession).toHaveBeenCalledTimes(1);
128
+
129
+ const firstSessionId = vi.mocked(sandbox.client.commands.execute).mock.calls[0][1];
130
+ const fileSessionId = vi.mocked(sandbox.client.files.writeFile).mock.calls[0][2];
131
+ const secondSessionId = vi.mocked(sandbox.client.commands.execute).mock.calls[1][1];
132
+
133
+ expect(firstSessionId).toBe(fileSessionId);
134
+ expect(firstSessionId).toBe(secondSessionId);
135
+ });
136
+
137
+ it('should use default session for process management', async () => {
138
+ vi.spyOn(sandbox.client.processes, 'startProcess').mockResolvedValue({
139
+ success: true,
140
+ processId: 'proc-1',
141
+ pid: 1234,
142
+ command: 'sleep 10',
143
+ timestamp: new Date().toISOString(),
144
+ } as any);
145
+
146
+ vi.spyOn(sandbox.client.processes, 'listProcesses').mockResolvedValue({
147
+ success: true,
148
+ processes: [{
149
+ id: 'proc-1',
150
+ pid: 1234,
151
+ command: 'sleep 10',
152
+ status: 'running',
153
+ startTime: new Date().toISOString(),
154
+ }],
155
+ timestamp: new Date().toISOString(),
156
+ } as any);
157
+
158
+ const process = await sandbox.startProcess('sleep 10');
159
+ const processes = await sandbox.listProcesses();
160
+
161
+ expect(sandbox.client.utils.createSession).toHaveBeenCalledTimes(1);
162
+
163
+ // startProcess uses sessionId (to start process in that session)
164
+ const startSessionId = vi.mocked(sandbox.client.processes.startProcess).mock.calls[0][1];
165
+ expect(startSessionId).toMatch(/^sandbox-/);
166
+
167
+ // listProcesses is sandbox-scoped - no sessionId parameter
168
+ const listProcessesCall = vi.mocked(sandbox.client.processes.listProcesses).mock.calls[0];
169
+ expect(listProcessesCall).toEqual([]);
170
+
171
+ // Verify the started process appears in the list
172
+ expect(process.id).toBe('proc-1');
173
+ expect(processes).toHaveLength(1);
174
+ expect(processes[0].id).toBe('proc-1');
175
+ });
176
+
177
+ it('should use default session for git operations', async () => {
178
+ vi.spyOn(sandbox.client.git, 'checkout').mockResolvedValue({
179
+ success: true,
180
+ stdout: 'Cloned successfully',
181
+ stderr: '',
182
+ branch: 'main',
183
+ targetDir: '/workspace/repo',
184
+ timestamp: new Date().toISOString(),
185
+ } as any);
186
+
187
+ await sandbox.gitCheckout('https://github.com/test/repo.git', { branch: 'main' });
188
+
189
+ expect(sandbox.client.utils.createSession).toHaveBeenCalledTimes(1);
190
+ expect(sandbox.client.git.checkout).toHaveBeenCalledWith(
191
+ 'https://github.com/test/repo.git',
192
+ expect.stringMatching(/^sandbox-/),
193
+ { branch: 'main', targetDir: undefined }
194
+ );
195
+ });
196
+
197
+ it('should initialize session with sandbox name when available', async () => {
198
+ await sandbox.setSandboxName('my-sandbox');
199
+
200
+ await sandbox.exec('pwd');
201
+
202
+ expect(sandbox.client.utils.createSession).toHaveBeenCalledWith({
203
+ id: 'sandbox-my-sandbox',
204
+ env: {},
205
+ cwd: '/workspace',
206
+ });
207
+ });
208
+ });
209
+
210
+ describe('explicit session creation', () => {
211
+ it('should create isolated execution session', async () => {
212
+ vi.mocked(sandbox.client.utils.createSession).mockResolvedValueOnce({
213
+ success: true,
214
+ id: 'custom-session-123',
215
+ message: 'Created',
216
+ } as any);
217
+
218
+ const session = await sandbox.createSession({
219
+ id: 'custom-session-123',
220
+ env: { NODE_ENV: 'test' },
221
+ cwd: '/test',
222
+ });
223
+
224
+ expect(sandbox.client.utils.createSession).toHaveBeenCalledWith({
225
+ id: 'custom-session-123',
226
+ env: { NODE_ENV: 'test' },
227
+ cwd: '/test',
228
+ });
229
+
230
+ expect(session.id).toBe('custom-session-123');
231
+ expect(session.exec).toBeInstanceOf(Function);
232
+ expect(session.startProcess).toBeInstanceOf(Function);
233
+ expect(session.writeFile).toBeInstanceOf(Function);
234
+ expect(session.gitCheckout).toBeInstanceOf(Function);
235
+ });
236
+
237
+ it('should execute operations in specific session context', async () => {
238
+ vi.mocked(sandbox.client.utils.createSession).mockResolvedValueOnce({
239
+ success: true,
240
+ id: 'isolated-session',
241
+ message: 'Created',
242
+ } as any);
243
+
244
+ const session = await sandbox.createSession({ id: 'isolated-session' });
245
+
246
+ await session.exec('echo test');
247
+
248
+ expect(sandbox.client.commands.execute).toHaveBeenCalledWith(
249
+ 'echo test',
250
+ 'isolated-session'
251
+ );
252
+ });
253
+
254
+ it('should isolate multiple explicit sessions', async () => {
255
+ vi.mocked(sandbox.client.utils.createSession)
256
+ .mockResolvedValueOnce({ success: true, id: 'session-1', message: 'Created' } as any)
257
+ .mockResolvedValueOnce({ success: true, id: 'session-2', message: 'Created' } as any);
258
+
259
+ const session1 = await sandbox.createSession({ id: 'session-1' });
260
+ const session2 = await sandbox.createSession({ id: 'session-2' });
261
+
262
+ await session1.exec('echo build');
263
+ await session2.exec('echo test');
264
+
265
+ const session1Id = vi.mocked(sandbox.client.commands.execute).mock.calls[0][1];
266
+ const session2Id = vi.mocked(sandbox.client.commands.execute).mock.calls[1][1];
267
+
268
+ expect(session1Id).toBe('session-1');
269
+ expect(session2Id).toBe('session-2');
270
+ expect(session1Id).not.toBe(session2Id);
271
+ });
272
+
273
+ it('should not interfere with default session', async () => {
274
+ vi.mocked(sandbox.client.utils.createSession)
275
+ .mockResolvedValueOnce({ success: true, id: 'sandbox-default', message: 'Created' } as any)
276
+ .mockResolvedValueOnce({ success: true, id: 'explicit-session', message: 'Created' } as any);
277
+
278
+ await sandbox.exec('echo default');
279
+
280
+ const explicitSession = await sandbox.createSession({ id: 'explicit-session' });
281
+ await explicitSession.exec('echo explicit');
282
+
283
+ await sandbox.exec('echo default-again');
284
+
285
+ const defaultSessionId1 = vi.mocked(sandbox.client.commands.execute).mock.calls[0][1];
286
+ const explicitSessionId = vi.mocked(sandbox.client.commands.execute).mock.calls[1][1];
287
+ const defaultSessionId2 = vi.mocked(sandbox.client.commands.execute).mock.calls[2][1];
288
+
289
+ expect(defaultSessionId1).toBe('sandbox-default');
290
+ expect(explicitSessionId).toBe('explicit-session');
291
+ expect(defaultSessionId2).toBe('sandbox-default');
292
+ expect(defaultSessionId1).toBe(defaultSessionId2);
293
+ expect(explicitSessionId).not.toBe(defaultSessionId1);
294
+ });
295
+
296
+ it('should generate session ID if not provided', async () => {
297
+ vi.mocked(sandbox.client.utils.createSession).mockResolvedValueOnce({
298
+ success: true,
299
+ id: 'session-generated-123',
300
+ message: 'Created',
301
+ } as any);
302
+
303
+ await sandbox.createSession();
304
+
305
+ expect(sandbox.client.utils.createSession).toHaveBeenCalledWith({
306
+ id: expect.stringMatching(/^session-/),
307
+ env: undefined,
308
+ cwd: undefined,
309
+ });
310
+ });
311
+ });
312
+
313
+ describe('ExecutionSession operations', () => {
314
+ let session: any;
315
+
316
+ beforeEach(async () => {
317
+ vi.mocked(sandbox.client.utils.createSession).mockResolvedValueOnce({
318
+ success: true,
319
+ id: 'test-session',
320
+ message: 'Created',
321
+ } as any);
322
+
323
+ session = await sandbox.createSession({ id: 'test-session' });
324
+ });
325
+
326
+ it('should execute command with session context', async () => {
327
+ await session.exec('pwd');
328
+ expect(sandbox.client.commands.execute).toHaveBeenCalledWith('pwd', 'test-session');
329
+ });
330
+
331
+ it('should start process with session context', async () => {
332
+ vi.spyOn(sandbox.client.processes, 'startProcess').mockResolvedValue({
333
+ success: true,
334
+ process: {
335
+ id: 'proc-1',
336
+ pid: 1234,
337
+ command: 'sleep 10',
338
+ status: 'running',
339
+ startTime: new Date().toISOString(),
340
+ },
341
+ } as any);
342
+
343
+ await session.startProcess('sleep 10');
344
+
345
+ expect(sandbox.client.processes.startProcess).toHaveBeenCalledWith(
346
+ 'sleep 10',
347
+ 'test-session',
348
+ { processId: undefined }
349
+ );
350
+ });
351
+
352
+ it('should write file with session context', async () => {
353
+ vi.spyOn(sandbox.client.files, 'writeFile').mockResolvedValue({
354
+ success: true,
355
+ path: '/test.txt',
356
+ timestamp: new Date().toISOString(),
357
+ } as any);
358
+
359
+ await session.writeFile('/test.txt', 'content');
360
+
361
+ expect(sandbox.client.files.writeFile).toHaveBeenCalledWith(
362
+ '/test.txt',
363
+ 'content',
364
+ 'test-session',
365
+ { encoding: undefined }
366
+ );
367
+ });
368
+
369
+ it('should perform git checkout with session context', async () => {
370
+ vi.spyOn(sandbox.client.git, 'checkout').mockResolvedValue({
371
+ success: true,
372
+ stdout: 'Cloned',
373
+ stderr: '',
374
+ branch: 'main',
375
+ targetDir: '/workspace/repo',
376
+ timestamp: new Date().toISOString(),
377
+ } as any);
378
+
379
+ await session.gitCheckout('https://github.com/test/repo.git');
380
+
381
+ expect(sandbox.client.git.checkout).toHaveBeenCalledWith(
382
+ 'https://github.com/test/repo.git',
383
+ 'test-session',
384
+ { branch: undefined, targetDir: undefined }
385
+ );
386
+ });
387
+ });
388
+
389
+ describe('edge cases and error handling', () => {
390
+ it('should handle session creation errors gracefully', async () => {
391
+ vi.mocked(sandbox.client.utils.createSession).mockRejectedValueOnce(
392
+ new Error('Session creation failed')
393
+ );
394
+
395
+ await expect(sandbox.exec('echo test')).rejects.toThrow('Session creation failed');
396
+ });
397
+
398
+ it('should initialize with empty environment when not set', async () => {
399
+ await sandbox.exec('pwd');
400
+
401
+ expect(sandbox.client.utils.createSession).toHaveBeenCalledWith({
402
+ id: expect.any(String),
403
+ env: {},
404
+ cwd: '/workspace',
405
+ });
406
+ });
407
+
408
+ it('should use updated environment after setEnvVars', async () => {
409
+ await sandbox.setEnvVars({ NODE_ENV: 'production', DEBUG: 'true' });
410
+
411
+ await sandbox.exec('env');
412
+
413
+ expect(sandbox.client.utils.createSession).toHaveBeenCalledWith({
414
+ id: expect.any(String),
415
+ env: { NODE_ENV: 'production', DEBUG: 'true' },
416
+ cwd: '/workspace',
417
+ });
418
+ });
419
+ });
420
+
421
+ describe('port exposure - workers.dev detection', () => {
422
+ beforeEach(async () => {
423
+ await sandbox.setSandboxName('test-sandbox');
424
+ vi.spyOn(sandbox.client.ports, 'exposePort').mockResolvedValue({
425
+ success: true,
426
+ port: 8080,
427
+ name: 'test-service',
428
+ exposedAt: new Date().toISOString(),
429
+ } as any);
430
+ });
431
+
432
+ it('should reject workers.dev domains with CustomDomainRequiredError', async () => {
433
+ const hostnames = [
434
+ 'my-worker.workers.dev',
435
+ 'my-worker.my-account.workers.dev'
436
+ ];
437
+
438
+ for (const hostname of hostnames) {
439
+ try {
440
+ await sandbox.exposePort(8080, { name: 'test', hostname });
441
+ // Should not reach here
442
+ expect.fail('Should have thrown CustomDomainRequiredError');
443
+ } catch (error: any) {
444
+ expect(error.name).toBe('CustomDomainRequiredError');
445
+ expect(error.code).toBe('CUSTOM_DOMAIN_REQUIRED');
446
+ expect(error.message).toContain('workers.dev');
447
+ expect(error.message).toContain('custom domain');
448
+ }
449
+ }
450
+
451
+ // Verify client method was never called
452
+ expect(sandbox.client.ports.exposePort).not.toHaveBeenCalled();
453
+ });
454
+
455
+ it('should accept custom domains and subdomains', async () => {
456
+ const testCases = [
457
+ { hostname: 'example.com', description: 'apex domain' },
458
+ { hostname: 'sandbox.example.com', description: 'subdomain' }
459
+ ];
460
+
461
+ for (const { hostname } of testCases) {
462
+ const result = await sandbox.exposePort(8080, { name: 'test', hostname });
463
+ expect(result.url).toContain(hostname);
464
+ expect(result.port).toBe(8080);
465
+ }
466
+ });
467
+
468
+ it('should accept localhost for local development', async () => {
469
+ const result = await sandbox.exposePort(8080, {
470
+ name: 'test',
471
+ hostname: 'localhost:8787'
472
+ });
473
+
474
+ expect(result.url).toContain('localhost');
475
+ expect(sandbox.client.ports.exposePort).toHaveBeenCalled();
476
+ });
477
+ });
478
+
479
+ describe('fetch() override - WebSocket detection', () => {
480
+ let superFetchSpy: any;
481
+
482
+ beforeEach(async () => {
483
+ await sandbox.setSandboxName('test-sandbox');
484
+
485
+ // Spy on Container.prototype.fetch to verify WebSocket routing
486
+ superFetchSpy = vi.spyOn(Container.prototype, 'fetch')
487
+ .mockResolvedValue(new Response('WebSocket response'));
488
+ });
489
+
490
+ afterEach(() => {
491
+ superFetchSpy?.mockRestore();
492
+ });
493
+
494
+ it('should detect WebSocket upgrade header and route to super.fetch', async () => {
495
+ const request = new Request('https://example.com/ws', {
496
+ headers: {
497
+ 'Upgrade': 'websocket',
498
+ 'Connection': 'Upgrade',
499
+ },
500
+ });
501
+
502
+ const response = await sandbox.fetch(request);
503
+
504
+ // Should route through super.fetch() for WebSocket
505
+ expect(superFetchSpy).toHaveBeenCalledTimes(1);
506
+ expect(await response.text()).toBe('WebSocket response');
507
+ });
508
+
509
+ it('should route non-WebSocket requests through containerFetch', async () => {
510
+ // GET request
511
+ const getRequest = new Request('https://example.com/api/data');
512
+ await sandbox.fetch(getRequest);
513
+ expect(superFetchSpy).not.toHaveBeenCalled();
514
+
515
+ vi.clearAllMocks();
516
+
517
+ // POST request
518
+ const postRequest = new Request('https://example.com/api/data', {
519
+ method: 'POST',
520
+ body: JSON.stringify({ data: 'test' }),
521
+ headers: { 'Content-Type': 'application/json' },
522
+ });
523
+ await sandbox.fetch(postRequest);
524
+ expect(superFetchSpy).not.toHaveBeenCalled();
525
+
526
+ vi.clearAllMocks();
527
+
528
+ // SSE request (should not be detected as WebSocket)
529
+ const sseRequest = new Request('https://example.com/events', {
530
+ headers: { 'Accept': 'text/event-stream' },
531
+ });
532
+ await sandbox.fetch(sseRequest);
533
+ expect(superFetchSpy).not.toHaveBeenCalled();
534
+ });
535
+
536
+ it('should preserve WebSocket request unchanged when calling super.fetch()', async () => {
537
+ const request = new Request('https://example.com/ws', {
538
+ headers: {
539
+ 'Upgrade': 'websocket',
540
+ 'Sec-WebSocket-Key': 'test-key-123',
541
+ 'Sec-WebSocket-Version': '13',
542
+ },
543
+ });
544
+
545
+ await sandbox.fetch(request);
546
+
547
+ expect(superFetchSpy).toHaveBeenCalledTimes(1);
548
+ const passedRequest = superFetchSpy.mock.calls[0][0] as Request;
549
+ expect(passedRequest.headers.get('Upgrade')).toBe('websocket');
550
+ expect(passedRequest.headers.get('Sec-WebSocket-Key')).toBe('test-key-123');
551
+ expect(passedRequest.headers.get('Sec-WebSocket-Version')).toBe('13');
552
+ });
553
+ });
554
+ });