@bytescale/sdk 3.0.0-alpha.9 → 3.1.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 (30) hide show
  1. package/README.md +388 -48
  2. package/dist/browser/cjs/main.js +704 -568
  3. package/dist/node/cjs/main.js +622 -240
  4. package/dist/node/esm/main.mjs +622 -240
  5. package/dist/types/index.d.ts +1 -1
  6. package/dist/types/private/AuthSessionState.d.ts +25 -8
  7. package/dist/types/private/EnvChecker.d.ts +1 -1
  8. package/dist/types/private/Mutex.d.ts +1 -1
  9. package/dist/types/private/StreamUtils.d.ts +1 -0
  10. package/dist/types/private/UploadManagerBase.d.ts +6 -1
  11. package/dist/types/private/UploadManagerBrowserWorkerBase.d.ts +19 -0
  12. package/dist/types/private/UploadManagerFetchUtils.d.ts +8 -0
  13. package/dist/types/private/model/AuthManagerInterface.d.ts +22 -5
  14. package/dist/types/private/model/AuthSession.d.ts +2 -2
  15. package/dist/types/private/model/OnPartProgress.d.ts +1 -1
  16. package/dist/types/private/model/UploadSourceProcessed.d.ts +6 -1
  17. package/dist/types/public/browser/AuthManagerBrowser.d.ts +10 -6
  18. package/dist/types/public/browser/UploadManagerBrowser.d.ts +3 -12
  19. package/dist/types/public/node/AuthManagerNode.d.ts +8 -3
  20. package/dist/types/public/shared/CommonTypes.d.ts +0 -1
  21. package/dist/types/public/shared/UrlBuilder.d.ts +10 -12
  22. package/dist/types/public/shared/UrlBuilderTypes.d.ts +0 -6
  23. package/dist/types/public/shared/generated/runtime.d.ts +7 -5
  24. package/dist/types/public/worker/UploadManagerWorker.d.ts +8 -0
  25. package/dist/types/public/worker/index.d.ts +2 -0
  26. package/dist/worker/cjs/main.js +2578 -0
  27. package/dist/worker/esm/main.mjs +2578 -0
  28. package/package.json +7 -4
  29. package/tests/UploadManager.test.ts +0 -7
  30. package/tests/UrlBuilder.test.ts +33 -27
@@ -1,25 +1,3 @@
1
- // ----------------------------------------
2
- // POLYFILL GUIDE:
3
- // ----------------------------------------
4
- //
5
- // "buffer" & "stream" are not required for browser environments.
6
- //
7
- // They are only used when the code detects it's running in Node.js (at runtime).
8
- //
9
- // You may polyfill them with empty objects (for browser environments):
10
- //
11
- // ----------------------------------------
12
- // Webpack:
13
- // {
14
- // resolve: {
15
- // fallback: {
16
- // buffer: false,
17
- // stream: false
18
- // }
19
- // }
20
- // }
21
- // ----------------------------------------
22
- //
23
1
  import * as __WEBPACK_EXTERNAL_MODULE_stream__ from "stream";
24
2
  import * as __WEBPACK_EXTERNAL_MODULE_buffer__ from "buffer";
25
3
  /******/ // The require scope
@@ -67,16 +45,332 @@ __lib_require__.d(__lib_exports__, {
67
45
  "querystring": function() { return /* reexport */ querystring; }
68
46
  });
69
47
 
70
- ;// CONCATENATED MODULE: ./src/private/AuthSessionState.ts
48
+ ;// CONCATENATED MODULE: ./src/private/Mutex.ts
71
49
  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); }
50
+ function _call(body, then, direct) {
51
+ if (direct) {
52
+ return then ? then(body()) : body();
53
+ }
54
+ try {
55
+ var result = Promise.resolve(body());
56
+ return then ? result.then(then) : result;
57
+ } catch (e) {
58
+ return Promise.reject(e);
59
+ }
60
+ }
61
+ function _rethrow(thrown, value) {
62
+ if (thrown) throw value;
63
+ return value;
64
+ }
65
+ function _finallyRethrows(body, finalizer) {
66
+ try {
67
+ var result = body();
68
+ } catch (e) {
69
+ return finalizer(true, e);
70
+ }
71
+ if (result && result.then) {
72
+ return result.then(finalizer.bind(null, false), finalizer.bind(null, true));
73
+ }
74
+ return finalizer(false, result);
75
+ }
76
+ function _await(value, then, direct) {
77
+ if (direct) {
78
+ return then ? then(value) : value;
79
+ }
80
+ if (!value || !value.then) {
81
+ value = Promise.resolve(value);
82
+ }
83
+ return then ? value.then(then) : value;
84
+ }
85
+ function _empty() {}
86
+ function _awaitIgnored(value, direct) {
87
+ if (!direct) {
88
+ return value && value.then ? value.then(_empty) : Promise.resolve();
89
+ }
90
+ }
91
+ function _settle(pact, state, value) {
92
+ if (!pact.s) {
93
+ if (value instanceof _Pact) {
94
+ if (value.s) {
95
+ if (state & 1) {
96
+ state = value.s;
97
+ }
98
+ value = value.v;
99
+ } else {
100
+ value.o = _settle.bind(null, pact, state);
101
+ return;
102
+ }
103
+ }
104
+ if (value && value.then) {
105
+ value.then(_settle.bind(null, pact, state), _settle.bind(null, pact, 2));
106
+ return;
107
+ }
108
+ pact.s = state;
109
+ pact.v = value;
110
+ var observer = pact.o;
111
+ if (observer) {
112
+ observer(pact);
113
+ }
114
+ }
115
+ }
116
+ var _Pact = /*#__PURE__*/function () {
117
+ function _Pact() {}
118
+ _Pact.prototype.then = function (onFulfilled, onRejected) {
119
+ var result = new _Pact();
120
+ var state = this.s;
121
+ if (state) {
122
+ var callback = state & 1 ? onFulfilled : onRejected;
123
+ if (callback) {
124
+ try {
125
+ _settle(result, 1, callback(this.v));
126
+ } catch (e) {
127
+ _settle(result, 2, e);
128
+ }
129
+ return result;
130
+ } else {
131
+ return this;
132
+ }
133
+ }
134
+ this.o = function (_this) {
135
+ try {
136
+ var value = _this.v;
137
+ if (_this.s & 1) {
138
+ _settle(result, 1, onFulfilled ? onFulfilled(value) : value);
139
+ } else if (onRejected) {
140
+ _settle(result, 1, onRejected(value));
141
+ } else {
142
+ _settle(result, 2, value);
143
+ }
144
+ } catch (e) {
145
+ _settle(result, 2, e);
146
+ }
147
+ };
148
+ return result;
149
+ };
150
+ return _Pact;
151
+ }();
152
+ function _isSettledPact(thenable) {
153
+ return thenable instanceof _Pact && thenable.s & 1;
154
+ }
155
+ function _for(test, update, body) {
156
+ var stage;
157
+ for (;;) {
158
+ var shouldContinue = test();
159
+ if (_isSettledPact(shouldContinue)) {
160
+ shouldContinue = shouldContinue.v;
161
+ }
162
+ if (!shouldContinue) {
163
+ return result;
164
+ }
165
+ if (shouldContinue.then) {
166
+ stage = 0;
167
+ break;
168
+ }
169
+ var result = body();
170
+ if (result && result.then) {
171
+ if (_isSettledPact(result)) {
172
+ result = result.s;
173
+ } else {
174
+ stage = 1;
175
+ break;
176
+ }
177
+ }
178
+ if (update) {
179
+ var updateValue = update();
180
+ if (updateValue && updateValue.then && !_isSettledPact(updateValue)) {
181
+ stage = 2;
182
+ break;
183
+ }
184
+ }
185
+ }
186
+ var pact = new _Pact();
187
+ var reject = _settle.bind(null, pact, 2);
188
+ (stage === 0 ? shouldContinue.then(_resumeAfterTest) : stage === 1 ? result.then(_resumeAfterBody) : updateValue.then(_resumeAfterUpdate)).then(void 0, reject);
189
+ return pact;
190
+ function _resumeAfterBody(value) {
191
+ result = value;
192
+ do {
193
+ if (update) {
194
+ updateValue = update();
195
+ if (updateValue && updateValue.then && !_isSettledPact(updateValue)) {
196
+ updateValue.then(_resumeAfterUpdate).then(void 0, reject);
197
+ return;
198
+ }
199
+ }
200
+ shouldContinue = test();
201
+ if (!shouldContinue || _isSettledPact(shouldContinue) && !shouldContinue.v) {
202
+ _settle(pact, 1, result);
203
+ return;
204
+ }
205
+ if (shouldContinue.then) {
206
+ shouldContinue.then(_resumeAfterTest).then(void 0, reject);
207
+ return;
208
+ }
209
+ result = body();
210
+ if (_isSettledPact(result)) {
211
+ result = result.v;
212
+ }
213
+ } while (!result || !result.then);
214
+ result.then(_resumeAfterBody).then(void 0, reject);
215
+ }
216
+ function _resumeAfterTest(shouldContinue) {
217
+ if (shouldContinue) {
218
+ result = body();
219
+ if (result && result.then) {
220
+ result.then(_resumeAfterBody).then(void 0, reject);
221
+ } else {
222
+ _resumeAfterBody(result);
223
+ }
224
+ } else {
225
+ _settle(pact, 1, result);
226
+ }
227
+ }
228
+ function _resumeAfterUpdate() {
229
+ if (shouldContinue = test()) {
230
+ if (shouldContinue.then) {
231
+ shouldContinue.then(_resumeAfterTest).then(void 0, reject);
232
+ } else {
233
+ _resumeAfterTest(shouldContinue);
234
+ }
235
+ } else {
236
+ _settle(pact, 1, result);
237
+ }
238
+ }
239
+ }
240
+ function _continue(value, then) {
241
+ return value && value.then ? value.then(then) : then(value);
242
+ }
243
+ function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
72
244
  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); } }
