@uploadcare/upload-client 3.1.1 → 4.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.cjs DELETED
@@ -1,1775 +0,0 @@
1
- 'use strict';
2
-
3
- Object.defineProperty(exports, '__esModule', { value: true });
4
-
5
- var http = require('http');
6
- var https = require('https');
7
- var url = require('url');
8
- var stream = require('stream');
9
- var NodeFormData = require('form-data');
10
- var abortController = require('abort-controller');
11
- var WebSocket = require('ws');
12
-
13
- function _interopDefaultLegacy (e) { return e && typeof e === 'object' && 'default' in e ? e : { 'default': e }; }
14
-
15
- var http__default = /*#__PURE__*/_interopDefaultLegacy(http);
16
- var https__default = /*#__PURE__*/_interopDefaultLegacy(https);
17
- var NodeFormData__default = /*#__PURE__*/_interopDefaultLegacy(NodeFormData);
18
- var WebSocket__default = /*#__PURE__*/_interopDefaultLegacy(WebSocket);
19
-
20
- /*! *****************************************************************************
21
- Copyright (c) Microsoft Corporation. All rights reserved.
22
- Licensed under the Apache License, Version 2.0 (the "License"); you may not use
23
- this file except in compliance with the License. You may obtain a copy of the
24
- License at http://www.apache.org/licenses/LICENSE-2.0
25
-
26
- THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
27
- KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED
28
- WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,
29
- MERCHANTABLITY OR NON-INFRINGEMENT.
30
-
31
- See the Apache Version 2.0 License for specific language governing permissions
32
- and limitations under the License.
33
- ***************************************************************************** */
34
- /* global Reflect, Promise */
35
-
36
- var extendStatics = function(d, b) {
37
- extendStatics = Object.setPrototypeOf ||
38
- ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
39
- function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
40
- return extendStatics(d, b);
41
- };
42
-
43
- function __extends(d, b) {
44
- extendStatics(d, b);
45
- function __() { this.constructor = d; }
46
- d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
47
- }
48
-
49
- var __assign = function() {
50
- __assign = Object.assign || function __assign(t) {
51
- for (var s, i = 1, n = arguments.length; i < n; i++) {
52
- s = arguments[i];
53
- for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p];
54
- }
55
- return t;
56
- };
57
- return __assign.apply(this, arguments);
58
- };
59
-
60
- function __spreadArrays() {
61
- for (var s = 0, i = 0, il = arguments.length; i < il; i++) s += arguments[i].length;
62
- for (var r = Array(s), k = 0, i = 0; i < il; i++)
63
- for (var a = arguments[i], j = 0, jl = a.length; j < jl; j++, k++)
64
- r[k] = a[j];
65
- return r;
66
- }
67
-
68
- var UploadClientError = /** @class */ (function (_super) {
69
- __extends(UploadClientError, _super);
70
- function UploadClientError(message, code, request, response, headers) {
71
- var _this = _super.call(this) || this;
72
- _this.name = 'UploadClientError';
73
- _this.message = message;
74
- _this.code = code;
75
- _this.request = request;
76
- _this.response = response;
77
- _this.headers = headers;
78
- Object.setPrototypeOf(_this, UploadClientError.prototype);
79
- return _this;
80
- }
81
- return UploadClientError;
82
- }(Error));
83
- var cancelError = function (message) {
84
- if (message === void 0) { message = 'Request canceled'; }
85
- var error = new UploadClientError(message);
86
- error.isCancel = true;
87
- return error;
88
- };
89
-
90
- var onCancel = function (signal, callback) {
91
- if (signal) {
92
- if (signal.aborted) {
93
- Promise.resolve().then(callback);
94
- }
95
- else {
96
- signal.addEventListener('abort', function () { return callback(); }, { once: true });
97
- }
98
- }
99
- };
100
-
101
- // ProgressEmitter is a simple PassThrough-style transform stream which keeps
102
- // track of the number of bytes which have been piped through it and will
103
- // invoke the `onprogress` function whenever new number are available.
104
- var ProgressEmitter = /** @class */ (function (_super) {
105
- __extends(ProgressEmitter, _super);
106
- function ProgressEmitter(onProgress, size) {
107
- var _this = _super.call(this) || this;
108
- _this._onprogress = onProgress;
109
- _this._position = 0;
110
- _this.size = size;
111
- return _this;
112
- }
113
- ProgressEmitter.prototype._transform = function (chunk, encoding, callback) {
114
- this._position += chunk.length;
115
- this._onprogress({
116
- isComputable: true,
117
- value: this._position / this.size
118
- });
119
- callback(null, chunk);
120
- };
121
- return ProgressEmitter;
122
- }(stream.Transform));
123
- var getLength = function (formData) {
124
- return new Promise(function (resolve, reject) {
125
- formData.getLength(function (error, length) {
126
- if (error)
127
- reject(error);
128
- else
129
- resolve(length);
130
- });
131
- });
132
- };
133
- function isFormData(formData) {
134
- if (formData && formData.toString() === '[object FormData]') {
135
- return true;
136
- }
137
- return false;
138
- }
139
- function isReadable(data, isFormData) {
140
- if (data && (data instanceof stream.Readable || isFormData)) {
141
- return true;
142
- }
143
- return false;
144
- }
145
- var request = function (params) {
146
- var _a = params.method, method = _a === void 0 ? 'GET' : _a, url$1 = params.url, data = params.data, _b = params.headers, headers = _b === void 0 ? {} : _b, signal = params.signal, onProgress = params.onProgress;
147
- return Promise.resolve()
148
- .then(function () {
149
- if (isFormData(data)) {
150
- return getLength(data);
151
- }
152
- else {
153
- return undefined;
154
- }
155
- })
156
- .then(function (length) {
157
- return new Promise(function (resolve, reject) {
158
- var isFormData = !!length;
159
- var aborted = false;
160
- var options = url.parse(url$1);
161
- options.method = method;
162
- options.headers = isFormData
163
- ? Object.assign(data.getHeaders(), headers)
164
- : headers;
165
- if (isFormData || (data && data.length)) {
166
- options.headers['Content-Length'] =
167
- length || data.length;
168
- }
169
- var req = options.protocol !== 'https:'
170
- ? http__default["default"].request(options)
171
- : https__default["default"].request(options);
172
- onCancel(signal, function () {
173
- aborted = true;
174
- req.abort();
175
- reject(cancelError());
176
- });
177
- req.on('response', function (res) {
178
- if (aborted)
179
- return;
180
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
181
- var resChunks = [];
182
- res.on('data', function (data) {
183
- resChunks.push(data);
184
- });
185
- res.on('end', function () {
186
- return resolve({
187
- data: Buffer.concat(resChunks).toString('utf8'),
188
- status: res.statusCode,
189
- headers: res.headers,
190
- request: params
191
- });
192
- });
193
- });
194
- req.on('error', function (err) {
195
- if (aborted)
196
- return;
197
- reject(err);
198
- });
199
- if (isReadable(data, isFormData)) {
200
- if (onProgress && length) {
201
- data.pipe(new ProgressEmitter(onProgress, length)).pipe(req);
202
- }
203
- else {
204
- data.pipe(req);
205
- }
206
- }
207
- else {
208
- req.end(data);
209
- }
210
- });
211
- });
212
- };
213
-
214
- function identity(obj) {
215
- return obj;
216
- }
217
-
218
- var transformFile = identity;
219
- var getFormData = (function () { return new NodeFormData__default["default"](); });
220
-
221
- /**
222
- * FileData type guard.
223
- */
224
- var isFileData = function (data) {
225
- return (data !== undefined &&
226
- ((typeof Blob !== 'undefined' && data instanceof Blob) ||
227
- (typeof File !== 'undefined' && data instanceof File) ||
228
- (typeof Buffer !== 'undefined' && data instanceof Buffer)));
229
- };
230
- /**
231
- * Uuid type guard.
232
- */
233
- var isUuid = function (data) {
234
- var UUID_REGEX = '[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}';
235
- var regExp = new RegExp(UUID_REGEX);
236
- return !isFileData(data) && regExp.test(data);
237
- };
238
- /**
239
- * Url type guard.
240
- *
241
- * @param {NodeFile | BrowserFile | Url | Uuid} data
242
- */
243
- var isUrl = function (data) {
244
- var URL_REGEX = '^(?:\\w+:)?\\/\\/([^\\s\\.]+\\.\\S{2}|localhost[\\:?\\d]*)\\S*$';
245
- var regExp = new RegExp(URL_REGEX);
246
- return !isFileData(data) && regExp.test(data);
247
- };
248
-
249
- var isSimpleValue = function (value) {
250
- return (typeof value === 'string' ||
251
- typeof value === 'number' ||
252
- typeof value === 'undefined');
253
- };
254
- var isObjectValue = function (value) {
255
- return !!value && typeof value === 'object' && !Array.isArray(value);
256
- };
257
- var isFileValue = function (value) {
258
- return !!value &&
259
- typeof value === 'object' &&
260
- 'data' in value &&
261
- isFileData(value.data);
262
- };
263
- function collectParams(params, inputKey, inputValue) {
264
- if (isFileValue(inputValue)) {
265
- var name_1 = inputValue.name;
266
- var file = transformFile(inputValue.data); // lgtm [js/superfluous-trailing-arguments]
267
- params.push(name_1 ? [inputKey, file, name_1] : [inputKey, file]);
268
- }
269
- else if (isObjectValue(inputValue)) {
270
- for (var _i = 0, _a = Object.entries(inputValue); _i < _a.length; _i++) {
271
- var _b = _a[_i], key = _b[0], value = _b[1];
272
- if (typeof value !== 'undefined') {
273
- params.push([inputKey + "[" + key + "]", String(value)]);
274
- }
275
- }
276
- }
277
- else if (isSimpleValue(inputValue) && inputValue) {
278
- params.push([inputKey, inputValue.toString()]);
279
- }
280
- }
281
- function getFormDataParams(options) {
282
- var params = [];
283
- for (var _i = 0, _a = Object.entries(options); _i < _a.length; _i++) {
284
- var _b = _a[_i], key = _b[0], value = _b[1];
285
- collectParams(params, key, value);
286
- }
287
- return params;
288
- }
289
- function buildFormData(options) {
290
- var formData = getFormData();
291
- var params = getFormDataParams(options);
292
- for (var _i = 0, params_1 = params; _i < params_1.length; _i++) {
293
- var param = params_1[_i];
294
- formData.append.apply(formData, param);
295
- }
296
- return formData;
297
- }
298
-
299
- var serializePair = function (key, value) {
300
- return typeof value !== 'undefined' ? key + "=" + encodeURIComponent(value) : null;
301
- };
302
- // TODO: generalize value transforming logic and use it here and inside `buildFormData`
303
- var createQuery = function (query) {
304
- return Object.entries(query)
305
- .reduce(function (params, _a) {
306
- var key = _a[0], value = _a[1];
307
- var param;
308
- if (typeof value === 'object' && !Array.isArray(value)) {
309
- param = Object.entries(value)
310
- .filter(function (entry) { return typeof entry[1] !== 'undefined'; })
311
- .map(function (entry) {
312
- return serializePair(key + "[" + entry[0] + "]", String(entry[1]));
313
- });
314
- }
315
- else if (Array.isArray(value)) {
316
- param = value.map(function (val) { return serializePair(key + "[]", val); });
317
- }
318
- else {
319
- param = serializePair(key, value);
320
- }
321
- return params.concat(param);
322
- }, [])
323
- .filter(function (x) { return !!x; })
324
- .join('&');
325
- };
326
- var getUrl = function (base, path, query) {
327
- return [
328
- base,
329
- path,
330
- query && Object.keys(query).length > 0 ? '?' : '',
331
- query && createQuery(query)
332
- ]
333
- .filter(Boolean)
334
- .join('');
335
- };
336
-
337
- /*
338
- Settings for future support:
339
- parallelDirectUploads: 10,
340
- */
341
- var defaultSettings = {
342
- baseCDN: 'https://ucarecdn.com',
343
- baseURL: 'https://upload.uploadcare.com',
344
- maxContentLength: 50 * 1024 * 1024,
345
- retryThrottledRequestMaxTimes: 1,
346
- multipartMinFileSize: 25 * 1024 * 1024,
347
- multipartChunkSize: 5 * 1024 * 1024,
348
- multipartMinLastPartSize: 1024 * 1024,
349
- maxConcurrentRequests: 4,
350
- multipartMaxAttempts: 3,
351
- pollingTimeoutMilliseconds: 10000,
352
- pusherKey: '79ae88bd931ea68464d9'
353
- };
354
- var defaultContentType = 'application/octet-stream';
355
- var defaultFilename = 'original';
356
-
357
- var version = '3.1.1';
358
-
359
- /**
360
- * Returns User Agent based on version and settings.
361
- */
362
- function getUserAgent(_a) {
363
- var _b = _a === void 0 ? {} : _a, userAgent = _b.userAgent, _c = _b.publicKey, publicKey = _c === void 0 ? '' : _c, _d = _b.integration, integration = _d === void 0 ? '' : _d;
364
- var libraryName = 'UploadcareUploadClient';
365
- var libraryVersion = version;
366
- var languageName = 'JavaScript';
367
- if (typeof userAgent === 'string') {
368
- return userAgent;
369
- }
370
- if (typeof userAgent === 'function') {
371
- return userAgent({
372
- publicKey: publicKey,
373
- libraryName: libraryName,
374
- libraryVersion: libraryVersion,
375
- languageName: languageName,
376
- integration: integration
377
- });
378
- }
379
- var mainInfo = [libraryName, libraryVersion, publicKey]
380
- .filter(Boolean)
381
- .join('/');
382
- var additionInfo = [languageName, integration].filter(Boolean).join('; ');
383
- return mainInfo + " (" + additionInfo + ")";
384
- }
385
-
386
- var SEPARATOR = /\W|_/g;
387
- /**
388
- * Transforms a string to camelCased.
389
- */
390
- function camelize(text) {
391
- return text
392
- .split(SEPARATOR)
393
- .map(function (word, index) {
394
- return word.charAt(0)[index > 0 ? 'toUpperCase' : 'toLowerCase']() +
395
- word.slice(1);
396
- })
397
- .join('');
398
- }
399
- /**
400
- * Transforms keys of an object to camelCased recursively.
401
- */
402
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
403
- function camelizeKeys(source) {
404
- if (!source || typeof source !== 'object') {
405
- return source;
406
- }
407
- return Object.keys(source).reduce(function (accumulator, key) {
408
- accumulator[camelize(key)] =
409
- typeof source[key] === 'object' ? camelizeKeys(source[key]) : source[key];
410
- return accumulator;
411
- }, {});
412
- }
413
-
414
- /**
415
- * setTimeout as Promise.
416
- *
417
- * @param {number} ms Timeout in milliseconds.
418
- */
419
- var delay = function (ms) {
420
- return new Promise(function (resolve) { return setTimeout(resolve, ms); });
421
- };
422
-
423
- var defaultOptions = {
424
- factor: 2,
425
- time: 100
426
- };
427
- function retrier(fn, options) {
428
- if (options === void 0) { options = defaultOptions; }
429
- var attempts = 0;
430
- function runAttempt(fn) {
431
- var defaultDelayTime = Math.round(options.time * Math.pow(options.factor, attempts));
432
- var retry = function (ms) {
433
- return delay(ms !== null && ms !== void 0 ? ms : defaultDelayTime).then(function () {
434
- attempts += 1;
435
- return runAttempt(fn);
436
- });
437
- };
438
- return fn({
439
- attempt: attempts,
440
- retry: retry
441
- });
442
- }
443
- return runAttempt(fn);
444
- }
445
-
446
- var REQUEST_WAS_THROTTLED_CODE = 'RequestThrottledError';
447
- var DEFAULT_RETRY_AFTER_TIMEOUT = 15000;
448
- function getTimeoutFromThrottledRequest(error) {
449
- var headers = (error || {}).headers;
450
- return ((headers &&
451
- Number.parseInt(headers['x-throttle-wait-seconds']) * 1000) ||
452
- DEFAULT_RETRY_AFTER_TIMEOUT);
453
- }
454
- function retryIfThrottled(fn, retryThrottledMaxTimes) {
455
- return retrier(function (_a) {
456
- var attempt = _a.attempt, retry = _a.retry;
457
- return fn().catch(function (error) {
458
- if ('response' in error &&
459
- (error === null || error === void 0 ? void 0 : error.code) === REQUEST_WAS_THROTTLED_CODE &&
460
- attempt < retryThrottledMaxTimes) {
461
- return retry(getTimeoutFromThrottledRequest(error));
462
- }
463
- throw error;
464
- });
465
- });
466
- }
467
-
468
- function getStoreValue(store) {
469
- return typeof store === 'undefined' ? 'auto' : store ? '1' : '0';
470
- }
471
-
472
- /**
473
- * Performs file uploading request to Uploadcare Upload API.
474
- * Can be canceled and has progress.
475
- */
476
- function base(file, _a) {
477
- var publicKey = _a.publicKey, fileName = _a.fileName, _b = _a.baseURL, baseURL = _b === void 0 ? defaultSettings.baseURL : _b, secureSignature = _a.secureSignature, secureExpire = _a.secureExpire, store = _a.store, signal = _a.signal, onProgress = _a.onProgress, _c = _a.source, source = _c === void 0 ? 'local' : _c, integration = _a.integration, userAgent = _a.userAgent, _d = _a.retryThrottledRequestMaxTimes, retryThrottledRequestMaxTimes = _d === void 0 ? defaultSettings.retryThrottledRequestMaxTimes : _d, metadata = _a.metadata;
478
- return retryIfThrottled(function () {
479
- var _a;
480
- return request({
481
- method: 'POST',
482
- url: getUrl(baseURL, '/base/', {
483
- jsonerrors: 1
484
- }),
485
- headers: {
486
- 'X-UC-User-Agent': getUserAgent({ publicKey: publicKey, integration: integration, userAgent: userAgent })
487
- },
488
- data: buildFormData({
489
- file: {
490
- data: file,
491
- name: (_a = fileName !== null && fileName !== void 0 ? fileName : file.name) !== null && _a !== void 0 ? _a : defaultFilename
492
- },
493
- UPLOADCARE_PUB_KEY: publicKey,
494
- UPLOADCARE_STORE: getStoreValue(store),
495
- signature: secureSignature,
496
- expire: secureExpire,
497
- source: source,
498
- metadata: metadata
499
- }),
500
- signal: signal,
501
- onProgress: onProgress
502
- }).then(function (_a) {
503
- var data = _a.data, headers = _a.headers, request = _a.request;
504
- var response = camelizeKeys(JSON.parse(data));
505
- if ('error' in response) {
506
- throw new UploadClientError(response.error.content, response.error.errorCode, request, response, headers);
507
- }
508
- else {
509
- return response;
510
- }
511
- });
512
- }, retryThrottledRequestMaxTimes);
513
- }
514
-
515
- var TypeEnum;
516
- (function (TypeEnum) {
517
- TypeEnum["Token"] = "token";
518
- TypeEnum["FileInfo"] = "file_info";
519
- })(TypeEnum || (TypeEnum = {}));
520
- /**
521
- * Uploading files from URL.
522
- */
523
- function fromUrl(sourceUrl, _a) {
524
- var publicKey = _a.publicKey, _b = _a.baseURL, baseURL = _b === void 0 ? defaultSettings.baseURL : _b, store = _a.store, fileName = _a.fileName, checkForUrlDuplicates = _a.checkForUrlDuplicates, saveUrlForRecurrentUploads = _a.saveUrlForRecurrentUploads, secureSignature = _a.secureSignature, secureExpire = _a.secureExpire, _c = _a.source, source = _c === void 0 ? 'url' : _c, signal = _a.signal, integration = _a.integration, userAgent = _a.userAgent, _d = _a.retryThrottledRequestMaxTimes, retryThrottledRequestMaxTimes = _d === void 0 ? defaultSettings.retryThrottledRequestMaxTimes : _d, metadata = _a.metadata;
525
- return retryIfThrottled(function () {
526
- return request({
527
- method: 'POST',
528
- headers: {
529
- 'X-UC-User-Agent': getUserAgent({ publicKey: publicKey, integration: integration, userAgent: userAgent })
530
- },
531
- url: getUrl(baseURL, '/from_url/', {
532
- jsonerrors: 1,
533
- pub_key: publicKey,
534
- source_url: sourceUrl,
535
- store: getStoreValue(store),
536
- filename: fileName,
537
- check_URL_duplicates: checkForUrlDuplicates ? 1 : undefined,
538
- save_URL_duplicates: saveUrlForRecurrentUploads ? 1 : undefined,
539
- signature: secureSignature,
540
- expire: secureExpire,
541
- source: source,
542
- metadata: metadata
543
- }),
544
- signal: signal
545
- }).then(function (_a) {
546
- var data = _a.data, headers = _a.headers, request = _a.request;
547
- var response = camelizeKeys(JSON.parse(data));
548
- if ('error' in response) {
549
- throw new UploadClientError(response.error.content, response.error.errorCode, request, response, headers);
550
- }
551
- else {
552
- return response;
553
- }
554
- });
555
- }, retryThrottledRequestMaxTimes);
556
- }
557
-
558
- var Status;
559
- (function (Status) {
560
- Status["Unknown"] = "unknown";
561
- Status["Waiting"] = "waiting";
562
- Status["Progress"] = "progress";
563
- Status["Error"] = "error";
564
- Status["Success"] = "success";
565
- })(Status || (Status = {}));
566
- var isErrorResponse = function (response) {
567
- return 'status' in response && response.status === Status.Error;
568
- };
569
- /**
570
- * Checking upload status and working with file tokens.
571
- */
572
- function fromUrlStatus(token, _a) {
573
- var _b = _a === void 0 ? {} : _a, publicKey = _b.publicKey, _c = _b.baseURL, baseURL = _c === void 0 ? defaultSettings.baseURL : _c, signal = _b.signal, integration = _b.integration, userAgent = _b.userAgent, _d = _b.retryThrottledRequestMaxTimes, retryThrottledRequestMaxTimes = _d === void 0 ? defaultSettings.retryThrottledRequestMaxTimes : _d;
574
- return retryIfThrottled(function () {
575
- return request({
576
- method: 'GET',
577
- headers: publicKey
578
- ? {
579
- 'X-UC-User-Agent': getUserAgent({
580
- publicKey: publicKey,
581
- integration: integration,
582
- userAgent: userAgent
583
- })
584
- }
585
- : undefined,
586
- url: getUrl(baseURL, '/from_url/status/', {
587
- jsonerrors: 1,
588
- token: token
589
- }),
590
- signal: signal
591
- }).then(function (_a) {
592
- var data = _a.data, headers = _a.headers, request = _a.request;
593
- var response = camelizeKeys(JSON.parse(data));
594
- if ('error' in response && !isErrorResponse(response)) {
595
- throw new UploadClientError(response.error.content, undefined, request, response, headers);
596
- }
597
- else {
598
- return response;
599
- }
600
- });
601
- }, retryThrottledRequestMaxTimes);
602
- }
603
-
604
- /**
605
- * Create files group.
606
- */
607
- function group(uuids, _a) {
608
- var publicKey = _a.publicKey, _b = _a.baseURL, baseURL = _b === void 0 ? defaultSettings.baseURL : _b, jsonpCallback = _a.jsonpCallback, secureSignature = _a.secureSignature, secureExpire = _a.secureExpire, signal = _a.signal, source = _a.source, integration = _a.integration, userAgent = _a.userAgent, _c = _a.retryThrottledRequestMaxTimes, retryThrottledRequestMaxTimes = _c === void 0 ? defaultSettings.retryThrottledRequestMaxTimes : _c;
609
- return retryIfThrottled(function () {
610
- return request({
611
- method: 'POST',
612
- headers: {
613
- 'X-UC-User-Agent': getUserAgent({ publicKey: publicKey, integration: integration, userAgent: userAgent })
614
- },
615
- url: getUrl(baseURL, '/group/', {
616
- jsonerrors: 1,
617
- pub_key: publicKey,
618
- files: uuids,
619
- callback: jsonpCallback,
620
- signature: secureSignature,
621
- expire: secureExpire,
622
- source: source
623
- }),
624
- signal: signal
625
- }).then(function (_a) {
626
- var data = _a.data, headers = _a.headers, request = _a.request;
627
- var response = camelizeKeys(JSON.parse(data));
628
- if ('error' in response) {
629
- throw new UploadClientError(response.error.content, response.error.errorCode, request, response, headers);
630
- }
631
- else {
632
- return response;
633
- }
634
- });
635
- }, retryThrottledRequestMaxTimes);
636
- }
637
-
638
- /**
639
- * Get info about group.
640
- */
641
- function groupInfo(id, _a) {
642
- var publicKey = _a.publicKey, _b = _a.baseURL, baseURL = _b === void 0 ? defaultSettings.baseURL : _b, signal = _a.signal, source = _a.source, integration = _a.integration, userAgent = _a.userAgent, _c = _a.retryThrottledRequestMaxTimes, retryThrottledRequestMaxTimes = _c === void 0 ? defaultSettings.retryThrottledRequestMaxTimes : _c;
643
- return retryIfThrottled(function () {
644
- return request({
645
- method: 'GET',
646
- headers: {
647
- 'X-UC-User-Agent': getUserAgent({ publicKey: publicKey, integration: integration, userAgent: userAgent })
648
- },
649
- url: getUrl(baseURL, '/group/info/', {
650
- jsonerrors: 1,
651
- pub_key: publicKey,
652
- group_id: id,
653
- source: source
654
- }),
655
- signal: signal
656
- }).then(function (_a) {
657
- var data = _a.data, headers = _a.headers, request = _a.request;
658
- var response = camelizeKeys(JSON.parse(data));
659
- if ('error' in response) {
660
- throw new UploadClientError(response.error.content, response.error.errorCode, request, response, headers);
661
- }
662
- else {
663
- return response;
664
- }
665
- });
666
- }, retryThrottledRequestMaxTimes);
667
- }
668
-
669
- /**
670
- * Returns a JSON dictionary holding file info.
671
- */
672
- function info(uuid, _a) {
673
- var publicKey = _a.publicKey, _b = _a.baseURL, baseURL = _b === void 0 ? defaultSettings.baseURL : _b, signal = _a.signal, source = _a.source, integration = _a.integration, userAgent = _a.userAgent, _c = _a.retryThrottledRequestMaxTimes, retryThrottledRequestMaxTimes = _c === void 0 ? defaultSettings.retryThrottledRequestMaxTimes : _c;
674
- return retryIfThrottled(function () {
675
- return request({
676
- method: 'GET',
677
- headers: {
678
- 'X-UC-User-Agent': getUserAgent({ publicKey: publicKey, integration: integration, userAgent: userAgent })
679
- },
680
- url: getUrl(baseURL, '/info/', {
681
- jsonerrors: 1,
682
- pub_key: publicKey,
683
- file_id: uuid,
684
- source: source
685
- }),
686
- signal: signal
687
- }).then(function (_a) {
688
- var data = _a.data, headers = _a.headers, request = _a.request;
689
- var response = camelizeKeys(JSON.parse(data));
690
- if ('error' in response) {
691
- throw new UploadClientError(response.error.content, response.error.errorCode, request, response, headers);
692
- }
693
- else {
694
- return response;
695
- }
696
- });
697
- }, retryThrottledRequestMaxTimes);
698
- }
699
-
700
- /**
701
- * Start multipart uploading.
702
- */
703
- function multipartStart(size, _a) {
704
- var publicKey = _a.publicKey, contentType = _a.contentType, fileName = _a.fileName, _b = _a.multipartChunkSize, multipartChunkSize = _b === void 0 ? defaultSettings.multipartChunkSize : _b, _c = _a.baseURL, baseURL = _c === void 0 ? '' : _c, secureSignature = _a.secureSignature, secureExpire = _a.secureExpire, store = _a.store, signal = _a.signal, _d = _a.source, source = _d === void 0 ? 'local' : _d, integration = _a.integration, userAgent = _a.userAgent, _e = _a.retryThrottledRequestMaxTimes, retryThrottledRequestMaxTimes = _e === void 0 ? defaultSettings.retryThrottledRequestMaxTimes : _e, metadata = _a.metadata;
705
- return retryIfThrottled(function () {
706
- return request({
707
- method: 'POST',
708
- url: getUrl(baseURL, '/multipart/start/', { jsonerrors: 1 }),
709
- headers: {
710
- 'X-UC-User-Agent': getUserAgent({ publicKey: publicKey, integration: integration, userAgent: userAgent })
711
- },
712
- data: buildFormData({
713
- filename: fileName !== null && fileName !== void 0 ? fileName : defaultFilename,
714
- size: size,
715
- content_type: contentType !== null && contentType !== void 0 ? contentType : defaultContentType,
716
- part_size: multipartChunkSize,
717
- UPLOADCARE_STORE: getStoreValue(store),
718
- UPLOADCARE_PUB_KEY: publicKey,
719
- signature: secureSignature,
720
- expire: secureExpire,
721
- source: source,
722
- metadata: metadata
723
- }),
724
- signal: signal
725
- }).then(function (_a) {
726
- var data = _a.data, headers = _a.headers, request = _a.request;
727
- var response = camelizeKeys(JSON.parse(data));
728
- if ('error' in response) {
729
- throw new UploadClientError(response.error.content, response.error.errorCode, request, response, headers);
730
- }
731
- else {
732
- // convert to array
733
- response.parts = Object.keys(response.parts).map(function (key) { return response.parts[key]; });
734
- return response;
735
- }
736
- });
737
- }, retryThrottledRequestMaxTimes);
738
- }
739
-
740
- /**
741
- * Complete multipart uploading.
742
- */
743
- function multipartUpload(part, url, _a) {
744
- var signal = _a.signal, onProgress = _a.onProgress;
745
- return request({
746
- method: 'PUT',
747
- url: url,
748
- data: part,
749
- // Upload request can't be non-computable because we always know exact size
750
- onProgress: onProgress,
751
- signal: signal
752
- })
753
- .then(function (result) {
754
- // hack for node ¯\_(ツ)_/¯
755
- if (onProgress)
756
- onProgress({
757
- isComputable: true,
758
- value: 1
759
- });
760
- return result;
761
- })
762
- .then(function (_a) {
763
- var status = _a.status;
764
- return ({ code: status });
765
- });
766
- }
767
-
768
- /**
769
- * Complete multipart uploading.
770
- */
771
- function multipartComplete(uuid, _a) {
772
- var publicKey = _a.publicKey, _b = _a.baseURL, baseURL = _b === void 0 ? defaultSettings.baseURL : _b, _c = _a.source, source = _c === void 0 ? 'local' : _c, signal = _a.signal, integration = _a.integration, userAgent = _a.userAgent, _d = _a.retryThrottledRequestMaxTimes, retryThrottledRequestMaxTimes = _d === void 0 ? defaultSettings.retryThrottledRequestMaxTimes : _d;
773
- return retryIfThrottled(function () {
774
- return request({
775
- method: 'POST',
776
- url: getUrl(baseURL, '/multipart/complete/', { jsonerrors: 1 }),
777
- headers: {
778
- 'X-UC-User-Agent': getUserAgent({ publicKey: publicKey, integration: integration, userAgent: userAgent })
779
- },
780
- data: buildFormData({
781
- uuid: uuid,
782
- UPLOADCARE_PUB_KEY: publicKey,
783
- source: source
784
- }),
785
- signal: signal
786
- }).then(function (_a) {
787
- var data = _a.data, headers = _a.headers, request = _a.request;
788
- var response = camelizeKeys(JSON.parse(data));
789
- if ('error' in response) {
790
- throw new UploadClientError(response.error.content, response.error.errorCode, request, response, headers);
791
- }
792
- else {
793
- return response;
794
- }
795
- });
796
- }, retryThrottledRequestMaxTimes);
797
- }
798
-
799
- var UploadcareFile = /** @class */ (function () {
800
- function UploadcareFile(fileInfo, _a) {
801
- var baseCDN = _a.baseCDN, defaultEffects = _a.defaultEffects, fileName = _a.fileName;
802
- this.name = null;
803
- this.size = null;
804
- this.isStored = null;
805
- this.isImage = null;
806
- this.mimeType = null;
807
- this.cdnUrl = null;
808
- this.cdnUrlModifiers = null;
809
- this.originalUrl = null;
810
- this.originalFilename = null;
811
- this.imageInfo = null;
812
- this.videoInfo = null;
813
- this.contentInfo = null;
814
- this.metadata = null;
815
- var uuid = fileInfo.uuid, s3Bucket = fileInfo.s3Bucket;
816
- var urlBase = s3Bucket
817
- ? "https://" + s3Bucket + ".s3.amazonaws.com/" + uuid + "/" + fileInfo.filename
818
- : baseCDN + "/" + uuid + "/";
819
- var cdnUrlModifiers = defaultEffects ? "-/" + defaultEffects : null;
820
- var cdnUrl = "" + urlBase + (cdnUrlModifiers || '');
821
- var originalUrl = uuid ? urlBase : null;
822
- this.uuid = uuid;
823
- this.name = fileName || fileInfo.filename;
824
- this.size = fileInfo.size;
825
- this.isStored = fileInfo.isStored;
826
- this.isImage = fileInfo.isImage;
827
- this.mimeType = fileInfo.mimeType;
828
- this.cdnUrl = cdnUrl;
829
- this.cdnUrlModifiers = cdnUrlModifiers;
830
- this.originalUrl = originalUrl;
831
- this.originalFilename = fileInfo.originalFilename;
832
- this.imageInfo = camelizeKeys(fileInfo.imageInfo);
833
- this.videoInfo = camelizeKeys(fileInfo.videoInfo);
834
- this.contentInfo = camelizeKeys(fileInfo.contentInfo);
835
- this.metadata = fileInfo.metadata || null;
836
- }
837
- return UploadcareFile;
838
- }());
839
-
840
- var DEFAULT_INTERVAL = 500;
841
- var poll = function (_a) {
842
- var check = _a.check, _b = _a.interval, interval = _b === void 0 ? DEFAULT_INTERVAL : _b, signal = _a.signal;
843
- return new Promise(function (resolve, reject) {
844
- var timeoutId;
845
- onCancel(signal, function () {
846
- timeoutId && clearTimeout(timeoutId);
847
- reject(cancelError('Poll cancelled'));
848
- });
849
- var tick = function () {
850
- try {
851
- Promise.resolve(check(signal))
852
- .then(function (result) {
853
- if (result) {
854
- resolve(result);
855
- }
856
- else {
857
- timeoutId = setTimeout(tick, interval);
858
- }
859
- })
860
- .catch(function (error) { return reject(error); });
861
- }
862
- catch (error) {
863
- reject(error);
864
- }
865
- };
866
- timeoutId = setTimeout(tick, 0);
867
- });
868
- };
869
-
870
- function isReadyPoll(_a) {
871
- var file = _a.file, publicKey = _a.publicKey, baseURL = _a.baseURL, source = _a.source, integration = _a.integration, userAgent = _a.userAgent, retryThrottledRequestMaxTimes = _a.retryThrottledRequestMaxTimes, signal = _a.signal, onProgress = _a.onProgress;
872
- return poll({
873
- check: function (signal) {
874
- return info(file, {
875
- publicKey: publicKey,
876
- baseURL: baseURL,
877
- signal: signal,
878
- source: source,
879
- integration: integration,
880
- userAgent: userAgent,
881
- retryThrottledRequestMaxTimes: retryThrottledRequestMaxTimes
882
- }).then(function (response) {
883
- if (response.isReady) {
884
- return response;
885
- }
886
- onProgress && onProgress({ isComputable: true, value: 1 });
887
- return false;
888
- });
889
- },
890
- signal: signal
891
- });
892
- }
893
-
894
- var uploadFromObject = function (file, _a) {
895
- var publicKey = _a.publicKey, fileName = _a.fileName, baseURL = _a.baseURL, secureSignature = _a.secureSignature, secureExpire = _a.secureExpire, store = _a.store, signal = _a.signal, onProgress = _a.onProgress, source = _a.source, integration = _a.integration, userAgent = _a.userAgent, retryThrottledRequestMaxTimes = _a.retryThrottledRequestMaxTimes, baseCDN = _a.baseCDN, metadata = _a.metadata;
896
- return base(file, {
897
- publicKey: publicKey,
898
- fileName: fileName,
899
- baseURL: baseURL,
900
- secureSignature: secureSignature,
901
- secureExpire: secureExpire,
902
- store: store,
903
- signal: signal,
904
- onProgress: onProgress,
905
- source: source,
906
- integration: integration,
907
- userAgent: userAgent,
908
- retryThrottledRequestMaxTimes: retryThrottledRequestMaxTimes,
909
- metadata: metadata
910
- })
911
- .then(function (_a) {
912
- var file = _a.file;
913
- return isReadyPoll({
914
- file: file,
915
- publicKey: publicKey,
916
- baseURL: baseURL,
917
- source: source,
918
- integration: integration,
919
- userAgent: userAgent,
920
- retryThrottledRequestMaxTimes: retryThrottledRequestMaxTimes,
921
- onProgress: onProgress,
922
- signal: signal
923
- });
924
- })
925
- .then(function (fileInfo) { return new UploadcareFile(fileInfo, { baseCDN: baseCDN }); });
926
- };
927
-
928
- var race = function (fns, _a) {
929
- var signal = (_a === void 0 ? {} : _a).signal;
930
- var lastError = null;
931
- var winnerIndex = null;
932
- var controllers = fns.map(function () { return new abortController.AbortController(); });
933
- var createStopRaceCallback = function (i) { return function () {
934
- winnerIndex = i;
935
- controllers.forEach(function (controller, index) { return index !== i && controller.abort(); });
936
- }; };
937
- onCancel(signal, function () {
938
- controllers.forEach(function (controller) { return controller.abort(); });
939
- });
940
- return Promise.all(fns.map(function (fn, i) {
941
- var stopRace = createStopRaceCallback(i);
942
- return Promise.resolve()
943
- .then(function () { return fn({ stopRace: stopRace, signal: controllers[i].signal }); })
944
- .then(function (result) {
945
- stopRace();
946
- return result;
947
- })
948
- .catch(function (error) {
949
- lastError = error;
950
- return null;
951
- });
952
- })).then(function (results) {
953
- if (winnerIndex === null) {
954
- throw lastError;
955
- }
956
- else {
957
- return results[winnerIndex];
958
- }
959
- });
960
- };
961
-
962
- var Events = /** @class */ (function () {
963
- function Events() {
964
- this.events = Object.create({});
965
- }
966
- Events.prototype.emit = function (event, data) {
967
- var _a;
968
- (_a = this.events[event]) === null || _a === void 0 ? void 0 : _a.forEach(function (fn) { return fn(data); });
969
- };
970
- Events.prototype.on = function (event, callback) {
971
- this.events[event] = this.events[event] || [];
972
- this.events[event].push(callback);
973
- };
974
- Events.prototype.off = function (event, callback) {
975
- if (callback) {
976
- this.events[event] = this.events[event].filter(function (fn) { return fn !== callback; });
977
- }
978
- else {
979
- this.events[event] = [];
980
- }
981
- };
982
- return Events;
983
- }());
984
-
985
- var response = function (type, data) {
986
- if (type === 'success') {
987
- return __assign({ status: Status.Success }, data);
988
- }
989
- if (type === 'progress') {
990
- return __assign({ status: Status.Progress }, data);
991
- }
992
- return __assign({ status: Status.Error }, data);
993
- };
994
- var Pusher = /** @class */ (function () {
995
- function Pusher(pusherKey, disconnectTime) {
996
- if (disconnectTime === void 0) { disconnectTime = 30000; }
997
- this.ws = undefined;
998
- this.queue = [];
999
- this.isConnected = false;
1000
- this.subscribers = 0;
1001
- this.emmitter = new Events();
1002
- this.disconnectTimeoutId = null;
1003
- this.key = pusherKey;
1004
- this.disconnectTime = disconnectTime;
1005
- }
1006
- Pusher.prototype.connect = function () {
1007
- var _this = this;
1008
- this.disconnectTimeoutId && clearTimeout(this.disconnectTimeoutId);
1009
- if (!this.isConnected && !this.ws) {
1010
- var pusherUrl = "wss://ws.pusherapp.com/app/" + this.key + "?protocol=5&client=js&version=1.12.2";
1011
- this.ws = new WebSocket__default["default"](pusherUrl);
1012
- this.ws.addEventListener('error', function (error) {
1013
- _this.emmitter.emit('error', new Error(error.message));
1014
- });
1015
- this.emmitter.on('connected', function () {
1016
- _this.isConnected = true;
1017
- _this.queue.forEach(function (message) { return _this.send(message.event, message.data); });
1018
- _this.queue = [];
1019
- });
1020
- this.ws.addEventListener('message', function (e) {
1021
- var data = JSON.parse(e.data.toString());
1022
- switch (data.event) {
1023
- case 'pusher:connection_established': {
1024
- _this.emmitter.emit('connected', undefined);
1025
- break;
1026
- }
1027
- case 'pusher:ping': {
1028
- _this.send('pusher:pong', {});
1029
- break;
1030
- }
1031
- case 'progress':
1032
- case 'success':
1033
- case 'fail': {
1034
- _this.emmitter.emit(data.channel, response(data.event, JSON.parse(data.data)));
1035
- }
1036
- }
1037
- });
1038
- }
1039
- };
1040
- Pusher.prototype.disconnect = function () {
1041
- var _this = this;
1042
- var actualDisconect = function () {
1043
- var _a;
1044
- (_a = _this.ws) === null || _a === void 0 ? void 0 : _a.close();
1045
- _this.ws = undefined;
1046
- _this.isConnected = false;
1047
- };
1048
- if (this.disconnectTime) {
1049
- this.disconnectTimeoutId = setTimeout(function () {
1050
- actualDisconect();
1051
- }, this.disconnectTime);
1052
- }
1053
- else {
1054
- actualDisconect();
1055
- }
1056
- };
1057
- Pusher.prototype.send = function (event, data) {
1058
- var _a;
1059
- var str = JSON.stringify({ event: event, data: data });
1060
- (_a = this.ws) === null || _a === void 0 ? void 0 : _a.send(str);
1061
- };
1062
- Pusher.prototype.subscribe = function (token, handler) {
1063
- this.subscribers += 1;
1064
- this.connect();
1065
- var channel = "task-status-" + token;
1066
- var message = {
1067
- event: 'pusher:subscribe',
1068
- data: { channel: channel }
1069
- };
1070
- this.emmitter.on(channel, handler);
1071
- if (this.isConnected) {
1072
- this.send(message.event, message.data);
1073
- }
1074
- else {
1075
- this.queue.push(message);
1076
- }
1077
- };
1078
- Pusher.prototype.unsubscribe = function (token) {
1079
- this.subscribers -= 1;
1080
- var channel = "task-status-" + token;
1081
- var message = {
1082
- event: 'pusher:unsubscribe',
1083
- data: { channel: channel }
1084
- };
1085
- this.emmitter.off(channel);
1086
- if (this.isConnected) {
1087
- this.send(message.event, message.data);
1088
- }
1089
- else {
1090
- this.queue = this.queue.filter(function (msg) { return msg.data.channel !== channel; });
1091
- }
1092
- if (this.subscribers === 0) {
1093
- this.disconnect();
1094
- }
1095
- };
1096
- Pusher.prototype.onError = function (callback) {
1097
- var _this = this;
1098
- this.emmitter.on('error', callback);
1099
- return function () { return _this.emmitter.off('error', callback); };
1100
- };
1101
- return Pusher;
1102
- }());
1103
- var pusher = null;
1104
- var getPusher = function (key) {
1105
- if (!pusher) {
1106
- // no timeout for nodeJS and 30000 ms for browser
1107
- var disconectTimeout = typeof window === 'undefined' ? 0 : 30000;
1108
- pusher = new Pusher(key, disconectTimeout);
1109
- }
1110
- return pusher;
1111
- };
1112
- var preconnect = function (key) {
1113
- getPusher(key).connect();
1114
- };
1115
-
1116
- function pollStrategy(_a) {
1117
- var token = _a.token, publicKey = _a.publicKey, baseURL = _a.baseURL, integration = _a.integration, userAgent = _a.userAgent, retryThrottledRequestMaxTimes = _a.retryThrottledRequestMaxTimes, onProgress = _a.onProgress, signal = _a.signal;
1118
- return poll({
1119
- check: function (signal) {
1120
- return fromUrlStatus(token, {
1121
- publicKey: publicKey,
1122
- baseURL: baseURL,
1123
- integration: integration,
1124
- userAgent: userAgent,
1125
- retryThrottledRequestMaxTimes: retryThrottledRequestMaxTimes,
1126
- signal: signal
1127
- }).then(function (response) {
1128
- switch (response.status) {
1129
- case Status.Error: {
1130
- return new UploadClientError(response.error, response.errorCode);
1131
- }
1132
- case Status.Waiting: {
1133
- return false;
1134
- }
1135
- case Status.Unknown: {
1136
- return new UploadClientError("Token \"" + token + "\" was not found.");
1137
- }
1138
- case Status.Progress: {
1139
- if (onProgress) {
1140
- if (response.total === 'unknown') {
1141
- onProgress({ isComputable: false });
1142
- }
1143
- else {
1144
- onProgress({
1145
- isComputable: true,
1146
- value: response.done / response.total
1147
- });
1148
- }
1149
- }
1150
- return false;
1151
- }
1152
- case Status.Success: {
1153
- if (onProgress)
1154
- onProgress({
1155
- isComputable: true,
1156
- value: response.done / response.total
1157
- });
1158
- return response;
1159
- }
1160
- default: {
1161
- throw new Error('Unknown status');
1162
- }
1163
- }
1164
- });
1165
- },
1166
- signal: signal
1167
- });
1168
- }
1169
- var pushStrategy = function (_a) {
1170
- var token = _a.token, pusherKey = _a.pusherKey, signal = _a.signal, onProgress = _a.onProgress;
1171
- return new Promise(function (resolve, reject) {
1172
- var pusher = getPusher(pusherKey);
1173
- var unsubErrorHandler = pusher.onError(reject);
1174
- var destroy = function () {
1175
- unsubErrorHandler();
1176
- pusher.unsubscribe(token);
1177
- };
1178
- onCancel(signal, function () {
1179
- destroy();
1180
- reject(cancelError('pusher cancelled'));
1181
- });
1182
- pusher.subscribe(token, function (result) {
1183
- switch (result.status) {
1184
- case Status.Progress: {
1185
- if (onProgress) {
1186
- if (result.total === 'unknown') {
1187
- onProgress({ isComputable: false });
1188
- }
1189
- else {
1190
- onProgress({
1191
- isComputable: true,
1192
- value: result.done / result.total
1193
- });
1194
- }
1195
- }
1196
- break;
1197
- }
1198
- case Status.Success: {
1199
- destroy();
1200
- if (onProgress)
1201
- onProgress({
1202
- isComputable: true,
1203
- value: result.done / result.total
1204
- });
1205
- resolve(result);
1206
- break;
1207
- }
1208
- case Status.Error: {
1209
- destroy();
1210
- reject(new UploadClientError(result.msg, result.error_code));
1211
- }
1212
- }
1213
- });
1214
- });
1215
- };
1216
- var uploadFromUrl = function (sourceUrl, _a) {
1217
- var publicKey = _a.publicKey, fileName = _a.fileName, baseURL = _a.baseURL, baseCDN = _a.baseCDN, checkForUrlDuplicates = _a.checkForUrlDuplicates, saveUrlForRecurrentUploads = _a.saveUrlForRecurrentUploads, secureSignature = _a.secureSignature, secureExpire = _a.secureExpire, store = _a.store, signal = _a.signal, onProgress = _a.onProgress, source = _a.source, integration = _a.integration, userAgent = _a.userAgent, retryThrottledRequestMaxTimes = _a.retryThrottledRequestMaxTimes, _b = _a.pusherKey, pusherKey = _b === void 0 ? defaultSettings.pusherKey : _b, metadata = _a.metadata;
1218
- return Promise.resolve(preconnect(pusherKey))
1219
- .then(function () {
1220
- return fromUrl(sourceUrl, {
1221
- publicKey: publicKey,
1222
- fileName: fileName,
1223
- baseURL: baseURL,
1224
- checkForUrlDuplicates: checkForUrlDuplicates,
1225
- saveUrlForRecurrentUploads: saveUrlForRecurrentUploads,
1226
- secureSignature: secureSignature,
1227
- secureExpire: secureExpire,
1228
- store: store,
1229
- signal: signal,
1230
- source: source,
1231
- integration: integration,
1232
- userAgent: userAgent,
1233
- retryThrottledRequestMaxTimes: retryThrottledRequestMaxTimes,
1234
- metadata: metadata
1235
- });
1236
- })
1237
- .catch(function (error) {
1238
- var pusher = getPusher(pusherKey);
1239
- pusher === null || pusher === void 0 ? void 0 : pusher.disconnect();
1240
- return Promise.reject(error);
1241
- })
1242
- .then(function (urlResponse) {
1243
- if (urlResponse.type === TypeEnum.FileInfo) {
1244
- return urlResponse;
1245
- }
1246
- else {
1247
- return race([
1248
- function (_a) {
1249
- var signal = _a.signal;
1250
- return pollStrategy({
1251
- token: urlResponse.token,
1252
- publicKey: publicKey,
1253
- baseURL: baseURL,
1254
- integration: integration,
1255
- userAgent: userAgent,
1256
- retryThrottledRequestMaxTimes: retryThrottledRequestMaxTimes,
1257
- onProgress: onProgress,
1258
- signal: signal
1259
- });
1260
- },
1261
- function (_a) {
1262
- var signal = _a.signal;
1263
- return pushStrategy({
1264
- token: urlResponse.token,
1265
- pusherKey: pusherKey,
1266
- signal: signal,
1267
- onProgress: onProgress
1268
- });
1269
- }
1270
- ], { signal: signal });
1271
- }
1272
- })
1273
- .then(function (result) {
1274
- if (result instanceof UploadClientError)
1275
- throw result;
1276
- return result;
1277
- })
1278
- .then(function (result) {
1279
- return isReadyPoll({
1280
- file: result.uuid,
1281
- publicKey: publicKey,
1282
- baseURL: baseURL,
1283
- integration: integration,
1284
- userAgent: userAgent,
1285
- retryThrottledRequestMaxTimes: retryThrottledRequestMaxTimes,
1286
- onProgress: onProgress,
1287
- signal: signal
1288
- });
1289
- })
1290
- .then(function (fileInfo) { return new UploadcareFile(fileInfo, { baseCDN: baseCDN }); });
1291
- };
1292
-
1293
- var uploadFromUploaded = function (uuid, _a) {
1294
- var publicKey = _a.publicKey, fileName = _a.fileName, baseURL = _a.baseURL, signal = _a.signal, onProgress = _a.onProgress, source = _a.source, integration = _a.integration, userAgent = _a.userAgent, retryThrottledRequestMaxTimes = _a.retryThrottledRequestMaxTimes, baseCDN = _a.baseCDN;
1295
- return info(uuid, {
1296
- publicKey: publicKey,
1297
- baseURL: baseURL,
1298
- signal: signal,
1299
- source: source,
1300
- integration: integration,
1301
- userAgent: userAgent,
1302
- retryThrottledRequestMaxTimes: retryThrottledRequestMaxTimes
1303
- })
1304
- .then(function (fileInfo) { return new UploadcareFile(fileInfo, { baseCDN: baseCDN, fileName: fileName }); })
1305
- .then(function (result) {
1306
- // hack for node ¯\_(ツ)_/¯
1307
- if (onProgress)
1308
- onProgress({
1309
- isComputable: true,
1310
- value: 1
1311
- });
1312
- return result;
1313
- });
1314
- };
1315
-
1316
- /**
1317
- * Get file size.
1318
- */
1319
- var getFileSize = function (file) {
1320
- return file.length || file.size;
1321
- };
1322
- /**
1323
- * Check if FileData is multipart data.
1324
- */
1325
- var isMultipart = function (fileSize, multipartMinFileSize) {
1326
- if (multipartMinFileSize === void 0) { multipartMinFileSize = defaultSettings.multipartMinFileSize; }
1327
- return fileSize >= multipartMinFileSize;
1328
- };
1329
-
1330
- var sliceChunk = function (file, index, fileSize, chunkSize) {
1331
- var start = chunkSize * index;
1332
- var end = Math.min(start + chunkSize, fileSize);
1333
- return file.slice(start, end);
1334
- };
1335
-
1336
- function prepareChunks(file, fileSize, chunkSize) {
1337
- return function (index) {
1338
- return sliceChunk(file, index, fileSize, chunkSize);
1339
- };
1340
- }
1341
-
1342
- var runWithConcurrency = function (concurrency, tasks) {
1343
- return new Promise(function (resolve, reject) {
1344
- var results = [];
1345
- var rejected = false;
1346
- var settled = tasks.length;
1347
- var forRun = __spreadArrays(tasks);
1348
- var run = function () {
1349
- var index = tasks.length - forRun.length;
1350
- var next = forRun.shift();
1351
- if (next) {
1352
- next()
1353
- .then(function (result) {
1354
- if (rejected)
1355
- return;
1356
- results[index] = result;
1357
- settled -= 1;
1358
- if (settled) {
1359
- run();
1360
- }
1361
- else {
1362
- resolve(results);
1363
- }
1364
- })
1365
- .catch(function (error) {
1366
- rejected = true;
1367
- reject(error);
1368
- });
1369
- }
1370
- };
1371
- for (var i = 0; i < concurrency; i++) {
1372
- run();
1373
- }
1374
- });
1375
- };
1376
-
1377
- var uploadPartWithRetry = function (chunk, url, _a) {
1378
- var publicKey = _a.publicKey, onProgress = _a.onProgress, signal = _a.signal, integration = _a.integration, multipartMaxAttempts = _a.multipartMaxAttempts;
1379
- return retrier(function (_a) {
1380
- var attempt = _a.attempt, retry = _a.retry;
1381
- return multipartUpload(chunk, url, {
1382
- publicKey: publicKey,
1383
- onProgress: onProgress,
1384
- signal: signal,
1385
- integration: integration
1386
- }).catch(function (error) {
1387
- if (attempt < multipartMaxAttempts) {
1388
- return retry();
1389
- }
1390
- throw error;
1391
- });
1392
- });
1393
- };
1394
- var uploadMultipart = function (file, _a) {
1395
- var publicKey = _a.publicKey, fileName = _a.fileName, fileSize = _a.fileSize, baseURL = _a.baseURL, secureSignature = _a.secureSignature, secureExpire = _a.secureExpire, store = _a.store, signal = _a.signal, onProgress = _a.onProgress, source = _a.source, integration = _a.integration, userAgent = _a.userAgent, retryThrottledRequestMaxTimes = _a.retryThrottledRequestMaxTimes, contentType = _a.contentType, _b = _a.multipartChunkSize, multipartChunkSize = _b === void 0 ? defaultSettings.multipartChunkSize : _b, _c = _a.maxConcurrentRequests, maxConcurrentRequests = _c === void 0 ? defaultSettings.maxConcurrentRequests : _c, _d = _a.multipartMaxAttempts, multipartMaxAttempts = _d === void 0 ? defaultSettings.multipartMaxAttempts : _d, baseCDN = _a.baseCDN, metadata = _a.metadata;
1396
- var size = fileSize || getFileSize(file);
1397
- var progressValues;
1398
- var createProgressHandler = function (totalChunks, chunkIdx) {
1399
- if (!onProgress)
1400
- return;
1401
- if (!progressValues) {
1402
- progressValues = Array(totalChunks).fill(0);
1403
- }
1404
- var sum = function (values) {
1405
- return values.reduce(function (sum, next) { return sum + next; }, 0);
1406
- };
1407
- return function (info) {
1408
- if (!info.isComputable) {
1409
- return;
1410
- }
1411
- progressValues[chunkIdx] = info.value;
1412
- onProgress({
1413
- isComputable: true,
1414
- value: sum(progressValues) / totalChunks
1415
- });
1416
- };
1417
- };
1418
- return multipartStart(size, {
1419
- publicKey: publicKey,
1420
- contentType: contentType,
1421
- fileName: fileName !== null && fileName !== void 0 ? fileName : file.name,
1422
- baseURL: baseURL,
1423
- secureSignature: secureSignature,
1424
- secureExpire: secureExpire,
1425
- store: store,
1426
- signal: signal,
1427
- source: source,
1428
- integration: integration,
1429
- userAgent: userAgent,
1430
- retryThrottledRequestMaxTimes: retryThrottledRequestMaxTimes,
1431
- metadata: metadata
1432
- })
1433
- .then(function (_a) {
1434
- var uuid = _a.uuid, parts = _a.parts;
1435
- var getChunk = prepareChunks(file, size, multipartChunkSize);
1436
- return Promise.all([
1437
- uuid,
1438
- runWithConcurrency(maxConcurrentRequests, parts.map(function (url, index) { return function () {
1439
- return uploadPartWithRetry(getChunk(index), url, {
1440
- publicKey: publicKey,
1441
- onProgress: createProgressHandler(parts.length, index),
1442
- signal: signal,
1443
- integration: integration,
1444
- multipartMaxAttempts: multipartMaxAttempts
1445
- });
1446
- }; }))
1447
- ]);
1448
- })
1449
- .then(function (_a) {
1450
- var uuid = _a[0];
1451
- return multipartComplete(uuid, {
1452
- publicKey: publicKey,
1453
- baseURL: baseURL,
1454
- source: source,
1455
- integration: integration,
1456
- userAgent: userAgent,
1457
- retryThrottledRequestMaxTimes: retryThrottledRequestMaxTimes
1458
- });
1459
- })
1460
- .then(function (fileInfo) {
1461
- if (fileInfo.isReady) {
1462
- return fileInfo;
1463
- }
1464
- else {
1465
- return isReadyPoll({
1466
- file: fileInfo.uuid,
1467
- publicKey: publicKey,
1468
- baseURL: baseURL,
1469
- source: source,
1470
- integration: integration,
1471
- userAgent: userAgent,
1472
- retryThrottledRequestMaxTimes: retryThrottledRequestMaxTimes,
1473
- onProgress: onProgress,
1474
- signal: signal
1475
- });
1476
- }
1477
- })
1478
- .then(function (fileInfo) { return new UploadcareFile(fileInfo, { baseCDN: baseCDN }); });
1479
- };
1480
-
1481
- /**
1482
- * Uploads file from provided data.
1483
- */
1484
- function uploadFile(data, _a) {
1485
- var publicKey = _a.publicKey, fileName = _a.fileName, _b = _a.baseURL, baseURL = _b === void 0 ? defaultSettings.baseURL : _b, secureSignature = _a.secureSignature, secureExpire = _a.secureExpire, store = _a.store, signal = _a.signal, onProgress = _a.onProgress, source = _a.source, integration = _a.integration, userAgent = _a.userAgent, retryThrottledRequestMaxTimes = _a.retryThrottledRequestMaxTimes, contentType = _a.contentType, multipartMinFileSize = _a.multipartMinFileSize, multipartChunkSize = _a.multipartChunkSize, multipartMaxAttempts = _a.multipartMaxAttempts, maxConcurrentRequests = _a.maxConcurrentRequests, _c = _a.baseCDN, baseCDN = _c === void 0 ? defaultSettings.baseCDN : _c, checkForUrlDuplicates = _a.checkForUrlDuplicates, saveUrlForRecurrentUploads = _a.saveUrlForRecurrentUploads, pusherKey = _a.pusherKey, metadata = _a.metadata;
1486
- if (isFileData(data)) {
1487
- var fileSize = getFileSize(data);
1488
- if (isMultipart(fileSize, multipartMinFileSize)) {
1489
- return uploadMultipart(data, {
1490
- publicKey: publicKey,
1491
- contentType: contentType,
1492
- multipartChunkSize: multipartChunkSize,
1493
- multipartMaxAttempts: multipartMaxAttempts,
1494
- fileName: fileName,
1495
- baseURL: baseURL,
1496
- secureSignature: secureSignature,
1497
- secureExpire: secureExpire,
1498
- store: store,
1499
- signal: signal,
1500
- onProgress: onProgress,
1501
- source: source,
1502
- integration: integration,
1503
- userAgent: userAgent,
1504
- maxConcurrentRequests: maxConcurrentRequests,
1505
- retryThrottledRequestMaxTimes: retryThrottledRequestMaxTimes,
1506
- baseCDN: baseCDN,
1507
- metadata: metadata
1508
- });
1509
- }
1510
- return uploadFromObject(data, {
1511
- publicKey: publicKey,
1512
- fileName: fileName,
1513
- baseURL: baseURL,
1514
- secureSignature: secureSignature,
1515
- secureExpire: secureExpire,
1516
- store: store,
1517
- signal: signal,
1518
- onProgress: onProgress,
1519
- source: source,
1520
- integration: integration,
1521
- userAgent: userAgent,
1522
- retryThrottledRequestMaxTimes: retryThrottledRequestMaxTimes,
1523
- baseCDN: baseCDN,
1524
- metadata: metadata
1525
- });
1526
- }
1527
- if (isUrl(data)) {
1528
- return uploadFromUrl(data, {
1529
- publicKey: publicKey,
1530
- fileName: fileName,
1531
- baseURL: baseURL,
1532
- baseCDN: baseCDN,
1533
- checkForUrlDuplicates: checkForUrlDuplicates,
1534
- saveUrlForRecurrentUploads: saveUrlForRecurrentUploads,
1535
- secureSignature: secureSignature,
1536
- secureExpire: secureExpire,
1537
- store: store,
1538
- signal: signal,
1539
- onProgress: onProgress,
1540
- source: source,
1541
- integration: integration,
1542
- userAgent: userAgent,
1543
- retryThrottledRequestMaxTimes: retryThrottledRequestMaxTimes,
1544
- pusherKey: pusherKey,
1545
- metadata: metadata
1546
- });
1547
- }
1548
- if (isUuid(data)) {
1549
- return uploadFromUploaded(data, {
1550
- publicKey: publicKey,
1551
- fileName: fileName,
1552
- baseURL: baseURL,
1553
- signal: signal,
1554
- onProgress: onProgress,
1555
- source: source,
1556
- integration: integration,
1557
- userAgent: userAgent,
1558
- retryThrottledRequestMaxTimes: retryThrottledRequestMaxTimes,
1559
- baseCDN: baseCDN
1560
- });
1561
- }
1562
- throw new TypeError("File uploading from \"" + data + "\" is not supported");
1563
- }
1564
-
1565
- var UploadcareGroup = /** @class */ (function () {
1566
- function UploadcareGroup(groupInfo, files) {
1567
- this.storedAt = null;
1568
- this.uuid = groupInfo.id;
1569
- this.filesCount = groupInfo.filesCount;
1570
- this.totalSize = Object.values(groupInfo.files).reduce(function (acc, file) { return acc + file.size; }, 0);
1571
- this.isStored = !!groupInfo.datetimeStored;
1572
- this.isImage = !!Object.values(groupInfo.files).filter(function (file) { return file.isImage; }).length;
1573
- this.cdnUrl = groupInfo.cdnUrl;
1574
- this.files = files;
1575
- this.createdAt = groupInfo.datetimeCreated;
1576
- this.storedAt = groupInfo.datetimeStored;
1577
- }
1578
- return UploadcareGroup;
1579
- }());
1580
-
1581
- /**
1582
- * FileData type guard.
1583
- */
1584
- var isFileDataArray = function (data) {
1585
- for (var _i = 0, data_1 = data; _i < data_1.length; _i++) {
1586
- var item = data_1[_i];
1587
- if (!isFileData(item)) {
1588
- return false;
1589
- }
1590
- }
1591
- return true;
1592
- };
1593
- /**
1594
- * Uuid type guard.
1595
- */
1596
- var isUuidArray = function (data) {
1597
- for (var _i = 0, data_2 = data; _i < data_2.length; _i++) {
1598
- var item = data_2[_i];
1599
- if (!isUuid(item)) {
1600
- return false;
1601
- }
1602
- }
1603
- return true;
1604
- };
1605
- /**
1606
- * Url type guard.
1607
- */
1608
- var isUrlArray = function (data) {
1609
- for (var _i = 0, data_3 = data; _i < data_3.length; _i++) {
1610
- var item = data_3[_i];
1611
- if (!isUrl(item)) {
1612
- return false;
1613
- }
1614
- }
1615
- return true;
1616
- };
1617
-
1618
- function uploadFileGroup(data, _a) {
1619
- var publicKey = _a.publicKey, fileName = _a.fileName, _b = _a.baseURL, baseURL = _b === void 0 ? defaultSettings.baseURL : _b, secureSignature = _a.secureSignature, secureExpire = _a.secureExpire, store = _a.store, signal = _a.signal, onProgress = _a.onProgress, source = _a.source, integration = _a.integration, userAgent = _a.userAgent, retryThrottledRequestMaxTimes = _a.retryThrottledRequestMaxTimes, contentType = _a.contentType, _c = _a.multipartChunkSize, multipartChunkSize = _c === void 0 ? defaultSettings.multipartChunkSize : _c, _d = _a.baseCDN, baseCDN = _d === void 0 ? defaultSettings.baseCDN : _d, jsonpCallback = _a.jsonpCallback, defaultEffects = _a.defaultEffects;
1620
- if (!isFileDataArray(data) && !isUrlArray(data) && !isUuidArray(data)) {
1621
- throw new TypeError("Group uploading from \"" + data + "\" is not supported");
1622
- }
1623
- var progressValues;
1624
- var isStillComputable = true;
1625
- var filesCount = data.length;
1626
- var createProgressHandler = function (size, index) {
1627
- if (!onProgress)
1628
- return;
1629
- if (!progressValues) {
1630
- progressValues = Array(size).fill(0);
1631
- }
1632
- var normalize = function (values) {
1633
- return values.reduce(function (sum, next) { return sum + next; }) / size;
1634
- };
1635
- return function (info) {
1636
- if (!info.isComputable || !isStillComputable) {
1637
- isStillComputable = false;
1638
- onProgress({ isComputable: false });
1639
- return;
1640
- }
1641
- progressValues[index] = info.value;
1642
- onProgress({ isComputable: true, value: normalize(progressValues) });
1643
- };
1644
- };
1645
- return Promise.all(data.map(function (file, index) {
1646
- return uploadFile(file, {
1647
- publicKey: publicKey,
1648
- fileName: fileName,
1649
- baseURL: baseURL,
1650
- secureSignature: secureSignature,
1651
- secureExpire: secureExpire,
1652
- store: store,
1653
- signal: signal,
1654
- onProgress: createProgressHandler(filesCount, index),
1655
- source: source,
1656
- integration: integration,
1657
- userAgent: userAgent,
1658
- retryThrottledRequestMaxTimes: retryThrottledRequestMaxTimes,
1659
- contentType: contentType,
1660
- multipartChunkSize: multipartChunkSize,
1661
- baseCDN: baseCDN
1662
- });
1663
- })).then(function (files) {
1664
- var uuids = files.map(function (file) { return file.uuid; });
1665
- var addDefaultEffects = function (file) {
1666
- var cdnUrlModifiers = defaultEffects ? "-/" + defaultEffects : null;
1667
- var cdnUrl = "" + file.urlBase + (cdnUrlModifiers || '');
1668
- return __assign(__assign({}, file), { cdnUrlModifiers: cdnUrlModifiers,
1669
- cdnUrl: cdnUrl });
1670
- };
1671
- var filesInGroup = defaultEffects ? files.map(addDefaultEffects) : files;
1672
- return group(uuids, {
1673
- publicKey: publicKey,
1674
- baseURL: baseURL,
1675
- jsonpCallback: jsonpCallback,
1676
- secureSignature: secureSignature,
1677
- secureExpire: secureExpire,
1678
- signal: signal,
1679
- source: source,
1680
- integration: integration,
1681
- userAgent: userAgent,
1682
- retryThrottledRequestMaxTimes: retryThrottledRequestMaxTimes
1683
- })
1684
- .then(function (groupInfo) { return new UploadcareGroup(groupInfo, filesInGroup); })
1685
- .then(function (group) {
1686
- onProgress && onProgress({ isComputable: true, value: 1 });
1687
- return group;
1688
- });
1689
- });
1690
- }
1691
-
1692
- /**
1693
- * Populate options with settings.
1694
- */
1695
- var populateOptionsWithSettings = function (options, settings) { return (__assign(__assign({}, settings), options)); };
1696
- var UploadClient = /** @class */ (function () {
1697
- function UploadClient(settings) {
1698
- this.settings = Object.assign({}, defaultSettings, settings);
1699
- }
1700
- UploadClient.prototype.updateSettings = function (newSettings) {
1701
- this.settings = Object.assign(this.settings, newSettings);
1702
- };
1703
- UploadClient.prototype.getSettings = function () {
1704
- return this.settings;
1705
- };
1706
- UploadClient.prototype.base = function (file, options) {
1707
- var settings = this.getSettings();
1708
- return base(file, populateOptionsWithSettings(options, settings));
1709
- };
1710
- UploadClient.prototype.info = function (uuid, options) {
1711
- var settings = this.getSettings();
1712
- return info(uuid, populateOptionsWithSettings(options, settings));
1713
- };
1714
- UploadClient.prototype.fromUrl = function (sourceUrl, options) {
1715
- var settings = this.getSettings();
1716
- return fromUrl(sourceUrl, populateOptionsWithSettings(options, settings));
1717
- };
1718
- UploadClient.prototype.fromUrlStatus = function (token, options) {
1719
- var settings = this.getSettings();
1720
- return fromUrlStatus(token, populateOptionsWithSettings(options, settings));
1721
- };
1722
- UploadClient.prototype.group = function (uuids, options) {
1723
- var settings = this.getSettings();
1724
- return group(uuids, populateOptionsWithSettings(options, settings));
1725
- };
1726
- UploadClient.prototype.groupInfo = function (id, options) {
1727
- var settings = this.getSettings();
1728
- return groupInfo(id, populateOptionsWithSettings(options, settings));
1729
- };
1730
- UploadClient.prototype.multipartStart = function (size, options) {
1731
- var settings = this.getSettings();
1732
- return multipartStart(size, populateOptionsWithSettings(options, settings));
1733
- };
1734
- UploadClient.prototype.multipartUpload = function (part, url, options) {
1735
- var settings = this.getSettings();
1736
- return multipartUpload(part, url, populateOptionsWithSettings(options, settings));
1737
- };
1738
- UploadClient.prototype.multipartComplete = function (uuid, options) {
1739
- var settings = this.getSettings();
1740
- return multipartComplete(uuid, populateOptionsWithSettings(options, settings));
1741
- };
1742
- UploadClient.prototype.uploadFile = function (data, options) {
1743
- var settings = this.getSettings();
1744
- return uploadFile(data, populateOptionsWithSettings(options, settings));
1745
- };
1746
- UploadClient.prototype.uploadFileGroup = function (data, options) {
1747
- var settings = this.getSettings();
1748
- return uploadFileGroup(data, populateOptionsWithSettings(options, settings));
1749
- };
1750
- return UploadClient;
1751
- }());
1752
-
1753
- Object.defineProperty(exports, 'AbortController', {
1754
- enumerable: true,
1755
- get: function () { return abortController.AbortController; }
1756
- });
1757
- exports.UploadClient = UploadClient;
1758
- exports.UploadClientError = UploadClientError;
1759
- exports.UploadcareFile = UploadcareFile;
1760
- exports.UploadcareGroup = UploadcareGroup;
1761
- exports.base = base;
1762
- exports.fromUrl = fromUrl;
1763
- exports.fromUrlStatus = fromUrlStatus;
1764
- exports.group = group;
1765
- exports.groupInfo = groupInfo;
1766
- exports.info = info;
1767
- exports.multipartComplete = multipartComplete;
1768
- exports.multipartStart = multipartStart;
1769
- exports.multipartUpload = multipartUpload;
1770
- exports.uploadBase = uploadFromObject;
1771
- exports.uploadFile = uploadFile;
1772
- exports.uploadFileGroup = uploadFileGroup;
1773
- exports.uploadFromUploaded = uploadFromUploaded;
1774
- exports.uploadFromUrl = uploadFromUrl;
1775
- exports.uploadMultipart = uploadMultipart;