@scaleflex/widget-xhr-upload 4.8.6 → 4.8.11

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (3) hide show
  1. package/lib/index.js +797 -0
  2. package/package.json +4 -4
  3. package/CHANGELOG.md +0 -7197
package/lib/index.js ADDED
@@ -0,0 +1,797 @@
1
+ var _excluded = ["isVideoProcessActive"],
2
+ _excluded2 = ["isImageProcessActive"];
3
+ function _objectWithoutProperties(e, t) { if (null == e) return {}; var o, r, i = _objectWithoutPropertiesLoose(e, t); if (Object.getOwnPropertySymbols) { var n = Object.getOwnPropertySymbols(e); for (r = 0; r < n.length; r++) o = n[r], -1 === t.indexOf(o) && {}.propertyIsEnumerable.call(e, o) && (i[o] = e[o]); } return i; }
4
+ function _objectWithoutPropertiesLoose(r, e) { if (null == r) return {}; var t = {}; for (var n in r) if ({}.hasOwnProperty.call(r, n)) { if (-1 !== e.indexOf(n)) continue; t[n] = r[n]; } return t; }
5
+ 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); }
6
+ 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; }
7
+ 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; }
8
+ 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; }
9
+ function _classCallCheck(a, n) { if (!(a instanceof n)) throw new TypeError("Cannot call a class as a function"); }
10
+ 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); } }
11
+ function _createClass(e, r, t) { return r && _defineProperties(e.prototype, r), t && _defineProperties(e, t), Object.defineProperty(e, "prototype", { writable: !1 }), e; }
12
+ function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == _typeof(i) ? i : i + ""; }
13
+ 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); }
14
+ function _callSuper(t, o, e) { return o = _getPrototypeOf(o), _possibleConstructorReturn(t, _isNativeReflectConstruct() ? Reflect.construct(o, e || [], _getPrototypeOf(t).constructor) : o.apply(t, e)); }
15
+ 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); }
16
+ function _assertThisInitialized(e) { if (void 0 === e) throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); return e; }
17
+ function _isNativeReflectConstruct() { try { var t = !Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); } catch (t) {} return (_isNativeReflectConstruct = function _isNativeReflectConstruct() { return !!t; })(); }
18
+ function _superPropGet(t, o, e, r) { var p = _get(_getPrototypeOf(1 & r ? t.prototype : t), o, e); return 2 & r && "function" == typeof p ? function (t) { return p.apply(e, t); } : p; }
19
+ function _get() { return _get = "undefined" != typeof Reflect && Reflect.get ? Reflect.get.bind() : function (e, t, r) { var p = _superPropBase(e, t); if (p) { var n = Object.getOwnPropertyDescriptor(p, t); return n.get ? n.get.call(arguments.length < 3 ? e : r) : n.value; } }, _get.apply(null, arguments); }
20
+ function _superPropBase(t, o) { for (; !{}.hasOwnProperty.call(t, o) && null !== (t = _getPrototypeOf(t));); return t; }
21
+ function _getPrototypeOf(t) { return _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf.bind() : function (t) { return t.__proto__ || Object.getPrototypeOf(t); }, _getPrototypeOf(t); }
22
+ 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); }
23
+ function _setPrototypeOf(t, e) { return _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function (t, e) { return t.__proto__ = e, t; }, _setPrototypeOf(t, e); }
24
+ 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); }
25
+ import { Plugin } from '@scaleflex/widget-core';
26
+ import cuid from 'cuid';
27
+ import Translator from '@scaleflex/widget-utils/lib/Translator';
28
+ import { Provider, RequestClient, Socket } from '@scaleflex/widget-companion-client';
29
+ import emitSocketProgress from '@scaleflex/widget-utils/lib/emitSocketProgress';
30
+ import getSocketHost from '@scaleflex/widget-utils/lib/getSocketHost';
31
+ import settle from '@scaleflex/widget-utils/lib/settle';
32
+ import EventTracker from '@scaleflex/widget-utils/lib/EventTracker';
33
+ import ProgressTimeout from '@scaleflex/widget-utils/lib/ProgressTimeout';
34
+ import RateLimitedQueue from '@scaleflex/widget-utils/lib/RateLimitedQueue';
35
+ import NetworkError from '@scaleflex/widget-utils/lib/NetworkError';
36
+ import isNetworkError from '@scaleflex/widget-utils/lib/isNetworkError';
37
+ import isSupportedVideo from '@scaleflex/widget-utils/lib/isSupportedVideo';
38
+ import isImage from '@scaleflex/widget-utils/lib/isImage';
39
+ import checkConnection from '@scaleflex/widget-utils/lib/checkConnection';
40
+ import { uploadCapabilitiesUpdated } from '@scaleflex/widget-core/lib/slices/uploads.slice';
41
+ import { selectUserSassKey } from '@scaleflex/widget-core/lib/slices/user.slice';
42
+ import { PROGRESS_PANEL_STATUS, PLUGINS_IDS } from '@scaleflex/widget-utils/lib/constants';
43
+ import getJsonParsedValue from '@scaleflex/widget-utils/lib/getJsonParsedValue';
44
+
45
+ // TODO: find a way to show version of the current plugin
46
+ // why solution below isn't good?
47
+ // first import doesn't work with webpack 5 as it was deprecated
48
+ // second import fixes webpack 5 issue as it was mentioned in their docs
49
+ // but it exposes our package.json to the client and it is mentioned as security rist in mutiple places
50
+ // https://github.com/axelpale/genversion
51
+ // https://stackoverflow.com/questions/64993118/error-should-not-import-the-named-export-version-imported-as-version
52
+ // https://stackoverflow.com/questions/9153571/is-there-a-way-to-get-version-from-package-json-in-nodejs-code/10855054#10855054
53
+ // import { version } from '../package.json'
54
+ // import packageInfo from '../package.json'
55
+
56
+ var FIELD_NAME = 'files[]';
57
+ function buildResponseError(xhr, error) {
58
+ // No error message
59
+ if (!error) error = new Error('Upload error');
60
+ // Got an error message string
61
+ if (typeof error === 'string') error = new Error(error);
62
+ // Got something else
63
+ if (!(error instanceof Error)) {
64
+ error = _extends(new Error('Upload error'), {
65
+ data: error
66
+ });
67
+ }
68
+ if (isNetworkError(xhr)) {
69
+ error = new NetworkError(error, xhr);
70
+ return error;
71
+ }
72
+ error.request = xhr;
73
+ return error;
74
+ }
75
+
76
+ /**
77
+ * Set `data.type` in the blob to `file.info.type`,
78
+ * because we might have detected a more accurate file type in Filerobot
79
+ * https://stackoverflow.com/a/50875615
80
+ *
81
+ * @param {object} file File object with `data`, `size` and `info` properties
82
+ * @returns {object} blob updated with the new `type` set from `file.info.type`
83
+ */
84
+ function setTypeInBlob(file) {
85
+ var dataWithUpdatedType = file.data.slice(0, file.data.size, file.info.type);
86
+ return dataWithUpdatedType;
87
+ }
88
+ var XHRUpload = /*#__PURE__*/function (_Plugin) {
89
+ // static VERSION = packageInfo.version
90
+
91
+ function XHRUpload(filerobot) {
92
+ var _this;
93
+ var opts = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
94
+ _classCallCheck(this, XHRUpload);
95
+ _this = _callSuper(this, XHRUpload, [filerobot, opts]);
96
+ _this.type = 'uploader';
97
+ _this.id = _this.opts.id || PLUGINS_IDS.XHR_UPLOAD;
98
+ _this.title = 'XHRUpload';
99
+ _this.defaultLocale = {
100
+ strings: {
101
+ timedOut: 'Upload stalled for %{seconds} seconds, aborting.'
102
+ }
103
+ };
104
+
105
+ // Default options
106
+ var defaultOptions = {
107
+ dev: false,
108
+ uploadQueryParams: '',
109
+ method: 'post',
110
+ responseUrlFieldName: 'url',
111
+ uploadToFolderPath: null,
112
+ bundle: false,
113
+ headers: {},
114
+ timeout: 60 * 1000,
115
+ limit: 0,
116
+ withCredentials: false,
117
+ responseType: '',
118
+ info: undefined,
119
+ addInfoCallback: undefined,
120
+ meta: undefined,
121
+ skipUpload: false,
122
+ /**
123
+ * @typedef respObj
124
+ * @property {string} responseText
125
+ * @property {number} status
126
+ * @property {string} statusText
127
+ * @property {object.<string, string>} headers
128
+ *
129
+ * @param {string} responseText the response body string
130
+ * @param {XMLHttpRequest | respObj} response the response object (XHR or similar)
131
+ */
132
+ getResponseData: function getResponseData(responseText, response) {
133
+ var parsedResponse = {};
134
+ try {
135
+ parsedResponse = JSON.parse(responseText);
136
+ } catch (err) {
137
+ console.log(err);
138
+ }
139
+ return parsedResponse;
140
+ },
141
+ /**
142
+ *
143
+ * @param {string} responseText the response body string
144
+ * @param {XMLHttpRequest | respObj} response the response object (XHR or similar)
145
+ */
146
+ getResponseError: function getResponseError(responseText, response) {
147
+ var error = new Error('Upload error');
148
+ if (isNetworkError(response)) {
149
+ error = new NetworkError(error, response);
150
+ }
151
+ if (responseText) {
152
+ var jsonedResponse = JSON.parse(responseText);
153
+ if (jsonedResponse.hint || jsonedResponse.msg) {
154
+ error = new Error(jsonedResponse.hint || jsonedResponse.msg);
155
+ }
156
+ }
157
+ return error;
158
+ },
159
+ /**
160
+ * Check if the response from the upload endpoint indicates that the upload was successful.
161
+ *
162
+ * @param {number} status the response status code
163
+ * @param {string} responseText the response body string
164
+ * @param {XMLHttpRequest | respObj} response the response object (XHR or similar)
165
+ */
166
+ validateStatus: function validateStatus(status, responseText, response) {
167
+ return status >= 200 && status < 300;
168
+ }
169
+ };
170
+ _this.opts = _objectSpread(_objectSpread({}, defaultOptions), opts);
171
+ _this.opts.endpoint = _this.getUploadEndpoint();
172
+ _this.opts.headers['X-Filerobot-Key'] = selectUserSassKey(_this.getGlobalState()) || filerobot.opts.sassKey;
173
+ if (!_this.opts.headers['X-Filerobot-Key']) {
174
+ filerobot.on('sass-key-obtained', function (sassKey) {
175
+ _this.opts.headers['X-Filerobot-Key'] = sassKey;
176
+ });
177
+ }
178
+ _this.i18nInit();
179
+ _this.handleUpload = _this.handleUpload.bind(_this);
180
+
181
+ // Simultaneous upload limiting is shared across all uploads with this plugin.
182
+ // __queue is for internal Filerobot use only!
183
+ if (_this.opts.__queue instanceof RateLimitedQueue) {
184
+ _this.requests = _this.opts.__queue;
185
+ } else {
186
+ _this.requests = new RateLimitedQueue(_this.opts.limit);
187
+ }
188
+ _this.filerobotEvents = Object.create(null);
189
+ return _this;
190
+ }
191
+ _inherits(XHRUpload, _Plugin);
192
+ return _createClass(XHRUpload, [{
193
+ key: "setOptions",
194
+ value: function setOptions(newOpts) {
195
+ _superPropGet(XHRUpload, "setOptions", this, 3)([newOpts]);
196
+ this.i18nInit();
197
+ }
198
+ }, {
199
+ key: "getUploadEndpoint",
200
+ value: function getUploadEndpoint() {
201
+ return "".concat(this.filerobot.opts.apiEndpointWithContainer, "/v4/files");
202
+ }
203
+ }, {
204
+ key: "i18nInit",
205
+ value: function i18nInit() {
206
+ this.translator = new Translator([this.defaultLocale, this.filerobot.locale, this.opts.locale]);
207
+ this.i18n = this.translator.translate.bind(this.translator);
208
+ }
209
+ }, {
210
+ key: "getOptions",
211
+ value: function getOptions(file) {
212
+ var overrides = this.filerobot.getCoreCommonState().xhrUpload;
213
+ var opts = _objectSpread(_objectSpread(_objectSpread(_objectSpread({}, this.opts), overrides || {}), file.xhrUpload || {}), {}, {
214
+ headers: {}
215
+ });
216
+ _extends(opts.headers, this.opts.headers);
217
+ if (overrides) {
218
+ _extends(opts.headers, overrides.headers);
219
+ }
220
+ if (file.xhrUpload) {
221
+ _extends(opts.headers, file.xhrUpload.headers);
222
+ }
223
+ return opts;
224
+ }
225
+ }, {
226
+ key: "getRelativeFileName",
227
+ value: function getRelativeFileName(file) {
228
+ var _file$data;
229
+ return typeof ((_file$data = file.data) === null || _file$data === void 0 ? void 0 : _file$data.relativePath) === 'string' ? file.data.relativePath.substr(1).replaceAll('/', '|') : '';
230
+ }
231
+ }, {
232
+ key: "createFormDataUpload",
233
+ value: function createFormDataUpload(file, opts) {
234
+ var formPost = new FormData();
235
+ if (file.meta && Object.keys(file.meta).length > 0 || opts.meta && Object.keys(opts.meta).length > 0) {
236
+ formPost.append("meta[".concat(FIELD_NAME, "]"), JSON.stringify(_objectSpread(_objectSpread({}, file.meta), opts.meta)));
237
+ }
238
+ if (file.info && Object.keys(file.info).length > 0 || opts.info && Object.keys(opts.info).length > 0 || typeof this.opts.addInfoCallback === 'function') {
239
+ var _this$opts$addInfoCal, _this$opts;
240
+ var infoFromCbFn = (_this$opts$addInfoCal = (_this$opts = this.opts).addInfoCallback) === null || _this$opts$addInfoCal === void 0 ? void 0 : _this$opts$addInfoCal.call(_this$opts, file);
241
+ formPost.append("info[".concat(FIELD_NAME, "]"), JSON.stringify(_objectSpread(_objectSpread(_objectSpread({}, file.info), opts.info), _typeof(infoFromCbFn) === 'object' ? infoFromCbFn : {})));
242
+ }
243
+ if (file.tags && Object.keys(file.tags).length > 0 || opts.tags && Object.keys(opts.tags).length > 0) {
244
+ var tagLang = Object.keys(file.tags)[0];
245
+ formPost.append("tags[".concat(FIELD_NAME, "]"), JSON.stringify({
246
+ // ...file.tags,
247
+ // ...opts.tags
248
+ lang: tagLang,
249
+ new_tags: file.tags[tagLang].map(function (_ref) {
250
+ var sid = _ref.sid,
251
+ label = _ref.label;
252
+ return sid || label;
253
+ })
254
+ }));
255
+ }
256
+ if (file.product && Object.keys(file.product).length > 0 || opts.product && Object.keys(opts.product).length > 0) {
257
+ formPost.append("product[".concat(FIELD_NAME, "]"), JSON.stringify(_objectSpread(_objectSpread({}, file.product), opts.product)));
258
+ }
259
+ var dataWithUpdatedType = setTypeInBlob(file);
260
+ var fileName = file.name || this.getRelativeFileName(file);
261
+ if (fileName) {
262
+ formPost.append(FIELD_NAME, dataWithUpdatedType, fileName);
263
+ } else {
264
+ formPost.append(FIELD_NAME, dataWithUpdatedType);
265
+ }
266
+ return formPost;
267
+ }
268
+ }, {
269
+ key: "createBundledUpload",
270
+ value: function createBundledUpload(files, opts) {
271
+ var _this2 = this;
272
+ var formPost = new FormData();
273
+ files.forEach(function (file) {
274
+ var dataWithUpdatedType = setTypeInBlob(file);
275
+ var fileName = file.name || _this2.getRelativeFileName(file);
276
+ if (fileName) {
277
+ formPost.append(FIELD_NAME, dataWithUpdatedType, fileName);
278
+ } else {
279
+ formPost.append(FIELD_NAME, dataWithUpdatedType);
280
+ }
281
+ });
282
+ return formPost;
283
+ }
284
+ }, {
285
+ key: "upload",
286
+ value: function upload(_ref2) {
287
+ var _this3 = this;
288
+ var file = _ref2.file,
289
+ uploadId = _ref2.uploadId,
290
+ current = _ref2.current,
291
+ total = _ref2.total;
292
+ var opts = this.getOptions(file);
293
+ this.filerobot.log("uploading ".concat(current, " of ").concat(total));
294
+ return new Promise(function (resolve, reject) {
295
+ var _videoTranscoding$fil, _imageProcessor$files, _file$toFolder, _opts$uploadToFolderP;
296
+ _this3.filerobot.emit('upload-started', file, {
297
+ uploadId: uploadId
298
+ });
299
+ var data = file.uploadUrl ? JSON.stringify({
300
+ files_urls: [{
301
+ url: file.uploadUrl,
302
+ name: file.name
303
+ }]
304
+ }) : _this3.createFormDataUpload(file, opts);
305
+ var xhr = new XMLHttpRequest();
306
+ _this3.filerobotEvents[file.id] = new EventTracker(_this3.filerobot);
307
+ var timer = new ProgressTimeout(opts.timeout, function () {
308
+ xhr.abort();
309
+ queuedRequest.done();
310
+ var error = new Error(_this3.i18n('timedOut', {
311
+ seconds: Math.ceil(opts.timeout / 1000)
312
+ }));
313
+ _this3.filerobot.emit('upload-error', file, error, {
314
+ uploadId: uploadId
315
+ });
316
+ reject(error);
317
+ });
318
+ var id = cuid();
319
+ xhr.upload.addEventListener('loadstart', function (ev) {
320
+ _this3.filerobot.log("[XHRUpload] ".concat(id, " started"));
321
+ });
322
+ xhr.upload.addEventListener('progress', function (ev) {
323
+ _this3.filerobot.log("[XHRUpload] ".concat(id, " progress: ").concat(ev.loaded, " / ").concat(ev.total));
324
+ // Begin checking for timeouts when progress starts, instead of loading,
325
+ // to avoid timing out requests on browser concurrency queue
326
+ timer.progress();
327
+ var isOnline = checkConnection();
328
+ if (!isOnline) {
329
+ xhr.abort();
330
+ queuedRequest.done();
331
+ var error = new Error(_this3.i18n('filerobotNoInternetConnectionInfo'));
332
+ _this3.filerobot.emit('upload-error', file, error, {
333
+ uploadId: uploadId
334
+ });
335
+ reject(error);
336
+ }
337
+ if (ev.lengthComputable) {
338
+ _this3.filerobot.emit('upload-progress', file, {
339
+ filerobot: _this3,
340
+ bytesFinished: ev.loaded,
341
+ bytesTotal: ev.total,
342
+ uploadId: uploadId
343
+ });
344
+ }
345
+ });
346
+ xhr.addEventListener('load', function (ev) {
347
+ _this3.filerobot.log("[XHRUpload] ".concat(id, " finished"));
348
+ timer.done();
349
+ queuedRequest.done();
350
+ if (_this3.filerobotEvents[file.id]) {
351
+ _this3.filerobotEvents[file.id].remove();
352
+ _this3.filerobotEvents[file.id] = null;
353
+ }
354
+ if (opts.validateStatus(ev.target.status, xhr.responseText, xhr)) {
355
+ var body = opts.getResponseData(xhr.responseText, xhr);
356
+ var uploadURL = body[opts.responseUrlFieldName];
357
+ var uploadResp = {
358
+ status: ev.target.status,
359
+ body: body,
360
+ uploadURL: uploadURL
361
+ };
362
+ _this3.filerobot.emit('upload-success', _objectSpread(_objectSpread({}, file), uploadResp.body.file), uploadResp, {
363
+ uploadId: uploadId
364
+ });
365
+ if (uploadURL) {
366
+ _this3.filerobot.log("Download ".concat(file.name, " from ").concat(uploadURL));
367
+ }
368
+ return resolve(file);
369
+ } else {
370
+ var _body = opts.getResponseData(xhr.responseText, xhr);
371
+ var error = buildResponseError(xhr, opts.getResponseError(xhr.responseText, xhr));
372
+ var response = {
373
+ status: ev.target.status,
374
+ body: _body
375
+ };
376
+ _this3.filerobot.emit('upload-error', file, error, {
377
+ response: response,
378
+ uploadId: uploadId
379
+ });
380
+ return reject(error);
381
+ }
382
+ });
383
+ xhr.addEventListener('error', function (ev) {
384
+ _this3.filerobot.log("[XHRUpload] ".concat(id, " errored"));
385
+ timer.done();
386
+ queuedRequest.done();
387
+ if (_this3.filerobotEvents[file.id]) {
388
+ _this3.filerobotEvents[file.id].remove();
389
+ _this3.filerobotEvents[file.id] = null;
390
+ }
391
+ var error = buildResponseError(xhr, opts.getResponseError(xhr.responseText, xhr));
392
+ _this3.filerobot.emit('upload-error', file, error, {
393
+ uploadId: uploadId
394
+ });
395
+ return reject(error);
396
+ });
397
+ var _this3$filerobot$getC = _this3.filerobot.getCoreCommonState(),
398
+ _this3$filerobot$getC2 = _this3$filerobot$getC.dndTargetFolderPath,
399
+ dndTargetFolderPath = _this3$filerobot$getC2 === void 0 ? '/' : _this3$filerobot$getC2,
400
+ _this3$filerobot$getC3 = _this3$filerobot$getC.videoTranscoding,
401
+ _this3$filerobot$getC4 = _this3$filerobot$getC3 === void 0 ? {} : _this3$filerobot$getC3,
402
+ _this3$filerobot$getC5 = _this3$filerobot$getC4.isVideoProcessActive,
403
+ isVideoProcessActive = _this3$filerobot$getC5 === void 0 ? false : _this3$filerobot$getC5,
404
+ videoTranscoding = _objectWithoutProperties(_this3$filerobot$getC4, _excluded),
405
+ _this3$filerobot$getC6 = _this3$filerobot$getC.imageProcessor,
406
+ _this3$filerobot$getC7 = _this3$filerobot$getC6 === void 0 ? {} : _this3$filerobot$getC6,
407
+ _this3$filerobot$getC8 = _this3$filerobot$getC7.isImageProcessActive,
408
+ isImageProcessActive = _this3$filerobot$getC8 === void 0 ? false : _this3$filerobot$getC8,
409
+ imageProcessor = _objectWithoutProperties(_this3$filerobot$getC7, _excluded2),
410
+ _this3$filerobot$getC9 = _this3$filerobot$getC.fromDragging,
411
+ fromDragging = _this3$filerobot$getC9 === void 0 ? false : _this3$filerobot$getC9,
412
+ _this3$filerobot$getC10 = _this3$filerobot$getC.isQuickUploader,
413
+ isQuickUploader = _this3$filerobot$getC10 === void 0 ? false : _this3$filerobot$getC10;
414
+ var preprocessorParamsIfFound = '';
415
+ var allowVideoProcesses = isSupportedVideo(file) && isVideoProcessActive && ((_videoTranscoding$fil = videoTranscoding.filesIds) === null || _videoTranscoding$fil === void 0 ? void 0 : _videoTranscoding$fil.includes(file.id));
416
+ var allowImageProcesses = isImage(file) && isImageProcessActive && ((_imageProcessor$files = imageProcessor.filesIds) === null || _imageProcessor$files === void 0 ? void 0 : _imageProcessor$files.includes(file.id));
417
+ if (allowVideoProcesses) {
418
+ preprocessorParamsIfFound = "&postprocess=transcode&video-resolution=".concat(videoTranscoding.resolution, "&video_protocols=").concat(videoTranscoding.protocol);
419
+ } else if (allowImageProcesses) {
420
+ preprocessorParamsIfFound = "&resize=".concat(imageProcessor.values.width, ",").concat(imageProcessor.values.height);
421
+ }
422
+ var fileXhrQueryParams = Object.keys(file.xhrQueryParams || {});
423
+ var fileQueryParams = fileXhrQueryParams.map(function (key) {
424
+ return "".concat(key, "=").concat(file.xhrQueryParams[key]);
425
+ }).join('&');
426
+ var folder = opts.uploadQueryParams.search('(^|&)folder=') > -1 ? '' : "?folder=".concat(encodeURIComponent((_file$toFolder = file.toFolder) !== null && _file$toFolder !== void 0 ? _file$toFolder : ((_opts$uploadToFolderP = opts.uploadToFolderPath) !== null && _opts$uploadToFolderP !== void 0 ? _opts$uploadToFolderP : fromDragging) ? dndTargetFolderPath : '/'));
427
+ var finalEndpoint = "".concat(opts.endpoint).concat(folder).concat(opts.uploadQueryParams ? "".concat(folder ? '&' : '?').concat(opts.uploadQueryParams) : '').concat(isQuickUploader ? '&upload_mode=quick' : '').concat(preprocessorParamsIfFound).concat(fileQueryParams ? "&".concat(fileQueryParams) : '');
428
+ xhr.open(opts.method.toUpperCase(), finalEndpoint, true);
429
+ // IE10 does not allow setting `withCredentials` and `responseType`
430
+ // before `open()` is called.
431
+ xhr.withCredentials = opts.withCredentials;
432
+ if (opts.responseType !== '') {
433
+ xhr.responseType = opts.responseType;
434
+ }
435
+ var headers = _objectSpread(_objectSpread({}, opts.headers), file.xhrHeaders);
436
+ Object.keys(headers).forEach(function (header) {
437
+ xhr.setRequestHeader(header, headers[header]);
438
+ });
439
+ var queuedRequest = _this3.requests.run(function () {
440
+ xhr.send(data);
441
+ return function () {
442
+ timer.done();
443
+ xhr.abort();
444
+ };
445
+ });
446
+ _this3.onFileRemove(file.id, function () {
447
+ queuedRequest.abort();
448
+ reject(new Error('File removed'));
449
+ });
450
+ _this3.onCancelAll(file.id, function () {
451
+ queuedRequest.abort();
452
+ reject(new Error('Upload cancelled'));
453
+ });
454
+ });
455
+ }
456
+ }, {
457
+ key: "uploadRemote",
458
+ value: function uploadRemote(_ref3) {
459
+ var _this4 = this;
460
+ var file = _ref3.file,
461
+ uploadId = _ref3.uploadId;
462
+ var opts = this.getOptions(file);
463
+ return new Promise(function (resolve, reject) {
464
+ var _this4$opts$addInfoCa, _this4$opts;
465
+ var _this4$filerobot$getC = _this4.filerobot.getCoreCommonState(),
466
+ _this4$filerobot$getC2 = _this4$filerobot$getC.videoTranscoding,
467
+ _this4$filerobot$getC3 = _this4$filerobot$getC2 === void 0 ? {} : _this4$filerobot$getC2,
468
+ isVideoProcessActive = _this4$filerobot$getC3.isVideoProcessActive,
469
+ videoFilesIds = _this4$filerobot$getC3.filesIds,
470
+ resolution = _this4$filerobot$getC3.resolution,
471
+ protocol = _this4$filerobot$getC3.protocol,
472
+ _this4$filerobot$getC4 = _this4$filerobot$getC.imageProcessor,
473
+ _this4$filerobot$getC5 = _this4$filerobot$getC4 === void 0 ? {} : _this4$filerobot$getC4,
474
+ isImageProcessActive = _this4$filerobot$getC5.isImageProcessActive,
475
+ filesIds = _this4$filerobot$getC5.filesIds,
476
+ values = _this4$filerobot$getC5.values;
477
+ var allowImageProcesses = isImage(file) && isImageProcessActive && (filesIds === null || filesIds === void 0 ? void 0 : filesIds.includes(file.id));
478
+ var allowVideoProcesses = isSupportedVideo(file) && isVideoProcessActive && (videoFilesIds === null || videoFilesIds === void 0 ? void 0 : videoFilesIds.includes(file.id));
479
+ _this4.filerobot.emit('upload-started', file, {
480
+ uploadId: uploadId
481
+ });
482
+ var folderPath = _this4.filerobot.getRemoteUploadFolder({
483
+ file: file,
484
+ opts: opts
485
+ });
486
+ var restUploadQueryParams = opts.uploadQueryParams.split('&').filter(function (item) {
487
+ return !/^folder=/.test(item);
488
+ }).join('&');
489
+ var infoFromCbFn = (_this4$opts$addInfoCa = (_this4$opts = _this4.opts).addInfoCallback) === null || _this4$opts$addInfoCa === void 0 ? void 0 : _this4$opts$addInfoCa.call(_this4$opts, file);
490
+ var fields = _objectSpread(_objectSpread(_objectSpread(_objectSpread({}, file.info), _this4.opts.info), _typeof(infoFromCbFn) === 'object' ? infoFromCbFn : {}), {}, {
491
+ meta: JSON.stringify(file.meta || {}),
492
+ name: file.name,
493
+ 'filerobot-folder': folderPath
494
+ });
495
+ if (allowVideoProcesses) {
496
+ fields['video-resolution'] = resolution;
497
+ fields['video-protocols'] = protocol;
498
+ } else if (allowImageProcesses) {
499
+ fields.resize = "".concat(values.width, ",").concat(values.height);
500
+ }
501
+ var Client = file.remote.providerOptions.provider ? Provider : RequestClient;
502
+ var client = new Client(_this4.filerobot, file.remote.providerOptions);
503
+ client.post(file.remote.url, _objectSpread(_objectSpread({}, file.remote.body), {}, {
504
+ endpoint: "".concat(opts.endpoint, "?folder=").concat(encodeURIComponent(folderPath)).concat(restUploadQueryParams ? "&".concat(restUploadQueryParams) : ''),
505
+ size: file.data.size,
506
+ fieldname: FIELD_NAME,
507
+ metadata: fields,
508
+ httpMethod: opts.method,
509
+ useFormData: true,
510
+ headers: opts.headers
511
+ })).then(function (res) {
512
+ var token = res.token;
513
+ var host = getSocketHost(file.remote.companionUrl);
514
+ var socket = new Socket({
515
+ target: "".concat(host, "/api/").concat(token),
516
+ autoOpen: false
517
+ });
518
+ _this4.filerobotEvents[file.id] = new EventTracker(_this4.filerobot);
519
+ _this4.onFileRemove(file.id, function () {
520
+ socket.send('cancel', {});
521
+ queuedRequest.abort();
522
+ resolve("upload ".concat(file.id, " was removed"));
523
+ });
524
+ _this4.onCancelAll(file.id, function () {
525
+ socket.send('cancel', {});
526
+ queuedRequest.abort();
527
+ resolve("upload ".concat(file.id, " was canceled"));
528
+ });
529
+ _this4.onRetry(file.id, function () {
530
+ socket.send('pause', {});
531
+ socket.send('resume', {});
532
+ });
533
+ _this4.onRetryAll(file.id, function () {
534
+ socket.send('pause', {});
535
+ socket.send('resume', {});
536
+ });
537
+ socket.on('progress', function (progressData) {
538
+ return emitSocketProgress(_this4, progressData, file);
539
+ });
540
+ socket.on('success', function (data) {
541
+ var body = opts.getResponseData(data.response.responseText, data.response);
542
+ var uploadURL = body[opts.responseUrlFieldName];
543
+ var uploadResp = {
544
+ status: data.response.status,
545
+ body: body,
546
+ uploadURL: uploadURL
547
+ };
548
+ _this4.filerobot.emit('upload-success', _objectSpread(_objectSpread({}, file), uploadResp.body.file), uploadResp, {
549
+ uploadId: uploadId
550
+ });
551
+ queuedRequest.done();
552
+ if (_this4.filerobotEvents[file.id]) {
553
+ _this4.filerobotEvents[file.id].remove();
554
+ _this4.filerobotEvents[file.id] = null;
555
+ }
556
+ return resolve();
557
+ });
558
+ socket.on('error', function (errData) {
559
+ var _errData$error, _errData$error$extraD;
560
+ var resp = errData.response;
561
+ var errIfNoResp = !resp ? getJsonParsedValue((_errData$error = errData.error) === null || _errData$error === void 0 ? void 0 : (_errData$error$extraD = _errData$error.extraData) === null || _errData$error$extraD === void 0 ? void 0 : _errData$error$extraD.responseText) : null;
562
+ var error = resp ? opts.getResponseError(resp.responseText, resp) : _extends(new Error((errIfNoResp === null || errIfNoResp === void 0 ? void 0 : errIfNoResp.hint) || errData.error.message), {
563
+ cause: (errIfNoResp === null || errIfNoResp === void 0 ? void 0 : errIfNoResp.msg) || errData.error
564
+ });
565
+ _this4.filerobot.emit('upload-error', file, error, {
566
+ uploadId: uploadId
567
+ });
568
+ queuedRequest.done();
569
+ if (_this4.filerobotEvents[file.id]) {
570
+ _this4.filerobotEvents[file.id].remove();
571
+ _this4.filerobotEvents[file.id] = null;
572
+ }
573
+ reject(error);
574
+ });
575
+ var queuedRequest = _this4.requests.run(function () {
576
+ socket.open();
577
+ if (file.progress.status === PROGRESS_PANEL_STATUS.PAUSED) {
578
+ socket.send('pause', {});
579
+ }
580
+ return function () {
581
+ return socket.close();
582
+ };
583
+ });
584
+ })["catch"](function (err) {
585
+ _this4.filerobot.emit('upload-error', file, err, {
586
+ uploadId: uploadId
587
+ });
588
+ reject(err);
589
+ });
590
+ });
591
+ }
592
+ }, {
593
+ key: "uploadBundle",
594
+ value: function uploadBundle(files, uploadId) {
595
+ var _this5 = this;
596
+ return new Promise(function (resolve, reject) {
597
+ var endpoint = _this5.opts.endpoint;
598
+ var method = _this5.opts.method;
599
+ var optsFromState = _this5.filerobot.getCoreCommonState().xhrUpload;
600
+ var formData = _this5.createBundledUpload(files, _objectSpread(_objectSpread({}, _this5.opts), optsFromState || {}));
601
+ var xhr = new XMLHttpRequest();
602
+ var timer = new ProgressTimeout(_this5.opts.timeout, function () {
603
+ xhr.abort();
604
+ var error = new Error(_this5.i18n('timedOut', {
605
+ seconds: Math.ceil(_this5.opts.timeout / 1000)
606
+ }));
607
+ emitError(error);
608
+ reject(error);
609
+ });
610
+ var emitError = function emitError(error) {
611
+ files.forEach(function (file) {
612
+ _this5.filerobot.emit('upload-error', file, error, {
613
+ uploadId: uploadId
614
+ });
615
+ });
616
+ };
617
+ xhr.upload.addEventListener('loadstart', function (ev) {
618
+ _this5.filerobot.log('[XHRUpload] started uploading bundle');
619
+ timer.progress();
620
+ });
621
+ xhr.upload.addEventListener('progress', function (ev) {
622
+ timer.progress();
623
+ if (!ev.lengthComputable) return;
624
+ files.forEach(function (file) {
625
+ _this5.filerobot.emit('upload-progress', file, {
626
+ filerobot: _this5,
627
+ bytesFinished: ev.loaded / ev.total * file.size,
628
+ bytesTotal: file.size,
629
+ uploadId: uploadId
630
+ });
631
+ });
632
+ });
633
+ xhr.addEventListener('load', function (ev) {
634
+ timer.done();
635
+ if (_this5.opts.validateStatus(ev.target.status, xhr.responseText, xhr)) {
636
+ var body = _this5.opts.getResponseData(xhr.responseText, xhr);
637
+ var uploadResp = {
638
+ status: ev.target.status,
639
+ body: body
640
+ };
641
+ files.forEach(function (file) {
642
+ _this5.filerobot.emit('upload-success', _objectSpread(_objectSpread({}, file), uploadResp.body.file), uploadResp, {
643
+ uploadId: uploadId
644
+ });
645
+ });
646
+ return resolve();
647
+ }
648
+ var error = _this5.opts.getResponseError(xhr.responseText, xhr) || new Error('Upload error');
649
+ error.request = xhr;
650
+ emitError(error);
651
+ return reject(error);
652
+ });
653
+ xhr.addEventListener('error', function (ev) {
654
+ timer.done();
655
+ var error = _this5.opts.getResponseError(xhr.responseText, xhr) || new Error('Upload error');
656
+ emitError(error);
657
+ return reject(error);
658
+ });
659
+ _this5.filerobot.on('cancel-uploads', function () {
660
+ timer.done();
661
+ xhr.abort();
662
+ });
663
+ xhr.open(method.toUpperCase(), endpoint, true);
664
+ // IE10 does not allow setting `withCredentials` and `responseType`
665
+ // before `open()` is called.
666
+ xhr.withCredentials = _this5.opts.withCredentials;
667
+ if (_this5.opts.responseType !== '') {
668
+ xhr.responseType = _this5.opts.responseType;
669
+ }
670
+ Object.keys(_this5.opts.headers).forEach(function (header) {
671
+ xhr.setRequestHeader(header, _this5.opts.headers[header]);
672
+ });
673
+ xhr.send(formData);
674
+ files.forEach(function (file) {
675
+ _this5.filerobot.emit('upload-started', file, {
676
+ uploadId: uploadId
677
+ });
678
+ });
679
+ });
680
+ }
681
+ }, {
682
+ key: "uploadFiles",
683
+ value: function uploadFiles(files, uploadId) {
684
+ var _this6 = this;
685
+ var total = files.length;
686
+ var promises = files.map(function (file, i) {
687
+ var current = parseInt(i, 10) + 1;
688
+ if (file.error) {
689
+ return Promise.reject(new Error(file.error));
690
+ } else if (file.isRemote) {
691
+ return _this6.uploadRemote({
692
+ file: file,
693
+ uploadId: uploadId
694
+ });
695
+ } else {
696
+ return _this6.upload({
697
+ file: file,
698
+ uploadId: uploadId,
699
+ current: current,
700
+ total: total
701
+ });
702
+ }
703
+ });
704
+ return settle(promises);
705
+ }
706
+ }, {
707
+ key: "onFileRemove",
708
+ value: function onFileRemove(fileId, cb) {
709
+ this.filerobotEvents[fileId].on('file-removed', function (file) {
710
+ if (fileId === file.id) cb(file.id);
711
+ });
712
+ }
713
+ }, {
714
+ key: "onRetry",
715
+ value: function onRetry(fileId, cb) {
716
+ this.filerobotEvents[fileId].on('upload-retry', function (targetFileID) {
717
+ if (fileId === targetFileID) {
718
+ cb();
719
+ }
720
+ });
721
+ }
722
+ }, {
723
+ key: "onRetryAll",
724
+ value: function onRetryAll(fileId, cb) {
725
+ var _this7 = this;
726
+ this.filerobotEvents[fileId].on('retry-all', function (filesToRetry) {
727
+ if (!_this7.filerobot.getFileUploading(fileId)) return;
728
+ cb();
729
+ });
730
+ }
731
+ }, {
732
+ key: "onCancelAll",
733
+ value: function onCancelAll(fileId, cb) {
734
+ var _this8 = this;
735
+ this.filerobotEvents[fileId].on('cancel-uploads', function () {
736
+ if (!_this8.filerobot.getFileUploading(fileId)) return;
737
+ cb();
738
+ });
739
+ }
740
+ }, {
741
+ key: "handleUpload",
742
+ value: function handleUpload(fileIds, uploadId) {
743
+ var _this9 = this;
744
+ if (fileIds.length === 0) {
745
+ this.filerobot.log('[XHRUpload] No files to upload!');
746
+ return Promise.resolve();
747
+ }
748
+ if (this.opts.skipUpload) {
749
+ // Duplicated logic from Hub to support FRA-6565
750
+ return Promise.resolve();
751
+ }
752
+
753
+ // no limit configured by the user, and no RateLimitedQueue passed in by a "parent" plugin (basically just AwsS3) using the top secret `__queue` option
754
+ if (this.opts.limit === 0 && !this.opts.__queue) {
755
+ this.filerobot.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.', 'warning');
756
+ }
757
+ this.filerobot.log('[XHRUpload] Uploading...');
758
+ var files = fileIds.map(function (fileId) {
759
+ return _this9.filerobot.getFileUploading(fileId);
760
+ });
761
+ if (this.opts.bundle) {
762
+ // if bundle: true, we don’t support remote uploads
763
+ var isSomeFileRemote = files.some(function (file) {
764
+ return file.isRemote;
765
+ });
766
+ if (isSomeFileRemote) {
767
+ throw new Error('Can’t upload remote files when bundle: true option is set');
768
+ }
769
+ return this.uploadBundle(files, uploadId);
770
+ }
771
+ return this.uploadFiles(files, uploadId).then(function () {
772
+ return null;
773
+ });
774
+ }
775
+ }, {
776
+ key: "install",
777
+ value: function install() {
778
+ if (this.opts.bundle) {
779
+ this.dispatch(uploadCapabilitiesUpdated({
780
+ allowIndividualCancellation: false
781
+ }));
782
+ }
783
+ this.filerobot.addFilerobot(this.handleUpload);
784
+ }
785
+ }, {
786
+ key: "uninstall",
787
+ value: function uninstall() {
788
+ if (this.opts.bundle) {
789
+ this.dispatch(uploadCapabilitiesUpdated({
790
+ allowIndividualCancellation: true
791
+ }));
792
+ }
793
+ this.filerobot.removeFilerobot(this.handleUpload);
794
+ }
795
+ }]);
796
+ }(Plugin);
797
+ export { XHRUpload as default };