-
Notifications
You must be signed in to change notification settings - Fork 2k
/
Copy pathindex.js
698 lines (585 loc) · 21.1 KB
/
index.js
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
import BasePlugin from '@uppy/core/lib/BasePlugin.js'
import { nanoid } from 'nanoid/non-secure'
import { Provider, RequestClient, Socket } from '@uppy/companion-client'
import emitSocketProgress from '@uppy/utils/lib/emitSocketProgress'
import getSocketHost from '@uppy/utils/lib/getSocketHost'
import EventTracker from '@uppy/utils/lib/EventTracker'
import ProgressTimeout from '@uppy/utils/lib/ProgressTimeout'
import { RateLimitedQueue, internalRateLimitedQueue } from '@uppy/utils/lib/RateLimitedQueue'
import NetworkError from '@uppy/utils/lib/NetworkError'
import isNetworkError from '@uppy/utils/lib/isNetworkError'
import { filterNonFailedFiles, filterFilesToEmitUploadStarted } from '@uppy/utils/lib/fileFilters'
import packageJson from '../package.json'
import locale from './locale.js'
function buildResponseError (xhr, err) {
let error = err
// No error message
if (!error) error = new Error('Upload error')
// Got an error message string
if (typeof error === 'string') error = new Error(error)
// Got something else
if (!(error instanceof Error)) {
error = Object.assign(new Error('Upload error'), { data: error })
}
if (isNetworkError(xhr)) {
error = new NetworkError(error, xhr)
return error
}
error.request = xhr
return error
}
/**
* Set `data.type` in the blob to `file.meta.type`,
* because we might have detected a more accurate file type in Uppy
* https://stackoverflow.com/a/50875615
*
* @param {object} file File object with `data`, `size` and `meta` properties
* @returns {object} blob updated with the new `type` set from `file.meta.type`
*/
function setTypeInBlob (file) {
const dataWithUpdatedType = file.data.slice(0, file.data.size, file.meta.type)
return dataWithUpdatedType
}
export default class XHRUpload extends BasePlugin {
// eslint-disable-next-line global-require
static VERSION = packageJson.version
#queueRequestSocketToken
constructor (uppy, opts) {
super(uppy, opts)
this.type = 'uploader'
this.id = this.opts.id || 'XHRUpload'
this.title = 'XHRUpload'
this.defaultLocale = locale
// Default options
const defaultOptions = {
formData: true,
fieldName: opts.bundle ? 'files[]' : 'file',
method: 'post',
allowedMetaFields: null,
responseUrlFieldName: 'url',
bundle: false,
headers: {},
timeout: 30 * 1000,
limit: 5,
withCredentials: false,
responseType: '',
/**
* @param {string} responseText the response body string
*/
getResponseData (responseText) {
let parsedResponse = {}
try {
parsedResponse = JSON.parse(responseText)
} catch (err) {
uppy.log(err)
}
return parsedResponse
},
/**
*
* @param {string} _ the response body string
* @param {XMLHttpRequest | respObj} response the response object (XHR or similar)
*/
getResponseError (_, response) {
let error = new Error('Upload error')
if (isNetworkError(response)) {
error = new NetworkError(error, response)
}
return error
},
/**
* Check if the response from the upload endpoint indicates that the upload was successful.
*
* @param {number} status the response status code
*/
validateStatus (status) {
return status >= 200 && status < 300
},
}
this.opts = { ...defaultOptions, ...opts }
this.i18nInit()
// Simultaneous upload limiting is shared across all uploads with this plugin.
if (internalRateLimitedQueue in this.opts) {
this.requests = this.opts[internalRateLimitedQueue]
} else {
this.requests = new RateLimitedQueue(this.opts.limit)
}
if (this.opts.bundle && !this.opts.formData) {
throw new Error('`opts.formData` must be true when `opts.bundle` is enabled.')
}
if (opts?.allowedMetaFields === undefined && 'metaFields' in this.opts) {
throw new Error('The `metaFields` option has been renamed to `allowedMetaFields`.')
}
this.uploaderEvents = Object.create(null)
this.#queueRequestSocketToken = this.requests.wrapPromiseFunction(this.#requestSocketToken, { priority: -1 })
}
getOptions (file) {
const overrides = this.uppy.getState().xhrUpload
const { headers } = this.opts
const opts = {
...this.opts,
...(overrides || {}),
...(file.xhrUpload || {}),
headers: {},
}
// Support for `headers` as a function, only in the XHRUpload settings.
// Options set by other plugins in Uppy state or on the files themselves are still merged in afterward.
//
// ```js
// headers: (file) => ({ expires: file.meta.expires })
// ```
if (typeof headers === 'function') {
opts.headers = headers(file)
} else {
Object.assign(opts.headers, this.opts.headers)
}
if (overrides) {
Object.assign(opts.headers, overrides.headers)
}
if (file.xhrUpload) {
Object.assign(opts.headers, file.xhrUpload.headers)
}
return opts
}
// eslint-disable-next-line class-methods-use-this
addMetadata (formData, meta, opts) {
const allowedMetaFields = Array.isArray(opts.allowedMetaFields)
? opts.allowedMetaFields
: Object.keys(meta) // Send along all fields by default.
allowedMetaFields.forEach((item) => {
if (Array.isArray(meta[item])) {
// In this case we don't transform `item` to add brackets, it's up to
// the user to add the brackets so it won't be overridden.
meta[item].forEach(subItem => formData.append(item, subItem))
} else {
formData.append(item, meta[item])
}
})
}
createFormDataUpload (file, opts) {
const formPost = new FormData()
this.addMetadata(formPost, file.meta, opts)
const dataWithUpdatedType = setTypeInBlob(file)
if (file.name) {
formPost.append(opts.fieldName, dataWithUpdatedType, file.meta.name)
} else {
formPost.append(opts.fieldName, dataWithUpdatedType)
}
return formPost
}
createBundledUpload (files, opts) {
const formPost = new FormData()
const { meta } = this.uppy.getState()
this.addMetadata(formPost, meta, opts)
files.forEach((file) => {
const options = this.getOptions(file)
const dataWithUpdatedType = setTypeInBlob(file)
if (file.name) {
formPost.append(options.fieldName, dataWithUpdatedType, file.name)
} else {
formPost.append(options.fieldName, dataWithUpdatedType)
}
})
return formPost
}
async #upload (file, current, total) {
const opts = this.getOptions(file)
this.uppy.log(`uploading ${current} of ${total}`)
return new Promise((resolve, reject) => {
const data = opts.formData
? this.createFormDataUpload(file, opts)
: file.data
const xhr = new XMLHttpRequest()
this.uploaderEvents[file.id] = new EventTracker(this.uppy)
let queuedRequest
const timer = new ProgressTimeout(opts.timeout, () => {
const error = new Error(this.i18n('uploadStalled', { seconds: Math.ceil(opts.timeout / 1000) }))
this.uppy.emit('upload-stalled', error, [file])
})
const id = nanoid()
xhr.upload.addEventListener('loadstart', () => {
this.uppy.log(`[XHRUpload] ${id} started`)
})
xhr.upload.addEventListener('progress', (ev) => {
this.uppy.log(`[XHRUpload] ${id} progress: ${ev.loaded} / ${ev.total}`)
// Begin checking for timeouts when progress starts, instead of loading,
// to avoid timing out requests on browser concurrency queue
timer.progress()
if (ev.lengthComputable) {
this.uppy.emit('upload-progress', file, {
uploader: this,
bytesUploaded: ev.loaded,
bytesTotal: ev.total,
})
}
})
xhr.addEventListener('load', () => {
this.uppy.log(`[XHRUpload] ${id} finished`)
timer.done()
queuedRequest.done()
if (this.uploaderEvents[file.id]) {
this.uploaderEvents[file.id].remove()
this.uploaderEvents[file.id] = null
}
if (opts.validateStatus(xhr.status, xhr.responseText, xhr)) {
const body = opts.getResponseData(xhr.responseText, xhr)
const uploadURL = body[opts.responseUrlFieldName]
const uploadResp = {
status: xhr.status,
body,
uploadURL,
}
this.uppy.emit('upload-success', file, uploadResp)
if (uploadURL) {
this.uppy.log(`Download ${file.name} from ${uploadURL}`)
}
return resolve(file)
}
const body = opts.getResponseData(xhr.responseText, xhr)
const error = buildResponseError(xhr, opts.getResponseError(xhr.responseText, xhr))
const response = {
status: xhr.status,
body,
}
this.uppy.emit('upload-error', file, error, response)
return reject(error)
})
xhr.addEventListener('error', () => {
this.uppy.log(`[XHRUpload] ${id} errored`)
timer.done()
queuedRequest.done()
if (this.uploaderEvents[file.id]) {
this.uploaderEvents[file.id].remove()
this.uploaderEvents[file.id] = null
}
const error = buildResponseError(xhr, opts.getResponseError(xhr.responseText, xhr))
this.uppy.emit('upload-error', file, error)
return reject(error)
})
xhr.open(opts.method.toUpperCase(), opts.endpoint, true)
// IE10 does not allow setting `withCredentials` and `responseType`
// before `open()` is called.
xhr.withCredentials = opts.withCredentials
if (opts.responseType !== '') {
xhr.responseType = opts.responseType
}
queuedRequest = this.requests.run(() => {
// When using an authentication system like JWT, the bearer token goes as a header. This
// header needs to be fresh each time the token is refreshed so computing and setting the
// headers just before the upload starts enables this kind of authentication to work properly.
// Otherwise, half-way through the list of uploads the token could be stale and the upload would fail.
const currentOpts = this.getOptions(file)
Object.keys(currentOpts.headers).forEach((header) => {
xhr.setRequestHeader(header, currentOpts.headers[header])
})
xhr.send(data)
return () => {
timer.done()
xhr.abort()
}
})
this.onFileRemove(file.id, () => {
queuedRequest.abort()
reject(new Error('File removed'))
})
this.onCancelAll(file.id, ({ reason }) => {
if (reason === 'user') {
queuedRequest.abort()
}
reject(new Error('Upload cancelled'))
})
})
}
#requestSocketToken = async (file) => {
const opts = this.getOptions(file)
const Client = file.remote.providerOptions.provider ? Provider : RequestClient
const client = new Client(this.uppy, file.remote.providerOptions)
const allowedMetaFields = Array.isArray(opts.allowedMetaFields)
? opts.allowedMetaFields
// Send along all fields by default.
: Object.keys(file.meta)
const res = await client.post(file.remote.url, {
...file.remote.body,
protocol: 'multipart',
endpoint: opts.endpoint,
size: file.data.size,
fieldname: opts.fieldName,
metadata: Object.fromEntries(allowedMetaFields.map(name => [name, file.meta[name]])),
httpMethod: opts.method,
useFormData: opts.formData,
headers: opts.headers,
})
return res.token
}
// NOTE! Keep this duplicated code in sync with other plugins
// TODO we should probably abstract this into a common function
async #uploadRemote (file) {
// TODO: we could rewrite this to use server-sent events instead of creating WebSockets.
try {
if (file.serverToken) {
return await this.connectToServerSocket(file)
}
const serverToken = await this.#queueRequestSocketToken(file)
if (!this.uppy.getState().files[file.id]) return undefined
this.uppy.setFileState(file.id, { serverToken })
return await this.connectToServerSocket(this.uppy.getFile(file.id))
} catch (err) {
this.uppy.setFileState(file.id, { serverToken: undefined })
this.uppy.emit('upload-error', file, err)
throw err
}
}
async connectToServerSocket (file) {
return new Promise((resolve, reject) => {
const opts = this.getOptions(file)
const token = file.serverToken
const host = getSocketHost(file.remote.companionUrl)
let socket
const createSocket = () => {
if (socket != null) return
socket = new Socket({ target: `${host}/api/${token}` })
socket.on('progress', (progressData) => emitSocketProgress(this, progressData, file))
socket.on('success', (data) => {
const body = opts.getResponseData(data.response.responseText, data.response)
const uploadURL = body[opts.responseUrlFieldName]
const uploadResp = {
status: data.response.status,
body,
uploadURL,
}
this.uppy.emit('upload-success', file, uploadResp)
queuedRequest.done() // eslint-disable-line no-use-before-define
socket.close()
if (this.uploaderEvents[file.id]) {
this.uploaderEvents[file.id].remove()
this.uploaderEvents[file.id] = null
}
return resolve()
})
socket.on('error', (errData) => {
const resp = errData.response
const error = resp
? opts.getResponseError(resp.responseText, resp)
: Object.assign(new Error(errData.error.message), { cause: errData.error })
this.uppy.emit('upload-error', file, error)
queuedRequest.done() // eslint-disable-line no-use-before-define
if (this.uploaderEvents[file.id]) {
this.uploaderEvents[file.id].remove()
this.uploaderEvents[file.id] = null
}
reject(error)
})
}
this.uploaderEvents[file.id] = new EventTracker(this.uppy)
let queuedRequest = this.requests.run(() => {
if (file.isPaused) {
socket?.send('pause', {})
} else {
createSocket()
}
return () => socket.close()
})
this.onFileRemove(file.id, () => {
socket?.send('cancel', {})
queuedRequest.abort()
resolve(`upload ${file.id} was removed`)
})
this.onCancelAll(file.id, ({ reason } = {}) => {
if (reason === 'user') {
socket?.send('cancel', {})
queuedRequest.abort()
}
resolve(`upload ${file.id} was canceled`)
})
const onRetryRequest = () => {
if (socket == null) {
queuedRequest.abort()
} else {
socket.send('pause', {})
queuedRequest.done()
}
queuedRequest = this.requests.run(() => {
if (!file.isPaused) {
if (socket == null) {
createSocket()
} else {
socket.send('resume', {})
}
}
return () => socket.close()
})
}
this.onRetry(file.id, onRetryRequest)
this.onRetryAll(file.id, onRetryRequest)
}).catch((err) => {
this.uppy.emit('upload-error', file, err)
return Promise.reject(err)
})
}
#uploadBundle (files) {
return new Promise((resolve, reject) => {
const { endpoint } = this.opts
const { method } = this.opts
const optsFromState = this.uppy.getState().xhrUpload
const formData = this.createBundledUpload(files, {
...this.opts,
...(optsFromState || {}),
})
const xhr = new XMLHttpRequest()
const emitError = (error) => {
files.forEach((file) => {
this.uppy.emit('upload-error', file, error)
})
}
const timer = new ProgressTimeout(this.opts.timeout, () => {
const error = new Error(this.i18n('uploadStalled', { seconds: Math.ceil(this.opts.timeout / 1000) }))
this.uppy.emit('upload-stalled', error, files)
})
xhr.upload.addEventListener('loadstart', () => {
this.uppy.log('[XHRUpload] started uploading bundle')
timer.progress()
})
xhr.upload.addEventListener('progress', (ev) => {
timer.progress()
if (!ev.lengthComputable) return
files.forEach((file) => {
this.uppy.emit('upload-progress', file, {
uploader: this,
bytesUploaded: (ev.loaded / ev.total) * file.size,
bytesTotal: file.size,
})
})
})
xhr.addEventListener('load', (ev) => {
timer.done()
if (this.opts.validateStatus(ev.target.status, xhr.responseText, xhr)) {
const body = this.opts.getResponseData(xhr.responseText, xhr)
const uploadResp = {
status: ev.target.status,
body,
}
files.forEach((file) => {
this.uppy.emit('upload-success', file, uploadResp)
})
return resolve()
}
const error = this.opts.getResponseError(xhr.responseText, xhr) || new Error('Upload error')
error.request = xhr
emitError(error)
return reject(error)
})
xhr.addEventListener('error', () => {
timer.done()
const error = this.opts.getResponseError(xhr.responseText, xhr) || new Error('Upload error')
emitError(error)
return reject(error)
})
this.uppy.on('cancel-all', ({ reason } = {}) => {
if (reason !== 'user') return
timer.done()
xhr.abort()
})
xhr.open(method.toUpperCase(), endpoint, true)
// IE10 does not allow setting `withCredentials` and `responseType`
// before `open()` is called.
xhr.withCredentials = this.opts.withCredentials
if (this.opts.responseType !== '') {
xhr.responseType = this.opts.responseType
}
Object.keys(this.opts.headers).forEach((header) => {
xhr.setRequestHeader(header, this.opts.headers[header])
})
xhr.send(formData)
})
}
async #uploadFiles (files) {
await Promise.allSettled(files.map((file, i) => {
const current = parseInt(i, 10) + 1
const total = files.length
if (file.isRemote) {
return this.#uploadRemote(file, current, total)
}
return this.#upload(file, current, total)
}))
}
onFileRemove (fileID, cb) {
this.uploaderEvents[fileID].on('file-removed', (file) => {
if (fileID === file.id) cb(file.id)
})
}
onRetry (fileID, cb) {
this.uploaderEvents[fileID].on('upload-retry', (targetFileID) => {
if (fileID === targetFileID) {
cb()
}
})
}
onRetryAll (fileID, cb) {
this.uploaderEvents[fileID].on('retry-all', () => {
if (!this.uppy.getFile(fileID)) return
cb()
})
}
onCancelAll (fileID, eventHandler) {
this.uploaderEvents[fileID].on('cancel-all', (...args) => {
if (!this.uppy.getFile(fileID)) return
eventHandler(...args)
})
}
#handleUpload = async (fileIDs) => {
if (fileIDs.length === 0) {
this.uppy.log('[XHRUpload] No files to upload!')
return
}
// No limit configured by the user, and no RateLimitedQueue passed in by a "parent" plugin
// (basically just AwsS3) using the internal symbol
if (this.opts.limit === 0 && !this.opts[internalRateLimitedQueue]) {
this.uppy.log(
'[XHRUpload] When uploading multiple files at once, consider setting the `limit` option (to `10` for example), to limit the number of concurrent uploads, which helps prevent memory and network issues: https://uppy.io/docs/xhr-upload/#limit-0',
'warning',
)
}
this.uppy.log('[XHRUpload] Uploading...')
const files = this.uppy.getFilesByIds(fileIDs)
const filesFiltered = filterNonFailedFiles(files)
const filesToEmit = filterFilesToEmitUploadStarted(filesFiltered)
this.uppy.emit('upload-start', filesToEmit)
if (this.opts.bundle) {
// if bundle: true, we don’t support remote uploads
const isSomeFileRemote = filesFiltered.some(file => file.isRemote)
if (isSomeFileRemote) {
throw new Error('Can’t upload remote files when the `bundle: true` option is set')
}
if (typeof this.opts.headers === 'function') {
throw new TypeError('`headers` may not be a function when the `bundle: true` option is set')
}
await this.#uploadBundle(filesFiltered)
} else {
await this.#uploadFiles(filesFiltered)
}
}
install () {
if (this.opts.bundle) {
const { capabilities } = this.uppy.getState()
this.uppy.setState({
capabilities: {
...capabilities,
individualCancellation: false,
},
})
}
this.uppy.addUploader(this.#handleUpload)
}
uninstall () {
if (this.opts.bundle) {
const { capabilities } = this.uppy.getState()
this.uppy.setState({
capabilities: {
...capabilities,
individualCancellation: true,
},
})
}
this.uppy.removeUploader(this.#handleUpload)
}
}