@docbox-nz/hapi-gateway 0.2.1 → 0.3.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (48) hide show
  1. package/.github/workflows/build.yml +33 -0
  2. package/.github/workflows/release.yml +37 -0
  3. package/.oxfmtrc.json +8 -0
  4. package/.oxlintrc.json +11 -0
  5. package/.zed/settings.json +10 -0
  6. package/README.md +32 -38
  7. package/cspell.json +1 -4
  8. package/dist/index.node.cjs +15319 -24159
  9. package/dist/index.node.cjs.map +1 -1
  10. package/dist/index.node.esm.js +15259 -24104
  11. package/dist/index.node.esm.js.map +1 -1
  12. package/package.json +20 -30
  13. package/rolldown.config.js +19 -0
  14. package/src/index.ts +257 -257
  15. package/tsconfig.json +15 -15
  16. package/.eslintignore +0 -6
  17. package/.eslintrc +0 -131
  18. package/.prettierignore +0 -11
  19. package/.prettierrc +0 -6
  20. package/dist/api/adminService.d.ts +0 -16
  21. package/dist/api/boxService.d.ts +0 -43
  22. package/dist/api/client.d.ts +0 -45
  23. package/dist/api/docboxFile.d.ts +0 -15
  24. package/dist/api/fileService.d.ts +0 -251
  25. package/dist/api/folderService.d.ts +0 -45
  26. package/dist/api/linkService.d.ts +0 -115
  27. package/dist/api/taskService.d.ts +0 -23
  28. package/dist/api/utils.d.ts +0 -1
  29. package/dist/error.d.ts +0 -11
  30. package/dist/index.browser.cjs +0 -988
  31. package/dist/index.browser.cjs.map +0 -1
  32. package/dist/index.browser.esm.js +0 -984
  33. package/dist/index.browser.esm.js.map +0 -1
  34. package/dist/index.browser.js +0 -4390
  35. package/dist/index.browser.js.map +0 -1
  36. package/dist/index.d.ts +0 -4
  37. package/dist/index.node.js +0 -20809
  38. package/dist/index.node.js.map +0 -1
  39. package/dist/options.d.ts +0 -85
  40. package/dist/types/box.d.ts +0 -59
  41. package/dist/types/file.d.ts +0 -371
  42. package/dist/types/folder.d.ts +0 -153
  43. package/dist/types/index.d.ts +0 -22
  44. package/dist/types/link.d.ts +0 -136
  45. package/dist/types/search.d.ts +0 -177
  46. package/dist/types/shared.d.ts +0 -94
  47. package/dist/types/user.d.ts +0 -20
  48. package/rollup.config.js +0 -36
