@nuvix/storage 1.0.0 → 1.0.1

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 (38) hide show
  1. package/dist/index.cjs +7375 -0
  2. package/dist/index.cjs.map +1 -0
  3. package/dist/index.d.cts +469 -0
  4. package/dist/index.d.ts +1 -2
  5. package/dist/index.js +7360 -0
  6. package/dist/index.js.map +1 -0
  7. package/package.json +12 -18
  8. package/dist/index.cjs.js +0 -1296
  9. package/dist/index.cjs.js.map +0 -1
  10. package/dist/index.d.ts.map +0 -1
  11. package/dist/index.esm.js +0 -1283
  12. package/dist/index.esm.js.map +0 -1
  13. package/dist/src/device/local.d.ts +0 -31
  14. package/dist/src/device/local.d.ts.map +0 -1
  15. package/dist/src/device/minio.d.ts +0 -16
  16. package/dist/src/device/minio.d.ts.map +0 -1
  17. package/dist/src/device/s3.d.ts +0 -94
  18. package/dist/src/device/s3.d.ts.map +0 -1
  19. package/dist/src/device/wasabi.d.ts +0 -24
  20. package/dist/src/device/wasabi.d.ts.map +0 -1
  21. package/dist/src/device.d.ts +0 -146
  22. package/dist/src/device.d.ts.map +0 -1
  23. package/dist/src/storage.d.ts +0 -57
  24. package/dist/src/storage.d.ts.map +0 -1
  25. package/dist/src/validator/file-ext.d.ts +0 -15
  26. package/dist/src/validator/file-ext.d.ts.map +0 -1
  27. package/dist/src/validator/file-name.d.ts +0 -15
  28. package/dist/src/validator/file-name.d.ts.map +0 -1
  29. package/dist/src/validator/file-size.d.ts +0 -17
  30. package/dist/src/validator/file-size.d.ts.map +0 -1
  31. package/dist/src/validator/file-type.d.ts +0 -27
  32. package/dist/src/validator/file-type.d.ts.map +0 -1
  33. package/dist/src/validator/file.d.ts +0 -14
  34. package/dist/src/validator/file.d.ts.map +0 -1
  35. package/dist/src/validator/upload.d.ts +0 -15
  36. package/dist/src/validator/upload.d.ts.map +0 -1
  37. package/dist/src/validator/validator.d.ts +0 -8
  38. package/dist/src/validator/validator.d.ts.map +0 -1
