@bytescale/sdk 1.1.0 → 1.3.0

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 (49) hide show
  1. package/dist/browser/cjs/main.js +1152 -1094
  2. package/dist/node/cjs/main.js +1156 -952
  3. package/dist/node/esm/main.mjs +1167 -933
  4. package/dist/types/index.d.ts +2 -2
  5. package/dist/types/private/AuthSessionState.d.ts +13 -0
  6. package/dist/types/private/ConsoleUtils.d.ts +5 -0
  7. package/dist/types/private/EnvChecker.d.ts +4 -0
  8. package/dist/types/private/Mutex.d.ts +16 -0
  9. package/dist/types/{uploads/ChunkedStream.d.ts → private/NodeChunkedStream.d.ts} +11 -4
  10. package/dist/types/private/StreamUtils.d.ts +8 -0
  11. package/dist/types/private/TypeUtils.d.ts +2 -0
  12. package/dist/types/private/UploadManagerBase.d.ts +43 -0
  13. package/dist/types/private/dtos/SetAccessTokenRequestDto.d.ts +6 -0
  14. package/dist/types/private/dtos/SetAccessTokenResponseDto.d.ts +7 -0
  15. package/dist/types/private/model/AddCancellationHandler.d.ts +1 -0
  16. package/dist/types/private/model/AuthManagerInterface.d.ts +44 -0
  17. package/dist/types/private/model/AuthSession.d.ts +7 -0
  18. package/dist/types/private/model/OnPartProgress.d.ts +1 -0
  19. package/dist/types/private/model/PreUploadInfo.d.ts +6 -0
  20. package/dist/types/private/model/PutUploadPartResult.d.ts +4 -0
  21. package/dist/types/private/model/UploadManagerInterface.d.ts +5 -0
  22. package/dist/types/private/model/UploadSourceProcessed.d.ts +18 -0
  23. package/dist/types/public/browser/AuthManagerBrowser.d.ts +20 -0
  24. package/dist/types/public/browser/UploadManagerBrowser.d.ts +17 -0
  25. package/dist/types/public/browser/index.d.ts +2 -0
  26. package/dist/types/public/node/AuthManagerNode.d.ts +6 -0
  27. package/dist/types/public/node/UploadManagerNode.d.ts +26 -0
  28. package/dist/types/public/node/index.d.ts +2 -0
  29. package/dist/types/{uploads/UploadModel.d.ts → public/shared/CommonTypes.d.ts} +8 -11
  30. package/dist/types/public/shared/UrlBuilder.d.ts +28 -0
  31. package/dist/types/public/shared/UrlBuilderTypes.d.ts +173 -0
  32. package/dist/types/{generated → public/shared/generated}/runtime.d.ts +44 -29
  33. package/dist/types/public/shared/index.d.ts +4 -0
  34. package/package.json +2 -2
  35. package/tests/ChunkedStream.test.ts +3 -3
  36. package/tests/UploadManager.test.ts +1 -1
  37. package/tests/UrlBuilder.test.ts +168 -0
  38. package/dist/browser/cjs/_70b2.main.js +0 -10
  39. package/dist/browser/cjs/_7392.main.js +0 -10
  40. package/dist/types/uploads/NodeUtils.d.ts +0 -13
  41. package/dist/types/uploads/UploadManager.d.ts +0 -39
  42. package/dist/types/uploads/index.d.ts +0 -3
  43. /package/dist/types/{generated → public/shared/generated}/apis/FileApi.d.ts +0 -0
  44. /package/dist/types/{generated → public/shared/generated}/apis/FolderApi.d.ts +0 -0
  45. /package/dist/types/{generated → public/shared/generated}/apis/JobApi.d.ts +0 -0
  46. /package/dist/types/{generated → public/shared/generated}/apis/UploadApi.d.ts +0 -0
  47. /package/dist/types/{generated → public/shared/generated}/apis/index.d.ts +0 -0
  48. /package/dist/types/{generated → public/shared/generated}/index.d.ts +0 -0
  49. /package/dist/types/{generated → public/shared/generated}/models/index.d.ts +0 -0
@@ -1,165 +1,30 @@
1
1
  /******/ (function() { // webpackBootstrap
2
2
  /******/ "use strict";
3
- /******/ var __webpack_modules__ = ({});
4
- /************************************************************************/
5
- /******/ // The module cache
6
- /******/ var __webpack_module_cache__ = {};
7
- /******/
8
- /******/ // The require function
9
- /******/ function __webpack_require__(moduleId) {
10
- /******/ // Check if module is in cache
11
- /******/ var cachedModule = __webpack_module_cache__[moduleId];
12
- /******/ if (cachedModule !== undefined) {
13
- /******/ return cachedModule.exports;
14
- /******/ }
15
- /******/ // Create a new module (and put it into the cache)
16
- /******/ var module = __webpack_module_cache__[moduleId] = {
17
- /******/ // no module.id needed
18
- /******/ // no module.loaded needed
19
- /******/ exports: {}
20
- /******/ };
21
- /******/
22
- /******/ // Execute the module function
23
- /******/ __webpack_modules__[moduleId](module, module.exports, __webpack_require__);
24
- /******/
25
- /******/ // Return the exports of the module
26
- /******/ return module.exports;
27
- /******/ }
28
- /******/
29
- /******/ // expose the modules object (__webpack_modules__)
30
- /******/ __webpack_require__.m = __webpack_modules__;
3
+ /******/ // The require scope
4
+ /******/ var __lib_require__ = {};
31
5
  /******/
32
6
  /************************************************************************/
33
- /******/ /* webpack/runtime/create fake namespace object */
34
- /******/ !function() {
35
- /******/ var getProto = Object.getPrototypeOf ? function(obj) { return Object.getPrototypeOf(obj); } : function(obj) { return obj.__proto__; };
36
- /******/ var leafPrototypes;
37
- /******/ // create a fake namespace object
38
- /******/ // mode & 1: value is a module id, require it
39
- /******/ // mode & 2: merge all properties of value into the ns
40
- /******/ // mode & 4: return value when already ns object
41
- /******/ // mode & 16: return value when it's Promise-like
42
- /******/ // mode & 8|1: behave like require
43
- /******/ __webpack_require__.t = function(value, mode) {
44
- /******/ if(mode & 1) value = this(value);
45
- /******/ if(mode & 8) return value;
46
- /******/ if(typeof value === 'object' && value) {
47
- /******/ if((mode & 4) && value.__esModule) return value;
48
- /******/ if((mode & 16) && typeof value.then === 'function') return value;
49
- /******/ }
50
- /******/ var ns = Object.create(null);
51
- /******/ __webpack_require__.r(ns);
52
- /******/ var def = {};
53
- /******/ leafPrototypes = leafPrototypes || [null, getProto({}), getProto([]), getProto(getProto)];
54
- /******/ for(var current = mode & 2 && value; typeof current == 'object' && !~leafPrototypes.indexOf(current); current = getProto(current)) {
55
- /******/ Object.getOwnPropertyNames(current).forEach(function(key) { def[key] = function() { return value[key]; }; });
56
- /******/ }
57
- /******/ def['default'] = function() { return value; };
58
- /******/ __webpack_require__.d(ns, def);
59
- /******/ return ns;
60
- /******/ };
61
- /******/ }();
62
- /******/
63
7
  /******/ /* webpack/runtime/define property getters */
64
8
  /******/ !function() {
65
9
  /******/ // define getter functions for harmony exports
66
- /******/ __webpack_require__.d = function(exports, definition) {
10
+ /******/ __lib_require__.d = function(exports, definition) {
67
11
  /******/ for(var key in definition) {
68
- /******/ if(__webpack_require__.o(definition, key) && !__webpack_require__.o(exports, key)) {
12
+ /******/ if(__lib_require__.o(definition, key) && !__lib_require__.o(exports, key)) {
69
13
  /******/ Object.defineProperty(exports, key, { enumerable: true, get: definition[key] });
70
14
  /******/ }
71
15
  /******/ }
72
16
  /******/ };
73
17
  /******/ }();
74
18
  /******/
75
- /******/ /* webpack/runtime/ensure chunk */
76
- /******/ !function() {
77
- /******/ __webpack_require__.f = {};
78
- /******/ // This file contains only the entry chunk.
79
- /******/ // The chunk loading function for additional chunks
80
- /******/ __webpack_require__.e = function(chunkId) {
81
- /******/ return Promise.all(Object.keys(__webpack_require__.f).reduce(function(promises, key) {
82
- /******/ __webpack_require__.f[key](chunkId, promises);
83
- /******/ return promises;
84
- /******/ }, []));
85
- /******/ };
86
- /******/ }();
87
- /******/
88
- /******/ /* webpack/runtime/get javascript chunk filename */
89
- /******/ !function() {
90
- /******/ // This function allow to reference async chunks
91
- /******/ __webpack_require__.u = function(chunkId) {
92
- /******/ // return url for filenames based on template
93
- /******/ return "" + chunkId + ".main.js";
94
- /******/ };
95
- /******/ }();
96
- /******/
97
- /******/ /* webpack/runtime/global */
98
- /******/ !function() {
99
- /******/ __webpack_require__.g = (function() {
100
- /******/ if (typeof globalThis === 'object') return globalThis;
101
- /******/ try {
102
- /******/ return this || new Function('return this')();
103
- /******/ } catch (e) {
104
- /******/ if (typeof window === 'object') return window;
105
- /******/ }
106
- /******/ })();
107
- /******/ }();
108
- /******/
109
19
  /******/ /* webpack/runtime/hasOwnProperty shorthand */
110
20
  /******/ !function() {
111
- /******/ __webpack_require__.o = function(obj, prop) { return Object.prototype.hasOwnProperty.call(obj, prop); }
112
- /******/ }();
113
- /******/
114
- /******/ /* webpack/runtime/load script */
115
- /******/ !function() {
116
- /******/ var inProgress = {};
117
- /******/ var dataWebpackPrefix = "@bytescale/sdk:";
118
- /******/ // loadScript function to load a script via script tag
119
- /******/ __webpack_require__.l = function(url, done, key, chunkId) {
120
- /******/ if(inProgress[url]) { inProgress[url].push(done); return; }
121
- /******/ var script, needAttach;
122
- /******/ if(key !== undefined) {
123
- /******/ var scripts = document.getElementsByTagName("script");
124
- /******/ for(var i = 0; i < scripts.length; i++) {
125
- /******/ var s = scripts[i];
126
- /******/ if(s.getAttribute("src") == url || s.getAttribute("data-webpack") == dataWebpackPrefix + key) { script = s; break; }
127
- /******/ }
128
- /******/ }
129
- /******/ if(!script) {
130
- /******/ needAttach = true;
131
- /******/ script = document.createElement('script');
132
- /******/
133
- /******/ script.charset = 'utf-8';
134
- /******/ script.timeout = 120;
135
- /******/ if (__webpack_require__.nc) {
136
- /******/ script.setAttribute("nonce", __webpack_require__.nc);
137
- /******/ }
138
- /******/ script.setAttribute("data-webpack", dataWebpackPrefix + key);
139
- /******/ script.src = url;
140
- /******/ }
141
- /******/ inProgress[url] = [done];
142
- /******/ var onScriptComplete = function(prev, event) {
143
- /******/ // avoid mem leaks in IE.
144
- /******/ script.onerror = script.onload = null;
145
- /******/ clearTimeout(timeout);
146
- /******/ var doneFns = inProgress[url];
147
- /******/ delete inProgress[url];
148
- /******/ script.parentNode && script.parentNode.removeChild(script);
149
- /******/ doneFns && doneFns.forEach(function(fn) { return fn(event); });
150
- /******/ if(prev) return prev(event);
151
- /******/ };
152
- /******/ var timeout = setTimeout(onScriptComplete.bind(null, undefined, { type: 'timeout', target: script }), 120000);
153
- /******/ script.onerror = onScriptComplete.bind(null, script.onerror);
154
- /******/ script.onload = onScriptComplete.bind(null, script.onload);
155
- /******/ needAttach && document.head.appendChild(script);
156
- /******/ };
21
+ /******/ __lib_require__.o = function(obj, prop) { return Object.prototype.hasOwnProperty.call(obj, prop); }
157
22
  /******/ }();
158
23
  /******/
159
24
  /******/ /* webpack/runtime/make namespace object */
160
25
  /******/ !function() {
161
26
  /******/ // define __esModule on exports
162
- /******/ __webpack_require__.r = function(exports) {
27
+ /******/ __lib_require__.r = function(exports) {
163
28
  /******/ if(typeof Symbol !== 'undefined' && Symbol.toStringTag) {
164
29
  /******/ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
165
30
  /******/ }
@@ -167,149 +32,47 @@
167
32
  /******/ };
168
33
  /******/ }();
169
34
  /******/
170
- /******/ /* webpack/runtime/publicPath */
171
- /******/ !function() {
172
- /******/ var scriptUrl;
173
- /******/ if (__webpack_require__.g.importScripts) scriptUrl = __webpack_require__.g.location + "";
174
- /******/ var document = __webpack_require__.g.document;
175
- /******/ if (!scriptUrl && document) {
176
- /******/ if (document.currentScript)
177
- /******/ scriptUrl = document.currentScript.src
178
- /******/ if (!scriptUrl) {
179
- /******/ var scripts = document.getElementsByTagName("script");
180
- /******/ if(scripts.length) scriptUrl = scripts[scripts.length - 1].src
181
- /******/ }
182
- /******/ }
183
- /******/ // When supporting browsers where an automatic publicPath is not supported you must specify an output.publicPath manually via configuration
184
- /******/ // or pass an empty string ("") and set the __webpack_public_path__ variable from your code to use your own logic.
185
- /******/ if (!scriptUrl) throw new Error("Automatic publicPath is not supported in this browser");
186
- /******/ scriptUrl = scriptUrl.replace(/#.*$/, "").replace(/\?.*$/, "").replace(/\/[^\/]+$/, "/");
187
- /******/ __webpack_require__.p = scriptUrl;
188
- /******/ }();
189
- /******/
190
- /******/ /* webpack/runtime/jsonp chunk loading */
191
- /******/ !function() {
192
- /******/ // no baseURI
193
- /******/
194
- /******/ // object to store loaded and loading chunks
195
- /******/ // undefined = chunk not loaded, null = chunk preloaded/prefetched
196
- /******/ // [resolve, reject, Promise] = chunk loading, 0 = chunk loaded
197
- /******/ var installedChunks = {
198
- /******/ "main": 0
199
- /******/ };
200
- /******/
201
- /******/ __webpack_require__.f.j = function(chunkId, promises) {
202
- /******/ // JSONP chunk loading for javascript
203
- /******/ var installedChunkData = __webpack_require__.o(installedChunks, chunkId) ? installedChunks[chunkId] : undefined;
204
- /******/ if(installedChunkData !== 0) { // 0 means "already installed".
205
- /******/
206
- /******/ // a Promise means "currently loading".
207
- /******/ if(installedChunkData) {
208
- /******/ promises.push(installedChunkData[2]);
209
- /******/ } else {
210
- /******/ if(true) { // all chunks have JS
211
- /******/ // setup Promise in chunk cache
212
- /******/ var promise = new Promise(function(resolve, reject) { installedChunkData = installedChunks[chunkId] = [resolve, reject]; });
213
- /******/ promises.push(installedChunkData[2] = promise);
214
- /******/
215
- /******/ // start chunk loading
216
- /******/ var url = __webpack_require__.p + __webpack_require__.u(chunkId);
217
- /******/ // create error before stack unwound to get useful stacktrace later
218
- /******/ var error = new Error();
219
- /******/ var loadingEnded = function(event) {
220
- /******/ if(__webpack_require__.o(installedChunks, chunkId)) {
221
- /******/ installedChunkData = installedChunks[chunkId];
222
- /******/ if(installedChunkData !== 0) installedChunks[chunkId] = undefined;
223
- /******/ if(installedChunkData) {
224
- /******/ var errorType = event && (event.type === 'load' ? 'missing' : event.type);
225
- /******/ var realSrc = event && event.target && event.target.src;
226
- /******/ error.message = 'Loading chunk ' + chunkId + ' failed.\n(' + errorType + ': ' + realSrc + ')';
227
- /******/ error.name = 'ChunkLoadError';
228
- /******/ error.type = errorType;
229
- /******/ error.request = realSrc;
230
- /******/ installedChunkData[1](error);
231
- /******/ }
232
- /******/ }
233
- /******/ };
234
- /******/ __webpack_require__.l(url, loadingEnded, "chunk-" + chunkId, chunkId);
235
- /******/ } else installedChunks[chunkId] = 0;
236
- /******/ }
237
- /******/ }
238
- /******/ };
239
- /******/
240
- /******/ // no prefetching
241
- /******/
242
- /******/ // no preloaded
243
- /******/
244
- /******/ // no HMR
245
- /******/
246
- /******/ // no HMR manifest
247
- /******/
248
- /******/ // no on chunks loaded
249
- /******/
250
- /******/ // install a JSONP callback for chunk loading
251
- /******/ var webpackJsonpCallback = function(parentChunkLoadingFunction, data) {
252
- /******/ var chunkIds = data[0];
253
- /******/ var moreModules = data[1];
254
- /******/ var runtime = data[2];
255
- /******/ // add "moreModules" to the modules object,
256
- /******/ // then flag all "chunkIds" as loaded and fire callback
257
- /******/ var moduleId, chunkId, i = 0;
258
- /******/ if(chunkIds.some(function(id) { return installedChunks[id] !== 0; })) {
259
- /******/ for(moduleId in moreModules) {
260
- /******/ if(__webpack_require__.o(moreModules, moduleId)) {
261
- /******/ __webpack_require__.m[moduleId] = moreModules[moduleId];
262
- /******/ }
263
- /******/ }
264
- /******/ if(runtime) var result = runtime(__webpack_require__);
265
- /******/ }
266
- /******/ if(parentChunkLoadingFunction) parentChunkLoadingFunction(data);
267
- /******/ for(;i < chunkIds.length; i++) {
268
- /******/ chunkId = chunkIds[i];
269
- /******/ if(__webpack_require__.o(installedChunks, chunkId) && installedChunks[chunkId]) {
270
- /******/ installedChunks[chunkId][0]();
271
- /******/ }
272
- /******/ installedChunks[chunkId] = 0;
273
- /******/ }
274
- /******/
275
- /******/ }
276
- /******/
277
- /******/ var chunkLoadingGlobal = self["webpackChunk_bytescale_sdk"] = self["webpackChunk_bytescale_sdk"] || [];
278
- /******/ chunkLoadingGlobal.forEach(webpackJsonpCallback.bind(null, 0));
279
- /******/ chunkLoadingGlobal.push = webpackJsonpCallback.bind(null, chunkLoadingGlobal.push.bind(chunkLoadingGlobal));
280
- /******/ }();
281
- /******/
282
35
  /************************************************************************/
283
- var __webpack_exports__ = {};
36
+ var __lib_exports__ = {};
284
37
  // ESM COMPAT FLAG
285
- __webpack_require__.r(__webpack_exports__);
38
+ __lib_require__.r(__lib_exports__);
286
39
 
287
40
  // EXPORTS
288
- __webpack_require__.d(__webpack_exports__, {
289
- "BASE_PATH": function() { return /* reexport */ BASE_PATH; },
41
+ __lib_require__.d(__lib_exports__, {
42
+ "AuthManager": function() { return /* reexport */ AuthManager; },
290
43
  "BaseAPI": function() { return /* reexport */ BaseAPI; },
291
44
  "BinaryResult": function() { return /* reexport */ BinaryResult; },
45
+ "BytescaleApiClientConfigResolver": function() { return /* reexport */ BytescaleApiClientConfigResolver; },
292
46
  "BytescaleApiError": function() { return /* reexport */ BytescaleApiError; },
293
47
  "CancelledError": function() { return /* reexport */ CancelledError; },
294
- "ChunkedStream": function() { return /* reexport */ ChunkedStream; },
295
- "FetchError": function() { return /* reexport */ FetchError; },
48
+ "CommonTypesNoOp": function() { return /* reexport */ CommonTypesNoOp; },
296
49
  "FileApi": function() { return /* reexport */ FileApi; },
297
50
  "FolderApi": function() { return /* reexport */ FolderApi; },
298
51
  "JSONApiResponse": function() { return /* reexport */ JSONApiResponse; },
299
52
  "JobApi": function() { return /* reexport */ JobApi; },
300
- "RequiredError": function() { return /* reexport */ RequiredError; },
301
- "ResponseError": function() { return /* reexport */ ResponseError; },
302
53
  "UploadApi": function() { return /* reexport */ UploadApi; },
303
54
  "UploadManager": function() { return /* reexport */ UploadManager; },
55
+ "UrlBuilder": function() { return /* reexport */ UrlBuilder; },
56
+ "UrlBuilderTypesNoOp": function() { return /* reexport */ UrlBuilderTypesNoOp; },
304
57
  "VoidApiResponse": function() { return /* reexport */ VoidApiResponse; },
305
58
  "querystring": function() { return /* reexport */ querystring; }
306
59
  });
307
60
 
308
- ;// CONCATENATED MODULE: ./src/generated/runtime.ts
61
+ ;// CONCATENATED MODULE: ./src/private/AuthSessionState.ts
309
62
  function _typeof(obj) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (obj) { return typeof obj; } : function (obj) { return obj && "function" == typeof Symbol && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }, _typeof(obj); }
63
+ function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, _toPropertyKey(descriptor.key), descriptor); } }
64
+ function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); Object.defineProperty(Constructor, "prototype", { writable: false }); return Constructor; }
65
+ function _toPropertyKey(arg) { var key = _toPrimitive(arg, "string"); return _typeof(key) === "symbol" ? key : String(key); }
66
+ function _toPrimitive(input, hint) { if (_typeof(input) !== "object" || input === null) return input; var prim = input[Symbol.toPrimitive]; if (prim !== undefined) { var res = prim.call(input, hint || "default"); if (_typeof(res) !== "object") return res; throw new TypeError("@@toPrimitive must return a primitive value."); } return (hint === "string" ? String : Number)(input); }
67
+ function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
68
+ var AuthSessionState = /*#__PURE__*/_createClass(function AuthSessionState() {
69
+ _classCallCheck(this, AuthSessionState);
70
+ });
71
+ ;// CONCATENATED MODULE: ./src/public/shared/generated/runtime.ts
72
+ function runtime_typeof(obj) { "@babel/helpers - typeof"; return runtime_typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (obj) { return typeof obj; } : function (obj) { return obj && "function" == typeof Symbol && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }, runtime_typeof(obj); }
310
73
  function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function"); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, writable: true, configurable: true } }); Object.defineProperty(subClass, "prototype", { writable: false }); if (superClass) _setPrototypeOf(subClass, superClass); }
311
74
  function _createSuper(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct(); return function _createSuperInternal() { var Super = _getPrototypeOf(Derived), result; if (hasNativeReflectConstruct) { var NewTarget = _getPrototypeOf(this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return _possibleConstructorReturn(this, result); }; }
312
- function _possibleConstructorReturn(self, call) { if (call && (_typeof(call) === "object" || typeof call === "function")) { return call; } else if (call !== void 0) { throw new TypeError("Derived constructors may only return object or undefined"); } return _assertThisInitialized(self); }
75
+ function _possibleConstructorReturn(self, call) { if (call && (runtime_typeof(call) === "object" || typeof call === "function")) { return call; } else if (call !== void 0) { throw new TypeError("Derived constructors may only return object or undefined"); } return _assertThisInitialized(self); }
313
76
  function _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self; }
314
77
  function _wrapNativeSuper(Class) { var _cache = typeof Map === "function" ? new Map() : undefined; _wrapNativeSuper = function _wrapNativeSuper(Class) { if (Class === null || !_isNativeFunction(Class)) return Class; if (typeof Class !== "function") { throw new TypeError("Super expression must either be null or a function"); } if (typeof _cache !== "undefined") { if (_cache.has(Class)) return _cache.get(Class); _cache.set(Class, Wrapper); } function Wrapper() { return _construct(Class, arguments, _getPrototypeOf(this).constructor); } Wrapper.prototype = Object.create(Class.prototype, { constructor: { value: Wrapper, enumerable: false, writable: true, configurable: true } }); return _setPrototypeOf(Wrapper, Class); }; return _wrapNativeSuper(Class); }
315
78
  function _construct(Parent, args, Class) { if (_isNativeReflectConstruct()) { _construct = Reflect.construct.bind(); } else { _construct = function _construct(Parent, args, Class) { var a = [null]; a.push.apply(a, args); var Constructor = Function.bind.apply(Parent, a); var instance = new Constructor(); if (Class) _setPrototypeOf(instance, Class.prototype); return instance; }; } return _construct.apply(null, arguments); }
@@ -317,15 +80,6 @@ function _isNativeReflectConstruct() { if (typeof Reflect === "undefined" || !Re
317
80
  function _isNativeFunction(fn) { return Function.toString.call(fn).indexOf("[native code]") !== -1; }
318
81
  function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); }
319
82
  function _getPrototypeOf(o) { _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf.bind() : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _getPrototypeOf(o); }
320
- function _await(value, then, direct) {
321
- if (direct) {
322
- return then ? then(value) : value;
323
- }
324
- if (!value || !value.then) {
325
- value = Promise.resolve(value);
326
- }
327
- return then ? value.then(then) : value;
328
- }
329
83
  function _catch(body, recover) {
330
84
  try {
331
85
  var result = body();
@@ -337,22 +91,10 @@ function _catch(body, recover) {
337
91
  }
338
92
  return result;
339
93
  }
94
+ function _empty() {}
340
95
  function _continue(value, then) {
341
96
  return value && value.then ? value.then(then) : then(value);
342
97
  }
343
- function _async(f) {
344
- return function () {
345
- for (var args = [], i = 0; i < arguments.length; i++) {
346
- args[i] = arguments[i];
347
- }
348
- try {
349
- return Promise.resolve(f.apply(this, args));
350
- } catch (e) {
351
- return Promise.reject(e);
352
- }
353
- };
354
- }
355
- function _empty() {}
356
98
  function _invoke(body, then) {
357
99
  var result = body();
358
100
  if (result && result.then) {
@@ -360,85 +102,122 @@ function _invoke(body, then) {
360
102
  }
361
103
  return then(result);
362
104
  }
363
- function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
364
- function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, _toPropertyKey(descriptor.key), descriptor); } }
365
- function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); Object.defineProperty(Constructor, "prototype", { writable: false }); return Constructor; }
366
- function _toPropertyKey(arg) { var key = _toPrimitive(arg, "string"); return _typeof(key) === "symbol" ? key : String(key); }
367
- function _toPrimitive(input, hint) { if (_typeof(input) !== "object" || input === null) return input; var prim = input[Symbol.toPrimitive]; if (prim !== undefined) { var res = prim.call(input, hint || "default"); if (_typeof(res) !== "object") return res; throw new TypeError("@@toPrimitive must return a primitive value."); } return (hint === "string" ? String : Number)(input); }
368
- /**
369
- * @bytescale/api
370
- * Bytescale API
371
- *
372
- * The version of the OpenAPI document: 2.0.0
373
- * Contact: hello@bytescale.com
374
- *
375
- * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
376
- * https://openapi-generator.tech
377
- * Do not edit the class manually.
378
- */
379
- var BASE_PATH = "https://api.bytescale.com".replace(/\/+$/, "");
105
+ function _defineProperty(obj, key, value) { key = runtime_toPropertyKey(key); if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }
106
+ function _await(value, then, direct) {
107
+ if (direct) {
108
+ return then ? then(value) : value;
109
+ }
110
+ if (!value || !value.then) {
111
+ value = Promise.resolve(value);
112
+ }
113
+ return then ? value.then(then) : value;
114
+ }
115
+ function runtime_classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
116
+ function runtime_defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, runtime_toPropertyKey(descriptor.key), descriptor); } }
117
+ function runtime_createClass(Constructor, protoProps, staticProps) { if (protoProps) runtime_defineProperties(Constructor.prototype, protoProps); if (staticProps) runtime_defineProperties(Constructor, staticProps); Object.defineProperty(Constructor, "prototype", { writable: false }); return Constructor; }
118
+ function runtime_toPropertyKey(arg) { var key = runtime_toPrimitive(arg, "string"); return runtime_typeof(key) === "symbol" ? key : String(key); }
119
+ function runtime_toPrimitive(input, hint) { if (runtime_typeof(input) !== "object" || input === null) return input; var prim = input[Symbol.toPrimitive]; if (prim !== undefined) { var res = prim.call(input, hint || "default"); if (runtime_typeof(res) !== "object") return res; throw new TypeError("@@toPrimitive must return a primitive value."); } return (hint === "string" ? String : Number)(input); }
120
+
121
+ var BytescaleApiClientConfigResolver = /*#__PURE__*/function () {
122
+ function BytescaleApiClientConfigResolver() {
123
+ runtime_classCallCheck(this, BytescaleApiClientConfigResolver);
124
+ }
125
+ runtime_createClass(BytescaleApiClientConfigResolver, null, [{
126
+ key: "getApiUrl",
127
+ value: function getApiUrl(config) {
128
+ var _a;
129
+ return (_a = config.apiUrl) !== null && _a !== void 0 ? _a : BytescaleApiClientConfigResolver.defaultApiUrl;
130
+ }
131
+ }, {
132
+ key: "getCdnUrl",
133
+ value: function getCdnUrl(config) {
134
+ var _a;
135
+ return (_a = config.cdnUrl) !== null && _a !== void 0 ? _a : BytescaleApiClientConfigResolver.defaultCdnUrl;
136
+ }
137
+ }, {
138
+ key: "getFetchApi",
139
+ value: function getFetchApi(config) {
140
+ var _a;
141
+ return (_a = config.fetchApi) !== null && _a !== void 0 ? _a : fetch;
142
+ }
143
+ }]);
144
+ return BytescaleApiClientConfigResolver;
145
+ }();
146
+ BytescaleApiClientConfigResolver.defaultApiUrl = "https://api.bytescale.com";
147
+ BytescaleApiClientConfigResolver.defaultCdnUrl = "https://upcdn.io";
380
148
  /**
381
149
  * This is the base class for all generated API classes.
382
150
  */
