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); }
function asyncGeneratorStep(n, t, e, r, o, a, c) { try { var i = n[a](c), u = i.value; } catch (n) { return void e(n); } i.done ? t(u) : Promise.resolve(u).then(r, o); }
function _asyncToGenerator(n) { return function () { var t = this, e = arguments; return new Promise(function (r, o) { var a = n.apply(t, e); function _next(n) { asyncGeneratorStep(a, r, o, _next, _throw, "next", n); } function _throw(n) { asyncGeneratorStep(a, r, o, _next, _throw, "throw", n); } _next(void 0); }); }; }
function _regeneratorRuntime() { "use strict"; var r = _regenerator(), e = r.m(_regeneratorRuntime), t = (Object.getPrototypeOf ? Object.getPrototypeOf(e) : e.__proto__).constructor; function n(r) { var e = "function" == typeof r && r.constructor; return !!e && (e === t || "GeneratorFunction" === (e.displayName || e.name)); } var o = { "throw": 1, "return": 2, "break": 3, "continue": 3 }; function a(r) { var e, t; return function (n) { e || (e = { stop: function stop() { return t(n.a, 2); }, "catch": function _catch() { return n.v; }, abrupt: function abrupt(r, e) { return t(n.a, o[r], e); }, delegateYield: function delegateYield(r, o, a) { return e.resultName = o, t(n.d, _regeneratorValues(r), a); }, finish: function finish(r) { return t(n.f, r); } }, t = function t(r, _t, o) { n.p = e.prev, n.n = e.next; try { return r(_t, o); } finally { e.next = n.n; } }), e.resultName && (e[e.resultName] = n.v, e.resultName = void 0), e.sent = n.v, e.next = n.n; try { return r.call(this, e); } finally { n.p = e.prev, n.n = e.next; } }; } return (_regeneratorRuntime = function _regeneratorRuntime() { return { wrap: function wrap(e, t, n, o) { return r.w(a(e), t, n, o && o.reverse()); }, isGeneratorFunction: n, mark: r.m, awrap: function awrap(r, e) { return new _OverloadYield(r, e); }, AsyncIterator: _regeneratorAsyncIterator, async: function async(r, e, t, o, u) { return (n(e) ? _regeneratorAsyncGen : _regeneratorAsync)(a(r), e, t, o, u); }, keys: _regeneratorKeys, values: _regeneratorValues }; })(); }
function _regeneratorValues(e) { if (null != e) { var t = e["function" == typeof Symbol && Symbol.iterator || "@@iterator"], r = 0; if (t) return t.call(e); if ("function" == typeof e.next) return e; if (!isNaN(e.length)) return { next: function next() { return e && r >= e.length && (e = void 0), { value: e && e[r++], done: !e }; } }; } throw new TypeError(_typeof(e) + " is not iterable"); }
function _regeneratorKeys(e) { var n = Object(e), r = []; for (var t in n) r.unshift(t); return function e() { for (; r.length;) if ((t = r.pop()) in n) return e.value = t, e.done = !1, e; return e.done = !0, e; }; }
function _regeneratorAsync(n, e, r, t, o) { var a = _regeneratorAsyncGen(n, e, r, t, o); return a.next().then(function (n) { return n.done ? n.value : a.next(); }); }
function _regeneratorAsyncGen(r, e, t, o, n) { return new _regeneratorAsyncIterator(_regenerator().w(r, e, t, o), n || Promise); }
function _regeneratorAsyncIterator(t, e) { function n(r, o, i, f) { try { var c = t[r](o), u = c.value; return u instanceof _OverloadYield ? e.resolve(u.v).then(function (t) { n("next", t, i, f); }, function (t) { n("throw", t, i, f); }) : e.resolve(u).then(function (t) { c.value = t, i(c); }, function (t) { return n("throw", t, i, f); }); } catch (t) { f(t); } } var r; this.next || (_regeneratorDefine2(_regeneratorAsyncIterator.prototype), _regeneratorDefine2(_regeneratorAsyncIterator.prototype, "function" == typeof Symbol && Symbol.asyncIterator || "@asyncIterator", function () { return this; })), _regeneratorDefine2(this, "_invoke", function (t, o, i) { function f() { return new e(function (e, r) { n(t, i, e, r); }); } return r = r ? r.then(f, f) : f(); }, !0); }
function _regenerator() { /*! regenerator-runtime -- Copyright (c) 2014-present, Facebook, Inc. -- license (MIT): https://github.com/babel/babel/blob/main/packages/babel-helpers/LICENSE */ var e, t, r = "function" == typeof Symbol ? Symbol : {}, n = r.iterator || "@@iterator", o = r.toStringTag || "@@toStringTag"; function i(r, n, o, i) { var c = n && n.prototype instanceof Generator ? n : Generator, u = Object.create(c.prototype); return _regeneratorDefine2(u, "_invoke", function (r, n, o) { var i, c, u, f = 0, p = o || [], y = !1, G = { p: 0, n: 0, v: e, a: d, f: d.bind(e, 4), d: function d(t, r) { return i = t, c = 0, u = e, G.n = r, a; } }; function d(r, n) { for (c = r, u = n, t = 0; !y && f && !o && t < p.length; t++) { var o, i = p[t], d = G.p, l = i[2]; r > 3 ? (o = l === n) && (u = i[(c = i[4]) ? 5 : (c = 3, 3)], i[4] = i[5] = e) : i[0] <= d && ((o = r < 2 && d < i[1]) ? (c = 0, G.v = n, G.n = i[1]) : d < l && (o = r < 3 || i[0] > n || n > l) && (i[4] = r, i[5] = n, G.n = l, c = 0)); } if (o || r > 1) return a; throw y = !0, n; } return function (o, p, l) { if (f > 1) throw TypeError("Generator is already running"); for (y && 1 === p && d(p, l), c = p, u = l; (t = c < 2 ? e : u) || !y;) { i || (c ? c < 3 ? (c > 1 && (G.n = -1), d(c, u)) : G.n = u : G.v = u); try { if (f = 2, i) { if (c || (o = "next"), t = i[o]) { if (!(t = t.call(i, u))) throw TypeError("iterator result is not an object"); if (!t.done) return t; u = t.value, c < 2 && (c = 0); } else 1 === c && (t = i["return"]) && t.call(i), c < 2 && (u = TypeError("The iterator does not provide a '" + o + "' method"), c = 1); i = e; } else if ((t = (y = G.n < 0) ? u : r.call(n, G)) !== a) break; } catch (t) { i = e, c = 1, u = t; } finally { f = 1; } } return { value: t, done: y }; }; }(r, o, i), !0), u; } var a = {}; function Generator() {} function GeneratorFunction() {} function GeneratorFunctionPrototype() {} t = Object.getPrototypeOf; var c = [][n] ? t(t([][n]())) : (_regeneratorDefine2(t = {}, n, function () { return this; }), t), u = GeneratorFunctionPrototype.prototype = Generator.prototype = Object.create(c); function f(e) { return Object.setPrototypeOf ? Object.setPrototypeOf(e, GeneratorFunctionPrototype) : (e.__proto__ = GeneratorFunctionPrototype, _regeneratorDefine2(e, o, "GeneratorFunction")), e.prototype = Object.create(u), e; } return GeneratorFunction.prototype = GeneratorFunctionPrototype, _regeneratorDefine2(u, "constructor", GeneratorFunctionPrototype), _regeneratorDefine2(GeneratorFunctionPrototype, "constructor", GeneratorFunction), GeneratorFunction.displayName = "GeneratorFunction", _regeneratorDefine2(GeneratorFunctionPrototype, o, "GeneratorFunction"), _regeneratorDefine2(u), _regeneratorDefine2(u, o, "Generator"), _regeneratorDefine2(u, n, function () { return this; }), _regeneratorDefine2(u, "toString", function () { return "[object Generator]"; }), (_regenerator = function _regenerator() { return { w: i, m: f }; })(); }
function _regeneratorDefine2(e, r, n, t) { var i = Object.defineProperty; try { i({}, "", {}); } catch (e) { i = 0; } _regeneratorDefine2 = function _regeneratorDefine(e, r, n, t) { if (r) i ? i(e, r, { value: n, enumerable: !t, configurable: !t, writable: !t }) : e[r] = n;else { var o = function o(r, n) { _regeneratorDefine2(e, r, function (e) { return this._invoke(r, n, e); }); }; o("next", 0), o("throw", 1), o("return", 2); } }, _regeneratorDefine2(e, r, n, t); }
function _awaitAsyncGenerator(e) { return new _OverloadYield(e, 0); }
function _wrapAsyncGenerator(e) { return function () { return new AsyncGenerator(e.apply(this, arguments)); }; }
function AsyncGenerator(e) { var r, t; function resume(r, t) { try { var n = e[r](t), o = n.value, u = o instanceof _OverloadYield; Promise.resolve(u ? o.v : o).then(function (t) { if (u) { var i = "return" === r ? "return" : "next"; if (!o.k || t.done) return resume(i, t); t = e[i](t).value; } settle(n.done ? "return" : "normal", t); }, function (e) { resume("throw", e); }); } catch (e) { settle("throw", e); } } function settle(e, n) { switch (e) { case "return": r.resolve({ value: n, done: !0 }); break; case "throw": r.reject(n); break; default: r.resolve({ value: n, done: !1 }); } (r = r.next) ? resume(r.key, r.arg) : t = null; } this._invoke = function (e, n) { return new Promise(function (o, u) { var i = { key: e, arg: n, resolve: o, reject: u, next: null }; t ? t = t.next = i : (r = t = i, resume(e, n)); }); }, "function" != typeof e["return"] && (this["return"] = void 0); }
AsyncGenerator.prototype["function" == typeof Symbol && Symbol.asyncIterator || "@@asyncIterator"] = function () { return this; }, AsyncGenerator.prototype.next = function (e) { return this._invoke("next", e); }, AsyncGenerator.prototype["throw"] = function (e) { return this._invoke("throw", e); }, AsyncGenerator.prototype["return"] = function (e) { return this._invoke("return", e); };
function _OverloadYield(e, d) { this.v = e, this.k = d; }
import axios from 'axios';
import { isFunction } from '../_utils/isFunction';
import { runInQueue } from '../_utils/runInQueue';
// max number of concurrent connections in most modern browsers
var maxConcurrentUpload = 6;
var progressUpdateInterval = 750;
function coroutine(generatorFunction) {
  return function () {
    var generatorObject = generatorFunction.apply(void 0, arguments);
    generatorObject.next();
    return generatorObject;
  };
}
function uploadQueue() {
  return _uploadQueue.apply(this, arguments);
}
function _uploadQueue() {
  _uploadQueue = _wrapAsyncGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee() {
    var uploadProcess;
    return _regeneratorRuntime().wrap(function _callee$(_context) {
      while (1) switch (_context.prev = _context.next) {
        case 0:
          uploadProcess = function uploadProcess() {
            return Promise.resolve();
          };
        case 1:
          if (!true) {
            _context.next = 9;
            break;
          }
          _context.next = 4;
          return _awaitAsyncGenerator(uploadProcess());
        case 4:
          _context.next = 6;
          return _context.sent;
        case 6:
          uploadProcess = _context.sent;
          _context.next = 1;
          break;
        case 9:
        case "end":
          return _context.stop();
      }
    }, _callee);
  }));
  return _uploadQueue.apply(this, arguments);
}
var queue = coroutine(uploadQueue)();
export function useFileUploader(_ref) {
  var externalGetEndpoint = _ref.getEndpoint,
    getMethod = _ref.getMethod,
    getPayload = _ref.getPayload,
    getPayloadKey = _ref.getPayloadKey,
    getHeaders = _ref.getHeaders,
    uploadFile = _ref.uploadFile;
  if (!externalGetEndpoint && !uploadFile) {
    throw new Error('FileSelect.LocalSource: neither "getEndpoint" nor "uploadFile" is defined');
  }
  return {
    uploadFiles: function () {
      var _uploadFiles = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee4(files, _ref2) {
        var onCompleteAll, onComplete, onError, onProgress;
        return _regeneratorRuntime().wrap(function _callee4$(_context4) {
          while (1) switch (_context4.prev = _context4.next) {
            case 0:
              onCompleteAll = _ref2.onCompleteAll, onComplete = _ref2.onComplete, onError = _ref2.onError, onProgress = _ref2.onProgress;
              _context4.next = 3;
              return queue.next( /*#__PURE__*/_asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee3() {
                var uploadProgressState, updateProgress, completeProgressUpdate, notifyProgress, upload, progressNotifierId;
                return _regeneratorRuntime().wrap(function _callee3$(_context3) {
                  while (1) switch (_context3.prev = _context3.next) {
                    case 0:
                      uploadProgressState = new Map();
                      updateProgress = function updateProgress(id, progress) {
                        var _uploadProgressState$;
                        var isCompleted = ((_uploadProgressState$ = uploadProgressState.get(id)) === null || _uploadProgressState$ === void 0 ? void 0 : _uploadProgressState$.done) || false;
                        if (!isCompleted) {
                          uploadProgressState.set(id, {
                            progress: progress,
                            done: isCompleted
                          });
                        }
                      };
                      completeProgressUpdate = function completeProgressUpdate(fileId) {
                        uploadProgressState.set(fileId, {
                          progress: 100,
                          done: true
                        });
                      };
                      notifyProgress = function notifyProgress() {
                        if (isFunction(onProgress)) {
                          uploadProgressState.forEach(function (_ref4, fileId) {
                            var progress = _ref4.progress,
                              done = _ref4.done;
                            if (!done) {
                              onProgress(fileId, progress);
                            }
                          });
                        }
                      };
                      upload = /*#__PURE__*/function () {
                        var _ref5 = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee2(file) {
                          var getEndpoint, execFileUpload, response;
                          return _regeneratorRuntime().wrap(function _callee2$(_context2) {
                            while (1) switch (_context2.prev = _context2.next) {
                              case 0:
                                getEndpoint = externalGetEndpoint;
                                execFileUpload = uploadFile !== null && uploadFile !== void 0 ? uploadFile : uploadFileViaNetwork.bind(null, {
                                  getEndpoint: getEndpoint,
                                  getMethod: getMethod,
                                  getPayload: getPayload,
                                  getPayloadKey: getPayloadKey,
                                  getHeaders: getHeaders
                                });
                                _context2.prev = 2;
                                _context2.next = 5;
                                return new Promise(function (resolve, reject) {
                                  execFileUpload(file.blob, {
                                    onSuccess: resolve,
                                    onProgress: function onProgress(progress) {
                                      updateProgress(file.id, progress);
                                    },
                                    onError: reject
                                  });
                                });
                              case 5:
                                response = _context2.sent;
                                onComplete === null || onComplete === void 0 ? void 0 : onComplete(file.id, response);
                                _context2.next = 12;
                                break;
                              case 9:
                                _context2.prev = 9;
                                _context2.t0 = _context2["catch"](2);
                                onError === null || onError === void 0 ? void 0 : onError(file.id, _context2.t0);
                              case 12:
                                _context2.prev = 12;
                                completeProgressUpdate(file.id);
                                return _context2.finish(12);
                              case 15:
                              case "end":
                                return _context2.stop();
                            }
                          }, _callee2, null, [[2, 9, 12, 15]]);
                        }));
                        return function upload(_x3) {
                          return _ref5.apply(this, arguments);
                        };
                      }(); // batch progress bar updates for better performance
                      progressNotifierId = setInterval(notifyProgress, progressUpdateInterval);
                      _context3.next = 8;
                      return Promise.all(runInQueue(files, upload, maxConcurrentUpload));
                    case 8:
                      clearInterval(progressNotifierId);
                      onCompleteAll === null || onCompleteAll === void 0 ? void 0 : onCompleteAll();
                    case 10:
                    case "end":
                      return _context3.stop();
                  }
                }, _callee3);
              })));
            case 3:
            case "end":
              return _context4.stop();
          }
        }, _callee4);
      }));
      function uploadFiles(_x, _x2) {
        return _uploadFiles.apply(this, arguments);
      }
      return uploadFiles;
    }()
  };
}
function getDefaultPayload(key, file) {
  var payload = new FormData();
  payload.append(key, file);
  return payload;
}
function uploadFileViaNetwork(_x4, _x5, _x6) {
  return _uploadFileViaNetwork.apply(this, arguments);
}
function _uploadFileViaNetwork() {
  _uploadFileViaNetwork = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee5(_ref6, file, _ref7) {
    var getEndpoint, _ref6$getMethod, getMethod, _ref6$getHeaders, getHeaders, getPayload, _ref6$getPayloadKey, getPayloadKey, onProgress, onSuccess, onError, endpoint, method, headers, payload, response;
    return _regeneratorRuntime().wrap(function _callee5$(_context5) {
      while (1) switch (_context5.prev = _context5.next) {
        case 0:
          getEndpoint = _ref6.getEndpoint, _ref6$getMethod = _ref6.getMethod, getMethod = _ref6$getMethod === void 0 ? function () {
            return 'POST';
          } : _ref6$getMethod, _ref6$getHeaders = _ref6.getHeaders, getHeaders = _ref6$getHeaders === void 0 ? function () {
            return {};
          } : _ref6$getHeaders, getPayload = _ref6.getPayload, _ref6$getPayloadKey = _ref6.getPayloadKey, getPayloadKey = _ref6$getPayloadKey === void 0 ? function () {
            return 'file';
          } : _ref6$getPayloadKey;
          onProgress = _ref7.onProgress, onSuccess = _ref7.onSuccess, onError = _ref7.onError;
          endpoint = getEndpoint(file);
          method = getMethod(file);
          headers = getHeaders(file);
          payload = isFunction(getPayload) ? getPayload(file) : getDefaultPayload(getPayloadKey(file), file);
          _context5.prev = 6;
          _context5.next = 9;
          return axios({
            url: endpoint,
            method: method,
            data: payload,
            headers: headers,
            onUploadProgress: function onUploadProgress(e) {
              var progress = Math.floor(e.loaded / e.total * 100);
              onProgress(progress);
            }
          });
        case 9:
          response = _context5.sent;
          onSuccess(response.data);
          _context5.next = 16;
          break;
        case 13:
          _context5.prev = 13;
          _context5.t0 = _context5["catch"](6);
          onError(_context5.t0);
        case 16:
        case "end":
          return _context5.stop();
      }
    }, _callee5, null, [[6, 13]]);
  }));
  return _uploadFileViaNetwork.apply(this, arguments);
}
//# sourceMappingURL=useFileUploader.js.map