73
245
  function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); Object.defineProperty(Constructor, "prototype", { writable: false }); return Constructor; }
74
246
  function _toPropertyKey(arg) { var key = _toPrimitive(arg, "string"); return _typeof(key) === "symbol" ? key : String(key); }
75
247
  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); }
76
- function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
77
- var AuthSessionState = /*#__PURE__*/_createClass(function AuthSessionState() {
78
- _classCallCheck(this, AuthSessionState);
79
- });
248
+ /**
249
+ * A lightweight mutex. (Other libraries contain too many features and we want to keep size down).
250
+ *
251
+ * Characteristics:
252
+ * - Non-reentrant.
253
+ * - Unfair. (Multiple callers awaiting 'acquire' will be granted the mutex in no order.)
254
+ * - When calling `safe` consecutively with no 'awaits' in-between, the current context will synchronously acquire
255
+ * the mutex every time.
256
+ */
257
+ var Mutex = /*#__PURE__*/function () {
258
+ function Mutex() {
259
+ _classCallCheck(this, Mutex);
260
+ this.mutex = undefined;
261
+ this.resolver = undefined;
262
+ }
263
+ _createClass(Mutex, [{
264
+ key: "safe",
265
+ value: function safe(callback) {
266
+ try {
267
+ var _this2 = this;
268
+ return _await(_this2.acquire(), function () {
269
+ return _finallyRethrows(callback, function (_wasThrown, _result) {
270
+ _this2.release();
271
+ return _rethrow(_wasThrown, _result);
272
+ });
273
+ });
274
+ } catch (e) {
275
+ return Promise.reject(e);
276
+ }
277
+ }
278
+ }, {
279
+ key: "acquire",
280
+ value: function acquire() {
281
+ try {
282
+ var _this4 = this;
283
+ // Loop necessary for when multiple calls are made to 'acquire' before a 'release' is called, else the call to
284
+ // 'release' will resume every caller currently waiting on 'acquire'.
285
+ return _continue(_for(function () {
286
+ return _this4.mutex !== undefined;
287
+ }, void 0, function () {
288
+ return _awaitIgnored(_this4.mutex);
289
+ }), function () {
290
+ _this4.mutex = new Promise(function (resolve) {
291
+ _this4.resolver = resolve;
292
+ });
293
+ });
294
+ } catch (e) {
295
+ return Promise.reject(e);
296
+ }
297
+ }
298
+ }, {
299
+ key: "release",
300
+ value: function release() {
301
+ if (this.resolver === undefined) {
302
+ throw new Error("Unable to release mutex: already released.");
303
+ }
304
+ this.resolver();
305
+ this.resolver = undefined;
306
+ this.mutex = undefined;
307
+ }
308
+ }]);
309
+ return Mutex;
310
+ }();
311
+ ;// CONCATENATED MODULE: ./src/private/AuthSessionState.ts
312
+ function AuthSessionState_typeof(obj) { "@babel/helpers - typeof"; return AuthSessionState_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; }, AuthSessionState_typeof(obj); }
313
+ function AuthSessionState_classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
314
+ function AuthSessionState_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, AuthSessionState_toPropertyKey(descriptor.key), descriptor); } }
315
+ function AuthSessionState_createClass(Constructor, protoProps, staticProps) { if (protoProps) AuthSessionState_defineProperties(Constructor.prototype, protoProps); if (staticProps) AuthSessionState_defineProperties(Constructor, staticProps); Object.defineProperty(Constructor, "prototype", { writable: false }); return Constructor; }
316
+ function AuthSessionState_toPropertyKey(arg) { var key = AuthSessionState_toPrimitive(arg, "string"); return AuthSessionState_typeof(key) === "symbol" ? key : String(key); }
317
+ function AuthSessionState_toPrimitive(input, hint) { if (AuthSessionState_typeof(input) !== "object" || input === null) return input; var prim = input[Symbol.toPrimitive]; if (prim !== undefined) { var res = prim.call(input, hint || "default"); if (AuthSessionState_typeof(res) !== "object") return res; throw new TypeError("@@toPrimitive must return a primitive value."); } return (hint === "string" ? String : Number)(input); }
318
+
319
+ /**
320
+ * Maintains a global session state, even across package versions.
321
+ *
322
+ * This is to allow users to start auth sessions via the Bytescale JavaScript SDK, where due to versioning or other
323
+ * bundling issues, the Bytescale Upload Widget has been bundled with a different Bytescale JavaScript SDK. In this
324
+ * scenario, the user wouldn't be able to start an auth session with the Bytescale Upload Widget. Therefore, we use
325
+ * global state (i.e. on the window) to ensure the session state can be shared between the user's instance of the
326
+ * Bytescale JavaScript SDK and the Upload Widget's version of the Bytescale JavaScript SDK.
327
+ *
328
+ * Users also frequently have problems caused by them not keeping track of *Api and *Manager instances correctly, so
329
+ * making this global prevents a lot of common mistakes.
330
+ */
331
+ var AuthSessionState = /*#__PURE__*/function () {
332
+ function AuthSessionState() {
333
+ AuthSessionState_classCallCheck(this, AuthSessionState);
334
+ }
335
+ AuthSessionState_createClass(AuthSessionState, null, [{
336
+ key: "getMutex",
337
+ value:
338
+ /**
339
+ * Called in the browser only.
340
+ */
341
+ function getMutex() {
342
+ var key = AuthSessionState.mutexKey;
343
+ var mutex = window[key];
344
+ if (mutex === undefined) {
345
+ mutex = new Mutex();
346
+ window[key] = mutex;
347
+ }
348
+ return mutex;
349
+ }
350
+ /**
351
+ * Called in the browser only.
352
+ */
353
+ }, {
354
+ key: "setSession",
355
+ value: function setSession(session) {
356
+ window[AuthSessionState.stateKey] = session;
357
+ }
358
+ /**
359
+ * Called in the browser and in Node.js (so we check the env before calling env-specific code).
360
+ */
361
+ }, {
362
+ key: "getSession",
363
+ value: function getSession() {
364
+ if (typeof window === "undefined") {
365
+ return undefined;
366
+ }
367
+ return window[AuthSessionState.stateKey];
368
+ }
369
+ }]);
370
+ return AuthSessionState;
371
+ }();
372
+ AuthSessionState.stateKey = "BytescaleSessionState";
373
+ AuthSessionState.mutexKey = "BytescaleSessionStateMutex";
80
374
  ;// CONCATENATED MODULE: ./src/public/shared/generated/runtime.ts
81
375
  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); }
82
376
  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); }
@@ -100,8 +394,8 @@ function _catch(body, recover) {
100
394
  }
101
395
  return result;
102
396
  }
