-
Notifications
You must be signed in to change notification settings - Fork 14
/
Copy pathtusuploader.umd.js
1914 lines (1578 loc) · 52.2 KB
/
tusuploader.umd.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
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
(function (global, factory) {
typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory() :
typeof define === 'function' && define.amd ? define(factory) :
(global.TusUploader = factory());
}(this, (function () { 'use strict';
var commonjsGlobal = typeof window !== 'undefined' ? window : typeof global !== 'undefined' ? global : typeof self !== 'undefined' ? self : {};
function createCommonjsModule(fn, module) {
return module = { exports: {} }, fn(module, module.exports), module.exports;
}
var fingerprint_1 = createCommonjsModule(function (module, exports) {
// Generated by Babel
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = fingerprint;
/**
* Generate a fingerprint for a file which will be used the store the endpoint
*
* @param {File} file
* @return {String}
*/
function fingerprint(file) {
return ["tus", file.name, file.type, file.size, file.lastModified].join("-");
}
});
var error = createCommonjsModule(function (module, exports) {
// Generated by Babel
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }
function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }
var DetailedError = function (_Error) {
_inherits(DetailedError, _Error);
function DetailedError(error) {
var causingErr = arguments.length <= 1 || arguments[1] === undefined ? null : arguments[1];
var xhr = arguments.length <= 2 || arguments[2] === undefined ? null : arguments[2];
_classCallCheck(this, DetailedError);
var _this = _possibleConstructorReturn(this, Object.getPrototypeOf(DetailedError).call(this, error.message));
_this.originalRequest = xhr;
_this.causingError = causingErr;
var message = error.message;
if (causingErr != null) {
message += ", caused by " + causingErr.toString();
}
if (xhr != null) {
message += ", originated from request (response code: " + xhr.status + ", response text: " + xhr.responseText + ")";
}
_this.message = message;
return _this;
}
return DetailedError;
}(Error);
exports.default = DetailedError;
});
var hasOwn = Object.prototype.hasOwnProperty;
var toStr = Object.prototype.toString;
var isArray = function isArray(arr) {
if (typeof Array.isArray === 'function') {
return Array.isArray(arr);
}
return toStr.call(arr) === '[object Array]';
};
var isPlainObject = function isPlainObject(obj) {
if (!obj || toStr.call(obj) !== '[object Object]') {
return false;
}
var hasOwnConstructor = hasOwn.call(obj, 'constructor');
var hasIsPrototypeOf = obj.constructor && obj.constructor.prototype && hasOwn.call(obj.constructor.prototype, 'isPrototypeOf');
// Not own constructor property must be Object
if (obj.constructor && !hasOwnConstructor && !hasIsPrototypeOf) {
return false;
}
// Own properties are enumerated firstly, so to speed up,
// if last one is own, then all properties are own.
var key;
for (key in obj) { /**/ }
return typeof key === 'undefined' || hasOwn.call(obj, key);
};
var index$2 = function extend() {
var options, name, src, copy, copyIsArray, clone;
var target = arguments[0];
var i = 1;
var length = arguments.length;
var deep = false;
// Handle a deep copy situation
if (typeof target === 'boolean') {
deep = target;
target = arguments[1] || {};
// skip the boolean and the target
i = 2;
}
if (target == null || (typeof target !== 'object' && typeof target !== 'function')) {
target = {};
}
for (; i < length; ++i) {
options = arguments[i];
// Only deal with non-null/undefined values
if (options != null) {
// Extend the base object
for (name in options) {
src = target[name];
copy = options[name];
// Prevent never-ending loop
if (target !== copy) {
// Recurse if we're merging plain objects or arrays
if (deep && copy && (isPlainObject(copy) || (copyIsArray = isArray(copy)))) {
if (copyIsArray) {
copyIsArray = false;
clone = src && isArray(src) ? src : [];
} else {
clone = src && isPlainObject(src) ? src : {};
}
// Never move original objects, clone them
target[name] = extend(deep, clone, copy);
// Don't bring in undefined values
} else if (typeof copy !== 'undefined') {
target[name] = copy;
}
}
}
}
}
// Return the modified object
return target;
};
var resolveUrl = createCommonjsModule(function (module, exports) {
// Copyright 2014 Simon Lydell
// X11 (“MIT”) Licensed. (See LICENSE.)
void (function(root, factory) {
if (typeof undefined === "function" && undefined.amd) {
undefined(factory);
} else {
module.exports = factory();
}
}(commonjsGlobal, function() {
function resolveUrl(/* ...urls */) {
var numUrls = arguments.length;
if (numUrls === 0) {
throw new Error("resolveUrl requires at least one argument; got none.")
}
var base = document.createElement("base");
base.href = arguments[0];
if (numUrls === 1) {
return base.href
}
var head = document.getElementsByTagName("head")[0];
head.insertBefore(base, head.firstChild);
var a = document.createElement("a");
var resolved;
for (var index = 1; index < numUrls; index++) {
a.href = arguments[index];
resolved = a.href;
base.href = resolved;
}
head.removeChild(base);
return resolved
}
return resolveUrl
}));
});
var request = createCommonjsModule(function (module, exports) {
// Generated by Babel
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.newRequest = newRequest;
exports.resolveUrl = resolveUrl$$1;
var _resolveUrl2 = _interopRequireDefault(resolveUrl);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function newRequest() {
return new window.XMLHttpRequest();
} /* global window */
function resolveUrl$$1(origin, link) {
return (0, _resolveUrl2.default)(origin, link);
}
});
var source = createCommonjsModule(function (module, exports) {
// Generated by Babel
"use strict";
var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.getSource = getSource;
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
var FileSource = function () {
function FileSource(file) {
_classCallCheck(this, FileSource);
this._file = file;
this.size = file.size;
}
_createClass(FileSource, [{
key: "slice",
value: function slice(start, end) {
return this._file.slice(start, end);
}
}, {
key: "close",
value: function close() {}
}]);
return FileSource;
}();
function getSource(input) {
// Since we emulate the Blob type in our tests (not all target browsers
// support it), we cannot use `instanceof` for testing whether the input value
// can be handled. Instead, we simply check is the slice() function and the
// size property are available.
if (typeof input.slice === "function" && typeof input.size !== "undefined") {
return new FileSource(input);
}
throw new Error("source object may only be an instance of File or Blob in this environment");
}
});
var base64 = createCommonjsModule(function (module, exports) {
// Generated by Babel
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.encode = encode;
/* global: window */
var _window = window;
var btoa = _window.btoa;
function encode(data) {
return btoa(unescape(encodeURIComponent(data)));
}
var isSupported = exports.isSupported = "btoa" in window;
});
var storage = createCommonjsModule(function (module, exports) {
// Generated by Babel
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.setItem = setItem;
exports.getItem = getItem;
exports.removeItem = removeItem;
/* global window, localStorage */
var hasStorage = false;
try {
hasStorage = "localStorage" in window;
// Attempt to store and read entries from the local storage to detect Private
// Mode on Safari on iOS (see #49)
var key = "tusSupport";
localStorage.setItem(key, localStorage.getItem(key));
} catch (e) {
// If we try to access localStorage inside a sandboxed iframe, a SecurityError
// is thrown. When in private mode on iOS Safari, a QuotaExceededError is
// thrown (see #49)
if (e.code === e.SECURITY_ERR || e.code === e.QUOTA_EXCEEDED_ERR) {
hasStorage = false;
} else {
throw e;
}
}
var canStoreURLs = exports.canStoreURLs = hasStorage;
function setItem(key, value) {
if (!hasStorage) return;
return localStorage.setItem(key, value);
}
function getItem(key) {
if (!hasStorage) return;
return localStorage.getItem(key);
}
function removeItem(key) {
if (!hasStorage) return;
return localStorage.removeItem(key);
}
});
var upload = createCommonjsModule(function (module, exports) {
// Generated by Babel
"use strict";
var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); /* global window */
// We import the files used inside the Node environment which are rewritten
// for browsers using the rules defined in the package.json
Object.defineProperty(exports, "__esModule", {
value: true
});
var _fingerprint2 = _interopRequireDefault(fingerprint_1);
var _error2 = _interopRequireDefault(error);
var _extend2 = _interopRequireDefault(index$2);
var Base64 = _interopRequireWildcard(base64);
var Storage = _interopRequireWildcard(storage);
function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } }
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
var defaultOptions = {
endpoint: "",
fingerprint: _fingerprint2.default,
resume: true,
onProgress: null,
onChunkComplete: null,
onSuccess: null,
onError: null,
headers: {},
chunkSize: Infinity,
withCredentials: false,
uploadUrl: null,
uploadSize: null,
overridePatchMethod: false,
retryDelays: null
};
var Upload = function () {
function Upload(file, options) {
_classCallCheck(this, Upload);
this.options = (0, _extend2.default)(true, {}, defaultOptions, options);
// The underlying File/Blob object
this.file = file;
// The URL against which the file will be uploaded
this.url = null;
// The underlying XHR object for the current PATCH request
this._xhr = null;
// The fingerpinrt for the current file (set after start())
this._fingerprint = null;
// The offset used in the current PATCH request
this._offset = null;
// True if the current PATCH request has been aborted
this._aborted = false;
// The file's size in bytes
this._size = null;
// The Source object which will wrap around the given file and provides us
// with a unified interface for getting its size and slice chunks from its
// content allowing us to easily handle Files, Blobs, Buffers and Streams.
this._source = null;
// The current count of attempts which have been made. Null indicates none.
this._retryAttempt = 0;
// The timeout's ID which is used to delay the next retry
this._retryTimeout = null;
// The offset of the remote upload before the latest attempt was started.
this._offsetBeforeRetry = 0;
}
_createClass(Upload, [{
key: "start",
value: function start() {
var _this = this;
var file = this.file;
if (!file) {
this._emitError(new Error("tus: no file or stream to upload provided"));
return;
}
if (!this.options.endpoint) {
this._emitError(new Error("tus: no endpoint provided"));
return;
}
var source$$1 = this._source = (0, source.getSource)(file, this.options.chunkSize);
// Firstly, check if the caller has supplied a manual upload size or else
// we will use the calculated size by the source object.
if (this.options.uploadSize != null) {
var size = +this.options.uploadSize;
if (isNaN(size)) {
throw new Error("tus: cannot convert `uploadSize` option into a number");
}
this._size = size;
} else {
var size = source$$1.size;
// The size property will be null if we cannot calculate the file's size,
// for example if you handle a stream.
if (size == null) {
throw new Error("tus: cannot automatically derive upload's size from input and must be specified manually using the `uploadSize` option");
}
this._size = size;
}
var retryDelays = this.options.retryDelays;
if (retryDelays != null) {
if (Object.prototype.toString.call(retryDelays) !== "[object Array]") {
throw new Error("tus: the `retryDelays` option must either be an array or null");
} else {
(function () {
var errorCallback = _this.options.onError;
_this.options.onError = function (err) {
// Restore the original error callback which may have been set.
_this.options.onError = errorCallback;
// We will reset the attempt counter if
// - we were already able to connect to the server (offset != null) and
// - we were able to upload a small chunk of data to the server
var shouldResetDelays = _this._offset != null && _this._offset > _this._offsetBeforeRetry;
if (shouldResetDelays) {
_this._retryAttempt = 0;
}
var isOnline = true;
if (typeof window !== "undefined" && "navigator" in window && window.navigator.onLine === false) {
isOnline = false;
}
// We only attempt a retry if
// - we didn't exceed the maxium number of retries, yet, and
// - this error was caused by a request or it's response and
// - the browser does not indicate that we are offline
var shouldRetry = _this._retryAttempt < retryDelays.length && err.originalRequest != null && isOnline;
if (!shouldRetry) {
_this._emitError(err);
return;
}
var delay = retryDelays[_this._retryAttempt++];
_this._offsetBeforeRetry = _this._offset;
_this.options.uploadUrl = _this.url;
_this._retryTimeout = setTimeout(function () {
_this.start();
}, delay);
};
})();
}
}
// Reset the aborted flag when the upload is started or else the
// _startUpload will stop before sending a request if the upload has been
// aborted previously.
this._aborted = false;
// A URL has manually been specified, so we try to resume
if (this.options.uploadUrl != null) {
this.url = this.options.uploadUrl;
this._resumeUpload();
return;
}
// Try to find the endpoint for the file in the storage
if (this.options.resume) {
this._fingerprint = this.options.fingerprint(file);
var resumedUrl = Storage.getItem(this._fingerprint);
if (resumedUrl != null) {
this.url = resumedUrl;
this._resumeUpload();
return;
}
}
// An upload has not started for the file yet, so we start a new one
this._createUpload();
}
}, {
key: "abort",
value: function abort() {
if (this._xhr !== null) {
this._xhr.abort();
this._source.close();
this._aborted = true;
}
if (this._retryTimeout != null) {
clearTimeout(this._retryTimeout);
this._retryTimeout = null;
}
}
}, {
key: "_emitXhrError",
value: function _emitXhrError(xhr, err, causingErr) {
this._emitError(new _error2.default(err, causingErr, xhr));
}
}, {
key: "_emitError",
value: function _emitError(err) {
if (typeof this.options.onError === "function") {
this.options.onError(err);
} else {
throw err;
}
}
}, {
key: "_emitSuccess",
value: function _emitSuccess() {
if (typeof this.options.onSuccess === "function") {
this.options.onSuccess();
}
}
/**
* Publishes notification when data has been sent to the server. This
* data may not have been accepted by the server yet.
* @param {number} bytesSent Number of bytes sent to the server.
* @param {number} bytesTotal Total number of bytes to be sent to the server.
*/
}, {
key: "_emitProgress",
value: function _emitProgress(bytesSent, bytesTotal) {
if (typeof this.options.onProgress === "function") {
this.options.onProgress(bytesSent, bytesTotal);
}
}
/**
* Publishes notification when a chunk of data has been sent to the server
* and accepted by the server.
* @param {number} chunkSize Size of the chunk that was accepted by the
* server.
* @param {number} bytesAccepted Total number of bytes that have been
* accepted by the server.
* @param {number} bytesTotal Total number of bytes to be sent to the server.
*/
}, {
key: "_emitChunkComplete",
value: function _emitChunkComplete(chunkSize, bytesAccepted, bytesTotal) {
if (typeof this.options.onChunkComplete === "function") {
this.options.onChunkComplete(chunkSize, bytesAccepted, bytesTotal);
}
}
/**
* Set the headers used in the request and the withCredentials property
* as defined in the options
*
* @param {XMLHttpRequest} xhr
*/
}, {
key: "_setupXHR",
value: function _setupXHR(xhr) {
xhr.setRequestHeader("Tus-Resumable", "1.0.0");
var headers = this.options.headers;
for (var name in headers) {
xhr.setRequestHeader(name, headers[name]);
}
xhr.withCredentials = this.options.withCredentials;
}
/**
* Create a new upload using the creation extension by sending a POST
* request to the endpoint. After successful creation the file will be
* uploaded
*
* @api private
*/
}, {
key: "_createUpload",
value: function _createUpload() {
var _this2 = this;
var xhr = (0, request.newRequest)();
xhr.open("POST", this.options.endpoint, true);
xhr.onload = function () {
if (!(xhr.status >= 200 && xhr.status < 300)) {
_this2._emitXhrError(xhr, new Error("tus: unexpected response while creating upload"));
return;
}
_this2.url = (0, request.resolveUrl)(_this2.options.endpoint, xhr.getResponseHeader("Location"));
if (_this2.options.resume) {
Storage.setItem(_this2._fingerprint, _this2.url);
}
_this2._offset = 0;
_this2._startUpload();
};
xhr.onerror = function (err) {
_this2._emitXhrError(xhr, new Error("tus: failed to create upload"), err);
};
this._setupXHR(xhr);
xhr.setRequestHeader("Upload-Length", this._size);
// Add metadata if values have been added
var metadata = encodeMetadata(this.options.metadata);
if (metadata !== "") {
xhr.setRequestHeader("Upload-Metadata", metadata);
}
xhr.send(null);
}
/*
* Try to resume an existing upload. First a HEAD request will be sent
* to retrieve the offset. If the request fails a new upload will be
* created. In the case of a successful response the file will be uploaded.
*
* @api private
*/
}, {
key: "_resumeUpload",
value: function _resumeUpload() {
var _this3 = this;
var xhr = (0, request.newRequest)();
xhr.open("HEAD", this.url, true);
xhr.onload = function () {
if (!(xhr.status >= 200 && xhr.status < 300)) {
if (_this3.options.resume) {
// Remove stored fingerprint and corresponding endpoint,
// since the file can not be found
Storage.removeItem(_this3._fingerprint);
}
// If the upload is locked (indicated by the 423 Locked status code), we
// emit an error instead of directly starting a new upload. This way the
// retry logic can catch the error and will retry the upload. An upload
// is usually locked for a short period of time and will be available
// afterwards.
if (xhr.status === 423) {
_this3._emitXhrError(xhr, new Error("tus: upload is currently locked; retry later"));
return;
}
// Try to create a new upload
_this3.url = null;
_this3._createUpload();
return;
}
var offset = parseInt(xhr.getResponseHeader("Upload-Offset"), 10);
if (isNaN(offset)) {
_this3._emitXhrError(xhr, new Error("tus: invalid or missing offset value"));
return;
}
var length = parseInt(xhr.getResponseHeader("Upload-Length"), 10);
if (isNaN(length)) {
_this3._emitXhrError(xhr, new Error("tus: invalid or missing length value"));
return;
}
// Upload has already been completed and we do not need to send additional
// data to the server
if (offset === length) {
_this3._emitProgress(length, length);
_this3._emitSuccess();
return;
}
_this3._offset = offset;
_this3._startUpload();
};
xhr.onerror = function (err) {
_this3._emitXhrError(xhr, new Error("tus: failed to resume upload"), err);
};
this._setupXHR(xhr);
xhr.send(null);
}
/**
* Start uploading the file using PATCH requests. The file will be divided
* into chunks as specified in the chunkSize option. During the upload
* the onProgress event handler may be invoked multiple times.
*
* @api private
*/
}, {
key: "_startUpload",
value: function _startUpload() {
var _this4 = this;
// If the upload has been aborted, we will not send the next PATCH request.
// This is important if the abort method was called during a callback, such
// as onChunkComplete or onProgress.
if (this._aborted) {
return;
}
var xhr = this._xhr = (0, request.newRequest)();
// Some browser and servers may not support the PATCH method. For those
// cases, you can tell tus-js-client to use a POST request with the
// X-HTTP-Method-Override header for simulating a PATCH request.
if (this.options.overridePatchMethod) {
xhr.open("POST", this.url, true);
xhr.setRequestHeader("X-HTTP-Method-Override", "PATCH");
} else {
xhr.open("PATCH", this.url, true);
}
xhr.onload = function () {
if (!(xhr.status >= 200 && xhr.status < 300)) {
_this4._emitXhrError(xhr, new Error("tus: unexpected response while uploading chunk"));
return;
}
var offset = parseInt(xhr.getResponseHeader("Upload-Offset"), 10);
if (isNaN(offset)) {
_this4._emitXhrError(xhr, new Error("tus: invalid or missing offset value"));
return;
}
_this4._emitProgress(offset, _this4._size);
_this4._emitChunkComplete(offset - _this4._offset, offset, _this4._size);
_this4._offset = offset;
if (offset == _this4._size) {
// Yay, finally done :)
_this4._emitSuccess();
_this4._source.close();
return;
}
_this4._startUpload();
};
xhr.onerror = function (err) {
// Don't emit an error if the upload was aborted manually
if (_this4._aborted) {
return;
}
_this4._emitXhrError(xhr, new Error("tus: failed to upload chunk at offset " + _this4._offset), err);
};
// Test support for progress events before attaching an event listener
if ("upload" in xhr) {
xhr.upload.onprogress = function (e) {
if (!e.lengthComputable) {
return;
}
_this4._emitProgress(start + e.loaded, _this4._size);
};
}
this._setupXHR(xhr);
xhr.setRequestHeader("Upload-Offset", this._offset);
xhr.setRequestHeader("Content-Type", "application/offset+octet-stream");
var start = this._offset;
var end = this._offset + this.options.chunkSize;
// The specified chunkSize may be Infinity or the calcluated end position
// may exceed the file's size. In both cases, we limit the end position to
// the input's total size for simpler calculations and correctness.
if (end === Infinity || end > this._size) {
end = this._size;
}
xhr.send(this._source.slice(start, end));
}
}]);
return Upload;
}();
function encodeMetadata(metadata) {
if (!Base64.isSupported) {
return "";
}
var encoded = [];
for (var key in metadata) {
encoded.push(key + " " + Base64.encode(metadata[key]));
}
return encoded.join(",");
}
Upload.defaultOptions = defaultOptions;
exports.default = Upload;
});
var index = createCommonjsModule(function (module) {
// Generated by Babel
"use strict";
var _upload2 = _interopRequireDefault(upload);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
/* global window */
var defaultOptions = _upload2.default.defaultOptions;
if (typeof window !== "undefined") {
// Browser environment using XMLHttpRequest
var _window = window;
var XMLHttpRequest = _window.XMLHttpRequest;
var Blob = _window.Blob;
var isSupported = XMLHttpRequest && Blob && typeof Blob.prototype.slice === "function";
} else {
// Node.js environment using http module
var isSupported = true;
}
// The usage of the commonjs exporting syntax instead of the new ECMAScript
// one is actually inteded and prevents weird behaviour if we are trying to
// import this module in another module using Babel.
module.exports = {
Upload: _upload2.default,
isSupported: isSupported,
canStoreURLs: storage.canStoreURLs,
defaultOptions: defaultOptions
};
});
var ee = createCommonjsModule(function (module) {
module.exports = {
on: function (ev, handler) {
var events = this._events;(events[ev] || (events[ev] = [])).push(handler);
},
removeListener: function (ev, handler) {
var array = this._events[ev];
array && array.splice(array.indexOf(handler), 1);
},
emit: function (ev) {
var args = [].slice.call(arguments, 1),
array = this._events[ev] || [];
for (var i = 0, len = array.length; i < len; i++) {
array[i].apply(this, args);
}
},
once: function (ev, handler) {
this.on(ev, function () {
handler.apply(this, arguments);
this.removeListener(ev, handler);
});
},
constructor: function constructor() {
this._events = {};
return this
}
};
module.exports.constructor.prototype = module.exports;
});
var browserCuid = createCommonjsModule(function (module) {
/**
* cuid.js
* Collision-resistant UID generator for browsers and node.
* Sequential for fast db lookups and recency sorting.
* Safe for element IDs and server-side lookups.
*
* Extracted from CLCTR
*
* Copyright (c) Eric Elliott 2012
* MIT License
*/
/*global window, navigator, document, require, process, module */
(function (app) {
'use strict';
var namespace = 'cuid',
c = 0,
blockSize = 4,
base = 36,
discreteValues = Math.pow(base, blockSize),
pad = function pad(num, size) {
var s = "000000000" + num;
return s.substr(s.length-size);