383
151
  var BaseAPI = /*#__PURE__*/function () {
384
152
  function BaseAPI(config) {
385
- var _this = this;
386
- _classCallCheck(this, BaseAPI);
153
+ runtime_classCallCheck(this, BaseAPI);
387
154
  this.config = config;
388
- this.fetchApi = _async(function (url, init) {
389
- var _exit = false;
390
- var fetchParams = {
391
- url: url,
392
- init: init
393
- };
394
- var response = undefined;
395
- return _continue(_catch(function () {
396
- return _await((_this.config.fetchApi || fetch)(fetchParams.url, fetchParams.init), function (_temp) {
397
- response = _temp;
398
- });
399
- }, function (e) {
400
- if (response === undefined) {
401
- if (e instanceof Error) {
402
- throw new FetchError(e, "The request failed and the interceptors did not return an alternative response");
403
- } else {
404
- throw e;
405
- }
406
- }
407
- }), function (_result) {
408
- return _exit ? _result : response;
409
- });
410
- });
411
155
  }
412
- _createClass(BaseAPI, [{
156
+ runtime_createClass(BaseAPI, [{
413
157
  key: "request",
414
- value: function request(context, initOverrides, operationBasePathOverride) {
158
+ value: function request(context, initOverrides, baseUrlOverride) {
415
159
  try {
416
- var _this3 = this;
417
- var _a;
418
- var apiKey = _this3.config.apiKey;
160
+ var _this2 = this;
161
+ var _a, _b;
162
+ var apiKey = _this2.config.apiKey;
419
163
  context.headers["Authorization"] = "Bearer ".concat(apiKey); // authorization-header authentication
420
- return _await(_this3.createFetchParams(context, initOverrides, operationBasePathOverride), function (_ref) {
164
+ if (((_a = AuthSessionState.session) === null || _a === void 0 ? void 0 : _a.accessToken) !== undefined) {
165
+ context.headers["Authorization-Token"] = AuthSessionState.session.accessToken;
166
+ }
167
+ // Key: any possible value for 'baseUrlOverride'
168
+ // Value: user-overridden value for that base URL from the config.
169
+ var nonDefaultBasePaths = _defineProperty({}, BytescaleApiClientConfigResolver.defaultCdnUrl, BytescaleApiClientConfigResolver.getCdnUrl(_this2.config));
170
+ return _await(_this2.createFetchParams(context, initOverrides, baseUrlOverride === undefined ? undefined : (_b = nonDefaultBasePaths[baseUrlOverride]) !== null && _b !== void 0 ? _b : baseUrlOverride), function (_ref) {
421
171
  var url = _ref.url,
422
172
  init = _ref.init;
423
- return _await(_this3.fetchApi(url, init), function (response) {
424
- var _exit2 = false;
425
- return response && response.status >= 200 && response.status < 300 ? response : _invoke(function () {
426
- if (response !== undefined) {
427
- var jsonError = undefined;
428
- return _continue(_catch(function () {
429
- return _await(response.json(), function (_response$json) {
430
- jsonError = _response$json;
431
- });
432
- }, _empty), function () {
433
- if (typeof ((_a = jsonError === null || jsonError === void 0 ? void 0 : jsonError.error) === null || _a === void 0 ? void 0 : _a.code) === "string") {
434
- throw new BytescaleApiError(jsonError);
435
- }
173
+ return _this2.doFetch(url, init, true);
174
+ });
175
+ } catch (e) {
176
+ return Promise.reject(e);
177
+ }
178
+ }
179
+ /**
180
+ * Returns a successful response (2**) else throws an error.
181
+ */
182
+ }, {
183
+ key: "doFetch",
184
+ value: function doFetch(url, init, isBytescaleApi) {
185
+ try {
186
+ var _exit3 = false;
187
+ var _this4 = this;
188
+ var _a, _b;
189
+ var response;
190
+ return _continue(_catch(function () {
191
+ return _await(BytescaleApiClientConfigResolver.getFetchApi(_this4.config)(url, init), function (_BytescaleApiClientCo) {
192
+ response = _BytescaleApiClientCo;
193
+ });
194
+ }, function (e) {
195
+ // Network-level errors, CORS errors, or HTTP-level errors from intermediary services (e.g. AWS or the user's own infrastructure/proxies).
196
+ // HTTP-level errors from external services (e.g. AWS or the user's own proxy) will appear as CORS errors as their response headers won't include the appropriate CORS values.
197
+ throw new Error(isBytescaleApi ? "Unable to resolve the Bytescale API: ".concat(e.message, " If the problem persists, and your network connection is OK, then please contact support@bytescale.com and provide: (a) time of failed request in UTC (b) screenshot of failed network response header + body (c) screenshot of failed network request header + body (d) browser and OS version.") : "Unable to resolve URL (".concat(url, "): ").concat(e.message));
198
+ }), function (_result) {
199
+ var _exit2 = false;
200
+ if (_exit3) return _result;
201
+ return response.status >= 200 && response.status < 300 ? response : _invoke(function () {
202
+ if (isBytescaleApi) {
203
+ var jsonError = undefined;
204
+ return _continue(_catch(function () {
205
+ return _await(response.json(), function (_response$json) {
206
+ jsonError = _response$json;
436
207
  });
437
- }
438
- }, function (_result2) {
439
- if (_exit2) return _result2;
440
- throw new ResponseError(response, "Response returned an error code");
441
- });
208
+ }, _empty), function () {
209
+ if (typeof ((_a = jsonError === null || jsonError === void 0 ? void 0 : jsonError.error) === null || _a === void 0 ? void 0 : _a.code) === "string") {
210
+ throw new BytescaleApiError(jsonError);
211
+ }
212
+ // HTTP-level errors from intermediary services (e.g. AWS or the user's own infrastructure/proxies). On the browser,
213
+ // this error is unlikely to be triggered since these errors will masqurade as CORS errors (see above) but in Node.js
214
+ // this error will appear from any intermediary service failure.
215
+ throw new Error("Unable to connect to the Bytescale API (".concat(response.status, "): please try again."));
216
+ });
217
+ }
218
+ }, function (_result2) {
219
+ if (_exit2) return _result2;
220
+ throw new Error("Failure status code (".concat(response.status, ") received for request: ").concat((_b = init.method) !== null && _b !== void 0 ? _b : "GET", " ").concat(url));
442
221
  });
443
222
  });
444
223
  } catch (e) {
@@ -460,17 +239,17 @@ var BaseAPI = /*#__PURE__*/function () {
460
239
  }
461
240
  }, {
462
241
  key: "createFetchParams",
463
- value: function createFetchParams(context, initOverrides, operationBasePathOverride) {
242
+ value: function createFetchParams(context, initOverrides, baseUrlOverride) {
464
243
  try {
465
- var _this5 = this;
466
- var url = (operationBasePathOverride !== null && operationBasePathOverride !== void 0 ? operationBasePathOverride : BASE_PATH) + context.path;
244
+ var _this6 = this;
245
+ var url = (baseUrlOverride !== null && baseUrlOverride !== void 0 ? baseUrlOverride : BytescaleApiClientConfigResolver.getApiUrl(_this6.config)) + context.path;
467
246
  if (context.query !== undefined && Object.keys(context.query).length !== 0) {
468
247
  // only add the querystring to the URL if there are query parameters.
469
248
  // this is done to avoid urls ending with a "?" character which buggy webservers
470
249
  // do not handle correctly sometimes.
471
250
  url += "?" + querystring(context.query);
472
251
  }
473
- var configHeaders = _this5.config.headers;
252
+ var configHeaders = _this6.config.headers;
474
253
  var _Object$assign3 = Object.assign({}, context.headers);
475
254
  return _await(configHeaders === undefined ? {} : configHeaders(), function (_configHeaders) {
476
255
  var headers = Object.assign(_Object$assign3, _configHeaders);
@@ -492,7 +271,7 @@ var BaseAPI = /*#__PURE__*/function () {
492
271
  }), function (_initOverrideFn) {
493
272
  var overriddenInit = Object.assign(_Object$assign2, _initOverrideFn);
494
273
  var init = Object.assign(Object.assign({}, overriddenInit), {
495
- body: isFormData(overriddenInit.body) || overriddenInit.body instanceof URLSearchParams || isBlob(overriddenInit.body) ? overriddenInit.body : JSON.stringify(overriddenInit.body)
274
+ body: JSON.stringify(overriddenInit.body)
496
275
  });
497
276
  return {
498
277
  url: url,
@@ -507,64 +286,34 @@ var BaseAPI = /*#__PURE__*/function () {
507
286
  }]);
508
287
  return BaseAPI;
509
288
  }();
510
- function isBlob(value) {
511
- return typeof Blob !== "undefined" && value instanceof Blob;
512
- }
513
- function isFormData(value) {
514
- return typeof FormData !== "undefined" && value instanceof FormData;
515
- }
516
- var BytescaleApiError = /*#__PURE__*/function (_Error) {
517
- _inherits(BytescaleApiError, _Error);
518
- var _super = _createSuper(BytescaleApiError);
519
- function BytescaleApiError(response) {
520
- var _this6;
521
- _classCallCheck(this, BytescaleApiError);
522
- _this6 = _super.call(this, response.error.message);
523
- _this6.name = "BytescaleApiError";
524
- _this6.errorCode = response.error.code;
525
- _this6.details = response.error.details;
526
- return _this6;
527
- }
528
- return _createClass(BytescaleApiError);
529
- }( /*#__PURE__*/_wrapNativeSuper(Error));
530
- var ResponseError = /*#__PURE__*/function (_Error2) {
531
- _inherits(ResponseError, _Error2);
532
- var _super2 = _createSuper(ResponseError);
533
- function ResponseError(response, msg) {
289
+ BaseAPI.specialApiKeys = ["free", "demo"];
290
+ BaseAPI.specialApiKeyAccountId = "W142hJk";
291
+ BaseAPI.accountIdLength = 7; // Sync with: upload/shared/**/AccountIdUtils
292
+ var CancelledError = /*#__PURE__*/function (_Error) {
293
+ _inherits(CancelledError, _Error);
294
+ var _super = _createSuper(CancelledError);
295
+ function CancelledError() {
534
296
  var _this7;
535
- _classCallCheck(this, ResponseError);
536
- _this7 = _super2.call(this, msg);
537
- _this7.response = response;
538
- _this7.name = "ResponseError";
297
+ runtime_classCallCheck(this, CancelledError);
298
+ _this7 = _super.call(this, "Operation cancelled by caller.");
299
+ _this7.name = "CancelledError";
539
300
  return _this7;
540
301
  }
541
- return _createClass(ResponseError);
302
+ return runtime_createClass(CancelledError);
542
303
  }( /*#__PURE__*/_wrapNativeSuper(Error));
543
- var FetchError = /*#__PURE__*/function (_Error3) {
544
- _inherits(FetchError, _Error3);
545
- var _super3 = _createSuper(FetchError);
546
- function FetchError(cause, msg) {
304
+ var BytescaleApiError = /*#__PURE__*/function (_Error2) {
305
+ _inherits(BytescaleApiError, _Error2);
306
+ var _super2 = _createSuper(BytescaleApiError);
307
+ function BytescaleApiError(response) {
547
308
  var _this8;
548
- _classCallCheck(this, FetchError);
549
- _this8 = _super3.call(this, msg);
550
- _this8.cause = cause;
551
- _this8.name = "FetchError";
309
+ runtime_classCallCheck(this, BytescaleApiError);
310
+ _this8 = _super2.call(this, response.error.message);
311
+ _this8.name = "BytescaleApiError";
312
+ _this8.errorCode = response.error.code;
313
+ _this8.details = response.error.details;
552
314
  return _this8;
553
315
  }
554
- return _createClass(FetchError);
555
- }( /*#__PURE__*/_wrapNativeSuper(Error));
556
- var RequiredError = /*#__PURE__*/function (_Error4) {
557
- _inherits(RequiredError, _Error4);
558
- var _super4 = _createSuper(RequiredError);
559
- function RequiredError(field, msg) {
560
- var _this9;
561
- _classCallCheck(this, RequiredError);
562
- _this9 = _super4.call(this, msg);
563
- _this9.field = field;
564
- _this9.name = "RequiredError";
565
- return _this9;
566
- }
567
- return _createClass(RequiredError);
316
+ return runtime_createClass(BytescaleApiError);
568
317
  }( /*#__PURE__*/_wrapNativeSuper(Error));
569
318
  function querystring(params) {
570
319
  var prefix = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : "";
@@ -597,22 +346,15 @@ function querystringSingleKey(key, value) {
597
346
  }
598
347
  var JSONApiResponse = /*#__PURE__*/function () {
599
348
  function JSONApiResponse(raw) {
600
- var transformer = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : function (jsonValue) {
601
- return jsonValue;
602
- };
603
- _classCallCheck(this, JSONApiResponse);
349
+ runtime_classCallCheck(this, JSONApiResponse);
604
350
  this.raw = raw;
605
- this.transformer = transformer;
606
351
  }
607
- _createClass(JSONApiResponse, [{
352
+ runtime_createClass(JSONApiResponse, [{
608
353
  key: "value",
609
354
  value: function value() {
610
355
  try {
611
- var _this11 = this;
612
- var _transformer2 = _this11.transformer;
613
- return _await(_this11.raw.json(), function (_this10$raw$json) {
614
- return _transformer2.call(_this11, _this10$raw$json);
615
- });
356
+ var _this10 = this;
357
+ return _await(_this10.raw.json());
616
358
  } catch (e) {
617
359
  return Promise.reject(e);
618
360
  }
@@ -622,10 +364,10 @@ var JSONApiResponse = /*#__PURE__*/function () {
622
364
  }();
623
365
  var VoidApiResponse = /*#__PURE__*/function () {
624
366
  function VoidApiResponse(raw) {
625
- _classCallCheck(this, VoidApiResponse);
367
+ runtime_classCallCheck(this, VoidApiResponse);
626
368
  this.raw = raw;
627
369
  }
628
- _createClass(VoidApiResponse, [{
370
+ runtime_createClass(VoidApiResponse, [{
629
371
  key: "value",
630
372
  value: function value() {
631
373
  return _await(undefined);
@@ -635,10 +377,10 @@ var VoidApiResponse = /*#__PURE__*/function () {
635
377
  }();
636
378
  var BinaryResult = /*#__PURE__*/function () {
637
379
  function BinaryResult(raw) {
638
- _classCallCheck(this, BinaryResult);
380
+ runtime_classCallCheck(this, BinaryResult);
639
381
  this.raw = raw;
640
382
  }
641
- _createClass(BinaryResult, [{
383
+ runtime_createClass(BinaryResult, [{
642
384
  key: "stream",
643
385
  value: function stream() {
644
386
  if (this.raw.bodyUsed) {
@@ -653,8 +395,8 @@ var BinaryResult = /*#__PURE__*/function () {
653
395
  key: "text",
654
396
  value: function text() {
655
397
  try {
656
- var _this13 = this;
657
- return _await(_this13.raw.text());
398
+ var _this12 = this;
399
+ return _await(_this12.raw.text());
658
400
  } catch (e) {
659
401
  return Promise.reject(e);
660
402
  }
@@ -663,8 +405,8 @@ var BinaryResult = /*#__PURE__*/function () {
663
405
  key: "blob",
664
406
  value: function blob() {
665
407
  try {
666
- var _this15 = this;
667
- return _await(_this15.raw.blob());
408
+ var _this14 = this;
409
+ return _await(_this14.raw.blob());
668
410
  } catch (e) {
669
411
  return Promise.reject(e);
670
412
  }
@@ -673,8 +415,8 @@ var BinaryResult = /*#__PURE__*/function () {
673
415
  key: "json",
674
416
  value: function json() {
675
417
  try {
676
- var _this17 = this;
677
- return _await(_this17.raw.json());
418
+ var _this16 = this;
419
+ return _await(_this16.raw.json());
678
420
  } catch (e) {
679
421
  return Promise.reject(e);
680
422
  }
@@ -682,7 +424,7 @@ var BinaryResult = /*#__PURE__*/function () {
682
424
  }]);
683
425
  return BinaryResult;
684
426
  }();
685
- ;// CONCATENATED MODULE: ./src/generated/apis/FileApi.ts
427
+ ;// CONCATENATED MODULE: ./src/public/shared/generated/apis/FileApi.ts
686
428
  function FileApi_typeof(obj) { "@babel/helpers - typeof"; return FileApi_typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (obj) { return typeof obj; } : function (obj) { return obj && "function" == typeof Symbol && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }, FileApi_typeof(obj); }
687
429
  function FileApi_await(value, then, direct) {
688
430
  if (direct) {
@@ -977,7 +719,7 @@ var FileApi = /*#__PURE__*/function (_runtime$BaseAPI) {
977
719
  }]);
978
720
  return FileApi;
979
721
  }(BaseAPI);
980
- ;// CONCATENATED MODULE: ./src/generated/apis/FolderApi.ts
722
+ ;// CONCATENATED MODULE: ./src/public/shared/generated/apis/FolderApi.ts
981
723
  function FolderApi_typeof(obj) { "@babel/helpers - typeof"; return FolderApi_typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (obj) { return typeof obj; } : function (obj) { return obj && "function" == typeof Symbol && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }, FolderApi_typeof(obj); }
982
724
  function FolderApi_await(value, then, direct) {
983
725
  if (direct) {
@@ -1237,7 +979,7 @@ var FolderApi = /*#__PURE__*/function (_runtime$BaseAPI) {
1237
979
  }]);
1238
980
  return FolderApi;
1239
981
  }(BaseAPI);
1240
- ;// CONCATENATED MODULE: ./src/generated/apis/JobApi.ts
982
+ ;// CONCATENATED MODULE: ./src/public/shared/generated/apis/JobApi.ts
1241
983
  function JobApi_typeof(obj) { "@babel/helpers - typeof"; return JobApi_typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (obj) { return typeof obj; } : function (obj) { return obj && "function" == typeof Symbol && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }, JobApi_typeof(obj); }
1242
984
  function JobApi_await(value, then, direct) {
1243
985
  if (direct) {
@@ -1372,7 +1114,7 @@ var JobApi = /*#__PURE__*/function (_runtime$BaseAPI) {
1372
1114
  }]);
1373
1115
  return JobApi;
1374
1116
  }(BaseAPI);
1375
- ;// CONCATENATED MODULE: ./src/generated/apis/UploadApi.ts
1117
+ ;// CONCATENATED MODULE: ./src/public/shared/generated/apis/UploadApi.ts
1376
1118
  function UploadApi_typeof(obj) { "@babel/helpers - typeof"; return UploadApi_typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (obj) { return typeof obj; } : function (obj) { return obj && "function" == typeof Symbol && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }, UploadApi_typeof(obj); }
1377
1119
  function UploadApi_await(value, then, direct) {
1378
1120
  if (direct) {
@@ -1560,325 +1302,170 @@ var UploadApi = /*#__PURE__*/function (_runtime$BaseAPI) {
1560
1302
  }]);
1561
1303
  return UploadApi;
1562
1304
  }(BaseAPI);
1563
- ;// CONCATENATED MODULE: ./src/generated/apis/index.ts
1305
+ ;// CONCATENATED MODULE: ./src/public/shared/generated/apis/index.ts
1564
1306
  /* tslint:disable */
1565
1307
  /* eslint-disable */
1566
1308
 
1567
1309
 
1568
1310
 
1569
1311
 
1570
- ;// CONCATENATED MODULE: ./src/generated/index.ts
1312
+ ;// CONCATENATED MODULE: ./src/public/shared/generated/index.ts
1571
1313
  /* tslint:disable */
1572
1314
  /* eslint-disable */
1573
1315
 
1574
1316
 
1575
1317
 
1576
- ;// CONCATENATED MODULE: ./src/uploads/NodeUtils.ts
1577
- function NodeUtils_typeof(obj) { "@babel/helpers - typeof"; return NodeUtils_typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (obj) { return typeof obj; } : function (obj) { return obj && "function" == typeof Symbol && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }, NodeUtils_typeof(obj); }
1578
- function NodeUtils_await(value, then, direct) {
1579
- if (direct) {
1580
- return then ? then(value) : value;
1581
- }
1582
- if (!value || !value.then) {
1583
- value = Promise.resolve(value);
1584
- }
1585
- return then ? value.then(then) : value;
1586
- }
1587
- function NodeUtils_classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
1588
- function NodeUtils_defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, NodeUtils_toPropertyKey(descriptor.key), descriptor); } }
1589
- function NodeUtils_createClass(Constructor, protoProps, staticProps) { if (protoProps) NodeUtils_defineProperties(Constructor.prototype, protoProps); if (staticProps) NodeUtils_defineProperties(Constructor, staticProps); Object.defineProperty(Constructor, "prototype", { writable: false }); return Constructor; }
1590
- function NodeUtils_toPropertyKey(arg) { var key = NodeUtils_toPrimitive(arg, "string"); return NodeUtils_typeof(key) === "symbol" ? key : String(key); }
1591
- function NodeUtils_toPrimitive(input, hint) { if (NodeUtils_typeof(input) !== "object" || input === null) return input; var prim = input[Symbol.toPrimitive]; if (prim !== undefined) { var res = prim.call(input, hint || "default"); if (NodeUtils_typeof(res) !== "object") return res; throw new TypeError("@@toPrimitive must return a primitive value."); } return (hint === "string" ? String : Number)(input); }
1318
+ ;// CONCATENATED MODULE: ./src/public/shared/CommonTypes.ts
1592
1319
  /**
1593
- * Provides access to Node.js built-in libraries. Should only be called when we're certain we're running in Node.js.
1594
- *
1595
- * We import lazily to support browsers, which don't have these modules, but also won't call these methods so won't trigger the imports.
1320
+ * Workaround for tsc aliases, where we cannot export implementation-less modules in our dists.
1596
1321
  */
1597
- var NodeUtils = /*#__PURE__*/function () {
1598
- function NodeUtils() {
1599
- NodeUtils_classCallCheck(this, NodeUtils);
1600
- }
1601
- NodeUtils_createClass(NodeUtils, null, [{
1602
- key: "createStream",
1603
- value: function createStream() {
1604
- try {
1605
- return NodeUtils_await(__webpack_require__.e(/* import() */ "_70b2").then(__webpack_require__.t.bind(__webpack_require__, "?70b2", 23)), function (_import) {
1606
- var streamModule = _import["default"];
1607
- var Readable = streamModule.Readable;
1608
- var readable = new Readable();
1609
- readable._read = function () {}; // _read is required but you can noop it
1610
- return readable;
1611
- });
1612
- } catch (e) {
1613
- return Promise.reject(e);
1614
- }
1615
- }
1616
- }, {
1617
- key: "createBlob",
1618
- value: function createBlob(sources, options) {
1619
- try {
1620
- return NodeUtils_await(__webpack_require__.e(/* import() */ "_7392").then(__webpack_require__.t.bind(__webpack_require__, "?7392", 23)), function (_import2) {
1621
- var bufferModule = _import2["default"];
1622
- var B = bufferModule.Blob;
1623
- return new B(sources, options);
1624
- });
1625
- } catch (e) {
1626
- return Promise.reject(e);
1627
- }
1628
- }
1629
- }]);
1630
- return NodeUtils;
1631
- }();
1632
- ;// CONCATENATED MODULE: ./src/uploads/ChunkedStream.ts
1633
- function ChunkedStream_typeof(obj) { "@babel/helpers - typeof"; return ChunkedStream_typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (obj) { return typeof obj; } : function (obj) { return obj && "function" == typeof Symbol && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }, ChunkedStream_typeof(obj); }
1634
- function ChunkedStream_invoke(body, then) {
1635
- var result = body();
1636
- if (result && result.then) {
1637
- return result.then(then);
1638
- }
1639
- return then(result);
1322
+ var CommonTypesNoOp = false;
1323
+ ;// CONCATENATED MODULE: ./src/private/TypeUtils.ts
1324
+ function assertUnreachable(x) {
1325
+ throw new Error("Didn't expect to get here: ".concat(JSON.stringify(x)));
1326
+ }
1327
+ function isDefinedEntry(object) {
1328
+ return object[1] !== undefined && object[1] !== null;
1640
1329
  }
1330
+ ;// CONCATENATED MODULE: ./src/public/shared/UrlBuilder.ts
1331
+ function UrlBuilder_typeof(obj) { "@babel/helpers - typeof"; return UrlBuilder_typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (obj) { return typeof obj; } : function (obj) { return obj && "function" == typeof Symbol && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }, UrlBuilder_typeof(obj); }
1641
1332
  function _slicedToArray(arr, i) { return _arrayWithHoles(arr) || _iterableToArrayLimit(arr, i) || _unsupportedIterableToArray(arr, i) || _nonIterableRest(); }
1642
1333
  function _nonIterableRest() { throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); }
1643
- function _unsupportedIterableToArray(o, minLen) { if (!o) return; if (typeof o === "string") return _arrayLikeToArray(o, minLen); var n = Object.prototype.toString.call(o).slice(8, -1); if (n === "Object" && o.constructor) n = o.constructor.name; if (n === "Map" || n === "Set") return Array.from(o); if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen); }
1644
- function _arrayLikeToArray(arr, len) { if (len == null || len > arr.length) len = arr.length; for (var i = 0, arr2 = new Array(len); i < len; i++) { arr2[i] = arr[i]; } return arr2; }
1645
1334
  function _iterableToArrayLimit(arr, i) { var _i = null == arr ? null : "undefined" != typeof Symbol && arr[Symbol.iterator] || arr["@@iterator"]; if (null != _i) { var _s, _e, _x, _r, _arr = [], _n = !0, _d = !1; try { if (_x = (_i = _i.call(arr)).next, 0 === i) { if (Object(_i) !== _i) return; _n = !1; } else for (; !(_n = (_s = _x.call(_i)).done) && (_arr.push(_s.value), _arr.length !== i); _n = !0) { ; } } catch (err) { _d = !0, _e = err; } finally { try { if (!_n && null != _i["return"] && (_r = _i["return"](), Object(_r) !== _r)) return; } finally { if (_d) throw _e; } } return _arr; } }
1646
1335
  function _arrayWithHoles(arr) { if (Array.isArray(arr)) return arr; }
1647
- function ChunkedStream_await(value, then, direct) {
1648
- if (direct) {
1649
- return then ? then(value) : value;
1650
- }
1651
- if (!value || !value.then) {
1652
- value = Promise.resolve(value);
1653
- }
1654
- return then ? value.then(then) : value;
1655
- }
1656
- function ChunkedStream_classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
1657
- function ChunkedStream_defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, ChunkedStream_toPropertyKey(descriptor.key), descriptor); } }
1658
- function ChunkedStream_createClass(Constructor, protoProps, staticProps) { if (protoProps) ChunkedStream_defineProperties(Constructor.prototype, protoProps); if (staticProps) ChunkedStream_defineProperties(Constructor, staticProps); Object.defineProperty(Constructor, "prototype", { writable: false }); return Constructor; }
1659
- function ChunkedStream_toPropertyKey(arg) { var key = ChunkedStream_toPrimitive(arg, "string"); return ChunkedStream_typeof(key) === "symbol" ? key : String(key); }
1660
- function ChunkedStream_toPrimitive(input, hint) { if (ChunkedStream_typeof(input) !== "object" || input === null) return input; var prim = input[Symbol.toPrimitive]; if (prim !== undefined) { var res = prim.call(input, hint || "default"); if (ChunkedStream_typeof(res) !== "object") return res; throw new TypeError("@@toPrimitive must return a primitive value."); } return (hint === "string" ? String : Number)(input); }
1336
+ function _toConsumableArray(arr) { return _arrayWithoutHoles(arr) || _iterableToArray(arr) || _unsupportedIterableToArray(arr) || _nonIterableSpread(); }
1337
+ function _nonIterableSpread() { throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); }
1338
+ function _unsupportedIterableToArray(o, minLen) { if (!o) return; if (typeof o === "string") return _arrayLikeToArray(o, minLen); var n = Object.prototype.toString.call(o).slice(8, -1); if (n === "Object" && o.constructor) n = o.constructor.name; if (n === "Map" || n === "Set") return Array.from(o); if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen); }
1339
+ function _iterableToArray(iter) { if (typeof Symbol !== "undefined" && iter[Symbol.iterator] != null || iter["@@iterator"] != null) return Array.from(iter); }
1340
+ function _arrayWithoutHoles(arr) { if (Array.isArray(arr)) return _arrayLikeToArray(arr); }
1341
+ function _arrayLikeToArray(arr, len) { if (len == null || len > arr.length) len = arr.length; for (var i = 0, arr2 = new Array(len); i < len; i++) { arr2[i] = arr[i]; } return arr2; }
1342
+ function UrlBuilder_classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
1343
+ function UrlBuilder_defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, UrlBuilder_toPropertyKey(descriptor.key), descriptor); } }
1344
+ function UrlBuilder_createClass(Constructor, protoProps, staticProps) { if (protoProps) UrlBuilder_defineProperties(Constructor.prototype, protoProps); if (staticProps) UrlBuilder_defineProperties(Constructor, staticProps); Object.defineProperty(Constructor, "prototype", { writable: false }); return Constructor; }
1345
+ function UrlBuilder_toPropertyKey(arg) { var key = UrlBuilder_toPrimitive(arg, "string"); return UrlBuilder_typeof(key) === "symbol" ? key : String(key); }
1346
+ function UrlBuilder_toPrimitive(input, hint) { if (UrlBuilder_typeof(input) !== "object" || input === null) return input; var prim = input[Symbol.toPrimitive]; if (prim !== undefined) { var res = prim.call(input, hint || "default"); if (UrlBuilder_typeof(res) !== "object") return res; throw new TypeError("@@toPrimitive must return a primitive value."); } return (hint === "string" ? String : Number)(input); }
1661
1347
 
1662
- var ChunkedStream = /*#__PURE__*/function () {
1663
- function ChunkedStream(source) {
1664
- ChunkedStream_classCallCheck(this, ChunkedStream);
1665
- this.source = source;
1666
- this.buffer = Buffer.alloc(0);
1667
- this.isSourceFullyConsumed = false; // true if the source stream indicates it has finished.
1668
- this.isFinishedConsuming = false; // true if _we_ indicate we have finished reading all we want from the stream.
1669
- this.resolver = undefined;
1348
+
1349
+ var UrlBuilder = /*#__PURE__*/function () {
1350
+ function UrlBuilder(config) {
1351
+ UrlBuilder_classCallCheck(this, UrlBuilder);
1352
+ var _a;
1353
+ this.cdnUrl = (_a = config === null || config === void 0 ? void 0 : config.cdnUrl) !== null && _a !== void 0 ? _a : BytescaleApiClientConfigResolver.defaultCdnUrl;
1670
1354
  }
1671
1355
  /**
1672
- * If the source stream is larger than the 'size' the user is consuming (i.e. they're only wanting to upload a subset
1673
- * of the stream) then the stream won't be resolved by the 'end' event inside 'runChunkPipeline', so calling this
1674
- * method is necessary.
1356
+ * Builds a URL to either a raw file or a transformed file.
1357
+ *
1358
+ * Example 1) Raw file:
1359
+ *
1360
+ * new UrlBuilder().url({ accountId: "1234abc", filePath: "/example.jpg" })
1361
+ *
1362
+ * Example 2) Image resized to 500x500:
1363
+ *
1364
+ * new UrlBuilder().url({ accountId: "1234abc", filePath: "/example.jpg", transformation: { type: "image", params: { w: 500, h: 500, fit: "crop" } } })
1365
+ *
1366
+ * Example 3) Image resized to 500x500, which is privately accessible (i.e. requires 'AuthManager.beginAuthSession' before it can be accessed):
1367
+ *
1368
+ * new UrlBuilder().url({ accountId: "1234abc", filePath: "/example.jpg", transformation: { type: "image", params: { w: 500, h: 500, fit: "crop" } }, auth: true })
1675
1369
  */
1676
- ChunkedStream_createClass(ChunkedStream, [{
1677
- key: "finishedConsuming",
1678
- value: function finishedConsuming() {
1679
- this.isFinishedConsuming = true;
1680
- if (this.resolver !== undefined) {
1681
- this.resolver();
1682
- }
1370
+ UrlBuilder_createClass(UrlBuilder, [{
1371
+ key: "url",
1372
+ value: function url(params) {
1373
+ var _a;
1374
+ return ((_a = params.options) === null || _a === void 0 ? void 0 : _a.transformation) === undefined ? this.raw(params) : this.transformation(params, params.options.transformation);
1683
1375
  }
1684
- /**
1685
- * Promise resolves when the entire stream has finished processing, or an error occurs.
1686
- * You must call 'take' a sufficient number of times after calling this method in order for this promise to resolve.
1687
- */
1688
1376
  }, {
1689
- key: "runChunkPipeline",
1690
- value: function runChunkPipeline() {
1691
- try {
1692
- var _this2 = this;
1693
- return ChunkedStream_await(new Promise(function (resolve, reject) {
1694
- _this2.resolver = resolve;
1695
- var onError = function onError(error) {
1696
- removeListeners();
1697
- reject(error);
1698
- };
1699
- var onEnd = function onEnd() {
1700
- _this2.isSourceFullyConsumed = true;
1701
- removeListeners();
1702
- resolve();
1703
- };
1704
- var onData = function onData(buffer) {
1705
- try {
1706
- if (_this2.isFinishedConsuming) {
1707
- return;
1708
- }
1709
- if (_this2.consumer === undefined) {
1710
- console.warn("Stream yielded data while paused. The data will be buffered, but excessive buffering can cause memory issues.");
1711
- _this2.buffer = Buffer.concat([_this2.buffer, buffer]);
1712
- return;
1713
- }
1714
- if (_this2.consumer.bytesRemaining <= 0) {
1715
- throw new Error("Consumer requires zero bytes, so should not be consuming from the stream.");
1716
- }
1717
- if (_this2.buffer.byteLength > 0) {
1718
- throw new Error("Buffer was expected to be empty (as it should have been flushed to the consumer when '.take' was called).");
1719
- }
1720
- var splitResult = _this2.splitBuffer(buffer, _this2.consumer.bytesRemaining);
1721
- if (splitResult === undefined) {
1722
- return; // Received empty data.
1723
- }
1724
-
1725
- var _splitResult = _slicedToArray(splitResult, 2),
1726
- consumed = _splitResult[0],
1727
- remaining = _splitResult[1];
1728
- _this2.buffer = remaining;
1729
- _this2.consumer.bytesRemaining -= consumed.byteLength;
1730
- _this2.consumer.stream.push(consumed);
1731
- if (_this2.consumer.bytesRemaining === 0) {
1732
- _this2.finishStream(_this2.consumer.stream);
1733
- _this2.consumer = undefined;
1734
- _this2.source.pause();
1735
- }
1736
- } catch (e) {
1737
- removeListeners();
1738
- reject(e);
1739
- }
1740
- };
1741
- var removeListeners = function removeListeners() {
1742
- _this2.source.removeListener("data", onData);
1743
- _this2.source.removeListener("error", onError);
1744
- _this2.source.removeListener("end", onEnd);
1745
- };
1746
- _this2.source.on("data", onData);
1747
- _this2.source.on("error", onError);
1748
- _this2.source.on("end", onEnd);
1749
- _this2.source.pause(); // Resumed when 'take' is called.
1750
- }));
1751
- } catch (e) {
1752
- return Promise.reject(e);
1753
- }
1377
+ key: "raw",
1378
+ value: function raw(params) {
1379
+ var _a;
1380
+ var baseUrl = this.getBaseUrl(params, "raw");
1381
+ var commonParams = this.getCommonQueryParams((_a = params.options) !== null && _a !== void 0 ? _a : {});
1382
+ return this.addQueryParams(baseUrl, commonParams);
1754
1383
  }
1755
- /**
1756
- * Only call 'take' after the previously returned stream has been fully consumed.
1757
- */
1758
1384
  }, {
1759
- key: "take",
1760
- value: function take(bytes) {
1761
- try {
1762
- var _exit2 = false;
1763
- var _this4 = this;
1764
- var _a;
1765
- if (_this4.consumer !== undefined) {
1766
- throw new Error("The stream from the previous 'take' call must be fully consumed before calling 'take' again.");
1767
- }
1768
- return ChunkedStream_invoke(function () {
1769
- if (bytes <= 0) {
1770
- _exit2 = true;
1771
- return ChunkedStream_await(_this4.emptyStream());
1772
- }
1773
- }, function (_result) {
1774
- return _exit2 ? _result : ChunkedStream_await(NodeUtils.createStream(), function (readable) {
1775
- var consumedFromBuffer = _this4.consumeFromBuffer(bytes);
1776
- var consumedFromBufferLength = (_a = consumedFromBuffer === null || consumedFromBuffer === void 0 ? void 0 : consumedFromBuffer.length) !== null && _a !== void 0 ? _a : 0;
1777
- var bytesToConsumeFromStream = bytes - consumedFromBufferLength;
1778
- if (consumedFromBuffer !== undefined) {
1779
- readable.push(consumedFromBuffer);
1780
- }
1781
- if (bytesToConsumeFromStream > 0) {
1782
- if (_this4.isSourceFullyConsumed) {
1783
- throw new Error("Stream finished processing earlier than expected. The \"size\" parameter is likely larger than the stream's actual contents.");
1784
- }
1785
- _this4.consumer = {
1786
- bytesRemaining: bytesToConsumeFromStream,
1787
- stream: readable
1788
- };
1789
- _this4.source.resume();
1790
- } else {
1791
- _this4.finishStream(readable);
1792
- }
1793
- return readable;
1794
- });
1795
- });
1796
- } catch (e) {
1797
- return Promise.reject(e);
1798
- }
1385
+ key: "transformation",
1386
+ value: function transformation(params, trans) {
1387
+ var _a;
1388
+ var baseUrl = this.getBaseUrl(params, trans.type === "preset" ? trans.preset : trans.type);
1389
+ var transParams = this.getTransformationParams(trans, {
1390
+ cachePermanently: "cache_perm"
1391
+ });
1392
+ var commonParams = this.getCommonQueryParams((_a = params.options) !== null && _a !== void 0 ? _a : {});
1393
+ return this.addQueryParams(baseUrl, [].concat(_toConsumableArray(commonParams), _toConsumableArray(transParams)));
1799
1394
  }
1800
1395
  }, {
1801
- key: "consumeFromBuffer",
1802
- value: function consumeFromBuffer(bytes) {
1803
- var splitResult = this.splitBuffer(this.buffer, bytes);
1804
- if (splitResult === undefined) {
1805
- return undefined;
1806
- }
1807
- var _splitResult2 = _slicedToArray(splitResult, 2),
1808
- consumed = _splitResult2[0],
1809
- remaining = _splitResult2[1];
1810
- this.buffer = remaining;
1811
- return consumed;
1396
+ key: "getBaseUrl",
1397
+ value: function getBaseUrl(params, prefix) {
1398
+ return "".concat(this.cdnUrl, "/").concat(params.accountId, "/").concat(prefix).concat(params.filePath);
1812
1399
  }
1813
1400
  }, {
1814
- key: "splitBuffer",
1815
- value: function splitBuffer(buffer, maxBytes) {
1816
- if (buffer.byteLength === 0) {
1817
- return undefined;
1818
- }
1819
- var bytesToConsume = Math.min(maxBytes, buffer.byteLength);
1820
- if (bytesToConsume === buffer.byteLength) {
1821
- return [buffer, Buffer.alloc(0)]; // Optimization
1822
- }
1823
-
1824
- var consumed = buffer.subarray(0, bytesToConsume);
1825
- var remaining = buffer.subarray(bytesToConsume);
1826
- return [consumed, remaining];
1401
+ key: "getCommonQueryParams",
1402
+ value: function getCommonQueryParams(params) {
1403
+ return this.makeQueryParams(["auth", "cache", "cacheTtl", "version", "forceDownloadPrompt"], {
1404
+ cacheTtl: "cache_ttl",
1405
+ forceDownloadPrompt: "download"
1406
+ })(params);
1827
1407
  }
1828
1408
  }, {
1829
- key: "emptyStream",
1830
- value: function emptyStream() {
1831
- try {
1832
- var _this6 = this;
1833
- return ChunkedStream_await(NodeUtils.createStream(), function (readable) {
1834
- _this6.finishStream(readable);
1835
- return readable;
1409
+ key: "makeQueryParams",
1410
+ value: function makeQueryParams(keys, keyOverrides) {
1411
+ return function (data) {
1412
+ var result = [];
1413
+ keys.forEach(function (key) {
1414
+ var _a;
1415
+ var value = data[key];
1416
+ if (value !== undefined) {
1417
+ result.push([(_a = keyOverrides[key]) !== null && _a !== void 0 ? _a : key, value.toString()]);
1418
+ }
1836
1419
  });
1837
- } catch (e) {
1838
- return Promise.reject(e);
1839
- }
1420
+ return result;
1421
+ };
1840
1422
  }
1841
1423
  }, {
1842
- key: "finishStream",
1843
- value: function finishStream(readable) {
1844
- readable.push(null);
1424
+ key: "getTransformationParams",
1425
+ value: function getTransformationParams(trans, keyRewrites) {
1426
+ if (trans.params === undefined) {
1427
+ return [];
1428
+ }
1429
+ var serializeObj = function serializeObj(obj) {
1430
+ return Object.entries(obj).filter(isDefinedEntry).map(function (_ref) {
1431
+ var _ref2 = _slicedToArray(_ref, 2),
1432
+ key = _ref2[0],
1433
+ value = _ref2[1];
1434
+ var _a;
1435
+ return [(_a = keyRewrites[key]) !== null && _a !== void 0 ? _a : key, value.toString()];
1436
+ });
1437
+ };
1438
+ return Array.isArray(trans.params) ? trans.params.flatMap(serializeObj) : serializeObj(trans.params);
1439
+ }
1440
+ }, {
1441
+ key: "addQueryParams",
1442
+ value: function addQueryParams(baseUrl, params) {
1443
+ if (params.length === 0) {
1444
+ return baseUrl;
1445
+ }
1446
+ return "".concat(baseUrl, "?").concat(params.map(function (_ref3) {
1447
+ var _ref4 = _slicedToArray(_ref3, 2),
1448
+ key = _ref4[0],
1449
+ value = _ref4[1];
1450
+ return "".concat(encodeURIComponent(key), "=").concat(encodeURIComponent(value));
1451
+ }).join("&"));
1845
1452
  }
1846
1453
  }]);
1847
- return ChunkedStream;
1454
+ return UrlBuilder;
1848
1455
  }();
1849
- ;// CONCATENATED MODULE: ./src/uploads/UploadModel.ts
1850
- function UploadModel_typeof(obj) { "@babel/helpers - typeof"; return UploadModel_typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (obj) { return typeof obj; } : function (obj) { return obj && "function" == typeof Symbol && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }, UploadModel_typeof(obj); }
1851
- function UploadModel_defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, UploadModel_toPropertyKey(descriptor.key), descriptor); } }
1852
- function UploadModel_createClass(Constructor, protoProps, staticProps) { if (protoProps) UploadModel_defineProperties(Constructor.prototype, protoProps); if (staticProps) UploadModel_defineProperties(Constructor, staticProps); Object.defineProperty(Constructor, "prototype", { writable: false }); return Constructor; }
1853
- function UploadModel_toPropertyKey(arg) { var key = UploadModel_toPrimitive(arg, "string"); return UploadModel_typeof(key) === "symbol" ? key : String(key); }
1854
- function UploadModel_toPrimitive(input, hint) { if (UploadModel_typeof(input) !== "object" || input === null) return input; var prim = input[Symbol.toPrimitive]; if (prim !== undefined) { var res = prim.call(input, hint || "default"); if (UploadModel_typeof(res) !== "object") return res; throw new TypeError("@@toPrimitive must return a primitive value."); } return (hint === "string" ? String : Number)(input); }
1855
- function UploadModel_classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
1856
- function UploadModel_inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function"); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, writable: true, configurable: true } }); Object.defineProperty(subClass, "prototype", { writable: false }); if (superClass) UploadModel_setPrototypeOf(subClass, superClass); }
1857
- function UploadModel_createSuper(Derived) { var hasNativeReflectConstruct = UploadModel_isNativeReflectConstruct(); return function _createSuperInternal() { var Super = UploadModel_getPrototypeOf(Derived), result; if (hasNativeReflectConstruct) { var NewTarget = UploadModel_getPrototypeOf(this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return UploadModel_possibleConstructorReturn(this, result); }; }
1858
- function UploadModel_possibleConstructorReturn(self, call) { if (call && (UploadModel_typeof(call) === "object" || typeof call === "function")) { return call; } else if (call !== void 0) { throw new TypeError("Derived constructors may only return object or undefined"); } return UploadModel_assertThisInitialized(self); }
1859
- function UploadModel_assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self; }
1860
- function UploadModel_wrapNativeSuper(Class) { var _cache = typeof Map === "function" ? new Map() : undefined; UploadModel_wrapNativeSuper = function _wrapNativeSuper(Class) { if (Class === null || !UploadModel_isNativeFunction(Class)) return Class; if (typeof Class !== "function") { throw new TypeError("Super expression must either be null or a function"); } if (typeof _cache !== "undefined") { if (_cache.has(Class)) return _cache.get(Class); _cache.set(Class, Wrapper); } function Wrapper() { return UploadModel_construct(Class, arguments, UploadModel_getPrototypeOf(this).constructor); } Wrapper.prototype = Object.create(Class.prototype, { constructor: { value: Wrapper, enumerable: false, writable: true, configurable: true } }); return UploadModel_setPrototypeOf(Wrapper, Class); }; return UploadModel_wrapNativeSuper(Class); }
1861
- function UploadModel_construct(Parent, args, Class) { if (UploadModel_isNativeReflectConstruct()) { UploadModel_construct = Reflect.construct.bind(); } else { UploadModel_construct = function _construct(Parent, args, Class) { var a = [null]; a.push.apply(a, args); var Constructor = Function.bind.apply(Parent, a); var instance = new Constructor(); if (Class) UploadModel_setPrototypeOf(instance, Class.prototype); return instance; }; } return UploadModel_construct.apply(null, arguments); }
1862
- function UploadModel_isNativeReflectConstruct() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); return true; } catch (e) { return false; } }
1863
- function UploadModel_isNativeFunction(fn) { return Function.toString.call(fn).indexOf("[native code]") !== -1; }
1864
- function UploadModel_setPrototypeOf(o, p) { UploadModel_setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return UploadModel_setPrototypeOf(o, p); }
1865
- function UploadModel_getPrototypeOf(o) { UploadModel_getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf.bind() : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return UploadModel_getPrototypeOf(o); }
1866
- var CancelledError = /*#__PURE__*/function (_Error) {
1867
- UploadModel_inherits(CancelledError, _Error);
1868
- var _super = UploadModel_createSuper(CancelledError);
1869
- function CancelledError(msg) {
1870
- var _this;
1871
- UploadModel_classCallCheck(this, CancelledError);
1872
- _this = _super.call(this, msg);
1873
- _this.msg = msg;
1874
- _this.name = "CancelledError";
1875
- return _this;
1876
- }
1877
- return UploadModel_createClass(CancelledError);
1878
- }( /*#__PURE__*/UploadModel_wrapNativeSuper(Error));
1879
- ;// CONCATENATED MODULE: ./src/uploads/UploadManager.ts
1880
- function UploadManager_typeof(obj) { "@babel/helpers - typeof"; return UploadManager_typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (obj) { return typeof obj; } : function (obj) { return obj && "function" == typeof Symbol && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }, UploadManager_typeof(obj); }
1881
- function UploadManager_async(f) {
1456
+ ;// CONCATENATED MODULE: ./src/public/shared/UrlBuilderTypes.ts
1457
+ /**
1458
+ * Workaround for tsc aliases, where we cannot export implementation-less modules in our dists.
1459
+ */
1460
+ var UrlBuilderTypesNoOp = false;
1461
+ ;// CONCATENATED MODULE: ./src/public/shared/index.ts
1462
+
1463
+
1464
+
1465
+
1466
+ ;// CONCATENATED MODULE: ./src/private/UploadManagerBase.ts
1467
+ function UploadManagerBase_typeof(obj) { "@babel/helpers - typeof"; return UploadManagerBase_typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (obj) { return typeof obj; } : function (obj) { return obj && "function" == typeof Symbol && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }, UploadManagerBase_typeof(obj); }
1468
+ function _async(f) {
1882
1469
  return function () {
1883
1470
  for (var args = [], i = 0; i < arguments.length; i++) {
1884
1471
  args[i] = arguments[i];
@@ -1890,23 +1477,10 @@ function UploadManager_async(f) {
1890
1477
  }
1891
1478
  };
1892
1479
  }
1893
- function UploadManager_empty() {}
1894
- function _awaitIgnored(value, direct) {
1895
- if (!direct) {
1896
- return value && value.then ? value.then(UploadManager_empty) : Promise.resolve();
1897
- }
1898
- }
1899
- function UploadManager_invoke(body, then) {
1900
- var result = body();
1901
- if (result && result.then) {
1902
- return result.then(then);
1903
- }
1904
- return then(result);
1905
- }
1906
1480
  function _invokeIgnored(body) {
1907
1481
  var result = body();
1908
1482
  if (result && result.then) {
1909
- return result.then(UploadManager_empty);
1483
+ return result.then(UploadManagerBase_empty);
1910
1484
  }
1911
1485
  }
1912
1486
  function _settle(pact, state, value) {
@@ -2060,16 +1634,22 @@ function _for(test, update, body) {
2060
1634
  }
2061
1635
  function _continueIgnored(value) {
2062
1636
  if (value && value.then) {
2063
- return value.then(UploadManager_empty);
1637
+ return value.then(UploadManagerBase_empty);
2064
1638
  }
2065
1639
  }
2066
- function _toConsumableArray(arr) { return _arrayWithoutHoles(arr) || _iterableToArray(arr) || UploadManager_unsupportedIterableToArray(arr) || _nonIterableSpread(); }
2067
- function _nonIterableSpread() { throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); }
2068
- function UploadManager_unsupportedIterableToArray(o, minLen) { if (!o) return; if (typeof o === "string") return UploadManager_arrayLikeToArray(o, minLen); var n = Object.prototype.toString.call(o).slice(8, -1); if (n === "Object" && o.constructor) n = o.constructor.name; if (n === "Map" || n === "Set") return Array.from(o); if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return UploadManager_arrayLikeToArray(o, minLen); }
2069
- function _iterableToArray(iter) { if (typeof Symbol !== "undefined" && iter[Symbol.iterator] != null || iter["@@iterator"] != null) return Array.from(iter); }
2070
- function _arrayWithoutHoles(arr) { if (Array.isArray(arr)) return UploadManager_arrayLikeToArray(arr); }
2071
- function UploadManager_arrayLikeToArray(arr, len) { if (len == null || len > arr.length) len = arr.length; for (var i = 0, arr2 = new Array(len); i < len; i++) { arr2[i] = arr[i]; } return arr2; }
2072
- function UploadManager_await(value, then, direct) {
1640
+ function UploadManagerBase_toConsumableArray(arr) { return UploadManagerBase_arrayWithoutHoles(arr) || UploadManagerBase_iterableToArray(arr) || UploadManagerBase_unsupportedIterableToArray(arr) || UploadManagerBase_nonIterableSpread(); }
1641
+ function UploadManagerBase_nonIterableSpread() { throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); }
1642
+ function UploadManagerBase_unsupportedIterableToArray(o, minLen) { if (!o) return; if (typeof o === "string") return UploadManagerBase_arrayLikeToArray(o, minLen); var n = Object.prototype.toString.call(o).slice(8, -1); if (n === "Object" && o.constructor) n = o.constructor.name; if (n === "Map" || n === "Set") return Array.from(o); if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return UploadManagerBase_arrayLikeToArray(o, minLen); }
1643
+ function UploadManagerBase_iterableToArray(iter) { if (typeof Symbol !== "undefined" && iter[Symbol.iterator] != null || iter["@@iterator"] != null) return Array.from(iter); }
1644
+ function UploadManagerBase_arrayWithoutHoles(arr) { if (Array.isArray(arr)) return UploadManagerBase_arrayLikeToArray(arr); }
1645
+ function UploadManagerBase_arrayLikeToArray(arr, len) { if (len == null || len > arr.length) len = arr.length; for (var i = 0, arr2 = new Array(len); i < len; i++) { arr2[i] = arr[i]; } return arr2; }
1646
+ function UploadManagerBase_empty() {}
1647
+ function _awaitIgnored(value, direct) {
1648
+ if (!direct) {
1649
+ return value && value.then ? value.then(UploadManagerBase_empty) : Promise.resolve();
1650
+ }
1651
+ }
1652
+ function UploadManagerBase_await(value, then, direct) {
2073
1653
  if (direct) {
2074
1654
  return then ? then(value) : value;
2075
1655
  }
@@ -2078,46 +1658,72 @@ function UploadManager_await(value, then, direct) {
2078
1658
  }
2079
1659
  return then ? value.then(then) : value;
2080
1660
  }
2081
- function UploadManager_classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
2082
- function UploadManager_defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, UploadManager_toPropertyKey(descriptor.key), descriptor); } }
2083
- function UploadManager_createClass(Constructor, protoProps, staticProps) { if (protoProps) UploadManager_defineProperties(Constructor.prototype, protoProps); if (staticProps) UploadManager_defineProperties(Constructor, staticProps); Object.defineProperty(Constructor, "prototype", { writable: false }); return Constructor; }
2084
- function UploadManager_toPropertyKey(arg) { var key = UploadManager_toPrimitive(arg, "string"); return UploadManager_typeof(key) === "symbol" ? key : String(key); }
2085
- function UploadManager_toPrimitive(input, hint) { if (UploadManager_typeof(input) !== "object" || input === null) return input; var prim = input[Symbol.toPrimitive]; if (prim !== undefined) { var res = prim.call(input, hint || "default"); if (UploadManager_typeof(res) !== "object") return res; throw new TypeError("@@toPrimitive must return a primitive value."); } return (hint === "string" ? String : Number)(input); }
2086
-
2087
-
2088
-
1661
+ function _rethrow(thrown, value) {
1662
+ if (thrown) throw value;
1663
+ return value;
1664
+ }
1665
+ function _finallyRethrows(body, finalizer) {
1666
+ try {
1667
+ var result = body();
1668
+ } catch (e) {
1669
+ return finalizer(true, e);
1670
+ }
1671
+ if (result && result.then) {
1672
+ return result.then(finalizer.bind(null, false), finalizer.bind(null, true));
1673
+ }
1674
+ return finalizer(false, result);
1675
+ }
1676
+ function UploadManagerBase_continue(value, then) {
1677
+ return value && value.then ? value.then(then) : then(value);
1678
+ }
1679
+ function UploadManagerBase_classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
1680
+ function UploadManagerBase_defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, UploadManagerBase_toPropertyKey(descriptor.key), descriptor); } }
1681
+ function UploadManagerBase_createClass(Constructor, protoProps, staticProps) { if (protoProps) UploadManagerBase_defineProperties(Constructor.prototype, protoProps); if (staticProps) UploadManagerBase_defineProperties(Constructor, staticProps); Object.defineProperty(Constructor, "prototype", { writable: false }); return Constructor; }
1682
+ function UploadManagerBase_toPropertyKey(arg) { var key = UploadManagerBase_toPrimitive(arg, "string"); return UploadManagerBase_typeof(key) === "symbol" ? key : String(key); }
1683
+ function UploadManagerBase_toPrimitive(input, hint) { if (UploadManagerBase_typeof(input) !== "object" || input === null) return input; var prim = input[Symbol.toPrimitive]; if (prim !== undefined) { var res = prim.call(input, hint || "default"); if (UploadManagerBase_typeof(res) !== "object") return res; throw new TypeError("@@toPrimitive must return a primitive value."); } return (hint === "string" ? String : Number)(input); }
2089
1684
 
2090
- var UploadManager = /*#__PURE__*/function () {
2091
- function UploadManager(config) {
2092
- UploadManager_classCallCheck(this, UploadManager);
1685
+ /**
1686
+ * Methods common to UploadManagerNode and UploadManagerBrowser.
1687
+ */
1688
+ var UploadManagerBase = /*#__PURE__*/function () {
1689
+ function UploadManagerBase(config) {
1690
+ UploadManagerBase_classCallCheck(this, UploadManagerBase);
2093
1691
  this.config = config;
2094
1692
  this.stringMimeType = "text/plain";
2095
1693
  this.defaultMaxConcurrentUploadParts = 4;
1694
+ this.intervalMs = 500;
2096
1695
  this.uploadApi = new UploadApi(config);
2097
1696
  }
2098
- UploadManager_createClass(UploadManager, [{
1697
+ UploadManagerBase_createClass(UploadManagerBase, [{
2099
1698
  key: "upload",
2100
1699
  value: function upload(request) {
2101
1700
  try {
2102
1701
  var _this2 = this;
2103
- return UploadManager_await(_this2.processUploadSource(request.data), function (data) {
2104
- var chunkedStream = _this2.getChunkedStream(data);
2105
- return UploadManager_await(_this2.beginUpload(request, data), function (uploadInfo) {
2106
- _this2.checkIfCancelled(request);
2107
- var maxConcurrency = _this2.calculateMaxConcurrency(request, data);
2108
- var partCount = uploadInfo.uploadParts.count;
2109
- var parts = _toConsumableArray(Array(partCount).keys());
2110
- var runSourceStreamPump = chunkedStream === null || chunkedStream === void 0 ? void 0 : chunkedStream.runChunkPipeline();
2111
- return UploadManager_await(_this2.mapAsync(parts, maxConcurrency, UploadManager_async(function (part) {
2112
- return _this2.uploadPart(request, data, part, uploadInfo);
1702
+ _this2.assertNotCancelled(request);
1703
+ var source = _this2.processUploadSource(request.data);
1704
+ var preUploadInfo = _this2.getPreUploadInfo(request, source);
1705
+ var onProgress = _this2.makeProgressCallback(request, preUploadInfo.size);
1706
+ var init = _this2.preUpload(source);
1707
+ // Raise initial progress event SYNCHRONOUSLY.
1708
+ onProgress(0);
1709
+ return UploadManagerBase_await(_this2.beginUpload(request, preUploadInfo), function (uploadInfo) {
1710
+ var partCount = uploadInfo.uploadParts.count;
1711
+ var parts = UploadManagerBase_toConsumableArray(Array(partCount).keys());
1712
+ var _this2$makeCancellati = _this2.makeCancellationMethods(),
1713
+ cancel = _this2$makeCancellati.cancel,
1714
+ addCancellationHandler = _this2$makeCancellati.addCancellationHandler;
1715
+ var intervalHandle = setInterval(_this2.onIntervalTick(request, cancel), _this2.intervalMs);
1716
+ return UploadManagerBase_continue(_finallyRethrows(function () {
1717
+ return UploadManagerBase_await(_this2.mapAsync(parts, preUploadInfo.maxConcurrentUploadParts, _async(function (part) {
1718
+ return _this2.uploadPart(request, source, part, uploadInfo, onProgress, addCancellationHandler);
2113
1719
  })), function () {
2114
- if (chunkedStream !== undefined) {
2115
- chunkedStream.finishedConsuming();
2116
- }
2117
- return UploadManager_await(runSourceStreamPump, function () {
2118
- return uploadInfo.file;
2119
- });
1720
+ return _awaitIgnored(_this2.postUpload(init));
2120
1721
  });
1722
+ }, function (_wasThrown, _result) {
1723
+ clearInterval(intervalHandle);
1724
+ return _rethrow(_wasThrown, _result);
1725
+ }), function () {
1726
+ return uploadInfo.file;
2121
1727
  });
2122
1728
  });
2123
1729
  } catch (e) {
@@ -2125,22 +1731,85 @@ var UploadManager = /*#__PURE__*/function () {
2125
1731
  }
2126
1732
  }
2127
1733
  }, {
2128
- key: "checkIfCancelled",
2129
- value: function checkIfCancelled(request) {
2130
- var _a;
2131
- if (((_a = request.cancellationToken) === null || _a === void 0 ? void 0 : _a.isCancelled) === true) {
2132
- throw new CancelledError("Upload cancelled by user.");
1734
+ key: "getBlobInfo",
1735
+ value: function getBlobInfo(_ref) {
1736
+ var _ref$value = _ref.value,
1737
+ name = _ref$value.name,
1738
+ size = _ref$value.size,
1739
+ type = _ref$value.type;
1740
+ return {
1741
+ mime: type,
1742
+ size: size,
1743
+ originalFileName: name,
1744
+ maxConcurrentUploadParts: undefined
1745
+ };
1746
+ }
1747
+ }, {
1748
+ key: "onIntervalTick",
1749
+ value: function onIntervalTick(request, cancel) {
1750
+ var _this3 = this;
1751
+ return function () {
1752
+ if (_this3.isCancelled(request)) {
1753
+ cancel();
1754
+ }
1755
+ };
1756
+ }
1757
+ }, {
1758
+ key: "makeCancellationMethods",
1759
+ value: function makeCancellationMethods() {
1760
+ var cancellationHandlers = [];
1761
+ var addCancellationHandler = function addCancellationHandler(ca) {
1762
+ cancellationHandlers.push(ca);
1763
+ };
1764
+ var cancel = function cancel() {
1765
+ return cancellationHandlers.forEach(function (x) {
1766
+ return x();
1767
+ });
1768
+ };
1769
+ return {
1770
+ cancel: cancel,
1771
+ addCancellationHandler: addCancellationHandler
1772
+ };
1773
+ }
1774
+ }, {
1775
+ key: "makeProgressCallback",
1776
+ value: function makeProgressCallback(request, bytesTotal) {
1777
+ var onProgress = request.onProgress;
1778
+ if (onProgress === undefined) {
1779
+ return function () {};
1780
+ }
1781
+ var bytesSent = 0;
1782
+ return function (bytesSentDelta) {
1783
+ bytesSent += bytesSentDelta;
1784
+ onProgress({
1785
+ bytesTotal: bytesTotal,
1786
+ bytesSent: bytesSent,
1787
+ progress: Math.round(bytesSent / bytesTotal * 100)
1788
+ });
1789
+ };
1790
+ }
1791
+ }, {
1792
+ key: "assertNotCancelled",
1793
+ value: function assertNotCancelled(request) {
1794
+ if (this.isCancelled(request)) {
1795
+ throw new CancelledError();
2133
1796
  }
2134
1797
  }
1798
+ }, {
1799
+ key: "isCancelled",
1800
+ value: function isCancelled(request) {
1801
+ var _a;
1802
+ return ((_a = request.cancellationToken) === null || _a === void 0 ? void 0 : _a.isCancelled) === true;
1803
+ }
2135
1804
  }, {
2136
1805
  key: "beginUpload",
2137
- value: function beginUpload(request, data) {
1806
+ value: function beginUpload(request, _ref2) {
1807
+ var size = _ref2.size,
1808
+ mime = _ref2.mime,
1809
+ originalFileName = _ref2.originalFileName;
2138
1810
  try {
2139
- var _this4 = this;
2140
- var size = _this4.calculateSize(request, data);
2141
- var mime = _this4.calculateMime(request, data);
2142
- var originalFileName = _this4.calculateOriginalFileName(request, data);
2143
- return UploadManager_await(_this4.uploadApi.beginMultipartUpload({
1811
+ var _this5 = this;
1812
+ return UploadManagerBase_await(_this5.uploadApi.beginMultipartUpload({
2144
1813
  accountId: request.accountId,
2145
1814
  beginMultipartUploadRequest: {
2146
1815
  metadata: request.metadata,
@@ -2158,15 +1827,15 @@ var UploadManager = /*#__PURE__*/function () {
2158
1827
  }
2159
1828
  }, {
2160
1829
  key: "uploadPart",
2161
- value: function uploadPart(request, data, partIndex, uploadInfo) {
1830
+ value: function uploadPart(request, source, partIndex, uploadInfo, onProgress, addCancellationHandler) {
2162
1831
  try {
2163
- var _this6 = this;
2164
- _this6.checkIfCancelled(request);
2165
- return UploadManager_await(_this6.getUploadPart(request, partIndex, uploadInfo), function (part) {
2166
- _this6.checkIfCancelled(request);
2167
- return UploadManager_await(_this6.putUploadPart(part, data), function (etag) {
2168
- _this6.checkIfCancelled(request);
2169
- return _awaitIgnored(_this6.uploadApi.completeUploadPart({
1832
+ var _this7 = this;
1833
+ _this7.assertNotCancelled(request);
1834
+ return UploadManagerBase_await(_this7.getUploadPart(request, partIndex, uploadInfo), function (part) {
1835
+ _this7.assertNotCancelled(request);
1836
+ return UploadManagerBase_await(_this7.putUploadPart(part, source, onProgress, addCancellationHandler), function (etag) {
1837
+ _this7.assertNotCancelled(request);
1838
+ return _awaitIgnored(_this7.uploadApi.completeUploadPart({
2170
1839
  accountId: request.accountId,
2171
1840
  uploadId: uploadInfo.uploadId,
2172
1841
  uploadPartIndex: partIndex,
@@ -2185,303 +1854,502 @@ var UploadManager = /*#__PURE__*/function () {
2185
1854
  */
2186
1855
  }, {
2187
1856
  key: "putUploadPart",
2188
- value: function putUploadPart(part, data) {
1857
+ value: function putUploadPart(part, source, onProgress, addCancellationHandler) {
2189
1858
  try {
2190
- var _this8 = this;
2191
- var _a, _b;
2192
- var fetchApi = (_a = _this8.config.fetchApi) !== null && _a !== void 0 ? _a : fetch;
2193
- var headers = {
2194
- // Required to prevent fetch using "Transfer-Encoding: Chunked" when body is a stream.
2195
- "content-length": (part.range.inclusiveEnd + 1 - part.range.inclusiveStart).toString()
2196
- };
2197
- var _part$uploadUrl2 = part.uploadUrl,
2198
- _coerceRequestBody2 = _this8.coerceRequestBody;
2199
- return UploadManager_await(_this8.makeRequestBody(part, data), function (_this7$makeRequestBod) {
2200
- return UploadManager_await(fetchApi(_part$uploadUrl2, {
2201
- method: "PUT",
2202
- headers: headers,
2203
- body: _coerceRequestBody2.call(_this8, _this7$makeRequestBod)
2204
- }), function (response) {
2205
- var _exit = false;
2206
- var etag = (_b = response.headers.get("etag")) !== null && _b !== void 0 ? _b : undefined;
2207
- return UploadManager_invoke(function () {
2208
- if (Math.floor(response.status / 100) !== 2) {
2209
- return UploadManager_await(response.text(), function (_response$text) {
2210
- console.error("Failed to upload part (".concat(response.status, "). Response from server:\n").concat(_response$text));
2211
- throw new Error("Failed to upload part (".concat(response.status, ")."));
2212
- });
2213
- }
2214
- }, function (_result) {
2215
- if (_exit) return _result;
2216
- if (etag === undefined) {
2217
- throw new Error("No 'etag' response header found in upload part response.");
2218
- }
2219
- return etag;
2220
- });
2221
- });
1859
+ var _this9 = this;
1860
+ var contentLength = part.range.inclusiveEnd + 1 - part.range.inclusiveStart;
1861
+ return UploadManagerBase_await(_this9.doPutUploadPart(part, contentLength, source, onProgress, addCancellationHandler), function (_ref3) {
1862
+ var status = _ref3.status,
1863
+ etag = _ref3.etag;
1864
+ if (Math.floor(status / 100) !== 2) {
1865
+ throw new Error("Failed to upload part (".concat(status, ")."));
1866
+ }
1867
+ if (etag === undefined) {
1868
+ throw new Error("No 'etag' response header found in upload part response.");
1869
+ }
1870
+ return etag;
2222
1871
  });
2223
1872
  } catch (e) {
2224
1873
  return Promise.reject(e);
2225
1874
  }
2226
1875
  }
2227
1876
  }, {
2228
- key: "coerceRequestBody",
2229
- value: function coerceRequestBody(data) {
2230
- return data; // node-fetch supports 'NodeJS.ReadableStream'
2231
- }
2232
- }, {
2233
- key: "makeRequestBody",
2234
- value: function makeRequestBody(part, data) {
1877
+ key: "getUploadPart",
1878
+ value: function getUploadPart(request, partIndex, uploadInfo) {
2235
1879
  try {
2236
- var _this10 = this;
2237
- return UploadManager_await(_this10.sliceDataForRequest(data, part), function (slicedData) {
2238
- var isNodeJs = _this10.isNodeJs();
2239
- // node-fetch requires 'NodeJS.ReadableStream' for the body.
2240
- // browser fetch supports blobs and buffers.
2241
- return UploadManager_await(_this10.foldDataRaw(slicedData, {
2242
- ifBuffer: UploadManager_async(function (buffer) {
2243
- return isNodeJs ? _this10.bufferToStream(buffer) : buffer;
2244
- }),
2245
- ifBlob: UploadManager_async(function (blob) {
2246
- var _bufferToStream = isNodeJs && _this10.bufferToStream;
2247
- return UploadManager_await(isNodeJs ? _this10.blobToBuffer(blob) : blob, function (_this10$blobToBuffer) {
2248
- return UploadManager_await(isNodeJs ? _bufferToStream.call(_this10, _this10$blobToBuffer) : _this10$blobToBuffer, void 0, !isNodeJs);
2249
- }, !isNodeJs);
2250
- }),
2251
- ifNodeJsStream: function (stream) {
2252
- return UploadManager_await(stream);
2253
- }
2254
- }));
2255
- });
1880
+ var _this11 = this;
1881
+ if (partIndex === 0) {
1882
+ return uploadInfo.uploadParts.first;
1883
+ }
1884
+ return UploadManagerBase_await(_this11.uploadApi.getUploadPart({
1885
+ uploadId: uploadInfo.uploadId,
1886
+ accountId: request.accountId,
1887
+ uploadPartIndex: partIndex
1888
+ }));
2256
1889
  } catch (e) {
2257
1890
  return Promise.reject(e);
2258
1891
  }
2259
1892
  }
2260
1893
  }, {
2261
- key: "bufferToStream",
2262
- value: function bufferToStream(buffer) {
2263
- try {
2264
- return UploadManager_await(NodeUtils.createStream(), function (readable) {
2265
- readable.push(buffer);
2266
- readable.push(null);
2267
- return readable;
2268
- });
2269
- } catch (e) {
2270
- return Promise.reject(e);
2271
- }
1894
+ key: "getPreUploadInfo",
1895
+ value: function getPreUploadInfo(request, source) {
1896
+ var _a, _b, _c;
1897
+ var partial = this.getPreUploadInfoPartial(request, source);
1898
+ return {
1899
+ maxConcurrentUploadParts: (_a = partial.maxConcurrentUploadParts) !== null && _a !== void 0 ? _a : this.defaultMaxConcurrentUploadParts,
1900
+ originalFileName: (_b = request.originalFileName) !== null && _b !== void 0 ? _b : partial.originalFileName,
1901
+ mime: (_c = request.mime) !== null && _c !== void 0 ? _c : partial.mime,
1902
+ size: partial.size
1903
+ };
2272
1904
  }
2273
- /**
2274
- * Only expected to be called in Node.js environments, and as such, we can assume 'BlobLike' is not a DOM 'File' object.
2275
- */
2276
1905
  }, {
2277
- key: "blobToBuffer",
2278
- value: function blobToBuffer(blob) {
1906
+ key: "mapAsync",
1907
+ value: function mapAsync(items, concurrency, callback) {
2279
1908
  try {
2280
- var _exit3 = false;
2281
- // DOM Blob and Node.js Blob both have 'arrayBuffer' with the same signature...
2282
- return UploadManager_invoke(function () {
2283
- if (blob.arrayBuffer !== undefined) {
2284
- _exit3 = true;
2285
- var _Buffer2 = Buffer,
2286
- _from2 = _Buffer2.from;
2287
- return UploadManager_await(blob.arrayBuffer(), function (_blob$arrayBuffer) {
2288
- return _from2.call(_Buffer2, _blob$arrayBuffer);
1909
+ var workQueue = UploadManagerBase_toConsumableArray(items);
1910
+ return _awaitIgnored(Promise.all(UploadManagerBase_toConsumableArray(Array(concurrency).keys()).map(_async(function () {
1911
+ return _continueIgnored(_for(function () {
1912
+ return workQueue.length > 0;
1913
+ }, void 0, function () {
1914
+ var work = workQueue.shift(); // IMPORTANT: use 'shift' instead of 'pop' to ensure 'items' are processed in order when 'concurrency = 1'.
1915
+ return _invokeIgnored(function () {
1916
+ if (work !== undefined) {
1917
+ return _awaitIgnored(callback(work));
1918
+ }
2289
1919
  });
2290
- }
2291
- }, function (_result2) {
2292
- if (_exit3) return _result2;
2293
- throw new Error("The provided 'data' field was treated as a BLOB, but it does not have an 'arrayBuffer' method.");
2294
- });
1920
+ }));
1921
+ }))));
2295
1922
  } catch (e) {
2296
1923
  return Promise.reject(e);
2297
1924
  }
2298
1925
  }
1926
+ }]);
1927
+ return UploadManagerBase;
1928
+ }();
1929
+ ;// CONCATENATED MODULE: ./src/public/browser/UploadManagerBrowser.ts
1930
+ function UploadManagerBrowser_typeof(obj) { "@babel/helpers - typeof"; return UploadManagerBrowser_typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (obj) { return typeof obj; } : function (obj) { return obj && "function" == typeof Symbol && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }, UploadManagerBrowser_typeof(obj); }
1931
+ function UploadManagerBrowser_await(value, then, direct) {
1932
+ if (direct) {
1933
+ return then ? then(value) : value;
1934
+ }
1935
+ if (!value || !value.then) {
1936
+ value = Promise.resolve(value);
1937
+ }
1938
+ return then ? value.then(then) : value;
1939
+ }
1940
+ function UploadManagerBrowser_rethrow(thrown, value) {
1941
+ if (thrown) throw value;
1942
+ return value;
1943
+ }
1944
+ function UploadManagerBrowser_finallyRethrows(body, finalizer) {
1945
+ try {
1946
+ var result = body();
1947
+ } catch (e) {
1948
+ return finalizer(true, e);
1949
+ }
1950
+ if (result && result.then) {
1951
+ return result.then(finalizer.bind(null, false), finalizer.bind(null, true));
1952
+ }
1953
+ return finalizer(false, result);
1954
+ }
1955
+ function UploadManagerBrowser_classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
1956
+ function UploadManagerBrowser_defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, UploadManagerBrowser_toPropertyKey(descriptor.key), descriptor); } }
1957
+ function UploadManagerBrowser_createClass(Constructor, protoProps, staticProps) { if (protoProps) UploadManagerBrowser_defineProperties(Constructor.prototype, protoProps); if (staticProps) UploadManagerBrowser_defineProperties(Constructor, staticProps); Object.defineProperty(Constructor, "prototype", { writable: false }); return Constructor; }
1958
+ function UploadManagerBrowser_toPropertyKey(arg) { var key = UploadManagerBrowser_toPrimitive(arg, "string"); return UploadManagerBrowser_typeof(key) === "symbol" ? key : String(key); }
1959
+ function UploadManagerBrowser_toPrimitive(input, hint) { if (UploadManagerBrowser_typeof(input) !== "object" || input === null) return input; var prim = input[Symbol.toPrimitive]; if (prim !== undefined) { var res = prim.call(input, hint || "default"); if (UploadManagerBrowser_typeof(res) !== "object") return res; throw new TypeError("@@toPrimitive must return a primitive value."); } return (hint === "string" ? String : Number)(input); }
1960
+ function UploadManagerBrowser_inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function"); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, writable: true, configurable: true } }); Object.defineProperty(subClass, "prototype", { writable: false }); if (superClass) UploadManagerBrowser_setPrototypeOf(subClass, superClass); }
1961
+ function UploadManagerBrowser_setPrototypeOf(o, p) { UploadManagerBrowser_setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return UploadManagerBrowser_setPrototypeOf(o, p); }
1962
+ function UploadManagerBrowser_createSuper(Derived) { var hasNativeReflectConstruct = UploadManagerBrowser_isNativeReflectConstruct(); return function _createSuperInternal() { var Super = UploadManagerBrowser_getPrototypeOf(Derived), result; if (hasNativeReflectConstruct) { var NewTarget = UploadManagerBrowser_getPrototypeOf(this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return UploadManagerBrowser_possibleConstructorReturn(this, result); }; }
1963
+ function UploadManagerBrowser_possibleConstructorReturn(self, call) { if (call && (UploadManagerBrowser_typeof(call) === "object" || typeof call === "function")) { return call; } else if (call !== void 0) { throw new TypeError("Derived constructors may only return object or undefined"); } return UploadManagerBrowser_assertThisInitialized(self); }
1964
+ function UploadManagerBrowser_assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self; }
1965
+ function UploadManagerBrowser_isNativeReflectConstruct() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); return true; } catch (e) { return false; } }
1966
+ function UploadManagerBrowser_getPrototypeOf(o) { UploadManagerBrowser_getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf.bind() : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return UploadManagerBrowser_getPrototypeOf(o); }
1967
+
1968
+
1969
+
1970
+ var UploadManager = /*#__PURE__*/function (_UploadManagerBase) {
1971
+ UploadManagerBrowser_inherits(UploadManager, _UploadManagerBase);
1972
+ var _super = UploadManagerBrowser_createSuper(UploadManager);
1973
+ function UploadManager() {
1974
+ UploadManagerBrowser_classCallCheck(this, UploadManager);
1975
+ return _super.apply(this, arguments);
1976
+ }
1977
+ UploadManagerBrowser_createClass(UploadManager, [{
1978
+ key: "processUploadSource",
1979
+ value: function processUploadSource(data) {
1980
+ if (typeof data === "string") {
1981
+ // 'Blob' must be from 'global' (i.e. not imported) as we're in a browser context here, so is globally available.
1982
+ return {
1983
+ type: "Blob",
1984
+ value: new Blob([data], {
1985
+ type: this.stringMimeType
1986
+ })
1987
+ };
1988
+ }
1989
+ if (data.size !== undefined) {
1990
+ return {
1991
+ type: "Blob",
1992
+ value: data
1993
+ };
1994
+ }
1995
+ throw new Error("Unsupported type for 'data' parameter. Please provide a String, Blob, or File object (from a file input element).");
1996
+ }
2299
1997
  }, {
2300
- key: "sliceDataForRequest",
2301
- value: function sliceDataForRequest(data, part) {
2302
- try {
2303
- var _this12 = this;
2304
- if (part.range.inclusiveEnd === -1) {
2305
- return "";
2306
- }
2307
- var start = part.range.inclusiveStart;
2308
- var endExclusive = part.range.inclusiveEnd + 1;
2309
- var partSize = endExclusive - start;
2310
- return UploadManager_await(_this12.foldData(data, {
2311
- ifBlob: UploadManager_async(function (blob) {
2312
- return blob.slice(start, endExclusive);
2313
- }),
2314
- ifBuffer: UploadManager_async(function (buffer) {
2315
- return buffer.subarray(start, endExclusive);
2316
- }),
2317
- ifNodeJsStream: UploadManager_async(function (stream) {
2318
- return stream.take(partSize);
2319
- }) // Assumes stream is read using one worker (which it is).
2320
- }));
2321
- } catch (e) {
2322
- return Promise.reject(e);
1998
+ key: "getPreUploadInfoPartial",
1999
+ value: function getPreUploadInfoPartial(_request, data) {
2000
+ switch (data.type) {
2001
+ case "Blob":
2002
+ return this.getBlobInfo(data);
2003
+ default:
2004
+ assertUnreachable(data.type);
2323
2005
  }
2324
2006
  }
2325
2007
  }, {
2326
- key: "isNodeJs",
2327
- value: function isNodeJs() {
2328
- return typeof process !== "undefined" && process.versions !== undefined && process.versions.node !== undefined;
2008
+ key: "preUpload",
2009
+ value: function preUpload(_source) {
2010
+ return undefined;
2329
2011
  }
2330
2012
  }, {
2331
- key: "getUploadPart",
2332
- value: function getUploadPart(request, partIndex, uploadInfo) {
2013
+ key: "postUpload",
2014
+ value: function postUpload(_init) {
2015
+ return UploadManagerBrowser_await();
2016
+ } // NO-OP.
2017
+ }, {
2018
+ key: "doPutUploadPart",
2019
+ value: function doPutUploadPart(part, contentLength, source, onProgress, addCancellationHandler) {
2333
2020
  try {
2334
- var _this14 = this;
2335
- if (partIndex === 0) {
2336
- return uploadInfo.uploadParts.first;
2337
- }
2338
- return UploadManager_await(_this14.uploadApi.getUploadPart({
2339
- uploadId: uploadInfo.uploadId,
2340
- accountId: request.accountId,
2341
- uploadPartIndex: partIndex
2342
- }));
2021
+ var _this2 = this;
2022
+ var xhr = new XMLHttpRequest();
2023
+ var pending = true;
2024
+ addCancellationHandler(function () {
2025
+ if (pending) {
2026
+ xhr.abort();
2027
+ }
2028
+ });
2029
+ var lastBytesSent = 0;
2030
+ var setBytesSent = function setBytesSent(newBytesSent) {
2031
+ var delta = newBytesSent - lastBytesSent;
2032
+ lastBytesSent = newBytesSent;
2033
+ onProgress(delta);
2034
+ };
2035
+ return UploadManagerBrowser_finallyRethrows(function () {
2036
+ return UploadManagerBrowser_await(new Promise(function (resolve, reject) {
2037
+ xhr.upload.addEventListener("progress", function (evt) {
2038
+ if (evt.lengthComputable) {
2039
+ setBytesSent(evt.loaded);
2040
+ }
2041
+ }, false);
2042
+ xhr.addEventListener("load", function () {
2043
+ var _a;
2044
+ // Ensure we always report the progress of a finished upload as 100%.
2045
+ setBytesSent(contentLength);
2046
+ var etag = (_a = xhr.getResponseHeader("etag")) !== null && _a !== void 0 ? _a : undefined;
2047
+ resolve({
2048
+ etag: etag,
2049
+ status: xhr.status
2050
+ });
2051
+ });
2052
+ xhr.onabort = function () {
2053
+ return reject(new CancelledError());
2054
+ };
2055
+ xhr.onerror = function () {
2056
+ return reject(new Error("File upload error."));
2057
+ };
2058
+ xhr.ontimeout = function () {
2059
+ return reject(new Error("File upload timeout."));
2060
+ };
2061
+ xhr.open("PUT", part.uploadUrl);
2062
+ xhr.send(_this2.getRequestBody(part, source));
2063
+ }));
2064
+ }, function (_wasThrown, _result) {
2065
+ pending = false;
2066
+ return UploadManagerBrowser_rethrow(_wasThrown, _result);
2067
+ });
2343
2068
  } catch (e) {
2344
2069
  return Promise.reject(e);
2345
2070
  }
2346
2071
  }
2347
2072
  }, {
2348
- key: "calculateSize",
2349
- value: function calculateSize(request, data) {
2350
- return this.foldData(data, {
2351
- ifBlob: function ifBlob(blob) {
2352
- return blob.size;
2353
- },
2354
- ifBuffer: function ifBuffer(buffer) {
2355
- return buffer.length;
2356
- },
2357
- ifNodeJsStream: function ifNodeJsStream(_) {
2358
- if (request.size === undefined) {
2359
- throw new Error("You must include the 'size' parameter when using a stream for the 'data' parameter.");
2360
- }
2361
- return request.size;
2362
- }
2363
- });
2073
+ key: "getRequestBody",
2074
+ value: function getRequestBody(part, blob) {
2075
+ return part.range.inclusiveEnd === -1 ? new Blob() : blob.value.slice(part.range.inclusiveStart, part.range.inclusiveEnd + 1);
2076
+ }
2077
+ }]);
2078
+ return UploadManager;
2079
+ }(UploadManagerBase);
2080
+ ;// CONCATENATED MODULE: ./src/private/ConsoleUtils.ts
2081
+ function ConsoleUtils_typeof(obj) { "@babel/helpers - typeof"; return ConsoleUtils_typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (obj) { return typeof obj; } : function (obj) { return obj && "function" == typeof Symbol && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }, ConsoleUtils_typeof(obj); }
2082
+ function ConsoleUtils_classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
2083
+ function ConsoleUtils_defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, ConsoleUtils_toPropertyKey(descriptor.key), descriptor); } }
2084
+ function ConsoleUtils_createClass(Constructor, protoProps, staticProps) { if (protoProps) ConsoleUtils_defineProperties(Constructor.prototype, protoProps); if (staticProps) ConsoleUtils_defineProperties(Constructor, staticProps); Object.defineProperty(Constructor, "prototype", { writable: false }); return Constructor; }
2085
+ function ConsoleUtils_toPropertyKey(arg) { var key = ConsoleUtils_toPrimitive(arg, "string"); return ConsoleUtils_typeof(key) === "symbol" ? key : String(key); }
2086
+ function ConsoleUtils_toPrimitive(input, hint) { if (ConsoleUtils_typeof(input) !== "object" || input === null) return input; var prim = input[Symbol.toPrimitive]; if (prim !== undefined) { var res = prim.call(input, hint || "default"); if (ConsoleUtils_typeof(res) !== "object") return res; throw new TypeError("@@toPrimitive must return a primitive value."); } return (hint === "string" ? String : Number)(input); }
2087
+ var ConsoleUtils = /*#__PURE__*/function () {
2088
+ function ConsoleUtils() {
2089
+ ConsoleUtils_classCallCheck(this, ConsoleUtils);
2090
+ }
2091
+ ConsoleUtils_createClass(ConsoleUtils, null, [{
2092
+ key: "error",
2093
+ value: function error(message) {
2094
+ console.error(ConsoleUtils.prefix(message));
2364
2095
  }
2365
2096
  }, {
2366
- key: "calculateMime",
2367
- value: function calculateMime(request, data) {
2368
- var _a;
2369
- return (_a = request.mime) !== null && _a !== void 0 ? _a : this.foldData(data, {
2370
- ifBlob: function ifBlob(blob) {
2371
- return blob.type;
2372
- },
2373
- ifBuffer: function ifBuffer(_) {
2374
- return undefined;
2375
- },
2376
- ifNodeJsStream: function ifNodeJsStream(_) {
2377
- return undefined;
2378
- }
2379
- });
2097
+ key: "warn",
2098
+ value: function warn(message) {
2099
+ console.warn(ConsoleUtils.prefix(message));
2380
2100
  }
2381
2101
  }, {
2382
- key: "calculateOriginalFileName",
2383
- value: function calculateOriginalFileName(request, data) {
2384
- var _a;
2385
- return (_a = request.originalFileName) !== null && _a !== void 0 ? _a : this.foldData(data, {
2386
- ifBlob: function ifBlob(blob) {
2387
- return blob.name;
2388
- },
2389
- ifBuffer: function ifBuffer(_) {
2390
- return undefined;
2391
- },
2392
- ifNodeJsStream: function ifNodeJsStream(_) {
2393
- return undefined;
2102
+ key: "prefix",
2103
+ value: function prefix(message) {
2104
+ return "[bytescale-sdk] ".concat(message);
2105
+ }
2106
+ }]);
2107
+ return ConsoleUtils;
2108
+ }();
2109
+ ;// CONCATENATED MODULE: ./src/private/Mutex.ts
2110
+ function Mutex_typeof(obj) { "@babel/helpers - typeof"; return Mutex_typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (obj) { return typeof obj; } : function (obj) { return obj && "function" == typeof Symbol && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }, Mutex_typeof(obj); }
2111
+ function _call(body, then, direct) {
2112
+ if (direct) {
2113
+ return then ? then(body()) : body();
2114
+ }
2115
+ try {
2116
+ var result = Promise.resolve(body());
2117
+ return then ? result.then(then) : result;
2118
+ } catch (e) {
2119
+ return Promise.reject(e);
2120
+ }
2121
+ }
2122
+ function Mutex_rethrow(thrown, value) {
2123
+ if (thrown) throw value;
2124
+ return value;
2125
+ }
2126
+ function Mutex_finallyRethrows(body, finalizer) {
2127
+ try {
2128
+ var result = body();
2129
+ } catch (e) {
2130
+ return finalizer(true, e);
2131
+ }
2132
+ if (result && result.then) {
2133
+ return result.then(finalizer.bind(null, false), finalizer.bind(null, true));
2134
+ }
2135
+ return finalizer(false, result);
2136
+ }
2137
+ function Mutex_await(value, then, direct) {
2138
+ if (direct) {
2139
+ return then ? then(value) : value;
2140
+ }
2141
+ if (!value || !value.then) {
2142
+ value = Promise.resolve(value);
2143
+ }
2144
+ return then ? value.then(then) : value;
2145
+ }
2146
+ function Mutex_empty() {}
2147
+ function Mutex_awaitIgnored(value, direct) {
2148
+ if (!direct) {
2149
+ return value && value.then ? value.then(Mutex_empty) : Promise.resolve();
2150
+ }
2151
+ }
2152
+ function Mutex_settle(pact, state, value) {
2153
+ if (!pact.s) {
2154
+ if (value instanceof Mutex_Pact) {
2155
+ if (value.s) {
2156
+ if (state & 1) {
2157
+ state = value.s;
2394
2158
  }
2395
- });
2159
+ value = value.v;
2160
+ } else {
2161
+ value.o = Mutex_settle.bind(null, pact, state);
2162
+ return;
2163
+ }
2396
2164
  }
2397
- }, {
2398
- key: "calculateMaxConcurrency",
2399
- value: function calculateMaxConcurrency(request, data) {
2400
- var _a;
2401
- return (_a = this.foldData(data, {
2402
- ifBlob: function ifBlob(_) {
2403
- return request.maxConcurrentUploadParts;
2404
- },
2405
- ifBuffer: function ifBuffer(_) {
2406
- return request.maxConcurrentUploadParts;
2407
- },
2408
- ifNodeJsStream: function ifNodeJsStream(_) {
2409
- return 1;
2410
- } // Uploading from a stream concurrently is more complex, as would require buffering parts in memory, so we serialize.
2411
- })) !== null && _a !== void 0 ? _a : this.defaultMaxConcurrentUploadParts;
2165
+ if (value && value.then) {
2166
+ value.then(Mutex_settle.bind(null, pact, state), Mutex_settle.bind(null, pact, 2));
2167
+ return;
2412
2168
  }
2413
- }, {
2414
- key: "getChunkedStream",
2415
- value: function getChunkedStream(data) {
2416
- return this.foldData(data, {
2417
- ifBlob: function ifBlob(_) {
2418
- return undefined;
2419
- },
2420
- ifBuffer: function ifBuffer(_) {
2421
- return undefined;
2422
- },
2423
- ifNodeJsStream: function ifNodeJsStream(x) {
2424
- return x;
2169
+ pact.s = state;
2170
+ pact.v = value;
2171
+ var observer = pact.o;
2172
+ if (observer) {
2173
+ observer(pact);
2174
+ }
2175
+ }
2176
+ }
2177
+ var Mutex_Pact = /*#__PURE__*/function () {
2178
+ function _Pact() {}
2179
+ _Pact.prototype.then = function (onFulfilled, onRejected) {
2180
+ var result = new _Pact();
2181
+ var state = this.s;
2182
+ if (state) {
2183
+ var callback = state & 1 ? onFulfilled : onRejected;
2184
+ if (callback) {
2185
+ try {
2186
+ Mutex_settle(result, 1, callback(this.v));
2187
+ } catch (e) {
2188
+ Mutex_settle(result, 2, e);
2425
2189
  }
2426
- });
2190
+ return result;
2191
+ } else {
2192
+ return this;
2193
+ }
2427
2194
  }
2428
- }, {
2429
- key: "foldData",
2430
- value: function foldData(data, handle) {
2431
- if (data instanceof ChunkedStream) {
2432
- return handle.ifNodeJsStream(data);
2195
+ this.o = function (_this) {
2196
+ try {
2197
+ var value = _this.v;
2198
+ if (_this.s & 1) {
2199
+ Mutex_settle(result, 1, onFulfilled ? onFulfilled(value) : value);
2200
+ } else if (onRejected) {
2201
+ Mutex_settle(result, 1, onRejected(value));
2202
+ } else {
2203
+ Mutex_settle(result, 2, value);
2204
+ }
2205
+ } catch (e) {
2206
+ Mutex_settle(result, 2, e);
2207
+ }
2208
+ };
2209
+ return result;
2210
+ };
2211
+ return _Pact;
2212
+ }();
2213
+ function Mutex_isSettledPact(thenable) {
2214
+ return thenable instanceof Mutex_Pact && thenable.s & 1;
2215
+ }
2216
+ function Mutex_for(test, update, body) {
2217
+ var stage;
2218
+ for (;;) {
2219
+ var shouldContinue = test();
2220
+ if (Mutex_isSettledPact(shouldContinue)) {
2221
+ shouldContinue = shouldContinue.v;
2222
+ }
2223
+ if (!shouldContinue) {
2224
+ return result;
2225
+ }
2226
+ if (shouldContinue.then) {
2227
+ stage = 0;
2228
+ break;
2229
+ }
2230
+ var result = body();
2231
+ if (result && result.then) {
2232
+ if (Mutex_isSettledPact(result)) {
2233
+ result = result.s;
2234
+ } else {
2235
+ stage = 1;
2236
+ break;
2237
+ }
2238
+ }
2239
+ if (update) {
2240
+ var updateValue = update();
2241
+ if (updateValue && updateValue.then && !Mutex_isSettledPact(updateValue)) {
2242
+ stage = 2;
2243
+ break;
2244
+ }
2245
+ }
2246
+ }
2247
+ var pact = new Mutex_Pact();
2248
+ var reject = Mutex_settle.bind(null, pact, 2);
2249
+ (stage === 0 ? shouldContinue.then(_resumeAfterTest) : stage === 1 ? result.then(_resumeAfterBody) : updateValue.then(_resumeAfterUpdate)).then(void 0, reject);
2250
+ return pact;
2251
+ function _resumeAfterBody(value) {
2252
+ result = value;
2253
+ do {
2254
+ if (update) {
2255
+ updateValue = update();
2256
+ if (updateValue && updateValue.then && !Mutex_isSettledPact(updateValue)) {
2257
+ updateValue.then(_resumeAfterUpdate).then(void 0, reject);
2258
+ return;
2259
+ }
2260
+ }
2261
+ shouldContinue = test();
2262
+ if (!shouldContinue || Mutex_isSettledPact(shouldContinue) && !shouldContinue.v) {
2263
+ Mutex_settle(pact, 1, result);
2264
+ return;
2265
+ }
2266
+ if (shouldContinue.then) {
2267
+ shouldContinue.then(_resumeAfterTest).then(void 0, reject);
2268
+ return;
2269
+ }
2270
+ result = body();
2271
+ if (Mutex_isSettledPact(result)) {
2272
+ result = result.v;
2433
2273
  }
2434
- if (data.subarray !== undefined) {
2435
- return handle.ifBuffer(data);
2274
+ } while (!result || !result.then);
2275
+ result.then(_resumeAfterBody).then(void 0, reject);
2276
+ }
2277
+ function _resumeAfterTest(shouldContinue) {
2278
+ if (shouldContinue) {
2279
+ result = body();
2280
+ if (result && result.then) {
2281
+ result.then(_resumeAfterBody).then(void 0, reject);
2282
+ } else {
2283
+ _resumeAfterBody(result);
2284
+ }
2285
+ } else {
2286
+ Mutex_settle(pact, 1, result);
2287
+ }
2288
+ }
2289
+ function _resumeAfterUpdate() {
2290
+ if (shouldContinue = test()) {
2291
+ if (shouldContinue.then) {
2292
+ shouldContinue.then(_resumeAfterTest).then(void 0, reject);
2293
+ } else {
2294
+ _resumeAfterTest(shouldContinue);
2436
2295
  }
2437
- if (data.slice !== undefined) {
2438
- return handle.ifBlob(data);
2296
+ } else {
2297
+ Mutex_settle(pact, 1, result);
2298
+ }
2299
+ }
2300
+ }
2301
+ function Mutex_continue(value, then) {
2302
+ return value && value.then ? value.then(then) : then(value);
2303
+ }
2304
+ function Mutex_classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
2305
+ function Mutex_defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, Mutex_toPropertyKey(descriptor.key), descriptor); } }
2306
+ function Mutex_createClass(Constructor, protoProps, staticProps) { if (protoProps) Mutex_defineProperties(Constructor.prototype, protoProps); if (staticProps) Mutex_defineProperties(Constructor, staticProps); Object.defineProperty(Constructor, "prototype", { writable: false }); return Constructor; }
2307
+ function Mutex_toPropertyKey(arg) { var key = Mutex_toPrimitive(arg, "string"); return Mutex_typeof(key) === "symbol" ? key : String(key); }
2308
+ function Mutex_toPrimitive(input, hint) { if (Mutex_typeof(input) !== "object" || input === null) return input; var prim = input[Symbol.toPrimitive]; if (prim !== undefined) { var res = prim.call(input, hint || "default"); if (Mutex_typeof(res) !== "object") return res; throw new TypeError("@@toPrimitive must return a primitive value."); } return (hint === "string" ? String : Number)(input); }
2309
+ /**
2310
+ * A lightweight mutex. (Other libraries contain too many features and we want to keep the size upload-js down).
2311
+ *
2312
+ * Characteristics:
2313
+ * - Non-reentrant.
2314
+ * - Unfair. (Multiple callers awaiting 'acquire' will be granted the mutex in no order.)
2315
+ * - When calling `safe` consecutively with no 'awaits' in-between, the current context will synchronously acquire
2316
+ * the mutex every time.
2317
+ */
2318
+ var Mutex = /*#__PURE__*/function () {
2319
+ function Mutex() {
2320
+ Mutex_classCallCheck(this, Mutex);
2321
+ this.mutex = undefined;
2322
+ this.resolver = undefined;
2323
+ }
2324
+ Mutex_createClass(Mutex, [{
2325
+ key: "safe",
2326
+ value: function safe(callback) {
2327
+ try {
2328
+ var _this2 = this;
2329
+ return Mutex_await(_this2.acquire(), function () {
2330
+ return Mutex_finallyRethrows(callback, function (_wasThrown, _result) {
2331
+ _this2.release();
2332
+ return Mutex_rethrow(_wasThrown, _result);
2333
+ });
2334
+ });
2335
+ } catch (e) {
2336
+ return Promise.reject(e);
2439
2337
  }
2440
- throw new Error("Unsupported type for 'data' parameter. Please provide a String, Blob, or Readable (Node.js).");
2441
2338
  }
2442
2339
  }, {
2443
- key: "foldDataRaw",
2444
- value: function foldDataRaw(data, handle) {
2340
+ key: "acquire",
2341
+ value: function acquire() {
2445
2342
  try {
2446
- var _exit8 = false;
2447
- var _this16 = this;
2448
- return UploadManager_invoke(function () {
2449
- if (typeof data === "string") {
2450
- _exit8 = true;
2451
- var _ifBlob2 = handle.ifBlob;
2452
- return UploadManager_await(_this16.stringToBlob(data), function (_this15$stringToBlob) {
2453
- return UploadManager_await(_ifBlob2.call(handle, _this15$stringToBlob));
2454
- });
2455
- }
2456
- }, function (_result3) {
2457
- var _exit5 = false;
2458
- if (_exit8) return _result3;
2459
- return UploadManager_invoke(function () {
2460
- if (data.on !== undefined) {
2461
- _exit5 = true;
2462
- return UploadManager_await(handle.ifNodeJsStream(data));
2463
- }
2464
- }, function (_result4) {
2465
- var _exit6 = false;
2466
- if (_exit5) return _result4;
2467
- return UploadManager_invoke(function () {
2468
- if (data.subarray !== undefined) {
2469
- _exit6 = true;
2470
- return UploadManager_await(handle.ifBuffer(data));
2471
- }
2472
- }, function (_result5) {
2473
- var _exit7 = false;
2474
- if (_exit6) return _result5;
2475
- return UploadManager_invoke(function () {
2476
- if (data.slice !== undefined) {
2477
- _exit7 = true;
2478
- return UploadManager_await(handle.ifBlob(data));
2479
- }
2480
- }, function (_result6) {
2481
- if (_exit7) return _result6;
2482
- throw new Error("Unsupported type for 'data' parameter. Please provide a String, Blob, or Readable (Node.js).");
2483
- });
2484
- });
2343
+ var _this4 = this;
2344
+ // Loop necessary for when multiple calls are made to 'acquire' before a 'release' is called, else the call to
2345
+ // 'release' will resume every caller currently waiting on 'acquire'.
2346
+ return Mutex_continue(Mutex_for(function () {
2347
+ return _this4.mutex !== undefined;
2348
+ }, void 0, function () {
2349
+ return Mutex_awaitIgnored(_this4.mutex);
2350
+ }), function () {
2351
+ _this4.mutex = new Promise(function (resolve) {
2352
+ _this4.resolver = resolve;
2485
2353
  });
2486
2354
  });
2487
2355
  } catch (e) {
@@ -2489,102 +2357,292 @@ var UploadManager = /*#__PURE__*/function () {
2489
2357
  }
2490
2358
  }
2491
2359
  }, {
2492
- key: "processUploadSource",
2493
- value: function processUploadSource(data) {
2360
+ key: "release",
2361
+ value: function release() {
2362
+ if (this.resolver === undefined) {
2363
+ throw new Error("Unable to release mutex: already released.");
2364
+ }
2365
+ this.resolver();
2366
+ this.resolver = undefined;
2367
+ this.mutex = undefined;
2368
+ }
2369
+ }]);
2370
+ return Mutex;
2371
+ }();
2372
+ ;// CONCATENATED MODULE: ./src/public/browser/AuthManagerBrowser.ts
2373
+ function AuthManagerBrowser_typeof(obj) { "@babel/helpers - typeof"; return AuthManagerBrowser_typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (obj) { return typeof obj; } : function (obj) { return obj && "function" == typeof Symbol && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }, AuthManagerBrowser_typeof(obj); }
2374
+ function AuthManagerBrowser_defineProperty(obj, key, value) { key = AuthManagerBrowser_toPropertyKey(key); if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }
2375
+ function AuthManagerBrowser_empty() {}
2376
+ function AuthManagerBrowser_awaitIgnored(value, direct) {
2377
+ if (!direct) {
2378
+ return value && value.then ? value.then(AuthManagerBrowser_empty) : Promise.resolve();
2379
+ }
2380
+ }
2381
+ function AuthManagerBrowser_await(value, then, direct) {
2382
+ if (direct) {
2383
+ return then ? then(value) : value;
2384
+ }
2385
+ if (!value || !value.then) {
2386
+ value = Promise.resolve(value);
2387
+ }
2388
+ return then ? value.then(then) : value;
2389
+ }
2390
+ function AuthManagerBrowser_async(f) {
2391
+ return function () {
2392
+ for (var args = [], i = 0; i < arguments.length; i++) {
2393
+ args[i] = arguments[i];
2394
+ }
2395
+ try {
2396
+ return Promise.resolve(f.apply(this, args));
2397
+ } catch (e) {
2398
+ return Promise.reject(e);
2399
+ }
2400
+ };
2401
+ }
2402
+ function AuthManagerBrowser_catch(body, recover) {
2403
+ try {
2404
+ var result = body();
2405
+ } catch (e) {
2406
+ return recover(e);
2407
+ }
2408
+ if (result && result.then) {
2409
+ return result.then(void 0, recover);
2410
+ }
2411
+ return result;
2412
+ }
2413
+ function AuthManagerBrowser_rethrow(thrown, value) {
2414
+ if (thrown) throw value;
2415
+ return value;
2416
+ }
2417
+ function AuthManagerBrowser_finallyRethrows(body, finalizer) {
2418
+ try {
2419
+ var result = body();
2420
+ } catch (e) {
2421
+ return finalizer(true, e);
2422
+ }
2423
+ if (result && result.then) {
2424
+ return result.then(finalizer.bind(null, false), finalizer.bind(null, true));
2425
+ }
2426
+ return finalizer(false, result);
2427
+ }
2428
+ function AuthManagerBrowser_continueIgnored(value) {
2429
+ if (value && value.then) {
2430
+ return value.then(AuthManagerBrowser_empty);
2431
+ }
2432
+ }
2433
+ function AuthManagerBrowser_classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
2434
+ function AuthManagerBrowser_defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, AuthManagerBrowser_toPropertyKey(descriptor.key), descriptor); } }
2435
+ function AuthManagerBrowser_createClass(Constructor, protoProps, staticProps) { if (protoProps) AuthManagerBrowser_defineProperties(Constructor.prototype, protoProps); if (staticProps) AuthManagerBrowser_defineProperties(Constructor, staticProps); Object.defineProperty(Constructor, "prototype", { writable: false }); return Constructor; }
2436
+ function AuthManagerBrowser_toPropertyKey(arg) { var key = AuthManagerBrowser_toPrimitive(arg, "string"); return AuthManagerBrowser_typeof(key) === "symbol" ? key : String(key); }
2437
+ function AuthManagerBrowser_toPrimitive(input, hint) { if (AuthManagerBrowser_typeof(input) !== "object" || input === null) return input; var prim = input[Symbol.toPrimitive]; if (prim !== undefined) { var res = prim.call(input, hint || "default"); if (AuthManagerBrowser_typeof(res) !== "object") return res; throw new TypeError("@@toPrimitive must return a primitive value."); } return (hint === "string" ? String : Number)(input); }
2438
+ function AuthManagerBrowser_inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function"); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, writable: true, configurable: true } }); Object.defineProperty(subClass, "prototype", { writable: false }); if (superClass) AuthManagerBrowser_setPrototypeOf(subClass, superClass); }
2439
+ function AuthManagerBrowser_setPrototypeOf(o, p) { AuthManagerBrowser_setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return AuthManagerBrowser_setPrototypeOf(o, p); }
2440
+ function AuthManagerBrowser_createSuper(Derived) { var hasNativeReflectConstruct = AuthManagerBrowser_isNativeReflectConstruct(); return function _createSuperInternal() { var Super = AuthManagerBrowser_getPrototypeOf(Derived), result; if (hasNativeReflectConstruct) { var NewTarget = AuthManagerBrowser_getPrototypeOf(this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return AuthManagerBrowser_possibleConstructorReturn(this, result); }; }
2441
+ function AuthManagerBrowser_possibleConstructorReturn(self, call) { if (call && (AuthManagerBrowser_typeof(call) === "object" || typeof call === "function")) { return call; } else if (call !== void 0) { throw new TypeError("Derived constructors may only return object or undefined"); } return AuthManagerBrowser_assertThisInitialized(self); }
2442
+ function AuthManagerBrowser_assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self; }
2443
+ function AuthManagerBrowser_isNativeReflectConstruct() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); return true; } catch (e) { return false; } }
2444
+ function AuthManagerBrowser_getPrototypeOf(o) { AuthManagerBrowser_getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf.bind() : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return AuthManagerBrowser_getPrototypeOf(o); }
2445
+
2446
+
2447
+
2448
+
2449
+ var AuthManager = /*#__PURE__*/function (_BaseAPI) {
2450
+ AuthManagerBrowser_inherits(AuthManager, _BaseAPI);
2451
+ var _super = AuthManagerBrowser_createSuper(AuthManager);
2452
+ function AuthManager(config) {
2453
+ var _this;
2454
+ AuthManagerBrowser_classCallCheck(this, AuthManager);
2455
+ var _a, _b;
2456
+ _this = _super.call(this, config);
2457
+ _this.authSessionMutex = new Mutex();
2458
+ _this.contentType = "content-type";
2459
+ _this.contentTypeJson = "application/json";
2460
+ _this.contentTypeText = "text/plain";
2461
+ _this.minJwtTtlSeconds = 10;
2462
+ _this.retryAuthAfterErrorSeconds = 5;
2463
+ _this.refreshBeforeExpirySeconds = 20;
2464
+ var accountId;
2465
+ if (BaseAPI.specialApiKeys.includes(config.apiKey)) {
2466
+ accountId = BaseAPI.specialApiKeyAccountId;
2467
+ } else {
2468
+ accountId = (_b = (_a = config.apiKey.split("_")[1]) === null || _a === void 0 ? void 0 : _a.substr(0, BaseAPI.accountIdLength)) !== null && _b !== void 0 ? _b : "";
2469
+ if (accountId.length !== BaseAPI.accountIdLength) {
2470
+ throw new Error("Invalid Bytescale API key.");
2471
+ }
2472
+ }
2473
+ _this.accessTokenUrl = "".concat(BytescaleApiClientConfigResolver.getCdnUrl(config), "/api/v1/access_tokens/").concat(accountId);
2474
+ return _this;
2475
+ }
2476
+ AuthManagerBrowser_createClass(AuthManager, [{
2477
+ key: "isAuthSessionActive",
2478
+ value: function isAuthSessionActive() {
2479
+ return AuthSessionState.session !== undefined;
2480
+ }
2481
+ }, {
2482
+ key: "beginAuthSession",
2483
+ value: function beginAuthSession(authUrl, authHeaders) {
2494
2484
  try {
2495
- var _exit10 = false;
2496
- var _this18 = this;
2497
- return UploadManager_invoke(function () {
2498
- if (typeof data === "string") {
2499
- _exit10 = true;
2500
- return UploadManager_await(_this18.stringToBlob(data));
2501
- }
2502
- }, function (_result7) {
2503
- if (_exit10) return _result7;
2504
- if (data.on !== undefined) {
2505
- return new ChunkedStream(data);
2485
+ var _this3 = this;
2486
+ var newSession = {
2487
+ accessToken: undefined,
2488
+ accessTokenRefreshHandle: undefined,
2489
+ authUrl: authUrl,
2490
+ authHeaders: authHeaders,
2491
+ isActive: true
2492
+ };
2493
+ return AuthManagerBrowser_await(_this3.authSessionMutex.safe(AuthManagerBrowser_async(function () {
2494
+ // We check both 'session' and 'sessionDisposing' here, as we don't want to call 'beginAuthSession' until the session is fully disposed.
2495
+ if (_this3.isAuthSessionActive()) {
2496
+ throw new Error("Auth session already active: see AuthManager.isAuthSessionActive(). Please call 'await endAuthSession()' and then 'await beginAuthSession(...)' if you want to start a new auth session.");
2506
2497
  }
2507
- if (data.subarray !== undefined) {
2508
- return data;
2498
+ AuthSessionState.session = newSession;
2499
+ return AuthManagerBrowser_await();
2500
+ })), function () {
2501
+ // IMPORTANT: must be called outside the above, else re-entrant deadlock will occur.
2502
+ return AuthManagerBrowser_awaitIgnored(_this3.refreshAccessToken(newSession));
2503
+ });
2504
+ } catch (e) {
2505
+ return Promise.reject(e);
2506
+ }
2507
+ }
2508
+ }, {
2509
+ key: "endAuthSession",
2510
+ value: function endAuthSession() {
2511
+ try {
2512
+ var _this5 = this;
2513
+ return AuthManagerBrowser_awaitIgnored(_this5.authSessionMutex.safe(AuthManagerBrowser_async(function () {
2514
+ if (AuthSessionState.session === undefined) {
2515
+ return;
2509
2516
  }
2510
- if (data.slice !== undefined) {
2511
- return data;
2517
+ var session = AuthSessionState.session;
2518
+ AuthSessionState.session = undefined;
2519
+ session.isActive = false;
2520
+ if (session.accessTokenRefreshHandle !== undefined) {
2521
+ clearTimeout(session.accessTokenRefreshHandle);
2512
2522
  }
2513
- throw new Error("Unsupported type for 'data' parameter. Please provide a String, Blob, or Readable (Node.js).");
2514
- });
2523
+ return AuthManagerBrowser_awaitIgnored(_this5.deleteAccessToken());
2524
+ })));
2515
2525
  } catch (e) {
2516
2526
  return Promise.reject(e);
2517
2527
  }
2518
2528
  }
2519
2529
  }, {
2520
- key: "stringToBlob",
2521
- value: function stringToBlob(data) {
2530
+ key: "refreshAccessToken",
2531
+ value: function refreshAccessToken(session) {
2522
2532
  try {
2523
- var _this20 = this;
2524
- var _a;
2525
- var _temp2 = (_a = _this20.globalBlob(data)) !== null && _a !== void 0;
2526
- return UploadManager_await(_temp2 ? _a : _this20.nodeJsBlob(data), void 0, _temp2);
2533
+ var _this7 = this;
2534
+ return AuthManagerBrowser_awaitIgnored(_this7.authSessionMutex.safe(AuthManagerBrowser_async(function () {
2535
+ if (!session.isActive) {
2536
+ return;
2537
+ }
2538
+ var timeout = _this7.retryAuthAfterErrorSeconds;
2539
+ return AuthManagerBrowser_continueIgnored(AuthManagerBrowser_finallyRethrows(function () {
2540
+ return AuthManagerBrowser_catch(function () {
2541
+ var _getAccessToken = _this7.getAccessToken,
2542
+ _session$authUrl = session.authUrl;
2543
+ return AuthManagerBrowser_await(session.authHeaders(), function (_session$authHeaders) {
2544
+ return AuthManagerBrowser_await(_getAccessToken.call(_this7, _session$authUrl, _session$authHeaders), function (jwt) {
2545
+ return AuthManagerBrowser_await(_this7.setAccessToken(jwt), function (setTokenResult) {
2546
+ var desiredTtl = setTokenResult.ttlSeconds - _this7.refreshBeforeExpirySeconds;
2547
+ timeout = Math.max(desiredTtl, _this7.minJwtTtlSeconds);
2548
+ if (desiredTtl !== timeout) {
2549
+ ConsoleUtils.warn("JWT expiration is too short: waiting for ".concat(timeout, " seconds before refreshing."));
2550
+ }
2551
+ session.accessToken = setTokenResult.accessToken;
2552
+ });
2553
+ });
2554
+ });
2555
+ }, function (e) {
2556
+ // Use 'error' instead of 'debug' so that the user sees error messages.
2557
+ ConsoleUtils.error("Error when refreshing access token: ".concat(e));
2558
+ });
2559
+ }, function (_wasThrown, _result) {
2560
+ session.accessTokenRefreshHandle = window.setTimeout(function () {
2561
+ _this7.refreshAccessToken(session).then(function () {}, function (e) {
2562
+ return ConsoleUtils.error("Unexpected error when refreshing access token: ".concat(e));
2563
+ });
2564
+ }, timeout * 1000);
2565
+ return AuthManagerBrowser_rethrow(_wasThrown, _result);
2566
+ }));
2567
+ })));
2527
2568
  } catch (e) {
2528
2569
  return Promise.reject(e);
2529
2570
  }
2530
- } // Supported by browsers & newer versions of Node.js.
2571
+ }
2531
2572
  }, {
2532
- key: "globalBlob",
2533
- value: function globalBlob(data) {
2534
- var B = globalThis.Blob;
2535
- if (B === undefined) {
2536
- return undefined;
2537
- }
2538
- return new B([data], {
2539
- type: this.stringMimeType
2540
- });
2573
+ key: "deleteAccessToken",
2574
+ value: function deleteAccessToken() {
2575
+ try {
2576
+ var _this9 = this;
2577
+ return AuthManagerBrowser_awaitIgnored(_this9.doFetch(_this9.accessTokenUrl, {
2578
+ method: "DELETE",
2579
+ credentials: "include",
2580
+ headers: {}
2581
+ }, true));
2582
+ } catch (e) {
2583
+ return Promise.reject(e);
2584
+ }
2541
2585
  }
2542
- // Fallback for Node.js
2543
2586
  }, {
2544
- key: "nodeJsBlob",
2545
- value: function nodeJsBlob(data) {
2587
+ key: "setAccessToken",
2588
+ value: function setAccessToken(jwt) {
2546
2589
  try {
2547
- var _this22 = this;
2548
- return UploadManager_await(NodeUtils.createBlob([data], {
2549
- type: _this22.stringMimeType
2550
- }));
2590
+ var _this11 = this;
2591
+ var request = {
2592
+ accessToken: jwt
2593
+ };
2594
+ return AuthManagerBrowser_await(_this11.doFetch(_this11.accessTokenUrl, {
2595
+ method: "PUT",
2596
+ credentials: "include",
2597
+ headers: AuthManagerBrowser_defineProperty({}, _this11.contentType, _this11.contentTypeJson),
2598
+ body: JSON.stringify(request)
2599
+ }, true), function (response) {
2600
+ return AuthManagerBrowser_await(response.json());
2601
+ });
2551
2602
  } catch (e) {
2552
2603
  return Promise.reject(e);
2553
2604
  }
2554
2605
  }
2555
2606
  }, {
2556
- key: "mapAsync",
2557
- value: function mapAsync(items, concurrency, callback) {
2607
+ key: "getAccessToken",
2608
+ value: function getAccessToken(authUrl, headers) {
2558
2609
  try {
2559
- var workQueue = _toConsumableArray(items);
2560
- return _awaitIgnored(Promise.all(_toConsumableArray(Array(concurrency).keys()).map(UploadManager_async(function () {
2561
- return _continueIgnored(_for(function () {
2562
- return workQueue.length > 0;
2563
- }, void 0, function () {
2564
- var work = workQueue.shift(); // IMPORTANT: use 'shift' instead of 'pop' to ensure 'items' are processed in order when 'concurrency = 1'.
2565
- return _invokeIgnored(function () {
2566
- if (work !== undefined) {
2567
- return _awaitIgnored(callback(work));
2568
- }
2569
- });
2570
- }));
2571
- }))));
2610
+ var _this13 = this;
2611
+ var endpointName = "Your auth API endpoint";
2612
+ var requiredContentType = _this13.contentTypeText;
2613
+ return AuthManagerBrowser_await(_this13.doFetch(authUrl, {
2614
+ method: "GET",
2615
+ headers: headers
2616
+ }, false), function (result) {
2617
+ if (result.headers.get(_this13.contentType) !== requiredContentType) {
2618
+ throw new Error("".concat(endpointName, " returned an unsupported '").concat(_this13.contentType, "' response header: please return '").concat(requiredContentType, "'."));
2619
+ }
2620
+ return AuthManagerBrowser_await(result.text(), function (jwt) {
2621
+ if (jwt.length === 0) {
2622
+ throw new Error("".concat(endpointName, " returned an empty string. Please return a valid JWT instead."));
2623
+ }
2624
+ if (jwt.trim().length !== jwt.length) {
2625
+ // Whitespace can be a nightmare to spot/debug, so we fail early here.
2626
+ throw new Error("".concat(endpointName, " returned whitespace around the JWT, please remove it."));
2627
+ }
2628
+ return jwt;
2629
+ });
2630
+ });
2572
2631
  } catch (e) {
2573
2632
  return Promise.reject(e);
2574
2633
  }
2575
2634
  }
2576
2635
  }]);
2577
- return UploadManager;
2578
- }();
2579
- ;// CONCATENATED MODULE: ./src/uploads/index.ts
2580
-
2636
+ return AuthManager;
2637
+ }(BaseAPI);
2638
+ ;// CONCATENATED MODULE: ./src/public/browser/index.ts
2581
2639
 
2582
2640
 
2583
- ;// CONCATENATED MODULE: ./src/index.ts
2641
+ ;// CONCATENATED MODULE: ./src/index.browser.ts
2584
2642
  /* tslint:disable */
2585
2643
  /* eslint-disable */
2586
2644
 
2587
2645
 
2588
- module.exports = __webpack_exports__;
2646
+ module.exports = __lib_exports__;
2589
2647
  /******/ })()
2590
2648
  ;