@uploadcare/upload-client 6.4.0 → 6.5.0-alpha.2

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