@uploadcare/upload-client 3.1.2-alpha.0 → 4.1.0

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