-
Notifications
You must be signed in to change notification settings - Fork 1k
Expand file tree
/
Copy pathindex.ts
More file actions
694 lines (621 loc) · 16.8 KB
/
Copy pathindex.ts
File metadata and controls
694 lines (621 loc) · 16.8 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
import { ApiClient, handleApiError, components as ApiComponents } from '../api'
import {
VolumeApiClient,
VolumeApiComponents,
VolumeConnectionConfig,
VolumeApiOpts,
FILE_TIMEOUT_MS,
} from './client'
import { ConnectionConfig, ConnectionOpts } from '../connectionConfig'
import { NotFoundError, VolumeError } from '../errors'
import { runtime, toBlob } from '../utils'
import { VolumeFileType } from './types'
import type {
VolumeAndToken,
VolumeEntryStat,
VolumeInfo,
VolumeMetadataOptions,
VolumeWriteOptions,
} from './types'
/**
* Convert API VolumeEntryStat to SDK VolumeEntryStat.
*/
function convertVolumeEntryStat(
entry: VolumeApiComponents['schemas']['VolumeEntryStat']
): VolumeEntryStat {
return {
...entry,
type: entry.type as VolumeFileType,
atime: new Date(entry.atime),
mtime: new Date(entry.mtime),
ctime: new Date(entry.ctime),
}
}
/**
* Module for interacting with E2B volumes.
*
* Create a `Volume` instance to interact with a volume by its ID,
* or use the static methods to manage volumes.
*/
export class Volume {
/**
* Volume ID.
*/
readonly volumeId: string
/**
* Volume name.
*/
readonly name: string
/**
* Volume auth token.
*/
readonly token: string
/**
* Domain used for constructing the volume API URL.
*/
readonly domain?: string
/**
* Whether to use debug mode (connects to local volume API server).
*/
readonly debug?: boolean
/**
* Proxy URL used for requests to the volume content API.
*/
readonly proxy?: string
/**
* Create a local Volume instance with no API call.
*
* @param volumeId volume ID.
* @param name volume name.
* @param token volume auth token.
* @param domain domain for the volume API.
* @param debug whether to use debug mode.
* @param proxy proxy URL for the volume content API.
*/
constructor(
volumeId: string,
name: string,
token: string,
domain?: string,
debug?: boolean,
proxy?: string
) {
this.volumeId = volumeId
this.name = name
this.token = token
this.domain = domain
this.debug = debug
this.proxy = proxy
}
/**
* Create a new volume.
*
* @param name name of the volume.
* @param opts connection options.
*
* @returns new Volume instance.
*/
static async create(name: string, opts?: ConnectionOpts): Promise<Volume> {
const config = new ConnectionConfig(opts)
const client = new ApiClient(config)
const res = await client.api.POST('/volumes', {
body: {
name,
},
signal: config.getSignal(opts?.requestTimeoutMs, opts?.signal),
})
const err = handleApiError(res, VolumeError)
if (err) {
throw err
}
if (!res.data) {
throw new Error('Response data is missing')
}
return new Volume(
res.data.volumeID,
res.data.name,
res.data.token,
config.domain,
config.debug,
config.proxy
)
}
/**
* Connect to an existing volume by ID.
*
* @param volumeId volume ID.
* @param opts connection options.
*
* @returns Volume instance.
*/
static async connect(
volumeId: string,
opts?: ConnectionOpts
): Promise<Volume> {
const config = new ConnectionConfig(opts)
const { name, token } = await Volume.getInfo(volumeId, opts)
return new Volume(
volumeId,
name,
token,
config.domain,
config.debug,
config.proxy
)
}
/**
* Get volume information.
*
* @param volumeId volume ID.
* @param opts connection options.
*
* @returns volume information.
*/
static async getInfo(
volumeId: string,
opts?: ConnectionOpts
): Promise<VolumeAndToken> {
const config = new ConnectionConfig(opts)
const client = new ApiClient(config)
const res = await client.api.GET('/volumes/{volumeID}', {
params: {
path: {
volumeID: volumeId,
},
},
signal: config.getSignal(opts?.requestTimeoutMs, opts?.signal),
})
if (res.response.status === 404) {
throw new NotFoundError(`Volume ${volumeId} not found`)
}
const err = handleApiError(res, VolumeError)
if (err) {
throw err
}
return {
volumeId: res.data!.volumeID,
name: res.data!.name,
token: res.data!.token,
}
}
/**
* List all volumes.
*
* @param opts connection options.
*
* @returns list of volume information.
*/
static async list(opts?: ConnectionOpts): Promise<VolumeInfo[]> {
const config = new ConnectionConfig(opts)
const client = new ApiClient(config)
const res = await client.api.GET('/volumes', {
signal: config.getSignal(opts?.requestTimeoutMs, opts?.signal),
})
const err = handleApiError(res, VolumeError)
if (err) {
throw err
}
return (res.data ?? []).map((vol: ApiComponents['schemas']['Volume']) => ({
volumeId: vol.volumeID,
name: vol.name,
}))
}
/**
* Destroy a volume.
*
* @param volumeId volume ID.
* @param opts connection options.
*/
static async destroy(
volumeId: string,
opts?: ConnectionOpts
): Promise<boolean> {
const config = new ConnectionConfig(opts)
const client = new ApiClient(config)
const res = await client.api.DELETE('/volumes/{volumeID}', {
params: {
path: {
volumeID: volumeId,
},
},
signal: config.getSignal(opts?.requestTimeoutMs, opts?.signal),
})
if (res.response.status === 404) {
return false
}
const err = handleApiError(res, VolumeError)
if (err) {
throw err
}
return true
}
/**
* List directory contents.
*
* @param path path to the directory.
* @param opts connection options.
* @param [opts.depth] number of layers deep to recurse into the directory (default: 1).
*
* @returns list of entries in the directory.
*/
async list(
path: string,
opts?: VolumeApiOpts & { depth?: number }
): Promise<VolumeEntryStat[]> {
const config = new VolumeConnectionConfig(this, opts)
const client = new VolumeApiClient(config)
const res = await client.api.GET('/volumecontent/{volumeID}/dir', {
params: {
path: {
volumeID: this.volumeId,
},
query: {
path,
depth: opts?.depth,
},
},
signal: config.getSignal(),
})
if (res.response.status === 404) {
throw new NotFoundError(`Path ${path} not found`)
}
const err = handleApiError(res, VolumeError)
if (err) {
throw err
}
// VolumeDirectoryListing is an array according to the spec
const entries = Array.isArray(res.data) ? res.data : []
return entries.map(convertVolumeEntryStat)
}
/**
* Create a directory.
*
* @param path path to the directory to create.
* @param options directory creation options.
* @param opts connection options.
*/
async makeDir(
path: string,
opts?: VolumeWriteOptions & VolumeApiOpts
): Promise<VolumeEntryStat> {
const config = new VolumeConnectionConfig(this, opts)
const client = new VolumeApiClient(config)
const res = await client.api.POST('/volumecontent/{volumeID}/dir', {
params: {
path: {
volumeID: this.volumeId,
},
query: {
path,
uid: opts?.uid,
gid: opts?.gid,
mode: opts?.mode,
force: opts?.force,
},
},
signal: config.getSignal(),
})
if (res.response.status === 404) {
throw new NotFoundError(`Path ${path} not found`)
}
const err = handleApiError(res, VolumeError)
if (err) {
throw err
}
if (!res.data) {
throw new Error('Response data is missing')
}
return convertVolumeEntryStat(
res.data as VolumeApiComponents['schemas']['VolumeEntryStat']
)
}
/**
* Get information about a file or directory.
*
* @param path path to the file or directory.
* @param opts connection options.
*
* @returns information about the entry.
*/
async getInfo(path: string, opts?: VolumeApiOpts): Promise<VolumeEntryStat> {
const config = new VolumeConnectionConfig(this, opts)
const client = new VolumeApiClient(config)
const res = await client.api.GET('/volumecontent/{volumeID}/path', {
params: {
path: {
volumeID: this.volumeId,
},
query: {
path,
},
},
signal: config.getSignal(),
})
if (res.response.status === 404) {
throw new NotFoundError(`Path ${path} not found`)
}
const err = handleApiError(res, VolumeError)
if (err) {
throw err
}
if (!res.data) {
throw new Error('Response data is missing')
}
return convertVolumeEntryStat(
res.data as VolumeApiComponents['schemas']['VolumeEntryStat']
)
}
/**
* Check whether a file or directory exists.
*
* Uses {@link getInfo} under the hood. Returns `true` if the path exists,
* `false` if it does not (404). Other errors are rethrown.
*
* @param path path to the file or directory.
* @param opts connection options.
*
* @returns `true` if the path exists, `false` otherwise.
*/
async exists(path: string, opts?: VolumeApiOpts): Promise<boolean> {
try {
await this.getInfo(path, opts)
return true
} catch (err) {
if (err instanceof NotFoundError) {
return false
}
throw err
}
}
/**
* Update file or directory metadata.
*
* @param path path to the file or directory.
* @param metadata metadata to update (uid, gid, mode).
* @param opts connection options.
*
* @returns updated entry information.
*/
async updateMetadata(
path: string,
metadata: VolumeMetadataOptions,
opts?: VolumeApiOpts
): Promise<VolumeEntryStat> {
const config = new VolumeConnectionConfig(this, opts)
const client = new VolumeApiClient(config)
const res = await client.api.PATCH('/volumecontent/{volumeID}/path', {
params: {
path: {
volumeID: this.volumeId,
},
query: {
path,
},
},
body: {
uid: metadata.uid,
gid: metadata.gid,
mode: metadata.mode,
},
signal: config.getSignal(),
})
if (res.response.status === 404) {
throw new NotFoundError(`Path ${path} not found`)
}
const err = handleApiError(res, VolumeError)
if (err) {
throw err
}
if (!res.data) {
throw new Error('Response data is missing')
}
return convertVolumeEntryStat(
res.data as VolumeApiComponents['schemas']['VolumeEntryStat']
)
}
/**
* Read file content as a `string`.
*
* You can pass `text`, `bytes`, `blob`, or `stream` to `opts.format` to change the return type.
*
* @param path path to the file.
* @param opts connection options.
* @param [opts.format] format of the file content—`text` by default.
*
* @returns file content as string
*/
async readFile(
path: string,
opts?: VolumeApiOpts & { format?: 'text' }
): Promise<string>
/**
* Read file content as a `Uint8Array`.
*
* You can pass `text`, `bytes`, `blob`, or `stream` to `opts.format` to change the return type.
*
* @param path path to the file.
* @param opts connection options.
* @param [opts.format] format of the file content—`bytes`.
*
* @returns file content as `Uint8Array`
*/
async readFile(
path: string,
opts?: VolumeApiOpts & { format: 'bytes' }
): Promise<Uint8Array>
/**
* Read file content as a `Blob`.
*
* You can pass `text`, `bytes`, `blob`, or `stream` to `opts.format` to change the return type.
*
* @param path path to the file.
* @param opts connection options.
* @param [opts.format] format of the file content—`blob`.
*
* @returns file content as `Blob`
*/
async readFile(
path: string,
opts?: VolumeApiOpts & { format: 'blob' }
): Promise<Blob>
/**
* Read file content as a `ReadableStream`.
*
* You can pass `text`, `bytes`, `blob`, or `stream` to `opts.format` to change the return type.
*
* @param path path to the file.
* @param opts connection options.
* @param [opts.format] format of the file content—`stream`.
*
* @returns file content as `ReadableStream`
*/
async readFile(
path: string,
opts?: VolumeApiOpts & { format: 'stream' }
): Promise<ReadableStream<Uint8Array>>
async readFile(
path: string,
opts?: VolumeApiOpts & {
format?: 'text' | 'stream' | 'bytes' | 'blob'
}
): Promise<unknown> {
const format = opts?.format ?? 'text'
const config = new VolumeConnectionConfig(this, {
...opts,
requestTimeoutMs: opts?.requestTimeoutMs ?? FILE_TIMEOUT_MS,
})
const client = new VolumeApiClient(config)
const res = await client.api.GET('/volumecontent/{volumeID}/file', {
params: {
path: {
volumeID: this.volumeId,
},
query: {
path,
},
},
parseAs: format === 'bytes' ? 'arrayBuffer' : format,
signal: config.getSignal(),
})
if (res.response.status === 404) {
throw new NotFoundError(`Path ${path} not found`)
}
const err = handleApiError(res, VolumeError)
if (err) {
throw err
}
// When the file is empty, `res.data` is `undefined`, so empty values are synthesized below.
if (format === 'bytes') {
return res.data instanceof ArrayBuffer
? new Uint8Array(res.data)
: new Uint8Array()
}
if (format === 'text') {
return typeof res.data === 'string' ? res.data : ''
}
if (format === 'blob') {
return res.data instanceof Blob ? res.data : new Blob([])
}
return res.data instanceof ReadableStream ? res.data : new Blob([]).stream()
}
/**
* Write content to a file.
*
* Writing to a file that doesn't exist creates the file.
*
* Writing to a file that already exists overwrites the file.
*
* @param path path to the file.
* @param data data to write to the file. Data can be a string, `ArrayBuffer`, `Blob`, or `ReadableStream`. Outside the browser, `ReadableStream` data is streamed to the API instead of being buffered in memory.
* @param options file creation options.
* @param opts connection options.
*
* @returns information about the written file
*/
async writeFile(
path: string,
data: string | ArrayBuffer | Blob | ReadableStream<Uint8Array>,
opts?: VolumeWriteOptions & VolumeApiOpts
): Promise<VolumeEntryStat> {
const config = new VolumeConnectionConfig(this, {
...opts,
requestTimeoutMs: opts?.requestTimeoutMs ?? FILE_TIMEOUT_MS,
})
const client = new VolumeApiClient(config)
// Browsers don't support streaming request bodies, so buffer there.
const isStream = data instanceof ReadableStream && runtime !== 'browser'
const body = isStream ? data : await toBlob(data)
const res = await client.api.PUT('/volumecontent/{volumeID}/file', {
params: {
path: {
volumeID: this.volumeId,
},
query: {
path,
uid: opts?.uid,
gid: opts?.gid,
mode: opts?.mode,
force: opts?.force,
},
},
bodySerializer: () => body,
body: {} as any,
headers: {
'Content-Type': 'application/octet-stream',
},
signal: config.getSignal(),
// Streaming request bodies require half-duplex mode.
...(isStream && { duplex: 'half' as const }),
})
if (res.response.status === 404) {
throw new NotFoundError(`Path ${path} not found`)
}
const err = handleApiError(res, VolumeError)
if (err) {
throw err
}
if (!res.data) {
throw new Error('Response data is missing')
}
return convertVolumeEntryStat(
res.data as VolumeApiComponents['schemas']['VolumeEntryStat']
)
}
/**
* Remove a file or directory.
*
* @param path path to the file or directory to remove.
* @param opts connection options.
*/
async remove(path: string, opts?: VolumeApiOpts): Promise<void> {
const config = new VolumeConnectionConfig(this, opts)
const client = new VolumeApiClient(config)
const res = await client.api.DELETE('/volumecontent/{volumeID}/path', {
params: {
path: {
volumeID: this.volumeId,
},
query: {
path,
},
},
signal: config.getSignal(),
})
if (res.response.status === 404) {
throw new NotFoundError(`Path ${path} not found`)
}
const err = handleApiError(res, VolumeError)
if (err) {
throw err
}
}
}
export type {
VolumeInfo,
VolumeAndToken,
VolumeEntryStat,
VolumeMetadataOptions,
VolumeWriteOptions,
} from './types'
export type { VolumeApiOpts, VolumeConnectionConfig } from './client'
export { VolumeFileType } from './types'