@cloudflare/sandbox 0.0.0-e1fa354 → 0.0.0-e489cbb

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 (94) hide show
  1. package/CHANGELOG.md +46 -0
  2. package/Dockerfile +107 -38
  3. package/README.md +89 -771
  4. package/dist/chunk-53JFOF7F.js +2352 -0
  5. package/dist/chunk-53JFOF7F.js.map +1 -0
  6. package/dist/chunk-BFVUNTP4.js +104 -0
  7. package/dist/chunk-BFVUNTP4.js.map +1 -0
  8. package/dist/chunk-EKSWCBCA.js +86 -0
  9. package/dist/chunk-EKSWCBCA.js.map +1 -0
  10. package/dist/chunk-JXZMAU2C.js +559 -0
  11. package/dist/chunk-JXZMAU2C.js.map +1 -0
  12. package/dist/chunk-Z532A7QC.js +78 -0
  13. package/dist/chunk-Z532A7QC.js.map +1 -0
  14. package/dist/file-stream.d.ts +43 -0
  15. package/dist/file-stream.js +9 -0
  16. package/dist/file-stream.js.map +1 -0
  17. package/dist/index.d.ts +9 -0
  18. package/dist/index.js +66 -0
  19. package/dist/index.js.map +1 -0
  20. package/dist/interpreter.d.ts +33 -0
  21. package/dist/interpreter.js +8 -0
  22. package/dist/interpreter.js.map +1 -0
  23. package/dist/request-handler.d.ts +18 -0
  24. package/dist/request-handler.js +12 -0
  25. package/dist/request-handler.js.map +1 -0
  26. package/dist/sandbox-D9K2ypln.d.ts +583 -0
  27. package/dist/sandbox.d.ts +4 -0
  28. package/dist/sandbox.js +12 -0
  29. package/dist/sandbox.js.map +1 -0
  30. package/dist/security.d.ts +31 -0
  31. package/dist/security.js +13 -0
  32. package/dist/security.js.map +1 -0
  33. package/dist/sse-parser.d.ts +28 -0
  34. package/dist/sse-parser.js +11 -0
  35. package/dist/sse-parser.js.map +1 -0
  36. package/package.json +13 -5
  37. package/src/clients/base-client.ts +280 -0
  38. package/src/clients/command-client.ts +115 -0
  39. package/src/clients/file-client.ts +269 -0
  40. package/src/clients/git-client.ts +92 -0
  41. package/src/clients/index.ts +63 -0
  42. package/src/{jupyter-client.ts → clients/interpreter-client.ts} +148 -168
  43. package/src/clients/port-client.ts +105 -0
  44. package/src/clients/process-client.ts +177 -0
  45. package/src/clients/sandbox-client.ts +41 -0
  46. package/src/clients/types.ts +84 -0
  47. package/src/clients/utility-client.ts +94 -0
  48. package/src/errors/adapter.ts +180 -0
  49. package/src/errors/classes.ts +469 -0
  50. package/src/errors/index.ts +105 -0
  51. package/src/file-stream.ts +164 -0
  52. package/src/index.ts +82 -53
  53. package/src/interpreter.ts +22 -13
  54. package/src/request-handler.ts +69 -43
  55. package/src/sandbox.ts +697 -527
  56. package/src/security.ts +14 -23
  57. package/src/sse-parser.ts +4 -8
  58. package/startup.sh +3 -0
  59. package/tests/base-client.test.ts +328 -0
  60. package/tests/command-client.test.ts +407 -0
  61. package/tests/file-client.test.ts +643 -0
  62. package/tests/file-stream.test.ts +306 -0
  63. package/tests/git-client.test.ts +328 -0
  64. package/tests/port-client.test.ts +301 -0
  65. package/tests/process-client.test.ts +658 -0
  66. package/tests/sandbox.test.ts +465 -0
  67. package/tests/sse-parser.test.ts +290 -0
  68. package/tests/utility-client.test.ts +266 -0
  69. package/tests/wrangler.jsonc +35 -0
  70. package/tsconfig.json +9 -1
  71. package/vitest.config.ts +31 -0
  72. package/container_src/bun.lock +0 -122
  73. package/container_src/circuit-breaker.ts +0 -121
  74. package/container_src/control-process.ts +0 -784
  75. package/container_src/handler/exec.ts +0 -185
  76. package/container_src/handler/file.ts +0 -406
  77. package/container_src/handler/git.ts +0 -130
  78. package/container_src/handler/ports.ts +0 -314
  79. package/container_src/handler/process.ts +0 -568
  80. package/container_src/handler/session.ts +0 -92
  81. package/container_src/index.ts +0 -601
  82. package/container_src/isolation.ts +0 -1038
  83. package/container_src/jupyter-server.ts +0 -579
  84. package/container_src/jupyter-service.ts +0 -461
  85. package/container_src/jupyter_config.py +0 -48
  86. package/container_src/mime-processor.ts +0 -255
  87. package/container_src/package.json +0 -18
  88. package/container_src/shell-escape.ts +0 -42
  89. package/container_src/startup.sh +0 -84
  90. package/container_src/types.ts +0 -131
  91. package/src/client.ts +0 -1009
  92. package/src/errors.ts +0 -218
  93. package/src/interpreter-types.ts +0 -383
  94. package/src/types.ts +0 -502
