@scaleflex/widget-tus 0.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.
package/lib/index.js ADDED
@@ -0,0 +1,983 @@
1
+ function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); }
2
+ function _extends() { return _extends = Object.assign ? Object.assign.bind() : function (n) { for (var e = 1; e < arguments.length; e++) { var t = arguments[e]; for (var r in t) ({}).hasOwnProperty.call(t, r) && (n[r] = t[r]); } return n; }, _extends.apply(null, arguments); }
3
+ function ownKeys(e, r) { var t = Object.keys(e); if (Object.getOwnPropertySymbols) { var o = Object.getOwnPropertySymbols(e); r && (o = o.filter(function (r) { return Object.getOwnPropertyDescriptor(e, r).enumerable; })), t.push.apply(t, o); } return t; }
4
+ function _objectSpread(e) { for (var r = 1; r < arguments.length; r++) { var t = null != arguments[r] ? arguments[r] : {}; r % 2 ? ownKeys(Object(t), !0).forEach(function (r) { _defineProperty(e, r, t[r]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys(Object(t)).forEach(function (r) { Object.defineProperty(e, r, Object.getOwnPropertyDescriptor(t, r)); }); } return e; }
5
+ function _classCallCheck(a, n) { if (!(a instanceof n)) throw new TypeError("Cannot call a class as a function"); }
6
+ function _defineProperties(e, r) { for (var t = 0; t < r.length; t++) { var o = r[t]; o.enumerable = o.enumerable || !1, o.configurable = !0, "value" in o && (o.writable = !0), Object.defineProperty(e, _toPropertyKey(o.key), o); } }
7
+ function _createClass(e, r, t) { return r && _defineProperties(e.prototype, r), t && _defineProperties(e, t), Object.defineProperty(e, "prototype", { writable: !1 }), e; }
8
+ function _callSuper(t, o, e) { return o = _getPrototypeOf(o), _possibleConstructorReturn(t, _isNativeReflectConstruct() ? Reflect.construct(o, e || [], _getPrototypeOf(t).constructor) : o.apply(t, e)); }
9
+ function _possibleConstructorReturn(t, e) { if (e && ("object" == _typeof(e) || "function" == typeof e)) return e; if (void 0 !== e) throw new TypeError("Derived constructors may only return object or undefined"); return _assertThisInitialized(t); }
10
+ function _assertThisInitialized(e) { if (void 0 === e) throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); return e; }
11
+ function _isNativeReflectConstruct() { try { var t = !Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); } catch (t) {} return (_isNativeReflectConstruct = function _isNativeReflectConstruct() { return !!t; })(); }
12
+ function _getPrototypeOf(t) { return _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf.bind() : function (t) { return t.__proto__ || Object.getPrototypeOf(t); }, _getPrototypeOf(t); }
13
+ function _inherits(t, e) { if ("function" != typeof e && null !== e) throw new TypeError("Super expression must either be null or a function"); t.prototype = Object.create(e && e.prototype, { constructor: { value: t, writable: !0, configurable: !0 } }), Object.defineProperty(t, "prototype", { writable: !1 }), e && _setPrototypeOf(t, e); }
14
+ function _setPrototypeOf(t, e) { return _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function (t, e) { return t.__proto__ = e, t; }, _setPrototypeOf(t, e); }
15
+ function _defineProperty(e, r, t) { return (r = _toPropertyKey(r)) in e ? Object.defineProperty(e, r, { value: t, enumerable: !0, configurable: !0, writable: !0 }) : e[r] = t, e; }
16
+ function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == _typeof(i) ? i : i + ""; }
17
+ function _toPrimitive(t, r) { if ("object" != _typeof(t) || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != _typeof(i)) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); }
18
+ import { Plugin } from '@scaleflex/widget-core';
19
+ import { Upload } from 'tus-js-client';
20
+ import { Provider, RequestClient, Socket } from '@scaleflex/widget-companion-client';
21
+ import emitSocketProgress from '@scaleflex/widget-utils/lib/emitSocketProgress';
22
+ import getSocketHost from '@scaleflex/widget-utils/lib/getSocketHost';
23
+ import settle from '@scaleflex/widget-utils/lib/settle';
24
+ import EventTracker from '@scaleflex/widget-utils/lib/EventTracker';
25
+ import NetworkError from '@scaleflex/widget-utils/lib/NetworkError';
26
+ import isNetworkError from '@scaleflex/widget-utils/lib/isNetworkError';
27
+ import RateLimitedQueue from '@scaleflex/widget-utils/lib/RateLimitedQueue';
28
+ import hasProperty from '@scaleflex/widget-utils/lib/hasProperty';
29
+ import { COMPANION_URLS, PROGRESS_PANEL_STATUS, UPLOAD_CONNECTOR_SERVER } from '@scaleflex/widget-utils/lib/constants';
30
+ import { uploadsReplaced, uploadCapabilitiesUpdated } from '@scaleflex/widget-core/lib/slices/uploads.slice';
31
+ import { selectUserSassKey } from '@scaleflex/widget-core/lib/slices/user.slice';
32
+ import Translator from '@scaleflex/widget-utils/lib/Translator';
33
+ import getFingerprint from './getFingerprint';
34
+
35
+ // TODO: find a way to show version of the current plugin
36
+ // why solution below isn't good?
37
+ // first import doesn't work with webpack 5 as it was deprecated
38
+ // second import fixes webpack 5 issue as it was mentioned in their docs
39
+ // but it exposes our package.json to the client and it is mentioned as security rist in mutiple places
40
+ // https://github.com/axelpale/genversion
41
+ // https://stackoverflow.com/questions/64993118/error-should-not-import-the-named-export-version-imported-as-version
42
+ // https://stackoverflow.com/questions/9153571/is-there-a-way-to-get-version-from-package-json-in-nodejs-code/10855054#10855054
43
+ // import { version } from '../package.json'
44
+ // import packageInfo from '../package.json'
45
+
46
+ /** @typedef {import('../types').TusOptions} TusOptions */
47
+ /** @typedef {import('tus-js-client').UploadOptions} RawTusOptions */
48
+ /** @typedef {import('@scaleflex/widget-core').Filerobot} Filerobot */
49
+ /** @typedef {import('@scaleflex/widget-core').FilerobotFile} FilerobotFile */
50
+ /** @typedef {import('@scaleflex/widget-core').FailedFilerobotFile<{}>} FailedFilerobotFile */
51
+
52
+ /**
53
+ * Extracted from https://github.com/tus/tus-js-client/blob/master/lib/upload.js#L13
54
+ * excepted we removed 'fingerprint' key to avoid adding more dependencies
55
+ *
56
+ * @type {RawTusOptions}
57
+ */
58
+ var tusDefaultOptions = {
59
+ endpoint: '',
60
+ uploadUrl: null,
61
+ metadata: {},
62
+ uploadSize: null,
63
+ onProgress: null,
64
+ onChunkComplete: null,
65
+ onSuccess: null,
66
+ onError: null,
67
+ overridePatchMethod: false,
68
+ headers: {},
69
+ addRequestId: false,
70
+ chunkSize: Infinity,
71
+ retryDelays: [0, 1000, 3000, 5000],
72
+ parallelUploads: 1,
73
+ storeFingerprintForResuming: true,
74
+ removeFingerprintOnSuccess: true,
75
+ uploadLengthDeferred: false,
76
+ uploadDataDuringCreation: false
77
+ };
78
+
79
+ /**
80
+ * Tus resumable file filerobot
81
+ */
82
+ var Tus = /*#__PURE__*/function (_Plugin) {
83
+ // static VERSION = packageInfo.version
84
+
85
+ /**
86
+ * @param {Filerobot} filerobot
87
+ * @param {TusOptions} opts
88
+ */
89
+ function Tus(filerobot) {
90
+ var _this$opts$retryDelay;
91
+ var _this;
92
+ var _opts = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
93
+ _classCallCheck(this, Tus);
94
+ _this = _callSuper(this, Tus, [filerobot, _opts]);
95
+ _defineProperty(_this, "successHandler", function (_ref) {
96
+ var _file$progress;
97
+ var _ref$fileResponse = _ref.fileResponse,
98
+ fileResponse = _ref$fileResponse === void 0 ? {} : _ref$fileResponse,
99
+ file = _ref.file,
100
+ uploadId = _ref.uploadId,
101
+ data = _ref.data,
102
+ queuedRequest = _ref.queuedRequest,
103
+ resolve = _ref.resolve;
104
+ if (file !== null && file !== void 0 && (_file$progress = file.progress) !== null && _file$progress !== void 0 && _file$progress.uploadComplete) return;
105
+ var fileJson = _objectSpread(_objectSpread({}, file.fileJson || {}), file);
106
+ fileJson === null || fileJson === void 0 ? true : delete fileJson.preview;
107
+ var uploadRes = {
108
+ uploadURL: data.url,
109
+ body: {
110
+ file: fileResponse
111
+ }
112
+ };
113
+ _this.resetFilerobotReferences(file.id);
114
+ queuedRequest.done();
115
+ _this.filerobot.emit('upload-success', fileJson, uploadRes, {
116
+ uploadId: uploadId
117
+ });
118
+ if (data.url) {
119
+ _this.filerobot.log("Download ".concat(data.file.name, " from ").concat(data.url));
120
+ }
121
+ resolve(data);
122
+ });
123
+ _defineProperty(_this, "getFileJson", async function (_ref2) {
124
+ var _uploadUrl$match;
125
+ var uploadUrl = _ref2.uploadUrl,
126
+ file = _ref2.file,
127
+ uploadId = _ref2.uploadId,
128
+ queuedRequest = _ref2.queuedRequest,
129
+ resolve = _ref2.resolve,
130
+ reject = _ref2.reject;
131
+ var retryLimit = 0;
132
+ var regex = /files\/(.*)/;
133
+ var id = (uploadUrl === null || uploadUrl === void 0 ? void 0 : (_uploadUrl$match = uploadUrl.match(regex)) === null || _uploadUrl$match === void 0 ? void 0 : _uploadUrl$match[1]) || '';
134
+ var fileSizeLimit = 1 * Math.pow(10, 8);
135
+ var isFileHasDelay = file.size > fileSizeLimit;
136
+ var delay = isFileHasDelay ? 13000 : 6000;
137
+ if (!id) return;
138
+ var req = new XMLHttpRequest();
139
+ var openRequest = function openRequest() {
140
+ req.open('GET', "".concat(_this.opts.jsonEndpoint, "/").concat(id));
141
+ req.onload = onSuccess;
142
+ req.onerror = onError;
143
+ req.send();
144
+ };
145
+ var onSuccess = function onSuccess(res) {
146
+ if (req.status !== 200 && retryLimit <= 3) {
147
+ retryLimit++;
148
+ if (isFileHasDelay && retryLimit === 1 && req.status === 404) {
149
+ _this.filerobot.info(_this.i18n('resumableUploadDelayInfo'), 'success');
150
+ _this.filerobot.setFileUploadingState(file.id, uploadId, {
151
+ progress: _objectSpread(_objectSpread({}, file.progress), {}, {
152
+ status: PROGRESS_PANEL_STATUS.DELAYED
153
+ })
154
+ });
155
+ _this.emit('activity-update', {
156
+ id: file.id,
157
+ progress: {
158
+ status: PROGRESS_PANEL_STATUS.DELAYED
159
+ }
160
+ });
161
+ }
162
+ setTimeout(function () {
163
+ openRequest();
164
+ }, delay);
165
+ return;
166
+ }
167
+ if (retryLimit === 4) {
168
+ _this.filerobot.setFileUploadingState(file.id, uploadId, {
169
+ progress: _objectSpread(_objectSpread({}, file.progress), {}, {
170
+ status: PROGRESS_PANEL_STATUS.COMPLETED
171
+ })
172
+ });
173
+ }
174
+ try {
175
+ var _JSON$parse;
176
+ var fileResponse = (_JSON$parse = JSON.parse(req === null || req === void 0 ? void 0 : req.response)) === null || _JSON$parse === void 0 ? void 0 : _JSON$parse.file;
177
+ if (!fileResponse) {
178
+ onError(res);
179
+ return;
180
+ }
181
+ _this.filerobot.setFileUploadingState(file.id, uploadId, {
182
+ fileJson: fileResponse
183
+ });
184
+ _this.successHandler({
185
+ fileResponse: fileResponse,
186
+ file: file,
187
+ uploadId: uploadId,
188
+ data: res,
189
+ queuedRequest: queuedRequest,
190
+ resolve: resolve
191
+ });
192
+ } catch (err) {
193
+ onError(err);
194
+ }
195
+ };
196
+ var onError = function onError(error) {
197
+ _this.filerobot.emit('upload-error', file, error, {
198
+ uploadId: uploadId
199
+ });
200
+ return reject(error);
201
+ };
202
+ openRequest();
203
+ });
204
+ _defineProperty(_this, "requestSocketToken", async function (file) {
205
+ var Client = file.remote.providerOptions.provider ? Provider : RequestClient;
206
+ var client = new Client(_this.filerobot, file.remote.providerOptions);
207
+ var opts = _objectSpread({}, _this.opts);
208
+ if (file.tus) {
209
+ // Install file-specific upload overrides.
210
+ _extends(opts, file.tus);
211
+ }
212
+ var res = await client.post(file.remote.url, _objectSpread(_objectSpread({}, file.remote.body), {}, {
213
+ endpoint: opts.endpoint,
214
+ uploadUrl: opts.uploadUrl,
215
+ protocol: 'tus',
216
+ size: file.data.size,
217
+ headers: opts.headers,
218
+ metadata: _objectSpread(_objectSpread({}, file.info), {}, {
219
+ 'filerobot-folder': _this.filerobot.getRemoteUploadFolder({
220
+ file: file,
221
+ opts: _this.opts
222
+ })
223
+ })
224
+ }));
225
+ return res.token;
226
+ });
227
+ _this.type = 'uploader';
228
+ _this.id = _this.opts.id || 'Tus';
229
+ _this.title = 'Tus';
230
+ _this.defaultLocale = {
231
+ strings: {
232
+ resumableUploadDelayInfo: 'Assets uploaded. It takes few seconds to complete processing, after you can use your assets.'
233
+ }
234
+ };
235
+
236
+ // set default options
237
+ var defaultOptions = {
238
+ autoRetry: true,
239
+ resume: true,
240
+ useFastRemoteRetry: true,
241
+ limit: 20,
242
+ retryDelays: [0, 1000, 3000, 5000],
243
+ headers: {}
244
+ };
245
+
246
+ // merge default options with the ones set by user
247
+ /** @type {import("../types").TusOptions} */
248
+ _this.opts = _extends({}, defaultOptions, _opts);
249
+ _this.opts.headers['X-Filerobot-Token'] = filerobot.opts.container;
250
+ _this.opts.headers['X-Filerobot-Key'] = selectUserSassKey(_this.getGlobalState());
251
+ if (!_this.opts.headers['X-Filerobot-Key']) {
252
+ filerobot.on('sass-key-obtained', function (sassKey) {
253
+ _this.opts.headers['X-Filerobot-Key'] = sassKey;
254
+ });
255
+ }
256
+ if (!_this.opts.headers['X-Filerobot-Token']) {
257
+ _this.opts.headers['X-Filerobot-Token'] = filerobot.opts.container;
258
+ }
259
+ _this.i18nInit();
260
+ if (!_this.opts.endpoint || _this.opts.endpoint.length === 0) {
261
+ var companionProdUrl = sessionStorage.getItem(UPLOAD_CONNECTOR_SERVER) || COMPANION_URLS.PROD;
262
+ _this.opts.endpoint = "".concat(filerobot.opts.dev ? COMPANION_URLS.DEV : companionProdUrl, "/files");
263
+ _this.opts.jsonEndpoint = "".concat(filerobot.opts.dev ? COMPANION_URLS.DEV : companionProdUrl, "/json");
264
+ }
265
+
266
+ /**
267
+ * Simultaneous upload limiting is shared across all uploads with this plugin.
268
+ *
269
+ * @type {RateLimitedQueue}
270
+ */
271
+ _this.requests = new RateLimitedQueue(_this.opts.limit);
272
+ _this.retryDelayIterator = (_this$opts$retryDelay = _this.opts.retryDelays) === null || _this$opts$retryDelay === void 0 ? void 0 : _this$opts$retryDelay.values();
273
+ _this.filerobots = Object.create(null);
274
+ _this.filerobotEvents = Object.create(null);
275
+ _this.filerobotSockets = Object.create(null);
276
+ _this.handleResetProgress = _this.handleResetProgress.bind(_this);
277
+ _this.handleUpload = _this.handleUpload.bind(_this);
278
+ _this.queueRequestSocketToken = _this.requests.wrapPromiseFunction(_this.requestSocketToken, {
279
+ priority: -1
280
+ });
281
+ return _this;
282
+ }
283
+ _inherits(Tus, _Plugin);
284
+ return _createClass(Tus, [{
285
+ key: "handleResetProgress",
286
+ value: function handleResetProgress() {
287
+ var files = _extends({}, this.filerobot.getUploads());
288
+ Object.keys(files).forEach(function (fileId) {
289
+ // Only clone the file object if it has a Tus `uploadUrl` attached.
290
+ if (files[fileId].tus && files[fileId].tus.uploadUrl) {
291
+ var tusState = _extends({}, files[fileId].tus);
292
+ delete tusState.uploadUrl;
293
+ files[fileId] = _extends({}, files[fileId], {
294
+ tus: tusState
295
+ });
296
+ }
297
+ });
298
+ this.filerobot.dispatch(uploadsReplaced(files));
299
+ }
300
+ }, {
301
+ key: "i18nInit",
302
+ value: function i18nInit() {
303
+ this.translator = new Translator([this.defaultLocale, this.filerobot.locale, this.opts.locale]);
304
+ this.i18n = this.translator.translate.bind(this.translator);
305
+ }
306
+
307
+ /**
308
+ * Clean up all references for a file's upload: the tus.Upload instance,
309
+ * any events related to the file, and the Companion WebSocket connection.
310
+ *
311
+ * @param {string} fileId
312
+ */
313
+ }, {
314
+ key: "resetFilerobotReferences",
315
+ value: function resetFilerobotReferences(fileId) {
316
+ var opts = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
317
+ if (this.filerobots[fileId]) {
318
+ var filerobot = this.filerobots[fileId];
319
+ filerobot.abort();
320
+ if (opts.abort) {
321
+ filerobot.abort(true);
322
+ }
323
+ this.filerobots[fileId] = null;
324
+ }
325
+ if (this.filerobotEvents[fileId]) {
326
+ this.filerobotEvents[fileId].remove();
327
+ this.filerobotEvents[fileId] = null;
328
+ }
329
+ if (this.filerobotSockets[fileId]) {
330
+ this.filerobotSockets[fileId].close();
331
+ this.filerobotSockets[fileId] = null;
332
+ }
333
+ }
334
+ }, {
335
+ key: "upload",
336
+ value:
337
+ /**
338
+ * Create a new Tus upload.
339
+ *
340
+ * A lot can happen during an upload, so this is quite hard to follow!
341
+ * - First, the upload is started. If the file was already paused by the time the upload starts, nothing should happen.
342
+ * If the `limit` option is used, the upload must be queued onto the `this.requests` queue.
343
+ * When an upload starts, we store the tus.Upload instance, and an EventTracker instance that manages the event listeners
344
+ * for pausing, cancellation, removal, etc.
345
+ * - While the upload is in progress, it may be paused or cancelled.
346
+ * Pausing aborts the underlying tus.Upload, and removes the upload from the `this.requests` queue. All other state is
347
+ * maintained.
348
+ * Cancelling removes the upload from the `this.requests` queue, and completely aborts the upload-- the `tus.Upload`
349
+ * instance is aborted and discarded, the EventTracker instance is destroyed (removing all listeners).
350
+ * Resuming the upload uses the `this.requests` queue as well, to prevent selectively pausing and resuming uploads from
351
+ * bypassing the limit.
352
+ * - After completing an upload, the tus.Upload and EventTracker instances are cleaned up, and the upload is marked as done
353
+ * in the `this.requests` queue.
354
+ * - When an upload completed with an error, the same happens as on successful completion, but the `upload()` promise is
355
+ * rejected.
356
+ *
357
+ * When working on this function, keep in mind:
358
+ * - When an upload is completed or cancelled for any reason, the tus.Upload and EventTracker instances need to be cleaned
359
+ * up using this.resetFilerobotReferences().
360
+ * - When an upload is cancelled or paused, for any reason, it needs to be removed from the `this.requests` queue using
361
+ * `queuedRequest.abort()`.
362
+ * - When an upload is completed for any reason, including errors, it needs to be marked as such using
363
+ * `queuedRequest.done()`.
364
+ * - When an upload is started or resumed, it needs to go through the `this.requests` queue. The `queuedRequest` variable
365
+ * must be updated so the other uses of it are valid.
366
+ * - Before replacing the `queuedRequest` variable, the previous `queuedRequest` must be aborted, else it will keep taking
367
+ * up a spot in the queue.
368
+ *
369
+ * @param {FilerobotFile} file for use with upload
370
+ * @returns {Promise<void>}
371
+ */
372
+ function upload(file, uploadId) {
373
+ var _this2 = this;
374
+ this.resetFilerobotReferences(file.id);
375
+
376
+ // Create a new tus upload
377
+ return new Promise(function (resolve, reject) {
378
+ var queuedRequest;
379
+ var startUploadRequest;
380
+ var upload = {};
381
+ _this2.filerobot.emit('upload-started', file, {
382
+ uploadId: uploadId
383
+ });
384
+ var opts = _objectSpread(_objectSpread({}, _this2.opts), file.tus || {});
385
+ if (typeof opts.headers === 'function') {
386
+ opts.headers = opts.headers(file);
387
+ }
388
+
389
+ /** @type {RawTusOptions} */
390
+ var uploadOptions = _objectSpread(_objectSpread({}, tusDefaultOptions), opts);
391
+
392
+ // We override tus fingerprint to filerobot’s `file.id`, since the `file.id`
393
+ // now also includes `relativePath` for files added from folders.
394
+ // This means you can add 2 identical files, if one is in folder a,
395
+ // the other in folder b.
396
+ uploadOptions.fingerprint = getFingerprint(file);
397
+ uploadOptions.onBeforeRequest = function (req) {
398
+ var xhr = req.getUnderlyingObject();
399
+ xhr.withCredentials = !!opts.withCredentials;
400
+ var userProvidedPromise;
401
+ if (typeof opts.onBeforeRequest === 'function') {
402
+ userProvidedPromise = opts.onBeforeRequest(req, file);
403
+ }
404
+ if (hasProperty(queuedRequest, 'shouldBeRequeued')) {
405
+ if (!queuedRequest.shouldBeRequeued) return Promise.reject(new Error('Nonexistent upload'));
406
+ var done;
407
+ var newPromise = new Promise(function (resolve) {
408
+ done = resolve;
409
+ });
410
+ queuedRequest = _this2.requests.run(function () {
411
+ if (file.progress.status === PROGRESS_PANEL_STATUS.PAUSED) {
412
+ queuedRequest.abort();
413
+ }
414
+ done();
415
+ return function () {};
416
+ });
417
+ // If the request has been requeued because it was rate limited by the
418
+ // remote server, we want to wait for `RateLimitedQueue` to dispatch
419
+ // the re-try request.
420
+ // Therefore we create a promise that the queue will resolve when
421
+ // enough time has elapsed to expect not to be rate-limited again.
422
+ // This means we can hold the Tus retry here with a `Promise.all`,
423
+ // together with the returned value of the user provided
424
+ // `onBeforeRequest` option callback (in case it returns a promise).
425
+ return Promise.all([newPromise, userProvidedPromise]);
426
+ }
427
+ return userProvidedPromise;
428
+ };
429
+ uploadOptions.onError = function (error) {
430
+ var _queuedRequest;
431
+ _this2.filerobot.log(error);
432
+ var xhr = error.originalRequest ? error.originalRequest.getUnderlyingObject() : null;
433
+ if (isNetworkError(xhr)) {
434
+ var networkError = new NetworkError(error, xhr);
435
+ return networkError;
436
+ }
437
+ _this2.resetFilerobotReferences(file.id);
438
+ (_queuedRequest = queuedRequest) === null || _queuedRequest === void 0 ? void 0 : _queuedRequest.abort();
439
+ _this2.filerobot.emit('upload-error', file, error, {
440
+ uploadId: uploadId
441
+ });
442
+ reject(error);
443
+ };
444
+ uploadOptions.onProgress = function (bytesFinished, bytesTotal) {
445
+ _this2.onReceiveUploadUrl(file, uploadId, upload.url);
446
+ _this2.filerobot.emit('upload-progress', file, {
447
+ filerobot: _this2,
448
+ bytesFinished: bytesFinished,
449
+ bytesTotal: bytesTotal,
450
+ uploadId: uploadId
451
+ });
452
+ };
453
+ uploadOptions.onSuccess = function () {
454
+ if (!file.fileJson) {
455
+ _this2.getFileJson({
456
+ uploadUrl: upload.url,
457
+ file: file,
458
+ uploadId: uploadId,
459
+ queuedRequest: queuedRequest,
460
+ resolve: resolve,
461
+ reject: reject
462
+ });
463
+ }
464
+ };
465
+ var defaultOnShouldRetry = function defaultOnShouldRetry(err) {
466
+ var _err$originalResponse;
467
+ var status = err === null || err === void 0 ? void 0 : (_err$originalResponse = err.originalResponse) === null || _err$originalResponse === void 0 ? void 0 : _err$originalResponse.getStatus();
468
+ if (status === 429) {
469
+ // HTTP 429 Too Many Requests => to avoid the whole download to fail, pause all requests.
470
+ if (!_this2.requests.isPaused) {
471
+ var _this2$retryDelayIter;
472
+ var next = (_this2$retryDelayIter = _this2.retryDelayIterator) === null || _this2$retryDelayIter === void 0 ? void 0 : _this2$retryDelayIter.next();
473
+ if (next == null || next.done) {
474
+ return false;
475
+ }
476
+ _this2.requests.rateLimit(next.value);
477
+ }
478
+ } else if (status > 400 && status < 500 && status !== 409) {
479
+ // HTTP 4xx, the server won't send anything, it's doesn't make sense to retry
480
+ return false;
481
+ } else if (typeof navigator !== 'undefined' && navigator.onLine === false) {
482
+ // The navigator is offline, let's wait for it to come back online.
483
+ if (!_this2.requests.isPaused) {
484
+ _this2.requests.pause();
485
+ window.addEventListener('online', function () {
486
+ _this2.requests.resume();
487
+ }, {
488
+ once: true
489
+ });
490
+ }
491
+ }
492
+ queuedRequest.abort();
493
+ queuedRequest = {
494
+ shouldBeRequeued: true,
495
+ abort: function abort() {
496
+ this.shouldBeRequeued = false;
497
+ },
498
+ done: function done() {
499
+ throw new Error('Cannot mark a queued request as done: this indicates a bug');
500
+ },
501
+ fn: function fn() {
502
+ throw new Error('Cannot run a queued request: this indicates a bug');
503
+ }
504
+ };
505
+ return true;
506
+ };
507
+ if (opts.onShouldRetry != null) {
508
+ uploadOptions.onShouldRetry = function () {
509
+ for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
510
+ args[_key] = arguments[_key];
511
+ }
512
+ return opts.onShouldRetry.apply(opts, args.concat([defaultOnShouldRetry]));
513
+ };
514
+ } else {
515
+ uploadOptions.onShouldRetry = defaultOnShouldRetry;
516
+ }
517
+ var copyProp = function copyProp(obj, srcProp, destProp) {
518
+ if (hasProperty(obj, srcProp) && !hasProperty(obj, destProp)) {
519
+ obj[destProp] = obj[srcProp];
520
+ }
521
+ };
522
+
523
+ /** @type {Record<string, string>} */
524
+ var meta = {};
525
+ var allowedMetaFields = Array.isArray(opts.allowedMetaFields) ? opts.allowedMetaFields
526
+ // Send along all fields by default.
527
+ : Object.keys(file.meta);
528
+ allowedMetaFields.forEach(function (item) {
529
+ meta[item] = file.meta[item];
530
+ });
531
+ // tusd uses metadata fields 'filetype' and 'filename'
532
+ copyProp(meta, 'type', 'filetype');
533
+ copyProp(meta, 'name', 'filename');
534
+ uploadOptions.metadata = _objectSpread(_objectSpread({}, file.info), {}, {
535
+ 'filerobot-folder': _this2.filerobot.getRemoteUploadFolder({
536
+ file: file,
537
+ opts: _this2.opts
538
+ })
539
+ });
540
+ upload = new Upload(file.data, uploadOptions);
541
+ _this2.filerobots[file.id] = upload;
542
+ _this2.filerobotEvents[file.id] = new EventTracker(_this2.filerobot);
543
+ // eslint-disable-next-line prefer-const
544
+ startUploadRequest = function startUploadRequest() {
545
+ if (file.progress.status !== PROGRESS_PANEL_STATUS.PAUSED) {
546
+ upload.start();
547
+ }
548
+ // Don't do anything here, the caller will take care of cancelling the upload itself
549
+ // using resetFilerobotReferences(). This is because resetFilerobotReferences() has to be
550
+ // called when this request is still in the queue, and has not been started yet, too. At
551
+ // that point this cancellation function is not going to be called.
552
+ // Also, we need to remove the request from the queue _without_ destroying everything
553
+ // related to this upload to handle pauses.
554
+ return function () {};
555
+ };
556
+ upload.findPreviousUploads().then(function (previousUploads) {
557
+ var previousUpload = previousUploads[0];
558
+ if (previousUpload) {
559
+ _this2.filerobot.log("[Tus] Resuming upload of ".concat(file.id, " started at ").concat(previousUpload.creationTime));
560
+ upload.resumeFromPreviousUpload(previousUpload);
561
+ }
562
+ });
563
+ queuedRequest = _this2.requests.run(startUploadRequest);
564
+ _this2.onFileRemove(file.id, function (targetFileID) {
565
+ queuedRequest.abort();
566
+ _this2.resetFilerobotReferences(file.id, {
567
+ abort: !!upload.url
568
+ });
569
+ resolve("upload ".concat(targetFileID, " was removed"));
570
+ });
571
+ _this2.onPause(file.id, function (isPaused) {
572
+ queuedRequest.abort();
573
+ if (isPaused) {
574
+ // Remove this file from the queue so another file can start in its place.
575
+ upload.abort();
576
+ } else {
577
+ // Resuming an upload should be queued, else you could pause and then
578
+ // resume a queued upload to make it skip the queue.
579
+ queuedRequest = _this2.requests.run(startUploadRequest);
580
+ }
581
+ });
582
+ _this2.onPauseAll(file.id, function () {
583
+ queuedRequest.abort();
584
+ upload.abort();
585
+ });
586
+ _this2.onCancelAll(file.id, function () {
587
+ var _ref3 = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {},
588
+ reason = _ref3.reason;
589
+ if (reason === 'user') {
590
+ queuedRequest.abort();
591
+ _this2.resetFilerobotReferences(file.id, {
592
+ abort: !!upload.url
593
+ });
594
+ }
595
+ resolve("upload ".concat(file.id, " was canceled"));
596
+ });
597
+ _this2.onResumeAll(file.id, function () {
598
+ queuedRequest.abort();
599
+ if (file.error) {
600
+ upload.abort();
601
+ }
602
+ queuedRequest = _this2.requests.run(startUploadRequest);
603
+ });
604
+ })["catch"](function (error) {
605
+ _this2.filerobot.emit('upload-error', file, error, {
606
+ uploadId: uploadId
607
+ });
608
+ throw error;
609
+ });
610
+ }
611
+ }, {
612
+ key: "uploadRemote",
613
+ value:
614
+ // NOTE! Keep this duplicated code in sync with other plugins
615
+ // TODO we should probably abstract this into a common function
616
+ /**
617
+ * @param {FilerobotFile} file for use with upload
618
+ * @returns {Promise<void>}
619
+ */
620
+ async function uploadRemote(file, uploadId) {
621
+ this.resetFilerobotReferences(file.id);
622
+
623
+ // Don't double-emit upload-started for Golden Retriever-restored files that were already started
624
+ if (!file.progress.uploadStarted || !file.isRestored) {
625
+ this.filerobot.emit('upload-started', file, {
626
+ uploadId: uploadId
627
+ });
628
+ }
629
+ try {
630
+ if (file.serverToken) {
631
+ return await this.connectToServerSocket(file, uploadId);
632
+ }
633
+ var serverToken = await this.queueRequestSocketToken(file);
634
+ this.filerobot.setFileUploadingState(file.id, uploadId, {
635
+ serverToken: serverToken
636
+ });
637
+ return await this.connectToServerSocket(this.filerobot.getFileUploading(file.id), uploadId);
638
+ } catch (error) {
639
+ this.filerobot.setFileUploadingState(file.id, uploadId, {
640
+ serverToken: undefined
641
+ });
642
+ this.filerobot.emit('upload-error', file, error, {
643
+ uploadId: uploadId
644
+ });
645
+ throw error;
646
+ }
647
+ }
648
+
649
+ /**
650
+ * See the comment on the upload() method.
651
+ *
652
+ * Additionally, when an upload is removed, completed, or cancelled, we need to close the WebSocket connection. This is
653
+ * handled by the resetFilerobotReferences() function, so the same guidelines apply as in upload().
654
+ *
655
+ * @param {FilerobotFile} file
656
+ */
657
+ }, {
658
+ key: "connectToServerSocket",
659
+ value: async function connectToServerSocket(file, uploadId) {
660
+ var _this3 = this;
661
+ return new Promise(function (resolve, reject) {
662
+ var token = file.serverToken;
663
+ var host = getSocketHost(file.remote.companionUrl);
664
+ var socket = new Socket({
665
+ target: "".concat(host, "/api/").concat(token),
666
+ autoOpen: false
667
+ });
668
+ _this3.filerobotSockets[file.id] = socket;
669
+ _this3.filerobotEvents[file.id] = new EventTracker(_this3.filerobot);
670
+ var queuedRequest;
671
+ _this3.onFileRemove(file.id, function () {
672
+ queuedRequest.abort();
673
+ socket.send('cancel', {});
674
+ _this3.resetFilerobotReferences(file.id);
675
+ resolve("upload ".concat(file.id, " was removed"));
676
+ });
677
+ _this3.onPause(file.id, function (isPaused) {
678
+ if (isPaused) {
679
+ // Remove this file from the queue so another file can start in its place.
680
+ socket.send('pause', {});
681
+ queuedRequest.abort();
682
+ } else {
683
+ // Resuming an upload should be queued, else you could pause and then
684
+ // resume a queued upload to make it skip the queue.
685
+ queuedRequest.abort();
686
+ queuedRequest = _this3.requests.run(function () {
687
+ socket.open();
688
+ socket.send('resume', {});
689
+ return function () {};
690
+ });
691
+ }
692
+ });
693
+ _this3.onPauseAll(file.id, function () {
694
+ socket.send('pause', {});
695
+ queuedRequest.abort();
696
+ });
697
+ _this3.onCancelAll(file.id, function () {
698
+ var _ref4 = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {},
699
+ reason = _ref4.reason;
700
+ if (reason === 'user') {
701
+ queuedRequest.abort();
702
+ socket.send('cancel', {});
703
+ _this3.resetFilerobotReferences(file.id);
704
+ }
705
+ resolve("upload ".concat(file.id, " was canceled"));
706
+ });
707
+ _this3.onResumeAll(file.id, function () {
708
+ queuedRequest.abort();
709
+ if (file.error) {
710
+ socket.send('pause', {});
711
+ }
712
+ queuedRequest = _this3.requests.run(function () {
713
+ socket.open();
714
+ socket.send('resume', {});
715
+ return function () {};
716
+ });
717
+ });
718
+ _this3.onRetry(file.id, function () {
719
+ // Only do the retry if the upload is actually in progress;
720
+ // else we could try to send these messages when the upload is still queued.
721
+ // We may need a better check for this since the socket may also be closed
722
+ // for other reasons, like network failures.
723
+ if (socket.isOpen) {
724
+ socket.send('pause', {});
725
+ socket.send('resume', {});
726
+ }
727
+ });
728
+ _this3.onRetryAll(file.id, function () {
729
+ // See the comment in the onRetry() call
730
+ if (socket.isOpen) {
731
+ socket.send('pause', {});
732
+ socket.send('resume', {});
733
+ }
734
+ });
735
+ socket.on('progress', function (progressData) {
736
+ return emitSocketProgress(_this3, progressData, file);
737
+ });
738
+ socket.on('error', function (errData) {
739
+ var message = errData.error.message;
740
+ var error = _extends(new Error(message), {
741
+ cause: errData.error
742
+ });
743
+
744
+ // If the remote retry optimisation should not be used,
745
+ // close the socket—this will tell companion to clear state and delete the file.
746
+ if (!_this3.opts.useFastRemoteRetry) {
747
+ _this3.resetFilerobotReferences(file.id);
748
+ // Remove the serverToken so that a new one will be created for the retry.
749
+ _this3.filerobot.setFileUploadingState(file.id, uploadId, {
750
+ serverToken: null
751
+ });
752
+ } else {
753
+ socket.close();
754
+ }
755
+ _this3.filerobot.emit('upload-error', file, error, {
756
+ uploadId: uploadId
757
+ });
758
+ queuedRequest.done();
759
+ reject(error);
760
+ });
761
+ socket.on('success', function (data) {
762
+ if (!file.fileJson) {
763
+ _this3.getFileJson({
764
+ uploadUrl: data.url,
765
+ file: file,
766
+ uploadId: uploadId,
767
+ queuedRequest: queuedRequest,
768
+ resolve: resolve
769
+ });
770
+ }
771
+ });
772
+ queuedRequest = _this3.requests.run(function () {
773
+ if (file.progress.status === PROGRESS_PANEL_STATUS.PAUSED) {
774
+ socket.send('pause', {});
775
+ } else {
776
+ socket.open();
777
+ }
778
+
779
+ // Just close the socket here, the caller will take care of cancelling the upload itself
780
+ // using resetFilerobotReferences(). This is because resetFilerobotReferences() has to be
781
+ // called when this request is still in the queue, and has not been started yet, too. At
782
+ // that point this cancellation function is not going to be called.
783
+ // Also, we need to remove the request from the queue _without_ destroying everything
784
+ // related to this upload to handle pauses.
785
+ return function () {};
786
+ });
787
+ });
788
+ }
789
+
790
+ /**
791
+ * Store the uploadUrl on the file options, so that when Golden Retriever
792
+ * restores state, we will continue uploading to the correct URL.
793
+ *
794
+ * @param {FilerobotFile} file
795
+ * @param {string} uploadURL
796
+ */
797
+ }, {
798
+ key: "onReceiveUploadUrl",
799
+ value: function onReceiveUploadUrl(file, uploadId, uploadURL) {
800
+ var currentFile = this.filerobot.getFileUploading(file.id);
801
+ if (!currentFile) return;
802
+ // Only do the update if we didn't have an upload URL yet.
803
+ if (!currentFile.tus || currentFile.tus.uploadUrl !== uploadURL) {
804
+ this.filerobot.log('[Tus] Storing upload url');
805
+ this.filerobot.setFileUploadingState(currentFile.id, uploadId, {
806
+ tus: _objectSpread(_objectSpread({}, currentFile.tus), {}, {
807
+ uploadUrl: uploadURL
808
+ })
809
+ });
810
+ }
811
+ }
812
+
813
+ /**
814
+ * @param {string} fileId
815
+ * @param {function(string): void} cb
816
+ */
817
+ }, {
818
+ key: "onFileRemove",
819
+ value: function onFileRemove(fileId, cb) {
820
+ this.filerobotEvents[fileId].on('file-removed', function (file) {
821
+ if (fileId === file.id) cb(file.id);
822
+ });
823
+ }
824
+
825
+ /**
826
+ * @param {string} fileId
827
+ * @param {function(boolean): void} cb
828
+ */
829
+ }, {
830
+ key: "onPause",
831
+ value: function onPause(fileId, cb) {
832
+ this.filerobotEvents[fileId].on('upload-pause', function (targetFileID, isPaused) {
833
+ if (fileId === targetFileID) {
834
+ cb(isPaused);
835
+ }
836
+ });
837
+ }
838
+
839
+ /**
840
+ * @param {string} fileId
841
+ * @param {function(): void} cb
842
+ */
843
+ }, {
844
+ key: "onRetry",
845
+ value: function onRetry(fileId, cb) {
846
+ this.filerobotEvents[fileId].on('upload-retry', function (targetFileID) {
847
+ if (fileId === targetFileID) {
848
+ cb();
849
+ }
850
+ });
851
+ }
852
+
853
+ /**
854
+ * @param {string} fileId
855
+ * @param {function(): void} cb
856
+ */
857
+ }, {
858
+ key: "onRetryAll",
859
+ value: function onRetryAll(fileId, cb) {
860
+ var _this4 = this;
861
+ this.filerobotEvents[fileId].on('retry-all', function () {
862
+ if (!_this4.filerobot.getFileUploading(fileId)) return;
863
+ cb();
864
+ });
865
+ }
866
+
867
+ /**
868
+ * @param {string} fileId
869
+ * @param {function(): void} cb
870
+ */
871
+ }, {
872
+ key: "onPauseAll",
873
+ value: function onPauseAll(fileId, cb) {
874
+ var _this5 = this;
875
+ this.filerobotEvents[fileId].on('pause-all', function () {
876
+ if (!_this5.filerobot.getFileUploading(fileId)) return;
877
+ cb();
878
+ });
879
+ }
880
+
881
+ /**
882
+ * @param {string} fileId
883
+ * @param {function(): void} cb
884
+ */
885
+ }, {
886
+ key: "onCancelAll",
887
+ value: function onCancelAll(fileId, eventHandler) {
888
+ var _this6 = this;
889
+ this.filerobotEvents[fileId].on('cancel-uploads', function () {
890
+ if (!_this6.filerobot.getFileUploading(fileId)) return;
891
+ eventHandler.apply(void 0, arguments);
892
+ });
893
+ }
894
+
895
+ /**
896
+ * @param {string} fileId
897
+ * @param {function(): void} cb
898
+ */
899
+ }, {
900
+ key: "onResumeAll",
901
+ value: function onResumeAll(fileId, cb) {
902
+ var _this7 = this;
903
+ this.filerobotEvents[fileId].on('resume-all', function () {
904
+ if (!_this7.filerobot.getFileUploading(fileId)) return;
905
+ cb();
906
+ });
907
+ }
908
+
909
+ /**
910
+ * @param {(FilerobotFile | FailedFilerobotFile)[]} files
911
+ */
912
+ }, {
913
+ key: "uploadFiles",
914
+ value: function uploadFiles(files, uploadId) {
915
+ var _this8 = this;
916
+ var promises = files.map(function (file, i) {
917
+ if ('error' in file && file.error) {
918
+ return Promise.reject(new Error(file.error));
919
+ }
920
+ if (file.isRemote) {
921
+ // We emit upload-started here, so that it's also emitted for files
922
+ // that have to wait due to the `limit` option.
923
+ // Don't double-emit upload-started for Golden Retriever-restored files that were already started
924
+ if (!file.progress.uploadStarted || !file.isRestored) {
925
+ _this8.filerobot.emit('upload-started', file, {
926
+ uploadId: uploadId
927
+ });
928
+ }
929
+ return _this8.uploadRemote(file, uploadId);
930
+ }
931
+ // Don't double-emit upload-started for Golden Retriever-restored files that were already started
932
+ if (!file.progress.uploadStarted || !file.isRestored) {
933
+ _this8.filerobot.emit('upload-started', file, {
934
+ uploadId: uploadId
935
+ });
936
+ }
937
+ return _this8.upload(file, uploadId);
938
+ });
939
+ return settle(promises);
940
+ }
941
+
942
+ /**
943
+ * @param {string[]} fileIds
944
+ */
945
+ }, {
946
+ key: "handleUpload",
947
+ value: function handleUpload(fileIds, uploadId) {
948
+ var _this9 = this;
949
+ if (fileIds.length === 0) {
950
+ this.filerobot.log('[Tus] No files to upload');
951
+ return Promise.resolve();
952
+ }
953
+ if (this.opts.limit === 0) {
954
+ this.filerobot.log('[Tus] 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://filerobot.io/docs/tus/#limit-0', 'warning');
955
+ }
956
+ this.filerobot.log('[Tus] Uploading...');
957
+ var filesToUpload = fileIds.map(function (fileId) {
958
+ return _this9.filerobot.getFileUploading(fileId);
959
+ });
960
+ return this.uploadFiles(filesToUpload, uploadId).then(function () {
961
+ return null;
962
+ });
963
+ }
964
+ }, {
965
+ key: "install",
966
+ value: function install() {
967
+ this.filerobot.dispatch(uploadCapabilitiesUpdated({
968
+ allowResumableUploads: true
969
+ }));
970
+ this.filerobot.addFilerobot(this.handleUpload);
971
+ this.filerobot.on('reset-progress', this.handleResetProgress);
972
+ }
973
+ }, {
974
+ key: "uninstall",
975
+ value: function uninstall() {
976
+ this.filerobot.dispatch(uploadCapabilitiesUpdated({
977
+ allowResumableUploads: false
978
+ }));
979
+ this.filerobot.removeFilerobot(this.handleUpload);
980
+ }
981
+ }]);
982
+ }(Plugin);
983
+ export { Tus as default };