-
Notifications
You must be signed in to change notification settings - Fork 2k
/
index.ts
1012 lines (891 loc) · 28.9 KB
/
index.ts
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
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import BasePlugin, {
type DefinePluginOpts,
type PluginOpts,
} from '@uppy/core/lib/BasePlugin.js'
import { RequestClient } from '@uppy/companion-client'
import type { RequestOptions } from '@uppy/utils/lib/CompanionClientProvider'
import type { Body, Meta, UppyFile } from '@uppy/utils/lib/UppyFile'
import type { Uppy } from '@uppy/core'
import EventManager from '@uppy/core/lib/EventManager.js'
import { RateLimitedQueue } from '@uppy/utils/lib/RateLimitedQueue'
import {
filterNonFailedFiles,
filterFilesToEmitUploadStarted,
} from '@uppy/utils/lib/fileFilters'
import { createAbortError } from '@uppy/utils/lib/AbortController'
import getAllowedMetaFields from '@uppy/utils/lib/getAllowedMetaFields'
import MultipartUploader from './MultipartUploader.ts'
import { throwIfAborted } from './utils.ts'
import type {
UploadResult,
UploadResultWithSignal,
MultipartUploadResultWithSignal,
UploadPartBytesResult,
} from './utils.js'
import createSignedURL from './createSignedURL.ts'
import { HTTPCommunicationQueue } from './HTTPCommunicationQueue.ts'
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
// @ts-ignore We don't want TS to generate types for the package.json
import packageJson from '../package.json'
interface MultipartFile<M extends Meta, B extends Body> extends UppyFile<M, B> {
s3Multipart: UploadResult
}
type PartUploadedCallback<M extends Meta, B extends Body> = (
file: UppyFile<M, B>,
part: { PartNumber: number; ETag: string },
) => void
declare module '@uppy/core' {
export interface UppyEventMap<M extends Meta, B extends Body> {
's3-multipart:part-uploaded': PartUploadedCallback<M, B>
}
}
function assertServerError<T>(res: T): T {
if ((res as any)?.error) {
const error = new Error((res as any).message)
Object.assign(error, (res as any).error)
throw error
}
return res
}
export interface AwsS3STSResponse {
credentials: {
AccessKeyId: string
SecretAccessKey: string
SessionToken: string
Expiration?: string
}
bucket: string
region: string
}
/**
* Computes the expiry time for a request signed with temporary credentials. If
* no expiration was provided, or an invalid value (e.g. in the past) is
* provided, undefined is returned. This function assumes the client clock is in
* sync with the remote server, which is a requirement for the signature to be
* validated for AWS anyway.
*/
function getExpiry(
credentials: AwsS3STSResponse['credentials'],
): number | undefined {
const expirationDate = credentials.Expiration
if (expirationDate) {
const timeUntilExpiry = Math.floor(
((new Date(expirationDate) as any as number) - Date.now()) / 1000,
)
if (timeUntilExpiry > 9) {
return timeUntilExpiry
}
}
return undefined
}
function getAllowedMetadata<M extends Record<string, any>>({
meta,
allowedMetaFields,
querify = false,
}: {
meta: M
allowedMetaFields?: string[] | null
querify?: boolean
}) {
const metaFields = allowedMetaFields ?? Object.keys(meta)
if (!meta) return {}
return Object.fromEntries(
metaFields
.filter((key) => meta[key] != null)
.map((key) => {
const realKey = querify ? `metadata[${key}]` : key
const value = String(meta[key])
return [realKey, value]
}),
)
}
type MaybePromise<T> = T | Promise<T>
type SignPartOptions = {
uploadId: string
key: string
partNumber: number
body: Blob
signal?: AbortSignal
}
export type AwsS3UploadParameters =
| {
method: 'POST'
url: string
fields: Record<string, string>
expires?: number
headers?: Record<string, string>
}
| {
method?: 'PUT'
url: string
fields?: Record<string, never>
expires?: number
headers?: Record<string, string>
}
export interface AwsS3Part {
PartNumber?: number
Size?: number
ETag?: string
}
type AWSS3WithCompanion = {
endpoint: ConstructorParameters<
typeof RequestClient<any, any>
>[1]['companionUrl']
headers?: ConstructorParameters<
typeof RequestClient<any, any>
>[1]['companionHeaders']
cookiesRule?: ConstructorParameters<
typeof RequestClient<any, any>
>[1]['companionCookiesRule']
getTemporarySecurityCredentials?: true
}
type AWSS3WithoutCompanion = {
getTemporarySecurityCredentials?: (options?: {
signal?: AbortSignal
}) => MaybePromise<AwsS3STSResponse>
uploadPartBytes?: (options: {
signature: AwsS3UploadParameters
body: FormData | Blob
size?: number
onProgress: any
onComplete: any
signal?: AbortSignal
}) => Promise<UploadPartBytesResult>
}
type AWSS3NonMultipartWithCompanionMandatory = {
// No related options
}
type AWSS3NonMultipartWithoutCompanionMandatory<
M extends Meta,
B extends Body,
> = {
getUploadParameters: (
file: UppyFile<M, B>,
options: RequestOptions,
) => MaybePromise<AwsS3UploadParameters>
}
type AWSS3NonMultipartWithCompanion = AWSS3WithCompanion &
AWSS3NonMultipartWithCompanionMandatory & {
shouldUseMultipart: false
}
type AWSS3NonMultipartWithoutCompanion<
M extends Meta,
B extends Body,
> = AWSS3WithoutCompanion &
AWSS3NonMultipartWithoutCompanionMandatory<M, B> & {
shouldUseMultipart: false
}
type AWSS3MultipartWithoutCompanionMandatorySignPart<
M extends Meta,
B extends Body,
> = {
signPart: (
file: UppyFile<M, B>,
opts: SignPartOptions,
) => MaybePromise<AwsS3UploadParameters>
}
type AWSS3MultipartWithoutCompanionMandatory<M extends Meta, B extends Body> = {
getChunkSize?: (file: { size: number }) => number
createMultipartUpload: (file: UppyFile<M, B>) => MaybePromise<UploadResult>
listParts: (
file: UppyFile<M, B>,
opts: UploadResultWithSignal,
) => MaybePromise<AwsS3Part[]>
abortMultipartUpload: (
file: UppyFile<M, B>,
opts: UploadResultWithSignal,
) => MaybePromise<void>
completeMultipartUpload: (
file: UppyFile<M, B>,
opts: {
uploadId: string
key: string
parts: AwsS3Part[]
signal: AbortSignal
},
) => MaybePromise<{ location?: string }>
} & AWSS3MultipartWithoutCompanionMandatorySignPart<M, B>
type AWSS3MultipartWithoutCompanion<
M extends Meta,
B extends Body,
> = AWSS3WithoutCompanion &
AWSS3MultipartWithoutCompanionMandatory<M, B> & {
shouldUseMultipart?: true
}
type AWSS3MultipartWithCompanion<
M extends Meta,
B extends Body,
> = AWSS3WithCompanion &
Partial<AWSS3MultipartWithoutCompanionMandatory<M, B>> & {
shouldUseMultipart?: true
}
type AWSS3MaybeMultipartWithCompanion<
M extends Meta,
B extends Body,
> = AWSS3WithCompanion &
Partial<AWSS3MultipartWithoutCompanionMandatory<M, B>> &
AWSS3NonMultipartWithCompanionMandatory & {
shouldUseMultipart: (file: UppyFile<M, B>) => boolean
}
type AWSS3MaybeMultipartWithoutCompanion<
M extends Meta,
B extends Body,
> = AWSS3WithoutCompanion &
AWSS3MultipartWithoutCompanionMandatory<M, B> &
AWSS3NonMultipartWithoutCompanionMandatory<M, B> & {
shouldUseMultipart: (file: UppyFile<M, B>) => boolean
}
interface _AwsS3MultipartOptions extends PluginOpts {
allowedMetaFields?: string[] | boolean
limit?: number
retryDelays?: number[] | null
}
export type AwsS3MultipartOptions<
M extends Meta,
B extends Body,
> = _AwsS3MultipartOptions &
(
| AWSS3NonMultipartWithCompanion
| AWSS3NonMultipartWithoutCompanion<M, B>
| AWSS3MultipartWithCompanion<M, B>
| AWSS3MultipartWithoutCompanion<M, B>
| AWSS3MaybeMultipartWithCompanion<M, B>
| AWSS3MaybeMultipartWithoutCompanion<M, B>
)
const defaultOptions = {
allowedMetaFields: true,
limit: 6,
getTemporarySecurityCredentials: false as any,
// eslint-disable-next-line no-bitwise
shouldUseMultipart: ((file: UppyFile<any, any>) =>
// eslint-disable-next-line no-bitwise
(file.size! >> 10) >> 10 > 100) as any as true,
retryDelays: [0, 1000, 3000, 5000],
} satisfies Partial<AwsS3MultipartOptions<any, any>>
export type { AwsBody } from './utils.ts'
export default class AwsS3Multipart<
M extends Meta,
B extends Body,
> extends BasePlugin<
DefinePluginOpts<AwsS3MultipartOptions<M, B>, keyof typeof defaultOptions> &
// We also have a few dynamic options defined below:
Pick<
AWSS3MultipartWithoutCompanionMandatory<M, B>,
| 'getChunkSize'
| 'createMultipartUpload'
| 'listParts'
| 'abortMultipartUpload'
| 'completeMultipartUpload'
> &
Required<Pick<AWSS3WithoutCompanion, 'uploadPartBytes'>> &
Partial<AWSS3WithCompanion> &
AWSS3MultipartWithoutCompanionMandatorySignPart<M, B> &
AWSS3NonMultipartWithoutCompanionMandatory<M, B>,
M,
B
> {
static VERSION = packageJson.version
#companionCommunicationQueue
#client!: RequestClient<M, B>
protected requests: any
protected uploaderEvents: Record<string, EventManager<M, B> | null>
protected uploaders: Record<string, MultipartUploader<M, B> | null>
constructor(uppy: Uppy<M, B>, opts?: AwsS3MultipartOptions<M, B>) {
super(uppy, {
...defaultOptions,
uploadPartBytes: AwsS3Multipart.uploadPartBytes,
createMultipartUpload: null as any,
listParts: null as any,
abortMultipartUpload: null as any,
completeMultipartUpload: null as any,
signPart: null as any,
getUploadParameters: null as any,
...opts,
})
// We need the `as any` here because of the dynamic default options.
this.type = 'uploader'
this.id = this.opts.id || 'AwsS3Multipart'
this.#setClient(opts)
const dynamicDefaultOptions = {
createMultipartUpload: this.createMultipartUpload,
listParts: this.listParts,
abortMultipartUpload: this.abortMultipartUpload,
completeMultipartUpload: this.completeMultipartUpload,
signPart:
opts?.getTemporarySecurityCredentials ?
this.createSignedURL
: this.signPart,
getUploadParameters:
opts?.getTemporarySecurityCredentials ?
(this.createSignedURL as any)
: this.getUploadParameters,
} satisfies Partial<AwsS3MultipartOptions<M, B>>
for (const key of Object.keys(dynamicDefaultOptions)) {
if (this.opts[key as keyof typeof dynamicDefaultOptions] == null) {
this.opts[key as keyof typeof dynamicDefaultOptions] =
dynamicDefaultOptions[key as keyof typeof dynamicDefaultOptions].bind(
this,
)
}
}
/**
* Simultaneous upload limiting is shared across all uploads with this plugin.
*
* @type {RateLimitedQueue}
*/
this.requests =
(this.opts as any).rateLimitedQueue ??
new RateLimitedQueue(this.opts.limit)
this.#companionCommunicationQueue = new HTTPCommunicationQueue(
this.requests,
this.opts,
this.#setS3MultipartState,
this.#getFile,
)
this.uploaders = Object.create(null)
this.uploaderEvents = Object.create(null)
}
private [Symbol.for('uppy test: getClient')]() {
return this.#client
}
#setClient(opts?: Partial<AwsS3MultipartOptions<M, B>>) {
if (
opts == null ||
!(
'endpoint' in opts ||
'companionUrl' in opts ||
'headers' in opts ||
'companionHeaders' in opts ||
'cookiesRule' in opts ||
'companionCookiesRule' in opts
)
)
return
if ('companionUrl' in opts && !('endpoint' in opts)) {
this.uppy.log(
'`companionUrl` option has been removed in @uppy/aws-s3, use `endpoint` instead.',
'warning',
)
}
if ('companionHeaders' in opts && !('headers' in opts)) {
this.uppy.log(
'`companionHeaders` option has been removed in @uppy/aws-s3, use `headers` instead.',
'warning',
)
}
if ('companionCookiesRule' in opts && !('cookiesRule' in opts)) {
this.uppy.log(
'`companionCookiesRule` option has been removed in @uppy/aws-s3, use `cookiesRule` instead.',
'warning',
)
}
if ('endpoint' in opts) {
this.#client = new RequestClient(this.uppy, {
pluginId: this.id,
provider: 'AWS',
companionUrl: this.opts.endpoint!,
companionHeaders: this.opts.headers,
companionCookiesRule: this.opts.cookiesRule,
})
} else {
if ('headers' in opts) {
this.#setCompanionHeaders()
}
if ('cookiesRule' in opts) {
this.#client.opts.companionCookiesRule = opts.cookiesRule
}
}
}
setOptions(newOptions: Partial<AwsS3MultipartOptions<M, B>>): void {
this.#companionCommunicationQueue.setOptions(newOptions)
super.setOptions(newOptions as any)
this.#setClient(newOptions)
}
/**
* Clean up all references for a file's upload: the MultipartUploader instance,
* any events related to the file, and the Companion WebSocket connection.
*
* Set `opts.abort` to tell S3 that the multipart upload is cancelled and must be removed.
* This should be done when the user cancels the upload, not when the upload is completed or errored.
*/
resetUploaderReferences(fileID: string, opts?: { abort: boolean }): void {
if (this.uploaders[fileID]) {
this.uploaders[fileID]!.abort({ really: opts?.abort || false })
this.uploaders[fileID] = null
}
if (this.uploaderEvents[fileID]) {
this.uploaderEvents[fileID]!.remove()
this.uploaderEvents[fileID] = null
}
}
#assertHost(method: string): void {
if (!this.#client) {
throw new Error(
`Expected a \`endpoint\` option containing a URL, or if you are not using Companion, a custom \`${method}\` implementation.`,
)
}
}
createMultipartUpload(
file: UppyFile<M, B>,
signal?: AbortSignal,
): Promise<UploadResult> {
this.#assertHost('createMultipartUpload')
throwIfAborted(signal)
const allowedMetaFields = getAllowedMetaFields(
this.opts.allowedMetaFields,
file.meta,
)
const metadata = getAllowedMetadata({ meta: file.meta, allowedMetaFields })
return this.#client
.post<UploadResult>(
's3/multipart',
{
filename: file.name,
type: file.type,
metadata,
},
{ signal },
)
.then(assertServerError)
}
listParts(
file: UppyFile<M, B>,
{ key, uploadId, signal }: UploadResultWithSignal,
oldSignal?: AbortSignal,
): Promise<AwsS3Part[]> {
signal ??= oldSignal // eslint-disable-line no-param-reassign
this.#assertHost('listParts')
throwIfAborted(signal)
const filename = encodeURIComponent(key)
return this.#client
.get<
AwsS3Part[]
>(`s3/multipart/${encodeURIComponent(uploadId)}?key=${filename}`, { signal })
.then(assertServerError)
}
completeMultipartUpload(
file: UppyFile<M, B>,
{ key, uploadId, parts, signal }: MultipartUploadResultWithSignal,
oldSignal?: AbortSignal,
): Promise<B> {
signal ??= oldSignal // eslint-disable-line no-param-reassign
this.#assertHost('completeMultipartUpload')
throwIfAborted(signal)
const filename = encodeURIComponent(key)
const uploadIdEnc = encodeURIComponent(uploadId)
return this.#client
.post<B>(
`s3/multipart/${uploadIdEnc}/complete?key=${filename}`,
{ parts: parts.map(({ ETag, PartNumber }) => ({ ETag, PartNumber })) },
{ signal },
)
.then(assertServerError)
}
#cachedTemporaryCredentials?: MaybePromise<AwsS3STSResponse>
async #getTemporarySecurityCredentials(options?: RequestOptions) {
throwIfAborted(options?.signal)
if (this.#cachedTemporaryCredentials == null) {
const { getTemporarySecurityCredentials } = this.opts
// We do not await it just yet, so concurrent calls do not try to override it:
if (getTemporarySecurityCredentials === true) {
this.#assertHost('getTemporarySecurityCredentials')
this.#cachedTemporaryCredentials = this.#client
.get<AwsS3STSResponse>('s3/sts', options)
.then(assertServerError)
} else {
this.#cachedTemporaryCredentials =
(getTemporarySecurityCredentials as AWSS3WithoutCompanion['getTemporarySecurityCredentials'])!(
options,
)
}
this.#cachedTemporaryCredentials = await this.#cachedTemporaryCredentials
setTimeout(
() => {
// At half the time left before expiration, we clear the cache. That's
// an arbitrary tradeoff to limit the number of requests made to the
// remote while limiting the risk of using an expired token in case the
// clocks are not exactly synced.
// The HTTP cache should be configured to ensure a client doesn't request
// more tokens than it needs, but this timeout provides a second layer of
// security in case the HTTP cache is disabled or misconfigured.
this.#cachedTemporaryCredentials = null as any
},
(getExpiry(this.#cachedTemporaryCredentials.credentials) || 0) * 500,
)
}
return this.#cachedTemporaryCredentials
}
async createSignedURL(
file: UppyFile<M, B>,
options: SignPartOptions,
): Promise<AwsS3UploadParameters> {
const data = await this.#getTemporarySecurityCredentials(options)
const expires = getExpiry(data.credentials) || 604_800 // 604 800 is the max value accepted by AWS.
const { uploadId, key, partNumber } = options
// Return an object in the correct shape.
return {
method: 'PUT',
expires,
fields: {},
url: `${await createSignedURL({
accountKey: data.credentials.AccessKeyId,
accountSecret: data.credentials.SecretAccessKey,
sessionToken: data.credentials.SessionToken,
expires,
bucketName: data.bucket,
Region: data.region,
Key: key ?? `${crypto.randomUUID()}-${file.name}`,
uploadId,
partNumber,
})}`,
// Provide content type header required by S3
headers: {
'Content-Type': file.type as string,
},
}
}
signPart(
file: UppyFile<M, B>,
{ uploadId, key, partNumber, signal }: SignPartOptions,
): Promise<AwsS3UploadParameters> {
this.#assertHost('signPart')
throwIfAborted(signal)
if (uploadId == null || key == null || partNumber == null) {
throw new Error(
'Cannot sign without a key, an uploadId, and a partNumber',
)
}
const filename = encodeURIComponent(key)
return this.#client
.get<AwsS3UploadParameters>(
`s3/multipart/${encodeURIComponent(uploadId)}/${partNumber}?key=${filename}`,
{ signal },
)
.then(assertServerError)
}
abortMultipartUpload(
file: UppyFile<M, B>,
{ key, uploadId, signal }: UploadResultWithSignal,
): Promise<void> {
this.#assertHost('abortMultipartUpload')
const filename = encodeURIComponent(key)
const uploadIdEnc = encodeURIComponent(uploadId)
return this.#client
.delete<void>(`s3/multipart/${uploadIdEnc}?key=${filename}`, undefined, {
signal,
})
.then(assertServerError)
}
getUploadParameters(
file: UppyFile<M, B>,
options: RequestOptions,
): Promise<AwsS3UploadParameters> {
const { meta } = file
const { type, name: filename } = meta
const allowedMetaFields = getAllowedMetaFields(
this.opts.allowedMetaFields,
file.meta,
)
const metadata = getAllowedMetadata({
meta,
allowedMetaFields,
querify: true,
})
const query = new URLSearchParams({ filename, type, ...metadata } as Record<
string,
string
>)
return this.#client.get(`s3/params?${query}`, options)
}
static async uploadPartBytes({
signature: { url, expires, headers, method = 'PUT' },
body,
size = (body as Blob).size,
onProgress,
onComplete,
signal,
}: {
signature: AwsS3UploadParameters
body: FormData | Blob
size?: number
onProgress: any
onComplete: any
signal?: AbortSignal
}): Promise<UploadPartBytesResult> {
throwIfAborted(signal)
if (url == null) {
throw new Error('Cannot upload to an undefined URL')
}
return new Promise((resolve, reject) => {
const xhr = new XMLHttpRequest()
xhr.open(method, url, true)
if (headers) {
Object.keys(headers).forEach((key) => {
xhr.setRequestHeader(key, headers[key])
})
}
xhr.responseType = 'text'
if (typeof expires === 'number') {
xhr.timeout = expires * 1000
}
function onabort() {
xhr.abort()
}
function cleanup() {
signal?.removeEventListener('abort', onabort)
}
signal?.addEventListener('abort', onabort)
xhr.upload.addEventListener('progress', (ev) => {
onProgress(ev)
})
xhr.addEventListener('abort', () => {
cleanup()
reject(createAbortError())
})
xhr.addEventListener('timeout', () => {
cleanup()
const error = new Error('Request has expired')
;(error as any).source = { status: 403 }
reject(error)
})
xhr.addEventListener('load', () => {
cleanup()
if (
xhr.status === 403 &&
xhr.responseText.includes('<Message>Request has expired</Message>')
) {
const error = new Error('Request has expired')
;(error as any).source = xhr
reject(error)
return
}
if (xhr.status < 200 || xhr.status >= 300) {
const error = new Error('Non 2xx')
;(error as any).source = xhr
reject(error)
return
}
onProgress?.({ loaded: size, lengthComputable: true })
// https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/getAllResponseHeaders#examples
const arr = xhr
.getAllResponseHeaders()
.trim()
.split(/[\r\n]+/)
// @ts-expect-error null is allowed to avoid inherited properties
const headersMap: Record<string, string> = { __proto__: null }
for (const line of arr) {
const parts = line.split(': ')
const header = parts.shift()!
const value = parts.join(': ')
headersMap[header] = value
}
const { etag, location } = headersMap
if (method.toUpperCase() === 'POST' && location === null) {
// Not being able to read the Location header is not a fatal error.
// eslint-disable-next-line no-console
console.warn(
'AwsS3/Multipart: Could not read the Location header. This likely means CORS is not configured correctly on the S3 Bucket. See https://uppy.io/docs/aws-s3-multipart#S3-Bucket-Configuration for instructions.',
)
}
if (etag === null) {
reject(
new Error(
'AwsS3/Multipart: Could not read the ETag header. This likely means CORS is not configured correctly on the S3 Bucket. See https://uppy.io/docs/aws-s3-multipart#S3-Bucket-Configuration for instructions.',
),
)
return
}
onComplete?.(etag)
resolve({
...headersMap,
ETag: etag, // keep capitalised ETag for backwards compatiblity
})
})
xhr.addEventListener('error', (ev) => {
cleanup()
const error = new Error('Unknown error')
;(error as any).source = ev.target
reject(error)
})
xhr.send(body)
})
}
#setS3MultipartState = (
file: UppyFile<M, B>,
{ key, uploadId }: UploadResult,
) => {
const cFile = this.uppy.getFile(file.id)
if (cFile == null) {
// file was removed from store
return
}
this.uppy.setFileState(file.id, {
s3Multipart: {
...(cFile as MultipartFile<M, B>).s3Multipart,
key,
uploadId,
},
} as Partial<MultipartFile<M, B>>)
}
#getFile = (file: UppyFile<M, B>) => {
return this.uppy.getFile(file.id) || file
}
#uploadLocalFile(file: UppyFile<M, B>) {
return new Promise<void | string>((resolve, reject) => {
const onProgress = (bytesUploaded: number, bytesTotal: number) => {
const latestFile = this.uppy.getFile(file.id)
this.uppy.emit('upload-progress', latestFile, {
uploadStarted: latestFile.progress.uploadStarted ?? 0,
bytesUploaded,
bytesTotal,
})
}
const onError = (err: unknown) => {
this.uppy.log(err as Error)
this.uppy.emit('upload-error', file, err as Error)
this.resetUploaderReferences(file.id)
reject(err)
}
const onSuccess = (result: B) => {
const uploadResp = {
body: {
...result,
},
status: 200,
uploadURL: result.location as string,
}
this.resetUploaderReferences(file.id)
this.uppy.emit('upload-success', this.#getFile(file), uploadResp)
if (result.location) {
this.uppy.log(`Download ${file.name} from ${result.location}`)
}
resolve()
}
const upload = new MultipartUploader<M, B>(file.data, {
// .bind to pass the file object to each handler.
companionComm: this.#companionCommunicationQueue,
log: (...args: Parameters<Uppy<M, B>['log']>) => this.uppy.log(...args),
getChunkSize:
this.opts.getChunkSize ?
this.opts.getChunkSize.bind(this)
: undefined,
onProgress,
onError,
onSuccess,
onPartComplete: (part) => {
this.uppy.emit(
's3-multipart:part-uploaded',
this.#getFile(file),
part,
)
},
file,
shouldUseMultipart: this.opts.shouldUseMultipart,
...(file as MultipartFile<M, B>).s3Multipart,
})
this.uploaders[file.id] = upload
const eventManager = new EventManager(this.uppy)
this.uploaderEvents[file.id] = eventManager
eventManager.onFileRemove(file.id, (removed) => {
upload.abort()
this.resetUploaderReferences(file.id, { abort: true })
resolve(`upload ${removed} was removed`)
})
eventManager.onCancelAll(file.id, () => {
upload.abort()
this.resetUploaderReferences(file.id, { abort: true })
resolve(`upload ${file.id} was canceled`)
})
eventManager.onFilePause(file.id, (isPaused) => {
if (isPaused) {
upload.pause()
} else {
upload.start()
}
})
eventManager.onPauseAll(file.id, () => {
upload.pause()
})
eventManager.onResumeAll(file.id, () => {
upload.start()
})
upload.start()
})
}
// eslint-disable-next-line class-methods-use-this
#getCompanionClientArgs(file: UppyFile<M, B>) {
return {
...file.remote?.body,
protocol: 's3-multipart',
size: file.data.size,
metadata: file.meta,
}
}
#upload = async (fileIDs: string[]) => {
if (fileIDs.length === 0) return undefined
const files = this.uppy.getFilesByIds(fileIDs)
const filesFiltered = filterNonFailedFiles(files)
const filesToEmit = filterFilesToEmitUploadStarted(filesFiltered)
this.uppy.emit('upload-start', filesToEmit)
const promises = filesFiltered.map((file) => {
if (file.isRemote) {
const getQueue = () => this.requests
this.#setResumableUploadsCapability(false)
const controller = new AbortController()
const removedHandler = (removedFile: UppyFile<M, B>) => {
if (removedFile.id === file.id) controller.abort()
}
this.uppy.on('file-removed', removedHandler)
const uploadPromise = this.uppy
.getRequestClientForFile<RequestClient<M, B>>(file)
.uploadRemoteFile(file, this.#getCompanionClientArgs(file), {
signal: controller.signal,
getQueue,
})
this.requests.wrapSyncFunction(
() => {
this.uppy.off('file-removed', removedHandler)
},
{ priority: -1 },
)()
return uploadPromise
}
return this.#uploadLocalFile(file)
})
const upload = await Promise.all(promises)
// After the upload is done, another upload may happen with only local files.
// We reset the capability so that the next upload can use resumable uploads.
this.#setResumableUploadsCapability(true)
return upload
}
#setCompanionHeaders = () => {
this.#client?.setCompanionHeaders(this.opts.headers!)
}
#setResumableUploadsCapability = (boolean: boolean) => {
const { capabilities } = this.uppy.getState()
this.uppy.setState({
capabilities: {
...capabilities,
resumableUploads: boolean,
},
})
}
#resetResumableCapability = () => {
this.#setResumableUploadsCapability(true)
}
install(): void {
this.#setResumableUploadsCapability(true)
this.uppy.addPreProcessor(this.#setCompanionHeaders)
this.uppy.addUploader(this.#upload)
this.uppy.on('cancel-all', this.#resetResumableCapability)
}