@cloudflare/sandbox 0.0.0-af082ab → 0.0.0-b4913fb

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 (75) hide show
  1. package/CHANGELOG.md +156 -21
  2. package/Dockerfile +157 -70
  3. package/LICENSE +176 -0
  4. package/README.md +92 -822
  5. package/dist/index.d.ts +1953 -0
  6. package/dist/index.d.ts.map +1 -0
  7. package/dist/index.js +3280 -0
  8. package/dist/index.js.map +1 -0
  9. package/package.json +16 -8
  10. package/src/clients/base-client.ts +295 -0
  11. package/src/clients/command-client.ts +115 -0
  12. package/src/clients/file-client.ts +300 -0
  13. package/src/clients/git-client.ts +98 -0
  14. package/src/clients/index.ts +64 -0
  15. package/src/clients/interpreter-client.ts +333 -0
  16. package/src/clients/port-client.ts +105 -0
  17. package/src/clients/process-client.ts +180 -0
  18. package/src/clients/sandbox-client.ts +39 -0
  19. package/src/clients/types.ts +88 -0
  20. package/src/clients/utility-client.ts +156 -0
  21. package/src/errors/adapter.ts +238 -0
  22. package/src/errors/classes.ts +594 -0
  23. package/src/errors/index.ts +109 -0
  24. package/src/file-stream.ts +123 -116
  25. package/src/index.ts +89 -66
  26. package/src/interpreter.ts +58 -40
  27. package/src/request-handler.ts +94 -55
  28. package/src/sandbox.ts +1009 -497
  29. package/src/security.ts +34 -28
  30. package/src/sse-parser.ts +8 -11
  31. package/src/version.ts +6 -0
  32. package/startup.sh +3 -0
  33. package/tests/base-client.test.ts +364 -0
  34. package/tests/command-client.test.ts +444 -0
  35. package/tests/file-client.test.ts +831 -0
  36. package/tests/file-stream.test.ts +310 -0
  37. package/tests/get-sandbox.test.ts +149 -0
  38. package/tests/git-client.test.ts +487 -0
  39. package/tests/port-client.test.ts +293 -0
  40. package/tests/process-client.test.ts +683 -0
  41. package/tests/request-handler.test.ts +292 -0
  42. package/tests/sandbox.test.ts +739 -0
  43. package/tests/sse-parser.test.ts +291 -0
  44. package/tests/utility-client.test.ts +339 -0
  45. package/tests/version.test.ts +16 -0
  46. package/tests/wrangler.jsonc +35 -0
  47. package/tsconfig.json +9 -1
  48. package/tsdown.config.ts +12 -0
  49. package/vitest.config.ts +31 -0
  50. package/container_src/bun.lock +0 -76
  51. package/container_src/circuit-breaker.ts +0 -121
  52. package/container_src/control-process.ts +0 -784
  53. package/container_src/handler/exec.ts +0 -185
  54. package/container_src/handler/file.ts +0 -457
  55. package/container_src/handler/git.ts +0 -130
  56. package/container_src/handler/ports.ts +0 -314
  57. package/container_src/handler/process.ts +0 -568
  58. package/container_src/handler/session.ts +0 -92
  59. package/container_src/index.ts +0 -601
  60. package/container_src/interpreter-service.ts +0 -276
  61. package/container_src/isolation.ts +0 -1213
  62. package/container_src/mime-processor.ts +0 -255
  63. package/container_src/package.json +0 -18
  64. package/container_src/runtime/executors/javascript/node_executor.ts +0 -123
  65. package/container_src/runtime/executors/python/ipython_executor.py +0 -338
  66. package/container_src/runtime/executors/typescript/ts_executor.ts +0 -138
  67. package/container_src/runtime/process-pool.ts +0 -464
  68. package/container_src/shell-escape.ts +0 -42
  69. package/container_src/startup.sh +0 -11
  70. package/container_src/types.ts +0 -131
  71. package/src/client.ts +0 -1048
  72. package/src/errors.ts +0 -219
  73. package/src/interpreter-client.ts +0 -352
  74. package/src/interpreter-types.ts +0 -390
  75. package/src/types.ts +0 -571