package/dist/index.esm.js DELETED
@@ -1,1283 +0,0 @@
1
- import { readFile } from 'fs/promises';
2
- import { promises } from 'fs';
3
- import path from 'path';
4
- import crypto, { createHash } from 'crypto';
5
-
6
- class Device {
7
- constructor() {
8
- /**
9
- * Max chunk size while transferring file from one device to another
10
- */
11
- this.transferChunkSize = 20000000; // 20 MB
12
- }
13
- /**
14
- * Set Transfer Chunk Size
15
- */
16
- setTransferChunkSize(chunkSize) {
17
- this.transferChunkSize = chunkSize;
18
- }
19
- /**
20
- * Get Transfer Chunk Size
21
- */
22
- getTransferChunkSize() {
23
- return this.transferChunkSize;
24
- }
25
- /**
26
- * Move file from given source to given path, return true on success and false on failure.
27
- */
28
- async move(source, target) {
29
- if (source === target) {
30
- return false;
31
- }
32
- if (await this.transfer(source, target, this)) {
33
- return await this.delete(source);
34
- }
35
- return false;
36
- }
37
- /**
38
- * Get the absolute path by resolving strings like ../, .., //, /\ and so on.
39
- *
40
- * Works like the realpath function but works on files that does not exist
41
- */
42
- getAbsolutePath(path) {
43
- const normalizedPath = path.replace(/[/\\]/g, "/");
44
- const parts = normalizedPath.split("/").filter((part) => part.length > 0);
45
- const absolutes = [];
46
- for (const part of parts) {
47
- if (part === ".") {
48
- continue;
49
- }
50
- if (part === "..") {
51
- absolutes.pop();
52
- }
53
- else {
54
- absolutes.push(part);
55
- }
56
- }
57
- return "/" + absolutes.join("/");
58
- }
59
- async getMimeType(filePath) {
60
- const path = await import('path');
61
- // Node.js doesn't have a built-in MIME type module, so we'll use a comprehensive mapping
62
- const ext = path.extname(filePath).toLowerCase().slice(1);
63
- const mimeTypes = {
64
- // Text
65
- txt: "text/plain",
66
- html: "text/html",
67
- htm: "text/html",
68
- css: "text/css",
69
- csv: "text/csv",
70
- xml: "text/xml",
71
- // JavaScript
72
- js: "application/javascript",
73
- mjs: "application/javascript",
74
- json: "application/json",
75
- // Images
76
- png: "image/png",
77
- jpg: "image/jpeg",
78
- jpeg: "image/jpeg",
79
- gif: "image/gif",
80
- svg: "image/svg+xml",
81
- webp: "image/webp",
82
- ico: "image/x-icon",
83
- bmp: "image/bmp",
84
- tiff: "image/tiff",
85
- tif: "image/tiff",
86
- // Documents
87
- pdf: "application/pdf",
88
- doc: "application/msword",
89
- docx: "application/vnd.openxmlformats-officedocument.wordprocessingml.document",
90
- xls: "application/vnd.ms-excel",
91
- xlsx: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
92
- ppt: "application/vnd.ms-powerpoint",
93
- pptx: "application/vnd.openxmlformats-officedocument.presentationml.presentation",
94
- // Audio
95
- mp3: "audio/mpeg",
96
- wav: "audio/wav",
97
- ogg: "audio/ogg",
98
- m4a: "audio/mp4",
99
- // Video
100
- mp4: "video/mp4",
101
- avi: "video/x-msvideo",
102
- mov: "video/quicktime",
103
- wmv: "video/x-ms-wmv",
104
- flv: "video/x-flv",
105
- webm: "video/webm",
106
- // Archives
107
- zip: "application/zip",
108
- rar: "application/x-rar-compressed",
109
- tar: "application/x-tar",
110
- gz: "application/gzip",
111
- "7z": "application/x-7z-compressed",
112
- // Other
113
- bin: "application/octet-stream",
114
- exe: "application/octet-stream",
115
- dmg: "application/octet-stream",
116
- };
117
- return mimeTypes[ext] || "application/octet-stream";
118
- }
119
- }
120
- /**
121
- * Sets the maximum number of keys returned to the response. By default, the action returns up to 1,000 key names.
122
- */
123
- Device.MAX_PAGE_SIZE = Number.MAX_SAFE_INTEGER;
124
-
125
- class Storage {
126
- /**
127
- * Set Device.
128
- *
129
- * Add device by name
130
- *
131
- * @param name
132
- * @param device
133
- * @throws Error
134
- */
135
- static setDevice(name, device) {
136
- this.devices.set(name, device);
137
- }
138
- /**
139
- * Get Device.
140
- *
141
- * Get device by name
142
- *
143
- * @param name
144
- * @returns Device
145
- * @throws Error
146
- */
147
- static getDevice(name) {
148
- if (!this.devices.has(name)) {
149
- throw new Error(`The device "${name}" is not listed`);
150
- }
151
- return this.devices.get(name);
152
- }
153
- /**
154
- * Exists.
155
- *
156
- * Checks if given storage name is registered or not
157
- *
158
- * @param name
159
- * @returns boolean
160
- */
161
- static exists(name) {
162
- return this.devices.has(name);
163
- }
164
- /**
165
- * Human readable data size format from bytes input.
166
- *
167
- * Based on: https://stackoverflow.com/a/38659168/2299554
168
- *
169
- * @param bytes
170
- * @param decimals
171
- * @param system
172
- * @returns string
173
- */
174
- static human(bytes, decimals = 2, system = "metric") {
175
- const mod = system === "binary" ? 1024 : 1000;
176
- const units = {
177
- binary: ["B", "KiB", "MiB", "GiB", "TiB", "PiB", "EiB", "ZiB", "YiB"],
178
- metric: ["B", "kB", "MB", "GB", "TB", "PB", "EB", "ZB", "YB"],
179
- };
180
- const factor = Math.floor((bytes.toString().length - 1) / 3);
181
- return `${(bytes / Math.pow(mod, factor)).toFixed(decimals)}${units[system][factor]}`;
182
- }
183
- }
184
- /**
185
- * Supported devices
186
- */
187
- Storage.DEVICE_LOCAL = "local";
188
- Storage.DEVICE_S3 = "s3";
189
- // static readonly DEVICE_DO_SPACES = 'dospaces';
190
- Storage.DEVICE_WASABI = "wasabi";
191
- Storage.DEVICE_MINIO = "minio";
192
- // static readonly DEVICE_BACKBLAZE = 'backblaze';
193
- // static readonly DEVICE_LINODE = 'linode';
194
- /**
195
- * Devices.
196
- *
197
- * List of all available storage devices
198
- */
199
- Storage.devices = new Map();
200
-
201
- class Validator {
202
- }
203
- Validator.TYPE_STRING = "string";
204
- Validator.TYPE_ARRAY = "array";
205
- Validator.TYPE_INTEGER = "integer";
206
- Validator.TYPE_BOOLEAN = "boolean";
207
-
208
- class File extends Validator {
209
- getDescription() {
210
- return "File is not valid";
211
- }
212
- /**
213
- * NOT MUCH RIGHT NOW.
214
- *
215
- * TODO think what to do here, currently only used for parameter to be present in SDKs
216
- *
217
- * @param name
218
- * @return boolean
219
- */
220
- isValid(name) {
221
- return true;
222
- }
223
- }
224
-
225
- class FileExt extends Validator {
226
- constructor(allowed) {
227
- super();
228
- this.allowed = allowed;
229
- }
230
- getDescription() {
231
- return "File extension is not valid";
232
- }
233
- isValid(filename) {
234
- const ext = this.getFileExtension(filename).toLowerCase();
235
- return this.allowed.includes(ext);
236
- }
237
- getFileExtension(filename) {
238
- const lastDotIndex = filename.lastIndexOf(".");
239
- return lastDotIndex !== -1 ? filename.substring(lastDotIndex + 1) : "";
240
- }
241
- }
242
- FileExt.TYPE_JPEG = "jpeg";
243
- FileExt.TYPE_JPG = "jpg";
244
- FileExt.TYPE_GIF = "gif";
245
- FileExt.TYPE_PNG = "png";
246
- FileExt.TYPE_GZIP = "gz";
247
- FileExt.TYPE_ZIP = "zip";
248
-
249
- class FileName extends Validator {
250
- /**
251
- * Get Description
252
- */
253
- getDescription() {
254
- return "Filename is not valid";
255
- }
256
- /**
257
- * The file name can only contain "a-z", "A-Z", "0-9" and "." and not empty.
258
- *
259
- * @param name - The filename to validate
260
- * @returns boolean indicating if the filename is valid
261
- */
262
- isValid(name) {
263
- if (!name) {
264
- return false;
265
- }
266
- if (typeof name !== "string") {
267
- return false;
268
- }
269
- if (!/^[a-zA-Z0-9.]+$/.test(name)) {
270
- return false;
271
- }
272
- return true;
273
- }
274
- }
275
-
276
- class FileSize extends Validator {
277
- /**
278
- * Max size in bytes
279
- */
280
- constructor(max) {
281
- super();
282
- this.max = max;
283
- }
284
- /**
285
- * Get Description
286
- */
287
- getDescription() {
288
- return `File size can't be bigger than ${this.max}`;
289
- }
290
- /**
291
- * Finds whether a file size is smaller than required limit.
292
- */
293
- isValid(fileSize) {
294
- if (typeof fileSize !== "number" || !Number.isInteger(fileSize)) {
295
- return false;
296
- }
297
- if (fileSize > this.max || fileSize < 0) {
298
- return false;
299
- }
300
- return true;
301
- }
302
- }
303
-
304
- class FileType extends Validator {
305
- constructor(allowed) {
306
- super();
307
- /**
308
- * File Type Binaries.
309
- */
310
- this.types = {
311
- [FileType.FILE_TYPE_JPEG]: "\xFF\xD8\xFF",
312
- [FileType.FILE_TYPE_GIF]: "GIF",
313
- [FileType.FILE_TYPE_PNG]: "\x89\x50\x4e\x47\x0d\x0a",
314
- [FileType.FILE_TYPE_GZIP]: "application/x-gzip",
315
- };
316
- for (const key of allowed) {
317
- if (!(key in this.types)) {
318
- throw new Error("Unknown file mime type");
319
- }
320
- }
321
- this.allowed = allowed;
322
- }
323
- /**
324
- * Get Description
325
- */
326
- getDescription() {
327
- return "File mime-type is not allowed ";
328
- }
329
- /**
330
- * Is Valid.
331
- *
332
- * Binary check to finds whether a file is of valid type
333
- */
334
- async isValid(path) {
335
- try {
336
- const buffer = await readFile(path);
337
- // Calculate the maximum signature length needed
338
- const maxSignatureLength = Math.max(...Object.values(this.types).map((sig) => sig.length));
339
- const bytesToRead = Math.min(buffer.length, Math.max(8, maxSignatureLength));
340
- const bytes = buffer.toString("binary", 0, bytesToRead);
341
- for (const key of this.allowed) {
342
- if (bytes.indexOf(this.types[key]) === 0) {
343
- return true;
344
- }
345
- }
346
- return false;
347
- }
348
- catch {
349
- return false;
350
- }
351
- }
352
- }
353
- /**
354
- * File Types Constants.
355
- */
356
- FileType.FILE_TYPE_JPEG = "jpeg";
357
- FileType.FILE_TYPE_GIF = "gif";
358
- FileType.FILE_TYPE_PNG = "png";
359
- FileType.FILE_TYPE_GZIP = "gz";
360
-
361
- class Upload extends Validator {
362
- /**
363
- * Get Description
364
- */
365
- getDescription() {
366
- return "Not a valid upload file";
367
- }
368
- /**
369
- * Check if a file is a valid upload file
370
- *
371
- * @param path - The file path to validate
372
- * @returns Promise that resolves to true if valid upload file, false otherwise
373
- */
374
- async isValid(path) {
375
- if (typeof path !== "string") {
376
- return false;
377
- }
378
- try {
379
- const stats = await promises.stat(path);
380
- return stats.isFile();
381
- }
382
- catch {
383
- return false;
384
- }
385
- }
386
- }
387
-
388
- class Local extends Device {
389
- constructor(root = "") {
390
- super();
391
- this.root = "temp";
392
- this.MAX_PAGE_SIZE = 1000;
393
- this.root = root;
394
- }
395
- getName() {
396
- return "Local Storage";
397
- }
398
- getType() {
399
- return Storage.DEVICE_LOCAL;
400
- }
401
- getDescription() {
402
- return "Adapter for Local storage that is in the physical or virtual machine or mounted to it.";
403
- }
404
- getRoot() {
405
- return this.root;
406
- }
407
- getPath(filename, prefix) {
408
- return this.getAbsolutePath(path.join(this.getRoot(), filename));
409
- }
410
- async upload(source, filePath, chunk = 1, chunks = 1, metadata = {}) {
411
- await this.createDirectory(path.dirname(filePath));
412
- if (chunks === 1) {
413
- try {
414
- await promises.rename(source, filePath);
415
- return chunks;
416
- }
417
- catch {
418
- throw new Error(`Can't upload file ${filePath}`);
419
- }
420
- }
421
- const tmp = path.join(path.dirname(filePath), `tmp_${path.basename(filePath)}`, `${path.basename(filePath)}_chunks.log`);
422
- await this.createDirectory(path.dirname(tmp));
423
- const chunkFilePath = path.join(path.dirname(tmp), `${path.parse(filePath).name}.part.${chunk}`);
424
- if (!(await this.exists(chunkFilePath))) {
425
- try {
426
- await promises.appendFile(tmp, `${chunk}\n`);
427
- }
428
- catch {
429
- throw new Error(`Can't write chunk log ${tmp}`);
430
- }
431
- }
432
- try {
433
- const chunkLogs = await promises.readFile(tmp, "utf8");
434
- const chunksReceived = chunkLogs.trim().split("\n").length;
435
- await promises.rename(source, chunkFilePath);
436
- if (chunks === chunksReceived) {
437
- await this.joinChunks(filePath, chunks);
438
- return chunksReceived;
439
- }
440
- return chunksReceived;
441
- }
442
- catch {
443
- throw new Error(`Failed to write chunk ${chunk}`);
444
- }
445
- }
446
- async uploadData(data, filePath, contentType, chunk = 1, chunks = 1, metadata = {}) {
447
- await this.createDirectory(path.dirname(filePath));
448
- if (chunks === 1) {
449
- try {
450
- await promises.writeFile(filePath, data);
451
- return chunks;
452
- }
453
- catch {
454
- throw new Error(`Can't write file ${filePath}`);
455
- }
456
- }
457
- const tmp = path.join(path.dirname(filePath), `tmp_${path.basename(filePath)}`, `${path.basename(filePath)}_chunks.log`);
458
- await this.createDirectory(path.dirname(tmp));
459
- try {
460
- await promises.appendFile(tmp, `${chunk}\n`);
461
- const chunkLogs = await promises.readFile(tmp, "utf8");
462
- const chunksReceived = chunkLogs.trim().split("\n").length;
463
- const chunkFilePath = path.join(path.dirname(tmp), `${path.parse(filePath).name}.part.${chunk}`);
464
- await promises.writeFile(chunkFilePath, data);
465
- if (chunks === chunksReceived) {
466
- await this.joinChunks(filePath, chunks);
467
- return chunksReceived;
468
- }
469
- return chunksReceived;
470
- }
471
- catch {
472
- throw new Error(`Failed to write chunk ${chunk}`);
473
- }
474
- }
475
- async joinChunks(filePath, chunks) {
476
- const tmp = path.join(path.dirname(filePath), `tmp_${path.basename(filePath)}`, `${path.basename(filePath)}_chunks.log`);
477
- for (let i = 1; i <= chunks; i++) {
478
- const part = path.join(path.dirname(tmp), `${path.parse(filePath).name}.part.${i}`);
479
- try {
480
- const data = await promises.readFile(part);
481
- await promises.appendFile(filePath, data);
482
- await promises.unlink(part);
483
- }
484
- catch {
485
- throw new Error(`Failed to read/append chunk ${part}`);
486
- }
487
- }
488
- await promises.unlink(tmp);
489
- await promises.rmdir(path.dirname(tmp));
490
- }
491
- async transfer(filePath, destination, device) {
492
- if (!(await this.exists(filePath))) {
493
- throw new Error("File Not Found");
494
- }
495
- const size = await this.getFileSize(filePath);
496
- const contentType = await this.getFileMimeType(filePath);
497
- if (size <= this.transferChunkSize) {
498
- const source = await this.read(filePath);
499
- return await device.write(destination, source, contentType);
500
- }
501
- const totalChunks = Math.ceil(size / this.transferChunkSize);
502
- const metadata = { content_type: contentType };
503
- for (let counter = 0; counter < totalChunks; counter++) {
504
- const start = counter * this.transferChunkSize;
505
- const data = await this.read(filePath, start, this.transferChunkSize);
506
- await device.uploadData(data, destination, contentType, counter + 1, totalChunks, metadata);
507
- }
508
- return true;
509
- }
510
- async abort(filePath, extra = "") {
511
- if (await this.exists(filePath)) {
512
- await promises.unlink(filePath);
513
- }
514
- const tmp = path.join(path.dirname(filePath), `tmp_${path.basename(filePath)}`);
515
- if (!(await this.exists(path.dirname(tmp)))) {
516
- throw new Error(`File doesn't exist: ${path.dirname(filePath)}`);
517
- }
518
- const files = await this.getFiles(tmp);
519
- for (const file of files) {
520
- await this.delete(file, true);
521
- }
522
- return promises
523
- .rmdir(tmp)
524
- .then(() => true)
525
- .catch(() => false);
526
- }
527
- async read(filePath, offset = 0, length) {
528
- if (!(await this.exists(filePath))) {
529
- throw new Error("File Not Found");
530
- }
531
- const fileHandle = await promises.open(filePath, "r");
532
- try {
533
- const size = length ?? (await fileHandle.stat()).size - offset;
534
- const buffer = Buffer.alloc(size);
535
- await fileHandle.read(buffer, 0, size, offset);
536
- return buffer;
537
- }
538
- finally {
539
- await fileHandle.close();
540
- }
541
- }
542
- async write(filePath, data, contentType = "") {
543
- try {
544
- await this.createDirectory(path.dirname(filePath));
545
- await promises.writeFile(filePath, data);
546
- return true;
547
- }
548
- catch {
549
- throw new Error(`Can't write to path ${filePath}`);
550
- }
551
- }
552
- async move(source, target) {
553
- if (source === target) {
554
- return false;
555
- }
556
- try {
557
- await this.createDirectory(path.dirname(target));
558
- await promises.rename(source, target);
559
- return true;
560
- }
561
- catch {
562
- return false;
563
- }
564
- }
565
- async delete(filePath, recursive = false) {
566
- try {
567
- const stats = await promises.stat(filePath);
568
- if (stats.isDirectory() && recursive) {
569
- const files = await this.getFiles(filePath);
570
- for (const file of files) {
571
- await this.delete(file, true);
572
- }
573
- await promises.rmdir(filePath);
574
- }
575
- else if (stats.isFile() || stats.isSymbolicLink()) {
576
- await promises.unlink(filePath);
577
- }
578
- return true;
579
- }
580
- catch {
581
- return false;
582
- }
583
- }
584
- async deletePath(filePath) {
585
- const fullPath = path.resolve(path.join(this.getRoot(), filePath));
586
- try {
587
- if (!(await this.exists(fullPath))) {
588
- return false;
589
- }
590
- const stats = await promises.stat(fullPath);
591
- if (!stats.isDirectory()) {
592
- return false;
593
- }
594
- const files = await this.getFiles(fullPath);
595
- for (const file of files) {
596
- const stats = await promises.stat(file);
597
- if (stats.isDirectory()) {
598
- const relativePath = file.replace(this.getRoot() + path.sep, "");
599
- await this.deletePath(relativePath);
600
- }
601
- else {
602
- await this.delete(file, true);
603
- }
604
- }
605
- await promises.rmdir(fullPath);
606
- return true;
607
- }
608
- catch {
609
- return false;
610
- }
611
- }
612
- async exists(filePath) {
613
- try {
614
- await promises.access(filePath);
615
- return true;
616
- }
617
- catch {
618
- return false;
619
- }
620
- }
621
- async getFileSize(filePath) {
622
- const stats = await promises.stat(filePath);
623
- return stats.size;
624
- }
625
- async getFileMimeType(filePath) {
626
- return this.getMimeType(filePath);
627
- }
628
- async getFileHash(filePath) {
629
- const data = await promises.readFile(filePath);
630
- return createHash("md5").update(data).digest("hex");
631
- }
632
- async createDirectory(dirPath) {
633
- try {
634
- await promises.mkdir(dirPath, { recursive: true, mode: 0o755 });
635
- return true;
636
- }
637
- catch {
638
- return false;
639
- }
640
- }
641
- async getDirectorySize(dirPath) {
642
- try {
643
- let size = 0;
644
- const files = await promises.readdir(dirPath, { withFileTypes: true });
645
- for (const file of files) {
646
- if (file.name.startsWith("."))
647
- continue;
648
- const fullPath = path.join(dirPath, file.name);
649
- if (file.isDirectory()) {
650
- size += await this.getDirectorySize(fullPath);
651
- }
652
- else {
653
- const stats = await promises.stat(fullPath);
654
- size += stats.size;
655
- }
656
- }
657
- return size;
658
- }
659
- catch {
660
- return -1;
661
- }
662
- }
663
- async getPartitionFreeSpace() {
664
- const stats = await promises.statfs(this.getRoot());
665
- return stats.bavail * stats.bsize;
666
- }
667
- async getPartitionTotalSpace() {
668
- const stats = await promises.statfs(this.getRoot());
669
- return stats.blocks * stats.bsize;
670
- }
671
- async getFiles(dir, max = this.MAX_PAGE_SIZE, continuationToken = "") {
672
- try {
673
- const entries = await promises.readdir(dir, { withFileTypes: true });
674
- return entries.map((entry) => path.join(dir, entry.name));
675
- }
676
- catch {
677
- return [];
678
- }
679
- }
680
- }
681
-
682
- class S3 extends Device {
683
- constructor(root, accessKey, secretKey, bucket, region = S3.US_EAST_1, acl = S3.ACL_PRIVATE, endpointUrl = "") {
684
- super();
685
- this.acl = S3.ACL_PRIVATE;
686
- this.root = "temp";
687
- this.headers = {
688
- host: "",
689
- date: "",
690
- "content-md5": "",
691
- "content-type": "",
692
- };
693
- this.accessKey = accessKey;
694
- this.secretKey = secretKey;
695
- this.bucket = bucket;
696
- this.region = region;
697
- this.root = root;
698
- this.acl = acl;
699
- this.amzHeaders = {};
700
- let host;
701
- if (endpointUrl) {
702
- host = `${bucket}.${endpointUrl}`;
703
- }
704
- else {
705
- switch (region) {
706
- case S3.CN_NORTH_1:
707
- case S3.CN_NORTH_4:
708
- case S3.CN_NORTHWEST_1:
709
- host = `${bucket}.s3.${region}.amazonaws.cn`;
710
- break;
711
- default:
712
- host = `${bucket}.s3.${region}.amazonaws.com`;
713
- }
714
- }
715
- this.headers["host"] = host;
716
- }
717
- getName() {
718
- return "S3 Storage";
719
- }
720
- getType() {
721
- return Storage.DEVICE_S3;
722
- }
723
- getDescription() {
724
- return "S3 Bucket Storage drive for AWS or on premise solution";
725
- }
726
- getRoot() {
727
- return this.root;
728
- }
729
- getPath(filename, prefix) {
730
- return `${this.getRoot()}/${filename}`;
731
- }
732
- getPartitionTotalSpace() {
733
- throw new Error("Method not implemented.");
734
- }
735
- static setRetryAttempts(attempts) {
736
- S3.retryAttempts = attempts;
737
- }
738
- static setRetryDelay(delay) {
739
- S3.retryDelay = delay;
740
- }
741
- async upload(source, path, chunk = 1, chunks = 1, metadata = {}) {
742
- let data;
743
- let contentType;
744
- if (typeof source === "string") {
745
- const fs = await import('fs');
746
- data = await fs.promises.readFile(source);
747
- contentType = await this.getMimeType(source);
748
- }
749
- else {
750
- data = source;
751
- contentType = metadata.contentType || "application/octet-stream";
752
- }
753
- return this.uploadData(data, path, contentType, chunk, chunks, metadata);
754
- }
755
- async uploadData(data, path, contentType, chunk = 1, chunks = 1, metadata = {}) {
756
- if (chunk === 1 && chunks === 1) {
757
- await this.write(path, data, contentType);
758
- return 1;
759
- }
760
- let uploadId = metadata["uploadId"];
761
- if (!uploadId) {
762
- uploadId = await this.createMultipartUpload(path, contentType);
763
- metadata["uploadId"] = uploadId;
764
- }
765
- metadata["parts"] = metadata["parts"] || {};
766
- metadata["chunks"] = metadata["chunks"] || 0;
767
- const etag = await this.uploadPart(data, path, contentType, chunk, uploadId);
768
- const cleanETag = etag.replace(/^"|"$/g, "");
769
- if (!(chunk in metadata["parts"])) {
770
- metadata["chunks"]++;
771
- }
772
- metadata["parts"][chunk] = cleanETag;
773
- if (metadata["chunks"] === chunks) {
774
- await this.completeMultipartUpload(path, uploadId, metadata["parts"]);
775
- }
776
- return metadata["chunks"];
777
- }
778
- async transfer(path, destination, device) {
779
- try {
780
- const response = await this.getInfo(path);
781
- const size = parseInt(response["content-length"] || "0");
782
- const contentType = response["content-type"] || "";
783
- if (size <= this.transferChunkSize) {
784
- const source = await this.read(path);
785
- return device.write(destination, source, contentType);
786
- }
787
- const totalChunks = Math.ceil(size / this.transferChunkSize);
788
- const metadata = { content_type: contentType };
789
- for (let counter = 0; counter < totalChunks; counter++) {
790
- const start = counter * this.transferChunkSize;
791
- const data = await this.read(path, start, this.transferChunkSize);
792
- await device.uploadData(data, destination, contentType, counter + 1, totalChunks, metadata);
793
- }
794
- return true;
795
- }
796
- catch (e) {
797
- throw new Error("File not found");
798
- }
799
- }
800
- async createMultipartUpload(path, contentType) {
801
- const uri = path !== ""
802
- ? `/${encodeURIComponent(path).replace(/%2F/g, "/").replace(/%3F/g, "?")}`
803
- : "/";
804
- this.headers["content-md5"] = Buffer.from(this.md5("")).toString("base64");
805
- delete this.amzHeaders["x-amz-content-sha256"];
806
- this.headers["content-type"] = contentType;
807
- this.amzHeaders["x-amz-acl"] = this.acl;
808
- const response = await this.call(S3.METHOD_POST, uri, "", { uploads: "" });
809
- const uploadId = response.body?.InitiateMultipartUploadResult?.UploadId?.[0];
810
- return uploadId;
811
- }
812
- async uploadPart(data, path, contentType, chunk, uploadId) {
813
- const uri = path !== ""
814
- ? `/${encodeURIComponent(path).replace(/%2F/g, "/").replace(/%3F/g, "?")}`
815
- : "/";
816
- this.headers["content-type"] = contentType;
817
- this.headers["content-md5"] = Buffer.from(this.md5(data)).toString("base64");
818
- this.amzHeaders["x-amz-content-sha256"] = this.sha256(data);
819
- delete this.amzHeaders["x-amz-acl"];
820
- const response = await this.call(S3.METHOD_PUT, uri, data, {
821
- partNumber: chunk.toString(),
822
- uploadId: uploadId,
823
- });
824
- return response.headers["etag"];
825
- }
826
- async completeMultipartUpload(path, uploadId, parts) {
827
- const uri = path !== ""
828
- ? `/${encodeURIComponent(path).replace(/%2F/g, "/").replace(/%3F/g, "?")}`
829
- : "/";
830
- let body = "<CompleteMultipartUpload>";
831
- for (const [key, etag] of Object.entries(parts)) {
832
- body += `<Part><ETag>${etag}</ETag><PartNumber>${key}</PartNumber></Part>`;
833
- }
834
- body += "</CompleteMultipartUpload>";
835
- this.amzHeaders["x-amz-content-sha256"] = this.sha256(body);
836
- this.headers["content-md5"] = Buffer.from(this.md5(body)).toString("base64");
837
- await this.call(S3.METHOD_POST, uri, body, { uploadId });
838
- return true;
839
- }
840
- async abort(path, extra = "") {
841
- const uri = path !== "" ? `/${encodeURIComponent(path).replace(/%2F/g, "/")}` : "/";
842
- delete this.headers["content-type"];
843
- this.headers["content-md5"] = Buffer.from(this.md5("")).toString("base64");
844
- await this.call(S3.METHOD_DELETE, uri, "", { uploadId: extra });
845
- return true;
846
- }
847
- async read(path, offset = 0, length) {
848
- delete this.amzHeaders["x-amz-acl"];
849
- delete this.amzHeaders["x-amz-content-sha256"];
850
- delete this.headers["content-type"];
851
- this.headers["content-md5"] = Buffer.from(this.md5("")).toString("base64");
852
- const uri = path !== "" ? `/${encodeURIComponent(path).replace(/%2F/g, "/")}` : "/";
853
- if (length !== undefined) {
854
- const end = offset + length - 1;
855
- this.headers["range"] = `bytes=${offset}-${end}`;
856
- }
857
- else {
858
- delete this.headers["range"];
859
- }
860
- const response = await this.call(S3.METHOD_GET, uri, "", {}, false);
861
- return Buffer.from(response.buffer);
862
- }
863
- async write(path, data, contentType = "") {
864
- const uri = path !== ""
865
- ? `/${encodeURIComponent(path).replace(/%2F/g, "/").replace(/%3F/g, "?")}`
866
- : "/";
867
- this.headers["content-type"] = contentType;
868
- this.headers["content-md5"] = Buffer.from(this.md5(data)).toString("base64");
869
- this.amzHeaders["x-amz-content-sha256"] = this.sha256(data);
870
- this.amzHeaders["x-amz-acl"] = this.acl;
871
- await this.call(S3.METHOD_PUT, uri, data);
872
- return true;
873
- }
874
- async delete(path, recursive = false) {
875
- const uri = path !== "" ? `/${encodeURIComponent(path).replace(/%2F/g, "/")}` : "/";
876
- delete this.headers["content-type"];
877
- delete this.amzHeaders["x-amz-acl"];
878
- delete this.amzHeaders["x-amz-content-sha256"];
879
- this.headers["content-md5"] = Buffer.from(this.md5("")).toString("base64");
880
- await this.call(S3.METHOD_DELETE, uri);
881
- return true;
882
- }
883
- async listObjects(prefix = "", maxKeys = S3.MAX_PAGE_SIZE, continuationToken = "") {
884
- if (maxKeys > S3.MAX_PAGE_SIZE) {
885
- throw new Error(`Cannot list more than ${S3.MAX_PAGE_SIZE} objects`);
886
- }
887
- const uri = "/";
888
- prefix = prefix.replace(/^\//, "");
889
- this.headers["content-type"] = "text/plain";
890
- this.headers["content-md5"] = Buffer.from(this.md5("")).toString("base64");
891
- delete this.amzHeaders["x-amz-content-sha256"];
892
- delete this.amzHeaders["x-amz-acl"];
893
- const parameters = {
894
- "list-type": "2",
895
- prefix: prefix,
896
- "max-keys": maxKeys.toString(),
897
- };
898
- if (continuationToken) {
899
- parameters["continuation-token"] = continuationToken;
900
- }
901
- const response = await this.call(S3.METHOD_GET, uri, "", parameters);
902
- return response.body;
903
- }
904
- async deletePath(path) {
905
- path = `${this.getRoot()}/${path}`;
906
- const uri = "/";
907
- let continuationToken = "";
908
- do {
909
- const objects = await this.listObjects(path, S3.MAX_PAGE_SIZE, continuationToken);
910
- const count = parseInt(objects["KeyCount"] || "1");
911
- if (count < 1)
912
- break;
913
- continuationToken = objects["NextContinuationToken"] || "";
914
- let body = '<Delete xmlns="http://s3.amazonaws.com/doc/2006-03-01/">';
915
- if (count > 1) {
916
- for (const object of objects["Contents"]) {
917
- body += `<Object><Key>${object["Key"]}</Key></Object>`;
918
- }
919
- }
920
- else {
921
- body += `<Object><Key>${objects["Contents"]["Key"]}</Key></Object>`;
922
- }
923
- body += "<Quiet>true</Quiet></Delete>";
924
- this.amzHeaders["x-amz-content-sha256"] = this.sha256(body);
925
- this.headers["content-md5"] = Buffer.from(this.md5(body)).toString("base64");
926
- await this.call(S3.METHOD_POST, uri, body, { delete: "" });
927
- } while (continuationToken);
928
- return true;
929
- }
930
- async exists(path) {
931
- try {
932
- await this.getInfo(path);
933
- return true;
934
- }
935
- catch {
936
- return false;
937
- }
938
- }
939
- async getFileSize(path) {
940
- const response = await this.getInfo(path);
941
- return parseInt(response["content-length"] || "0");
942
- }
943
- async getFileMimeType(path) {
944
- const response = await this.getInfo(path);
945
- return response["content-type"] || "";
946
- }
947
- async getFileHash(path) {
948
- const etag = (await this.getInfo(path))["etag"] || "";
949
- return etag ? etag.slice(1, -1) : etag;
950
- }
951
- async createDirectory(path) {
952
- return true; // S3 doesn't have directories
953
- }
954
- async getDirectorySize(path) {
955
- return -1;
956
- }
957
- async getPartitionFreeSpace() {
958
- return -1;
959
- }
960
- async getFiles(dir, max = S3.MAX_PAGE_SIZE, continuationToken = "") {
961
- const data = await this.listObjects(dir, max, continuationToken);
962
- data["IsTruncated"] = data["IsTruncated"] === "true";
963
- data["KeyCount"] = parseInt(data["KeyCount"]);
964
- data["MaxKeys"] = parseInt(data["MaxKeys"]);
965
- return data;
966
- }
967
- async getInfo(path) {
968
- delete this.headers["content-type"];
969
- delete this.amzHeaders["x-amz-acl"];
970
- delete this.amzHeaders["x-amz-content-sha256"];
971
- this.headers["content-md5"] = Buffer.from(this.md5("")).toString("base64");
972
- const uri = path !== "" ? `/${encodeURIComponent(path).replace(/%2F/g, "/")}` : "/";
973
- const response = await this.call(S3.METHOD_HEAD, uri);
974
- return response.headers;
975
- }
976
- getSignatureV4(method, uri, parameters = {}) {
977
- const service = "s3";
978
- const region = this.region;
979
- const algorithm = "AWS4-HMAC-SHA256";
980
- const combinedHeaders = {};
981
- const amzDateStamp = this.amzHeaders["x-amz-date"].substring(0, 8);
982
- // Combine headers
983
- for (const [k, v] of Object.entries(this.headers)) {
984
- combinedHeaders[k.toLowerCase()] = v.trim();
985
- }
986
- for (const [k, v] of Object.entries(this.amzHeaders)) {
987
- combinedHeaders[k.toLowerCase()] = v.trim();
988
- }
989
- // Sort headers
990
- const sortedHeaders = Object.keys(combinedHeaders).sort();
991
- const sortedCombinedHeaders = {};
992
- for (const key of sortedHeaders) {
993
- sortedCombinedHeaders[key] = combinedHeaders[key];
994
- }
995
- // Sort parameters
996
- const sortedParams = Object.keys(parameters).sort();
997
- const queryString = sortedParams
998
- .map((key) => `${encodeURIComponent(key)}=${encodeURIComponent(parameters[key])}`)
999
- .join("&");
1000
- // Create canonical request
1001
- const canonicalRequest = [
1002
- method,
1003
- uri.split("?")[0],
1004
- queryString,
1005
- ...Object.entries(sortedCombinedHeaders).map(([k, v]) => `${k}:${v}`),
1006
- "",
1007
- Object.keys(sortedCombinedHeaders).join(";"),
1008
- this.amzHeaders["x-amz-content-sha256"],
1009
- ].join("\n");
1010
- // Create string to sign
1011
- const credentialScope = [
1012
- amzDateStamp,
1013
- region,
1014
- service,
1015
- "aws4_request",
1016
- ].join("/");
1017
- const stringToSign = [
1018
- algorithm,
1019
- this.amzHeaders["x-amz-date"],
1020
- credentialScope,
1021
- this.sha256(canonicalRequest),
1022
- ].join("\n");
1023
- // Calculate signature
1024
- const kSecret = `AWS4${this.secretKey}`;
1025
- const kDate = this.hmacSha256(amzDateStamp, kSecret);
1026
- const kRegion = this.hmacSha256(region, kDate);
1027
- const kService = this.hmacSha256(service, kRegion);
1028
- const kSigning = this.hmacSha256("aws4_request", kService);
1029
- const signature = this.hmacSha256(stringToSign, kSigning, "hex");
1030
- return `${algorithm} Credential=${this.accessKey}/${credentialScope},SignedHeaders=${Object.keys(sortedCombinedHeaders).join(";")},Signature=${signature}`;
1031
- }
1032
- async call(method, uri, data = "", parameters = {}, decode = true) {
1033
- uri = this.getAbsolutePath(uri);
1034
- const queryString = Object.keys(parameters).length
1035
- ? "?" +
1036
- Object.entries(parameters)
1037
- .map(([k, v]) => `${encodeURIComponent(k)}=${encodeURIComponent(v)}`)
1038
- .join("&")
1039
- : "";
1040
- const url = `https://${this.headers["host"]}${uri}${queryString}`;
1041
- this.amzHeaders["x-amz-date"] = new Date()
1042
- .toISOString()
1043
- .replace(/[:-]|\.\d{3}/g, "");
1044
- if (!this.amzHeaders["x-amz-content-sha256"]) {
1045
- this.amzHeaders["x-amz-content-sha256"] = this.sha256(data);
1046
- }
1047
- const headers = {};
1048
- for (const [header, value] of Object.entries(this.amzHeaders)) {
1049
- if (value.length > 0) {
1050
- headers[header] = value;
1051
- }
1052
- }
1053
- this.headers["date"] = new Date().toUTCString();
1054
- for (const [header, value] of Object.entries(this.headers)) {
1055
- if (value.length > 0) {
1056
- headers[header] = value;
1057
- }
1058
- }
1059
- headers["Authorization"] = this.getSignatureV4(method, uri, parameters);
1060
- const fetchOptions = {
1061
- method,
1062
- headers,
1063
- };
1064
- if (method === S3.METHOD_PUT || method === S3.METHOD_POST) {
1065
- fetchOptions.body = data;
1066
- }
1067
- const response = await fetch(url, fetchOptions);
1068
- if (!response.ok) {
1069
- const errorBody = await response.text();
1070
- throw new Error(`HTTP ${response.status}: ${errorBody}`);
1071
- }
1072
- const responseHeaders = {};
1073
- response.headers.forEach((value, key) => {
1074
- responseHeaders[key.toLowerCase()] = value;
1075
- });
1076
- const buffer = await response.arrayBuffer();
1077
- let body = new TextDecoder().decode(buffer);
1078
- if (decode &&
1079
- (responseHeaders["content-type"] === "application/xml" ||
1080
- (body.startsWith("<?xml") &&
1081
- responseHeaders["content-type"] !== "image/svg+xml"))) {
1082
- const xml2js = await import('xml2js');
1083
- const parser = new xml2js.Parser();
1084
- body = await parser.parseStringPromise(body);
1085
- }
1086
- return {
1087
- body,
1088
- buffer,
1089
- headers: responseHeaders,
1090
- code: response.status,
1091
- };
1092
- }
1093
- md5(data) {
1094
- const buffer = typeof data === "string" ? Buffer.from(data, "utf8") : data;
1095
- return crypto.createHash("md5").update(buffer).digest();
1096
- }
1097
- sha256(data) {
1098
- const buffer = typeof data === "string" ? Buffer.from(data, "utf8") : data;
1099
- return crypto.createHash("sha256").update(buffer).digest("hex");
1100
- }
1101
- hmacSha256(data, key, encoding = "binary") {
1102
- const dataBuffer = typeof data === "string" ? Buffer.from(data, "utf8") : data;
1103
- const hmac = crypto.createHmac("sha256", key);
1104
- hmac.update(dataBuffer);
1105
- return encoding === "hex" ? hmac.digest("hex") : hmac.digest();
1106
- }
1107
- }
1108
- // HTTP Methods
1109
- S3.METHOD_GET = "GET";
1110
- S3.METHOD_POST = "POST";
1111
- S3.METHOD_PUT = "PUT";
1112
- S3.METHOD_PATCH = "PATCH";
1113
- S3.METHOD_DELETE = "DELETE";
1114
- S3.METHOD_HEAD = "HEAD";
1115
- S3.METHOD_OPTIONS = "OPTIONS";
1116
- S3.METHOD_CONNECT = "CONNECT";
1117
- S3.METHOD_TRACE = "TRACE";
1118
- // AWS Regions
1119
- S3.US_EAST_1 = "us-east-1";
1120
- S3.US_EAST_2 = "us-east-2";
1121
- S3.US_WEST_1 = "us-west-1";
1122
- S3.US_WEST_2 = "us-west-2";
1123
- S3.AF_SOUTH_1 = "af-south-1";
1124
- S3.AP_EAST_1 = "ap-east-1";
1125
- S3.AP_SOUTH_1 = "ap-south-1";
1126
- S3.AP_NORTHEAST_3 = "ap-northeast-3";
1127
- S3.AP_NORTHEAST_2 = "ap-northeast-2";
1128
- S3.AP_NORTHEAST_1 = "ap-northeast-1";
1129
- S3.AP_SOUTHEAST_1 = "ap-southeast-1";
1130
- S3.AP_SOUTHEAST_2 = "ap-southeast-2";
1131
- S3.CA_CENTRAL_1 = "ca-central-1";
1132
- S3.EU_CENTRAL_1 = "eu-central-1";
1133
- S3.EU_WEST_1 = "eu-west-1";
1134
- S3.EU_SOUTH_1 = "eu-south-1";
1135
- S3.EU_WEST_2 = "eu-west-2";
1136
- S3.EU_WEST_3 = "eu-west-3";
1137
- S3.EU_NORTH_1 = "eu-north-1";
1138
- S3.SA_EAST_1 = "eu-north-1";
1139
- S3.CN_NORTH_1 = "cn-north-1";
1140
- S3.CN_NORTH_4 = "cn-north-4";
1141
- S3.CN_NORTHWEST_1 = "cn-northwest-1";
1142
- S3.ME_SOUTH_1 = "me-south-1";
1143
- S3.US_GOV_EAST_1 = "us-gov-east-1";
1144
- S3.US_GOV_WEST_1 = "us-gov-west-1";
1145
- // ACL Flags
1146
- S3.ACL_PRIVATE = "private";
1147
- S3.ACL_PUBLIC_READ = "public-read";
1148
- S3.ACL_PUBLIC_READ_WRITE = "public-read-write";
1149
- S3.ACL_AUTHENTICATED_READ = "authenticated-read";
1150
- S3.MAX_PAGE_SIZE = 1000;
1151
- S3.retryAttempts = 3;
1152
- S3.retryDelay = 500;
1153
-
1154
- class Wasabi extends S3 {
1155
- /**
1156
- * Wasabi Constructor
1157
- */
1158
- constructor(root, accessKey, secretKey, bucket, region = Wasabi.EU_CENTRAL_1, acl = S3.ACL_PRIVATE) {
1159
- super(root, accessKey, secretKey, bucket, region, acl);
1160
- this.headers["host"] = `${bucket}.s3.${region}.wasabisys.com`;
1161
- }
1162
- getName() {
1163
- return "Wasabi Storage";
1164
- }
1165
- getDescription() {
1166
- return "Wasabi Storage";
1167
- }
1168
- getType() {
1169
- return Storage.DEVICE_WASABI;
1170
- }
1171
- }
1172
- /**
1173
- * Regions constants
1174
- */
1175
- Wasabi.US_WEST_1 = "us-west-1";
1176
- Wasabi.AP_NORTHEAST_1 = "ap-northeast-1";
1177
- Wasabi.AP_NORTHEAST_2 = "ap-northeast-2";
1178
- Wasabi.EU_CENTRAL_1 = "eu-central-1";
1179
- Wasabi.EU_CENTRAL_2 = "eu-central-2";
1180
- Wasabi.EU_WEST_1 = "eu-west-1";
1181
- Wasabi.EU_WEST_2 = "eu-west-2";
1182
- Wasabi.US_CENTRAL_1 = "us-central-1";
1183
- Wasabi.US_EAST_1 = "us-east-1";
1184
- Wasabi.US_EAST_2 = "us-east-2";
1185
-
1186
- class MinIO extends S3 {
1187
- /**
1188
- * MinIO Constructor
1189
- */
1190
- constructor(root, accessKey, secretKey, bucket, endpoint = "localhost:9000", acl = S3.ACL_PRIVATE, useSSL = false) {
1191
- const protocol = useSSL ? "https" : "http";
1192
- // Remove protocol from endpoint if it exists
1193
- const cleanEndpoint = endpoint.replace(/^https?:\/\//, "");
1194
- super(root, accessKey, secretKey, bucket, "us-east-1", acl, cleanEndpoint);
1195
- // Override the host for MinIO
1196
- this.headers["host"] = `${bucket}.${cleanEndpoint}`;
1197
- // Store the full endpoint URL for MinIO-specific operations
1198
- this.endpointUrl = `${protocol}://${cleanEndpoint}`;
1199
- }
1200
- getName() {
1201
- return "MinIO Storage";
1202
- }
1203
- getDescription() {
1204
- return "MinIO S3-compatible object storage server";
1205
- }
1206
- getType() {
1207
- return Storage.DEVICE_MINIO;
1208
- }
1209
- /**
1210
- * Override the call method to use the custom endpoint
1211
- */
1212
- async call(method, uri, data = "", parameters = {}, decode = true) {
1213
- // Temporarily modify the host header to not include the bucket for MinIO
1214
- const originalHost = this.headers["host"];
1215
- // For MinIO, we need to handle path-style URLs differently
1216
- const bucketName = originalHost.split(".")[0];
1217
- const endpoint = originalHost.split(".").slice(1).join(".");
1218
- // Use path-style URLs for MinIO
1219
- this.headers["host"] = endpoint;
1220
- const queryString = Object.keys(parameters).length
1221
- ? "?" +
1222
- Object.entries(parameters)
1223
- .map(([k, v]) => `${encodeURIComponent(k)}=${encodeURIComponent(v)}`)
1224
- .join("&")
1225
- : "";
1226
- const pathStyleUri = `/${bucketName}${this.getAbsolutePath(uri)}`;
1227
- const url = `${this.endpointUrl}${pathStyleUri}${queryString}`;
1228
- this.amzHeaders["x-amz-date"] = new Date()
1229
- .toISOString()
1230
- .replace(/[:-]|\.\d{3}/g, "");
1231
- if (!this.amzHeaders["x-amz-content-sha256"]) {
1232
- this.amzHeaders["x-amz-content-sha256"] = this.sha256(data);
1233
- }
1234
- const headers = {};
1235
- for (const [header, value] of Object.entries(this.amzHeaders)) {
1236
- if (value.length > 0) {
1237
- headers[header] = value;
1238
- }
1239
- }
1240
- this.headers["date"] = new Date().toUTCString();
1241
- for (const [header, value] of Object.entries(this.headers)) {
1242
- if (value.length > 0) {
1243
- headers[header] = value;
1244
- }
1245
- }
1246
- headers["Authorization"] = this.getSignatureV4(method, pathStyleUri, parameters);
1247
- const fetchOptions = {
1248
- method,
1249
- headers,
1250
- };
1251
- if (method === S3.METHOD_PUT || method === S3.METHOD_POST) {
1252
- fetchOptions.body = data;
1253
- }
1254
- const response = await fetch(url, fetchOptions);
1255
- // Restore original host
1256
- this.headers["host"] = originalHost;
1257
- if (!response.ok) {
1258
- const errorBody = await response.text();
1259
- throw new Error(`HTTP ${response.status}: ${errorBody}`);
1260
- }
1261
- const responseHeaders = {};
1262
- response.headers.forEach((value, key) => {
1263
- responseHeaders[key.toLowerCase()] = value;
1264
- });
1265
- let body = await response.text();
1266
- if (decode &&
1267
- (responseHeaders["content-type"] === "application/xml" ||
1268
- (body.startsWith("<?xml") &&
1269
- responseHeaders["content-type"] !== "image/svg+xml"))) {
1270
- const xml2js = await import('xml2js');
1271
- const parser = new xml2js.Parser();
1272
- body = await parser.parseStringPromise(body);
1273
- }
1274
- return {
1275
- body,
1276
- headers: responseHeaders,
1277
- code: response.status,
1278
- };
1279
- }
1280
- }
1281
-
1282
- export { Device, File, FileExt, FileName, FileSize, FileType, Local, MinIO, S3, Storage, Upload, Wasabi };
1283
- //# sourceMappingURL=index.esm.js.map