@@ -0,0 +1,407 @@
1
+ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
2
+ import type { ExecuteResponse } from '../src/clients';
3
+ import { CommandClient } from '../src/clients/command-client';
4
+ import { CommandError, CommandNotFoundError, SandboxError } from '../src/errors';
5
+
6
+ describe('CommandClient', () => {
7
+ let client: CommandClient;
8
+ let mockFetch: ReturnType<typeof vi.fn>;
9
+ let onCommandComplete: ReturnType<typeof vi.fn>;
10
+ let onError: ReturnType<typeof vi.fn>;
11
+
12
+ beforeEach(() => {
13
+ vi.clearAllMocks();
14
+
15
+ mockFetch = vi.fn();
16
+ global.fetch = mockFetch as unknown as typeof fetch;
17
+
18
+ onCommandComplete = vi.fn();
19
+ onError = vi.fn();
20
+
21
+ client = new CommandClient({
22
+ baseUrl: 'http://test.com',
23
+ port: 3000,
24
+ onCommandComplete,
25
+ onError,
26
+ });
27
+ });
28
+
29
+ afterEach(() => {
30
+ vi.restoreAllMocks();
31
+ });
32
+
33
+ describe('execute', () => {
34
+ it('should execute simple commands successfully', async () => {
35
+ const mockResponse: ExecuteResponse = {
36
+ success: true,
37
+ stdout: 'Hello World\n',
38
+ stderr: '',
39
+ exitCode: 0,
40
+ command: 'echo "Hello World"',
41
+ timestamp: '2023-01-01T00:00:00Z',
42
+ };
43
+
44
+ mockFetch.mockResolvedValue(new Response(
45
+ JSON.stringify(mockResponse),
46
+ { status: 200 }
47
+ ));
48
+
49
+ const result = await client.execute('echo "Hello World"', 'session-exec');
50
+
51
+ expect(result.success).toBe(true);
52
+ expect(result.stdout).toBe('Hello World\n');
53
+ expect(result.stderr).toBe('');
54
+ expect(result.exitCode).toBe(0);
55
+ expect(result.command).toBe('echo "Hello World"');
56
+ expect(onCommandComplete).toHaveBeenCalledWith(
57
+ true, 0, 'Hello World\n', '', 'echo "Hello World"'
58
+ );
59
+ });
60
+
61
+ it('should handle command failures with proper exit codes', async () => {
62
+ const mockResponse: ExecuteResponse = {
63
+ success: false,
64
+ stdout: '',
65
+ stderr: 'command not found: nonexistent-cmd\n',
66
+ exitCode: 127,
67
+ command: 'nonexistent-cmd',
68
+ timestamp: '2023-01-01T00:00:00Z',
69
+ };
70
+
71
+ mockFetch.mockResolvedValue(new Response(
72
+ JSON.stringify(mockResponse),
73
+ { status: 200 }
74
+ ));
75
+
76
+ const result = await client.execute('nonexistent-cmd', 'session-exec');
77
+
78
+ expect(result.success).toBe(false);
79
+ expect(result.exitCode).toBe(127);
80
+ expect(result.stderr).toContain('command not found');
81
+ expect(result.stdout).toBe('');
82
+ expect(onCommandComplete).toHaveBeenCalledWith(
83
+ false, 127, '', 'command not found: nonexistent-cmd\n', 'nonexistent-cmd'
84
+ );
85
+ });
86
+
87
+ it('should handle container-level errors with proper error mapping', async () => {
88
+ const errorResponse = {
89
+ code: 'COMMAND_NOT_FOUND',
90
+ message: 'Command not found: invalidcmd',
91
+ context: { command: 'invalidcmd' },
92
+ httpStatus: 404,
93
+ timestamp: new Date().toISOString()
94
+ };
95
+
96
+ mockFetch.mockResolvedValue(new Response(
97
+ JSON.stringify(errorResponse),
98
+ { status: 404 }
99
+ ));
100
+
101
+ await expect(client.execute('invalidcmd', 'session-err'))
102
+ .rejects.toThrow(CommandNotFoundError);
103
+ expect(onError).toHaveBeenCalledWith(
104
+ expect.stringContaining('Command not found'),
105
+ 'invalidcmd'
106
+ );
107
+ });
108
+
109
+ it('should handle network failures gracefully', async () => {
110
+ mockFetch.mockRejectedValue(new Error('Network connection failed'));
111
+
112
+ await expect(client.execute('ls', 'session-err'))
113
+ .rejects.toThrow('Network connection failed');
114
+ expect(onError).toHaveBeenCalledWith('Network connection failed', 'ls');
115
+ });
116
+
117
+ it('should handle server errors with proper status codes', async () => {
118
+ const scenarios = [
119
+ { status: 400, code: 'COMMAND_EXECUTION_ERROR', error: CommandError },
120
+ { status: 500, code: 'EXECUTION_ERROR', error: SandboxError },
121
+ ];
122
+
123
+ for (const scenario of scenarios) {
124
+ mockFetch.mockResolvedValueOnce(new Response(
125
+ JSON.stringify({
126
+ code: scenario.code,
127
+ message: 'Test error',
128
+ context: {},
129
+ httpStatus: scenario.status,
130
+ timestamp: new Date().toISOString()
131
+ }),
132
+ { status: scenario.status }
133
+ ));
134
+ await expect(client.execute('test-command', 'session-err'))
135
+ .rejects.toThrow(scenario.error);
136
+ }
137
+ });
138
+
139
+ it('should handle commands with large output', async () => {
140
+ const largeOutput = 'line of output\n'.repeat(10000);
141
+ const mockResponse: ExecuteResponse = {
142
+ success: true,
143
+ stdout: largeOutput,
144
+ stderr: '',
145
+ exitCode: 0,
146
+ command: 'find / -type f',
147
+ timestamp: '2023-01-01T00:00:00Z',
148
+ };
149
+
150
+ mockFetch.mockResolvedValue(new Response(
151
+ JSON.stringify(mockResponse),
152
+ { status: 200 }
153
+ ));
154
+
155
+ const result = await client.execute('find / -type f', 'session-exec');
156
+
157
+ expect(result.success).toBe(true);
158
+ expect(result.stdout.length).toBeGreaterThan(100000);
159
+ expect(result.stdout.split('\n')).toHaveLength(10001);
160
+ expect(result.exitCode).toBe(0);
161
+ });
162
+
163
+ it('should handle concurrent command executions', async () => {
164
+ mockFetch.mockImplementation((url: string, options: RequestInit) => {
165
+ const body = JSON.parse(options.body as string);
166
+ const command = body.command;
167
+ return Promise.resolve(new Response(
168
+ JSON.stringify({
169
+ success: true,
170
+ stdout: `output for ${command}\n`,
171
+ stderr: '',
172
+ exitCode: 0,
173
+ command: command,
174
+ timestamp: '2023-01-01T00:00:00Z',
175
+ }),
176
+ { status: 200 }
177
+ ));
178
+ });
179
+
180
+ const commands = ['echo 1', 'echo 2', 'echo 3', 'pwd', 'ls'];
181
+ const results = await Promise.all(
182
+ commands.map(cmd => client.execute(cmd, 'session-concurrent'))
183
+ );
184
+
185
+ expect(results).toHaveLength(5);
186
+ results.forEach((result, index) => {
187
+ expect(result.success).toBe(true);
188
+ expect(result.stdout).toBe(`output for ${commands[index]}\n`);
189
+ expect(result.exitCode).toBe(0);
190
+ });
191
+ expect(onCommandComplete).toHaveBeenCalledTimes(5);
192
+ });
193
+
194
+ it('should handle malformed server responses', async () => {
195
+ mockFetch.mockResolvedValue(new Response(
196
+ 'invalid json {',
197
+ { status: 200, headers: { 'Content-Type': 'application/json' } }
198
+ ));
199
+
200
+ await expect(client.execute('ls', 'session-err'))
201
+ .rejects.toThrow(SandboxError);
202
+ expect(onError).toHaveBeenCalled();
203
+ });
204
+
205
+ it('should handle empty command input', async () => {
206
+ const errorResponse = {
207
+ code: 'INVALID_COMMAND',
208
+ message: 'Invalid command: empty command provided',
209
+ context: {},
210
+ httpStatus: 400,
211
+ timestamp: new Date().toISOString()
212
+ };
213
+
214
+ mockFetch.mockResolvedValue(new Response(
215
+ JSON.stringify(errorResponse),
216
+ { status: 400 }
217
+ ));
218
+
219
+ await expect(client.execute('', 'session-err'))
220
+ .rejects.toThrow(CommandError);
221
+ });
222
+
223
+ it('should handle streaming command execution', async () => {
224
+ const streamContent = [
225
+ 'data: {"type":"start","command":"tail -f app.log","timestamp":"2023-01-01T00:00:00Z"}\n\n',
226
+ 'data: {"type":"stdout","data":"log line 1\\n","timestamp":"2023-01-01T00:00:01Z"}\n\n',
227
+ 'data: {"type":"stdout","data":"log line 2\\n","timestamp":"2023-01-01T00:00:02Z"}\n\n',
228
+ 'data: {"type":"complete","exitCode":0,"timestamp":"2023-01-01T00:00:03Z"}\n\n'
229
+ ].join('');
230
+
231
+ const mockStream = new ReadableStream({
232
+ start(controller) {
233
+ controller.enqueue(new TextEncoder().encode(streamContent));
234
+ controller.close();
235
+ }
236
+ });
237
+
238
+ mockFetch.mockResolvedValue(new Response(mockStream, {
239
+ status: 200,
240
+ headers: { 'Content-Type': 'text/event-stream' }
241
+ }));
242
+
243
+ const stream = await client.executeStream('tail -f app.log', 'session-stream');
244
+ expect(stream).toBeInstanceOf(ReadableStream);
245
+
246
+ const reader = stream.getReader();
247
+ const decoder = new TextDecoder();
248
+ let content = '';
249
+
250
+ try {
251
+ while (true) {
252
+ const { done, value } = await reader.read();
253
+ if (done) break;
254
+ content += decoder.decode(value);
255
+ }
256
+ } finally {
257
+ reader.releaseLock();
258
+ }
259
+
260
+ expect(content).toContain('tail -f app.log');
261
+ expect(content).toContain('log line 1');
262
+ expect(content).toContain('log line 2');
263
+ expect(content).toContain('"type":"complete"');
264
+ });
265
+
266
+
267
+ it('should handle streaming errors gracefully', async () => {
268
+ const errorResponse = {
269
+ code: 'STREAM_START_ERROR',
270
+ message: 'Command failed to start streaming',
271
+ context: { command: 'invalid-stream-command' },
272
+ httpStatus: 400,
273
+ timestamp: new Date().toISOString()
274
+ };
275
+
276
+ mockFetch.mockResolvedValue(new Response(
277
+ JSON.stringify(errorResponse),
278
+ { status: 400 }
279
+ ));
280
+
281
+ await expect(client.executeStream('invalid-stream-command', 'session-err'))
282
+ .rejects.toThrow(CommandError);
283
+ expect(onError).toHaveBeenCalledWith(
284
+ expect.stringContaining('Command failed to start streaming'),
285
+ 'invalid-stream-command'
286
+ );
287
+ });
288
+
289
+ it('should handle streaming without response body', async () => {
290
+ mockFetch.mockResolvedValue(new Response(null, {
291
+ status: 200,
292
+ headers: { 'Content-Type': 'text/event-stream' }
293
+ }));
294
+
295
+ await expect(client.executeStream('test-command', 'session-err'))
296
+ .rejects.toThrow('No response body for streaming');
297
+ });
298
+
299
+ it('should handle network failures during streaming setup', async () => {
300
+ mockFetch.mockRejectedValue(new Error('Connection lost during streaming'));
301
+
302
+ await expect(client.executeStream('stream-command', 'session-err'))
303
+ .rejects.toThrow('Connection lost during streaming');
304
+ expect(onError).toHaveBeenCalledWith(
305
+ 'Connection lost during streaming',
306
+ 'stream-command'
307
+ );
308
+ });
309
+ });
310
+
311
+ describe('callback integration', () => {
312
+ it('should work without any callbacks', async () => {
313
+ const clientWithoutCallbacks = new CommandClient({
314
+ baseUrl: 'http://test.com',
315
+ port: 3000,
316
+ });
317
+
318
+ const mockResponse: ExecuteResponse = {
319
+ success: true,
320
+ stdout: 'test output\n',
321
+ stderr: '',
322
+ exitCode: 0,
323
+ command: 'echo test',
324
+ timestamp: '2023-01-01T00:00:00Z',
325
+ };
326
+
327
+ mockFetch.mockResolvedValue(new Response(
328
+ JSON.stringify(mockResponse),
329
+ { status: 200 }
330
+ ));
331
+
332
+ const result = await clientWithoutCallbacks.execute('echo test', 'session-nocb');
333
+
334
+ expect(result.success).toBe(true);
335
+ expect(result.stdout).toBe('test output\n');
336
+ });
337
+
338
+ it('should handle errors gracefully without callbacks', async () => {
339
+ const clientWithoutCallbacks = new CommandClient({
340
+ baseUrl: 'http://test.com',
341
+ port: 3000,
342
+ });
343
+
344
+ mockFetch.mockRejectedValue(new Error('Network failed'));
345
+
346
+ await expect(clientWithoutCallbacks.execute('test', 'session-nocb'))
347
+ .rejects.toThrow('Network failed');
348
+ });
349
+
350
+ it('should call onCommandComplete for both success and failure', async () => {
351
+ const successResponse: ExecuteResponse = {
352
+ success: true,
353
+ stdout: 'success\n',
354
+ stderr: '',
355
+ exitCode: 0,
356
+ command: 'echo success',
357
+ timestamp: '2023-01-01T00:00:00Z',
358
+ };
359
+
360
+ mockFetch.mockResolvedValueOnce(new Response(
361
+ JSON.stringify(successResponse),
362
+ { status: 200 }
363
+ ));
364
+
365
+ await client.execute('echo success', 'session-cb');
366
+ expect(onCommandComplete).toHaveBeenLastCalledWith(
367
+ true, 0, 'success\n', '', 'echo success'
368
+ );
369
+
370
+ const failureResponse: ExecuteResponse = {
371
+ success: false,
372
+ stdout: '',
373
+ stderr: 'error\n',
374
+ exitCode: 1,
375
+ command: 'false',
376
+ timestamp: '2023-01-01T00:00:00Z',
377
+ };
378
+
379
+ mockFetch.mockResolvedValueOnce(new Response(
380
+ JSON.stringify(failureResponse),
381
+ { status: 200 }
382
+ ));
383
+
384
+ await client.execute('false', 'session-cb');
385
+ expect(onCommandComplete).toHaveBeenLastCalledWith(
386
+ false, 1, '', 'error\n', 'false'
387
+ );
388
+ });
389
+ });
390
+
391
+ describe('constructor options', () => {
392
+ it('should initialize with minimal options', async () => {
393
+ const minimalClient = new CommandClient();
394
+ expect(minimalClient).toBeDefined();
395
+ });
396
+
397
+ it('should initialize with full options', async () => {
398
+ const fullOptionsClient = new CommandClient({
399
+ baseUrl: 'http://custom.com',
400
+ port: 8080,
401
+ onCommandComplete: vi.fn(),
402
+ onError: vi.fn(),
403
+ });
404
+ expect(fullOptionsClient).toBeDefined();
405
+ });
406
+ });
407
+ });