@@ -1,4390 +0,0 @@
1
- 'use strict';
2
-
3
- exports.DocItemType = void 0;
4
- (function (DocItemType) {
5
- DocItemType["FILE"] = "File";
6
- DocItemType["FOLDER"] = "Folder";
7
- DocItemType["LINK"] = "Link";
8
- })(exports.DocItemType || (exports.DocItemType = {}));
9
- exports.GeneratedFileType = void 0;
10
- (function (GeneratedFileType) {
11
- GeneratedFileType["PDF"] = "Pdf";
12
- GeneratedFileType["COVER_PAGE"] = "CoverPage";
13
- GeneratedFileType["SMALL_THUMBNAIL"] = "SmallThumbnail";
14
- GeneratedFileType["LARGE_THUMBNAIL"] = "LargeThumbnail";
15
- })(exports.GeneratedFileType || (exports.GeneratedFileType = {}));
16
- exports.SearchResultItemType = void 0;
17
- (function (SearchResultItemType) {
18
- SearchResultItemType["FILE"] = "File";
19
- SearchResultItemType["FOLDER"] = "Folder";
20
- SearchResultItemType["LINK"] = "Link";
21
- })(exports.SearchResultItemType || (exports.SearchResultItemType = {}));
22
- exports.ItemContentMatchType = void 0;
23
- (function (ItemContentMatchType) {
24
- ItemContentMatchType["Content"] = "Content";
25
- ItemContentMatchType["Pages"] = "Pages";
26
- })(exports.ItemContentMatchType || (exports.ItemContentMatchType = {}));
27
- exports.DocboxTaskStatus = void 0;
28
- (function (DocboxTaskStatus) {
29
- DocboxTaskStatus["Pending"] = "Pending";
30
- DocboxTaskStatus["Completed"] = "Completed";
31
- DocboxTaskStatus["Failed"] = "Failed";
32
- })(exports.DocboxTaskStatus || (exports.DocboxTaskStatus = {}));
33
-
34
- function sleep(timeout) {
35
- return new Promise((resolve) => setTimeout(resolve, timeout));
36
- }
37
-
38
- /******************************************************************************
39
- Copyright (c) Microsoft Corporation.
40
-
41
- Permission to use, copy, modify, and/or distribute this software for any
42
- purpose with or without fee is hereby granted.
43
-
44
- THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
45
- REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
46
- AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
47
- INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
48
- LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
49
- OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
50
- PERFORMANCE OF THIS SOFTWARE.
51
- ***************************************************************************** */
52
- /* global Reflect, Promise, SuppressedError, Symbol, Iterator */
53
-
54
-
55
- function __awaiter(thisArg, _arguments, P, generator) {
56
- function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
57
- return new (P || (P = Promise))(function (resolve, reject) {
58
- function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
59
- function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
60
- function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
61
- step((generator = generator.apply(thisArg, _arguments || [])).next());
62
- });
63
- }
64
-
65
- typeof SuppressedError === "function" ? SuppressedError : function (error, suppressed, message) {
66
- var e = new Error(message);
67
- return e.name = "SuppressedError", e.error = error, e.suppressed = suppressed, e;
68
- };
69
-
70
- function bind(fn, thisArg) {
71
- return function wrap() {
72
- return fn.apply(thisArg, arguments);
73
- };
74
- }
75
-
76
- // utils is a library of generic helper functions non-specific to axios
77
-
78
- const {toString} = Object.prototype;
79
- const {getPrototypeOf} = Object;
80
-
81
- const kindOf = (cache => thing => {
82
- const str = toString.call(thing);
83
- return cache[str] || (cache[str] = str.slice(8, -1).toLowerCase());
84
- })(Object.create(null));
85
-
86
- const kindOfTest = (type) => {
87
- type = type.toLowerCase();
88
- return (thing) => kindOf(thing) === type
89
- };
90
-
91
- const typeOfTest = type => thing => typeof thing === type;
92
-
93
- /**
94
- * Determine if a value is an Array
95
- *
96
- * @param {Object} val The value to test
97
- *
98
- * @returns {boolean} True if value is an Array, otherwise false
99
- */
100
- const {isArray} = Array;
101
-
102
- /**
103
- * Determine if a value is undefined
104
- *
105
- * @param {*} val The value to test
106
- *
107
- * @returns {boolean} True if the value is undefined, otherwise false
108
- */
109
- const isUndefined = typeOfTest('undefined');
110
-
111
- /**
112
- * Determine if a value is a Buffer
113
- *
114
- * @param {*} val The value to test
115
- *
116
- * @returns {boolean} True if value is a Buffer, otherwise false
117
- */
118
- function isBuffer(val) {
119
- return val !== null && !isUndefined(val) && val.constructor !== null && !isUndefined(val.constructor)
120
- && isFunction(val.constructor.isBuffer) && val.constructor.isBuffer(val);
121
- }
122
-
123
- /**
124
- * Determine if a value is an ArrayBuffer
125
- *
126
- * @param {*} val The value to test
127
- *
128
- * @returns {boolean} True if value is an ArrayBuffer, otherwise false
129
- */
130
- const isArrayBuffer = kindOfTest('ArrayBuffer');
131
-
132
-
133
- /**
134
- * Determine if a value is a view on an ArrayBuffer
135
- *
136
- * @param {*} val The value to test
137
- *
138
- * @returns {boolean} True if value is a view on an ArrayBuffer, otherwise false
139
- */
140
- function isArrayBufferView(val) {
141
- let result;
142
- if ((typeof ArrayBuffer !== 'undefined') && (ArrayBuffer.isView)) {
143
- result = ArrayBuffer.isView(val);
144
- } else {
145
- result = (val) && (val.buffer) && (isArrayBuffer(val.buffer));
146
- }
147
- return result;
148
- }
149
-
150
- /**
151
- * Determine if a value is a String
152
- *
153
- * @param {*} val The value to test
154
- *
155
- * @returns {boolean} True if value is a String, otherwise false
156
- */
157
- const isString = typeOfTest('string');
158
-
159
- /**
160
- * Determine if a value is a Function
161
- *
162
- * @param {*} val The value to test
163
- * @returns {boolean} True if value is a Function, otherwise false
164
- */
165
- const isFunction = typeOfTest('function');
166
-
167
- /**
168
- * Determine if a value is a Number
169
- *
170
- * @param {*} val The value to test
171
- *
172
- * @returns {boolean} True if value is a Number, otherwise false
173
- */
174
- const isNumber = typeOfTest('number');
175
-
176
- /**
177
- * Determine if a value is an Object
178
- *
179
- * @param {*} thing The value to test
180
- *
181
- * @returns {boolean} True if value is an Object, otherwise false
182
- */
183
- const isObject = (thing) => thing !== null && typeof thing === 'object';
184
-
185
- /**
186
- * Determine if a value is a Boolean
187
- *
188
- * @param {*} thing The value to test
189
- * @returns {boolean} True if value is a Boolean, otherwise false
190
- */
191
- const isBoolean = thing => thing === true || thing === false;
192
-
193
- /**
194
- * Determine if a value is a plain Object
195
- *
196
- * @param {*} val The value to test
197
- *
198
- * @returns {boolean} True if value is a plain Object, otherwise false
199
- */
200
- const isPlainObject = (val) => {
201
- if (kindOf(val) !== 'object') {
202
- return false;
203
- }
204
-
205
- const prototype = getPrototypeOf(val);
206
- return (prototype === null || prototype === Object.prototype || Object.getPrototypeOf(prototype) === null) && !(Symbol.toStringTag in val) && !(Symbol.iterator in val);
207
- };
208
-
209
- /**
210
- * Determine if a value is a Date
211
- *
212
- * @param {*} val The value to test
213
- *
214
- * @returns {boolean} True if value is a Date, otherwise false
215
- */
216
- const isDate = kindOfTest('Date');
217
-
218
- /**
219
- * Determine if a value is a File
220
- *
221
- * @param {*} val The value to test
222
- *
223
- * @returns {boolean} True if value is a File, otherwise false
224
- */
225
- const isFile = kindOfTest('File');
226
-
227
- /**
228
- * Determine if a value is a Blob
229
- *
230
- * @param {*} val The value to test
231
- *
232
- * @returns {boolean} True if value is a Blob, otherwise false
233
- */
234
- const isBlob = kindOfTest('Blob');
235
-
236
- /**
237
- * Determine if a value is a FileList
238
- *
239
- * @param {*} val The value to test
240
- *
241
- * @returns {boolean} True if value is a File, otherwise false
242
- */
243
- const isFileList = kindOfTest('FileList');
244
-
245
- /**
246
- * Determine if a value is a Stream
247
- *
248
- * @param {*} val The value to test
249
- *
250
- * @returns {boolean} True if value is a Stream, otherwise false
251
- */
252
- const isStream = (val) => isObject(val) && isFunction(val.pipe);
253
-
254
- /**
255
- * Determine if a value is a FormData
256
- *
257
- * @param {*} thing The value to test
258
- *
259
- * @returns {boolean} True if value is an FormData, otherwise false
260
- */
261
- const isFormData = (thing) => {
262
- let kind;
263
- return thing && (
264
- (typeof FormData === 'function' && thing instanceof FormData) || (
265
- isFunction(thing.append) && (
266
- (kind = kindOf(thing)) === 'formdata' ||
267
- // detect form-data instance
268
- (kind === 'object' && isFunction(thing.toString) && thing.toString() === '[object FormData]')
269
- )
270
- )
271
- )
272
- };
273
-
274
- /**
275
- * Determine if a value is a URLSearchParams object
276
- *
277
- * @param {*} val The value to test
278
- *
279
- * @returns {boolean} True if value is a URLSearchParams object, otherwise false
280
- */
281
- const isURLSearchParams = kindOfTest('URLSearchParams');
282
-
283
- const [isReadableStream, isRequest, isResponse, isHeaders] = ['ReadableStream', 'Request', 'Response', 'Headers'].map(kindOfTest);
284
-
285
- /**
286
- * Trim excess whitespace off the beginning and end of a string
287
- *
288
- * @param {String} str The String to trim
289
- *
290
- * @returns {String} The String freed of excess whitespace
291
- */
292
- const trim = (str) => str.trim ?
293
- str.trim() : str.replace(/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g, '');
294
-
295
- /**
296
- * Iterate over an Array or an Object invoking a function for each item.
297
- *
298
- * If `obj` is an Array callback will be called passing
299
- * the value, index, and complete array for each item.
300
- *
301
- * If 'obj' is an Object callback will be called passing
302
- * the value, key, and complete object for each property.
303
- *
304
- * @param {Object|Array} obj The object to iterate
305
- * @param {Function} fn The callback to invoke for each item
306
- *
307
- * @param {Boolean} [allOwnKeys = false]
308
- * @returns {any}
309
- */
310
- function forEach(obj, fn, {allOwnKeys = false} = {}) {
311
- // Don't bother if no value provided
312
- if (obj === null || typeof obj === 'undefined') {
313
- return;
314
- }
315
-
316
- let i;
317
- let l;
318
-
319
- // Force an array if not already something iterable
320
- if (typeof obj !== 'object') {
321
- /*eslint no-param-reassign:0*/
322
- obj = [obj];
323
- }
324
-
325
- if (isArray(obj)) {
326
- // Iterate over array values
327
- for (i = 0, l = obj.length; i < l; i++) {
328
- fn.call(null, obj[i], i, obj);
329
- }
330
- } else {
331
- // Iterate over object keys
332
- const keys = allOwnKeys ? Object.getOwnPropertyNames(obj) : Object.keys(obj);
333
- const len = keys.length;
334
- let key;
335
-
336
- for (i = 0; i < len; i++) {
337
- key = keys[i];
338
- fn.call(null, obj[key], key, obj);
339
- }
340
- }
341
- }
342
-
343
- function findKey(obj, key) {
344
- key = key.toLowerCase();
345
- const keys = Object.keys(obj);
346
- let i = keys.length;
347
- let _key;
348
- while (i-- > 0) {
349
- _key = keys[i];
350
- if (key === _key.toLowerCase()) {
351
- return _key;
352
- }
353
- }
354
- return null;
355
- }
356
-
357
- const _global = (() => {
358
- /*eslint no-undef:0*/
359
- if (typeof globalThis !== "undefined") return globalThis;
360
- return typeof self !== "undefined" ? self : (typeof window !== 'undefined' ? window : global)
361
- })();
362
-
363
- const isContextDefined = (context) => !isUndefined(context) && context !== _global;
364
-
365
- /**
366
- * Accepts varargs expecting each argument to be an object, then
367
- * immutably merges the properties of each object and returns result.
368
- *
369
- * When multiple objects contain the same key the later object in
370
- * the arguments list will take precedence.
371
- *
372
- * Example:
373
- *
374
- * ```js
375
- * var result = merge({foo: 123}, {foo: 456});
376
- * console.log(result.foo); // outputs 456
377
- * ```
378
- *
379
- * @param {Object} obj1 Object to merge
380
- *
381
- * @returns {Object} Result of all merge properties
382
- */
383
- function merge(/* obj1, obj2, obj3, ... */) {
384
- const {caseless} = isContextDefined(this) && this || {};
385
- const result = {};
386
- const assignValue = (val, key) => {
387
- const targetKey = caseless && findKey(result, key) || key;
388
- if (isPlainObject(result[targetKey]) && isPlainObject(val)) {
389
- result[targetKey] = merge(result[targetKey], val);
390
- } else if (isPlainObject(val)) {
391
- result[targetKey] = merge({}, val);
392
- } else if (isArray(val)) {
393
- result[targetKey] = val.slice();
394
- } else {
395
- result[targetKey] = val;
396
- }
397
- };
398
-
399
- for (let i = 0, l = arguments.length; i < l; i++) {
400
- arguments[i] && forEach(arguments[i], assignValue);
401
- }
402
- return result;
403
- }
404
-
405
- /**
406
- * Extends object a by mutably adding to it the properties of object b.
407
- *
408
- * @param {Object} a The object to be extended
409
- * @param {Object} b The object to copy properties from
410
- * @param {Object} thisArg The object to bind function to
411
- *
412
- * @param {Boolean} [allOwnKeys]
413
- * @returns {Object} The resulting value of object a
414
- */
415
- const extend = (a, b, thisArg, {allOwnKeys}= {}) => {
416
- forEach(b, (val, key) => {
417
- if (thisArg && isFunction(val)) {
418
- a[key] = bind(val, thisArg);
419
- } else {
420
- a[key] = val;
421
- }
422
- }, {allOwnKeys});
423
- return a;
424
- };
425
-
426
- /**
427
- * Remove byte order marker. This catches EF BB BF (the UTF-8 BOM)
428
- *
429
- * @param {string} content with BOM
430
- *
431
- * @returns {string} content value without BOM
432
- */
433
- const stripBOM = (content) => {
434
- if (content.charCodeAt(0) === 0xFEFF) {
435
- content = content.slice(1);
436
- }
437
- return content;
438
- };
439
-
440
- /**
441
- * Inherit the prototype methods from one constructor into another
442
- * @param {function} constructor
443
- * @param {function} superConstructor
444
- * @param {object} [props]
445
- * @param {object} [descriptors]
446
- *
447
- * @returns {void}
448
- */
449
- const inherits = (constructor, superConstructor, props, descriptors) => {
450
- constructor.prototype = Object.create(superConstructor.prototype, descriptors);
451
- constructor.prototype.constructor = constructor;
452
- Object.defineProperty(constructor, 'super', {
453
- value: superConstructor.prototype
454
- });
455
- props && Object.assign(constructor.prototype, props);
456
- };
457
-
458
- /**
459
- * Resolve object with deep prototype chain to a flat object
460
- * @param {Object} sourceObj source object
461
- * @param {Object} [destObj]
462
- * @param {Function|Boolean} [filter]
463
- * @param {Function} [propFilter]
464
- *
465
- * @returns {Object}
466
- */
467
- const toFlatObject = (sourceObj, destObj, filter, propFilter) => {
468
- let props;
469
- let i;
470
- let prop;
471
- const merged = {};
472
-
473
- destObj = destObj || {};
474
- // eslint-disable-next-line no-eq-null,eqeqeq
475
- if (sourceObj == null) return destObj;
476
-
477
- do {
478
- props = Object.getOwnPropertyNames(sourceObj);
479
- i = props.length;
480
- while (i-- > 0) {
481
- prop = props[i];
482
- if ((!propFilter || propFilter(prop, sourceObj, destObj)) && !merged[prop]) {
483
- destObj[prop] = sourceObj[prop];
484
- merged[prop] = true;
485
- }
486
- }
487
- sourceObj = filter !== false && getPrototypeOf(sourceObj);
488
- } while (sourceObj && (!filter || filter(sourceObj, destObj)) && sourceObj !== Object.prototype);
489
-
490
- return destObj;
491
- };
492
-
493
- /**
494
- * Determines whether a string ends with the characters of a specified string
495
- *
496
- * @param {String} str
497
- * @param {String} searchString
498
- * @param {Number} [position= 0]
499
- *
500
- * @returns {boolean}
501
- */
502
- const endsWith = (str, searchString, position) => {
503
- str = String(str);
504
- if (position === undefined || position > str.length) {
505
- position = str.length;
506
- }
507
- position -= searchString.length;
508
- const lastIndex = str.indexOf(searchString, position);
509
- return lastIndex !== -1 && lastIndex === position;
510
- };
511
-
512
-
513
- /**
514
- * Returns new array from array like object or null if failed
515
- *
516
- * @param {*} [thing]
517
- *
518
- * @returns {?Array}
519
- */
520
- const toArray = (thing) => {
521
- if (!thing) return null;
522
- if (isArray(thing)) return thing;
523
- let i = thing.length;
524
- if (!isNumber(i)) return null;
525
- const arr = new Array(i);
526
- while (i-- > 0) {
527
- arr[i] = thing[i];
528
- }
529
- return arr;
530
- };
531
-
532
- /**
533
- * Checking if the Uint8Array exists and if it does, it returns a function that checks if the
534
- * thing passed in is an instance of Uint8Array
535
- *
536
- * @param {TypedArray}
537
- *
538
- * @returns {Array}
539
- */
540
- // eslint-disable-next-line func-names
541
- const isTypedArray = (TypedArray => {
542
- // eslint-disable-next-line func-names
543
- return thing => {
544
- return TypedArray && thing instanceof TypedArray;
545
- };
546
- })(typeof Uint8Array !== 'undefined' && getPrototypeOf(Uint8Array));
547
-
548
- /**
549
- * For each entry in the object, call the function with the key and value.
550
- *
551
- * @param {Object<any, any>} obj - The object to iterate over.
552
- * @param {Function} fn - The function to call for each entry.
553
- *
554
- * @returns {void}
555
- */
556
- const forEachEntry = (obj, fn) => {
557
- const generator = obj && obj[Symbol.iterator];
558
-
559
- const iterator = generator.call(obj);
560
-
561
- let result;
562
-
563
- while ((result = iterator.next()) && !result.done) {
564
- const pair = result.value;
565
- fn.call(obj, pair[0], pair[1]);
566
- }
567
- };
568
-
569
- /**
570
- * It takes a regular expression and a string, and returns an array of all the matches
571
- *
572
- * @param {string} regExp - The regular expression to match against.
573
- * @param {string} str - The string to search.
574
- *
575
- * @returns {Array<boolean>}
576
- */
577
- const matchAll = (regExp, str) => {
578
- let matches;
579
- const arr = [];
580
-
581
- while ((matches = regExp.exec(str)) !== null) {
582
- arr.push(matches);
583
- }
584
-
585
- return arr;
586
- };
587
-
588
- /* Checking if the kindOfTest function returns true when passed an HTMLFormElement. */
589
- const isHTMLForm = kindOfTest('HTMLFormElement');
590
-
591
- const toCamelCase = str => {
592
- return str.toLowerCase().replace(/[-_\s]([a-z\d])(\w*)/g,
593
- function replacer(m, p1, p2) {
594
- return p1.toUpperCase() + p2;
595
- }
596
- );
597
- };
598
-
599
- /* Creating a function that will check if an object has a property. */
600
- const hasOwnProperty = (({hasOwnProperty}) => (obj, prop) => hasOwnProperty.call(obj, prop))(Object.prototype);
601
-
602
- /**
603
- * Determine if a value is a RegExp object
604
- *
605
- * @param {*} val The value to test
606
- *
607
- * @returns {boolean} True if value is a RegExp object, otherwise false
608
- */
609
- const isRegExp = kindOfTest('RegExp');
610
-
611
- const reduceDescriptors = (obj, reducer) => {
612
- const descriptors = Object.getOwnPropertyDescriptors(obj);
613
- const reducedDescriptors = {};
614
-
615
- forEach(descriptors, (descriptor, name) => {
616
- let ret;
617
- if ((ret = reducer(descriptor, name, obj)) !== false) {
618
- reducedDescriptors[name] = ret || descriptor;
619
- }
620
- });
621
-
622
- Object.defineProperties(obj, reducedDescriptors);
623
- };
624
-
625
- /**
626
- * Makes all methods read-only
627
- * @param {Object} obj
628
- */
629
-
630
- const freezeMethods = (obj) => {
631
- reduceDescriptors(obj, (descriptor, name) => {
632
- // skip restricted props in strict mode
633
- if (isFunction(obj) && ['arguments', 'caller', 'callee'].indexOf(name) !== -1) {
634
- return false;
635
- }
636
-
637
- const value = obj[name];
638
-
639
- if (!isFunction(value)) return;
640
-
641
- descriptor.enumerable = false;
642
-
643
- if ('writable' in descriptor) {
644
- descriptor.writable = false;
645
- return;
646
- }
647
-
648
- if (!descriptor.set) {
649
- descriptor.set = () => {
650
- throw Error('Can not rewrite read-only method \'' + name + '\'');
651
- };
652
- }
653
- });
654
- };
655
-
656
- const toObjectSet = (arrayOrString, delimiter) => {
657
- const obj = {};
658
-
659
- const define = (arr) => {
660
- arr.forEach(value => {
661
- obj[value] = true;
662
- });
663
- };
664
-
665
- isArray(arrayOrString) ? define(arrayOrString) : define(String(arrayOrString).split(delimiter));
666
-
667
- return obj;
668
- };
669
-
670
- const noop = () => {};
671
-
672
- const toFiniteNumber = (value, defaultValue) => {
673
- return value != null && Number.isFinite(value = +value) ? value : defaultValue;
674
- };
675
-
676
- /**
677
- * If the thing is a FormData object, return true, otherwise return false.
678
- *
679
- * @param {unknown} thing - The thing to check.
680
- *
681
- * @returns {boolean}
682
- */
683
- function isSpecCompliantForm(thing) {
684
- return !!(thing && isFunction(thing.append) && thing[Symbol.toStringTag] === 'FormData' && thing[Symbol.iterator]);
685
- }
686
-
687
- const toJSONObject = (obj) => {
688
- const stack = new Array(10);
689
-
690
- const visit = (source, i) => {
691
-
692
- if (isObject(source)) {
693
- if (stack.indexOf(source) >= 0) {
694
- return;
695
- }
696
-
697
- if(!('toJSON' in source)) {
698
- stack[i] = source;
699
- const target = isArray(source) ? [] : {};
700
-
701
- forEach(source, (value, key) => {
702
- const reducedValue = visit(value, i + 1);
703
- !isUndefined(reducedValue) && (target[key] = reducedValue);
704
- });
705
-
706
- stack[i] = undefined;
707
-
708
- return target;
709
- }
710
- }
711
-
712
- return source;
713
- };
714
-
715
- return visit(obj, 0);
716
- };
717
-
718
- const isAsyncFn = kindOfTest('AsyncFunction');
719
-
720
- const isThenable = (thing) =>
721
- thing && (isObject(thing) || isFunction(thing)) && isFunction(thing.then) && isFunction(thing.catch);
722
-
723
- // original code
724
- // https://github.com/DigitalBrainJS/AxiosPromise/blob/16deab13710ec09779922131f3fa5954320f83ab/lib/utils.js#L11-L34
725
-
726
- const _setImmediate = ((setImmediateSupported, postMessageSupported) => {
727
- if (setImmediateSupported) {
728
- return setImmediate;
729
- }
730
-
731
- return postMessageSupported ? ((token, callbacks) => {
732
- _global.addEventListener("message", ({source, data}) => {
733
- if (source === _global && data === token) {
734
- callbacks.length && callbacks.shift()();
735
- }
736
- }, false);
737
-
738
- return (cb) => {
739
- callbacks.push(cb);
740
- _global.postMessage(token, "*");
741
- }
742
- })(`axios@${Math.random()}`, []) : (cb) => setTimeout(cb);
743
- })(
744
- typeof setImmediate === 'function',
745
- isFunction(_global.postMessage)
746
- );
747
-
748
- const asap = typeof queueMicrotask !== 'undefined' ?
749
- queueMicrotask.bind(_global) : ( typeof process !== 'undefined' && process.nextTick || _setImmediate);
750
-
751
- // *********************
752
-
753
- var utils$1 = {
754
- isArray,
755
- isArrayBuffer,
756
- isBuffer,
757
- isFormData,
758
- isArrayBufferView,
759
- isString,
760
- isNumber,
761
- isBoolean,
762
- isObject,
763
- isPlainObject,
764
- isReadableStream,
765
- isRequest,
766
- isResponse,
767
- isHeaders,
768
- isUndefined,
769
- isDate,
770
- isFile,
771
- isBlob,
772
- isRegExp,
773
- isFunction,
774
- isStream,
775
- isURLSearchParams,
776
- isTypedArray,
777
- isFileList,
778
- forEach,
779
- merge,
780
- extend,
781
- trim,
782
- stripBOM,
783
- inherits,
784
- toFlatObject,
785
- kindOf,
786
- kindOfTest,
787
- endsWith,
788
- toArray,
789
- forEachEntry,
790
- matchAll,
791
- isHTMLForm,
792
- hasOwnProperty,
793
- hasOwnProp: hasOwnProperty, // an alias to avoid ESLint no-prototype-builtins detection
794
- reduceDescriptors,
795
- freezeMethods,
796
- toObjectSet,
797
- toCamelCase,
798
- noop,
799
- toFiniteNumber,
800
- findKey,
801
- global: _global,
802
- isContextDefined,
803
- isSpecCompliantForm,
804
- toJSONObject,
805
- isAsyncFn,
806
- isThenable,
807
- setImmediate: _setImmediate,
808
- asap
809
- };
810
-
811
- /**
812
- * Create an Error with the specified message, config, error code, request and response.
813
- *
814
- * @param {string} message The error message.
815
- * @param {string} [code] The error code (for example, 'ECONNABORTED').
816
- * @param {Object} [config] The config.
817
- * @param {Object} [request] The request.
818
- * @param {Object} [response] The response.
819
- *
820
- * @returns {Error} The created error.
821
- */
822
- function AxiosError$1(message, code, config, request, response) {
823
- Error.call(this);
824
-
825
- if (Error.captureStackTrace) {
826
- Error.captureStackTrace(this, this.constructor);
827
- } else {
828
- this.stack = (new Error()).stack;
829
- }
830
-
831
- this.message = message;
832
- this.name = 'AxiosError';
833
- code && (this.code = code);
834
- config && (this.config = config);
835
- request && (this.request = request);
836
- if (response) {
837
- this.response = response;
838
- this.status = response.status ? response.status : null;
839
- }
840
- }
841
-
842
- utils$1.inherits(AxiosError$1, Error, {
843
- toJSON: function toJSON() {
844
- return {
845
- // Standard
846
- message: this.message,
847
- name: this.name,
848
- // Microsoft
849
- description: this.description,
850
- number: this.number,
851
- // Mozilla
852
- fileName: this.fileName,
853
- lineNumber: this.lineNumber,
854
- columnNumber: this.columnNumber,
855
- stack: this.stack,
856
- // Axios
857
- config: utils$1.toJSONObject(this.config),
858
- code: this.code,
859
- status: this.status
860
- };
861
- }
862
- });
863
-
864
- const prototype$1 = AxiosError$1.prototype;
865
- const descriptors = {};
866
-
867
- [
868
- 'ERR_BAD_OPTION_VALUE',
869
- 'ERR_BAD_OPTION',
870
- 'ECONNABORTED',
871
- 'ETIMEDOUT',
872
- 'ERR_NETWORK',
873
- 'ERR_FR_TOO_MANY_REDIRECTS',
874
- 'ERR_DEPRECATED',
875
- 'ERR_BAD_RESPONSE',
876
- 'ERR_BAD_REQUEST',
877
- 'ERR_CANCELED',
878
- 'ERR_NOT_SUPPORT',
879
- 'ERR_INVALID_URL'
880
- // eslint-disable-next-line func-names
881
- ].forEach(code => {
882
- descriptors[code] = {value: code};
883
- });
884
-
885
- Object.defineProperties(AxiosError$1, descriptors);
886
- Object.defineProperty(prototype$1, 'isAxiosError', {value: true});
887
-
888
- // eslint-disable-next-line func-names
889
- AxiosError$1.from = (error, code, config, request, response, customProps) => {
890
- const axiosError = Object.create(prototype$1);
891
-
892
- utils$1.toFlatObject(error, axiosError, function filter(obj) {
893
- return obj !== Error.prototype;
894
- }, prop => {
895
- return prop !== 'isAxiosError';
896
- });
897
-
898
- AxiosError$1.call(axiosError, error.message, code, config, request, response);
899
-
900
- axiosError.cause = error;
901
-
902
- axiosError.name = error.name;
903
-
904
- customProps && Object.assign(axiosError, customProps);
905
-
906
- return axiosError;
907
- };
908
-
909
- // eslint-disable-next-line strict
910
- var httpAdapter = null;
911
-
912
- /**
913
- * Determines if the given thing is a array or js object.
914
- *
915
- * @param {string} thing - The object or array to be visited.
916
- *
917
- * @returns {boolean}
918
- */
919
- function isVisitable(thing) {
920
- return utils$1.isPlainObject(thing) || utils$1.isArray(thing);
921
- }
922
-
923
- /**
924
- * It removes the brackets from the end of a string
925
- *
926
- * @param {string} key - The key of the parameter.
927
- *
928
- * @returns {string} the key without the brackets.
929
- */
930
- function removeBrackets(key) {
931
- return utils$1.endsWith(key, '[]') ? key.slice(0, -2) : key;
932
- }
933
-
934
- /**
935
- * It takes a path, a key, and a boolean, and returns a string
936
- *
937
- * @param {string} path - The path to the current key.
938
- * @param {string} key - The key of the current object being iterated over.
939
- * @param {string} dots - If true, the key will be rendered with dots instead of brackets.
940
- *
941
- * @returns {string} The path to the current key.
942
- */
943
- function renderKey(path, key, dots) {
944
- if (!path) return key;
945
- return path.concat(key).map(function each(token, i) {
946
- // eslint-disable-next-line no-param-reassign
947
- token = removeBrackets(token);
948
- return !dots && i ? '[' + token + ']' : token;
949
- }).join(dots ? '.' : '');
950
- }
951
-
952
- /**
953
- * If the array is an array and none of its elements are visitable, then it's a flat array.
954
- *
955
- * @param {Array<any>} arr - The array to check
956
- *
957
- * @returns {boolean}
958
- */
959
- function isFlatArray(arr) {
960
- return utils$1.isArray(arr) && !arr.some(isVisitable);
961
- }
962
-
963
- const predicates = utils$1.toFlatObject(utils$1, {}, null, function filter(prop) {
964
- return /^is[A-Z]/.test(prop);
965
- });
966
-
967
- /**
968
- * Convert a data object to FormData
969
- *
970
- * @param {Object} obj
971
- * @param {?Object} [formData]
972
- * @param {?Object} [options]
973
- * @param {Function} [options.visitor]
974
- * @param {Boolean} [options.metaTokens = true]
975
- * @param {Boolean} [options.dots = false]
976
- * @param {?Boolean} [options.indexes = false]
977
- *
978
- * @returns {Object}
979
- **/
980
-
981
- /**
982
- * It converts an object into a FormData object
983
- *
984
- * @param {Object<any, any>} obj - The object to convert to form data.
985
- * @param {string} formData - The FormData object to append to.
986
- * @param {Object<string, any>} options
987
- *
988
- * @returns
989
- */
990
- function toFormData$1(obj, formData, options) {
991
- if (!utils$1.isObject(obj)) {
992
- throw new TypeError('target must be an object');
993
- }
994
-
995
- // eslint-disable-next-line no-param-reassign
996
- formData = formData || new (FormData)();
997
-
998
- // eslint-disable-next-line no-param-reassign
999
- options = utils$1.toFlatObject(options, {
1000
- metaTokens: true,
1001
- dots: false,
1002
- indexes: false
1003
- }, false, function defined(option, source) {
1004
- // eslint-disable-next-line no-eq-null,eqeqeq
1005
- return !utils$1.isUndefined(source[option]);
1006
- });
1007
-
1008
- const metaTokens = options.metaTokens;
1009
- // eslint-disable-next-line no-use-before-define
1010
- const visitor = options.visitor || defaultVisitor;
1011
- const dots = options.dots;
1012
- const indexes = options.indexes;
1013
- const _Blob = options.Blob || typeof Blob !== 'undefined' && Blob;
1014
- const useBlob = _Blob && utils$1.isSpecCompliantForm(formData);
1015
-
1016
- if (!utils$1.isFunction(visitor)) {
1017
- throw new TypeError('visitor must be a function');
1018
- }
1019
-
1020
- function convertValue(value) {
1021
- if (value === null) return '';
1022
-
1023
- if (utils$1.isDate(value)) {
1024
- return value.toISOString();
1025
- }
1026
-
1027
- if (!useBlob && utils$1.isBlob(value)) {
1028
- throw new AxiosError$1('Blob is not supported. Use a Buffer instead.');
1029
- }
1030
-
1031
- if (utils$1.isArrayBuffer(value) || utils$1.isTypedArray(value)) {
1032
- return useBlob && typeof Blob === 'function' ? new Blob([value]) : Buffer.from(value);
1033
- }
1034
-
1035
- return value;
1036
- }
1037
-
1038
- /**
1039
- * Default visitor.
1040
- *
1041
- * @param {*} value
1042
- * @param {String|Number} key
1043
- * @param {Array<String|Number>} path
1044
- * @this {FormData}
1045
- *
1046
- * @returns {boolean} return true to visit the each prop of the value recursively
1047
- */
1048
- function defaultVisitor(value, key, path) {
1049
- let arr = value;
1050
-
1051
- if (value && !path && typeof value === 'object') {
1052
- if (utils$1.endsWith(key, '{}')) {
1053
- // eslint-disable-next-line no-param-reassign
1054
- key = metaTokens ? key : key.slice(0, -2);
1055
- // eslint-disable-next-line no-param-reassign
1056
- value = JSON.stringify(value);
1057
- } else if (
1058
- (utils$1.isArray(value) && isFlatArray(value)) ||
1059
- ((utils$1.isFileList(value) || utils$1.endsWith(key, '[]')) && (arr = utils$1.toArray(value))
1060
- )) {
1061
- // eslint-disable-next-line no-param-reassign
1062
- key = removeBrackets(key);
1063
-
1064
- arr.forEach(function each(el, index) {
1065
- !(utils$1.isUndefined(el) || el === null) && formData.append(
1066
- // eslint-disable-next-line no-nested-ternary
1067
- indexes === true ? renderKey([key], index, dots) : (indexes === null ? key : key + '[]'),
1068
- convertValue(el)
1069
- );
1070
- });
1071
- return false;
1072
- }
1073
- }
1074
-
1075
- if (isVisitable(value)) {
1076
- return true;
1077
- }
1078
-
1079
- formData.append(renderKey(path, key, dots), convertValue(value));
1080
-
1081
- return false;
1082
- }
1083
-
1084
- const stack = [];
1085
-
1086
- const exposedHelpers = Object.assign(predicates, {
1087
- defaultVisitor,
1088
- convertValue,
1089
- isVisitable
1090
- });
1091
-
1092
- function build(value, path) {
1093
- if (utils$1.isUndefined(value)) return;
1094
-
1095
- if (stack.indexOf(value) !== -1) {
1096
- throw Error('Circular reference detected in ' + path.join('.'));
1097
- }
1098
-
1099
- stack.push(value);
1100
-
1101
- utils$1.forEach(value, function each(el, key) {
1102
- const result = !(utils$1.isUndefined(el) || el === null) && visitor.call(
1103
- formData, el, utils$1.isString(key) ? key.trim() : key, path, exposedHelpers
1104
- );
1105
-
1106
- if (result === true) {
1107
- build(el, path ? path.concat(key) : [key]);
1108
- }
1109
- });
1110
-
1111
- stack.pop();
1112
- }
1113
-
1114
- if (!utils$1.isObject(obj)) {
1115
- throw new TypeError('data must be an object');
1116
- }
1117
-
1118
- build(obj);
1119
-
1120
- return formData;
1121
- }
1122
-
1123
- /**
1124
- * It encodes a string by replacing all characters that are not in the unreserved set with
1125
- * their percent-encoded equivalents
1126
- *
1127
- * @param {string} str - The string to encode.
1128
- *
1129
- * @returns {string} The encoded string.
1130
- */
1131
- function encode$1(str) {
1132
- const charMap = {
1133
- '!': '%21',
1134
- "'": '%27',
1135
- '(': '%28',
1136
- ')': '%29',
1137
- '~': '%7E',
1138
- '%20': '+',
1139
- '%00': '\x00'
1140
- };
1141
- return encodeURIComponent(str).replace(/[!'()~]|%20|%00/g, function replacer(match) {
1142
- return charMap[match];
1143
- });
1144
- }
1145
-
1146
- /**
1147
- * It takes a params object and converts it to a FormData object
1148
- *
1149
- * @param {Object<string, any>} params - The parameters to be converted to a FormData object.
1150
- * @param {Object<string, any>} options - The options object passed to the Axios constructor.
1151
- *
1152
- * @returns {void}
1153
- */
1154
- function AxiosURLSearchParams(params, options) {
1155
- this._pairs = [];
1156
-
1157
- params && toFormData$1(params, this, options);
1158
- }
1159
-
1160
- const prototype = AxiosURLSearchParams.prototype;
1161
-
1162
- prototype.append = function append(name, value) {
1163
- this._pairs.push([name, value]);
1164
- };
1165
-
1166
- prototype.toString = function toString(encoder) {
1167
- const _encode = encoder ? function(value) {
1168
- return encoder.call(this, value, encode$1);
1169
- } : encode$1;
1170
-
1171
- return this._pairs.map(function each(pair) {
1172
- return _encode(pair[0]) + '=' + _encode(pair[1]);
1173
- }, '').join('&');
1174
- };
1175
-
1176
- /**
1177
- * It replaces all instances of the characters `:`, `$`, `,`, `+`, `[`, and `]` with their
1178
- * URI encoded counterparts
1179
- *
1180
- * @param {string} val The value to be encoded.
1181
- *
1182
- * @returns {string} The encoded value.
1183
- */
1184
- function encode(val) {
1185
- return encodeURIComponent(val).
1186
- replace(/%3A/gi, ':').
1187
- replace(/%24/g, '$').
1188
- replace(/%2C/gi, ',').
1189
- replace(/%20/g, '+').
1190
- replace(/%5B/gi, '[').
1191
- replace(/%5D/gi, ']');
1192
- }
1193
-
1194
- /**
1195
- * Build a URL by appending params to the end
1196
- *
1197
- * @param {string} url The base of the url (e.g., http://www.google.com)
1198
- * @param {object} [params] The params to be appended
1199
- * @param {?(object|Function)} options
1200
- *
1201
- * @returns {string} The formatted url
1202
- */
1203
- function buildURL(url, params, options) {
1204
- /*eslint no-param-reassign:0*/
1205
- if (!params) {
1206
- return url;
1207
- }
1208
-
1209
- const _encode = options && options.encode || encode;
1210
-
1211
- if (utils$1.isFunction(options)) {
1212
- options = {
1213
- serialize: options
1214
- };
1215
- }
1216
-
1217
- const serializeFn = options && options.serialize;
1218
-
1219
- let serializedParams;
1220
-
1221
- if (serializeFn) {
1222
- serializedParams = serializeFn(params, options);
1223
- } else {
1224
- serializedParams = utils$1.isURLSearchParams(params) ?
1225
- params.toString() :
1226
- new AxiosURLSearchParams(params, options).toString(_encode);
1227
- }
1228
-
1229
- if (serializedParams) {
1230
- const hashmarkIndex = url.indexOf("#");
1231
-
1232
- if (hashmarkIndex !== -1) {
1233
- url = url.slice(0, hashmarkIndex);
1234
- }
1235
- url += (url.indexOf('?') === -1 ? '?' : '&') + serializedParams;
1236
- }
1237
-
1238
- return url;
1239
- }
1240
-
1241
- class InterceptorManager {
1242
- constructor() {
1243
- this.handlers = [];
1244
- }
1245
-
1246
- /**
1247
- * Add a new interceptor to the stack
1248
- *
1249
- * @param {Function} fulfilled The function to handle `then` for a `Promise`
1250
- * @param {Function} rejected The function to handle `reject` for a `Promise`
1251
- *
1252
- * @return {Number} An ID used to remove interceptor later
1253
- */
1254
- use(fulfilled, rejected, options) {
1255
- this.handlers.push({
1256
- fulfilled,
1257
- rejected,
1258
- synchronous: options ? options.synchronous : false,
1259
- runWhen: options ? options.runWhen : null
1260
- });
1261
- return this.handlers.length - 1;
1262
- }
1263
-
1264
- /**
1265
- * Remove an interceptor from the stack
1266
- *
1267
- * @param {Number} id The ID that was returned by `use`
1268
- *
1269
- * @returns {Boolean} `true` if the interceptor was removed, `false` otherwise
1270
- */
1271
- eject(id) {
1272
- if (this.handlers[id]) {
1273
- this.handlers[id] = null;
1274
- }
1275
- }
1276
-
1277
- /**
1278
- * Clear all interceptors from the stack
1279
- *
1280
- * @returns {void}
1281
- */
1282
- clear() {
1283
- if (this.handlers) {
1284
- this.handlers = [];
1285
- }
1286
- }
1287
-
1288
- /**
1289
- * Iterate over all the registered interceptors
1290
- *
1291
- * This method is particularly useful for skipping over any
1292
- * interceptors that may have become `null` calling `eject`.
1293
- *
1294
- * @param {Function} fn The function to call for each interceptor
1295
- *
1296
- * @returns {void}
1297
- */
1298
- forEach(fn) {
1299
- utils$1.forEach(this.handlers, function forEachHandler(h) {
1300
- if (h !== null) {
1301
- fn(h);
1302
- }
1303
- });
1304
- }
1305
- }
1306
-
1307
- var transitionalDefaults = {
1308
- silentJSONParsing: true,
1309
- forcedJSONParsing: true,
1310
- clarifyTimeoutError: false
1311
- };
1312
-
1313
- var URLSearchParams$1 = typeof URLSearchParams !== 'undefined' ? URLSearchParams : AxiosURLSearchParams;
1314
-
1315
- var FormData$1 = typeof FormData !== 'undefined' ? FormData : null;
1316
-
1317
- var Blob$1 = typeof Blob !== 'undefined' ? Blob : null;
1318
-
1319
- var platform$1 = {
1320
- isBrowser: true,
1321
- classes: {
1322
- URLSearchParams: URLSearchParams$1,
1323
- FormData: FormData$1,
1324
- Blob: Blob$1
1325
- },
1326
- protocols: ['http', 'https', 'file', 'blob', 'url', 'data']
1327
- };
1328
-
1329
- const hasBrowserEnv = typeof window !== 'undefined' && typeof document !== 'undefined';
1330
-
1331
- const _navigator = typeof navigator === 'object' && navigator || undefined;
1332
-
1333
- /**
1334
- * Determine if we're running in a standard browser environment
1335
- *
1336
- * This allows axios to run in a web worker, and react-native.
1337
- * Both environments support XMLHttpRequest, but not fully standard globals.
1338
- *
1339
- * web workers:
1340
- * typeof window -> undefined
1341
- * typeof document -> undefined
1342
- *
1343
- * react-native:
1344
- * navigator.product -> 'ReactNative'
1345
- * nativescript
1346
- * navigator.product -> 'NativeScript' or 'NS'
1347
- *
1348
- * @returns {boolean}
1349
- */
1350
- const hasStandardBrowserEnv = hasBrowserEnv &&
1351
- (!_navigator || ['ReactNative', 'NativeScript', 'NS'].indexOf(_navigator.product) < 0);
1352
-
1353
- /**
1354
- * Determine if we're running in a standard browser webWorker environment
1355
- *
1356
- * Although the `isStandardBrowserEnv` method indicates that
1357
- * `allows axios to run in a web worker`, the WebWorker will still be
1358
- * filtered out due to its judgment standard
1359
- * `typeof window !== 'undefined' && typeof document !== 'undefined'`.
1360
- * This leads to a problem when axios post `FormData` in webWorker
1361
- */
1362
- const hasStandardBrowserWebWorkerEnv = (() => {
1363
- return (
1364
- typeof WorkerGlobalScope !== 'undefined' &&
1365
- // eslint-disable-next-line no-undef
1366
- self instanceof WorkerGlobalScope &&
1367
- typeof self.importScripts === 'function'
1368
- );
1369
- })();
1370
-
1371
- const origin = hasBrowserEnv && window.location.href || 'http://localhost';
1372
-
1373
- var utils = /*#__PURE__*/Object.freeze({
1374
- __proto__: null,
1375
- hasBrowserEnv: hasBrowserEnv,
1376
- hasStandardBrowserEnv: hasStandardBrowserEnv,
1377
- hasStandardBrowserWebWorkerEnv: hasStandardBrowserWebWorkerEnv,
1378
- navigator: _navigator,
1379
- origin: origin
1380
- });
1381
-
1382
- var platform = {
1383
- ...utils,
1384
- ...platform$1
1385
- };
1386
-
1387
- function toURLEncodedForm(data, options) {
1388
- return toFormData$1(data, new platform.classes.URLSearchParams(), Object.assign({
1389
- visitor: function(value, key, path, helpers) {
1390
- if (platform.isNode && utils$1.isBuffer(value)) {
1391
- this.append(key, value.toString('base64'));
1392
- return false;
1393
- }
1394
-
1395
- return helpers.defaultVisitor.apply(this, arguments);
1396
- }
1397
- }, options));
1398
- }
1399
-
1400
- /**
1401
- * It takes a string like `foo[x][y][z]` and returns an array like `['foo', 'x', 'y', 'z']
1402
- *
1403
- * @param {string} name - The name of the property to get.
1404
- *
1405
- * @returns An array of strings.
1406
- */
1407
- function parsePropPath(name) {
1408
- // foo[x][y][z]
1409
- // foo.x.y.z
1410
- // foo-x-y-z
1411
- // foo x y z
1412
- return utils$1.matchAll(/\w+|\[(\w*)]/g, name).map(match => {
1413
- return match[0] === '[]' ? '' : match[1] || match[0];
1414
- });
1415
- }
1416
-
1417
- /**
1418
- * Convert an array to an object.
1419
- *
1420
- * @param {Array<any>} arr - The array to convert to an object.
1421
- *
1422
- * @returns An object with the same keys and values as the array.
1423
- */
1424
- function arrayToObject(arr) {
1425
- const obj = {};
1426
- const keys = Object.keys(arr);
1427
- let i;
1428
- const len = keys.length;
1429
- let key;
1430
- for (i = 0; i < len; i++) {
1431
- key = keys[i];
1432
- obj[key] = arr[key];
1433
- }
1434
- return obj;
1435
- }
1436
-
1437
- /**
1438
- * It takes a FormData object and returns a JavaScript object
1439
- *
1440
- * @param {string} formData The FormData object to convert to JSON.
1441
- *
1442
- * @returns {Object<string, any> | null} The converted object.
1443
- */
1444
- function formDataToJSON(formData) {
1445
- function buildPath(path, value, target, index) {
1446
- let name = path[index++];
1447
-
1448
- if (name === '__proto__') return true;
1449
-
1450
- const isNumericKey = Number.isFinite(+name);
1451
- const isLast = index >= path.length;
1452
- name = !name && utils$1.isArray(target) ? target.length : name;
1453
-
1454
- if (isLast) {
1455
- if (utils$1.hasOwnProp(target, name)) {
1456
- target[name] = [target[name], value];
1457
- } else {
1458
- target[name] = value;
1459
- }
1460
-
1461
- return !isNumericKey;
1462
- }
1463
-
1464
- if (!target[name] || !utils$1.isObject(target[name])) {
1465
- target[name] = [];
1466
- }
1467
-
1468
- const result = buildPath(path, value, target[name], index);
1469
-
1470
- if (result && utils$1.isArray(target[name])) {
1471
- target[name] = arrayToObject(target[name]);
1472
- }
1473
-
1474
- return !isNumericKey;
1475
- }
1476
-
1477
- if (utils$1.isFormData(formData) && utils$1.isFunction(formData.entries)) {
1478
- const obj = {};
1479
-
1480
- utils$1.forEachEntry(formData, (name, value) => {
1481
- buildPath(parsePropPath(name), value, obj, 0);
1482
- });
1483
-
1484
- return obj;
1485
- }
1486
-
1487
- return null;
1488
- }
1489
-
1490
- /**
1491
- * It takes a string, tries to parse it, and if it fails, it returns the stringified version
1492
- * of the input
1493
- *
1494
- * @param {any} rawValue - The value to be stringified.
1495
- * @param {Function} parser - A function that parses a string into a JavaScript object.
1496
- * @param {Function} encoder - A function that takes a value and returns a string.
1497
- *
1498
- * @returns {string} A stringified version of the rawValue.
1499
- */
1500
- function stringifySafely(rawValue, parser, encoder) {
1501
- if (utils$1.isString(rawValue)) {
1502
- try {
1503
- (parser || JSON.parse)(rawValue);
1504
- return utils$1.trim(rawValue);
1505
- } catch (e) {
1506
- if (e.name !== 'SyntaxError') {
1507
- throw e;
1508
- }
1509
- }
1510
- }
1511
-
1512
- return (encoder || JSON.stringify)(rawValue);
1513
- }
1514
-
1515
- const defaults = {
1516
-
1517
- transitional: transitionalDefaults,
1518
-
1519
- adapter: ['xhr', 'http', 'fetch'],
1520
-
1521
- transformRequest: [function transformRequest(data, headers) {
1522
- const contentType = headers.getContentType() || '';
1523
- const hasJSONContentType = contentType.indexOf('application/json') > -1;
1524
- const isObjectPayload = utils$1.isObject(data);
1525
-
1526
- if (isObjectPayload && utils$1.isHTMLForm(data)) {
1527
- data = new FormData(data);
1528
- }
1529
-
1530
- const isFormData = utils$1.isFormData(data);
1531
-
1532
- if (isFormData) {
1533
- return hasJSONContentType ? JSON.stringify(formDataToJSON(data)) : data;
1534
- }
1535
-
1536
- if (utils$1.isArrayBuffer(data) ||
1537
- utils$1.isBuffer(data) ||
1538
- utils$1.isStream(data) ||
1539
- utils$1.isFile(data) ||
1540
- utils$1.isBlob(data) ||
1541
- utils$1.isReadableStream(data)
1542
- ) {
1543
- return data;
1544
- }
1545
- if (utils$1.isArrayBufferView(data)) {
1546
- return data.buffer;
1547
- }
1548
- if (utils$1.isURLSearchParams(data)) {
1549
- headers.setContentType('application/x-www-form-urlencoded;charset=utf-8', false);
1550
- return data.toString();
1551
- }
1552
-
1553
- let isFileList;
1554
-
1555
- if (isObjectPayload) {
1556
- if (contentType.indexOf('application/x-www-form-urlencoded') > -1) {
1557
- return toURLEncodedForm(data, this.formSerializer).toString();
1558
- }
1559
-
1560
- if ((isFileList = utils$1.isFileList(data)) || contentType.indexOf('multipart/form-data') > -1) {
1561
- const _FormData = this.env && this.env.FormData;
1562
-
1563
- return toFormData$1(
1564
- isFileList ? {'files[]': data} : data,
1565
- _FormData && new _FormData(),
1566
- this.formSerializer
1567
- );
1568
- }
1569
- }
1570
-
1571
- if (isObjectPayload || hasJSONContentType ) {
1572
- headers.setContentType('application/json', false);
1573
- return stringifySafely(data);
1574
- }
1575
-
1576
- return data;
1577
- }],
1578
-
1579
- transformResponse: [function transformResponse(data) {
1580
- const transitional = this.transitional || defaults.transitional;
1581
- const forcedJSONParsing = transitional && transitional.forcedJSONParsing;
1582
- const JSONRequested = this.responseType === 'json';
1583
-
1584
- if (utils$1.isResponse(data) || utils$1.isReadableStream(data)) {
1585
- return data;
1586
- }
1587
-
1588
- if (data && utils$1.isString(data) && ((forcedJSONParsing && !this.responseType) || JSONRequested)) {
1589
- const silentJSONParsing = transitional && transitional.silentJSONParsing;
1590
- const strictJSONParsing = !silentJSONParsing && JSONRequested;
1591
-
1592
- try {
1593
- return JSON.parse(data);
1594
- } catch (e) {
1595
- if (strictJSONParsing) {
1596
- if (e.name === 'SyntaxError') {
1597
- throw AxiosError$1.from(e, AxiosError$1.ERR_BAD_RESPONSE, this, null, this.response);
1598
- }
1599
- throw e;
1600
- }
1601
- }
1602
- }
1603
-
1604
- return data;
1605
- }],
1606
-
1607
- /**
1608
- * A timeout in milliseconds to abort a request. If set to 0 (default) a
1609
- * timeout is not created.
1610
- */
1611
- timeout: 0,
1612
-
1613
- xsrfCookieName: 'XSRF-TOKEN',
1614
- xsrfHeaderName: 'X-XSRF-TOKEN',
1615
-
1616
- maxContentLength: -1,
1617
- maxBodyLength: -1,
1618
-
1619
- env: {
1620
- FormData: platform.classes.FormData,
1621
- Blob: platform.classes.Blob
1622
- },
1623
-
1624
- validateStatus: function validateStatus(status) {
1625
- return status >= 200 && status < 300;
1626
- },
1627
-
1628
- headers: {
1629
- common: {
1630
- 'Accept': 'application/json, text/plain, */*',
1631
- 'Content-Type': undefined
1632
- }
1633
- }
1634
- };
1635
-
1636
- utils$1.forEach(['delete', 'get', 'head', 'post', 'put', 'patch'], (method) => {
1637
- defaults.headers[method] = {};
1638
- });
1639
-
1640
- // RawAxiosHeaders whose duplicates are ignored by node
1641
- // c.f. https://nodejs.org/api/http.html#http_message_headers
1642
- const ignoreDuplicateOf = utils$1.toObjectSet([
1643
- 'age', 'authorization', 'content-length', 'content-type', 'etag',
1644
- 'expires', 'from', 'host', 'if-modified-since', 'if-unmodified-since',
1645
- 'last-modified', 'location', 'max-forwards', 'proxy-authorization',
1646
- 'referer', 'retry-after', 'user-agent'
1647
- ]);
1648
-
1649
- /**
1650
- * Parse headers into an object
1651
- *
1652
- * ```
1653
- * Date: Wed, 27 Aug 2014 08:58:49 GMT
1654
- * Content-Type: application/json
1655
- * Connection: keep-alive
1656
- * Transfer-Encoding: chunked
1657
- * ```
1658
- *
1659
- * @param {String} rawHeaders Headers needing to be parsed
1660
- *
1661
- * @returns {Object} Headers parsed into an object
1662
- */
1663
- var parseHeaders = rawHeaders => {
1664
- const parsed = {};
1665
- let key;
1666
- let val;
1667
- let i;
1668
-
1669
- rawHeaders && rawHeaders.split('\n').forEach(function parser(line) {
1670
- i = line.indexOf(':');
1671
- key = line.substring(0, i).trim().toLowerCase();
1672
- val = line.substring(i + 1).trim();
1673
-
1674
- if (!key || (parsed[key] && ignoreDuplicateOf[key])) {
1675
- return;
1676
- }
1677
-
1678
- if (key === 'set-cookie') {
1679
- if (parsed[key]) {
1680
- parsed[key].push(val);
1681
- } else {
1682
- parsed[key] = [val];
1683
- }
1684
- } else {
1685
- parsed[key] = parsed[key] ? parsed[key] + ', ' + val : val;
1686
- }
1687
- });
1688
-
1689
- return parsed;
1690
- };
1691
-
1692
- const $internals = Symbol('internals');
1693
-
1694
- function normalizeHeader(header) {
1695
- return header && String(header).trim().toLowerCase();
1696
- }
1697
-
1698
- function normalizeValue(value) {
1699
- if (value === false || value == null) {
1700
- return value;
1701
- }
1702
-
1703
- return utils$1.isArray(value) ? value.map(normalizeValue) : String(value);
1704
- }
1705
-
1706
- function parseTokens(str) {
1707
- const tokens = Object.create(null);
1708
- const tokensRE = /([^\s,;=]+)\s*(?:=\s*([^,;]+))?/g;
1709
- let match;
1710
-
1711
- while ((match = tokensRE.exec(str))) {
1712
- tokens[match[1]] = match[2];
1713
- }
1714
-
1715
- return tokens;
1716
- }
1717
-
1718
- const isValidHeaderName = (str) => /^[-_a-zA-Z0-9^`|~,!#$%&'*+.]+$/.test(str.trim());
1719
-
1720
- function matchHeaderValue(context, value, header, filter, isHeaderNameFilter) {
1721
- if (utils$1.isFunction(filter)) {
1722
- return filter.call(this, value, header);
1723
- }
1724
-
1725
- if (isHeaderNameFilter) {
1726
- value = header;
1727
- }
1728
-
1729
- if (!utils$1.isString(value)) return;
1730
-
1731
- if (utils$1.isString(filter)) {
1732
- return value.indexOf(filter) !== -1;
1733
- }
1734
-
1735
- if (utils$1.isRegExp(filter)) {
1736
- return filter.test(value);
1737
- }
1738
- }
1739
-
1740
- function formatHeader(header) {
1741
- return header.trim()
1742
- .toLowerCase().replace(/([a-z\d])(\w*)/g, (w, char, str) => {
1743
- return char.toUpperCase() + str;
1744
- });
1745
- }
1746
-
1747
- function buildAccessors(obj, header) {
1748
- const accessorName = utils$1.toCamelCase(' ' + header);
1749
-
1750
- ['get', 'set', 'has'].forEach(methodName => {
1751
- Object.defineProperty(obj, methodName + accessorName, {
1752
- value: function(arg1, arg2, arg3) {
1753
- return this[methodName].call(this, header, arg1, arg2, arg3);
1754
- },
1755
- configurable: true
1756
- });
1757
- });
1758
- }
1759
-
1760
- let AxiosHeaders$1 = class AxiosHeaders {
1761
- constructor(headers) {
1762
- headers && this.set(headers);
1763
- }
1764
-
1765
- set(header, valueOrRewrite, rewrite) {
1766
- const self = this;
1767
-
1768
- function setHeader(_value, _header, _rewrite) {
1769
- const lHeader = normalizeHeader(_header);
1770
-
1771
- if (!lHeader) {
1772
- throw new Error('header name must be a non-empty string');
1773
- }
1774
-
1775
- const key = utils$1.findKey(self, lHeader);
1776
-
1777
- if(!key || self[key] === undefined || _rewrite === true || (_rewrite === undefined && self[key] !== false)) {
1778
- self[key || _header] = normalizeValue(_value);
1779
- }
1780
- }
1781
-
1782
- const setHeaders = (headers, _rewrite) =>
1783
- utils$1.forEach(headers, (_value, _header) => setHeader(_value, _header, _rewrite));
1784
-
1785
- if (utils$1.isPlainObject(header) || header instanceof this.constructor) {
1786
- setHeaders(header, valueOrRewrite);
1787
- } else if(utils$1.isString(header) && (header = header.trim()) && !isValidHeaderName(header)) {
1788
- setHeaders(parseHeaders(header), valueOrRewrite);
1789
- } else if (utils$1.isHeaders(header)) {
1790
- for (const [key, value] of header.entries()) {
1791
- setHeader(value, key, rewrite);
1792
- }
1793
- } else {
1794
- header != null && setHeader(valueOrRewrite, header, rewrite);
1795
- }
1796
-
1797
- return this;
1798
- }
1799
-
1800
- get(header, parser) {
1801
- header = normalizeHeader(header);
1802
-
1803
- if (header) {
1804
- const key = utils$1.findKey(this, header);
1805
-
1806
- if (key) {
1807
- const value = this[key];
1808
-
1809
- if (!parser) {
1810
- return value;
1811
- }
1812
-
1813
- if (parser === true) {
1814
- return parseTokens(value);
1815
- }
1816
-
1817
- if (utils$1.isFunction(parser)) {
1818
- return parser.call(this, value, key);
1819
- }
1820
-
1821
- if (utils$1.isRegExp(parser)) {
1822
- return parser.exec(value);
1823
- }
1824
-
1825
- throw new TypeError('parser must be boolean|regexp|function');
1826
- }
1827
- }
1828
- }
1829
-
1830
- has(header, matcher) {
1831
- header = normalizeHeader(header);
1832
-
1833
- if (header) {
1834
- const key = utils$1.findKey(this, header);
1835
-
1836
- return !!(key && this[key] !== undefined && (!matcher || matchHeaderValue(this, this[key], key, matcher)));
1837
- }
1838
-
1839
- return false;
1840
- }
1841
-
1842
- delete(header, matcher) {
1843
- const self = this;
1844
- let deleted = false;
1845
-
1846
- function deleteHeader(_header) {
1847
- _header = normalizeHeader(_header);
1848
-
1849
- if (_header) {
1850
- const key = utils$1.findKey(self, _header);
1851
-
1852
- if (key && (!matcher || matchHeaderValue(self, self[key], key, matcher))) {
1853
- delete self[key];
1854
-
1855
- deleted = true;
1856
- }
1857
- }
1858
- }
1859
-
1860
- if (utils$1.isArray(header)) {
1861
- header.forEach(deleteHeader);
1862
- } else {
1863
- deleteHeader(header);
1864
- }
1865
-
1866
- return deleted;
1867
- }
1868
-
1869
- clear(matcher) {
1870
- const keys = Object.keys(this);
1871
- let i = keys.length;
1872
- let deleted = false;
1873
-
1874
- while (i--) {
1875
- const key = keys[i];
1876
- if(!matcher || matchHeaderValue(this, this[key], key, matcher, true)) {
1877
- delete this[key];
1878
- deleted = true;
1879
- }
1880
- }
1881
-
1882
- return deleted;
1883
- }
1884
-
1885
- normalize(format) {
1886
- const self = this;
1887
- const headers = {};
1888
-
1889
- utils$1.forEach(this, (value, header) => {
1890
- const key = utils$1.findKey(headers, header);
1891
-
1892
- if (key) {
1893
- self[key] = normalizeValue(value);
1894
- delete self[header];
1895
- return;
1896
- }
1897
-
1898
- const normalized = format ? formatHeader(header) : String(header).trim();
1899
-
1900
- if (normalized !== header) {
1901
- delete self[header];
1902
- }
1903
-
1904
- self[normalized] = normalizeValue(value);
1905
-
1906
- headers[normalized] = true;
1907
- });
1908
-
1909
- return this;
1910
- }
1911
-
1912
- concat(...targets) {
1913
- return this.constructor.concat(this, ...targets);
1914
- }
1915
-
1916
- toJSON(asStrings) {
1917
- const obj = Object.create(null);
1918
-
1919
- utils$1.forEach(this, (value, header) => {
1920
- value != null && value !== false && (obj[header] = asStrings && utils$1.isArray(value) ? value.join(', ') : value);
1921
- });
1922
-
1923
- return obj;
1924
- }
1925
-
1926
- [Symbol.iterator]() {
1927
- return Object.entries(this.toJSON())[Symbol.iterator]();
1928
- }
1929
-
1930
- toString() {
1931
- return Object.entries(this.toJSON()).map(([header, value]) => header + ': ' + value).join('\n');
1932
- }
1933
-
1934
- get [Symbol.toStringTag]() {
1935
- return 'AxiosHeaders';
1936
- }
1937
-
1938
- static from(thing) {
1939
- return thing instanceof this ? thing : new this(thing);
1940
- }
1941
-
1942
- static concat(first, ...targets) {
1943
- const computed = new this(first);
1944
-
1945
- targets.forEach((target) => computed.set(target));
1946
-
1947
- return computed;
1948
- }
1949
-
1950
- static accessor(header) {
1951
- const internals = this[$internals] = (this[$internals] = {
1952
- accessors: {}
1953
- });
1954
-
1955
- const accessors = internals.accessors;
1956
- const prototype = this.prototype;
1957
-
1958
- function defineAccessor(_header) {
1959
- const lHeader = normalizeHeader(_header);
1960
-
1961
- if (!accessors[lHeader]) {
1962
- buildAccessors(prototype, _header);
1963
- accessors[lHeader] = true;
1964
- }
1965
- }
1966
-
1967
- utils$1.isArray(header) ? header.forEach(defineAccessor) : defineAccessor(header);
1968
-
1969
- return this;
1970
- }
1971
- };
1972
-
1973
- AxiosHeaders$1.accessor(['Content-Type', 'Content-Length', 'Accept', 'Accept-Encoding', 'User-Agent', 'Authorization']);
1974
-
1975
- // reserved names hotfix
1976
- utils$1.reduceDescriptors(AxiosHeaders$1.prototype, ({value}, key) => {
1977
- let mapped = key[0].toUpperCase() + key.slice(1); // map `set` => `Set`
1978
- return {
1979
- get: () => value,
1980
- set(headerValue) {
1981
- this[mapped] = headerValue;
1982
- }
1983
- }
1984
- });
1985
-
1986
- utils$1.freezeMethods(AxiosHeaders$1);
1987
-
1988
- /**
1989
- * Transform the data for a request or a response
1990
- *
1991
- * @param {Array|Function} fns A single function or Array of functions
1992
- * @param {?Object} response The response object
1993
- *
1994
- * @returns {*} The resulting transformed data
1995
- */
1996
- function transformData(fns, response) {
1997
- const config = this || defaults;
1998
- const context = response || config;
1999
- const headers = AxiosHeaders$1.from(context.headers);
2000
- let data = context.data;
2001
-
2002
- utils$1.forEach(fns, function transform(fn) {
2003
- data = fn.call(config, data, headers.normalize(), response ? response.status : undefined);
2004
- });
2005
-
2006
- headers.normalize();
2007
-
2008
- return data;
2009
- }
2010
-
2011
- function isCancel$1(value) {
2012
- return !!(value && value.__CANCEL__);
2013
- }
2014
-
2015
- /**
2016
- * A `CanceledError` is an object that is thrown when an operation is canceled.
2017
- *
2018
- * @param {string=} message The message.
2019
- * @param {Object=} config The config.
2020
- * @param {Object=} request The request.
2021
- *
2022
- * @returns {CanceledError} The created error.
2023
- */
2024
- function CanceledError$1(message, config, request) {
2025
- // eslint-disable-next-line no-eq-null,eqeqeq
2026
- AxiosError$1.call(this, message == null ? 'canceled' : message, AxiosError$1.ERR_CANCELED, config, request);
2027
- this.name = 'CanceledError';
2028
- }
2029
-
2030
- utils$1.inherits(CanceledError$1, AxiosError$1, {
2031
- __CANCEL__: true
2032
- });
2033
-
2034
- /**
2035
- * Resolve or reject a Promise based on response status.
2036
- *
2037
- * @param {Function} resolve A function that resolves the promise.
2038
- * @param {Function} reject A function that rejects the promise.
2039
- * @param {object} response The response.
2040
- *
2041
- * @returns {object} The response.
2042
- */
2043
- function settle(resolve, reject, response) {
2044
- const validateStatus = response.config.validateStatus;
2045
- if (!response.status || !validateStatus || validateStatus(response.status)) {
2046
- resolve(response);
2047
- } else {
2048
- reject(new AxiosError$1(
2049
- 'Request failed with status code ' + response.status,
2050
- [AxiosError$1.ERR_BAD_REQUEST, AxiosError$1.ERR_BAD_RESPONSE][Math.floor(response.status / 100) - 4],
2051
- response.config,
2052
- response.request,
2053
- response
2054
- ));
2055
- }
2056
- }
2057
-
2058
- function parseProtocol(url) {
2059
- const match = /^([-+\w]{1,25})(:?\/\/|:)/.exec(url);
2060
- return match && match[1] || '';
2061
- }
2062
-
2063
- /**
2064
- * Calculate data maxRate
2065
- * @param {Number} [samplesCount= 10]
2066
- * @param {Number} [min= 1000]
2067
- * @returns {Function}
2068
- */
2069
- function speedometer(samplesCount, min) {
2070
- samplesCount = samplesCount || 10;
2071
- const bytes = new Array(samplesCount);
2072
- const timestamps = new Array(samplesCount);
2073
- let head = 0;
2074
- let tail = 0;
2075
- let firstSampleTS;
2076
-
2077
- min = min !== undefined ? min : 1000;
2078
-
2079
- return function push(chunkLength) {
2080
- const now = Date.now();
2081
-
2082
- const startedAt = timestamps[tail];
2083
-
2084
- if (!firstSampleTS) {
2085
- firstSampleTS = now;
2086
- }
2087
-
2088
- bytes[head] = chunkLength;
2089
- timestamps[head] = now;
2090
-
2091
- let i = tail;
2092
- let bytesCount = 0;
2093
-
2094
- while (i !== head) {
2095
- bytesCount += bytes[i++];
2096
- i = i % samplesCount;
2097
- }
2098
-
2099
- head = (head + 1) % samplesCount;
2100
-
2101
- if (head === tail) {
2102
- tail = (tail + 1) % samplesCount;
2103
- }
2104
-
2105
- if (now - firstSampleTS < min) {
2106
- return;
2107
- }
2108
-
2109
- const passed = startedAt && now - startedAt;
2110
-
2111
- return passed ? Math.round(bytesCount * 1000 / passed) : undefined;
2112
- };
2113
- }
2114
-
2115
- /**
2116
- * Throttle decorator
2117
- * @param {Function} fn
2118
- * @param {Number} freq
2119
- * @return {Function}
2120
- */
2121
- function throttle(fn, freq) {
2122
- let timestamp = 0;
2123
- let threshold = 1000 / freq;
2124
- let lastArgs;
2125
- let timer;
2126
-
2127
- const invoke = (args, now = Date.now()) => {
2128
- timestamp = now;
2129
- lastArgs = null;
2130
- if (timer) {
2131
- clearTimeout(timer);
2132
- timer = null;
2133
- }
2134
- fn.apply(null, args);
2135
- };
2136
-
2137
- const throttled = (...args) => {
2138
- const now = Date.now();
2139
- const passed = now - timestamp;
2140
- if ( passed >= threshold) {
2141
- invoke(args, now);
2142
- } else {
2143
- lastArgs = args;
2144
- if (!timer) {
2145
- timer = setTimeout(() => {
2146
- timer = null;
2147
- invoke(lastArgs);
2148
- }, threshold - passed);
2149
- }
2150
- }
2151
- };
2152
-
2153
- const flush = () => lastArgs && invoke(lastArgs);
2154
-
2155
- return [throttled, flush];
2156
- }
2157
-
2158
- const progressEventReducer = (listener, isDownloadStream, freq = 3) => {
2159
- let bytesNotified = 0;
2160
- const _speedometer = speedometer(50, 250);
2161
-
2162
- return throttle(e => {
2163
- const loaded = e.loaded;
2164
- const total = e.lengthComputable ? e.total : undefined;
2165
- const progressBytes = loaded - bytesNotified;
2166
- const rate = _speedometer(progressBytes);
2167
- const inRange = loaded <= total;
2168
-
2169
- bytesNotified = loaded;
2170
-
2171
- const data = {
2172
- loaded,
2173
- total,
2174
- progress: total ? (loaded / total) : undefined,
2175
- bytes: progressBytes,
2176
- rate: rate ? rate : undefined,
2177
- estimated: rate && total && inRange ? (total - loaded) / rate : undefined,
2178
- event: e,
2179
- lengthComputable: total != null,
2180
- [isDownloadStream ? 'download' : 'upload']: true
2181
- };
2182
-
2183
- listener(data);
2184
- }, freq);
2185
- };
2186
-
2187
- const progressEventDecorator = (total, throttled) => {
2188
- const lengthComputable = total != null;
2189
-
2190
- return [(loaded) => throttled[0]({
2191
- lengthComputable,
2192
- total,
2193
- loaded
2194
- }), throttled[1]];
2195
- };
2196
-
2197
- const asyncDecorator = (fn) => (...args) => utils$1.asap(() => fn(...args));
2198
-
2199
- var isURLSameOrigin = platform.hasStandardBrowserEnv ? ((origin, isMSIE) => (url) => {
2200
- url = new URL(url, platform.origin);
2201
-
2202
- return (
2203
- origin.protocol === url.protocol &&
2204
- origin.host === url.host &&
2205
- (isMSIE || origin.port === url.port)
2206
- );
2207
- })(
2208
- new URL(platform.origin),
2209
- platform.navigator && /(msie|trident)/i.test(platform.navigator.userAgent)
2210
- ) : () => true;
2211
-
2212
- var cookies = platform.hasStandardBrowserEnv ?
2213
-
2214
- // Standard browser envs support document.cookie
2215
- {
2216
- write(name, value, expires, path, domain, secure) {
2217
- const cookie = [name + '=' + encodeURIComponent(value)];
2218
-
2219
- utils$1.isNumber(expires) && cookie.push('expires=' + new Date(expires).toGMTString());
2220
-
2221
- utils$1.isString(path) && cookie.push('path=' + path);
2222
-
2223
- utils$1.isString(domain) && cookie.push('domain=' + domain);
2224
-
2225
- secure === true && cookie.push('secure');
2226
-
2227
- document.cookie = cookie.join('; ');
2228
- },
2229
-
2230
- read(name) {
2231
- const match = document.cookie.match(new RegExp('(^|;\\s*)(' + name + ')=([^;]*)'));
2232
- return (match ? decodeURIComponent(match[3]) : null);
2233
- },
2234
-
2235
- remove(name) {
2236
- this.write(name, '', Date.now() - 86400000);
2237
- }
2238
- }
2239
-
2240
- :
2241
-
2242
- // Non-standard browser env (web workers, react-native) lack needed support.
2243
- {
2244
- write() {},
2245
- read() {
2246
- return null;
2247
- },
2248
- remove() {}
2249
- };
2250
-
2251
- /**
2252
- * Determines whether the specified URL is absolute
2253
- *
2254
- * @param {string} url The URL to test
2255
- *
2256
- * @returns {boolean} True if the specified URL is absolute, otherwise false
2257
- */
2258
- function isAbsoluteURL(url) {
2259
- // A URL is considered absolute if it begins with "<scheme>://" or "//" (protocol-relative URL).
2260
- // RFC 3986 defines scheme name as a sequence of characters beginning with a letter and followed
2261
- // by any combination of letters, digits, plus, period, or hyphen.
2262
- return /^([a-z][a-z\d+\-.]*:)?\/\//i.test(url);
2263
- }
2264
-
2265
- /**
2266
- * Creates a new URL by combining the specified URLs
2267
- *
2268
- * @param {string} baseURL The base URL
2269
- * @param {string} relativeURL The relative URL
2270
- *
2271
- * @returns {string} The combined URL
2272
- */
2273
- function combineURLs(baseURL, relativeURL) {
2274
- return relativeURL
2275
- ? baseURL.replace(/\/?\/$/, '') + '/' + relativeURL.replace(/^\/+/, '')
2276
- : baseURL;
2277
- }
2278
-
2279
- /**
2280
- * Creates a new URL by combining the baseURL with the requestedURL,
2281
- * only when the requestedURL is not already an absolute URL.
2282
- * If the requestURL is absolute, this function returns the requestedURL untouched.
2283
- *
2284
- * @param {string} baseURL The base URL
2285
- * @param {string} requestedURL Absolute or relative URL to combine
2286
- *
2287
- * @returns {string} The combined full path
2288
- */
2289
- function buildFullPath(baseURL, requestedURL, allowAbsoluteUrls) {
2290
- let isRelativeUrl = !isAbsoluteURL(requestedURL);
2291
- if (baseURL && (isRelativeUrl || allowAbsoluteUrls == false)) {
2292
- return combineURLs(baseURL, requestedURL);
2293
- }
2294
- return requestedURL;
2295
- }
2296
-
2297
- const headersToObject = (thing) => thing instanceof AxiosHeaders$1 ? { ...thing } : thing;
2298
-
2299
- /**
2300
- * Config-specific merge-function which creates a new config-object
2301
- * by merging two configuration objects together.
2302
- *
2303
- * @param {Object} config1
2304
- * @param {Object} config2
2305
- *
2306
- * @returns {Object} New object resulting from merging config2 to config1
2307
- */
2308
- function mergeConfig$1(config1, config2) {
2309
- // eslint-disable-next-line no-param-reassign
2310
- config2 = config2 || {};
2311
- const config = {};
2312
-
2313
- function getMergedValue(target, source, prop, caseless) {
2314
- if (utils$1.isPlainObject(target) && utils$1.isPlainObject(source)) {
2315
- return utils$1.merge.call({caseless}, target, source);
2316
- } else if (utils$1.isPlainObject(source)) {
2317
- return utils$1.merge({}, source);
2318
- } else if (utils$1.isArray(source)) {
2319
- return source.slice();
2320
- }
2321
- return source;
2322
- }
2323
-
2324
- // eslint-disable-next-line consistent-return
2325
- function mergeDeepProperties(a, b, prop , caseless) {
2326
- if (!utils$1.isUndefined(b)) {
2327
- return getMergedValue(a, b, prop , caseless);
2328
- } else if (!utils$1.isUndefined(a)) {
2329
- return getMergedValue(undefined, a, prop , caseless);
2330
- }
2331
- }
2332
-
2333
- // eslint-disable-next-line consistent-return
2334
- function valueFromConfig2(a, b) {
2335
- if (!utils$1.isUndefined(b)) {
2336
- return getMergedValue(undefined, b);
2337
- }
2338
- }
2339
-
2340
- // eslint-disable-next-line consistent-return
2341
- function defaultToConfig2(a, b) {
2342
- if (!utils$1.isUndefined(b)) {
2343
- return getMergedValue(undefined, b);
2344
- } else if (!utils$1.isUndefined(a)) {
2345
- return getMergedValue(undefined, a);
2346
- }
2347
- }
2348
-
2349
- // eslint-disable-next-line consistent-return
2350
- function mergeDirectKeys(a, b, prop) {
2351
- if (prop in config2) {
2352
- return getMergedValue(a, b);
2353
- } else if (prop in config1) {
2354
- return getMergedValue(undefined, a);
2355
- }
2356
- }
2357
-
2358
- const mergeMap = {
2359
- url: valueFromConfig2,
2360
- method: valueFromConfig2,
2361
- data: valueFromConfig2,
2362
- baseURL: defaultToConfig2,
2363
- transformRequest: defaultToConfig2,
2364
- transformResponse: defaultToConfig2,
2365
- paramsSerializer: defaultToConfig2,
2366
- timeout: defaultToConfig2,
2367
- timeoutMessage: defaultToConfig2,
2368
- withCredentials: defaultToConfig2,
2369
- withXSRFToken: defaultToConfig2,
2370
- adapter: defaultToConfig2,
2371
- responseType: defaultToConfig2,
2372
- xsrfCookieName: defaultToConfig2,
2373
- xsrfHeaderName: defaultToConfig2,
2374
- onUploadProgress: defaultToConfig2,
2375
- onDownloadProgress: defaultToConfig2,
2376
- decompress: defaultToConfig2,
2377
- maxContentLength: defaultToConfig2,
2378
- maxBodyLength: defaultToConfig2,
2379
- beforeRedirect: defaultToConfig2,
2380
- transport: defaultToConfig2,
2381
- httpAgent: defaultToConfig2,
2382
- httpsAgent: defaultToConfig2,
2383
- cancelToken: defaultToConfig2,
2384
- socketPath: defaultToConfig2,
2385
- responseEncoding: defaultToConfig2,
2386
- validateStatus: mergeDirectKeys,
2387
- headers: (a, b , prop) => mergeDeepProperties(headersToObject(a), headersToObject(b),prop, true)
2388
- };
2389
-
2390
- utils$1.forEach(Object.keys(Object.assign({}, config1, config2)), function computeConfigValue(prop) {
2391
- const merge = mergeMap[prop] || mergeDeepProperties;
2392
- const configValue = merge(config1[prop], config2[prop], prop);
2393
- (utils$1.isUndefined(configValue) && merge !== mergeDirectKeys) || (config[prop] = configValue);
2394
- });
2395
-
2396
- return config;
2397
- }
2398
-
2399
- var resolveConfig = (config) => {
2400
- const newConfig = mergeConfig$1({}, config);
2401
-
2402
- let {data, withXSRFToken, xsrfHeaderName, xsrfCookieName, headers, auth} = newConfig;
2403
-
2404
- newConfig.headers = headers = AxiosHeaders$1.from(headers);
2405
-
2406
- newConfig.url = buildURL(buildFullPath(newConfig.baseURL, newConfig.url, newConfig.allowAbsoluteUrls), config.params, config.paramsSerializer);
2407
-
2408
- // HTTP basic authentication
2409
- if (auth) {
2410
- headers.set('Authorization', 'Basic ' +
2411
- btoa((auth.username || '') + ':' + (auth.password ? unescape(encodeURIComponent(auth.password)) : ''))
2412
- );
2413
- }
2414
-
2415
- let contentType;
2416
-
2417
- if (utils$1.isFormData(data)) {
2418
- if (platform.hasStandardBrowserEnv || platform.hasStandardBrowserWebWorkerEnv) {
2419
- headers.setContentType(undefined); // Let the browser set it
2420
- } else if ((contentType = headers.getContentType()) !== false) {
2421
- // fix semicolon duplication issue for ReactNative FormData implementation
2422
- const [type, ...tokens] = contentType ? contentType.split(';').map(token => token.trim()).filter(Boolean) : [];
2423
- headers.setContentType([type || 'multipart/form-data', ...tokens].join('; '));
2424
- }
2425
- }
2426
-
2427
- // Add xsrf header
2428
- // This is only done if running in a standard browser environment.
2429
- // Specifically not if we're in a web worker, or react-native.
2430
-
2431
- if (platform.hasStandardBrowserEnv) {
2432
- withXSRFToken && utils$1.isFunction(withXSRFToken) && (withXSRFToken = withXSRFToken(newConfig));
2433
-
2434
- if (withXSRFToken || (withXSRFToken !== false && isURLSameOrigin(newConfig.url))) {
2435
- // Add xsrf header
2436
- const xsrfValue = xsrfHeaderName && xsrfCookieName && cookies.read(xsrfCookieName);
2437
-
2438
- if (xsrfValue) {
2439
- headers.set(xsrfHeaderName, xsrfValue);
2440
- }
2441
- }
2442
- }
2443
-
2444
- return newConfig;
2445
- };
2446
-
2447
- const isXHRAdapterSupported = typeof XMLHttpRequest !== 'undefined';
2448
-
2449
- var xhrAdapter = isXHRAdapterSupported && function (config) {
2450
- return new Promise(function dispatchXhrRequest(resolve, reject) {
2451
- const _config = resolveConfig(config);
2452
- let requestData = _config.data;
2453
- const requestHeaders = AxiosHeaders$1.from(_config.headers).normalize();
2454
- let {responseType, onUploadProgress, onDownloadProgress} = _config;
2455
- let onCanceled;
2456
- let uploadThrottled, downloadThrottled;
2457
- let flushUpload, flushDownload;
2458
-
2459
- function done() {
2460
- flushUpload && flushUpload(); // flush events
2461
- flushDownload && flushDownload(); // flush events
2462
-
2463
- _config.cancelToken && _config.cancelToken.unsubscribe(onCanceled);
2464
-
2465
- _config.signal && _config.signal.removeEventListener('abort', onCanceled);
2466
- }
2467
-
2468
- let request = new XMLHttpRequest();
2469
-
2470
- request.open(_config.method.toUpperCase(), _config.url, true);
2471
-
2472
- // Set the request timeout in MS
2473
- request.timeout = _config.timeout;
2474
-
2475
- function onloadend() {
2476
- if (!request) {
2477
- return;
2478
- }
2479
- // Prepare the response
2480
- const responseHeaders = AxiosHeaders$1.from(
2481
- 'getAllResponseHeaders' in request && request.getAllResponseHeaders()
2482
- );
2483
- const responseData = !responseType || responseType === 'text' || responseType === 'json' ?
2484
- request.responseText : request.response;
2485
- const response = {
2486
- data: responseData,
2487
- status: request.status,
2488
- statusText: request.statusText,
2489
- headers: responseHeaders,
2490
- config,
2491
- request
2492
- };
2493
-
2494
- settle(function _resolve(value) {
2495
- resolve(value);
2496
- done();
2497
- }, function _reject(err) {
2498
- reject(err);
2499
- done();
2500
- }, response);
2501
-
2502
- // Clean up request
2503
- request = null;
2504
- }
2505
-
2506
- if ('onloadend' in request) {
2507
- // Use onloadend if available
2508
- request.onloadend = onloadend;
2509
- } else {
2510
- // Listen for ready state to emulate onloadend
2511
- request.onreadystatechange = function handleLoad() {
2512
- if (!request || request.readyState !== 4) {
2513
- return;
2514
- }
2515
-
2516
- // The request errored out and we didn't get a response, this will be
2517
- // handled by onerror instead
2518
- // With one exception: request that using file: protocol, most browsers
2519
- // will return status as 0 even though it's a successful request
2520
- if (request.status === 0 && !(request.responseURL && request.responseURL.indexOf('file:') === 0)) {
2521
- return;
2522
- }
2523
- // readystate handler is calling before onerror or ontimeout handlers,
2524
- // so we should call onloadend on the next 'tick'
2525
- setTimeout(onloadend);
2526
- };
2527
- }
2528
-
2529
- // Handle browser request cancellation (as opposed to a manual cancellation)
2530
- request.onabort = function handleAbort() {
2531
- if (!request) {
2532
- return;
2533
- }
2534
-
2535
- reject(new AxiosError$1('Request aborted', AxiosError$1.ECONNABORTED, config, request));
2536
-
2537
- // Clean up request
2538
- request = null;
2539
- };
2540
-
2541
- // Handle low level network errors
2542
- request.onerror = function handleError() {
2543
- // Real errors are hidden from us by the browser
2544
- // onerror should only fire if it's a network error
2545
- reject(new AxiosError$1('Network Error', AxiosError$1.ERR_NETWORK, config, request));
2546
-
2547
- // Clean up request
2548
- request = null;
2549
- };
2550
-
2551
- // Handle timeout
2552
- request.ontimeout = function handleTimeout() {
2553
- let timeoutErrorMessage = _config.timeout ? 'timeout of ' + _config.timeout + 'ms exceeded' : 'timeout exceeded';
2554
- const transitional = _config.transitional || transitionalDefaults;
2555
- if (_config.timeoutErrorMessage) {
2556
- timeoutErrorMessage = _config.timeoutErrorMessage;
2557
- }
2558
- reject(new AxiosError$1(
2559
- timeoutErrorMessage,
2560
- transitional.clarifyTimeoutError ? AxiosError$1.ETIMEDOUT : AxiosError$1.ECONNABORTED,
2561
- config,
2562
- request));
2563
-
2564
- // Clean up request
2565
- request = null;
2566
- };
2567
-
2568
- // Remove Content-Type if data is undefined
2569
- requestData === undefined && requestHeaders.setContentType(null);
2570
-
2571
- // Add headers to the request
2572
- if ('setRequestHeader' in request) {
2573
- utils$1.forEach(requestHeaders.toJSON(), function setRequestHeader(val, key) {
2574
- request.setRequestHeader(key, val);
2575
- });
2576
- }
2577
-
2578
- // Add withCredentials to request if needed
2579
- if (!utils$1.isUndefined(_config.withCredentials)) {
2580
- request.withCredentials = !!_config.withCredentials;
2581
- }
2582
-
2583
- // Add responseType to request if needed
2584
- if (responseType && responseType !== 'json') {
2585
- request.responseType = _config.responseType;
2586
- }
2587
-
2588
- // Handle progress if needed
2589
- if (onDownloadProgress) {
2590
- ([downloadThrottled, flushDownload] = progressEventReducer(onDownloadProgress, true));
2591
- request.addEventListener('progress', downloadThrottled);
2592
- }
2593
-
2594
- // Not all browsers support upload events
2595
- if (onUploadProgress && request.upload) {
2596
- ([uploadThrottled, flushUpload] = progressEventReducer(onUploadProgress));
2597
-
2598
- request.upload.addEventListener('progress', uploadThrottled);
2599
-
2600
- request.upload.addEventListener('loadend', flushUpload);
2601
- }
2602
-
2603
- if (_config.cancelToken || _config.signal) {
2604
- // Handle cancellation
2605
- // eslint-disable-next-line func-names
2606
- onCanceled = cancel => {
2607
- if (!request) {
2608
- return;
2609
- }
2610
- reject(!cancel || cancel.type ? new CanceledError$1(null, config, request) : cancel);
2611
- request.abort();
2612
- request = null;
2613
- };
2614
-
2615
- _config.cancelToken && _config.cancelToken.subscribe(onCanceled);
2616
- if (_config.signal) {
2617
- _config.signal.aborted ? onCanceled() : _config.signal.addEventListener('abort', onCanceled);
2618
- }
2619
- }
2620
-
2621
- const protocol = parseProtocol(_config.url);
2622
-
2623
- if (protocol && platform.protocols.indexOf(protocol) === -1) {
2624
- reject(new AxiosError$1('Unsupported protocol ' + protocol + ':', AxiosError$1.ERR_BAD_REQUEST, config));
2625
- return;
2626
- }
2627
-
2628
-
2629
- // Send the request
2630
- request.send(requestData || null);
2631
- });
2632
- };
2633
-
2634
- const composeSignals = (signals, timeout) => {
2635
- const {length} = (signals = signals ? signals.filter(Boolean) : []);
2636
-
2637
- if (timeout || length) {
2638
- let controller = new AbortController();
2639
-
2640
- let aborted;
2641
-
2642
- const onabort = function (reason) {
2643
- if (!aborted) {
2644
- aborted = true;
2645
- unsubscribe();
2646
- const err = reason instanceof Error ? reason : this.reason;
2647
- controller.abort(err instanceof AxiosError$1 ? err : new CanceledError$1(err instanceof Error ? err.message : err));
2648
- }
2649
- };
2650
-
2651
- let timer = timeout && setTimeout(() => {
2652
- timer = null;
2653
- onabort(new AxiosError$1(`timeout ${timeout} of ms exceeded`, AxiosError$1.ETIMEDOUT));
2654
- }, timeout);
2655
-
2656
- const unsubscribe = () => {
2657
- if (signals) {
2658
- timer && clearTimeout(timer);
2659
- timer = null;
2660
- signals.forEach(signal => {
2661
- signal.unsubscribe ? signal.unsubscribe(onabort) : signal.removeEventListener('abort', onabort);
2662
- });
2663
- signals = null;
2664
- }
2665
- };
2666
-
2667
- signals.forEach((signal) => signal.addEventListener('abort', onabort));
2668
-
2669
- const {signal} = controller;
2670
-
2671
- signal.unsubscribe = () => utils$1.asap(unsubscribe);
2672
-
2673
- return signal;
2674
- }
2675
- };
2676
-
2677
- const streamChunk = function* (chunk, chunkSize) {
2678
- let len = chunk.byteLength;
2679
-
2680
- if (len < chunkSize) {
2681
- yield chunk;
2682
- return;
2683
- }
2684
-
2685
- let pos = 0;
2686
- let end;
2687
-
2688
- while (pos < len) {
2689
- end = pos + chunkSize;
2690
- yield chunk.slice(pos, end);
2691
- pos = end;
2692
- }
2693
- };
2694
-
2695
- const readBytes = async function* (iterable, chunkSize) {
2696
- for await (const chunk of readStream(iterable)) {
2697
- yield* streamChunk(chunk, chunkSize);
2698
- }
2699
- };
2700
-
2701
- const readStream = async function* (stream) {
2702
- if (stream[Symbol.asyncIterator]) {
2703
- yield* stream;
2704
- return;
2705
- }
2706
-
2707
- const reader = stream.getReader();
2708
- try {
2709
- for (;;) {
2710
- const {done, value} = await reader.read();
2711
- if (done) {
2712
- break;
2713
- }
2714
- yield value;
2715
- }
2716
- } finally {
2717
- await reader.cancel();
2718
- }
2719
- };
2720
-
2721
- const trackStream = (stream, chunkSize, onProgress, onFinish) => {
2722
- const iterator = readBytes(stream, chunkSize);
2723
-
2724
- let bytes = 0;
2725
- let done;
2726
- let _onFinish = (e) => {
2727
- if (!done) {
2728
- done = true;
2729
- onFinish && onFinish(e);
2730
- }
2731
- };
2732
-
2733
- return new ReadableStream({
2734
- async pull(controller) {
2735
- try {
2736
- const {done, value} = await iterator.next();
2737
-
2738
- if (done) {
2739
- _onFinish();
2740
- controller.close();
2741
- return;
2742
- }
2743
-
2744
- let len = value.byteLength;
2745
- if (onProgress) {
2746
- let loadedBytes = bytes += len;
2747
- onProgress(loadedBytes);
2748
- }
2749
- controller.enqueue(new Uint8Array(value));
2750
- } catch (err) {
2751
- _onFinish(err);
2752
- throw err;
2753
- }
2754
- },
2755
- cancel(reason) {
2756
- _onFinish(reason);
2757
- return iterator.return();
2758
- }
2759
- }, {
2760
- highWaterMark: 2
2761
- })
2762
- };
2763
-
2764
- const isFetchSupported = typeof fetch === 'function' && typeof Request === 'function' && typeof Response === 'function';
2765
- const isReadableStreamSupported = isFetchSupported && typeof ReadableStream === 'function';
2766
-
2767
- // used only inside the fetch adapter
2768
- const encodeText = isFetchSupported && (typeof TextEncoder === 'function' ?
2769
- ((encoder) => (str) => encoder.encode(str))(new TextEncoder()) :
2770
- async (str) => new Uint8Array(await new Response(str).arrayBuffer())
2771
- );
2772
-
2773
- const test = (fn, ...args) => {
2774
- try {
2775
- return !!fn(...args);
2776
- } catch (e) {
2777
- return false
2778
- }
2779
- };
2780
-
2781
- const supportsRequestStream = isReadableStreamSupported && test(() => {
2782
- let duplexAccessed = false;
2783
-
2784
- const hasContentType = new Request(platform.origin, {
2785
- body: new ReadableStream(),
2786
- method: 'POST',
2787
- get duplex() {
2788
- duplexAccessed = true;
2789
- return 'half';
2790
- },
2791
- }).headers.has('Content-Type');
2792
-
2793
- return duplexAccessed && !hasContentType;
2794
- });
2795
-
2796
- const DEFAULT_CHUNK_SIZE = 64 * 1024;
2797
-
2798
- const supportsResponseStream = isReadableStreamSupported &&
2799
- test(() => utils$1.isReadableStream(new Response('').body));
2800
-
2801
-
2802
- const resolvers = {
2803
- stream: supportsResponseStream && ((res) => res.body)
2804
- };
2805
-
2806
- isFetchSupported && (((res) => {
2807
- ['text', 'arrayBuffer', 'blob', 'formData', 'stream'].forEach(type => {
2808
- !resolvers[type] && (resolvers[type] = utils$1.isFunction(res[type]) ? (res) => res[type]() :
2809
- (_, config) => {
2810
- throw new AxiosError$1(`Response type '${type}' is not supported`, AxiosError$1.ERR_NOT_SUPPORT, config);
2811
- });
2812
- });
2813
- })(new Response));
2814
-
2815
- const getBodyLength = async (body) => {
2816
- if (body == null) {
2817
- return 0;
2818
- }
2819
-
2820
- if(utils$1.isBlob(body)) {
2821
- return body.size;
2822
- }
2823
-
2824
- if(utils$1.isSpecCompliantForm(body)) {
2825
- const _request = new Request(platform.origin, {
2826
- method: 'POST',
2827
- body,
2828
- });
2829
- return (await _request.arrayBuffer()).byteLength;
2830
- }
2831
-
2832
- if(utils$1.isArrayBufferView(body) || utils$1.isArrayBuffer(body)) {
2833
- return body.byteLength;
2834
- }
2835
-
2836
- if(utils$1.isURLSearchParams(body)) {
2837
- body = body + '';
2838
- }
2839
-
2840
- if(utils$1.isString(body)) {
2841
- return (await encodeText(body)).byteLength;
2842
- }
2843
- };
2844
-
2845
- const resolveBodyLength = async (headers, body) => {
2846
- const length = utils$1.toFiniteNumber(headers.getContentLength());
2847
-
2848
- return length == null ? getBodyLength(body) : length;
2849
- };
2850
-
2851
- var fetchAdapter = isFetchSupported && (async (config) => {
2852
- let {
2853
- url,
2854
- method,
2855
- data,
2856
- signal,
2857
- cancelToken,
2858
- timeout,
2859
- onDownloadProgress,
2860
- onUploadProgress,
2861
- responseType,
2862
- headers,
2863
- withCredentials = 'same-origin',
2864
- fetchOptions
2865
- } = resolveConfig(config);
2866
-
2867
- responseType = responseType ? (responseType + '').toLowerCase() : 'text';
2868
-
2869
- let composedSignal = composeSignals([signal, cancelToken && cancelToken.toAbortSignal()], timeout);
2870
-
2871
- let request;
2872
-
2873
- const unsubscribe = composedSignal && composedSignal.unsubscribe && (() => {
2874
- composedSignal.unsubscribe();
2875
- });
2876
-
2877
- let requestContentLength;
2878
-
2879
- try {
2880
- if (
2881
- onUploadProgress && supportsRequestStream && method !== 'get' && method !== 'head' &&
2882
- (requestContentLength = await resolveBodyLength(headers, data)) !== 0
2883
- ) {
2884
- let _request = new Request(url, {
2885
- method: 'POST',
2886
- body: data,
2887
- duplex: "half"
2888
- });
2889
-
2890
- let contentTypeHeader;
2891
-
2892
- if (utils$1.isFormData(data) && (contentTypeHeader = _request.headers.get('content-type'))) {
2893
- headers.setContentType(contentTypeHeader);
2894
- }
2895
-
2896
- if (_request.body) {
2897
- const [onProgress, flush] = progressEventDecorator(
2898
- requestContentLength,
2899
- progressEventReducer(asyncDecorator(onUploadProgress))
2900
- );
2901
-
2902
- data = trackStream(_request.body, DEFAULT_CHUNK_SIZE, onProgress, flush);
2903
- }
2904
- }
2905
-
2906
- if (!utils$1.isString(withCredentials)) {
2907
- withCredentials = withCredentials ? 'include' : 'omit';
2908
- }
2909
-
2910
- // Cloudflare Workers throws when credentials are defined
2911
- // see https://github.com/cloudflare/workerd/issues/902
2912
- const isCredentialsSupported = "credentials" in Request.prototype;
2913
- request = new Request(url, {
2914
- ...fetchOptions,
2915
- signal: composedSignal,
2916
- method: method.toUpperCase(),
2917
- headers: headers.normalize().toJSON(),
2918
- body: data,
2919
- duplex: "half",
2920
- credentials: isCredentialsSupported ? withCredentials : undefined
2921
- });
2922
-
2923
- let response = await fetch(request);
2924
-
2925
- const isStreamResponse = supportsResponseStream && (responseType === 'stream' || responseType === 'response');
2926
-
2927
- if (supportsResponseStream && (onDownloadProgress || (isStreamResponse && unsubscribe))) {
2928
- const options = {};
2929
-
2930
- ['status', 'statusText', 'headers'].forEach(prop => {
2931
- options[prop] = response[prop];
2932
- });
2933
-
2934
- const responseContentLength = utils$1.toFiniteNumber(response.headers.get('content-length'));
2935
-
2936
- const [onProgress, flush] = onDownloadProgress && progressEventDecorator(
2937
- responseContentLength,
2938
- progressEventReducer(asyncDecorator(onDownloadProgress), true)
2939
- ) || [];
2940
-
2941
- response = new Response(
2942
- trackStream(response.body, DEFAULT_CHUNK_SIZE, onProgress, () => {
2943
- flush && flush();
2944
- unsubscribe && unsubscribe();
2945
- }),
2946
- options
2947
- );
2948
- }
2949
-
2950
- responseType = responseType || 'text';
2951
-
2952
- let responseData = await resolvers[utils$1.findKey(resolvers, responseType) || 'text'](response, config);
2953
-
2954
- !isStreamResponse && unsubscribe && unsubscribe();
2955
-
2956
- return await new Promise((resolve, reject) => {
2957
- settle(resolve, reject, {
2958
- data: responseData,
2959
- headers: AxiosHeaders$1.from(response.headers),
2960
- status: response.status,
2961
- statusText: response.statusText,
2962
- config,
2963
- request
2964
- });
2965
- })
2966
- } catch (err) {
2967
- unsubscribe && unsubscribe();
2968
-
2969
- if (err && err.name === 'TypeError' && /fetch/i.test(err.message)) {
2970
- throw Object.assign(
2971
- new AxiosError$1('Network Error', AxiosError$1.ERR_NETWORK, config, request),
2972
- {
2973
- cause: err.cause || err
2974
- }
2975
- )
2976
- }
2977
-
2978
- throw AxiosError$1.from(err, err && err.code, config, request);
2979
- }
2980
- });
2981
-
2982
- const knownAdapters = {
2983
- http: httpAdapter,
2984
- xhr: xhrAdapter,
2985
- fetch: fetchAdapter
2986
- };
2987
-
2988
- utils$1.forEach(knownAdapters, (fn, value) => {
2989
- if (fn) {
2990
- try {
2991
- Object.defineProperty(fn, 'name', {value});
2992
- } catch (e) {
2993
- // eslint-disable-next-line no-empty
2994
- }
2995
- Object.defineProperty(fn, 'adapterName', {value});
2996
- }
2997
- });
2998
-
2999
- const renderReason = (reason) => `- ${reason}`;
3000
-
3001
- const isResolvedHandle = (adapter) => utils$1.isFunction(adapter) || adapter === null || adapter === false;
3002
-
3003
- var adapters = {
3004
- getAdapter: (adapters) => {
3005
- adapters = utils$1.isArray(adapters) ? adapters : [adapters];
3006
-
3007
- const {length} = adapters;
3008
- let nameOrAdapter;
3009
- let adapter;
3010
-
3011
- const rejectedReasons = {};
3012
-
3013
- for (let i = 0; i < length; i++) {
3014
- nameOrAdapter = adapters[i];
3015
- let id;
3016
-
3017
- adapter = nameOrAdapter;
3018
-
3019
- if (!isResolvedHandle(nameOrAdapter)) {
3020
- adapter = knownAdapters[(id = String(nameOrAdapter)).toLowerCase()];
3021
-
3022
- if (adapter === undefined) {
3023
- throw new AxiosError$1(`Unknown adapter '${id}'`);
3024
- }
3025
- }
3026
-
3027
- if (adapter) {
3028
- break;
3029
- }
3030
-
3031
- rejectedReasons[id || '#' + i] = adapter;
3032
- }
3033
-
3034
- if (!adapter) {
3035
-
3036
- const reasons = Object.entries(rejectedReasons)
3037
- .map(([id, state]) => `adapter ${id} ` +
3038
- (state === false ? 'is not supported by the environment' : 'is not available in the build')
3039
- );
3040
-
3041
- let s = length ?
3042
- (reasons.length > 1 ? 'since :\n' + reasons.map(renderReason).join('\n') : ' ' + renderReason(reasons[0])) :
3043
- 'as no adapter specified';
3044
-
3045
- throw new AxiosError$1(
3046
- `There is no suitable adapter to dispatch the request ` + s,
3047
- 'ERR_NOT_SUPPORT'
3048
- );
3049
- }
3050
-
3051
- return adapter;
3052
- },
3053
- adapters: knownAdapters
3054
- };
3055
-
3056
- /**
3057
- * Throws a `CanceledError` if cancellation has been requested.
3058
- *
3059
- * @param {Object} config The config that is to be used for the request
3060
- *
3061
- * @returns {void}
3062
- */
3063
- function throwIfCancellationRequested(config) {
3064
- if (config.cancelToken) {
3065
- config.cancelToken.throwIfRequested();
3066
- }
3067
-
3068
- if (config.signal && config.signal.aborted) {
3069
- throw new CanceledError$1(null, config);
3070
- }
3071
- }
3072
-
3073
- /**
3074
- * Dispatch a request to the server using the configured adapter.
3075
- *
3076
- * @param {object} config The config that is to be used for the request
3077
- *
3078
- * @returns {Promise} The Promise to be fulfilled
3079
- */
3080
- function dispatchRequest(config) {
3081
- throwIfCancellationRequested(config);
3082
-
3083
- config.headers = AxiosHeaders$1.from(config.headers);
3084
-
3085
- // Transform request data
3086
- config.data = transformData.call(
3087
- config,
3088
- config.transformRequest
3089
- );
3090
-
3091
- if (['post', 'put', 'patch'].indexOf(config.method) !== -1) {
3092
- config.headers.setContentType('application/x-www-form-urlencoded', false);
3093
- }
3094
-
3095
- const adapter = adapters.getAdapter(config.adapter || defaults.adapter);
3096
-
3097
- return adapter(config).then(function onAdapterResolution(response) {
3098
- throwIfCancellationRequested(config);
3099
-
3100
- // Transform response data
3101
- response.data = transformData.call(
3102
- config,
3103
- config.transformResponse,
3104
- response
3105
- );
3106
-
3107
- response.headers = AxiosHeaders$1.from(response.headers);
3108
-
3109
- return response;
3110
- }, function onAdapterRejection(reason) {
3111
- if (!isCancel$1(reason)) {
3112
- throwIfCancellationRequested(config);
3113
-
3114
- // Transform response data
3115
- if (reason && reason.response) {
3116
- reason.response.data = transformData.call(
3117
- config,
3118
- config.transformResponse,
3119
- reason.response
3120
- );
3121
- reason.response.headers = AxiosHeaders$1.from(reason.response.headers);
3122
- }
3123
- }
3124
-
3125
- return Promise.reject(reason);
3126
- });
3127
- }
3128
-
3129
- const VERSION$1 = "1.8.4";
3130
-
3131
- const validators$1 = {};
3132
-
3133
- // eslint-disable-next-line func-names
3134
- ['object', 'boolean', 'number', 'function', 'string', 'symbol'].forEach((type, i) => {
3135
- validators$1[type] = function validator(thing) {
3136
- return typeof thing === type || 'a' + (i < 1 ? 'n ' : ' ') + type;
3137
- };
3138
- });
3139
-
3140
- const deprecatedWarnings = {};
3141
-
3142
- /**
3143
- * Transitional option validator
3144
- *
3145
- * @param {function|boolean?} validator - set to false if the transitional option has been removed
3146
- * @param {string?} version - deprecated version / removed since version
3147
- * @param {string?} message - some message with additional info
3148
- *
3149
- * @returns {function}
3150
- */
3151
- validators$1.transitional = function transitional(validator, version, message) {
3152
- function formatMessage(opt, desc) {
3153
- return '[Axios v' + VERSION$1 + '] Transitional option \'' + opt + '\'' + desc + (message ? '. ' + message : '');
3154
- }
3155
-
3156
- // eslint-disable-next-line func-names
3157
- return (value, opt, opts) => {
3158
- if (validator === false) {
3159
- throw new AxiosError$1(
3160
- formatMessage(opt, ' has been removed' + (version ? ' in ' + version : '')),
3161
- AxiosError$1.ERR_DEPRECATED
3162
- );
3163
- }
3164
-
3165
- if (version && !deprecatedWarnings[opt]) {
3166
- deprecatedWarnings[opt] = true;
3167
- // eslint-disable-next-line no-console
3168
- console.warn(
3169
- formatMessage(
3170
- opt,
3171
- ' has been deprecated since v' + version + ' and will be removed in the near future'
3172
- )
3173
- );
3174
- }
3175
-
3176
- return validator ? validator(value, opt, opts) : true;
3177
- };
3178
- };
3179
-
3180
- validators$1.spelling = function spelling(correctSpelling) {
3181
- return (value, opt) => {
3182
- // eslint-disable-next-line no-console
3183
- console.warn(`${opt} is likely a misspelling of ${correctSpelling}`);
3184
- return true;
3185
- }
3186
- };
3187
-
3188
- /**
3189
- * Assert object's properties type
3190
- *
3191
- * @param {object} options
3192
- * @param {object} schema
3193
- * @param {boolean?} allowUnknown
3194
- *
3195
- * @returns {object}
3196
- */
3197
-
3198
- function assertOptions(options, schema, allowUnknown) {
3199
- if (typeof options !== 'object') {
3200
- throw new AxiosError$1('options must be an object', AxiosError$1.ERR_BAD_OPTION_VALUE);
3201
- }
3202
- const keys = Object.keys(options);
3203
- let i = keys.length;
3204
- while (i-- > 0) {
3205
- const opt = keys[i];
3206
- const validator = schema[opt];
3207
- if (validator) {
3208
- const value = options[opt];
3209
- const result = value === undefined || validator(value, opt, options);
3210
- if (result !== true) {
3211
- throw new AxiosError$1('option ' + opt + ' must be ' + result, AxiosError$1.ERR_BAD_OPTION_VALUE);
3212
- }
3213
- continue;
3214
- }
3215
- if (allowUnknown !== true) {
3216
- throw new AxiosError$1('Unknown option ' + opt, AxiosError$1.ERR_BAD_OPTION);
3217
- }
3218
- }
3219
- }
3220
-
3221
- var validator = {
3222
- assertOptions,
3223
- validators: validators$1
3224
- };
3225
-
3226
- const validators = validator.validators;
3227
-
3228
- /**
3229
- * Create a new instance of Axios
3230
- *
3231
- * @param {Object} instanceConfig The default config for the instance
3232
- *
3233
- * @return {Axios} A new instance of Axios
3234
- */
3235
- let Axios$1 = class Axios {
3236
- constructor(instanceConfig) {
3237
- this.defaults = instanceConfig;
3238
- this.interceptors = {
3239
- request: new InterceptorManager(),
3240
- response: new InterceptorManager()
3241
- };
3242
- }
3243
-
3244
- /**
3245
- * Dispatch a request
3246
- *
3247
- * @param {String|Object} configOrUrl The config specific for this request (merged with this.defaults)
3248
- * @param {?Object} config
3249
- *
3250
- * @returns {Promise} The Promise to be fulfilled
3251
- */
3252
- async request(configOrUrl, config) {
3253
- try {
3254
- return await this._request(configOrUrl, config);
3255
- } catch (err) {
3256
- if (err instanceof Error) {
3257
- let dummy = {};
3258
-
3259
- Error.captureStackTrace ? Error.captureStackTrace(dummy) : (dummy = new Error());
3260
-
3261
- // slice off the Error: ... line
3262
- const stack = dummy.stack ? dummy.stack.replace(/^.+\n/, '') : '';
3263
- try {
3264
- if (!err.stack) {
3265
- err.stack = stack;
3266
- // match without the 2 top stack lines
3267
- } else if (stack && !String(err.stack).endsWith(stack.replace(/^.+\n.+\n/, ''))) {
3268
- err.stack += '\n' + stack;
3269
- }
3270
- } catch (e) {
3271
- // ignore the case where "stack" is an un-writable property
3272
- }
3273
- }
3274
-
3275
- throw err;
3276
- }
3277
- }
3278
-
3279
- _request(configOrUrl, config) {
3280
- /*eslint no-param-reassign:0*/
3281
- // Allow for axios('example/url'[, config]) a la fetch API
3282
- if (typeof configOrUrl === 'string') {
3283
- config = config || {};
3284
- config.url = configOrUrl;
3285
- } else {
3286
- config = configOrUrl || {};
3287
- }
3288
-
3289
- config = mergeConfig$1(this.defaults, config);
3290
-
3291
- const {transitional, paramsSerializer, headers} = config;
3292
-
3293
- if (transitional !== undefined) {
3294
- validator.assertOptions(transitional, {
3295
- silentJSONParsing: validators.transitional(validators.boolean),
3296
- forcedJSONParsing: validators.transitional(validators.boolean),
3297
- clarifyTimeoutError: validators.transitional(validators.boolean)
3298
- }, false);
3299
- }
3300
-
3301
- if (paramsSerializer != null) {
3302
- if (utils$1.isFunction(paramsSerializer)) {
3303
- config.paramsSerializer = {
3304
- serialize: paramsSerializer
3305
- };
3306
- } else {
3307
- validator.assertOptions(paramsSerializer, {
3308
- encode: validators.function,
3309
- serialize: validators.function
3310
- }, true);
3311
- }
3312
- }
3313
-
3314
- // Set config.allowAbsoluteUrls
3315
- if (config.allowAbsoluteUrls !== undefined) ; else if (this.defaults.allowAbsoluteUrls !== undefined) {
3316
- config.allowAbsoluteUrls = this.defaults.allowAbsoluteUrls;
3317
- } else {
3318
- config.allowAbsoluteUrls = true;
3319
- }
3320
-
3321
- validator.assertOptions(config, {
3322
- baseUrl: validators.spelling('baseURL'),
3323
- withXsrfToken: validators.spelling('withXSRFToken')
3324
- }, true);
3325
-
3326
- // Set config.method
3327
- config.method = (config.method || this.defaults.method || 'get').toLowerCase();
3328
-
3329
- // Flatten headers
3330
- let contextHeaders = headers && utils$1.merge(
3331
- headers.common,
3332
- headers[config.method]
3333
- );
3334
-
3335
- headers && utils$1.forEach(
3336
- ['delete', 'get', 'head', 'post', 'put', 'patch', 'common'],
3337
- (method) => {
3338
- delete headers[method];
3339
- }
3340
- );
3341
-
3342
- config.headers = AxiosHeaders$1.concat(contextHeaders, headers);
3343
-
3344
- // filter out skipped interceptors
3345
- const requestInterceptorChain = [];
3346
- let synchronousRequestInterceptors = true;
3347
- this.interceptors.request.forEach(function unshiftRequestInterceptors(interceptor) {
3348
- if (typeof interceptor.runWhen === 'function' && interceptor.runWhen(config) === false) {
3349
- return;
3350
- }
3351
-
3352
- synchronousRequestInterceptors = synchronousRequestInterceptors && interceptor.synchronous;
3353
-
3354
- requestInterceptorChain.unshift(interceptor.fulfilled, interceptor.rejected);
3355
- });
3356
-
3357
- const responseInterceptorChain = [];
3358
- this.interceptors.response.forEach(function pushResponseInterceptors(interceptor) {
3359
- responseInterceptorChain.push(interceptor.fulfilled, interceptor.rejected);
3360
- });
3361
-
3362
- let promise;
3363
- let i = 0;
3364
- let len;
3365
-
3366
- if (!synchronousRequestInterceptors) {
3367
- const chain = [dispatchRequest.bind(this), undefined];
3368
- chain.unshift.apply(chain, requestInterceptorChain);
3369
- chain.push.apply(chain, responseInterceptorChain);
3370
- len = chain.length;
3371
-
3372
- promise = Promise.resolve(config);
3373
-
3374
- while (i < len) {
3375
- promise = promise.then(chain[i++], chain[i++]);
3376
- }
3377
-
3378
- return promise;
3379
- }
3380
-
3381
- len = requestInterceptorChain.length;
3382
-
3383
- let newConfig = config;
3384
-
3385
- i = 0;
3386
-
3387
- while (i < len) {
3388
- const onFulfilled = requestInterceptorChain[i++];
3389
- const onRejected = requestInterceptorChain[i++];
3390
- try {
3391
- newConfig = onFulfilled(newConfig);
3392
- } catch (error) {
3393
- onRejected.call(this, error);
3394
- break;
3395
- }
3396
- }
3397
-
3398
- try {
3399
- promise = dispatchRequest.call(this, newConfig);
3400
- } catch (error) {
3401
- return Promise.reject(error);
3402
- }
3403
-
3404
- i = 0;
3405
- len = responseInterceptorChain.length;
3406
-
3407
- while (i < len) {
3408
- promise = promise.then(responseInterceptorChain[i++], responseInterceptorChain[i++]);
3409
- }
3410
-
3411
- return promise;
3412
- }
3413
-
3414
- getUri(config) {
3415
- config = mergeConfig$1(this.defaults, config);
3416
- const fullPath = buildFullPath(config.baseURL, config.url, config.allowAbsoluteUrls);
3417
- return buildURL(fullPath, config.params, config.paramsSerializer);
3418
- }
3419
- };
3420
-
3421
- // Provide aliases for supported request methods
3422
- utils$1.forEach(['delete', 'get', 'head', 'options'], function forEachMethodNoData(method) {
3423
- /*eslint func-names:0*/
3424
- Axios$1.prototype[method] = function(url, config) {
3425
- return this.request(mergeConfig$1(config || {}, {
3426
- method,
3427
- url,
3428
- data: (config || {}).data
3429
- }));
3430
- };
3431
- });
3432
-
3433
- utils$1.forEach(['post', 'put', 'patch'], function forEachMethodWithData(method) {
3434
- /*eslint func-names:0*/
3435
-
3436
- function generateHTTPMethod(isForm) {
3437
- return function httpMethod(url, data, config) {
3438
- return this.request(mergeConfig$1(config || {}, {
3439
- method,
3440
- headers: isForm ? {
3441
- 'Content-Type': 'multipart/form-data'
3442
- } : {},
3443
- url,
3444
- data
3445
- }));
3446
- };
3447
- }
3448
-
3449
- Axios$1.prototype[method] = generateHTTPMethod();
3450
-
3451
- Axios$1.prototype[method + 'Form'] = generateHTTPMethod(true);
3452
- });
3453
-
3454
- /**
3455
- * A `CancelToken` is an object that can be used to request cancellation of an operation.
3456
- *
3457
- * @param {Function} executor The executor function.
3458
- *
3459
- * @returns {CancelToken}
3460
- */
3461
- let CancelToken$1 = class CancelToken {
3462
- constructor(executor) {
3463
- if (typeof executor !== 'function') {
3464
- throw new TypeError('executor must be a function.');
3465
- }
3466
-
3467
- let resolvePromise;
3468
-
3469
- this.promise = new Promise(function promiseExecutor(resolve) {
3470
- resolvePromise = resolve;
3471
- });
3472
-
3473
- const token = this;
3474
-
3475
- // eslint-disable-next-line func-names
3476
- this.promise.then(cancel => {
3477
- if (!token._listeners) return;
3478
-
3479
- let i = token._listeners.length;
3480
-
3481
- while (i-- > 0) {
3482
- token._listeners[i](cancel);
3483
- }
3484
- token._listeners = null;
3485
- });
3486
-
3487
- // eslint-disable-next-line func-names
3488
- this.promise.then = onfulfilled => {
3489
- let _resolve;
3490
- // eslint-disable-next-line func-names
3491
- const promise = new Promise(resolve => {
3492
- token.subscribe(resolve);
3493
- _resolve = resolve;
3494
- }).then(onfulfilled);
3495
-
3496
- promise.cancel = function reject() {
3497
- token.unsubscribe(_resolve);
3498
- };
3499
-
3500
- return promise;
3501
- };
3502
-
3503
- executor(function cancel(message, config, request) {
3504
- if (token.reason) {
3505
- // Cancellation has already been requested
3506
- return;
3507
- }
3508
-
3509
- token.reason = new CanceledError$1(message, config, request);
3510
- resolvePromise(token.reason);
3511
- });
3512
- }
3513
-
3514
- /**
3515
- * Throws a `CanceledError` if cancellation has been requested.
3516
- */
3517
- throwIfRequested() {
3518
- if (this.reason) {
3519
- throw this.reason;
3520
- }
3521
- }
3522
-
3523
- /**
3524
- * Subscribe to the cancel signal
3525
- */
3526
-
3527
- subscribe(listener) {
3528
- if (this.reason) {
3529
- listener(this.reason);
3530
- return;
3531
- }
3532
-
3533
- if (this._listeners) {
3534
- this._listeners.push(listener);
3535
- } else {
3536
- this._listeners = [listener];
3537
- }
3538
- }
3539
-
3540
- /**
3541
- * Unsubscribe from the cancel signal
3542
- */
3543
-
3544
- unsubscribe(listener) {
3545
- if (!this._listeners) {
3546
- return;
3547
- }
3548
- const index = this._listeners.indexOf(listener);
3549
- if (index !== -1) {
3550
- this._listeners.splice(index, 1);
3551
- }
3552
- }
3553
-
3554
- toAbortSignal() {
3555
- const controller = new AbortController();
3556
-
3557
- const abort = (err) => {
3558
- controller.abort(err);
3559
- };
3560
-
3561
- this.subscribe(abort);
3562
-
3563
- controller.signal.unsubscribe = () => this.unsubscribe(abort);
3564
-
3565
- return controller.signal;
3566
- }
3567
-
3568
- /**
3569
- * Returns an object that contains a new `CancelToken` and a function that, when called,
3570
- * cancels the `CancelToken`.
3571
- */
3572
- static source() {
3573
- let cancel;
3574
- const token = new CancelToken(function executor(c) {
3575
- cancel = c;
3576
- });
3577
- return {
3578
- token,
3579
- cancel
3580
- };
3581
- }
3582
- };
3583
-
3584
- /**
3585
- * Syntactic sugar for invoking a function and expanding an array for arguments.
3586
- *
3587
- * Common use case would be to use `Function.prototype.apply`.
3588
- *
3589
- * ```js
3590
- * function f(x, y, z) {}
3591
- * var args = [1, 2, 3];
3592
- * f.apply(null, args);
3593
- * ```
3594
- *
3595
- * With `spread` this example can be re-written.
3596
- *
3597
- * ```js
3598
- * spread(function(x, y, z) {})([1, 2, 3]);
3599
- * ```
3600
- *
3601
- * @param {Function} callback
3602
- *
3603
- * @returns {Function}
3604
- */
3605
- function spread$1(callback) {
3606
- return function wrap(arr) {
3607
- return callback.apply(null, arr);
3608
- };
3609
- }
3610
-
3611
- /**
3612
- * Determines whether the payload is an error thrown by Axios
3613
- *
3614
- * @param {*} payload The value to test
3615
- *
3616
- * @returns {boolean} True if the payload is an error thrown by Axios, otherwise false
3617
- */
3618
- function isAxiosError$1(payload) {
3619
- return utils$1.isObject(payload) && (payload.isAxiosError === true);
3620
- }
3621
-
3622
- const HttpStatusCode$1 = {
3623
- Continue: 100,
3624
- SwitchingProtocols: 101,
3625
- Processing: 102,
3626
- EarlyHints: 103,
3627
- Ok: 200,
3628
- Created: 201,
3629
- Accepted: 202,
3630
- NonAuthoritativeInformation: 203,
3631
- NoContent: 204,
3632
- ResetContent: 205,
3633
- PartialContent: 206,
3634
- MultiStatus: 207,
3635
- AlreadyReported: 208,
3636
- ImUsed: 226,
3637
- MultipleChoices: 300,
3638
- MovedPermanently: 301,
3639
- Found: 302,
3640
- SeeOther: 303,
3641
- NotModified: 304,
3642
- UseProxy: 305,
3643
- Unused: 306,
3644
- TemporaryRedirect: 307,
3645
- PermanentRedirect: 308,
3646
- BadRequest: 400,
3647
- Unauthorized: 401,
3648
- PaymentRequired: 402,
3649
- Forbidden: 403,
3650
- NotFound: 404,
3651
- MethodNotAllowed: 405,
3652
- NotAcceptable: 406,
3653
- ProxyAuthenticationRequired: 407,
3654
- RequestTimeout: 408,
3655
- Conflict: 409,
3656
- Gone: 410,
3657
- LengthRequired: 411,
3658
- PreconditionFailed: 412,
3659
- PayloadTooLarge: 413,
3660
- UriTooLong: 414,
3661
- UnsupportedMediaType: 415,
3662
- RangeNotSatisfiable: 416,
3663
- ExpectationFailed: 417,
3664
- ImATeapot: 418,
3665
- MisdirectedRequest: 421,
3666
- UnprocessableEntity: 422,
3667
- Locked: 423,
3668
- FailedDependency: 424,
3669
- TooEarly: 425,
3670
- UpgradeRequired: 426,
3671
- PreconditionRequired: 428,
3672
- TooManyRequests: 429,
3673
- RequestHeaderFieldsTooLarge: 431,
3674
- UnavailableForLegalReasons: 451,
3675
- InternalServerError: 500,
3676
- NotImplemented: 501,
3677
- BadGateway: 502,
3678
- ServiceUnavailable: 503,
3679
- GatewayTimeout: 504,
3680
- HttpVersionNotSupported: 505,
3681
- VariantAlsoNegotiates: 506,
3682
- InsufficientStorage: 507,
3683
- LoopDetected: 508,
3684
- NotExtended: 510,
3685
- NetworkAuthenticationRequired: 511,
3686
- };
3687
-
3688
- Object.entries(HttpStatusCode$1).forEach(([key, value]) => {
3689
- HttpStatusCode$1[value] = key;
3690
- });
3691
-
3692
- /**
3693
- * Create an instance of Axios
3694
- *
3695
- * @param {Object} defaultConfig The default config for the instance
3696
- *
3697
- * @returns {Axios} A new instance of Axios
3698
- */
3699
- function createInstance(defaultConfig) {
3700
- const context = new Axios$1(defaultConfig);
3701
- const instance = bind(Axios$1.prototype.request, context);
3702
-
3703
- // Copy axios.prototype to instance
3704
- utils$1.extend(instance, Axios$1.prototype, context, {allOwnKeys: true});
3705
-
3706
- // Copy context to instance
3707
- utils$1.extend(instance, context, null, {allOwnKeys: true});
3708
-
3709
- // Factory for creating new instances
3710
- instance.create = function create(instanceConfig) {
3711
- return createInstance(mergeConfig$1(defaultConfig, instanceConfig));
3712
- };
3713
-
3714
- return instance;
3715
- }
3716
-
3717
- // Create the default instance to be exported
3718
- const axios = createInstance(defaults);
3719
-
3720
- // Expose Axios class to allow class inheritance
3721
- axios.Axios = Axios$1;
3722
-
3723
- // Expose Cancel & CancelToken
3724
- axios.CanceledError = CanceledError$1;
3725
- axios.CancelToken = CancelToken$1;
3726
- axios.isCancel = isCancel$1;
3727
- axios.VERSION = VERSION$1;
3728
- axios.toFormData = toFormData$1;
3729
-
3730
- // Expose AxiosError class
3731
- axios.AxiosError = AxiosError$1;
3732
-
3733
- // alias for CanceledError for backward compatibility
3734
- axios.Cancel = axios.CanceledError;
3735
-
3736
- // Expose all/spread
3737
- axios.all = function all(promises) {
3738
- return Promise.all(promises);
3739
- };
3740
-
3741
- axios.spread = spread$1;
3742
-
3743
- // Expose isAxiosError
3744
- axios.isAxiosError = isAxiosError$1;
3745
-
3746
- // Expose mergeConfig
3747
- axios.mergeConfig = mergeConfig$1;
3748
-
3749
- axios.AxiosHeaders = AxiosHeaders$1;
3750
-
3751
- axios.formToJSON = thing => formDataToJSON(utils$1.isHTMLForm(thing) ? new FormData(thing) : thing);
3752
-
3753
- axios.getAdapter = adapters.getAdapter;
3754
-
3755
- axios.HttpStatusCode = HttpStatusCode$1;
3756
-
3757
- axios.default = axios;
3758
-
3759
- // This module is intended to unwrap Axios default export as named.
3760
- // Keep top-level export same with static properties
3761
- // so that it can keep same with es module or cjs
3762
- const {
3763
- Axios,
3764
- AxiosError,
3765
- CanceledError,
3766
- isCancel,
3767
- CancelToken,
3768
- VERSION,
3769
- all,
3770
- Cancel,
3771
- isAxiosError,
3772
- spread,
3773
- toFormData,
3774
- AxiosHeaders,
3775
- HttpStatusCode,
3776
- formToJSON,
3777
- getAdapter,
3778
- mergeConfig
3779
- } = axios;
3780
-
3781
- var commonjsGlobal = typeof globalThis !== 'undefined' ? globalThis : typeof window !== 'undefined' ? window : typeof global !== 'undefined' ? global : typeof self !== 'undefined' ? self : {};
3782
-
3783
- var formdata_min = {};
3784
-
3785
- /*! formdata-polyfill. MIT License. Jimmy W?rting <https://jimmy.warting.se/opensource> */
3786
-
3787
- var hasRequiredFormdata_min;
3788
-
3789
- function requireFormdata_min () {
3790
- if (hasRequiredFormdata_min) return formdata_min;
3791
- hasRequiredFormdata_min = 1;
3792
- (function(){var h;function l(a){var b=0;return function(){return b<a.length?{done:false,value:a[b++]}:{done:true}}}var m="function"==typeof Object.defineProperties?Object.defineProperty:function(a,b,c){if(a==Array.prototype||a==Object.prototype)return a;a[b]=c.value;return a};
3793
- function n(a){a=["object"==typeof globalThis&&globalThis,a,"object"==typeof window&&window,"object"==typeof self&&self,"object"==typeof commonjsGlobal&&commonjsGlobal];for(var b=0;b<a.length;++b){var c=a[b];if(c&&c.Math==Math)return c}throw Error("Cannot find global object");}var q=n(this);function r(a,b){if(b)a:{var c=q;a=a.split(".");for(var d=0;d<a.length-1;d++){var e=a[d];if(!(e in c))break a;c=c[e];}a=a[a.length-1];d=c[a];b=b(d);b!=d&&null!=b&&m(c,a,{configurable:true,writable:true,value:b});}}
3794
- r("Symbol",function(a){function b(f){if(this instanceof b)throw new TypeError("Symbol is not a constructor");return new c(d+(f||"")+"_"+e++,f)}function c(f,g){this.A=f;m(this,"description",{configurable:true,writable:true,value:g});}if(a)return a;c.prototype.toString=function(){return this.A};var d="jscomp_symbol_"+(1E9*Math.random()>>>0)+"_",e=0;return b});
3795
- r("Symbol.iterator",function(a){if(a)return a;a=Symbol("Symbol.iterator");for(var b="Array Int8Array Uint8Array Uint8ClampedArray Int16Array Uint16Array Int32Array Uint32Array Float32Array Float64Array".split(" "),c=0;c<b.length;c++){var d=q[b[c]];"function"===typeof d&&"function"!=typeof d.prototype[a]&&m(d.prototype,a,{configurable:true,writable:true,value:function(){return u(l(this))}});}return a});function u(a){a={next:a};a[Symbol.iterator]=function(){return this};return a}
3796
- function v(a){var b="undefined"!=typeof Symbol&&Symbol.iterator&&a[Symbol.iterator];return b?b.call(a):{next:l(a)}}var w;if("function"==typeof Object.setPrototypeOf)w=Object.setPrototypeOf;else {var y;a:{var z={a:true},A={};try{A.__proto__=z;y=A.a;break a}catch(a){}y=false;}w=y?function(a,b){a.__proto__=b;if(a.__proto__!==b)throw new TypeError(a+" is not extensible");return a}:null;}var B=w;function C(){this.m=false;this.j=null;this.v=void 0;this.h=1;this.u=this.C=0;this.l=null;}
3797
- function D(a){if(a.m)throw new TypeError("Generator is already running");a.m=true;}C.prototype.o=function(a){this.v=a;};C.prototype.s=function(a){this.l={D:a,F:true};this.h=this.C||this.u;};C.prototype.return=function(a){this.l={return:a};this.h=this.u;};function E(a,b){a.h=3;return {value:b}}function F(a){this.g=new C;this.G=a;}F.prototype.o=function(a){D(this.g);if(this.g.j)return G(this,this.g.j.next,a,this.g.o);this.g.o(a);return H(this)};
3798
- function I(a,b){D(a.g);var c=a.g.j;if(c)return G(a,"return"in c?c["return"]:function(d){return {value:d,done:true}},b,a.g.return);a.g.return(b);return H(a)}F.prototype.s=function(a){D(this.g);if(this.g.j)return G(this,this.g.j["throw"],a,this.g.o);this.g.s(a);return H(this)};
3799
- function G(a,b,c,d){try{var e=b.call(a.g.j,c);if(!(e instanceof Object))throw new TypeError("Iterator result "+e+" is not an object");if(!e.done)return a.g.m=!1,e;var f=e.value;}catch(g){return a.g.j=null,a.g.s(g),H(a)}a.g.j=null;d.call(a.g,f);return H(a)}function H(a){for(;a.g.h;)try{var b=a.G(a.g);if(b)return a.g.m=!1,{value:b.value,done:!1}}catch(c){a.g.v=void 0,a.g.s(c);}a.g.m=false;if(a.g.l){b=a.g.l;a.g.l=null;if(b.F)throw b.D;return {value:b.return,done:true}}return {value:void 0,done:true}}
3800
- function J(a){this.next=function(b){return a.o(b)};this.throw=function(b){return a.s(b)};this.return=function(b){return I(a,b)};this[Symbol.iterator]=function(){return this};}function K(a,b){b=new J(new F(b));B&&a.prototype&&B(b,a.prototype);return b}function L(a,b){a instanceof String&&(a+="");var c=0,d=false,e={next:function(){if(!d&&c<a.length){var f=c++;return {value:b(f,a[f]),done:false}}d=true;return {done:true,value:void 0}}};e[Symbol.iterator]=function(){return e};return e}
3801
- r("Array.prototype.entries",function(a){return a?a:function(){return L(this,function(b,c){return [b,c]})}});
3802
- if("undefined"!==typeof Blob&&("undefined"===typeof FormData||!FormData.prototype.keys)){var M=function(a,b){for(var c=0;c<a.length;c++)b(a[c]);},N=function(a){return a.replace(/\r?\n|\r/g,"\r\n")},O=function(a,b,c){if(b instanceof Blob){c=void 0!==c?String(c+""):"string"===typeof b.name?b.name:"blob";if(b.name!==c||"[object Blob]"===Object.prototype.toString.call(b))b=new File([b],c);return [String(a),b]}return [String(a),String(b)]},P=function(a,b){if(a.length<b)throw new TypeError(b+" argument required, but only "+
3803
- a.length+" present.");},Q="object"===typeof globalThis?globalThis:"object"===typeof window?window:"object"===typeof self?self:this,R=Q.FormData,S=Q.XMLHttpRequest&&Q.XMLHttpRequest.prototype.send,T=Q.Request&&Q.fetch,U=Q.navigator&&Q.navigator.sendBeacon,V=Q.Element&&Q.Element.prototype,W=Q.Symbol&&Symbol.toStringTag;W&&(Blob.prototype[W]||(Blob.prototype[W]="Blob"),"File"in Q&&!File.prototype[W]&&(File.prototype[W]="File"));try{new File([],"");}catch(a){Q.File=function(b,c,d){b=new Blob(b,d||{});
3804
- Object.defineProperties(b,{name:{value:c},lastModified:{value:+(d&&void 0!==d.lastModified?new Date(d.lastModified):new Date)},toString:{value:function(){return "[object File]"}}});W&&Object.defineProperty(b,W,{value:"File"});return b};}var escape=function(a){return a.replace(/\n/g,"%0A").replace(/\r/g,"%0D").replace(/"/g,"%22")},X=function(a){this.i=[];var b=this;a&&M(a.elements,function(c){if(c.name&&!c.disabled&&"submit"!==c.type&&"button"!==c.type&&!c.matches("form fieldset[disabled] *"))if("file"===
3805
- c.type){var d=c.files&&c.files.length?c.files:[new File([],"",{type:"application/octet-stream"})];M(d,function(e){b.append(c.name,e);});}else "select-multiple"===c.type||"select-one"===c.type?M(c.options,function(e){!e.disabled&&e.selected&&b.append(c.name,e.value);}):"checkbox"===c.type||"radio"===c.type?c.checked&&b.append(c.name,c.value):(d="textarea"===c.type?N(c.value):c.value,b.append(c.name,d));});};h=X.prototype;h.append=function(a,b,c){P(arguments,2);this.i.push(O(a,b,c));};h.delete=function(a){P(arguments,
3806
- 1);var b=[];a=String(a);M(this.i,function(c){c[0]!==a&&b.push(c);});this.i=b;};h.entries=function b(){var c,d=this;return K(b,function(e){1==e.h&&(c=0);if(3!=e.h)return c<d.i.length?e=E(e,d.i[c]):(e.h=0,e=void 0),e;c++;e.h=2;})};h.forEach=function(b,c){P(arguments,1);for(var d=v(this),e=d.next();!e.done;e=d.next()){var f=v(e.value);e=f.next().value;f=f.next().value;b.call(c,f,e,this);}};h.get=function(b){P(arguments,1);var c=this.i;b=String(b);for(var d=0;d<c.length;d++)if(c[d][0]===b)return c[d][1];
3807
- return null};h.getAll=function(b){P(arguments,1);var c=[];b=String(b);M(this.i,function(d){d[0]===b&&c.push(d[1]);});return c};h.has=function(b){P(arguments,1);b=String(b);for(var c=0;c<this.i.length;c++)if(this.i[c][0]===b)return true;return false};h.keys=function c(){var d=this,e,f,g,k,p;return K(c,function(t){1==t.h&&(e=v(d),f=e.next());if(3!=t.h){if(f.done){t.h=0;return}g=f.value;k=v(g);p=k.next().value;return E(t,p)}f=e.next();t.h=2;})};h.set=function(c,d,e){P(arguments,2);c=String(c);var f=[],g=O(c,
3808
- d,e),k=true;M(this.i,function(p){p[0]===c?k&&(k=!f.push(g)):f.push(p);});k&&f.push(g);this.i=f;};h.values=function d(){var e=this,f,g,k,p,t;return K(d,function(x){1==x.h&&(f=v(e),g=f.next());if(3!=x.h){if(g.done){x.h=0;return}k=g.value;p=v(k);p.next();t=p.next().value;return E(x,t)}g=f.next();x.h=2;})};X.prototype._asNative=function(){for(var d=new R,e=v(this),f=e.next();!f.done;f=e.next()){var g=v(f.value);f=g.next().value;g=g.next().value;d.append(f,g);}return d};X.prototype._blob=function(){var d="----formdata-polyfill-"+
3809
- Math.random(),e=[],f="--"+d+'\r\nContent-Disposition: form-data; name="';this.forEach(function(g,k){return "string"==typeof g?e.push(f+escape(N(k))+('"\r\n\r\n'+N(g)+"\r\n")):e.push(f+escape(N(k))+('"; filename="'+escape(g.name)+'"\r\nContent-Type: '+(g.type||"application/octet-stream")+"\r\n\r\n"),g,"\r\n")});e.push("--"+d+"--");return new Blob(e,{type:"multipart/form-data; boundary="+d})};X.prototype[Symbol.iterator]=function(){return this.entries()};X.prototype.toString=function(){return "[object FormData]"};
3810
- V&&!V.matches&&(V.matches=V.matchesSelector||V.mozMatchesSelector||V.msMatchesSelector||V.oMatchesSelector||V.webkitMatchesSelector||function(d){d=(this.document||this.ownerDocument).querySelectorAll(d);for(var e=d.length;0<=--e&&d.item(e)!==this;);return -1<e});W&&(X.prototype[W]="FormData");if(S){var Y=Q.XMLHttpRequest.prototype.setRequestHeader;Q.XMLHttpRequest.prototype.setRequestHeader=function(d,e){Y.call(this,d,e);"content-type"===d.toLowerCase()&&(this.B=true);};Q.XMLHttpRequest.prototype.send=
3811
- function(d){d instanceof X?(d=d._blob(),this.B||this.setRequestHeader("Content-Type",d.type),S.call(this,d)):S.call(this,d);};}T&&(Q.fetch=function(d,e){e&&e.body&&e.body instanceof X&&(e.body=e.body._blob());return T.call(this,d,e)});U&&(Q.navigator.sendBeacon=function(d,e){e instanceof X&&(e=e._asNative());return U.call(this,d,e)});Q.FormData=X;}})();
3812
- return formdata_min;
3813
- }
3814
-
3815
- requireFormdata_min();
3816
-
3817
- class FileService {
3818
- constructor(client) {
3819
- this.client = client;
3820
- }
3821
- rawURL(scope, id) {
3822
- return `box/${scope}/file/${id}/raw`;
3823
- }
3824
- generatedRawURL(scope, id, type) {
3825
- return `box/${scope}/file/${id}/generated/${type}/raw`;
3826
- }
3827
- /**
3828
- * Direct upload
3829
- *
3830
- * @deprecated When behind the proxy service this will often encounter timeout issues
3831
- * its recommended you use another upload method
3832
- *
3833
- * @param scope
3834
- * @param name
3835
- * @param folder_id
3836
- * @param file
3837
- * @returns
3838
- */
3839
- upload(scope, name, folder_id, file) {
3840
- return __awaiter(this, void 0, void 0, function* () {
3841
- // Create form data
3842
- const data = new FormData();
3843
- data.append('name', name);
3844
- data.append('folder_id', folder_id);
3845
- data.append('file', file);
3846
- return this.client.httpPost(`box/${scope}/file`, data, {
3847
- // Clear default JSON content type (We need the browser to set multipart headers properly)
3848
- headers: { 'Content-Type': undefined },
3849
- });
3850
- });
3851
- }
3852
- /**
3853
- * Asynchronous direct upload (File is uploaded directly but processed asynchronously)
3854
- *
3855
- * @param request
3856
- * @returns
3857
- */
3858
- uploadAsync(request) {
3859
- return __awaiter(this, void 0, void 0, function* () {
3860
- // Create form data
3861
- const data = new FormData();
3862
- data.append('name', request.name);
3863
- data.append('folder_id', request.folder_id);
3864
- data.append('file', request.file);
3865
- data.append('asynchronous', 'true');
3866
- if (request.fixed_id) {
3867
- data.append('fixed_id', request.fixed_id);
3868
- }
3869
- const taskResponse = yield this.client.httpPost(`box/${request.scope}/file`, data, {
3870
- // Clear default JSON content type (We need the browser to set multipart headers properly)
3871
- headers: { 'Content-Type': undefined },
3872
- });
3873
- return yield this.client.task.finished(request.scope, taskResponse.task_id, 1000, request.abort);
3874
- });
3875
- }
3876
- uploadPresigned(scope, folderId, file, options) {
3877
- return __awaiter(this, void 0, void 0, function* () {
3878
- if (options && options.onProgress) {
3879
- options.onProgress('Preparing');
3880
- }
3881
- const presigned = yield this.createPresignedUpload(scope, {
3882
- name: file.name,
3883
- folder_id: folderId,
3884
- size: file.size,
3885
- mime: file.type,
3886
- });
3887
- yield this.performPresignedUpload(file, presigned, options);
3888
- if (options && options.onProgress) {
3889
- options.onProgress('Processing');
3890
- }
3891
- const taskId = presigned.task_id;
3892
- const response = yield this.presignedFinished(scope, taskId, 1000, options === null || options === void 0 ? void 0 : options.abort);
3893
- if (options && options.onProgress) {
3894
- options.onProgress('Complete', 1);
3895
- }
3896
- return response;
3897
- });
3898
- }
3899
- performPresignedUpload(file, presigned, options) {
3900
- return __awaiter(this, void 0, void 0, function* () {
3901
- if (options && options.onProgress) {
3902
- options.onProgress('Starting');
3903
- }
3904
- // Browser is not allowed to set this header
3905
- delete presigned.headers['content-length'];
3906
- const config = {
3907
- method: presigned.method,
3908
- url: presigned.uri,
3909
- headers: Object.assign({ 'Content-Type': file.type }, presigned.headers),
3910
- data: file,
3911
- };
3912
- if (options) {
3913
- if (options.onProgress) {
3914
- const onProgress = options.onProgress;
3915
- config.onUploadProgress = (event) => {
3916
- if (!event.progress) {
3917
- onProgress('Uploading');
3918
- return;
3919
- }
3920
- if (event.progress === 1) {
3921
- onProgress('Uploaded', 1);
3922
- }
3923
- else {
3924
- onProgress('Uploading', event.progress);
3925
- }
3926
- };
3927
- }
3928
- // Apply abort signal
3929
- if (options.abort) {
3930
- config.signal = options.abort.signal;
3931
- }
3932
- }
3933
- // Upload the file to the presigned target
3934
- yield axios.request(config);
3935
- });
3936
- }
3937
- createPresignedUpload(scope, request) {
3938
- return this.client.httpPost(`box/${scope}/file/presigned`, request);
3939
- }
3940
- presignedStatus(scope, taskId, abort) {
3941
- return this.client.httpGet(`box/${scope}/file/presigned/${taskId}`, { signal: abort === null || abort === void 0 ? void 0 : abort.signal });
3942
- }
3943
- /**
3944
- * Polls for the completion of a presigned upload task
3945
- *
3946
- * @param scope
3947
- * @param task_id
3948
- * @param abort
3949
- * @returns
3950
- */
3951
- presignedFinished(scope_1, task_id_1) {
3952
- return __awaiter(this, arguments, void 0, function* (scope, task_id, interval = 1000, abort) {
3953
- var _a;
3954
- while (abort === undefined ? true : !abort.signal.aborted) {
3955
- const task = yield this.presignedStatus(scope, task_id, abort);
3956
- if (task.status === 'Complete') {
3957
- return { file: task.file, generated: task.generated };
3958
- }
3959
- if (task.status === 'Failed') {
3960
- const error = (_a = task.error) !== null && _a !== void 0 ? _a : 'Unknown error';
3961
- throw new Error(error);
3962
- }
3963
- yield sleep(interval);
3964
- }
3965
- throw new Error('upload tracking aborted');
3966
- });
3967
- }
3968
- get(scope, file_id) {
3969
- return this.client.httpGet(`box/${scope}/file/${file_id}`);
3970
- }
3971
- editHistory(scope, file_id) {
3972
- return this.client.httpGet(`box/${scope}/file/${file_id}/edit-history`);
3973
- }
3974
- update(scope, file_id, data) {
3975
- return this.client.httpPut(`box/${scope}/file/${file_id}`, data);
3976
- }
3977
- /**
3978
- * Gets the raw file contents of the provided file
3979
- *
3980
- * @param scope
3981
- * @param file_id
3982
- * @returns
3983
- */
3984
- raw(scope, file_id) {
3985
- return this.client.httpGet(this.rawURL(scope, file_id), {
3986
- responseType: 'blob',
3987
- });
3988
- }
3989
- /**
3990
- * Gets the raw file contents of the provided file in
3991
- * JSON format (Will only work if the actual file is JSON)
3992
- *
3993
- * @param scope
3994
- * @param file_id
3995
- * @returns
3996
- */
3997
- json(scope, file_id) {
3998
- return this.client.httpGet(this.rawURL(scope, file_id), {
3999
- responseType: 'json',
4000
- });
4001
- }
4002
- /**
4003
- * Deletes a file
4004
- *
4005
- * @param scope
4006
- * @param file_id
4007
- * @returns
4008
- */
4009
- delete(scope, file_id) {
4010
- return this.client.httpDelete(`box/${scope}/file/${file_id}`);
4011
- }
4012
- /**
4013
- * Gets a generated file details
4014
- *
4015
- * @param scope
4016
- * @param file_id
4017
- * @param type
4018
- * @returns
4019
- */
4020
- generated(scope, file_id, type) {
4021
- return this.client.httpGet(`box/${scope}/file/${file_id}/generated/${type}`);
4022
- }
4023
- /**
4024
- * Gets a generated file raw contents
4025
- *
4026
- * @param scope
4027
- * @param file_id
4028
- * @param type
4029
- * @returns
4030
- */
4031
- generatedRaw(scope, file_id, type) {
4032
- return this.client.httpGet(this.generatedRawURL(scope, file_id, type), {
4033
- responseType: 'blob',
4034
- });
4035
- }
4036
- }
4037
-
4038
- class BoxService {
4039
- constructor(client) {
4040
- this.client = client;
4041
- }
4042
- /**
4043
- * Get a document box for a scope
4044
- *
4045
- * @param scope Scope of the document box to get
4046
- * @param createIfMissing Whether to create the document box if it doesn't exist
4047
- */
4048
- get(scope_1) {
4049
- return __awaiter(this, arguments, void 0, function* (scope, createIfMissing = false) {
4050
- var _a;
4051
- try {
4052
- return yield this.client.httpGet(`box/${scope}`);
4053
- }
4054
- catch (err) {
4055
- // Handle a document box not being created yet
4056
- if (createIfMissing && isAxiosError(err) && ((_a = err.response) === null || _a === void 0 ? void 0 : _a.status) === 404) {
4057
- // Attempt to create the document box
4058
- return this.create(scope, false);
4059
- }
4060
- throw err;
4061
- }
4062
- });
4063
- }
4064
- /**
4065
- * Creates a new document box optional returning an existing one if there is one available
4066
- *
4067
- * @param scope Scope for the document box to create
4068
- * @param allowExisting Whether to allow returning an existing document box (If one is present)
4069
- * @returns The created document box
4070
- */
4071
- create(scope_1) {
4072
- return __awaiter(this, arguments, void 0, function* (scope, allowExisting = true) {
4073
- var _a;
4074
- try {
4075
- return yield this.client.httpPost('box', { scope });
4076
- }
4077
- catch (err) {
4078
- // Handle document box already exists response
4079
- if (allowExisting && isAxiosError(err) && ((_a = err.response) === null || _a === void 0 ? void 0 : _a.status) === 409) {
4080
- return this.get(scope);
4081
- }
4082
- throw err;
4083
- }
4084
- });
4085
- }
4086
- /**
4087
- * Delete a specific document vox
4088
- *
4089
- * @param scope Scope of the document box to delete
4090
- * @returns
4091
- */
4092
- delete(scope) {
4093
- return __awaiter(this, void 0, void 0, function* () {
4094
- return this.client.httpDelete(`box/${scope}`);
4095
- });
4096
- }
4097
- /**
4098
- * Search within the provided document box
4099
- *
4100
- * @param scope The scope of the document box to search
4101
- * @param data Search request data
4102
- * @returns The search results
4103
- */
4104
- search(scope, data) {
4105
- return __awaiter(this, void 0, void 0, function* () {
4106
- return yield this.client.httpPost(`box/${scope}/search`, Object.assign(Object.assign({}, data), { version: 'v2' }));
4107
- });
4108
- }
4109
- /**
4110
- * Get statistics for the provided document box
4111
- *
4112
- * @param scope The scope of the document box
4113
- * @returns The box stats
4114
- */
4115
- stats(scope) {
4116
- return __awaiter(this, void 0, void 0, function* () {
4117
- return yield this.client.httpGet(`box/${scope}/stats`);
4118
- });
4119
- }
4120
- }
4121
-
4122
- class LinkService {
4123
- constructor(client) {
4124
- this.client = client;
4125
- }
4126
- faviconURL(scope, id) {
4127
- return `box/${scope}/link/${id}/favicon`;
4128
- }
4129
- imageURL(scope, id) {
4130
- return `box/${scope}/link/${id}/image`;
4131
- }
4132
- /**
4133
- * Creates a new link
4134
- *
4135
- * @param scope
4136
- * @param data
4137
- * @returns
4138
- */
4139
- create(scope, data) {
4140
- return this.client.httpPost(`box/${scope}/link`, data);
4141
- }
4142
- /**
4143
- * Loads a specific link
4144
- *
4145
- * @param scope
4146
- * @param link_id
4147
- * @returns
4148
- */
4149
- get(scope, link_id) {
4150
- return this.client.httpGet(`box/${scope}/link/${link_id}`);
4151
- }
4152
- /**
4153
- * Get the metadata for a link
4154
- *
4155
- * @param scope
4156
- * @param link_id
4157
- * @returns
4158
- */
4159
- metadata(scope, link_id) {
4160
- return this.client.httpGet(`box/${scope}/link/${link_id}/metadata`);
4161
- }
4162
- /**
4163
- * Get the raw favicon content for a link
4164
- *
4165
- * @param scope
4166
- * @param link_id
4167
- * @returns
4168
- */
4169
- favicon(scope, link_id) {
4170
- return this.client.httpGet(this.faviconURL(scope, link_id), {
4171
- responseType: 'blob',
4172
- });
4173
- }
4174
- /**
4175
- * Get the raw social image for a link
4176
- * @param scope
4177
- * @param link_id
4178
- * @returns
4179
- */
4180
- image(scope, link_id) {
4181
- return this.client.httpGet(this.imageURL(scope, link_id), {
4182
- responseType: 'blob',
4183
- });
4184
- }
4185
- /**
4186
- * Get the edit history for a link
4187
- *
4188
- * @param scope
4189
- * @param link_id
4190
- * @returns
4191
- */
4192
- editHistory(scope, link_id) {
4193
- return this.client.httpGet(`box/${scope}/link/${link_id}/edit-history`);
4194
- }
4195
- /**
4196
- * Updates a link
4197
- *
4198
- * @param scope
4199
- * @param link_id
4200
- * @param data
4201
- * @returns
4202
- */
4203
- update(scope, link_id, data) {
4204
- return this.client.httpPut(`box/${scope}/link/${link_id}`, data);
4205
- }
4206
- /**
4207
- * Deletes the provided link
4208
- *
4209
- * @param scope
4210
- * @param link_id
4211
- * @returns
4212
- */
4213
- delete(scope, link_id) {
4214
- return this.client.httpDelete(`box/${scope}/link/${link_id}`);
4215
- }
4216
- }
4217
-
4218
- class FolderService {
4219
- constructor(client) {
4220
- this.client = client;
4221
- }
4222
- create(scope, data) {
4223
- return this.client.httpPost(`box/${scope}/folder`, data);
4224
- }
4225
- /**
4226
- * Loads a specific folder
4227
- *
4228
- * @param scope
4229
- * @param folder_id
4230
- * @returns
4231
- */
4232
- get(scope, folder_id) {
4233
- return this.client.httpGet(`box/${scope}/folder/${folder_id}`);
4234
- }
4235
- /**
4236
- * Update a folder details
4237
- *
4238
- * @param scope
4239
- * @param folder_id
4240
- * @param data
4241
- * @returns
4242
- */
4243
- update(scope, folder_id, data) {
4244
- return this.client.httpPut(`box/${scope}/folder/${folder_id}`, data);
4245
- }
4246
- /**
4247
- * Deletes the provided folder
4248
- *
4249
- * @param scope
4250
- * @param folder_id
4251
- * @returns
4252
- */
4253
- delete(scope, folder_id) {
4254
- return this.client.httpDelete(`box/${scope}/folder/${folder_id}`);
4255
- }
4256
- /**
4257
- * Load the edit history of a folder
4258
- *
4259
- * @param scope
4260
- * @param folder_id
4261
- * @returns
4262
- */
4263
- editHistory(scope, folder_id) {
4264
- return this.client.httpGet(`box/${scope}/folder/${folder_id}/edit-history`);
4265
- }
4266
- }
4267
-
4268
- class TaskService {
4269
- constructor(client) {
4270
- this.client = client;
4271
- }
4272
- /**
4273
- * Get the current status of a specific task
4274
- *
4275
- * @param scope
4276
- * @param task_id
4277
- * @returns
4278
- */
4279
- get(scope, task_id, abort) {
4280
- return __awaiter(this, void 0, void 0, function* () {
4281
- return this.client.httpGet(`box/${scope}/task/${task_id}`, {
4282
- signal: abort === null || abort === void 0 ? void 0 : abort.signal,
4283
- });
4284
- });
4285
- }
4286
- /**
4287
- * Polls for the completion of a task
4288
- *
4289
- * @param scope
4290
- * @param task_id
4291
- * @param abort
4292
- * @returns
4293
- */
4294
- finished(scope_1, task_id_1) {
4295
- return __awaiter(this, arguments, void 0, function* (scope, task_id, interval = 1000, abort) {
4296
- var _a, _b;
4297
- while (abort === undefined ? true : !abort.signal.aborted) {
4298
- const task = yield this.get(scope, task_id, abort);
4299
- if (task.status === exports.DocboxTaskStatus.Completed) {
4300
- const response = task.output_data;
4301
- return response;
4302
- }
4303
- if (task.status === exports.DocboxTaskStatus.Failed) {
4304
- const error = (_b = (_a = task.output_data) === null || _a === void 0 ? void 0 : _a.error) !== null && _b !== void 0 ? _b : 'Unknown Error';
4305
- throw new Error(error);
4306
- }
4307
- yield sleep(interval);
4308
- }
4309
- throw new Error('upload tracking aborted');
4310
- });
4311
- }
4312
- }
4313
-
4314
- class DocboxClient {
4315
- /**
4316
- * Creates a new docbox
4317
- *
4318
- * @param client
4319
- */
4320
- constructor(client) {
4321
- this.client = client;
4322
- this.documentBox = new BoxService(this);
4323
- this.task = new TaskService(this);
4324
- this.file = new FileService(this);
4325
- this.link = new LinkService(this);
4326
- this.folder = new FolderService(this);
4327
- }
4328
- httpGet(url, config) {
4329
- return __awaiter(this, void 0, void 0, function* () {
4330
- const { data } = yield this.client.get(url, config);
4331
- return data;
4332
- });
4333
- }
4334
- httpPost(url, data, config) {
4335
- return __awaiter(this, void 0, void 0, function* () {
4336
- const { data: responseData } = yield this.client.post(url, data, config);
4337
- return responseData;
4338
- });
4339
- }
4340
- httpPut(url, data, config) {
4341
- return __awaiter(this, void 0, void 0, function* () {
4342
- const { data: responseData } = yield this.client.put(url, data, config);
4343
- return responseData;
4344
- });
4345
- }
4346
- httpPatch(url, data, config) {
4347
- return __awaiter(this, void 0, void 0, function* () {
4348
- const { data: responseData } = yield this.client.patch(url, data, config);
4349
- return responseData;
4350
- });
4351
- }
4352
- httpDelete(url, config) {
4353
- return __awaiter(this, void 0, void 0, function* () {
4354
- const { data: responseData } = yield this.client.delete(url, config);
4355
- return responseData;
4356
- });
4357
- }
4358
- }
4359
-
4360
- let FileGlobal = File;
4361
- // Node targets don't have this available, just mock it.
4362
- // this type should not be used in a node env
4363
- if (FileGlobal === undefined) {
4364
- class MockFile {
4365
- constructor(name, fileParts, options) {
4366
- this.name = name;
4367
- this.fileParts = fileParts;
4368
- this.options = options;
4369
- }
4370
- }
4371
- FileGlobal = MockFile;
4372
- }
4373
- /**
4374
- * Wrapper around the browser File type to allow using a docbox file
4375
- * in place when handling already uploaded files in a form
4376
- */
4377
- class DocboxFile extends FileGlobal {
4378
- get size() {
4379
- return this.file.size;
4380
- }
4381
- constructor(file) {
4382
- super([], file.name, { type: file.mime });
4383
- this.file = file;
4384
- }
4385
- }
4386
-
4387
- exports.DocboxClient = DocboxClient;
4388
- exports.DocboxFile = DocboxFile;
4389
- exports.sleep = sleep;
4390
- //# sourceMappingURL=index.browser.js.map