103
- function _empty() {}
104
- function _continue(value, then) {
397
+ function runtime_empty() {}
398
+ function runtime_continue(value, then) {
105
399
  return value && value.then ? value.then(then) : then(value);
106
400
  }
107
401
  function _invoke(body, then) {
@@ -112,7 +406,7 @@ function _invoke(body, then) {
112
406
  return then(result);
113
407
  }
114
408
  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; }
115
- function _await(value, then, direct) {
409
+ function runtime_await(value, then, direct) {
116
410
  if (direct) {
117
411
  return then ? then(value) : value;
118
412
  }
@@ -200,72 +494,30 @@ var BaseAPI = /*#__PURE__*/function () {
200
494
  this.config = config;
201
495
  BytescaleApiClientConfigUtils.validate(config);
202
496
  }
497
+ /**
498
+ * Returns a successful response (2**) else throws an error.
499
+ */
203
500
  runtime_createClass(BaseAPI, [{
204
501
  key: "request",
205
502
  value: function request(context, initOverrides, baseUrlOverride) {
206
503
  try {
207
504
  var _this2 = this;
208
- var _a, _b;
505
+ var _a;
209
506
  var apiKey = _this2.config.apiKey;
210
507
  context.headers["Authorization"] = "Bearer ".concat(apiKey); // authorization-header authentication
211
- if (((_a = AuthSessionState.session) === null || _a === void 0 ? void 0 : _a.accessToken) !== undefined) {
212
- context.headers["Authorization-Token"] = AuthSessionState.session.accessToken;
508
+ var session = AuthSessionState.getSession();
509
+ if ((session === null || session === void 0 ? void 0 : session.accessToken) !== undefined) {
510
+ context.headers["Authorization-Token"] = session.accessToken;
213
511
  }
214
512
  // Key: any possible value for 'baseUrlOverride'
215
513
  // Value: user-overridden value for that base URL from the config.
216
514
  var nonDefaultBasePaths = _defineProperty({}, BytescaleApiClientConfigUtils.defaultCdnUrl, BytescaleApiClientConfigUtils.getCdnUrl(_this2.config));
217
- return _await(_this2.createFetchParams(context, initOverrides, baseUrlOverride === undefined ? undefined : (_b = nonDefaultBasePaths[baseUrlOverride]) !== null && _b !== void 0 ? _b : baseUrlOverride), function (_ref) {
515
+ return runtime_await(_this2.createFetchParams(context, initOverrides, baseUrlOverride === undefined ? undefined : (_a = nonDefaultBasePaths[baseUrlOverride]) !== null && _a !== void 0 ? _a : baseUrlOverride), function (_ref) {
218
516
  var url = _ref.url,
219
517
  init = _ref.init;
220
- return _this2.doFetch(url, init, true);
221
- });
222
- } catch (e) {
223
- return Promise.reject(e);
224
- }
225
- }
226
- /**
227
- * Returns a successful response (2**) else throws an error.
228
- */
229
- }, {
230
- key: "doFetch",
231
- value: function doFetch(url, init, isBytescaleApi) {
232
- try {
233
- var _exit3 = false;
234
- var _this4 = this;
235
- var _a, _b;
236
- var response;
237
- return _continue(_catch(function () {
238
- return _await(BytescaleApiClientConfigUtils.getFetchApi(_this4.config)(url, init), function (_BytescaleApiClientCo) {
239
- response = _BytescaleApiClientCo;
240
- });
241
- }, function (e) {
242
- // Network-level errors, CORS errors, or HTTP-level errors from intermediary services (e.g. AWS or the user's own infrastructure/proxies).
243
- // 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.
244
- 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));
245
- }), function (_result) {
246
- var _exit2 = false;
247
- if (_exit3) return _result;
248
- return response.status >= 200 && response.status < 300 ? response : _invoke(function () {
249
- if (isBytescaleApi) {
250
- var jsonError = undefined;
251
- return _continue(_catch(function () {
252
- return _await(response.json(), function (_response$json) {
253
- jsonError = _response$json;
254
- });
255
- }, _empty), function () {
256
- if (typeof ((_a = jsonError === null || jsonError === void 0 ? void 0 : jsonError.error) === null || _a === void 0 ? void 0 : _a.code) === "string") {
257
- throw new BytescaleApiError(jsonError);
258
- }
259
- // HTTP-level errors from intermediary services (e.g. AWS or the user's own infrastructure/proxies). On the browser,
260
- // this error is unlikely to be triggered since these errors will masqurade as CORS errors (see above) but in Node.js
261
- // this error will appear from any intermediary service failure.
262
- throw new Error("Unable to connect to the Bytescale API (".concat(response.status, "): please try again."));
263
- });
264
- }
265
- }, function (_result2) {
266
- if (_exit2) return _result2;
267
- throw new Error("Failure status code (".concat(response.status, ") received for request: ").concat((_b = init.method) !== null && _b !== void 0 ? _b : "GET", " ").concat(url));
268
- });
518
+ return BaseAPI.fetch(url, init, Object.assign(Object.assign({}, _this2.config), {
519
+ isBytescaleApi: true
520
+ }));
269
521
  });
270
522
  } catch (e) {
271
523
  return Promise.reject(e);
@@ -288,23 +540,23 @@ var BaseAPI = /*#__PURE__*/function () {
288
540
  key: "createFetchParams",
289
541
  value: function createFetchParams(context, initOverrides, baseUrlOverride) {
290
542
  try {
291
- var _this6 = this;
292
- var url = (baseUrlOverride !== null && baseUrlOverride !== void 0 ? baseUrlOverride : BytescaleApiClientConfigUtils.getApiUrl(_this6.config)) + context.path;
543
+ var _this4 = this;
544
+ var url = (baseUrlOverride !== null && baseUrlOverride !== void 0 ? baseUrlOverride : BytescaleApiClientConfigUtils.getApiUrl(_this4.config)) + context.path;
293
545
  if (context.query !== undefined && Object.keys(context.query).length !== 0) {
294
546
  // only add the querystring to the URL if there are query parameters.
295
547
  // this is done to avoid urls ending with a "?" character which buggy webservers
296
548
  // do not handle correctly sometimes.
297
549
  url += "?" + querystring(context.query);
298
550
  }
299
- var configHeaders = _this6.config.headers;
551
+ var configHeaders = _this4.config.headers;
300
552
  var _Object$assign3 = Object.assign({}, context.headers);
301
- return _await(configHeaders === undefined ? {} : configHeaders(), function (_configHeaders) {
553
+ return runtime_await(configHeaders === undefined ? {} : configHeaders(), function (_configHeaders) {
302
554
  var headers = Object.assign(_Object$assign3, _configHeaders);
303
555
  Object.keys(headers).forEach(function (key) {
304
556
  return headers[key] === undefined ? delete headers[key] : {};
305
557
  });
306
558
  var initOverrideFn = typeof initOverrides === "function" ? initOverrides : function () {
307
- return _await(initOverrides);
559
+ return runtime_await(initOverrides);
308
560
  };
309
561
  var initParams = {
310
562
  method: context.method,
@@ -312,7 +564,7 @@ var BaseAPI = /*#__PURE__*/function () {
312
564
  body: context.body
313
565
  };
314
566
  var _Object$assign2 = Object.assign({}, initParams);
315
- return _await(initOverrideFn({
567
+ return runtime_await(initOverrideFn({
316
568
  init: initParams,
317
569
  context: context
318
570
  }), function (_initOverrideFn) {
@@ -330,6 +582,59 @@ var BaseAPI = /*#__PURE__*/function () {
330
582
  return Promise.reject(e);
331
583
  }
332
584
  }
585
+ }], [{
586
+ key: "fetch",
587
+ value: function fetch(url, init, config) {
588
+ try {
589
+ var _exit3 = false;
590
+ var _a, _b;
591
+ var response;
592
+ return runtime_continue(_catch(function () {
593
+ return runtime_await(BytescaleApiClientConfigUtils.getFetchApi(config)(url, Object.assign(Object.assign({}, init), {
594
+ // This is specifically added to cater for Next.js's Fetch implementation, which caches POST requests...
595
+ //
596
+ // "fetch requests that use the POST method are also automatically cached."
597
+ // - https://nextjs.org/docs/app/building-your-application/data-fetching/fetching-caching-and-revalidating#caching-data
598
+ //
599
+ // However, this is probably a good idea, even for all GET requests, as if the user is refreshing a JWT
600
+ // or downloading a file via 'FileApi.downloadFile', then they'll likely want the latest.
601
+ cache: "no-store"
602
+ })), function (_BytescaleApiClientCo) {
603
+ response = _BytescaleApiClientCo;
604
+ });
605
+ }, function (e) {
606
+ // Network-level errors, CORS errors, or HTTP-level errors from intermediary services (e.g. AWS or the user's own infrastructure/proxies).
607
+ // 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.
608
+ throw new Error(config.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));
609
+ }), function (_result) {
610
+ var _exit2 = false;
611
+ if (_exit3) return _result;
612
+ return response.status >= 200 && response.status < 300 ? response : _invoke(function () {
613
+ if (config.isBytescaleApi) {
614
+ var jsonError = undefined;
615
+ return runtime_continue(_catch(function () {
616
+ return runtime_await(response.json(), function (_response$json) {
617
+ jsonError = _response$json;
618
+ });
619
+ }, runtime_empty), function () {
620
+ if (typeof ((_a = jsonError === null || jsonError === void 0 ? void 0 : jsonError.error) === null || _a === void 0 ? void 0 : _a.code) === "string") {
621
+ throw new BytescaleApiError(jsonError);
622
+ }
623
+ // HTTP-level errors from intermediary services (e.g. AWS or the user's own infrastructure/proxies). On the browser,
624
+ // this error is unlikely to be triggered since these errors will masqurade as CORS errors (see above) but in Node.js
625
+ // this error will appear from any intermediary service failure.
626
+ throw new Error("Unable to connect to the Bytescale API (".concat(response.status, "): please try again."));
627
+ });
628
+ }
629
+ }, function (_result2) {
630
+ if (_exit2) return _result2;
631
+ throw new Error("Failure status code (".concat(response.status, ") received for request: ").concat((_b = init.method) !== null && _b !== void 0 ? _b : "GET", " ").concat(url));
632
+ });
633
+ });
634
+ } catch (e) {
635
+ return Promise.reject(e);
636
+ }
637
+ }
333
638
  }]);
334
639
  return BaseAPI;
335
640
  }();
@@ -337,11 +642,11 @@ var CancelledError = /*#__PURE__*/function (_Error) {
337
642
  _inherits(CancelledError, _Error);
338
643
  var _super = _createSuper(CancelledError);
339
644
  function CancelledError() {
340
- var _this7;
645
+ var _this5;
341
646
  runtime_classCallCheck(this, CancelledError);
342
- _this7 = _super.call(this, "Operation cancelled by caller.");
343
- _this7.name = "CancelledError";
344
- return _this7;
647
+ _this5 = _super.call(this, "Operation cancelled by caller.");
648
+ _this5.name = "CancelledError";
649
+ return _this5;
345
650
  }
346
651
  return runtime_createClass(CancelledError);
347
652
  }( /*#__PURE__*/_wrapNativeSuper(Error));
@@ -349,13 +654,13 @@ var BytescaleApiError = /*#__PURE__*/function (_Error2) {
349
654
  _inherits(BytescaleApiError, _Error2);
350
655
  var _super2 = _createSuper(BytescaleApiError);
351
656
  function BytescaleApiError(response) {
352
- var _this8;
657
+ var _this6;
353
658
  runtime_classCallCheck(this, BytescaleApiError);
354
- _this8 = _super2.call(this, response.error.message);
355
- _this8.name = "BytescaleApiError";
356
- _this8.errorCode = response.error.code;
357
- _this8.details = response.error.details;
358
- return _this8;
659
+ _this6 = _super2.call(this, response.error.message);
660
+ _this6.name = "BytescaleApiError";
661
+ _this6.errorCode = response.error.code;
662
+ _this6.details = response.error.details;
663
+ return _this6;
359
664
  }
360
665
  return runtime_createClass(BytescaleApiError);
361
666
  }( /*#__PURE__*/_wrapNativeSuper(Error));
@@ -381,8 +686,8 @@ var JSONApiResponse = /*#__PURE__*/function () {
381
686
  key: "value",
382
687
  value: function value() {
383
688
  try {
384
- var _this10 = this;
385
- return _await(_this10.raw.json());
689
+ var _this8 = this;
690
+ return runtime_await(_this8.raw.json());
386
691
  } catch (e) {
387
692
  return Promise.reject(e);
388
693
  }
@@ -398,7 +703,7 @@ var VoidApiResponse = /*#__PURE__*/function () {
398
703
  runtime_createClass(VoidApiResponse, [{
399
704
  key: "value",
400
705
  value: function value() {
401
- return _await(undefined);
706
+ return runtime_await(undefined);
402
707
  }
403
708
  }]);
404
709
  return VoidApiResponse;
@@ -423,8 +728,8 @@ var BinaryResult = /*#__PURE__*/function () {
423
728
  key: "text",
424
729
  value: function text() {
425
730
  try {
426
- var _this12 = this;
427
- return _await(_this12.raw.text());
731
+ var _this10 = this;
732
+ return runtime_await(_this10.raw.text());
428
733
  } catch (e) {
429
734
  return Promise.reject(e);
430
735
  }
@@ -433,8 +738,8 @@ var BinaryResult = /*#__PURE__*/function () {
433
738
  key: "blob",
434
739
  value: function blob() {
435
740
  try {
436
- var _this14 = this;
437
- return _await(_this14.raw.blob());
741
+ var _this12 = this;
742
+ return runtime_await(_this12.raw.blob());
438
743
  } catch (e) {
439
744
  return Promise.reject(e);
440
745
  }
@@ -443,8 +748,8 @@ var BinaryResult = /*#__PURE__*/function () {
443
748
  key: "json",
444
749
  value: function json() {
445
750
  try {
446
- var _this16 = this;
447
- return _await(_this16.raw.json());
751
+ var _this14 = this;
752
+ return runtime_await(_this14.raw.json());
448
753
  } catch (e) {
449
754
  return Promise.reject(e);
450
755
  }
@@ -1369,33 +1674,32 @@ function UrlBuilder_toPrimitive(input, hint) { if (UrlBuilder_typeof(input) !==
1369
1674
 
1370
1675
 
1371
1676
  var UrlBuilder = /*#__PURE__*/function () {
1372
- function UrlBuilder(config) {
1677
+ function UrlBuilder() {
1373
1678
  UrlBuilder_classCallCheck(this, UrlBuilder);
1374
- var _a;
1375
- this.cdnUrl = (_a = config === null || config === void 0 ? void 0 : config.cdnUrl) !== null && _a !== void 0 ? _a : BytescaleApiClientConfigUtils.defaultCdnUrl;
1376
1679
  }
1377
- /**
1378
- * Builds a URL to either a raw file or a transformed file.
1379
- *
1380
- * Example 1) Getting a publicly-accessible raw file URL:
1381
- *
1382
- * new UrlBuilder().url({ accountId: "1234abc", filePath: "/example.jpg" })
1383
- *
1384
- * Example 2) Getting a publicly-accessible image URL, resized to 500x500:
1385
- *
1386
- * new UrlBuilder().url({ accountId: "1234abc", filePath: "/example.jpg", options: { transformation: { type: "image", params: { w: 500, h: 500, fit: "crop" } } } })
1387
- *
1388
- * Example 3) Getting a privately-accessible image URL, resized to 500x500 (requires 'AuthManager.beginAuthSession' to be called before accessing the URL):
1389
- *
1390
- * new UrlBuilder().url({ accountId: "1234abc", filePath: "/example.jpg", options: { transformation: { type: "image", params: { w: 500, h: 500, fit: "crop" } }, auth: true } })
1391
- *
1392
- * Example 4) Getting a publicly-accessible image URL, resized using a transformation preset called "thumbnail" that was created manually in the Bytescale Dashboard:
1393
- *
1394
- * new UrlBuilder().url({ accountId: "1234abc", filePath: "/example.jpg", options: { transformation: { type: "preset", preset: "thumbnail" } } })
1395
- */
1396
- UrlBuilder_createClass(UrlBuilder, [{
1680
+ UrlBuilder_createClass(UrlBuilder, null, [{
1397
1681
  key: "url",
1398
- value: function url(params) {
1682
+ value:
1683
+ /**
1684
+ * Builds a URL to either a raw file or a transformed file.
1685
+ *
1686
+ * Example 1) Getting a publicly-accessible raw file URL:
1687
+ *
1688
+ * new UrlBuilder().url({ accountId: "1234abc", filePath: "/example.jpg" })
1689
+ *
1690
+ * Example 2) Getting a publicly-accessible image URL, resized to 500x500:
1691
+ *
1692
+ * new UrlBuilder().url({ accountId: "1234abc", filePath: "/example.jpg", options: { transformation: { type: "image", params: { w: 500, h: 500, fit: "crop" } } } })
1693
+ *
1694
+ * Example 3) Getting a privately-accessible image URL, resized to 500x500 (requires 'AuthManager.beginAuthSession' to be called before accessing the URL):
1695
+ *
1696
+ * new UrlBuilder().url({ accountId: "1234abc", filePath: "/example.jpg", options: { transformation: { type: "image", params: { w: 500, h: 500, fit: "crop" } }, auth: true } })
1697
+ *
1698
+ * Example 4) Getting a publicly-accessible image URL, resized using a transformation preset called "thumbnail" that was created manually in the Bytescale Dashboard:
1699
+ *
1700
+ * new UrlBuilder().url({ accountId: "1234abc", filePath: "/example.jpg", options: { transformation: { type: "preset", preset: "thumbnail" } } })
1701
+ */
1702
+ function url(params) {
1399
1703
  var _a;
1400
1704
  return ((_a = params.options) === null || _a === void 0 ? void 0 : _a.transformation) === undefined ? this.raw(params) : this.transformation(params, params.options);
1401
1705
  }
@@ -1421,7 +1725,8 @@ var UrlBuilder = /*#__PURE__*/function () {
1421
1725
  }, {
1422
1726
  key: "getBaseUrl",
1423
1727
  value: function getBaseUrl(params, prefix) {
1424
- return "".concat(this.cdnUrl, "/").concat(params.accountId, "/").concat(prefix).concat(params.filePath);
1728
+ var cdnUrl = BytescaleApiClientConfigUtils.defaultCdnUrl;
1729
+ return "".concat(cdnUrl, "/").concat(params.accountId, "/").concat(prefix).concat(params.filePath);
1425
1730
  }
1426
1731
  }, {
1427
1732
  key: "getCommonTransformationQueryParams",
@@ -1516,21 +1821,21 @@ function _invokeIgnored(body) {
1516
1821
  return result.then(UploadManagerBase_empty);
1517
1822
  }
1518
1823
  }
1519
- function _settle(pact, state, value) {
1824
+ function UploadManagerBase_settle(pact, state, value) {
1520
1825
  if (!pact.s) {
1521
- if (value instanceof _Pact) {
1826
+ if (value instanceof UploadManagerBase_Pact) {
1522
1827
  if (value.s) {
1523
1828
  if (state & 1) {
1524
1829
  state = value.s;
1525
1830
  }
1526
1831
  value = value.v;
1527
1832
  } else {
1528
- value.o = _settle.bind(null, pact, state);
1833
+ value.o = UploadManagerBase_settle.bind(null, pact, state);
1529
1834
  return;
1530
1835
  }
1531
1836
  }
1532
1837
  if (value && value.then) {
1533
- value.then(_settle.bind(null, pact, state), _settle.bind(null, pact, 2));
1838
+ value.then(UploadManagerBase_settle.bind(null, pact, state), UploadManagerBase_settle.bind(null, pact, 2));
1534
1839
  return;
1535
1840
  }
1536
1841
  pact.s = state;
@@ -1541,7 +1846,7 @@ function _settle(pact, state, value) {
1541
1846
  }
1542
1847
  }
1543
1848
  }
1544
- var _Pact = /*#__PURE__*/function () {
1849
+ var UploadManagerBase_Pact = /*#__PURE__*/function () {
1545
1850
  function _Pact() {}
1546
1851
  _Pact.prototype.then = function (onFulfilled, onRejected) {
1547
1852
  var result = new _Pact();
@@ -1550,9 +1855,9 @@ var _Pact = /*#__PURE__*/function () {
1550
1855
  var callback = state & 1 ? onFulfilled : onRejected;
1551
1856
  if (callback) {
1552
1857
  try {
1553
- _settle(result, 1, callback(this.v));
1858
+ UploadManagerBase_settle(result, 1, callback(this.v));
1554
1859
  } catch (e) {
1555
- _settle(result, 2, e);
1860
+ UploadManagerBase_settle(result, 2, e);
1556
1861
  }
1557
1862
  return result;
1558
1863
  } else {
@@ -1563,28 +1868,28 @@ var _Pact = /*#__PURE__*/function () {
1563
1868
  try {
1564
1869
  var value = _this.v;
1565
1870
  if (_this.s & 1) {
1566
- _settle(result, 1, onFulfilled ? onFulfilled(value) : value);
1871
+ UploadManagerBase_settle(result, 1, onFulfilled ? onFulfilled(value) : value);
1567
1872
  } else if (onRejected) {
1568
- _settle(result, 1, onRejected(value));
1873
+ UploadManagerBase_settle(result, 1, onRejected(value));
1569
1874
  } else {
1570
- _settle(result, 2, value);
1875
+ UploadManagerBase_settle(result, 2, value);
1571
1876
  }
1572
1877
  } catch (e) {
1573
- _settle(result, 2, e);
1878
+ UploadManagerBase_settle(result, 2, e);
1574
1879
  }
1575
1880
  };
1576
1881
  return result;
1577
1882
  };
1578
1883
  return _Pact;
1579
1884
  }();
1580
- function _isSettledPact(thenable) {
1581
- return thenable instanceof _Pact && thenable.s & 1;
1885
+ function UploadManagerBase_isSettledPact(thenable) {
1886
+ return thenable instanceof UploadManagerBase_Pact && thenable.s & 1;
1582
1887
  }
1583
- function _for(test, update, body) {
1888
+ function UploadManagerBase_for(test, update, body) {
1584
1889
  var stage;
1585
1890
  for (;;) {
1586
1891
  var shouldContinue = test();
1587
- if (_isSettledPact(shouldContinue)) {
1892
+ if (UploadManagerBase_isSettledPact(shouldContinue)) {
1588
1893
  shouldContinue = shouldContinue.v;
1589
1894
  }
1590
1895
  if (!shouldContinue) {
@@ -1596,7 +1901,7 @@ function _for(test, update, body) {
1596
1901
  }
1597
1902
  var result = body();
1598
1903
  if (result && result.then) {
1599
- if (_isSettledPact(result)) {
1904
+ if (UploadManagerBase_isSettledPact(result)) {
1600
1905
  result = result.s;
1601
1906
  } else {
1602
1907
  stage = 1;
@@ -1605,14 +1910,14 @@ function _for(test, update, body) {
1605
1910
  }
1606
1911
  if (update) {
1607
1912
  var updateValue = update();
1608
- if (updateValue && updateValue.then && !_isSettledPact(updateValue)) {
1913
+ if (updateValue && updateValue.then && !UploadManagerBase_isSettledPact(updateValue)) {
1609
1914
  stage = 2;
1610
1915
  break;
1611
1916
  }
1612
1917
  }
1613
1918
  }
1614
- var pact = new _Pact();
1615
- var reject = _settle.bind(null, pact, 2);
1919
+ var pact = new UploadManagerBase_Pact();
1920
+ var reject = UploadManagerBase_settle.bind(null, pact, 2);
1616
1921
  (stage === 0 ? shouldContinue.then(_resumeAfterTest) : stage === 1 ? result.then(_resumeAfterBody) : updateValue.then(_resumeAfterUpdate)).then(void 0, reject);
1617
1922
  return pact;
1618
1923
  function _resumeAfterBody(value) {
@@ -1620,14 +1925,14 @@ function _for(test, update, body) {
1620
1925
  do {
1621
1926
  if (update) {
1622
1927
  updateValue = update();
1623
- if (updateValue && updateValue.then && !_isSettledPact(updateValue)) {
1928
+ if (updateValue && updateValue.then && !UploadManagerBase_isSettledPact(updateValue)) {
1624
1929
  updateValue.then(_resumeAfterUpdate).then(void 0, reject);
1625
1930
  return;
1626
1931
  }
1627
1932
  }
1628
1933
  shouldContinue = test();
1629
- if (!shouldContinue || _isSettledPact(shouldContinue) && !shouldContinue.v) {
1630
- _settle(pact, 1, result);
1934
+ if (!shouldContinue || UploadManagerBase_isSettledPact(shouldContinue) && !shouldContinue.v) {
1935
+ UploadManagerBase_settle(pact, 1, result);
1631
1936
  return;
1632
1937
  }
1633
1938
  if (shouldContinue.then) {
@@ -1635,7 +1940,7 @@ function _for(test, update, body) {
1635
1940
  return;
1636
1941
  }
1637
1942
  result = body();
1638
- if (_isSettledPact(result)) {
1943
+ if (UploadManagerBase_isSettledPact(result)) {
1639
1944
  result = result.v;
1640
1945
  }
1641
1946
  } while (!result || !result.then);
@@ -1650,7 +1955,7 @@ function _for(test, update, body) {
1650
1955
  _resumeAfterBody(result);
1651
1956
  }
1652
1957
  } else {
1653
- _settle(pact, 1, result);
1958
+ UploadManagerBase_settle(pact, 1, result);
1654
1959
  }
1655
1960
  }
1656
1961
  function _resumeAfterUpdate() {
@@ -1661,7 +1966,7 @@ function _for(test, update, body) {
1661
1966
  _resumeAfterTest(shouldContinue);
1662
1967
  }
1663
1968
  } else {
1664
- _settle(pact, 1, result);
1969
+ UploadManagerBase_settle(pact, 1, result);
1665
1970
  }
1666
1971
  }
1667
1972
  }
@@ -1677,7 +1982,7 @@ function UploadManagerBase_iterableToArray(iter) { if (typeof Symbol !== "undefi
1677
1982
  function UploadManagerBase_arrayWithoutHoles(arr) { if (Array.isArray(arr)) return UploadManagerBase_arrayLikeToArray(arr); }
1678
1983
  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; }
1679
1984
  function UploadManagerBase_empty() {}
1680
- function _awaitIgnored(value, direct) {
1985
+ function UploadManagerBase_awaitIgnored(value, direct) {
1681
1986
  if (!direct) {
1682
1987
  return value && value.then ? value.then(UploadManagerBase_empty) : Promise.resolve();
1683
1988
  }
@@ -1691,11 +1996,11 @@ function UploadManagerBase_await(value, then, direct) {
1691
1996
  }
1692
1997
  return then ? value.then(then) : value;
1693
1998
  }
1694
- function _rethrow(thrown, value) {
1999
+ function UploadManagerBase_rethrow(thrown, value) {
1695
2000
  if (thrown) throw value;
1696
2001
  return value;
1697
2002
  }
1698
- function _finallyRethrows(body, finalizer) {
2003
+ function UploadManagerBase_finallyRethrows(body, finalizer) {
1699
2004
  try {
1700
2005
  var result = body();
1701
2006
  } catch (e) {
@@ -1726,6 +2031,7 @@ var UploadManagerBase = /*#__PURE__*/function () {
1726
2031
  this.defaultMaxConcurrentUploadParts = 4;
1727
2032
  this.intervalMs = 500;
1728
2033
  this.uploadApi = new UploadApi(config);
2034
+ this.accountId = BytescaleApiClientConfigUtils.getAccountId(config);
1729
2035
  }
1730
2036
  UploadManagerBase_createClass(UploadManagerBase, [{
1731
2037
  key: "upload",
@@ -1735,10 +2041,13 @@ var UploadManagerBase = /*#__PURE__*/function () {
1735
2041
  _this2.assertNotCancelled(request);
1736
2042
  var source = _this2.processUploadSource(request.data);
1737
2043
  var preUploadInfo = _this2.getPreUploadInfo(request, source);
1738
- var onProgress = _this2.makeProgressCallback(request, preUploadInfo.size);
2044
+ var bytesTotal = preUploadInfo.size;
2045
+ var makeOnProgressForPart = _this2.makeOnProgressForPartFactory(request, bytesTotal);
1739
2046
  var init = _this2.preUpload(source);
1740
2047
  // Raise initial progress event SYNCHRONOUSLY.
1741
- onProgress(0);
2048
+ if (request.onProgress !== undefined) {
2049
+ request.onProgress(_this2.makeProgressEvent(0, bytesTotal));
2050
+ }
1742
2051
  return UploadManagerBase_await(_this2.beginUpload(request, preUploadInfo), function (uploadInfo) {
1743
2052
  var partCount = uploadInfo.uploadParts.count;
1744
2053
  var parts = UploadManagerBase_toConsumableArray(Array(partCount).keys());
@@ -1746,15 +2055,15 @@ var UploadManagerBase = /*#__PURE__*/function () {
1746
2055
  cancel = _this2$makeCancellati.cancel,
1747
2056
  addCancellationHandler = _this2$makeCancellati.addCancellationHandler;
1748
2057
  var intervalHandle = setInterval(_this2.onIntervalTick(request, cancel), _this2.intervalMs);
1749
- return UploadManagerBase_continue(_finallyRethrows(function () {
2058
+ return UploadManagerBase_continue(UploadManagerBase_finallyRethrows(function () {
1750
2059
  return UploadManagerBase_await(_this2.mapAsync(parts, preUploadInfo.maxConcurrentUploadParts, _async(function (part) {
1751
- return _this2.uploadPart(request, source, part, uploadInfo, onProgress, addCancellationHandler);
2060
+ return _this2.uploadPart(request, source, part, uploadInfo, makeOnProgressForPart(), addCancellationHandler);
1752
2061
  })), function () {
1753
- return _awaitIgnored(_this2.postUpload(init));
2062
+ return UploadManagerBase_awaitIgnored(_this2.postUpload(init));
1754
2063
  });
1755
2064
  }, function (_wasThrown, _result) {
1756
2065
  clearInterval(intervalHandle);
1757
- return _rethrow(_wasThrown, _result);
2066
+ return UploadManagerBase_rethrow(_wasThrown, _result);
1758
2067
  }), function () {
1759
2068
  return uploadInfo.file;
1760
2069
  });
@@ -1804,21 +2113,37 @@ var UploadManagerBase = /*#__PURE__*/function () {
1804
2113
  addCancellationHandler: addCancellationHandler
1805
2114
  };
1806
2115
  }
2116
+ /**
2117
+ * Returns a callback, which when called, returns a callback that can be used by ONE specific part to report its progress.
2118
+ */
1807
2119
  }, {
1808
- key: "makeProgressCallback",
1809
- value: function makeProgressCallback(request, bytesTotal) {
2120
+ key: "makeOnProgressForPartFactory",
2121
+ value: function makeOnProgressForPartFactory(request, bytesTotal) {
2122
+ var _this4 = this;
1810
2123
  var onProgress = request.onProgress;
1811
2124
  if (onProgress === undefined) {
1812
- return function () {};
2125
+ return function () {
2126
+ return function () {};
2127
+ };
1813
2128
  }
1814
2129
  var bytesSent = 0;
1815
- return function (bytesSentDelta) {
1816
- bytesSent += bytesSentDelta;
1817
- onProgress({
1818
- bytesTotal: bytesTotal,
1819
- bytesSent: bytesSent,
1820
- progress: Math.round(bytesSent / bytesTotal * 100)
1821
- });
2130
+ return function () {
2131
+ var bytesSentForPart = 0;
2132
+ return function (bytesSentTotalForPart) {
2133
+ var delta = bytesSentTotalForPart - bytesSentForPart;
2134
+ bytesSentForPart += delta;
2135
+ bytesSent += delta;
2136
+ onProgress(_this4.makeProgressEvent(bytesSent, bytesTotal));
2137
+ };
2138
+ };
2139
+ }
2140
+ }, {
2141
+ key: "makeProgressEvent",
2142
+ value: function makeProgressEvent(bytesSent, bytesTotal) {
2143
+ return {
2144
+ bytesTotal: bytesTotal,
2145
+ bytesSent: bytesSent,
2146
+ progress: Math.round(bytesSent / bytesTotal * 100)
1822
2147
  };
1823
2148
  }
1824
2149
  }, {
@@ -1841,9 +2166,9 @@ var UploadManagerBase = /*#__PURE__*/function () {
1841
2166
  mime = _ref2.mime,
1842
2167
  originalFileName = _ref2.originalFileName;
1843
2168
  try {
1844
- var _this5 = this;
1845
- return UploadManagerBase_await(_this5.uploadApi.beginMultipartUpload({
1846
- accountId: request.accountId,
2169
+ var _this6 = this;
2170
+ return UploadManagerBase_await(_this6.uploadApi.beginMultipartUpload({
2171
+ accountId: _this6.accountId,
1847
2172
  beginMultipartUploadRequest: {
1848
2173
  metadata: request.metadata,
1849
2174
  mime: mime,
@@ -1862,14 +2187,14 @@ var UploadManagerBase = /*#__PURE__*/function () {
1862
2187
  key: "uploadPart",
1863
2188
  value: function uploadPart(request, source, partIndex, uploadInfo, onProgress, addCancellationHandler) {
1864
2189
  try {
1865
- var _this7 = this;
1866
- _this7.assertNotCancelled(request);
1867
- return UploadManagerBase_await(_this7.getUploadPart(request, partIndex, uploadInfo), function (part) {
1868
- _this7.assertNotCancelled(request);
1869
- return UploadManagerBase_await(_this7.putUploadPart(part, source, onProgress, addCancellationHandler), function (etag) {
1870
- _this7.assertNotCancelled(request);
1871
- return _awaitIgnored(_this7.uploadApi.completeUploadPart({
1872
- accountId: request.accountId,
2190
+ var _this8 = this;
2191
+ _this8.assertNotCancelled(request);
2192
+ return UploadManagerBase_await(_this8.getUploadPart(partIndex, uploadInfo), function (part) {
2193
+ _this8.assertNotCancelled(request);
2194
+ return UploadManagerBase_await(_this8.putUploadPart(part, source, onProgress, addCancellationHandler), function (etag) {
2195
+ _this8.assertNotCancelled(request);
2196
+ return UploadManagerBase_awaitIgnored(_this8.uploadApi.completeUploadPart({
2197
+ accountId: _this8.accountId,
1873
2198
  uploadId: uploadInfo.uploadId,
1874
2199
  uploadPartIndex: partIndex,
1875
2200
  completeUploadPartRequest: {
@@ -1889,9 +2214,9 @@ var UploadManagerBase = /*#__PURE__*/function () {
1889
2214
  key: "putUploadPart",
1890
2215
  value: function putUploadPart(part, source, onProgress, addCancellationHandler) {
1891
2216
  try {
1892
- var _this9 = this;
2217
+ var _this10 = this;
1893
2218
  var contentLength = part.range.inclusiveEnd + 1 - part.range.inclusiveStart;
1894
- return UploadManagerBase_await(_this9.doPutUploadPart(part, contentLength, source, onProgress, addCancellationHandler), function (_ref3) {
2219
+ return UploadManagerBase_await(_this10.doPutUploadPart(part, contentLength, source, onProgress, addCancellationHandler), function (_ref3) {
1895
2220
  var status = _ref3.status,
1896
2221
  etag = _ref3.etag;
1897
2222
  if (Math.floor(status / 100) !== 2) {
@@ -1900,6 +2225,8 @@ var UploadManagerBase = /*#__PURE__*/function () {
1900
2225
  if (etag === undefined) {
1901
2226
  throw new Error("No 'etag' response header found in upload part response.");
1902
2227
  }
2228
+ // Always send 100% for part, as some UploadManager implementations either don't report progress, or may not report the last chunk uploaded.
2229
+ onProgress(contentLength);
1903
2230
  return etag;
1904
2231
  });
1905
2232
  } catch (e) {
@@ -1908,15 +2235,15 @@ var UploadManagerBase = /*#__PURE__*/function () {
1908
2235
  }
1909
2236
  }, {
1910
2237
  key: "getUploadPart",
1911
- value: function getUploadPart(request, partIndex, uploadInfo) {
2238
+ value: function getUploadPart(partIndex, uploadInfo) {
1912
2239
  try {
1913
- var _this11 = this;
2240
+ var _this12 = this;
1914
2241
  if (partIndex === 0) {
1915
2242
  return uploadInfo.uploadParts.first;
1916
2243
  }
1917
- return UploadManagerBase_await(_this11.uploadApi.getUploadPart({
2244
+ return UploadManagerBase_await(_this12.uploadApi.getUploadPart({
1918
2245
  uploadId: uploadInfo.uploadId,
1919
- accountId: request.accountId,
2246
+ accountId: _this12.accountId,
1920
2247
  uploadPartIndex: partIndex
1921
2248
  }));
1922
2249
  } catch (e) {
@@ -1940,14 +2267,14 @@ var UploadManagerBase = /*#__PURE__*/function () {
1940
2267
  value: function mapAsync(items, concurrency, callback) {
1941
2268
  try {
1942
2269
  var workQueue = UploadManagerBase_toConsumableArray(items);
1943
- return _awaitIgnored(Promise.all(UploadManagerBase_toConsumableArray(Array(concurrency).keys()).map(_async(function () {
1944
- return _continueIgnored(_for(function () {
2270
+ return UploadManagerBase_awaitIgnored(Promise.all(UploadManagerBase_toConsumableArray(Array(concurrency).keys()).map(_async(function () {
2271
+ return _continueIgnored(UploadManagerBase_for(function () {
1945
2272
  return workQueue.length > 0;
1946
2273
  }, void 0, function () {
1947
2274
  var work = workQueue.shift(); // IMPORTANT: use 'shift' instead of 'pop' to ensure 'items' are processed in order when 'concurrency = 1'.
1948
2275
  return _invokeIgnored(function () {
1949
2276
  if (work !== undefined) {
1950
- return _awaitIgnored(callback(work));
2277
+ return UploadManagerBase_awaitIgnored(callback(work));
1951
2278
  }
1952
2279
  });
1953
2280
  }));
@@ -1989,6 +2316,11 @@ var StreamUtils = /*#__PURE__*/function () {
1989
2316
  StreamUtils.endStream(readable);
1990
2317
  return readable;
1991
2318
  }
2319
+ }, {
2320
+ key: "fromArrayBuffer",
2321
+ value: function fromArrayBuffer(buffer) {
2322
+ return StreamUtils.fromBuffer(Buffer.from(buffer));
2323
+ }
1992
2324
  }, {
1993
2325
  key: "fromBuffer",
1994
2326
  value: function fromBuffer(buffer) {
@@ -2199,6 +2531,62 @@ var NodeChunkedStream = /*#__PURE__*/function () {
2199
2531
  var external_buffer_x = y => { var x = {}; __lib_require__.d(x, y); return x; }
2200
2532
  var external_buffer_y = x => () => x
2201
2533
  var external_buffer_namespaceObject = external_buffer_x({ ["Blob"]: () => __WEBPACK_EXTERNAL_MODULE_buffer__.Blob });
2534
+ ;// CONCATENATED MODULE: ./src/private/UploadManagerFetchUtils.ts
2535
+ function UploadManagerFetchUtils_typeof(obj) { "@babel/helpers - typeof"; return UploadManagerFetchUtils_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; }, UploadManagerFetchUtils_typeof(obj); }
2536
+ function UploadManagerFetchUtils_await(value, then, direct) {
2537
+ if (direct) {
2538
+ return then ? then(value) : value;
2539
+ }
2540
+ if (!value || !value.then) {
2541
+ value = Promise.resolve(value);
2542
+ }
2543
+ return then ? value.then(then) : value;
2544
+ }
2545
+ function UploadManagerFetchUtils_classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
2546
+ function UploadManagerFetchUtils_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, UploadManagerFetchUtils_toPropertyKey(descriptor.key), descriptor); } }
2547
+ function UploadManagerFetchUtils_createClass(Constructor, protoProps, staticProps) { if (protoProps) UploadManagerFetchUtils_defineProperties(Constructor.prototype, protoProps); if (staticProps) UploadManagerFetchUtils_defineProperties(Constructor, staticProps); Object.defineProperty(Constructor, "prototype", { writable: false }); return Constructor; }
2548
+ function UploadManagerFetchUtils_toPropertyKey(arg) { var key = UploadManagerFetchUtils_toPrimitive(arg, "string"); return UploadManagerFetchUtils_typeof(key) === "symbol" ? key : String(key); }
2549
+ function UploadManagerFetchUtils_toPrimitive(input, hint) { if (UploadManagerFetchUtils_typeof(input) !== "object" || input === null) return input; var prim = input[Symbol.toPrimitive]; if (prim !== undefined) { var res = prim.call(input, hint || "default"); if (UploadManagerFetchUtils_typeof(res) !== "object") return res; throw new TypeError("@@toPrimitive must return a primitive value."); } return (hint === "string" ? String : Number)(input); }
2550
+
2551
+ var UploadManagerFetchUtils = /*#__PURE__*/function () {
2552
+ function UploadManagerFetchUtils() {
2553
+ UploadManagerFetchUtils_classCallCheck(this, UploadManagerFetchUtils);
2554
+ }
2555
+ UploadManagerFetchUtils_createClass(UploadManagerFetchUtils, null, [{
2556
+ key: "doPutUploadPart",
2557
+ value: function doPutUploadPart(config, part, content, contentLength, addCancellationHandler) {
2558
+ try {
2559
+ var _a;
2560
+ var fetchApi = BytescaleApiClientConfigUtils.getFetchApi(config);
2561
+ // Configure cancellation:
2562
+ var controller = new AbortController();
2563
+ var signal = controller.signal;
2564
+ addCancellationHandler(function () {
2565
+ return controller.abort();
2566
+ });
2567
+ var headers = {
2568
+ // Required to prevent fetch using "Transfer-Encoding: Chunked" when body is a stream.
2569
+ "content-length": contentLength.toString()
2570
+ };
2571
+ return UploadManagerFetchUtils_await(fetchApi(part.uploadUrl, {
2572
+ method: "PUT",
2573
+ headers: headers,
2574
+ body: content,
2575
+ signal: signal,
2576
+ cache: "no-store" // Required for Next.js's Fetch implementation, which caches POST/PUT requests by default.
2577
+ }), function (response) {
2578
+ return {
2579
+ etag: (_a = response.headers.get("etag")) !== null && _a !== void 0 ? _a : undefined,
2580
+ status: response.status
2581
+ };
2582
+ });
2583
+ } catch (e) {
2584
+ return Promise.reject(e);
2585
+ }
2586
+ }
2587
+ }]);
2588
+ return UploadManagerFetchUtils;
2589
+ }();
2202
2590
  ;// CONCATENATED MODULE: ./src/public/node/UploadManagerNode.ts
2203
2591
  function UploadManagerNode_typeof(obj) { "@babel/helpers - typeof"; return UploadManagerNode_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; }, UploadManagerNode_typeof(obj); }
2204
2592
  function UploadManagerNode_empty() {}
@@ -2398,6 +2786,7 @@ function UploadManagerNode_getPrototypeOf(o) { UploadManagerNode_getPrototypeOf
2398
2786
 
2399
2787
 
2400
2788
 
2789
+
2401
2790
  var UploadManager = /*#__PURE__*/function (_UploadManagerBase) {
2402
2791
  UploadManagerNode_inherits(UploadManager, _UploadManagerBase);
2403
2792
  var _super = UploadManagerNode_createSuper(UploadManager);
@@ -2429,13 +2818,19 @@ var UploadManager = /*#__PURE__*/function (_UploadManagerBase) {
2429
2818
  value: data
2430
2819
  };
2431
2820
  }
2821
+ if (data.byteLength !== undefined) {
2822
+ return {
2823
+ type: "ArrayBuffer",
2824
+ value: data
2825
+ };
2826
+ }
2432
2827
  if (data.size !== undefined) {
2433
2828
  return {
2434
2829
  type: "Blob",
2435
2830
  value: data
2436
2831
  };
2437
2832
  }
2438
- throw new Error("Unsupported type for 'data' parameter. Please provide a String, Blob, or Readable (Node.js).");
2833
+ throw new Error("Unsupported type for 'data' parameter. Please provide a String, Blob, Buffer, ArrayBuffer, or ReadableStream (Node.js).");
2439
2834
  }
2440
2835
  }, {
2441
2836
  key: "getPreUploadInfoPartial",
@@ -2444,9 +2839,10 @@ var UploadManager = /*#__PURE__*/function (_UploadManagerBase) {
2444
2839
  case "Blob":
2445
2840
  return this.getBlobInfo(data);
2446
2841
  case "Buffer":
2842
+ case "ArrayBuffer":
2447
2843
  return {
2448
2844
  mime: undefined,
2449
- size: data.value.length,
2845
+ size: data.value.byteLength,
2450
2846
  originalFileName: undefined,
2451
2847
  maxConcurrentUploadParts: undefined
2452
2848
  };
@@ -2497,40 +2893,20 @@ var UploadManager = /*#__PURE__*/function (_UploadManagerBase) {
2497
2893
  value: function doPutUploadPart(part, contentLength, source, onProgress, addCancellationHandler) {
2498
2894
  try {
2499
2895
  var _this2 = this;
2500
- var _a, _b;
2501
- var fetchApi = (_a = _this2.config.fetchApi) !== null && _a !== void 0 ? _a : fetch;
2502
- var headers = {
2503
- // Required to prevent fetch using "Transfer-Encoding: Chunked" when body is a stream.
2504
- "content-length": contentLength.toString()
2505
- };
2506
- // Configure cancellation:
2507
- var controller = new AbortController();
2508
- var signal = controller.signal;
2509
- addCancellationHandler(function () {
2510
- return controller.abort();
2511
- });
2512
2896
  // Report progress:
2513
2897
  var hasWarned = false;
2898
+ var bytesSent = 0;
2514
2899
  return UploadManagerNode_await(_this2.sliceDataForRequest(source, part), function (stream) {
2515
2900
  var streamWithProgress = stream.on("data", function (data) {
2516
- if (data.length !== undefined) {
2517
- onProgress(data.length);
2901
+ if (data.byteLength !== undefined) {
2902
+ bytesSent += data.byteLength;
2903
+ onProgress(bytesSent);
2518
2904
  } else if (!hasWarned) {
2519
2905
  hasWarned = true;
2520
2906
  console.warn("Expected stream to contain buffers, but it did not, so upload progress won't be reported.");
2521
2907
  }
2522
2908
  });
2523
- return UploadManagerNode_await(fetchApi(part.uploadUrl, {
2524
- method: "PUT",
2525
- headers: headers,
2526
- body: _this2.coerceRequestBody(streamWithProgress),
2527
- signal: signal
2528
- }), function (response) {
2529
- return {
2530
- etag: (_b = response.headers.get("etag")) !== null && _b !== void 0 ? _b : undefined,
2531
- status: response.status
2532
- };
2533
- });
2909
+ return UploadManagerNode_await(UploadManagerFetchUtils.doPutUploadPart(_this2.config, part, _this2.coerceRequestBody(streamWithProgress), contentLength, addCancellationHandler));
2534
2910
  });
2535
2911
  } catch (e) {
2536
2912
  return Promise.reject(e);
@@ -2554,12 +2930,14 @@ var UploadManager = /*#__PURE__*/function (_UploadManagerBase) {
2554
2930
  return _switch(data.type, [[function () {
2555
2931
  return "Blob";
2556
2932
  }, function () {
2557
- var _fromBuffer = StreamUtils.fromBuffer,
2558
- _Buffer = Buffer,
2559
- _from = _Buffer.from;
2933
+ var _fromArrayBuffer = StreamUtils.fromArrayBuffer;
2560
2934
  return UploadManagerNode_await(data.value.slice(start, endExclusive).arrayBuffer(), function (_data$value$slice$arr) {
2561
- return _fromBuffer.call(StreamUtils, _from.call(_Buffer, _data$value$slice$arr));
2935
+ return _fromArrayBuffer.call(StreamUtils, _data$value$slice$arr);
2562
2936
  });
2937
+ }], [function () {
2938
+ return "ArrayBuffer";
2939
+ }, function () {
2940
+ return StreamUtils.fromArrayBuffer(data.value.slice(start, endExclusive));
2563
2941
  }], [function () {
2564
2942
  return "Buffer";
2565
2943
  }, function () {
@@ -2590,17 +2968,17 @@ var EnvChecker = /*#__PURE__*/function () {
2590
2968
  EnvChecker_classCallCheck(this, EnvChecker);
2591
2969
  }
2592
2970
  EnvChecker_createClass(EnvChecker, null, [{
2593
- key: "isNodeJs",
2594
- value: function isNodeJs() {
2595
- return typeof process !== "undefined" && process.versions !== undefined && process.versions.node !== undefined;
2971
+ key: "isBrowser",
2972
+ value: function isBrowser() {
2973
+ return typeof window !== "undefined";
2596
2974
  }
2597
2975
  }, {
2598
2976
  key: "methodRequiresBrowser",
2599
2977
  value: function methodRequiresBrowser(methodName) {
2600
- if (EnvChecker.isNodeJs()) {
2601
- return new Error("You must call '".concat(methodName, "' in the browser. (You are currently in Node.js.)"));
2978
+ if (!EnvChecker.isBrowser()) {
2979
+ return new Error("You must call '".concat(methodName, "' in your client-side code. (You have called it in your server-side code.)"));
2602
2980
  }
2603
- return new Error("The '".concat(methodName, "' method cannot be called because you have bundled the Node.js implementation of the Bytescale JavaScript SDK into your client-side code. Please ensure your bundling tool (Webpack, Rollup, etc.) is honouring the \"browser\" field of the \"package.json\" file for this package, as this will allow the browser implementation of the Bytescale JavaScript SDK to be included in your client-side code."));
2981
+ return new Error("The '".concat(methodName, "' method cannot be called because you have bundled a non-browser implementation of the Bytescale JavaScript SDK into your client-side code. Please ensure your bundling tool (Webpack, Rollup, etc.) is honouring the \"browser\" field of the \"package.json\" file for this package, as this will allow the browser implementation of the Bytescale JavaScript SDK to be included in your client-side code."));
2604
2982
  }
2605
2983
  }]);
2606
2984
  return EnvChecker;
@@ -2613,13 +2991,13 @@ function AuthManagerNode_createClass(Constructor, protoProps, staticProps) { if
2613
2991
  function AuthManagerNode_toPropertyKey(arg) { var key = AuthManagerNode_toPrimitive(arg, "string"); return AuthManagerNode_typeof(key) === "symbol" ? key : String(key); }
2614
2992
  function AuthManagerNode_toPrimitive(input, hint) { if (AuthManagerNode_typeof(input) !== "object" || input === null) return input; var prim = input[Symbol.toPrimitive]; if (prim !== undefined) { var res = prim.call(input, hint || "default"); if (AuthManagerNode_typeof(res) !== "object") return res; throw new TypeError("@@toPrimitive must return a primitive value."); } return (hint === "string" ? String : Number)(input); }
2615
2993
 
2616
- var AuthManager = /*#__PURE__*/function () {
2617
- function AuthManager() {
2618
- AuthManagerNode_classCallCheck(this, AuthManager);
2994
+ var AuthManagerImpl = /*#__PURE__*/function () {
2995
+ function AuthManagerImpl() {
2996
+ AuthManagerNode_classCallCheck(this, AuthManagerImpl);
2619
2997
  }
2620
- AuthManagerNode_createClass(AuthManager, [{
2998
+ AuthManagerNode_createClass(AuthManagerImpl, [{
2621
2999
  key: "beginAuthSession",
2622
- value: function beginAuthSession(_authUrl, _authHeaders) {
3000
+ value: function beginAuthSession(_params) {
2623
3001
  try {
2624
3002
  throw EnvChecker.methodRequiresBrowser("beginAuthSession");
2625
3003
  } catch (e) {
@@ -2641,8 +3019,12 @@ var AuthManager = /*#__PURE__*/function () {
2641
3019
  return false;
2642
3020
  }
2643
3021
  }]);
2644
- return AuthManager;
3022
+ return AuthManagerImpl;
2645
3023
  }();
3024
+ /**
3025
+ * Alternative way of implementing a static class (i.e. all methods static). We do this so we can use a interface on the class (interfaces can't define static methods).
3026
+ */
3027
+ var AuthManager = new AuthManagerImpl();
2646
3028
  ;// CONCATENATED MODULE: ./src/public/node/index.ts
2647
3029
 
2648
3030