@@ -0,0 +1,831 @@
1
+ import type {
2
+ DeleteFileResult,
3
+ FileExistsResult,
4
+ ListFilesResult,
5
+ MkdirResult,
6
+ MoveFileResult,
7
+ ReadFileResult,
8
+ RenameFileResult,
9
+ WriteFileResult
10
+ } from '@repo/shared';
11
+ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
12
+ import { FileClient } from '../src/clients/file-client';
13
+ import {
14
+ FileExistsError,
15
+ FileNotFoundError,
16
+ FileSystemError,
17
+ PermissionDeniedError,
18
+ SandboxError
19
+ } from '../src/errors';
20
+
21
+ describe('FileClient', () => {
22
+ let client: FileClient;
23
+ let mockFetch: ReturnType<typeof vi.fn>;
24
+
25
+ beforeEach(() => {
26
+ vi.clearAllMocks();
27
+
28
+ mockFetch = vi.fn();
29
+ global.fetch = mockFetch as unknown as typeof fetch;
30
+
31
+ client = new FileClient({
32
+ baseUrl: 'http://test.com',
33
+ port: 3000
34
+ });
35
+ });
36
+
37
+ afterEach(() => {
38
+ vi.restoreAllMocks();
39
+ });
40
+
41
+ describe('mkdir', () => {
42
+ it('should create directories successfully', async () => {
43
+ const mockResponse: MkdirResult = {
44
+ success: true,
45
+ exitCode: 0,
46
+ path: '/app/new-directory',
47
+ recursive: false,
48
+ timestamp: '2023-01-01T00:00:00Z'
49
+ };
50
+
51
+ mockFetch.mockResolvedValue(
52
+ new Response(JSON.stringify(mockResponse), { status: 200 })
53
+ );
54
+
55
+ const result = await client.mkdir('/app/new-directory', 'session-mkdir');
56
+
57
+ expect(result.success).toBe(true);
58
+ expect(result.path).toBe('/app/new-directory');
59
+ expect(result.recursive).toBe(false);
60
+ expect(result.exitCode).toBe(0);
61
+ });
62
+
63
+ it('should create directories recursively', async () => {
64
+ const mockResponse: MkdirResult = {
65
+ success: true,
66
+ exitCode: 0,
67
+ path: '/app/deep/nested/directory',
68
+ recursive: true,
69
+ timestamp: '2023-01-01T00:00:00Z'
70
+ };
71
+
72
+ mockFetch.mockResolvedValue(
73
+ new Response(JSON.stringify(mockResponse), { status: 200 })
74
+ );
75
+
76
+ const result = await client.mkdir(
77
+ '/app/deep/nested/directory',
78
+ 'session-mkdir',
79
+ { recursive: true }
80
+ );
81
+
82
+ expect(result.success).toBe(true);
83
+ expect(result.recursive).toBe(true);
84
+ expect(result.path).toBe('/app/deep/nested/directory');
85
+ });
86
+
87
+ it('should handle permission denied errors', async () => {
88
+ const errorResponse = {
89
+ error: 'Permission denied: cannot create directory /root/secure',
90
+ code: 'PERMISSION_DENIED',
91
+ path: '/root/secure'
92
+ };
93
+
94
+ mockFetch.mockResolvedValue(
95
+ new Response(JSON.stringify(errorResponse), { status: 403 })
96
+ );
97
+
98
+ await expect(
99
+ client.mkdir('/root/secure', 'session-mkdir')
100
+ ).rejects.toThrow(PermissionDeniedError);
101
+ });
102
+
103
+ it('should handle directory already exists errors', async () => {
104
+ const errorResponse = {
105
+ error: 'Directory already exists: /app/existing',
106
+ code: 'FILE_EXISTS',
107
+ path: '/app/existing'
108
+ };
109
+
110
+ mockFetch.mockResolvedValue(
111
+ new Response(JSON.stringify(errorResponse), { status: 409 })
112
+ );
113
+
114
+ await expect(
115
+ client.mkdir('/app/existing', 'session-mkdir')
116
+ ).rejects.toThrow(FileExistsError);
117
+ });
118
+ });
119
+
120
+ describe('writeFile', () => {
121
+ it('should write files successfully', async () => {
122
+ const mockResponse: WriteFileResult = {
123
+ success: true,
124
+ exitCode: 0,
125
+ path: '/app/config.json',
126
+ timestamp: '2023-01-01T00:00:00Z'
127
+ };
128
+
129
+ mockFetch.mockResolvedValue(
130
+ new Response(JSON.stringify(mockResponse), { status: 200 })
131
+ );
132
+
133
+ const content = '{"setting": "value", "enabled": true}';
134
+ const result = await client.writeFile(
135
+ '/app/config.json',
136
+ content,
137
+ 'session-write'
138
+ );
139
+
140
+ expect(result.success).toBe(true);
141
+ expect(result.path).toBe('/app/config.json');
142
+ expect(result.exitCode).toBe(0);
143
+ });
144
+
145
+ it('should write files with different encodings', async () => {
146
+ const mockResponse: WriteFileResult = {
147
+ success: true,
148
+ exitCode: 0,
149
+ path: '/app/image.png',
150
+ timestamp: '2023-01-01T00:00:00Z'
151
+ };
152
+
153
+ mockFetch.mockResolvedValue(
154
+ new Response(JSON.stringify(mockResponse), { status: 200 })
155
+ );
156
+
157
+ const binaryData =
158
+ 'iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mNkYPhfDwAChAI9jYlkKQAAAABJRU5ErkJggg==';
159
+ const result = await client.writeFile(
160
+ '/app/image.png',
161
+ binaryData,
162
+ 'session-write',
163
+ { encoding: 'base64' }
164
+ );
165
+
166
+ expect(result.success).toBe(true);
167
+ expect(result.path).toBe('/app/image.png');
168
+ });
169
+
170
+ it('should handle write permission errors', async () => {
171
+ const errorResponse = {
172
+ error: 'Permission denied: cannot write to /system/readonly.txt',
173
+ code: 'PERMISSION_DENIED',
174
+ path: '/system/readonly.txt'
175
+ };
176
+
177
+ mockFetch.mockResolvedValue(
178
+ new Response(JSON.stringify(errorResponse), { status: 403 })
179
+ );
180
+
181
+ await expect(
182
+ client.writeFile('/system/readonly.txt', 'content', 'session-err')
183
+ ).rejects.toThrow(PermissionDeniedError);
184
+ });
185
+
186
+ it('should handle disk space errors', async () => {
187
+ const errorResponse = {
188
+ error: 'No space left on device',
189
+ code: 'NO_SPACE',
190
+ path: '/app/largefile.dat'
191
+ };
192
+
193
+ mockFetch.mockResolvedValue(
194
+ new Response(JSON.stringify(errorResponse), { status: 507 })
195
+ );
196
+
197
+ await expect(
198
+ client.writeFile(
199
+ '/app/largefile.dat',
200
+ 'x'.repeat(1000000),
201
+ 'session-err'
202
+ )
203
+ ).rejects.toThrow(FileSystemError);
204
+ });
205
+ });
206
+
207
+ describe('readFile', () => {
208
+ it('should read text files successfully with metadata', async () => {
209
+ const fileContent = `# Configuration File
210
+ server:
211
+ port: 3000
212
+ host: localhost
213
+ database:
214
+ url: postgresql://localhost/app`;
215
+
216
+ const mockResponse: ReadFileResult = {
217
+ success: true,
218
+ exitCode: 0,
219
+ path: '/app/config.yaml',
220
+ content: fileContent,
221
+ timestamp: '2023-01-01T00:00:00Z',
222
+ encoding: 'utf-8',
223
+ isBinary: false,
224
+ mimeType: 'text/yaml',
225
+ size: 100
226
+ };
227
+
228
+ mockFetch.mockResolvedValue(
229
+ new Response(JSON.stringify(mockResponse), { status: 200 })
230
+ );
231
+
232
+ const result = await client.readFile('/app/config.yaml', 'session-read');
233
+
234
+ expect(result.success).toBe(true);
235
+ expect(result.path).toBe('/app/config.yaml');
236
+ expect(result.content).toContain('port: 3000');
237
+ expect(result.content).toContain('postgresql://localhost/app');
238
+ expect(result.exitCode).toBe(0);
239
+ expect(result.encoding).toBe('utf-8');
240
+ expect(result.isBinary).toBe(false);
241
+ expect(result.mimeType).toBe('text/yaml');
242
+ expect(result.size).toBe(100);
243
+ });
244
+
245
+ it('should read binary files with base64 encoding and metadata', async () => {
246
+ const binaryContent =
247
+ 'iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mNkYPhfDwAChAI9jYlkKQAAAABJRU5ErkJggg==';
248
+ const mockResponse: ReadFileResult = {
249
+ success: true,
250
+ exitCode: 0,
251
+ path: '/app/logo.png',
252
+ content: binaryContent,
253
+ timestamp: '2023-01-01T00:00:00Z',
254
+ encoding: 'base64',
255
+ isBinary: true,
256
+ mimeType: 'image/png',
257
+ size: 95
258
+ };
259
+
260
+ mockFetch.mockResolvedValue(
261
+ new Response(JSON.stringify(mockResponse), { status: 200 })
262
+ );
263
+
264
+ const result = await client.readFile('/app/logo.png', 'session-read', {
265
+ encoding: 'base64'
266
+ });
267
+
268
+ expect(result.success).toBe(true);
269
+ expect(result.content).toBe(binaryContent);
270
+ expect(result.content.startsWith('iVBORw0K')).toBe(true);
271
+ expect(result.encoding).toBe('base64');
272
+ expect(result.isBinary).toBe(true);
273
+ expect(result.mimeType).toBe('image/png');
274
+ expect(result.size).toBe(95);
275
+ });
276
+
277
+ it('should handle file not found errors', async () => {
278
+ const errorResponse = {
279
+ error: 'File not found: /app/missing.txt',
280
+ code: 'FILE_NOT_FOUND',
281
+ path: '/app/missing.txt'
282
+ };
283
+
284
+ mockFetch.mockResolvedValue(
285
+ new Response(JSON.stringify(errorResponse), { status: 404 })
286
+ );
287
+
288
+ await expect(
289
+ client.readFile('/app/missing.txt', 'session-read')
290
+ ).rejects.toThrow(FileNotFoundError);
291
+ });
292
+
293
+ it('should handle directory read attempts', async () => {
294
+ const errorResponse = {
295
+ error: 'Is a directory: /app/logs',
296
+ code: 'IS_DIRECTORY',
297
+ path: '/app/logs'
298
+ };
299
+
300
+ mockFetch.mockResolvedValue(
301
+ new Response(JSON.stringify(errorResponse), { status: 400 })
302
+ );
303
+
304
+ await expect(
305
+ client.readFile('/app/logs', 'session-read')
306
+ ).rejects.toThrow(FileSystemError);
307
+ });
308
+ });
309
+
310
+ describe('readFileStream', () => {
311
+ it('should stream file successfully', async () => {
312
+ const mockStream = new ReadableStream({
313
+ start(controller) {
314
+ controller.enqueue(
315
+ new TextEncoder().encode(
316
+ 'data: {"type":"metadata","mimeType":"text/plain","size":100,"isBinary":false,"encoding":"utf-8"}\n\n'
317
+ )
318
+ );
319
+ controller.enqueue(
320
+ new TextEncoder().encode(
321
+ 'data: {"type":"chunk","data":"Hello"}\n\n'
322
+ )
323
+ );
324
+ controller.enqueue(
325
+ new TextEncoder().encode(
326
+ 'data: {"type":"complete","bytesRead":5}\n\n'
327
+ )
328
+ );
329
+ controller.close();
330
+ }
331
+ });
332
+
333
+ mockFetch.mockResolvedValue(
334
+ new Response(mockStream, {
335
+ status: 200,
336
+ headers: { 'Content-Type': 'text/event-stream' }
337
+ })
338
+ );
339
+
340
+ const result = await client.readFileStream(
341
+ '/app/test.txt',
342
+ 'session-stream'
343
+ );
344
+
345
+ expect(result).toBeInstanceOf(ReadableStream);
346
+ expect(mockFetch).toHaveBeenCalledWith(
347
+ expect.stringContaining('/api/read/stream'),
348
+ expect.objectContaining({
349
+ method: 'POST',
350
+ body: JSON.stringify({
351
+ path: '/app/test.txt',
352
+ sessionId: 'session-stream'
353
+ })
354
+ })
355
+ );
356
+ });
357
+
358
+ it('should handle binary file streams', async () => {
359
+ const mockStream = new ReadableStream({
360
+ start(controller) {
361
+ controller.enqueue(
362
+ new TextEncoder().encode(
363
+ 'data: {"type":"metadata","mimeType":"image/png","size":1024,"isBinary":true,"encoding":"base64"}\n\n'
364
+ )
365
+ );
366
+ controller.enqueue(
367
+ new TextEncoder().encode(
368
+ 'data: {"type":"chunk","data":"iVBORw0K"}\n\n'
369
+ )
370
+ );
371
+ controller.enqueue(
372
+ new TextEncoder().encode(
373
+ 'data: {"type":"complete","bytesRead":1024}\n\n'
374
+ )
375
+ );
376
+ controller.close();
377
+ }
378
+ });
379
+
380
+ mockFetch.mockResolvedValue(
381
+ new Response(mockStream, {
382
+ status: 200,
383
+ headers: { 'Content-Type': 'text/event-stream' }
384
+ })
385
+ );
386
+
387
+ const result = await client.readFileStream(
388
+ '/app/image.png',
389
+ 'session-stream'
390
+ );
391
+
392
+ expect(result).toBeInstanceOf(ReadableStream);
393
+ });
394
+
395
+ it('should handle stream errors', async () => {
396
+ const errorResponse = {
397
+ error: 'File not found: /app/missing.txt',
398
+ code: 'FILE_NOT_FOUND',
399
+ path: '/app/missing.txt'
400
+ };
401
+
402
+ mockFetch.mockResolvedValue(
403
+ new Response(JSON.stringify(errorResponse), { status: 404 })
404
+ );
405
+
406
+ await expect(
407
+ client.readFileStream('/app/missing.txt', 'session-stream')
408
+ ).rejects.toThrow(FileNotFoundError);
409
+ });
410
+
411
+ it('should handle network errors during streaming', async () => {
412
+ mockFetch.mockRejectedValue(new Error('Network timeout'));
413
+
414
+ await expect(
415
+ client.readFileStream('/app/file.txt', 'session-stream')
416
+ ).rejects.toThrow('Network timeout');
417
+ });
418
+ });
419
+
420
+ describe('deleteFile', () => {
421
+ it('should delete files successfully', async () => {
422
+ const mockResponse: DeleteFileResult = {
423
+ success: true,
424
+ exitCode: 0,
425
+ path: '/app/temp.txt',
426
+ timestamp: '2023-01-01T00:00:00Z'
427
+ };
428
+
429
+ mockFetch.mockResolvedValue(
430
+ new Response(JSON.stringify(mockResponse), { status: 200 })
431
+ );
432
+
433
+ const result = await client.deleteFile('/app/temp.txt', 'session-delete');
434
+
435
+ expect(result.success).toBe(true);
436
+ expect(result.path).toBe('/app/temp.txt');
437
+ expect(result.exitCode).toBe(0);
438
+ });
439
+
440
+ it('should handle delete non-existent file', async () => {
441
+ const errorResponse = {
442
+ error: 'File not found: /app/nonexistent.txt',
443
+ code: 'FILE_NOT_FOUND',
444
+ path: '/app/nonexistent.txt'
445
+ };
446
+
447
+ mockFetch.mockResolvedValue(
448
+ new Response(JSON.stringify(errorResponse), { status: 404 })
449
+ );
450
+
451
+ await expect(
452
+ client.deleteFile('/app/nonexistent.txt', 'session-delete')
453
+ ).rejects.toThrow(FileNotFoundError);
454
+ });
455
+
456
+ it('should handle delete permission errors', async () => {
457
+ const errorResponse = {
458
+ error: 'Permission denied: cannot delete /system/important.conf',
459
+ code: 'PERMISSION_DENIED',
460
+ path: '/system/important.conf'
461
+ };
462
+
463
+ mockFetch.mockResolvedValue(
464
+ new Response(JSON.stringify(errorResponse), { status: 403 })
465
+ );
466
+
467
+ await expect(
468
+ client.deleteFile('/system/important.conf', 'session-delete')
469
+ ).rejects.toThrow(PermissionDeniedError);
470
+ });
471
+ });
472
+
473
+ describe('renameFile', () => {
474
+ it('should rename files successfully', async () => {
475
+ const mockResponse: RenameFileResult = {
476
+ success: true,
477
+ exitCode: 0,
478
+ path: '/app/old-name.txt',
479
+ newPath: '/app/new-name.txt',
480
+ timestamp: '2023-01-01T00:00:00Z'
481
+ };
482
+
483
+ mockFetch.mockResolvedValue(
484
+ new Response(JSON.stringify(mockResponse), { status: 200 })
485
+ );
486
+
487
+ const result = await client.renameFile(
488
+ '/app/old-name.txt',
489
+ '/app/new-name.txt',
490
+ 'session-rename'
491
+ );
492
+
493
+ expect(result.success).toBe(true);
494
+ expect(result.path).toBe('/app/old-name.txt');
495
+ expect(result.newPath).toBe('/app/new-name.txt');
496
+ expect(result.exitCode).toBe(0);
497
+ });
498
+
499
+ it('should handle rename to existing file', async () => {
500
+ const errorResponse = {
501
+ error: 'Target file already exists: /app/existing.txt',
502
+ code: 'FILE_EXISTS',
503
+ path: '/app/existing.txt'
504
+ };
505
+
506
+ mockFetch.mockResolvedValue(
507
+ new Response(JSON.stringify(errorResponse), { status: 409 })
508
+ );
509
+
510
+ await expect(
511
+ client.renameFile(
512
+ '/app/source.txt',
513
+ '/app/existing.txt',
514
+ 'session-rename'
515
+ )
516
+ ).rejects.toThrow(FileExistsError);
517
+ });
518
+ });
519
+
520
+ describe('moveFile', () => {
521
+ it('should move files successfully', async () => {
522
+ const mockResponse: MoveFileResult = {
523
+ success: true,
524
+ exitCode: 0,
525
+ path: '/src/document.pdf',
526
+ newPath: '/dest/document.pdf',
527
+ timestamp: '2023-01-01T00:00:00Z'
528
+ };
529
+
530
+ mockFetch.mockResolvedValue(
531
+ new Response(JSON.stringify(mockResponse), { status: 200 })
532
+ );
533
+
534
+ const result = await client.moveFile(
535
+ '/src/document.pdf',
536
+ '/dest/document.pdf',
537
+ 'session-move'
538
+ );
539
+
540
+ expect(result.success).toBe(true);
541
+ expect(result.path).toBe('/src/document.pdf');
542
+ expect(result.newPath).toBe('/dest/document.pdf');
543
+ expect(result.exitCode).toBe(0);
544
+ });
545
+
546
+ it('should handle move to non-existent directory', async () => {
547
+ const errorResponse = {
548
+ error: 'Destination directory does not exist: /nonexistent/',
549
+ code: 'NOT_DIRECTORY',
550
+ path: '/nonexistent/'
551
+ };
552
+
553
+ mockFetch.mockResolvedValue(
554
+ new Response(JSON.stringify(errorResponse), { status: 404 })
555
+ );
556
+
557
+ await expect(
558
+ client.moveFile(
559
+ '/app/file.txt',
560
+ '/nonexistent/file.txt',
561
+ 'session-move'
562
+ )
563
+ ).rejects.toThrow(FileSystemError);
564
+ });
565
+ });
566
+
567
+ describe('listFiles', () => {
568
+ const createMockFile = (overrides: Partial<any> = {}) => ({
569
+ name: 'test.txt',
570
+ absolutePath: '/workspace/test.txt',
571
+ relativePath: 'test.txt',
572
+ type: 'file' as const,
573
+ size: 1024,
574
+ modifiedAt: '2023-01-01T00:00:00Z',
575
+ mode: 'rw-r--r--',
576
+ permissions: { readable: true, writable: true, executable: false },
577
+ ...overrides
578
+ });
579
+
580
+ it('should list files with correct structure', async () => {
581
+ const mockResponse: ListFilesResult = {
582
+ success: true,
583
+ path: '/workspace',
584
+ files: [
585
+ createMockFile({ name: 'file.txt' }),
586
+ createMockFile({ name: 'dir', type: 'directory', mode: 'rwxr-xr-x' })
587
+ ],
588
+ count: 2,
589
+ timestamp: '2023-01-01T00:00:00Z'
590
+ };
591
+
592
+ mockFetch.mockResolvedValue(
593
+ new Response(JSON.stringify(mockResponse), { status: 200 })
594
+ );
595
+
596
+ const result = await client.listFiles('/workspace', 'session-list');
597
+
598
+ expect(result.success).toBe(true);
599
+ expect(result.count).toBe(2);
600
+ expect(result.files[0].name).toBe('file.txt');
601
+ expect(result.files[1].name).toBe('dir');
602
+ expect(result.files[1].type).toBe('directory');
603
+ });
604
+
605
+ it('should pass options correctly', async () => {
606
+ const mockResponse: ListFilesResult = {
607
+ success: true,
608
+ path: '/workspace',
609
+ files: [createMockFile({ name: '.hidden', relativePath: '.hidden' })],
610
+ count: 1,
611
+ timestamp: '2023-01-01T00:00:00Z'
612
+ };
613
+
614
+ mockFetch.mockResolvedValue(
615
+ new Response(JSON.stringify(mockResponse), { status: 200 })
616
+ );
617
+
618
+ await client.listFiles('/workspace', 'session-list', {
619
+ recursive: true,
620
+ includeHidden: true
621
+ });
622
+
623
+ expect(mockFetch).toHaveBeenCalledWith(
624
+ expect.stringContaining('/api/list-files'),
625
+ expect.objectContaining({
626
+ body: JSON.stringify({
627
+ path: '/workspace',
628
+ sessionId: 'session-list',
629
+ options: { recursive: true, includeHidden: true }
630
+ })
631
+ })
632
+ );
633
+ });
634
+
635
+ it('should handle empty directories', async () => {
636
+ mockFetch.mockResolvedValue(
637
+ new Response(
638
+ JSON.stringify({
639
+ success: true,
640
+ path: '/empty',
641
+ files: [],
642
+ count: 0,
643
+ timestamp: '2023-01-01T00:00:00Z'
644
+ }),
645
+ { status: 200 }
646
+ )
647
+ );
648
+
649
+ const result = await client.listFiles('/empty', 'session-list');
650
+
651
+ expect(result.count).toBe(0);
652
+ expect(result.files).toHaveLength(0);
653
+ });
654
+
655
+ it('should handle error responses', async () => {
656
+ mockFetch.mockResolvedValue(
657
+ new Response(
658
+ JSON.stringify({
659
+ error: 'Directory not found',
660
+ code: 'FILE_NOT_FOUND'
661
+ }),
662
+ { status: 404 }
663
+ )
664
+ );
665
+
666
+ await expect(
667
+ client.listFiles('/nonexistent', 'session-list')
668
+ ).rejects.toThrow(FileNotFoundError);
669
+ });
670
+ });
671
+
672
+ describe('exists', () => {
673
+ it('should return true when file exists', async () => {
674
+ const mockResponse: FileExistsResult = {
675
+ success: true,
676
+ path: '/workspace/test.txt',
677
+ exists: true,
678
+ timestamp: '2023-01-01T00:00:00Z'
679
+ };
680
+
681
+ mockFetch.mockResolvedValue(
682
+ new Response(JSON.stringify(mockResponse), { status: 200 })
683
+ );
684
+
685
+ const result = await client.exists(
686
+ '/workspace/test.txt',
687
+ 'session-exists'
688
+ );
689
+
690
+ expect(result.success).toBe(true);
691
+ expect(result.exists).toBe(true);
692
+ expect(result.path).toBe('/workspace/test.txt');
693
+ });
694
+
695
+ it('should return false when file does not exist', async () => {
696
+ const mockResponse: FileExistsResult = {
697
+ success: true,
698
+ path: '/workspace/nonexistent.txt',
699
+ exists: false,
700
+ timestamp: '2023-01-01T00:00:00Z'
701
+ };
702
+
703
+ mockFetch.mockResolvedValue(
704
+ new Response(JSON.stringify(mockResponse), { status: 200 })
705
+ );
706
+
707
+ const result = await client.exists(
708
+ '/workspace/nonexistent.txt',
709
+ 'session-exists'
710
+ );
711
+
712
+ expect(result.success).toBe(true);
713
+ expect(result.exists).toBe(false);
714
+ });
715
+
716
+ it('should return true when directory exists', async () => {
717
+ const mockResponse: FileExistsResult = {
718
+ success: true,
719
+ path: '/workspace/some-dir',
720
+ exists: true,
721
+ timestamp: '2023-01-01T00:00:00Z'
722
+ };
723
+
724
+ mockFetch.mockResolvedValue(
725
+ new Response(JSON.stringify(mockResponse), { status: 200 })
726
+ );
727
+
728
+ const result = await client.exists(
729
+ '/workspace/some-dir',
730
+ 'session-exists'
731
+ );
732
+
733
+ expect(result.success).toBe(true);
734
+ expect(result.exists).toBe(true);
735
+ });
736
+
737
+ it('should send correct request payload', async () => {
738
+ const mockResponse: FileExistsResult = {
739
+ success: true,
740
+ path: '/test/path',
741
+ exists: true,
742
+ timestamp: '2023-01-01T00:00:00Z'
743
+ };
744
+
745
+ mockFetch.mockResolvedValue(
746
+ new Response(JSON.stringify(mockResponse), { status: 200 })
747
+ );
748
+
749
+ await client.exists('/test/path', 'session-test');
750
+
751
+ expect(mockFetch).toHaveBeenCalledWith(
752
+ expect.stringContaining('/api/exists'),
753
+ expect.objectContaining({
754
+ method: 'POST',
755
+ body: JSON.stringify({
756
+ path: '/test/path',
757
+ sessionId: 'session-test'
758
+ })
759
+ })
760
+ );
761
+ });
762
+ });
763
+
764
+ describe('error handling', () => {
765
+ it('should handle network failures gracefully', async () => {
766
+ mockFetch.mockRejectedValue(new Error('Network connection failed'));
767
+
768
+ await expect(
769
+ client.readFile('/app/file.txt', 'session-read')
770
+ ).rejects.toThrow('Network connection failed');
771
+ });
772
+
773
+ it('should handle malformed server responses', async () => {
774
+ mockFetch.mockResolvedValue(
775
+ new Response('invalid json {', {
776
+ status: 200,
777
+ headers: { 'Content-Type': 'application/json' }
778
+ })
779
+ );
780
+
781
+ await expect(
782
+ client.writeFile('/app/file.txt', 'content', 'session-err')
783
+ ).rejects.toThrow(SandboxError);
784
+ });
785
+
786
+ it('should handle server errors with proper mapping', async () => {
787
+ const serverErrorScenarios = [
788
+ { status: 400, code: 'FILESYSTEM_ERROR', error: FileSystemError },
789
+ {
790
+ status: 403,
791
+ code: 'PERMISSION_DENIED',
792
+ error: PermissionDeniedError
793
+ },
794
+ { status: 404, code: 'FILE_NOT_FOUND', error: FileNotFoundError },
795
+ { status: 409, code: 'FILE_EXISTS', error: FileExistsError },
796
+ { status: 500, code: 'INTERNAL_ERROR', error: SandboxError }
797
+ ];
798
+
799
+ for (const scenario of serverErrorScenarios) {
800
+ mockFetch.mockResolvedValueOnce(
801
+ new Response(
802
+ JSON.stringify({
803
+ error: 'Test error',
804
+ code: scenario.code
805
+ }),
806
+ { status: scenario.status }
807
+ )
808
+ );
809
+
810
+ await expect(
811
+ client.readFile('/app/test.txt', 'session-read')
812
+ ).rejects.toThrow(scenario.error);
813
+ }
814
+ });
815
+ });
816
+
817
+ describe('constructor options', () => {
818
+ it('should initialize with minimal options', () => {
819
+ const minimalClient = new FileClient();
820
+ expect(minimalClient).toBeDefined();
821
+ });
822
+
823
+ it('should initialize with full options', () => {
824
+ const fullOptionsClient = new FileClient({
825
+ baseUrl: 'http://custom.com',
826
+ port: 8080
827
+ });
828
+ expect(fullOptionsClient).toBeDefined();
829
+ });
830
+ });
831
+ });