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