@xchainjs/xchain-thorchain-amm 2.0.24 → 2.0.26

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 (3) hide show
  1. package/lib/index.esm.js +68 -4477
  2. package/lib/index.js +57 -4466
  3. package/package.json +11 -10
package/lib/index.js CHANGED
@@ -1,3747 +1,21 @@
1
1
  'use strict';
2
2
 
3
3
  var xchainAvax = require('@xchainjs/xchain-avax');
4
- var xchainClient = require('@xchainjs/xchain-client');
5
- var xchainEvm = require('@xchainjs/xchain-evm');
6
- var xchainUtil = require('@xchainjs/xchain-util');
7
- var ethers = require('ethers');
8
- var xchainBitcoin = require('@xchainjs/xchain-bitcoin');
9
- var xchainBitcoincash = require('@xchainjs/xchain-bitcoincash');
10
- var xchainBsc = require('@xchainjs/xchain-bsc');
11
- var xchainCosmos = require('@xchainjs/xchain-cosmos');
12
- var xchainDoge = require('@xchainjs/xchain-doge');
13
- var xchainEthereum = require('@xchainjs/xchain-ethereum');
14
- var xchainLitecoin = require('@xchainjs/xchain-litecoin');
15
- var xchainThorchain = require('@xchainjs/xchain-thorchain');
16
- var xchainThorchainQuery = require('@xchainjs/xchain-thorchain-query');
17
- var xchainWallet = require('@xchainjs/xchain-wallet');
18
-
19
- /******************************************************************************
20
- Copyright (c) Microsoft Corporation.
21
-
22
- Permission to use, copy, modify, and/or distribute this software for any
23
- purpose with or without fee is hereby granted.
24
-
25
- THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
26
- REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
27
- AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
28
- INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
29
- LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
30
- OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
31
- PERFORMANCE OF THIS SOFTWARE.
32
- ***************************************************************************** */
33
- /* global Reflect, Promise, SuppressedError, Symbol, Iterator */
34
-
35
-
36
- function __awaiter$1(thisArg, _arguments, P, generator) {
37
- function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
38
- return new (P || (P = Promise))(function (resolve, reject) {
39
- function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
40
- function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
41
- function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
42
- step((generator = generator.apply(thisArg, _arguments || [])).next());
43
- });
44
- }
45
-
46
- typeof SuppressedError === "function" ? SuppressedError : function (error, suppressed, message) {
47
- var e = new Error(message);
48
- return e.name = "SuppressedError", e.error = error, e.suppressed = suppressed, e;
49
- };
50
-
51
- function bind(fn, thisArg) {
52
- return function wrap() {
53
- return fn.apply(thisArg, arguments);
54
- };
55
- }
56
-
57
- // utils is a library of generic helper functions non-specific to axios
58
-
59
- const {toString} = Object.prototype;
60
- const {getPrototypeOf} = Object;
61
-
62
- const kindOf = (cache => thing => {
63
- const str = toString.call(thing);
64
- return cache[str] || (cache[str] = str.slice(8, -1).toLowerCase());
65
- })(Object.create(null));
66
-
67
- const kindOfTest = (type) => {
68
- type = type.toLowerCase();
69
- return (thing) => kindOf(thing) === type
70
- };
71
-
72
- const typeOfTest = type => thing => typeof thing === type;
73
-
74
- /**
75
- * Determine if a value is an Array
76
- *
77
- * @param {Object} val The value to test
78
- *
79
- * @returns {boolean} True if value is an Array, otherwise false
80
- */
81
- const {isArray} = Array;
82
-
83
- /**
84
- * Determine if a value is undefined
85
- *
86
- * @param {*} val The value to test
87
- *
88
- * @returns {boolean} True if the value is undefined, otherwise false
89
- */
90
- const isUndefined = typeOfTest('undefined');
91
-
92
- /**
93
- * Determine if a value is a Buffer
94
- *
95
- * @param {*} val The value to test
96
- *
97
- * @returns {boolean} True if value is a Buffer, otherwise false
98
- */
99
- function isBuffer(val) {
100
- return val !== null && !isUndefined(val) && val.constructor !== null && !isUndefined(val.constructor)
101
- && isFunction(val.constructor.isBuffer) && val.constructor.isBuffer(val);
102
- }
103
-
104
- /**
105
- * Determine if a value is an ArrayBuffer
106
- *
107
- * @param {*} val The value to test
108
- *
109
- * @returns {boolean} True if value is an ArrayBuffer, otherwise false
110
- */
111
- const isArrayBuffer = kindOfTest('ArrayBuffer');
112
-
113
-
114
- /**
115
- * Determine if a value is a view on an ArrayBuffer
116
- *
117
- * @param {*} val The value to test
118
- *
119
- * @returns {boolean} True if value is a view on an ArrayBuffer, otherwise false
120
- */
121
- function isArrayBufferView(val) {
122
- let result;
123
- if ((typeof ArrayBuffer !== 'undefined') && (ArrayBuffer.isView)) {
124
- result = ArrayBuffer.isView(val);
125
- } else {
126
- result = (val) && (val.buffer) && (isArrayBuffer(val.buffer));
127
- }
128
- return result;
129
- }
130
-
131
- /**
132
- * Determine if a value is a String
133
- *
134
- * @param {*} val The value to test
135
- *
136
- * @returns {boolean} True if value is a String, otherwise false
137
- */
138
- const isString = typeOfTest('string');
139
-
140
- /**
141
- * Determine if a value is a Function
142
- *
143
- * @param {*} val The value to test
144
- * @returns {boolean} True if value is a Function, otherwise false
145
- */
146
- const isFunction = typeOfTest('function');
147
-
148
- /**
149
- * Determine if a value is a Number
150
- *
151
- * @param {*} val The value to test
152
- *
153
- * @returns {boolean} True if value is a Number, otherwise false
154
- */
155
- const isNumber = typeOfTest('number');
156
-
157
- /**
158
- * Determine if a value is an Object
159
- *
160
- * @param {*} thing The value to test
161
- *
162
- * @returns {boolean} True if value is an Object, otherwise false
163
- */
164
- const isObject = (thing) => thing !== null && typeof thing === 'object';
165
-
166
- /**
167
- * Determine if a value is a Boolean
168
- *
169
- * @param {*} thing The value to test
170
- * @returns {boolean} True if value is a Boolean, otherwise false
171
- */
172
- const isBoolean = thing => thing === true || thing === false;
173
-
174
- /**
175
- * Determine if a value is a plain Object
176
- *
177
- * @param {*} val The value to test
178
- *
179
- * @returns {boolean} True if value is a plain Object, otherwise false
180
- */
181
- const isPlainObject = (val) => {
182
- if (kindOf(val) !== 'object') {
183
- return false;
184
- }
185
-
186
- const prototype = getPrototypeOf(val);
187
- return (prototype === null || prototype === Object.prototype || Object.getPrototypeOf(prototype) === null) && !(Symbol.toStringTag in val) && !(Symbol.iterator in val);
188
- };
189
-
190
- /**
191
- * Determine if a value is a Date
192
- *
193
- * @param {*} val The value to test
194
- *
195
- * @returns {boolean} True if value is a Date, otherwise false
196
- */
197
- const isDate = kindOfTest('Date');
198
-
199
- /**
200
- * Determine if a value is a File
201
- *
202
- * @param {*} val The value to test
203
- *
204
- * @returns {boolean} True if value is a File, otherwise false
205
- */
206
- const isFile = kindOfTest('File');
207
-
208
- /**
209
- * Determine if a value is a Blob
210
- *
211
- * @param {*} val The value to test
212
- *
213
- * @returns {boolean} True if value is a Blob, otherwise false
214
- */
215
- const isBlob = kindOfTest('Blob');
216
-
217
- /**
218
- * Determine if a value is a FileList
219
- *
220
- * @param {*} val The value to test
221
- *
222
- * @returns {boolean} True if value is a File, otherwise false
223
- */
224
- const isFileList = kindOfTest('FileList');
225
-
226
- /**
227
- * Determine if a value is a Stream
228
- *
229
- * @param {*} val The value to test
230
- *
231
- * @returns {boolean} True if value is a Stream, otherwise false
232
- */
233
- const isStream = (val) => isObject(val) && isFunction(val.pipe);
234
-
235
- /**
236
- * Determine if a value is a FormData
237
- *
238
- * @param {*} thing The value to test
239
- *
240
- * @returns {boolean} True if value is an FormData, otherwise false
241
- */
242
- const isFormData = (thing) => {
243
- let kind;
244
- return thing && (
245
- (typeof FormData === 'function' && thing instanceof FormData) || (
246
- isFunction(thing.append) && (
247
- (kind = kindOf(thing)) === 'formdata' ||
248
- // detect form-data instance
249
- (kind === 'object' && isFunction(thing.toString) && thing.toString() === '[object FormData]')
250
- )
251
- )
252
- )
253
- };
254
-
255
- /**
256
- * Determine if a value is a URLSearchParams object
257
- *
258
- * @param {*} val The value to test
259
- *
260
- * @returns {boolean} True if value is a URLSearchParams object, otherwise false
261
- */
262
- const isURLSearchParams = kindOfTest('URLSearchParams');
263
-
264
- const [isReadableStream, isRequest, isResponse, isHeaders] = ['ReadableStream', 'Request', 'Response', 'Headers'].map(kindOfTest);
265
-
266
- /**
267
- * Trim excess whitespace off the beginning and end of a string
268
- *
269
- * @param {String} str The String to trim
270
- *
271
- * @returns {String} The String freed of excess whitespace
272
- */
273
- const trim = (str) => str.trim ?
274
- str.trim() : str.replace(/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g, '');
275
-
276
- /**
277
- * Iterate over an Array or an Object invoking a function for each item.
278
- *
279
- * If `obj` is an Array callback will be called passing
280
- * the value, index, and complete array for each item.
281
- *
282
- * If 'obj' is an Object callback will be called passing
283
- * the value, key, and complete object for each property.
284
- *
285
- * @param {Object|Array} obj The object to iterate
286
- * @param {Function} fn The callback to invoke for each item
287
- *
288
- * @param {Boolean} [allOwnKeys = false]
289
- * @returns {any}
290
- */
291
- function forEach(obj, fn, {allOwnKeys = false} = {}) {
292
- // Don't bother if no value provided
293
- if (obj === null || typeof obj === 'undefined') {
294
- return;
295
- }
296
-
297
- let i;
298
- let l;
299
-
300
- // Force an array if not already something iterable
301
- if (typeof obj !== 'object') {
302
- /*eslint no-param-reassign:0*/
303
- obj = [obj];
304
- }
305
-
306
- if (isArray(obj)) {
307
- // Iterate over array values
308
- for (i = 0, l = obj.length; i < l; i++) {
309
- fn.call(null, obj[i], i, obj);
310
- }
311
- } else {
312
- // Iterate over object keys
313
- const keys = allOwnKeys ? Object.getOwnPropertyNames(obj) : Object.keys(obj);
314
- const len = keys.length;
315
- let key;
316
-
317
- for (i = 0; i < len; i++) {
318
- key = keys[i];
319
- fn.call(null, obj[key], key, obj);
320
- }
321
- }
322
- }
323
-
324
- function findKey(obj, key) {
325
- key = key.toLowerCase();
326
- const keys = Object.keys(obj);
327
- let i = keys.length;
328
- let _key;
329
- while (i-- > 0) {
330
- _key = keys[i];
331
- if (key === _key.toLowerCase()) {
332
- return _key;
333
- }
334
- }
335
- return null;
336
- }
337
-
338
- const _global = (() => {
339
- /*eslint no-undef:0*/
340
- if (typeof globalThis !== "undefined") return globalThis;
341
- return typeof self !== "undefined" ? self : (typeof window !== 'undefined' ? window : global)
342
- })();
343
-
344
- const isContextDefined = (context) => !isUndefined(context) && context !== _global;
345
-
346
- /**
347
- * Accepts varargs expecting each argument to be an object, then
348
- * immutably merges the properties of each object and returns result.
349
- *
350
- * When multiple objects contain the same key the later object in
351
- * the arguments list will take precedence.
352
- *
353
- * Example:
354
- *
355
- * ```js
356
- * var result = merge({foo: 123}, {foo: 456});
357
- * console.log(result.foo); // outputs 456
358
- * ```
359
- *
360
- * @param {Object} obj1 Object to merge
361
- *
362
- * @returns {Object} Result of all merge properties
363
- */
364
- function merge(/* obj1, obj2, obj3, ... */) {
365
- const {caseless} = isContextDefined(this) && this || {};
366
- const result = {};
367
- const assignValue = (val, key) => {
368
- const targetKey = caseless && findKey(result, key) || key;
369
- if (isPlainObject(result[targetKey]) && isPlainObject(val)) {
370
- result[targetKey] = merge(result[targetKey], val);
371
- } else if (isPlainObject(val)) {
372
- result[targetKey] = merge({}, val);
373
- } else if (isArray(val)) {
374
- result[targetKey] = val.slice();
375
- } else {
376
- result[targetKey] = val;
377
- }
378
- };
379
-
380
- for (let i = 0, l = arguments.length; i < l; i++) {
381
- arguments[i] && forEach(arguments[i], assignValue);
382
- }
383
- return result;
384
- }
385
-
386
- /**
387
- * Extends object a by mutably adding to it the properties of object b.
388
- *
389
- * @param {Object} a The object to be extended
390
- * @param {Object} b The object to copy properties from
391
- * @param {Object} thisArg The object to bind function to
392
- *
393
- * @param {Boolean} [allOwnKeys]
394
- * @returns {Object} The resulting value of object a
395
- */
396
- const extend = (a, b, thisArg, {allOwnKeys}= {}) => {
397
- forEach(b, (val, key) => {
398
- if (thisArg && isFunction(val)) {
399
- a[key] = bind(val, thisArg);
400
- } else {
401
- a[key] = val;
402
- }
403
- }, {allOwnKeys});
404
- return a;
405
- };
406
-
407
- /**
408
- * Remove byte order marker. This catches EF BB BF (the UTF-8 BOM)
409
- *
410
- * @param {string} content with BOM
411
- *
412
- * @returns {string} content value without BOM
413
- */
414
- const stripBOM = (content) => {
415
- if (content.charCodeAt(0) === 0xFEFF) {
416
- content = content.slice(1);
417
- }
418
- return content;
419
- };
420
-
421
- /**
422
- * Inherit the prototype methods from one constructor into another
423
- * @param {function} constructor
424
- * @param {function} superConstructor
425
- * @param {object} [props]
426
- * @param {object} [descriptors]
427
- *
428
- * @returns {void}
429
- */
430
- const inherits = (constructor, superConstructor, props, descriptors) => {
431
- constructor.prototype = Object.create(superConstructor.prototype, descriptors);
432
- constructor.prototype.constructor = constructor;
433
- Object.defineProperty(constructor, 'super', {
434
- value: superConstructor.prototype
435
- });
436
- props && Object.assign(constructor.prototype, props);
437
- };
438
-
439
- /**
440
- * Resolve object with deep prototype chain to a flat object
441
- * @param {Object} sourceObj source object
442
- * @param {Object} [destObj]
443
- * @param {Function|Boolean} [filter]
444
- * @param {Function} [propFilter]
445
- *
446
- * @returns {Object}
447
- */
448
- const toFlatObject = (sourceObj, destObj, filter, propFilter) => {
449
- let props;
450
- let i;
451
- let prop;
452
- const merged = {};
453
-
454
- destObj = destObj || {};
455
- // eslint-disable-next-line no-eq-null,eqeqeq
456
- if (sourceObj == null) return destObj;
457
-
458
- do {
459
- props = Object.getOwnPropertyNames(sourceObj);
460
- i = props.length;
461
- while (i-- > 0) {
462
- prop = props[i];
463
- if ((!propFilter || propFilter(prop, sourceObj, destObj)) && !merged[prop]) {
464
- destObj[prop] = sourceObj[prop];
465
- merged[prop] = true;
466
- }
467
- }
468
- sourceObj = filter !== false && getPrototypeOf(sourceObj);
469
- } while (sourceObj && (!filter || filter(sourceObj, destObj)) && sourceObj !== Object.prototype);
470
-
471
- return destObj;
472
- };
473
-
474
- /**
475
- * Determines whether a string ends with the characters of a specified string
476
- *
477
- * @param {String} str
478
- * @param {String} searchString
479
- * @param {Number} [position= 0]
480
- *
481
- * @returns {boolean}
482
- */
483
- const endsWith = (str, searchString, position) => {
484
- str = String(str);
485
- if (position === undefined || position > str.length) {
486
- position = str.length;
487
- }
488
- position -= searchString.length;
489
- const lastIndex = str.indexOf(searchString, position);
490
- return lastIndex !== -1 && lastIndex === position;
491
- };
492
-
493
-
494
- /**
495
- * Returns new array from array like object or null if failed
496
- *
497
- * @param {*} [thing]
498
- *
499
- * @returns {?Array}
500
- */
501
- const toArray = (thing) => {
502
- if (!thing) return null;
503
- if (isArray(thing)) return thing;
504
- let i = thing.length;
505
- if (!isNumber(i)) return null;
506
- const arr = new Array(i);
507
- while (i-- > 0) {
508
- arr[i] = thing[i];
509
- }
510
- return arr;
511
- };
512
-
513
- /**
514
- * Checking if the Uint8Array exists and if it does, it returns a function that checks if the
515
- * thing passed in is an instance of Uint8Array
516
- *
517
- * @param {TypedArray}
518
- *
519
- * @returns {Array}
520
- */
521
- // eslint-disable-next-line func-names
522
- const isTypedArray = (TypedArray => {
523
- // eslint-disable-next-line func-names
524
- return thing => {
525
- return TypedArray && thing instanceof TypedArray;
526
- };
527
- })(typeof Uint8Array !== 'undefined' && getPrototypeOf(Uint8Array));
528
-
529
- /**
530
- * For each entry in the object, call the function with the key and value.
531
- *
532
- * @param {Object<any, any>} obj - The object to iterate over.
533
- * @param {Function} fn - The function to call for each entry.
534
- *
535
- * @returns {void}
536
- */
537
- const forEachEntry = (obj, fn) => {
538
- const generator = obj && obj[Symbol.iterator];
539
-
540
- const iterator = generator.call(obj);
541
-
542
- let result;
543
-
544
- while ((result = iterator.next()) && !result.done) {
545
- const pair = result.value;
546
- fn.call(obj, pair[0], pair[1]);
547
- }
548
- };
549
-
550
- /**
551
- * It takes a regular expression and a string, and returns an array of all the matches
552
- *
553
- * @param {string} regExp - The regular expression to match against.
554
- * @param {string} str - The string to search.
555
- *
556
- * @returns {Array<boolean>}
557
- */
558
- const matchAll = (regExp, str) => {
559
- let matches;
560
- const arr = [];
561
-
562
- while ((matches = regExp.exec(str)) !== null) {
563
- arr.push(matches);
564
- }
565
-
566
- return arr;
567
- };
568
-
569
- /* Checking if the kindOfTest function returns true when passed an HTMLFormElement. */
570
- const isHTMLForm = kindOfTest('HTMLFormElement');
571
-
572
- const toCamelCase = str => {
573
- return str.toLowerCase().replace(/[-_\s]([a-z\d])(\w*)/g,
574
- function replacer(m, p1, p2) {
575
- return p1.toUpperCase() + p2;
576
- }
577
- );
578
- };
579
-
580
- /* Creating a function that will check if an object has a property. */
581
- const hasOwnProperty = (({hasOwnProperty}) => (obj, prop) => hasOwnProperty.call(obj, prop))(Object.prototype);
582
-
583
- /**
584
- * Determine if a value is a RegExp object
585
- *
586
- * @param {*} val The value to test
587
- *
588
- * @returns {boolean} True if value is a RegExp object, otherwise false
589
- */
590
- const isRegExp = kindOfTest('RegExp');
591
-
592
- const reduceDescriptors = (obj, reducer) => {
593
- const descriptors = Object.getOwnPropertyDescriptors(obj);
594
- const reducedDescriptors = {};
595
-
596
- forEach(descriptors, (descriptor, name) => {
597
- let ret;
598
- if ((ret = reducer(descriptor, name, obj)) !== false) {
599
- reducedDescriptors[name] = ret || descriptor;
600
- }
601
- });
602
-
603
- Object.defineProperties(obj, reducedDescriptors);
604
- };
605
-
606
- /**
607
- * Makes all methods read-only
608
- * @param {Object} obj
609
- */
610
-
611
- const freezeMethods = (obj) => {
612
- reduceDescriptors(obj, (descriptor, name) => {
613
- // skip restricted props in strict mode
614
- if (isFunction(obj) && ['arguments', 'caller', 'callee'].indexOf(name) !== -1) {
615
- return false;
616
- }
617
-
618
- const value = obj[name];
619
-
620
- if (!isFunction(value)) return;
621
-
622
- descriptor.enumerable = false;
623
-
624
- if ('writable' in descriptor) {
625
- descriptor.writable = false;
626
- return;
627
- }
628
-
629
- if (!descriptor.set) {
630
- descriptor.set = () => {
631
- throw Error('Can not rewrite read-only method \'' + name + '\'');
632
- };
633
- }
634
- });
635
- };
636
-
637
- const toObjectSet = (arrayOrString, delimiter) => {
638
- const obj = {};
639
-
640
- const define = (arr) => {
641
- arr.forEach(value => {
642
- obj[value] = true;
643
- });
644
- };
645
-
646
- isArray(arrayOrString) ? define(arrayOrString) : define(String(arrayOrString).split(delimiter));
647
-
648
- return obj;
649
- };
650
-
651
- const noop = () => {};
652
-
653
- const toFiniteNumber = (value, defaultValue) => {
654
- return value != null && Number.isFinite(value = +value) ? value : defaultValue;
655
- };
656
-
657
- const ALPHA = 'abcdefghijklmnopqrstuvwxyz';
658
-
659
- const DIGIT = '0123456789';
660
-
661
- const ALPHABET = {
662
- DIGIT,
663
- ALPHA,
664
- ALPHA_DIGIT: ALPHA + ALPHA.toUpperCase() + DIGIT
665
- };
666
-
667
- const generateString = (size = 16, alphabet = ALPHABET.ALPHA_DIGIT) => {
668
- let str = '';
669
- const {length} = alphabet;
670
- while (size--) {
671
- str += alphabet[Math.random() * length|0];
672
- }
673
-
674
- return str;
675
- };
676
-
677
- /**
678
- * If the thing is a FormData object, return true, otherwise return false.
679
- *
680
- * @param {unknown} thing - The thing to check.
681
- *
682
- * @returns {boolean}
683
- */
684
- function isSpecCompliantForm(thing) {
685
- return !!(thing && isFunction(thing.append) && thing[Symbol.toStringTag] === 'FormData' && thing[Symbol.iterator]);
686
- }
687
-
688
- const toJSONObject = (obj) => {
689
- const stack = new Array(10);
690
-
691
- const visit = (source, i) => {
692
-
693
- if (isObject(source)) {
694
- if (stack.indexOf(source) >= 0) {
695
- return;
696
- }
697
-
698
- if(!('toJSON' in source)) {
699
- stack[i] = source;
700
- const target = isArray(source) ? [] : {};
701
-
702
- forEach(source, (value, key) => {
703
- const reducedValue = visit(value, i + 1);
704
- !isUndefined(reducedValue) && (target[key] = reducedValue);
705
- });
706
-
707
- stack[i] = undefined;
708
-
709
- return target;
710
- }
711
- }
712
-
713
- return source;
714
- };
715
-
716
- return visit(obj, 0);
717
- };
718
-
719
- const isAsyncFn = kindOfTest('AsyncFunction');
720
-
721
- const isThenable = (thing) =>
722
- thing && (isObject(thing) || isFunction(thing)) && isFunction(thing.then) && isFunction(thing.catch);
723
-
724
- // original code
725
- // https://github.com/DigitalBrainJS/AxiosPromise/blob/16deab13710ec09779922131f3fa5954320f83ab/lib/utils.js#L11-L34
726
-
727
- const _setImmediate = ((setImmediateSupported, postMessageSupported) => {
728
- if (setImmediateSupported) {
729
- return setImmediate;
730
- }
731
-
732
- return postMessageSupported ? ((token, callbacks) => {
733
- _global.addEventListener("message", ({source, data}) => {
734
- if (source === _global && data === token) {
735
- callbacks.length && callbacks.shift()();
736
- }
737
- }, false);
738
-
739
- return (cb) => {
740
- callbacks.push(cb);
741
- _global.postMessage(token, "*");
742
- }
743
- })(`axios@${Math.random()}`, []) : (cb) => setTimeout(cb);
744
- })(
745
- typeof setImmediate === 'function',
746
- isFunction(_global.postMessage)
747
- );
748
-
749
- const asap = typeof queueMicrotask !== 'undefined' ?
750
- queueMicrotask.bind(_global) : ( typeof process !== 'undefined' && process.nextTick || _setImmediate);
751
-
752
- // *********************
753
-
754
- var utils$1 = {
755
- isArray,
756
- isArrayBuffer,
757
- isBuffer,
758
- isFormData,
759
- isArrayBufferView,
760
- isString,
761
- isNumber,
762
- isBoolean,
763
- isObject,
764
- isPlainObject,
765
- isReadableStream,
766
- isRequest,
767
- isResponse,
768
- isHeaders,
769
- isUndefined,
770
- isDate,
771
- isFile,
772
- isBlob,
773
- isRegExp,
774
- isFunction,
775
- isStream,
776
- isURLSearchParams,
777
- isTypedArray,
778
- isFileList,
779
- forEach,
780
- merge,
781
- extend,
782
- trim,
783
- stripBOM,
784
- inherits,
785
- toFlatObject,
786
- kindOf,
787
- kindOfTest,
788
- endsWith,
789
- toArray,
790
- forEachEntry,
791
- matchAll,
792
- isHTMLForm,
793
- hasOwnProperty,
794
- hasOwnProp: hasOwnProperty, // an alias to avoid ESLint no-prototype-builtins detection
795
- reduceDescriptors,
796
- freezeMethods,
797
- toObjectSet,
798
- toCamelCase,
799
- noop,
800
- toFiniteNumber,
801
- findKey,
802
- global: _global,
803
- isContextDefined,
804
- ALPHABET,
805
- generateString,
806
- isSpecCompliantForm,
807
- toJSONObject,
808
- isAsyncFn,
809
- isThenable,
810
- setImmediate: _setImmediate,
811
- asap
812
- };
813
-
814
- /**
815
- * Create an Error with the specified message, config, error code, request and response.
816
- *
817
- * @param {string} message The error message.
818
- * @param {string} [code] The error code (for example, 'ECONNABORTED').
819
- * @param {Object} [config] The config.
820
- * @param {Object} [request] The request.
821
- * @param {Object} [response] The response.
822
- *
823
- * @returns {Error} The created error.
824
- */
825
- function AxiosError(message, code, config, request, response) {
826
- Error.call(this);
827
-
828
- if (Error.captureStackTrace) {
829
- Error.captureStackTrace(this, this.constructor);
830
- } else {
831
- this.stack = (new Error()).stack;
832
- }
833
-
834
- this.message = message;
835
- this.name = 'AxiosError';
836
- code && (this.code = code);
837
- config && (this.config = config);
838
- request && (this.request = request);
839
- response && (this.response = response);
840
- }
841
-
842
- utils$1.inherits(AxiosError, 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.response && this.response.status ? this.response.status : null
860
- };
861
- }
862
- });
863
-
864
- const prototype$1 = AxiosError.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, descriptors);
886
- Object.defineProperty(prototype$1, 'isAxiosError', {value: true});
887
-
888
- // eslint-disable-next-line func-names
889
- AxiosError.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.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(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('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(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} 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
- const serializeFn = options && options.serialize;
1212
-
1213
- let serializedParams;
1214
-
1215
- if (serializeFn) {
1216
- serializedParams = serializeFn(params, options);
1217
- } else {
1218
- serializedParams = utils$1.isURLSearchParams(params) ?
1219
- params.toString() :
1220
- new AxiosURLSearchParams(params, options).toString(_encode);
1221
- }
1222
-
1223
- if (serializedParams) {
1224
- const hashmarkIndex = url.indexOf("#");
1225
-
1226
- if (hashmarkIndex !== -1) {
1227
- url = url.slice(0, hashmarkIndex);
1228
- }
1229
- url += (url.indexOf('?') === -1 ? '?' : '&') + serializedParams;
1230
- }
1231
-
1232
- return url;
1233
- }
1234
-
1235
- class InterceptorManager {
1236
- constructor() {
1237
- this.handlers = [];
1238
- }
1239
-
1240
- /**
1241
- * Add a new interceptor to the stack
1242
- *
1243
- * @param {Function} fulfilled The function to handle `then` for a `Promise`
1244
- * @param {Function} rejected The function to handle `reject` for a `Promise`
1245
- *
1246
- * @return {Number} An ID used to remove interceptor later
1247
- */
1248
- use(fulfilled, rejected, options) {
1249
- this.handlers.push({
1250
- fulfilled,
1251
- rejected,
1252
- synchronous: options ? options.synchronous : false,
1253
- runWhen: options ? options.runWhen : null
1254
- });
1255
- return this.handlers.length - 1;
1256
- }
1257
-
1258
- /**
1259
- * Remove an interceptor from the stack
1260
- *
1261
- * @param {Number} id The ID that was returned by `use`
1262
- *
1263
- * @returns {Boolean} `true` if the interceptor was removed, `false` otherwise
1264
- */
1265
- eject(id) {
1266
- if (this.handlers[id]) {
1267
- this.handlers[id] = null;
1268
- }
1269
- }
1270
-
1271
- /**
1272
- * Clear all interceptors from the stack
1273
- *
1274
- * @returns {void}
1275
- */
1276
- clear() {
1277
- if (this.handlers) {
1278
- this.handlers = [];
1279
- }
1280
- }
1281
-
1282
- /**
1283
- * Iterate over all the registered interceptors
1284
- *
1285
- * This method is particularly useful for skipping over any
1286
- * interceptors that may have become `null` calling `eject`.
1287
- *
1288
- * @param {Function} fn The function to call for each interceptor
1289
- *
1290
- * @returns {void}
1291
- */
1292
- forEach(fn) {
1293
- utils$1.forEach(this.handlers, function forEachHandler(h) {
1294
- if (h !== null) {
1295
- fn(h);
1296
- }
1297
- });
1298
- }
1299
- }
1300
-
1301
- var transitionalDefaults = {
1302
- silentJSONParsing: true,
1303
- forcedJSONParsing: true,
1304
- clarifyTimeoutError: false
1305
- };
1306
-
1307
- var URLSearchParams$1 = typeof URLSearchParams !== 'undefined' ? URLSearchParams : AxiosURLSearchParams;
1308
-
1309
- var FormData$1 = typeof FormData !== 'undefined' ? FormData : null;
1310
-
1311
- var Blob$1 = typeof Blob !== 'undefined' ? Blob : null;
1312
-
1313
- var platform$1 = {
1314
- isBrowser: true,
1315
- classes: {
1316
- URLSearchParams: URLSearchParams$1,
1317
- FormData: FormData$1,
1318
- Blob: Blob$1
1319
- },
1320
- protocols: ['http', 'https', 'file', 'blob', 'url', 'data']
1321
- };
1322
-
1323
- const hasBrowserEnv = typeof window !== 'undefined' && typeof document !== 'undefined';
1324
-
1325
- /**
1326
- * Determine if we're running in a standard browser environment
1327
- *
1328
- * This allows axios to run in a web worker, and react-native.
1329
- * Both environments support XMLHttpRequest, but not fully standard globals.
1330
- *
1331
- * web workers:
1332
- * typeof window -> undefined
1333
- * typeof document -> undefined
1334
- *
1335
- * react-native:
1336
- * navigator.product -> 'ReactNative'
1337
- * nativescript
1338
- * navigator.product -> 'NativeScript' or 'NS'
1339
- *
1340
- * @returns {boolean}
1341
- */
1342
- const hasStandardBrowserEnv = (
1343
- (product) => {
1344
- return hasBrowserEnv && ['ReactNative', 'NativeScript', 'NS'].indexOf(product) < 0
1345
- })(typeof navigator !== 'undefined' && navigator.product);
1346
-
1347
- /**
1348
- * Determine if we're running in a standard browser webWorker environment
1349
- *
1350
- * Although the `isStandardBrowserEnv` method indicates that
1351
- * `allows axios to run in a web worker`, the WebWorker will still be
1352
- * filtered out due to its judgment standard
1353
- * `typeof window !== 'undefined' && typeof document !== 'undefined'`.
1354
- * This leads to a problem when axios post `FormData` in webWorker
1355
- */
1356
- const hasStandardBrowserWebWorkerEnv = (() => {
1357
- return (
1358
- typeof WorkerGlobalScope !== 'undefined' &&
1359
- // eslint-disable-next-line no-undef
1360
- self instanceof WorkerGlobalScope &&
1361
- typeof self.importScripts === 'function'
1362
- );
1363
- })();
1364
-
1365
- const origin = hasBrowserEnv && window.location.href || 'http://localhost';
1366
-
1367
- var utils = /*#__PURE__*/Object.freeze({
1368
- __proto__: null,
1369
- hasBrowserEnv: hasBrowserEnv,
1370
- hasStandardBrowserEnv: hasStandardBrowserEnv,
1371
- hasStandardBrowserWebWorkerEnv: hasStandardBrowserWebWorkerEnv,
1372
- origin: origin
1373
- });
1374
-
1375
- var platform = {
1376
- ...utils,
1377
- ...platform$1
1378
- };
1379
-
1380
- function toURLEncodedForm(data, options) {
1381
- return toFormData(data, new platform.classes.URLSearchParams(), Object.assign({
1382
- visitor: function(value, key, path, helpers) {
1383
- if (platform.isNode && utils$1.isBuffer(value)) {
1384
- this.append(key, value.toString('base64'));
1385
- return false;
1386
- }
1387
-
1388
- return helpers.defaultVisitor.apply(this, arguments);
1389
- }
1390
- }, options));
1391
- }
1392
-
1393
- /**
1394
- * It takes a string like `foo[x][y][z]` and returns an array like `['foo', 'x', 'y', 'z']
1395
- *
1396
- * @param {string} name - The name of the property to get.
1397
- *
1398
- * @returns An array of strings.
1399
- */
1400
- function parsePropPath(name) {
1401
- // foo[x][y][z]
1402
- // foo.x.y.z
1403
- // foo-x-y-z
1404
- // foo x y z
1405
- return utils$1.matchAll(/\w+|\[(\w*)]/g, name).map(match => {
1406
- return match[0] === '[]' ? '' : match[1] || match[0];
1407
- });
1408
- }
1409
-
1410
- /**
1411
- * Convert an array to an object.
1412
- *
1413
- * @param {Array<any>} arr - The array to convert to an object.
1414
- *
1415
- * @returns An object with the same keys and values as the array.
1416
- */
1417
- function arrayToObject(arr) {
1418
- const obj = {};
1419
- const keys = Object.keys(arr);
1420
- let i;
1421
- const len = keys.length;
1422
- let key;
1423
- for (i = 0; i < len; i++) {
1424
- key = keys[i];
1425
- obj[key] = arr[key];
1426
- }
1427
- return obj;
1428
- }
1429
-
1430
- /**
1431
- * It takes a FormData object and returns a JavaScript object
1432
- *
1433
- * @param {string} formData The FormData object to convert to JSON.
1434
- *
1435
- * @returns {Object<string, any> | null} The converted object.
1436
- */
1437
- function formDataToJSON(formData) {
1438
- function buildPath(path, value, target, index) {
1439
- let name = path[index++];
1440
-
1441
- if (name === '__proto__') return true;
1442
-
1443
- const isNumericKey = Number.isFinite(+name);
1444
- const isLast = index >= path.length;
1445
- name = !name && utils$1.isArray(target) ? target.length : name;
1446
-
1447
- if (isLast) {
1448
- if (utils$1.hasOwnProp(target, name)) {
1449
- target[name] = [target[name], value];
1450
- } else {
1451
- target[name] = value;
1452
- }
1453
-
1454
- return !isNumericKey;
1455
- }
1456
-
1457
- if (!target[name] || !utils$1.isObject(target[name])) {
1458
- target[name] = [];
1459
- }
1460
-
1461
- const result = buildPath(path, value, target[name], index);
1462
-
1463
- if (result && utils$1.isArray(target[name])) {
1464
- target[name] = arrayToObject(target[name]);
1465
- }
1466
-
1467
- return !isNumericKey;
1468
- }
1469
-
1470
- if (utils$1.isFormData(formData) && utils$1.isFunction(formData.entries)) {
1471
- const obj = {};
1472
-
1473
- utils$1.forEachEntry(formData, (name, value) => {
1474
- buildPath(parsePropPath(name), value, obj, 0);
1475
- });
1476
-
1477
- return obj;
1478
- }
1479
-
1480
- return null;
1481
- }
1482
-
1483
- /**
1484
- * It takes a string, tries to parse it, and if it fails, it returns the stringified version
1485
- * of the input
1486
- *
1487
- * @param {any} rawValue - The value to be stringified.
1488
- * @param {Function} parser - A function that parses a string into a JavaScript object.
1489
- * @param {Function} encoder - A function that takes a value and returns a string.
1490
- *
1491
- * @returns {string} A stringified version of the rawValue.
1492
- */
1493
- function stringifySafely(rawValue, parser, encoder) {
1494
- if (utils$1.isString(rawValue)) {
1495
- try {
1496
- (parser || JSON.parse)(rawValue);
1497
- return utils$1.trim(rawValue);
1498
- } catch (e) {
1499
- if (e.name !== 'SyntaxError') {
1500
- throw e;
1501
- }
1502
- }
1503
- }
1504
-
1505
- return (0, JSON.stringify)(rawValue);
1506
- }
1507
-
1508
- const defaults$1 = {
1509
-
1510
- transitional: transitionalDefaults,
1511
-
1512
- adapter: ['xhr', 'http', 'fetch'],
1513
-
1514
- transformRequest: [function transformRequest(data, headers) {
1515
- const contentType = headers.getContentType() || '';
1516
- const hasJSONContentType = contentType.indexOf('application/json') > -1;
1517
- const isObjectPayload = utils$1.isObject(data);
1518
-
1519
- if (isObjectPayload && utils$1.isHTMLForm(data)) {
1520
- data = new FormData(data);
1521
- }
1522
-
1523
- const isFormData = utils$1.isFormData(data);
1524
-
1525
- if (isFormData) {
1526
- return hasJSONContentType ? JSON.stringify(formDataToJSON(data)) : data;
1527
- }
1528
-
1529
- if (utils$1.isArrayBuffer(data) ||
1530
- utils$1.isBuffer(data) ||
1531
- utils$1.isStream(data) ||
1532
- utils$1.isFile(data) ||
1533
- utils$1.isBlob(data) ||
1534
- utils$1.isReadableStream(data)
1535
- ) {
1536
- return data;
1537
- }
1538
- if (utils$1.isArrayBufferView(data)) {
1539
- return data.buffer;
1540
- }
1541
- if (utils$1.isURLSearchParams(data)) {
1542
- headers.setContentType('application/x-www-form-urlencoded;charset=utf-8', false);
1543
- return data.toString();
1544
- }
1545
-
1546
- let isFileList;
1547
-
1548
- if (isObjectPayload) {
1549
- if (contentType.indexOf('application/x-www-form-urlencoded') > -1) {
1550
- return toURLEncodedForm(data, this.formSerializer).toString();
1551
- }
1552
-
1553
- if ((isFileList = utils$1.isFileList(data)) || contentType.indexOf('multipart/form-data') > -1) {
1554
- const _FormData = this.env && this.env.FormData;
1555
-
1556
- return toFormData(
1557
- isFileList ? {'files[]': data} : data,
1558
- _FormData && new _FormData(),
1559
- this.formSerializer
1560
- );
1561
- }
1562
- }
1563
-
1564
- if (isObjectPayload || hasJSONContentType ) {
1565
- headers.setContentType('application/json', false);
1566
- return stringifySafely(data);
1567
- }
1568
-
1569
- return data;
1570
- }],
1571
-
1572
- transformResponse: [function transformResponse(data) {
1573
- const transitional = this.transitional || defaults$1.transitional;
1574
- const forcedJSONParsing = transitional && transitional.forcedJSONParsing;
1575
- const JSONRequested = this.responseType === 'json';
1576
-
1577
- if (utils$1.isResponse(data) || utils$1.isReadableStream(data)) {
1578
- return data;
1579
- }
1580
-
1581
- if (data && utils$1.isString(data) && ((forcedJSONParsing && !this.responseType) || JSONRequested)) {
1582
- const silentJSONParsing = transitional && transitional.silentJSONParsing;
1583
- const strictJSONParsing = !silentJSONParsing && JSONRequested;
1584
-
1585
- try {
1586
- return JSON.parse(data);
1587
- } catch (e) {
1588
- if (strictJSONParsing) {
1589
- if (e.name === 'SyntaxError') {
1590
- throw AxiosError.from(e, AxiosError.ERR_BAD_RESPONSE, this, null, this.response);
1591
- }
1592
- throw e;
1593
- }
1594
- }
1595
- }
1596
-
1597
- return data;
1598
- }],
1599
-
1600
- /**
1601
- * A timeout in milliseconds to abort a request. If set to 0 (default) a
1602
- * timeout is not created.
1603
- */
1604
- timeout: 0,
1605
-
1606
- xsrfCookieName: 'XSRF-TOKEN',
1607
- xsrfHeaderName: 'X-XSRF-TOKEN',
1608
-
1609
- maxContentLength: -1,
1610
- maxBodyLength: -1,
1611
-
1612
- env: {
1613
- FormData: platform.classes.FormData,
1614
- Blob: platform.classes.Blob
1615
- },
1616
-
1617
- validateStatus: function validateStatus(status) {
1618
- return status >= 200 && status < 300;
1619
- },
1620
-
1621
- headers: {
1622
- common: {
1623
- 'Accept': 'application/json, text/plain, */*',
1624
- 'Content-Type': undefined
1625
- }
1626
- }
1627
- };
1628
-
1629
- utils$1.forEach(['delete', 'get', 'head', 'post', 'put', 'patch'], (method) => {
1630
- defaults$1.headers[method] = {};
1631
- });
1632
-
1633
- // RawAxiosHeaders whose duplicates are ignored by node
1634
- // c.f. https://nodejs.org/api/http.html#http_message_headers
1635
- const ignoreDuplicateOf = utils$1.toObjectSet([
1636
- 'age', 'authorization', 'content-length', 'content-type', 'etag',
1637
- 'expires', 'from', 'host', 'if-modified-since', 'if-unmodified-since',
1638
- 'last-modified', 'location', 'max-forwards', 'proxy-authorization',
1639
- 'referer', 'retry-after', 'user-agent'
1640
- ]);
1641
-
1642
- /**
1643
- * Parse headers into an object
1644
- *
1645
- * ```
1646
- * Date: Wed, 27 Aug 2014 08:58:49 GMT
1647
- * Content-Type: application/json
1648
- * Connection: keep-alive
1649
- * Transfer-Encoding: chunked
1650
- * ```
1651
- *
1652
- * @param {String} rawHeaders Headers needing to be parsed
1653
- *
1654
- * @returns {Object} Headers parsed into an object
1655
- */
1656
- var parseHeaders = rawHeaders => {
1657
- const parsed = {};
1658
- let key;
1659
- let val;
1660
- let i;
1661
-
1662
- rawHeaders && rawHeaders.split('\n').forEach(function parser(line) {
1663
- i = line.indexOf(':');
1664
- key = line.substring(0, i).trim().toLowerCase();
1665
- val = line.substring(i + 1).trim();
1666
-
1667
- if (!key || (parsed[key] && ignoreDuplicateOf[key])) {
1668
- return;
1669
- }
1670
-
1671
- if (key === 'set-cookie') {
1672
- if (parsed[key]) {
1673
- parsed[key].push(val);
1674
- } else {
1675
- parsed[key] = [val];
1676
- }
1677
- } else {
1678
- parsed[key] = parsed[key] ? parsed[key] + ', ' + val : val;
1679
- }
1680
- });
1681
-
1682
- return parsed;
1683
- };
1684
-
1685
- const $internals = Symbol('internals');
1686
-
1687
- function normalizeHeader(header) {
1688
- return header && String(header).trim().toLowerCase();
1689
- }
1690
-
1691
- function normalizeValue(value) {
1692
- if (value === false || value == null) {
1693
- return value;
1694
- }
1695
-
1696
- return utils$1.isArray(value) ? value.map(normalizeValue) : String(value);
1697
- }
1698
-
1699
- function parseTokens(str) {
1700
- const tokens = Object.create(null);
1701
- const tokensRE = /([^\s,;=]+)\s*(?:=\s*([^,;]+))?/g;
1702
- let match;
1703
-
1704
- while ((match = tokensRE.exec(str))) {
1705
- tokens[match[1]] = match[2];
1706
- }
1707
-
1708
- return tokens;
1709
- }
1710
-
1711
- const isValidHeaderName = (str) => /^[-_a-zA-Z0-9^`|~,!#$%&'*+.]+$/.test(str.trim());
1712
-
1713
- function matchHeaderValue(context, value, header, filter, isHeaderNameFilter) {
1714
- if (utils$1.isFunction(filter)) {
1715
- return filter.call(this, value, header);
1716
- }
1717
-
1718
- if (isHeaderNameFilter) {
1719
- value = header;
1720
- }
1721
-
1722
- if (!utils$1.isString(value)) return;
1723
-
1724
- if (utils$1.isString(filter)) {
1725
- return value.indexOf(filter) !== -1;
1726
- }
1727
-
1728
- if (utils$1.isRegExp(filter)) {
1729
- return filter.test(value);
1730
- }
1731
- }
1732
-
1733
- function formatHeader(header) {
1734
- return header.trim()
1735
- .toLowerCase().replace(/([a-z\d])(\w*)/g, (w, char, str) => {
1736
- return char.toUpperCase() + str;
1737
- });
1738
- }
1739
-
1740
- function buildAccessors(obj, header) {
1741
- const accessorName = utils$1.toCamelCase(' ' + header);
1742
-
1743
- ['get', 'set', 'has'].forEach(methodName => {
1744
- Object.defineProperty(obj, methodName + accessorName, {
1745
- value: function(arg1, arg2, arg3) {
1746
- return this[methodName].call(this, header, arg1, arg2, arg3);
1747
- },
1748
- configurable: true
1749
- });
1750
- });
1751
- }
1752
-
1753
- class AxiosHeaders {
1754
- constructor(headers) {
1755
- headers && this.set(headers);
1756
- }
1757
-
1758
- set(header, valueOrRewrite, rewrite) {
1759
- const self = this;
1760
-
1761
- function setHeader(_value, _header, _rewrite) {
1762
- const lHeader = normalizeHeader(_header);
1763
-
1764
- if (!lHeader) {
1765
- throw new Error('header name must be a non-empty string');
1766
- }
1767
-
1768
- const key = utils$1.findKey(self, lHeader);
1769
-
1770
- if(!key || self[key] === undefined || _rewrite === true || (_rewrite === undefined && self[key] !== false)) {
1771
- self[key || _header] = normalizeValue(_value);
1772
- }
1773
- }
1774
-
1775
- const setHeaders = (headers, _rewrite) =>
1776
- utils$1.forEach(headers, (_value, _header) => setHeader(_value, _header, _rewrite));
1777
-
1778
- if (utils$1.isPlainObject(header) || header instanceof this.constructor) {
1779
- setHeaders(header, valueOrRewrite);
1780
- } else if(utils$1.isString(header) && (header = header.trim()) && !isValidHeaderName(header)) {
1781
- setHeaders(parseHeaders(header), valueOrRewrite);
1782
- } else if (utils$1.isHeaders(header)) {
1783
- for (const [key, value] of header.entries()) {
1784
- setHeader(value, key, rewrite);
1785
- }
1786
- } else {
1787
- header != null && setHeader(valueOrRewrite, header, rewrite);
1788
- }
1789
-
1790
- return this;
1791
- }
1792
-
1793
- get(header, parser) {
1794
- header = normalizeHeader(header);
1795
-
1796
- if (header) {
1797
- const key = utils$1.findKey(this, header);
1798
-
1799
- if (key) {
1800
- const value = this[key];
1801
-
1802
- if (!parser) {
1803
- return value;
1804
- }
1805
-
1806
- if (parser === true) {
1807
- return parseTokens(value);
1808
- }
1809
-
1810
- if (utils$1.isFunction(parser)) {
1811
- return parser.call(this, value, key);
1812
- }
1813
-
1814
- if (utils$1.isRegExp(parser)) {
1815
- return parser.exec(value);
1816
- }
1817
-
1818
- throw new TypeError('parser must be boolean|regexp|function');
1819
- }
1820
- }
1821
- }
1822
-
1823
- has(header, matcher) {
1824
- header = normalizeHeader(header);
1825
-
1826
- if (header) {
1827
- const key = utils$1.findKey(this, header);
1828
-
1829
- return !!(key && this[key] !== undefined && (!matcher || matchHeaderValue(this, this[key], key, matcher)));
1830
- }
1831
-
1832
- return false;
1833
- }
1834
-
1835
- delete(header, matcher) {
1836
- const self = this;
1837
- let deleted = false;
1838
-
1839
- function deleteHeader(_header) {
1840
- _header = normalizeHeader(_header);
1841
-
1842
- if (_header) {
1843
- const key = utils$1.findKey(self, _header);
1844
-
1845
- if (key && (!matcher || matchHeaderValue(self, self[key], key, matcher))) {
1846
- delete self[key];
1847
-
1848
- deleted = true;
1849
- }
1850
- }
1851
- }
1852
-
1853
- if (utils$1.isArray(header)) {
1854
- header.forEach(deleteHeader);
1855
- } else {
1856
- deleteHeader(header);
1857
- }
1858
-
1859
- return deleted;
1860
- }
1861
-
1862
- clear(matcher) {
1863
- const keys = Object.keys(this);
1864
- let i = keys.length;
1865
- let deleted = false;
1866
-
1867
- while (i--) {
1868
- const key = keys[i];
1869
- if(!matcher || matchHeaderValue(this, this[key], key, matcher, true)) {
1870
- delete this[key];
1871
- deleted = true;
1872
- }
1873
- }
1874
-
1875
- return deleted;
1876
- }
1877
-
1878
- normalize(format) {
1879
- const self = this;
1880
- const headers = {};
1881
-
1882
- utils$1.forEach(this, (value, header) => {
1883
- const key = utils$1.findKey(headers, header);
1884
-
1885
- if (key) {
1886
- self[key] = normalizeValue(value);
1887
- delete self[header];
1888
- return;
1889
- }
1890
-
1891
- const normalized = format ? formatHeader(header) : String(header).trim();
1892
-
1893
- if (normalized !== header) {
1894
- delete self[header];
1895
- }
1896
-
1897
- self[normalized] = normalizeValue(value);
1898
-
1899
- headers[normalized] = true;
1900
- });
1901
-
1902
- return this;
1903
- }
1904
-
1905
- concat(...targets) {
1906
- return this.constructor.concat(this, ...targets);
1907
- }
1908
-
1909
- toJSON(asStrings) {
1910
- const obj = Object.create(null);
1911
-
1912
- utils$1.forEach(this, (value, header) => {
1913
- value != null && value !== false && (obj[header] = asStrings && utils$1.isArray(value) ? value.join(', ') : value);
1914
- });
1915
-
1916
- return obj;
1917
- }
1918
-
1919
- [Symbol.iterator]() {
1920
- return Object.entries(this.toJSON())[Symbol.iterator]();
1921
- }
1922
-
1923
- toString() {
1924
- return Object.entries(this.toJSON()).map(([header, value]) => header + ': ' + value).join('\n');
1925
- }
1926
-
1927
- get [Symbol.toStringTag]() {
1928
- return 'AxiosHeaders';
1929
- }
1930
-
1931
- static from(thing) {
1932
- return thing instanceof this ? thing : new this(thing);
1933
- }
1934
-
1935
- static concat(first, ...targets) {
1936
- const computed = new this(first);
1937
-
1938
- targets.forEach((target) => computed.set(target));
1939
-
1940
- return computed;
1941
- }
1942
-
1943
- static accessor(header) {
1944
- const internals = this[$internals] = (this[$internals] = {
1945
- accessors: {}
1946
- });
1947
-
1948
- const accessors = internals.accessors;
1949
- const prototype = this.prototype;
1950
-
1951
- function defineAccessor(_header) {
1952
- const lHeader = normalizeHeader(_header);
1953
-
1954
- if (!accessors[lHeader]) {
1955
- buildAccessors(prototype, _header);
1956
- accessors[lHeader] = true;
1957
- }
1958
- }
1959
-
1960
- utils$1.isArray(header) ? header.forEach(defineAccessor) : defineAccessor(header);
1961
-
1962
- return this;
1963
- }
1964
- }
1965
-
1966
- AxiosHeaders.accessor(['Content-Type', 'Content-Length', 'Accept', 'Accept-Encoding', 'User-Agent', 'Authorization']);
1967
-
1968
- // reserved names hotfix
1969
- utils$1.reduceDescriptors(AxiosHeaders.prototype, ({value}, key) => {
1970
- let mapped = key[0].toUpperCase() + key.slice(1); // map `set` => `Set`
1971
- return {
1972
- get: () => value,
1973
- set(headerValue) {
1974
- this[mapped] = headerValue;
1975
- }
1976
- }
1977
- });
1978
-
1979
- utils$1.freezeMethods(AxiosHeaders);
1980
-
1981
- /**
1982
- * Transform the data for a request or a response
1983
- *
1984
- * @param {Array|Function} fns A single function or Array of functions
1985
- * @param {?Object} response The response object
1986
- *
1987
- * @returns {*} The resulting transformed data
1988
- */
1989
- function transformData(fns, response) {
1990
- const config = this || defaults$1;
1991
- const context = response || config;
1992
- const headers = AxiosHeaders.from(context.headers);
1993
- let data = context.data;
1994
-
1995
- utils$1.forEach(fns, function transform(fn) {
1996
- data = fn.call(config, data, headers.normalize(), response ? response.status : undefined);
1997
- });
1998
-
1999
- headers.normalize();
2000
-
2001
- return data;
2002
- }
2003
-
2004
- function isCancel(value) {
2005
- return !!(value && value.__CANCEL__);
2006
- }
2007
-
2008
- /**
2009
- * A `CanceledError` is an object that is thrown when an operation is canceled.
2010
- *
2011
- * @param {string=} message The message.
2012
- * @param {Object=} config The config.
2013
- * @param {Object=} request The request.
2014
- *
2015
- * @returns {CanceledError} The created error.
2016
- */
2017
- function CanceledError(message, config, request) {
2018
- // eslint-disable-next-line no-eq-null,eqeqeq
2019
- AxiosError.call(this, message == null ? 'canceled' : message, AxiosError.ERR_CANCELED, config, request);
2020
- this.name = 'CanceledError';
2021
- }
2022
-
2023
- utils$1.inherits(CanceledError, AxiosError, {
2024
- __CANCEL__: true
2025
- });
2026
-
2027
- /**
2028
- * Resolve or reject a Promise based on response status.
2029
- *
2030
- * @param {Function} resolve A function that resolves the promise.
2031
- * @param {Function} reject A function that rejects the promise.
2032
- * @param {object} response The response.
2033
- *
2034
- * @returns {object} The response.
2035
- */
2036
- function settle(resolve, reject, response) {
2037
- const validateStatus = response.config.validateStatus;
2038
- if (!response.status || !validateStatus || validateStatus(response.status)) {
2039
- resolve(response);
2040
- } else {
2041
- reject(new AxiosError(
2042
- 'Request failed with status code ' + response.status,
2043
- [AxiosError.ERR_BAD_REQUEST, AxiosError.ERR_BAD_RESPONSE][Math.floor(response.status / 100) - 4],
2044
- response.config,
2045
- response.request,
2046
- response
2047
- ));
2048
- }
2049
- }
2050
-
2051
- function parseProtocol(url) {
2052
- const match = /^([-+\w]{1,25})(:?\/\/|:)/.exec(url);
2053
- return match && match[1] || '';
2054
- }
2055
-
2056
- /**
2057
- * Calculate data maxRate
2058
- * @param {Number} [samplesCount= 10]
2059
- * @param {Number} [min= 1000]
2060
- * @returns {Function}
2061
- */
2062
- function speedometer(samplesCount, min) {
2063
- samplesCount = samplesCount || 10;
2064
- const bytes = new Array(samplesCount);
2065
- const timestamps = new Array(samplesCount);
2066
- let head = 0;
2067
- let tail = 0;
2068
- let firstSampleTS;
2069
-
2070
- min = min !== undefined ? min : 1000;
2071
-
2072
- return function push(chunkLength) {
2073
- const now = Date.now();
2074
-
2075
- const startedAt = timestamps[tail];
2076
-
2077
- if (!firstSampleTS) {
2078
- firstSampleTS = now;
2079
- }
2080
-
2081
- bytes[head] = chunkLength;
2082
- timestamps[head] = now;
2083
-
2084
- let i = tail;
2085
- let bytesCount = 0;
2086
-
2087
- while (i !== head) {
2088
- bytesCount += bytes[i++];
2089
- i = i % samplesCount;
2090
- }
2091
-
2092
- head = (head + 1) % samplesCount;
2093
-
2094
- if (head === tail) {
2095
- tail = (tail + 1) % samplesCount;
2096
- }
2097
-
2098
- if (now - firstSampleTS < min) {
2099
- return;
2100
- }
2101
-
2102
- const passed = startedAt && now - startedAt;
2103
-
2104
- return passed ? Math.round(bytesCount * 1000 / passed) : undefined;
2105
- };
2106
- }
2107
-
2108
- /**
2109
- * Throttle decorator
2110
- * @param {Function} fn
2111
- * @param {Number} freq
2112
- * @return {Function}
2113
- */
2114
- function throttle(fn, freq) {
2115
- let timestamp = 0;
2116
- let threshold = 1000 / freq;
2117
- let lastArgs;
2118
- let timer;
2119
-
2120
- const invoke = (args, now = Date.now()) => {
2121
- timestamp = now;
2122
- lastArgs = null;
2123
- if (timer) {
2124
- clearTimeout(timer);
2125
- timer = null;
2126
- }
2127
- fn.apply(null, args);
2128
- };
2129
-
2130
- const throttled = (...args) => {
2131
- const now = Date.now();
2132
- const passed = now - timestamp;
2133
- if ( passed >= threshold) {
2134
- invoke(args, now);
2135
- } else {
2136
- lastArgs = args;
2137
- if (!timer) {
2138
- timer = setTimeout(() => {
2139
- timer = null;
2140
- invoke(lastArgs);
2141
- }, threshold - passed);
2142
- }
2143
- }
2144
- };
2145
-
2146
- const flush = () => lastArgs && invoke(lastArgs);
2147
-
2148
- return [throttled, flush];
2149
- }
2150
-
2151
- const progressEventReducer = (listener, isDownloadStream, freq = 3) => {
2152
- let bytesNotified = 0;
2153
- const _speedometer = speedometer(50, 250);
2154
-
2155
- return throttle(e => {
2156
- const loaded = e.loaded;
2157
- const total = e.lengthComputable ? e.total : undefined;
2158
- const progressBytes = loaded - bytesNotified;
2159
- const rate = _speedometer(progressBytes);
2160
- const inRange = loaded <= total;
2161
-
2162
- bytesNotified = loaded;
2163
-
2164
- const data = {
2165
- loaded,
2166
- total,
2167
- progress: total ? (loaded / total) : undefined,
2168
- bytes: progressBytes,
2169
- rate: rate ? rate : undefined,
2170
- estimated: rate && total && inRange ? (total - loaded) / rate : undefined,
2171
- event: e,
2172
- lengthComputable: total != null,
2173
- [isDownloadStream ? 'download' : 'upload']: true
2174
- };
2175
-
2176
- listener(data);
2177
- }, freq);
2178
- };
2179
-
2180
- const progressEventDecorator = (total, throttled) => {
2181
- const lengthComputable = total != null;
2182
-
2183
- return [(loaded) => throttled[0]({
2184
- lengthComputable,
2185
- total,
2186
- loaded
2187
- }), throttled[1]];
2188
- };
2189
-
2190
- const asyncDecorator = (fn) => (...args) => utils$1.asap(() => fn(...args));
2191
-
2192
- var isURLSameOrigin = platform.hasStandardBrowserEnv ?
2193
-
2194
- // Standard browser envs have full support of the APIs needed to test
2195
- // whether the request URL is of the same origin as current location.
2196
- (function standardBrowserEnv() {
2197
- const msie = /(msie|trident)/i.test(navigator.userAgent);
2198
- const urlParsingNode = document.createElement('a');
2199
- let originURL;
2200
-
2201
- /**
2202
- * Parse a URL to discover its components
2203
- *
2204
- * @param {String} url The URL to be parsed
2205
- * @returns {Object}
2206
- */
2207
- function resolveURL(url) {
2208
- let href = url;
2209
-
2210
- if (msie) {
2211
- // IE needs attribute set twice to normalize properties
2212
- urlParsingNode.setAttribute('href', href);
2213
- href = urlParsingNode.href;
2214
- }
2215
-
2216
- urlParsingNode.setAttribute('href', href);
2217
-
2218
- // urlParsingNode provides the UrlUtils interface - http://url.spec.whatwg.org/#urlutils
2219
- return {
2220
- href: urlParsingNode.href,
2221
- protocol: urlParsingNode.protocol ? urlParsingNode.protocol.replace(/:$/, '') : '',
2222
- host: urlParsingNode.host,
2223
- search: urlParsingNode.search ? urlParsingNode.search.replace(/^\?/, '') : '',
2224
- hash: urlParsingNode.hash ? urlParsingNode.hash.replace(/^#/, '') : '',
2225
- hostname: urlParsingNode.hostname,
2226
- port: urlParsingNode.port,
2227
- pathname: (urlParsingNode.pathname.charAt(0) === '/') ?
2228
- urlParsingNode.pathname :
2229
- '/' + urlParsingNode.pathname
2230
- };
2231
- }
2232
-
2233
- originURL = resolveURL(window.location.href);
2234
-
2235
- /**
2236
- * Determine if a URL shares the same origin as the current location
2237
- *
2238
- * @param {String} requestURL The URL to test
2239
- * @returns {boolean} True if URL shares the same origin, otherwise false
2240
- */
2241
- return function isURLSameOrigin(requestURL) {
2242
- const parsed = (utils$1.isString(requestURL)) ? resolveURL(requestURL) : requestURL;
2243
- return (parsed.protocol === originURL.protocol &&
2244
- parsed.host === originURL.host);
2245
- };
2246
- })() :
2247
-
2248
- // Non standard browser envs (web workers, react-native) lack needed support.
2249
- (function nonStandardBrowserEnv() {
2250
- return function isURLSameOrigin() {
2251
- return true;
2252
- };
2253
- })();
2254
-
2255
- var cookies = platform.hasStandardBrowserEnv ?
2256
-
2257
- // Standard browser envs support document.cookie
2258
- {
2259
- write(name, value, expires, path, domain, secure) {
2260
- const cookie = [name + '=' + encodeURIComponent(value)];
2261
-
2262
- utils$1.isNumber(expires) && cookie.push('expires=' + new Date(expires).toGMTString());
2263
-
2264
- utils$1.isString(path) && cookie.push('path=' + path);
2265
-
2266
- utils$1.isString(domain) && cookie.push('domain=' + domain);
2267
-
2268
- secure === true && cookie.push('secure');
2269
-
2270
- document.cookie = cookie.join('; ');
2271
- },
2272
-
2273
- read(name) {
2274
- const match = document.cookie.match(new RegExp('(^|;\\s*)(' + name + ')=([^;]*)'));
2275
- return (match ? decodeURIComponent(match[3]) : null);
2276
- },
2277
-
2278
- remove(name) {
2279
- this.write(name, '', Date.now() - 86400000);
2280
- }
2281
- }
2282
-
2283
- :
2284
-
2285
- // Non-standard browser env (web workers, react-native) lack needed support.
2286
- {
2287
- write() {},
2288
- read() {
2289
- return null;
2290
- },
2291
- remove() {}
2292
- };
2293
-
2294
- /**
2295
- * Determines whether the specified URL is absolute
2296
- *
2297
- * @param {string} url The URL to test
2298
- *
2299
- * @returns {boolean} True if the specified URL is absolute, otherwise false
2300
- */
2301
- function isAbsoluteURL(url) {
2302
- // A URL is considered absolute if it begins with "<scheme>://" or "//" (protocol-relative URL).
2303
- // RFC 3986 defines scheme name as a sequence of characters beginning with a letter and followed
2304
- // by any combination of letters, digits, plus, period, or hyphen.
2305
- return /^([a-z][a-z\d+\-.]*:)?\/\//i.test(url);
2306
- }
2307
-
2308
- /**
2309
- * Creates a new URL by combining the specified URLs
2310
- *
2311
- * @param {string} baseURL The base URL
2312
- * @param {string} relativeURL The relative URL
2313
- *
2314
- * @returns {string} The combined URL
2315
- */
2316
- function combineURLs(baseURL, relativeURL) {
2317
- return relativeURL
2318
- ? baseURL.replace(/\/?\/$/, '') + '/' + relativeURL.replace(/^\/+/, '')
2319
- : baseURL;
2320
- }
2321
-
2322
- /**
2323
- * Creates a new URL by combining the baseURL with the requestedURL,
2324
- * only when the requestedURL is not already an absolute URL.
2325
- * If the requestURL is absolute, this function returns the requestedURL untouched.
2326
- *
2327
- * @param {string} baseURL The base URL
2328
- * @param {string} requestedURL Absolute or relative URL to combine
2329
- *
2330
- * @returns {string} The combined full path
2331
- */
2332
- function buildFullPath(baseURL, requestedURL) {
2333
- if (baseURL && !isAbsoluteURL(requestedURL)) {
2334
- return combineURLs(baseURL, requestedURL);
2335
- }
2336
- return requestedURL;
2337
- }
2338
-
2339
- const headersToObject = (thing) => thing instanceof AxiosHeaders ? { ...thing } : thing;
2340
-
2341
- /**
2342
- * Config-specific merge-function which creates a new config-object
2343
- * by merging two configuration objects together.
2344
- *
2345
- * @param {Object} config1
2346
- * @param {Object} config2
2347
- *
2348
- * @returns {Object} New object resulting from merging config2 to config1
2349
- */
2350
- function mergeConfig(config1, config2) {
2351
- // eslint-disable-next-line no-param-reassign
2352
- config2 = config2 || {};
2353
- const config = {};
2354
-
2355
- function getMergedValue(target, source, caseless) {
2356
- if (utils$1.isPlainObject(target) && utils$1.isPlainObject(source)) {
2357
- return utils$1.merge.call({caseless}, target, source);
2358
- } else if (utils$1.isPlainObject(source)) {
2359
- return utils$1.merge({}, source);
2360
- } else if (utils$1.isArray(source)) {
2361
- return source.slice();
2362
- }
2363
- return source;
2364
- }
2365
-
2366
- // eslint-disable-next-line consistent-return
2367
- function mergeDeepProperties(a, b, caseless) {
2368
- if (!utils$1.isUndefined(b)) {
2369
- return getMergedValue(a, b, caseless);
2370
- } else if (!utils$1.isUndefined(a)) {
2371
- return getMergedValue(undefined, a, caseless);
2372
- }
2373
- }
2374
-
2375
- // eslint-disable-next-line consistent-return
2376
- function valueFromConfig2(a, b) {
2377
- if (!utils$1.isUndefined(b)) {
2378
- return getMergedValue(undefined, b);
2379
- }
2380
- }
2381
-
2382
- // eslint-disable-next-line consistent-return
2383
- function defaultToConfig2(a, b) {
2384
- if (!utils$1.isUndefined(b)) {
2385
- return getMergedValue(undefined, b);
2386
- } else if (!utils$1.isUndefined(a)) {
2387
- return getMergedValue(undefined, a);
2388
- }
2389
- }
2390
-
2391
- // eslint-disable-next-line consistent-return
2392
- function mergeDirectKeys(a, b, prop) {
2393
- if (prop in config2) {
2394
- return getMergedValue(a, b);
2395
- } else if (prop in config1) {
2396
- return getMergedValue(undefined, a);
2397
- }
2398
- }
2399
-
2400
- const mergeMap = {
2401
- url: valueFromConfig2,
2402
- method: valueFromConfig2,
2403
- data: valueFromConfig2,
2404
- baseURL: defaultToConfig2,
2405
- transformRequest: defaultToConfig2,
2406
- transformResponse: defaultToConfig2,
2407
- paramsSerializer: defaultToConfig2,
2408
- timeout: defaultToConfig2,
2409
- timeoutMessage: defaultToConfig2,
2410
- withCredentials: defaultToConfig2,
2411
- withXSRFToken: defaultToConfig2,
2412
- adapter: defaultToConfig2,
2413
- responseType: defaultToConfig2,
2414
- xsrfCookieName: defaultToConfig2,
2415
- xsrfHeaderName: defaultToConfig2,
2416
- onUploadProgress: defaultToConfig2,
2417
- onDownloadProgress: defaultToConfig2,
2418
- decompress: defaultToConfig2,
2419
- maxContentLength: defaultToConfig2,
2420
- maxBodyLength: defaultToConfig2,
2421
- beforeRedirect: defaultToConfig2,
2422
- transport: defaultToConfig2,
2423
- httpAgent: defaultToConfig2,
2424
- httpsAgent: defaultToConfig2,
2425
- cancelToken: defaultToConfig2,
2426
- socketPath: defaultToConfig2,
2427
- responseEncoding: defaultToConfig2,
2428
- validateStatus: mergeDirectKeys,
2429
- headers: (a, b) => mergeDeepProperties(headersToObject(a), headersToObject(b), true)
2430
- };
2431
-
2432
- utils$1.forEach(Object.keys(Object.assign({}, config1, config2)), function computeConfigValue(prop) {
2433
- const merge = mergeMap[prop] || mergeDeepProperties;
2434
- const configValue = merge(config1[prop], config2[prop], prop);
2435
- (utils$1.isUndefined(configValue) && merge !== mergeDirectKeys) || (config[prop] = configValue);
2436
- });
2437
-
2438
- return config;
2439
- }
2440
-
2441
- var resolveConfig = (config) => {
2442
- const newConfig = mergeConfig({}, config);
2443
-
2444
- let {data, withXSRFToken, xsrfHeaderName, xsrfCookieName, headers, auth} = newConfig;
2445
-
2446
- newConfig.headers = headers = AxiosHeaders.from(headers);
2447
-
2448
- newConfig.url = buildURL(buildFullPath(newConfig.baseURL, newConfig.url), config.params, config.paramsSerializer);
2449
-
2450
- // HTTP basic authentication
2451
- if (auth) {
2452
- headers.set('Authorization', 'Basic ' +
2453
- btoa((auth.username || '') + ':' + (auth.password ? unescape(encodeURIComponent(auth.password)) : ''))
2454
- );
2455
- }
2456
-
2457
- let contentType;
2458
-
2459
- if (utils$1.isFormData(data)) {
2460
- if (platform.hasStandardBrowserEnv || platform.hasStandardBrowserWebWorkerEnv) {
2461
- headers.setContentType(undefined); // Let the browser set it
2462
- } else if ((contentType = headers.getContentType()) !== false) {
2463
- // fix semicolon duplication issue for ReactNative FormData implementation
2464
- const [type, ...tokens] = contentType ? contentType.split(';').map(token => token.trim()).filter(Boolean) : [];
2465
- headers.setContentType([type || 'multipart/form-data', ...tokens].join('; '));
2466
- }
2467
- }
2468
-
2469
- // Add xsrf header
2470
- // This is only done if running in a standard browser environment.
2471
- // Specifically not if we're in a web worker, or react-native.
2472
-
2473
- if (platform.hasStandardBrowserEnv) {
2474
- withXSRFToken && utils$1.isFunction(withXSRFToken) && (withXSRFToken = withXSRFToken(newConfig));
2475
-
2476
- if (withXSRFToken || (withXSRFToken !== false && isURLSameOrigin(newConfig.url))) {
2477
- // Add xsrf header
2478
- const xsrfValue = xsrfHeaderName && xsrfCookieName && cookies.read(xsrfCookieName);
2479
-
2480
- if (xsrfValue) {
2481
- headers.set(xsrfHeaderName, xsrfValue);
2482
- }
2483
- }
2484
- }
2485
-
2486
- return newConfig;
2487
- };
2488
-
2489
- const isXHRAdapterSupported = typeof XMLHttpRequest !== 'undefined';
2490
-
2491
- var xhrAdapter = isXHRAdapterSupported && function (config) {
2492
- return new Promise(function dispatchXhrRequest(resolve, reject) {
2493
- const _config = resolveConfig(config);
2494
- let requestData = _config.data;
2495
- const requestHeaders = AxiosHeaders.from(_config.headers).normalize();
2496
- let {responseType, onUploadProgress, onDownloadProgress} = _config;
2497
- let onCanceled;
2498
- let uploadThrottled, downloadThrottled;
2499
- let flushUpload, flushDownload;
2500
-
2501
- function done() {
2502
- flushUpload && flushUpload(); // flush events
2503
- flushDownload && flushDownload(); // flush events
2504
-
2505
- _config.cancelToken && _config.cancelToken.unsubscribe(onCanceled);
2506
-
2507
- _config.signal && _config.signal.removeEventListener('abort', onCanceled);
2508
- }
2509
-
2510
- let request = new XMLHttpRequest();
2511
-
2512
- request.open(_config.method.toUpperCase(), _config.url, true);
2513
-
2514
- // Set the request timeout in MS
2515
- request.timeout = _config.timeout;
2516
-
2517
- function onloadend() {
2518
- if (!request) {
2519
- return;
2520
- }
2521
- // Prepare the response
2522
- const responseHeaders = AxiosHeaders.from(
2523
- 'getAllResponseHeaders' in request && request.getAllResponseHeaders()
2524
- );
2525
- const responseData = !responseType || responseType === 'text' || responseType === 'json' ?
2526
- request.responseText : request.response;
2527
- const response = {
2528
- data: responseData,
2529
- status: request.status,
2530
- statusText: request.statusText,
2531
- headers: responseHeaders,
2532
- config,
2533
- request
2534
- };
2535
-
2536
- settle(function _resolve(value) {
2537
- resolve(value);
2538
- done();
2539
- }, function _reject(err) {
2540
- reject(err);
2541
- done();
2542
- }, response);
2543
-
2544
- // Clean up request
2545
- request = null;
2546
- }
2547
-
2548
- if ('onloadend' in request) {
2549
- // Use onloadend if available
2550
- request.onloadend = onloadend;
2551
- } else {
2552
- // Listen for ready state to emulate onloadend
2553
- request.onreadystatechange = function handleLoad() {
2554
- if (!request || request.readyState !== 4) {
2555
- return;
2556
- }
2557
-
2558
- // The request errored out and we didn't get a response, this will be
2559
- // handled by onerror instead
2560
- // With one exception: request that using file: protocol, most browsers
2561
- // will return status as 0 even though it's a successful request
2562
- if (request.status === 0 && !(request.responseURL && request.responseURL.indexOf('file:') === 0)) {
2563
- return;
2564
- }
2565
- // readystate handler is calling before onerror or ontimeout handlers,
2566
- // so we should call onloadend on the next 'tick'
2567
- setTimeout(onloadend);
2568
- };
2569
- }
2570
-
2571
- // Handle browser request cancellation (as opposed to a manual cancellation)
2572
- request.onabort = function handleAbort() {
2573
- if (!request) {
2574
- return;
2575
- }
2576
-
2577
- reject(new AxiosError('Request aborted', AxiosError.ECONNABORTED, config, request));
2578
-
2579
- // Clean up request
2580
- request = null;
2581
- };
2582
-
2583
- // Handle low level network errors
2584
- request.onerror = function handleError() {
2585
- // Real errors are hidden from us by the browser
2586
- // onerror should only fire if it's a network error
2587
- reject(new AxiosError('Network Error', AxiosError.ERR_NETWORK, config, request));
2588
-
2589
- // Clean up request
2590
- request = null;
2591
- };
2592
-
2593
- // Handle timeout
2594
- request.ontimeout = function handleTimeout() {
2595
- let timeoutErrorMessage = _config.timeout ? 'timeout of ' + _config.timeout + 'ms exceeded' : 'timeout exceeded';
2596
- const transitional = _config.transitional || transitionalDefaults;
2597
- if (_config.timeoutErrorMessage) {
2598
- timeoutErrorMessage = _config.timeoutErrorMessage;
2599
- }
2600
- reject(new AxiosError(
2601
- timeoutErrorMessage,
2602
- transitional.clarifyTimeoutError ? AxiosError.ETIMEDOUT : AxiosError.ECONNABORTED,
2603
- config,
2604
- request));
2605
-
2606
- // Clean up request
2607
- request = null;
2608
- };
2609
-
2610
- // Remove Content-Type if data is undefined
2611
- requestData === undefined && requestHeaders.setContentType(null);
2612
-
2613
- // Add headers to the request
2614
- if ('setRequestHeader' in request) {
2615
- utils$1.forEach(requestHeaders.toJSON(), function setRequestHeader(val, key) {
2616
- request.setRequestHeader(key, val);
2617
- });
2618
- }
2619
-
2620
- // Add withCredentials to request if needed
2621
- if (!utils$1.isUndefined(_config.withCredentials)) {
2622
- request.withCredentials = !!_config.withCredentials;
2623
- }
2624
-
2625
- // Add responseType to request if needed
2626
- if (responseType && responseType !== 'json') {
2627
- request.responseType = _config.responseType;
2628
- }
2629
-
2630
- // Handle progress if needed
2631
- if (onDownloadProgress) {
2632
- ([downloadThrottled, flushDownload] = progressEventReducer(onDownloadProgress, true));
2633
- request.addEventListener('progress', downloadThrottled);
2634
- }
2635
-
2636
- // Not all browsers support upload events
2637
- if (onUploadProgress && request.upload) {
2638
- ([uploadThrottled, flushUpload] = progressEventReducer(onUploadProgress));
2639
-
2640
- request.upload.addEventListener('progress', uploadThrottled);
2641
-
2642
- request.upload.addEventListener('loadend', flushUpload);
2643
- }
2644
-
2645
- if (_config.cancelToken || _config.signal) {
2646
- // Handle cancellation
2647
- // eslint-disable-next-line func-names
2648
- onCanceled = cancel => {
2649
- if (!request) {
2650
- return;
2651
- }
2652
- reject(!cancel || cancel.type ? new CanceledError(null, config, request) : cancel);
2653
- request.abort();
2654
- request = null;
2655
- };
2656
-
2657
- _config.cancelToken && _config.cancelToken.subscribe(onCanceled);
2658
- if (_config.signal) {
2659
- _config.signal.aborted ? onCanceled() : _config.signal.addEventListener('abort', onCanceled);
2660
- }
2661
- }
2662
-
2663
- const protocol = parseProtocol(_config.url);
2664
-
2665
- if (protocol && platform.protocols.indexOf(protocol) === -1) {
2666
- reject(new AxiosError('Unsupported protocol ' + protocol + ':', AxiosError.ERR_BAD_REQUEST, config));
2667
- return;
2668
- }
2669
-
2670
-
2671
- // Send the request
2672
- request.send(requestData || null);
2673
- });
2674
- };
2675
-
2676
- const composeSignals = (signals, timeout) => {
2677
- let controller = new AbortController();
2678
-
2679
- let aborted;
2680
-
2681
- const onabort = function (cancel) {
2682
- if (!aborted) {
2683
- aborted = true;
2684
- unsubscribe();
2685
- const err = cancel instanceof Error ? cancel : this.reason;
2686
- controller.abort(err instanceof AxiosError ? err : new CanceledError(err instanceof Error ? err.message : err));
2687
- }
2688
- };
2689
-
2690
- let timer = timeout && setTimeout(() => {
2691
- onabort(new AxiosError(`timeout ${timeout} of ms exceeded`, AxiosError.ETIMEDOUT));
2692
- }, timeout);
2693
-
2694
- const unsubscribe = () => {
2695
- if (signals) {
2696
- timer && clearTimeout(timer);
2697
- timer = null;
2698
- signals.forEach(signal => {
2699
- signal &&
2700
- (signal.removeEventListener ? signal.removeEventListener('abort', onabort) : signal.unsubscribe(onabort));
2701
- });
2702
- signals = null;
2703
- }
2704
- };
2705
-
2706
- signals.forEach((signal) => signal && signal.addEventListener && signal.addEventListener('abort', onabort));
2707
-
2708
- const {signal} = controller;
2709
-
2710
- signal.unsubscribe = unsubscribe;
2711
-
2712
- return [signal, () => {
2713
- timer && clearTimeout(timer);
2714
- timer = null;
2715
- }];
2716
- };
2717
-
2718
- const streamChunk = function* (chunk, chunkSize) {
2719
- let len = chunk.byteLength;
2720
-
2721
- if (len < chunkSize) {
2722
- yield chunk;
2723
- return;
2724
- }
2725
-
2726
- let pos = 0;
2727
- let end;
2728
-
2729
- while (pos < len) {
2730
- end = pos + chunkSize;
2731
- yield chunk.slice(pos, end);
2732
- pos = end;
2733
- }
2734
- };
2735
-
2736
- const readBytes = async function* (iterable, chunkSize, encode) {
2737
- for await (const chunk of iterable) {
2738
- yield* streamChunk(ArrayBuffer.isView(chunk) ? chunk : (await encode(String(chunk))), chunkSize);
2739
- }
2740
- };
2741
-
2742
- const trackStream = (stream, chunkSize, onProgress, onFinish, encode) => {
2743
- const iterator = readBytes(stream, chunkSize, encode);
2744
-
2745
- let bytes = 0;
2746
- let done;
2747
- let _onFinish = (e) => {
2748
- if (!done) {
2749
- done = true;
2750
- onFinish && onFinish(e);
2751
- }
2752
- };
2753
-
2754
- return new ReadableStream({
2755
- async pull(controller) {
2756
- try {
2757
- const {done, value} = await iterator.next();
2758
-
2759
- if (done) {
2760
- _onFinish();
2761
- controller.close();
2762
- return;
2763
- }
2764
-
2765
- let len = value.byteLength;
2766
- if (onProgress) {
2767
- let loadedBytes = bytes += len;
2768
- onProgress(loadedBytes);
2769
- }
2770
- controller.enqueue(new Uint8Array(value));
2771
- } catch (err) {
2772
- _onFinish(err);
2773
- throw err;
2774
- }
2775
- },
2776
- cancel(reason) {
2777
- _onFinish(reason);
2778
- return iterator.return();
2779
- }
2780
- }, {
2781
- highWaterMark: 2
2782
- })
2783
- };
2784
-
2785
- const isFetchSupported = typeof fetch === 'function' && typeof Request === 'function' && typeof Response === 'function';
2786
- const isReadableStreamSupported = isFetchSupported && typeof ReadableStream === 'function';
2787
-
2788
- // used only inside the fetch adapter
2789
- const encodeText = isFetchSupported && (typeof TextEncoder === 'function' ?
2790
- ((encoder) => (str) => encoder.encode(str))(new TextEncoder()) :
2791
- async (str) => new Uint8Array(await new Response(str).arrayBuffer())
2792
- );
2793
-
2794
- const test = (fn, ...args) => {
2795
- try {
2796
- return !!fn(...args);
2797
- } catch (e) {
2798
- return false
2799
- }
2800
- };
2801
-
2802
- const supportsRequestStream = isReadableStreamSupported && test(() => {
2803
- let duplexAccessed = false;
2804
-
2805
- const hasContentType = new Request(platform.origin, {
2806
- body: new ReadableStream(),
2807
- method: 'POST',
2808
- get duplex() {
2809
- duplexAccessed = true;
2810
- return 'half';
2811
- },
2812
- }).headers.has('Content-Type');
2813
-
2814
- return duplexAccessed && !hasContentType;
2815
- });
2816
-
2817
- const DEFAULT_CHUNK_SIZE = 64 * 1024;
2818
-
2819
- const supportsResponseStream = isReadableStreamSupported &&
2820
- test(() => utils$1.isReadableStream(new Response('').body));
2821
-
2822
-
2823
- const resolvers = {
2824
- stream: supportsResponseStream && ((res) => res.body)
2825
- };
2826
-
2827
- isFetchSupported && (((res) => {
2828
- ['text', 'arrayBuffer', 'blob', 'formData', 'stream'].forEach(type => {
2829
- !resolvers[type] && (resolvers[type] = utils$1.isFunction(res[type]) ? (res) => res[type]() :
2830
- (_, config) => {
2831
- throw new AxiosError(`Response type '${type}' is not supported`, AxiosError.ERR_NOT_SUPPORT, config);
2832
- });
2833
- });
2834
- })(new Response));
2835
-
2836
- const getBodyLength = async (body) => {
2837
- if (body == null) {
2838
- return 0;
2839
- }
2840
-
2841
- if(utils$1.isBlob(body)) {
2842
- return body.size;
2843
- }
2844
-
2845
- if(utils$1.isSpecCompliantForm(body)) {
2846
- return (await new Request(body).arrayBuffer()).byteLength;
2847
- }
2848
-
2849
- if(utils$1.isArrayBufferView(body) || utils$1.isArrayBuffer(body)) {
2850
- return body.byteLength;
2851
- }
2852
-
2853
- if(utils$1.isURLSearchParams(body)) {
2854
- body = body + '';
2855
- }
2856
-
2857
- if(utils$1.isString(body)) {
2858
- return (await encodeText(body)).byteLength;
2859
- }
2860
- };
2861
-
2862
- const resolveBodyLength = async (headers, body) => {
2863
- const length = utils$1.toFiniteNumber(headers.getContentLength());
2864
-
2865
- return length == null ? getBodyLength(body) : length;
2866
- };
2867
-
2868
- var fetchAdapter = isFetchSupported && (async (config) => {
2869
- let {
2870
- url,
2871
- method,
2872
- data,
2873
- signal,
2874
- cancelToken,
2875
- timeout,
2876
- onDownloadProgress,
2877
- onUploadProgress,
2878
- responseType,
2879
- headers,
2880
- withCredentials = 'same-origin',
2881
- fetchOptions
2882
- } = resolveConfig(config);
2883
-
2884
- responseType = responseType ? (responseType + '').toLowerCase() : 'text';
2885
-
2886
- let [composedSignal, stopTimeout] = (signal || cancelToken || timeout) ?
2887
- composeSignals([signal, cancelToken], timeout) : [];
2888
-
2889
- let finished, request;
2890
-
2891
- const onFinish = () => {
2892
- !finished && setTimeout(() => {
2893
- composedSignal && composedSignal.unsubscribe();
2894
- });
2895
-
2896
- finished = true;
2897
- };
2898
-
2899
- let requestContentLength;
2900
-
2901
- try {
2902
- if (
2903
- onUploadProgress && supportsRequestStream && method !== 'get' && method !== 'head' &&
2904
- (requestContentLength = await resolveBodyLength(headers, data)) !== 0
2905
- ) {
2906
- let _request = new Request(url, {
2907
- method: 'POST',
2908
- body: data,
2909
- duplex: "half"
2910
- });
2911
-
2912
- let contentTypeHeader;
2913
-
2914
- if (utils$1.isFormData(data) && (contentTypeHeader = _request.headers.get('content-type'))) {
2915
- headers.setContentType(contentTypeHeader);
2916
- }
2917
-
2918
- if (_request.body) {
2919
- const [onProgress, flush] = progressEventDecorator(
2920
- requestContentLength,
2921
- progressEventReducer(asyncDecorator(onUploadProgress))
2922
- );
2923
-
2924
- data = trackStream(_request.body, DEFAULT_CHUNK_SIZE, onProgress, flush, encodeText);
2925
- }
2926
- }
2927
-
2928
- if (!utils$1.isString(withCredentials)) {
2929
- withCredentials = withCredentials ? 'include' : 'omit';
2930
- }
2931
-
2932
- request = new Request(url, {
2933
- ...fetchOptions,
2934
- signal: composedSignal,
2935
- method: method.toUpperCase(),
2936
- headers: headers.normalize().toJSON(),
2937
- body: data,
2938
- duplex: "half",
2939
- credentials: withCredentials
2940
- });
2941
-
2942
- let response = await fetch(request);
2943
-
2944
- const isStreamResponse = supportsResponseStream && (responseType === 'stream' || responseType === 'response');
2945
-
2946
- if (supportsResponseStream && (onDownloadProgress || isStreamResponse)) {
2947
- const options = {};
2948
-
2949
- ['status', 'statusText', 'headers'].forEach(prop => {
2950
- options[prop] = response[prop];
2951
- });
2952
-
2953
- const responseContentLength = utils$1.toFiniteNumber(response.headers.get('content-length'));
2954
-
2955
- const [onProgress, flush] = onDownloadProgress && progressEventDecorator(
2956
- responseContentLength,
2957
- progressEventReducer(asyncDecorator(onDownloadProgress), true)
2958
- ) || [];
2959
-
2960
- response = new Response(
2961
- trackStream(response.body, DEFAULT_CHUNK_SIZE, onProgress, () => {
2962
- flush && flush();
2963
- isStreamResponse && onFinish();
2964
- }, encodeText),
2965
- options
2966
- );
2967
- }
2968
-
2969
- responseType = responseType || 'text';
2970
-
2971
- let responseData = await resolvers[utils$1.findKey(resolvers, responseType) || 'text'](response, config);
2972
-
2973
- !isStreamResponse && onFinish();
2974
-
2975
- stopTimeout && stopTimeout();
2976
-
2977
- return await new Promise((resolve, reject) => {
2978
- settle(resolve, reject, {
2979
- data: responseData,
2980
- headers: AxiosHeaders.from(response.headers),
2981
- status: response.status,
2982
- statusText: response.statusText,
2983
- config,
2984
- request
2985
- });
2986
- })
2987
- } catch (err) {
2988
- onFinish();
2989
-
2990
- if (err && err.name === 'TypeError' && /fetch/i.test(err.message)) {
2991
- throw Object.assign(
2992
- new AxiosError('Network Error', AxiosError.ERR_NETWORK, config, request),
2993
- {
2994
- cause: err.cause || err
2995
- }
2996
- )
2997
- }
2998
-
2999
- throw AxiosError.from(err, err && err.code, config, request);
3000
- }
3001
- });
3002
-
3003
- const knownAdapters = {
3004
- http: httpAdapter,
3005
- xhr: xhrAdapter,
3006
- fetch: fetchAdapter
3007
- };
3008
-
3009
- utils$1.forEach(knownAdapters, (fn, value) => {
3010
- if (fn) {
3011
- try {
3012
- Object.defineProperty(fn, 'name', {value});
3013
- } catch (e) {
3014
- // eslint-disable-next-line no-empty
3015
- }
3016
- Object.defineProperty(fn, 'adapterName', {value});
3017
- }
3018
- });
3019
-
3020
- const renderReason = (reason) => `- ${reason}`;
3021
-
3022
- const isResolvedHandle = (adapter) => utils$1.isFunction(adapter) || adapter === null || adapter === false;
3023
-
3024
- var adapters = {
3025
- getAdapter: (adapters) => {
3026
- adapters = utils$1.isArray(adapters) ? adapters : [adapters];
3027
-
3028
- const {length} = adapters;
3029
- let nameOrAdapter;
3030
- let adapter;
3031
-
3032
- const rejectedReasons = {};
3033
-
3034
- for (let i = 0; i < length; i++) {
3035
- nameOrAdapter = adapters[i];
3036
- let id;
3037
-
3038
- adapter = nameOrAdapter;
3039
-
3040
- if (!isResolvedHandle(nameOrAdapter)) {
3041
- adapter = knownAdapters[(id = String(nameOrAdapter)).toLowerCase()];
3042
-
3043
- if (adapter === undefined) {
3044
- throw new AxiosError(`Unknown adapter '${id}'`);
3045
- }
3046
- }
3047
-
3048
- if (adapter) {
3049
- break;
3050
- }
3051
-
3052
- rejectedReasons[id || '#' + i] = adapter;
3053
- }
3054
-
3055
- if (!adapter) {
3056
-
3057
- const reasons = Object.entries(rejectedReasons)
3058
- .map(([id, state]) => `adapter ${id} ` +
3059
- (state === false ? 'is not supported by the environment' : 'is not available in the build')
3060
- );
3061
-
3062
- let s = length ?
3063
- (reasons.length > 1 ? 'since :\n' + reasons.map(renderReason).join('\n') : ' ' + renderReason(reasons[0])) :
3064
- 'as no adapter specified';
3065
-
3066
- throw new AxiosError(
3067
- `There is no suitable adapter to dispatch the request ` + s,
3068
- 'ERR_NOT_SUPPORT'
3069
- );
3070
- }
3071
-
3072
- return adapter;
3073
- },
3074
- adapters: knownAdapters
3075
- };
3076
-
3077
- /**
3078
- * Throws a `CanceledError` if cancellation has been requested.
3079
- *
3080
- * @param {Object} config The config that is to be used for the request
3081
- *
3082
- * @returns {void}
3083
- */
3084
- function throwIfCancellationRequested(config) {
3085
- if (config.cancelToken) {
3086
- config.cancelToken.throwIfRequested();
3087
- }
3088
-
3089
- if (config.signal && config.signal.aborted) {
3090
- throw new CanceledError(null, config);
3091
- }
3092
- }
3093
-
3094
- /**
3095
- * Dispatch a request to the server using the configured adapter.
3096
- *
3097
- * @param {object} config The config that is to be used for the request
3098
- *
3099
- * @returns {Promise} The Promise to be fulfilled
3100
- */
3101
- function dispatchRequest(config) {
3102
- throwIfCancellationRequested(config);
3103
-
3104
- config.headers = AxiosHeaders.from(config.headers);
3105
-
3106
- // Transform request data
3107
- config.data = transformData.call(
3108
- config,
3109
- config.transformRequest
3110
- );
3111
-
3112
- if (['post', 'put', 'patch'].indexOf(config.method) !== -1) {
3113
- config.headers.setContentType('application/x-www-form-urlencoded', false);
3114
- }
3115
-
3116
- const adapter = adapters.getAdapter(config.adapter || defaults$1.adapter);
3117
-
3118
- return adapter(config).then(function onAdapterResolution(response) {
3119
- throwIfCancellationRequested(config);
3120
-
3121
- // Transform response data
3122
- response.data = transformData.call(
3123
- config,
3124
- config.transformResponse,
3125
- response
3126
- );
3127
-
3128
- response.headers = AxiosHeaders.from(response.headers);
3129
-
3130
- return response;
3131
- }, function onAdapterRejection(reason) {
3132
- if (!isCancel(reason)) {
3133
- throwIfCancellationRequested(config);
3134
-
3135
- // Transform response data
3136
- if (reason && reason.response) {
3137
- reason.response.data = transformData.call(
3138
- config,
3139
- config.transformResponse,
3140
- reason.response
3141
- );
3142
- reason.response.headers = AxiosHeaders.from(reason.response.headers);
3143
- }
3144
- }
3145
-
3146
- return Promise.reject(reason);
3147
- });
3148
- }
3149
-
3150
- const VERSION = "1.7.4";
3151
-
3152
- const validators$1 = {};
3153
-
3154
- // eslint-disable-next-line func-names
3155
- ['object', 'boolean', 'number', 'function', 'string', 'symbol'].forEach((type, i) => {
3156
- validators$1[type] = function validator(thing) {
3157
- return typeof thing === type || 'a' + (i < 1 ? 'n ' : ' ') + type;
3158
- };
3159
- });
3160
-
3161
- const deprecatedWarnings = {};
3162
-
3163
- /**
3164
- * Transitional option validator
3165
- *
3166
- * @param {function|boolean?} validator - set to false if the transitional option has been removed
3167
- * @param {string?} version - deprecated version / removed since version
3168
- * @param {string?} message - some message with additional info
3169
- *
3170
- * @returns {function}
3171
- */
3172
- validators$1.transitional = function transitional(validator, version, message) {
3173
- function formatMessage(opt, desc) {
3174
- return '[Axios v' + VERSION + '] Transitional option \'' + opt + '\'' + desc + (message ? '. ' + message : '');
3175
- }
3176
-
3177
- // eslint-disable-next-line func-names
3178
- return (value, opt, opts) => {
3179
- if (validator === false) {
3180
- throw new AxiosError(
3181
- formatMessage(opt, ' has been removed' + (version ? ' in ' + version : '')),
3182
- AxiosError.ERR_DEPRECATED
3183
- );
3184
- }
3185
-
3186
- if (version && !deprecatedWarnings[opt]) {
3187
- deprecatedWarnings[opt] = true;
3188
- // eslint-disable-next-line no-console
3189
- console.warn(
3190
- formatMessage(
3191
- opt,
3192
- ' has been deprecated since v' + version + ' and will be removed in the near future'
3193
- )
3194
- );
3195
- }
3196
-
3197
- return validator ? validator(value, opt, opts) : true;
3198
- };
3199
- };
3200
-
3201
- /**
3202
- * Assert object's properties type
3203
- *
3204
- * @param {object} options
3205
- * @param {object} schema
3206
- * @param {boolean?} allowUnknown
3207
- *
3208
- * @returns {object}
3209
- */
3210
-
3211
- function assertOptions(options, schema, allowUnknown) {
3212
- if (typeof options !== 'object') {
3213
- throw new AxiosError('options must be an object', AxiosError.ERR_BAD_OPTION_VALUE);
3214
- }
3215
- const keys = Object.keys(options);
3216
- let i = keys.length;
3217
- while (i-- > 0) {
3218
- const opt = keys[i];
3219
- const validator = schema[opt];
3220
- if (validator) {
3221
- const value = options[opt];
3222
- const result = value === undefined || validator(value, opt, options);
3223
- if (result !== true) {
3224
- throw new AxiosError('option ' + opt + ' must be ' + result, AxiosError.ERR_BAD_OPTION_VALUE);
3225
- }
3226
- continue;
3227
- }
3228
- if (allowUnknown !== true) {
3229
- throw new AxiosError('Unknown option ' + opt, AxiosError.ERR_BAD_OPTION);
3230
- }
3231
- }
3232
- }
3233
-
3234
- var validator = {
3235
- assertOptions,
3236
- validators: validators$1
3237
- };
3238
-
3239
- const validators = validator.validators;
3240
-
3241
- /**
3242
- * Create a new instance of Axios
3243
- *
3244
- * @param {Object} instanceConfig The default config for the instance
3245
- *
3246
- * @return {Axios} A new instance of Axios
3247
- */
3248
- class Axios {
3249
- constructor(instanceConfig) {
3250
- this.defaults = instanceConfig;
3251
- this.interceptors = {
3252
- request: new InterceptorManager(),
3253
- response: new InterceptorManager()
3254
- };
3255
- }
3256
-
3257
- /**
3258
- * Dispatch a request
3259
- *
3260
- * @param {String|Object} configOrUrl The config specific for this request (merged with this.defaults)
3261
- * @param {?Object} config
3262
- *
3263
- * @returns {Promise} The Promise to be fulfilled
3264
- */
3265
- async request(configOrUrl, config) {
3266
- try {
3267
- return await this._request(configOrUrl, config);
3268
- } catch (err) {
3269
- if (err instanceof Error) {
3270
- let dummy;
3271
-
3272
- Error.captureStackTrace ? Error.captureStackTrace(dummy = {}) : (dummy = new Error());
3273
-
3274
- // slice off the Error: ... line
3275
- const stack = dummy.stack ? dummy.stack.replace(/^.+\n/, '') : '';
3276
- try {
3277
- if (!err.stack) {
3278
- err.stack = stack;
3279
- // match without the 2 top stack lines
3280
- } else if (stack && !String(err.stack).endsWith(stack.replace(/^.+\n.+\n/, ''))) {
3281
- err.stack += '\n' + stack;
3282
- }
3283
- } catch (e) {
3284
- // ignore the case where "stack" is an un-writable property
3285
- }
3286
- }
3287
-
3288
- throw err;
3289
- }
3290
- }
3291
-
3292
- _request(configOrUrl, config) {
3293
- /*eslint no-param-reassign:0*/
3294
- // Allow for axios('example/url'[, config]) a la fetch API
3295
- if (typeof configOrUrl === 'string') {
3296
- config = config || {};
3297
- config.url = configOrUrl;
3298
- } else {
3299
- config = configOrUrl || {};
3300
- }
3301
-
3302
- config = mergeConfig(this.defaults, config);
3303
-
3304
- const {transitional, paramsSerializer, headers} = config;
3305
-
3306
- if (transitional !== undefined) {
3307
- validator.assertOptions(transitional, {
3308
- silentJSONParsing: validators.transitional(validators.boolean),
3309
- forcedJSONParsing: validators.transitional(validators.boolean),
3310
- clarifyTimeoutError: validators.transitional(validators.boolean)
3311
- }, false);
3312
- }
3313
-
3314
- if (paramsSerializer != null) {
3315
- if (utils$1.isFunction(paramsSerializer)) {
3316
- config.paramsSerializer = {
3317
- serialize: paramsSerializer
3318
- };
3319
- } else {
3320
- validator.assertOptions(paramsSerializer, {
3321
- encode: validators.function,
3322
- serialize: validators.function
3323
- }, true);
3324
- }
3325
- }
3326
-
3327
- // Set config.method
3328
- config.method = (config.method || this.defaults.method || 'get').toLowerCase();
3329
-
3330
- // Flatten headers
3331
- let contextHeaders = headers && utils$1.merge(
3332
- headers.common,
3333
- headers[config.method]
3334
- );
3335
-
3336
- headers && utils$1.forEach(
3337
- ['delete', 'get', 'head', 'post', 'put', 'patch', 'common'],
3338
- (method) => {
3339
- delete headers[method];
3340
- }
3341
- );
3342
-
3343
- config.headers = AxiosHeaders.concat(contextHeaders, headers);
3344
-
3345
- // filter out skipped interceptors
3346
- const requestInterceptorChain = [];
3347
- let synchronousRequestInterceptors = true;
3348
- this.interceptors.request.forEach(function unshiftRequestInterceptors(interceptor) {
3349
- if (typeof interceptor.runWhen === 'function' && interceptor.runWhen(config) === false) {
3350
- return;
3351
- }
3352
-
3353
- synchronousRequestInterceptors = synchronousRequestInterceptors && interceptor.synchronous;
3354
-
3355
- requestInterceptorChain.unshift(interceptor.fulfilled, interceptor.rejected);
3356
- });
3357
-
3358
- const responseInterceptorChain = [];
3359
- this.interceptors.response.forEach(function pushResponseInterceptors(interceptor) {
3360
- responseInterceptorChain.push(interceptor.fulfilled, interceptor.rejected);
3361
- });
3362
-
3363
- let promise;
3364
- let i = 0;
3365
- let len;
3366
-
3367
- if (!synchronousRequestInterceptors) {
3368
- const chain = [dispatchRequest.bind(this), undefined];
3369
- chain.unshift.apply(chain, requestInterceptorChain);
3370
- chain.push.apply(chain, responseInterceptorChain);
3371
- len = chain.length;
3372
-
3373
- promise = Promise.resolve(config);
3374
-
3375
- while (i < len) {
3376
- promise = promise.then(chain[i++], chain[i++]);
3377
- }
3378
-
3379
- return promise;
3380
- }
3381
-
3382
- len = requestInterceptorChain.length;
3383
-
3384
- let newConfig = config;
3385
-
3386
- i = 0;
3387
-
3388
- while (i < len) {
3389
- const onFulfilled = requestInterceptorChain[i++];
3390
- const onRejected = requestInterceptorChain[i++];
3391
- try {
3392
- newConfig = onFulfilled(newConfig);
3393
- } catch (error) {
3394
- onRejected.call(this, error);
3395
- break;
3396
- }
3397
- }
3398
-
3399
- try {
3400
- promise = dispatchRequest.call(this, newConfig);
3401
- } catch (error) {
3402
- return Promise.reject(error);
3403
- }
3404
-
3405
- i = 0;
3406
- len = responseInterceptorChain.length;
3407
-
3408
- while (i < len) {
3409
- promise = promise.then(responseInterceptorChain[i++], responseInterceptorChain[i++]);
3410
- }
3411
-
3412
- return promise;
3413
- }
3414
-
3415
- getUri(config) {
3416
- config = mergeConfig(this.defaults, config);
3417
- const fullPath = buildFullPath(config.baseURL, config.url);
3418
- return buildURL(fullPath, config.params, config.paramsSerializer);
3419
- }
3420
- }
3421
-
3422
- // Provide aliases for supported request methods
3423
- utils$1.forEach(['delete', 'get', 'head', 'options'], function forEachMethodNoData(method) {
3424
- /*eslint func-names:0*/
3425
- Axios.prototype[method] = function(url, config) {
3426
- return this.request(mergeConfig(config || {}, {
3427
- method,
3428
- url,
3429
- data: (config || {}).data
3430
- }));
3431
- };
3432
- });
3433
-
3434
- utils$1.forEach(['post', 'put', 'patch'], function forEachMethodWithData(method) {
3435
- /*eslint func-names:0*/
3436
-
3437
- function generateHTTPMethod(isForm) {
3438
- return function httpMethod(url, data, config) {
3439
- return this.request(mergeConfig(config || {}, {
3440
- method,
3441
- headers: isForm ? {
3442
- 'Content-Type': 'multipart/form-data'
3443
- } : {},
3444
- url,
3445
- data
3446
- }));
3447
- };
3448
- }
3449
-
3450
- Axios.prototype[method] = generateHTTPMethod();
3451
-
3452
- Axios.prototype[method + 'Form'] = generateHTTPMethod(true);
3453
- });
3454
-
3455
- /**
3456
- * A `CancelToken` is an object that can be used to request cancellation of an operation.
3457
- *
3458
- * @param {Function} executor The executor function.
3459
- *
3460
- * @returns {CancelToken}
3461
- */
3462
- class CancelToken {
3463
- constructor(executor) {
3464
- if (typeof executor !== 'function') {
3465
- throw new TypeError('executor must be a function.');
3466
- }
3467
-
3468
- let resolvePromise;
3469
-
3470
- this.promise = new Promise(function promiseExecutor(resolve) {
3471
- resolvePromise = resolve;
3472
- });
3473
-
3474
- const token = this;
3475
-
3476
- // eslint-disable-next-line func-names
3477
- this.promise.then(cancel => {
3478
- if (!token._listeners) return;
3479
-
3480
- let i = token._listeners.length;
3481
-
3482
- while (i-- > 0) {
3483
- token._listeners[i](cancel);
3484
- }
3485
- token._listeners = null;
3486
- });
3487
-
3488
- // eslint-disable-next-line func-names
3489
- this.promise.then = onfulfilled => {
3490
- let _resolve;
3491
- // eslint-disable-next-line func-names
3492
- const promise = new Promise(resolve => {
3493
- token.subscribe(resolve);
3494
- _resolve = resolve;
3495
- }).then(onfulfilled);
3496
-
3497
- promise.cancel = function reject() {
3498
- token.unsubscribe(_resolve);
3499
- };
3500
-
3501
- return promise;
3502
- };
3503
-
3504
- executor(function cancel(message, config, request) {
3505
- if (token.reason) {
3506
- // Cancellation has already been requested
3507
- return;
3508
- }
3509
-
3510
- token.reason = new CanceledError(message, config, request);
3511
- resolvePromise(token.reason);
3512
- });
3513
- }
3514
-
3515
- /**
3516
- * Throws a `CanceledError` if cancellation has been requested.
3517
- */
3518
- throwIfRequested() {
3519
- if (this.reason) {
3520
- throw this.reason;
3521
- }
3522
- }
3523
-
3524
- /**
3525
- * Subscribe to the cancel signal
3526
- */
3527
-
3528
- subscribe(listener) {
3529
- if (this.reason) {
3530
- listener(this.reason);
3531
- return;
3532
- }
3533
-
3534
- if (this._listeners) {
3535
- this._listeners.push(listener);
3536
- } else {
3537
- this._listeners = [listener];
3538
- }
3539
- }
3540
-
3541
- /**
3542
- * Unsubscribe from the cancel signal
3543
- */
3544
-
3545
- unsubscribe(listener) {
3546
- if (!this._listeners) {
3547
- return;
3548
- }
3549
- const index = this._listeners.indexOf(listener);
3550
- if (index !== -1) {
3551
- this._listeners.splice(index, 1);
3552
- }
3553
- }
3554
-
3555
- /**
3556
- * Returns an object that contains a new `CancelToken` and a function that, when called,
3557
- * cancels the `CancelToken`.
3558
- */
3559
- static source() {
3560
- let cancel;
3561
- const token = new CancelToken(function executor(c) {
3562
- cancel = c;
3563
- });
3564
- return {
3565
- token,
3566
- cancel
3567
- };
3568
- }
3569
- }
3570
-
3571
- /**
3572
- * Syntactic sugar for invoking a function and expanding an array for arguments.
3573
- *
3574
- * Common use case would be to use `Function.prototype.apply`.
3575
- *
3576
- * ```js
3577
- * function f(x, y, z) {}
3578
- * var args = [1, 2, 3];
3579
- * f.apply(null, args);
3580
- * ```
3581
- *
3582
- * With `spread` this example can be re-written.
3583
- *
3584
- * ```js
3585
- * spread(function(x, y, z) {})([1, 2, 3]);
3586
- * ```
3587
- *
3588
- * @param {Function} callback
3589
- *
3590
- * @returns {Function}
3591
- */
3592
- function spread(callback) {
3593
- return function wrap(arr) {
3594
- return callback.apply(null, arr);
3595
- };
3596
- }
3597
-
3598
- /**
3599
- * Determines whether the payload is an error thrown by Axios
3600
- *
3601
- * @param {*} payload The value to test
3602
- *
3603
- * @returns {boolean} True if the payload is an error thrown by Axios, otherwise false
3604
- */
3605
- function isAxiosError(payload) {
3606
- return utils$1.isObject(payload) && (payload.isAxiosError === true);
3607
- }
3608
-
3609
- const HttpStatusCode = {
3610
- Continue: 100,
3611
- SwitchingProtocols: 101,
3612
- Processing: 102,
3613
- EarlyHints: 103,
3614
- Ok: 200,
3615
- Created: 201,
3616
- Accepted: 202,
3617
- NonAuthoritativeInformation: 203,
3618
- NoContent: 204,
3619
- ResetContent: 205,
3620
- PartialContent: 206,
3621
- MultiStatus: 207,
3622
- AlreadyReported: 208,
3623
- ImUsed: 226,
3624
- MultipleChoices: 300,
3625
- MovedPermanently: 301,
3626
- Found: 302,
3627
- SeeOther: 303,
3628
- NotModified: 304,
3629
- UseProxy: 305,
3630
- Unused: 306,
3631
- TemporaryRedirect: 307,
3632
- PermanentRedirect: 308,
3633
- BadRequest: 400,
3634
- Unauthorized: 401,
3635
- PaymentRequired: 402,
3636
- Forbidden: 403,
3637
- NotFound: 404,
3638
- MethodNotAllowed: 405,
3639
- NotAcceptable: 406,
3640
- ProxyAuthenticationRequired: 407,
3641
- RequestTimeout: 408,
3642
- Conflict: 409,
3643
- Gone: 410,
3644
- LengthRequired: 411,
3645
- PreconditionFailed: 412,
3646
- PayloadTooLarge: 413,
3647
- UriTooLong: 414,
3648
- UnsupportedMediaType: 415,
3649
- RangeNotSatisfiable: 416,
3650
- ExpectationFailed: 417,
3651
- ImATeapot: 418,
3652
- MisdirectedRequest: 421,
3653
- UnprocessableEntity: 422,
3654
- Locked: 423,
3655
- FailedDependency: 424,
3656
- TooEarly: 425,
3657
- UpgradeRequired: 426,
3658
- PreconditionRequired: 428,
3659
- TooManyRequests: 429,
3660
- RequestHeaderFieldsTooLarge: 431,
3661
- UnavailableForLegalReasons: 451,
3662
- InternalServerError: 500,
3663
- NotImplemented: 501,
3664
- BadGateway: 502,
3665
- ServiceUnavailable: 503,
3666
- GatewayTimeout: 504,
3667
- HttpVersionNotSupported: 505,
3668
- VariantAlsoNegotiates: 506,
3669
- InsufficientStorage: 507,
3670
- LoopDetected: 508,
3671
- NotExtended: 510,
3672
- NetworkAuthenticationRequired: 511,
3673
- };
3674
-
3675
- Object.entries(HttpStatusCode).forEach(([key, value]) => {
3676
- HttpStatusCode[value] = key;
3677
- });
3678
-
3679
- /**
3680
- * Create an instance of Axios
3681
- *
3682
- * @param {Object} defaultConfig The default config for the instance
3683
- *
3684
- * @returns {Axios} A new instance of Axios
3685
- */
3686
- function createInstance(defaultConfig) {
3687
- const context = new Axios(defaultConfig);
3688
- const instance = bind(Axios.prototype.request, context);
3689
-
3690
- // Copy axios.prototype to instance
3691
- utils$1.extend(instance, Axios.prototype, context, {allOwnKeys: true});
3692
-
3693
- // Copy context to instance
3694
- utils$1.extend(instance, context, null, {allOwnKeys: true});
3695
-
3696
- // Factory for creating new instances
3697
- instance.create = function create(instanceConfig) {
3698
- return createInstance(mergeConfig(defaultConfig, instanceConfig));
3699
- };
3700
-
3701
- return instance;
3702
- }
3703
-
3704
- // Create the default instance to be exported
3705
- const axios = createInstance(defaults$1);
3706
-
3707
- // Expose Axios class to allow class inheritance
3708
- axios.Axios = Axios;
3709
-
3710
- // Expose Cancel & CancelToken
3711
- axios.CanceledError = CanceledError;
3712
- axios.CancelToken = CancelToken;
3713
- axios.isCancel = isCancel;
3714
- axios.VERSION = VERSION;
3715
- axios.toFormData = toFormData;
3716
-
3717
- // Expose AxiosError class
3718
- axios.AxiosError = AxiosError;
3719
-
3720
- // alias for CanceledError for backward compatibility
3721
- axios.Cancel = axios.CanceledError;
3722
-
3723
- // Expose all/spread
3724
- axios.all = function all(promises) {
3725
- return Promise.all(promises);
3726
- };
3727
-
3728
- axios.spread = spread;
3729
-
3730
- // Expose isAxiosError
3731
- axios.isAxiosError = isAxiosError;
3732
-
3733
- // Expose mergeConfig
3734
- axios.mergeConfig = mergeConfig;
3735
-
3736
- axios.AxiosHeaders = AxiosHeaders;
3737
-
3738
- axios.formToJSON = thing => formDataToJSON(utils$1.isHTMLForm(thing) ? new FormData(thing) : thing);
3739
-
3740
- axios.getAdapter = adapters.getAdapter;
3741
-
3742
- axios.HttpStatusCode = HttpStatusCode;
3743
-
3744
- axios.default = axios;
4
+ var xchainBase = require('@xchainjs/xchain-base');
5
+ var xchainBitcoin = require('@xchainjs/xchain-bitcoin');
6
+ var xchainBitcoincash = require('@xchainjs/xchain-bitcoincash');
7
+ var xchainBsc = require('@xchainjs/xchain-bsc');
8
+ var xchainClient = require('@xchainjs/xchain-client');
9
+ var xchainCosmos = require('@xchainjs/xchain-cosmos');
10
+ var xchainDoge = require('@xchainjs/xchain-doge');
11
+ var xchainEthereum = require('@xchainjs/xchain-ethereum');
12
+ var xchainEvm = require('@xchainjs/xchain-evm');
13
+ var xchainLitecoin = require('@xchainjs/xchain-litecoin');
14
+ var xchainThorchain = require('@xchainjs/xchain-thorchain');
15
+ var xchainThorchainQuery = require('@xchainjs/xchain-thorchain-query');
16
+ var xchainUtil = require('@xchainjs/xchain-util');
17
+ var xchainWallet = require('@xchainjs/xchain-wallet');
18
+ var ethers = require('ethers');
3745
19
 
3746
20
  /******************************************************************************
3747
21
  Copyright (c) Microsoft Corporation.
@@ -3766,7 +40,7 @@ function __awaiter(thisArg, _arguments, P, generator) {
3766
40
  function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
3767
41
  function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
3768
42
  function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
3769
- step((generator = generator.apply(thisArg, [])).next());
43
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
3770
44
  });
3771
45
  }
3772
46
 
@@ -3775,695 +49,13 @@ typeof SuppressedError === "function" ? SuppressedError : function (error, suppr
3775
49
  return e.name = "SuppressedError", e.error = error, e.suppressed = suppressed, e;
3776
50
  };
3777
51
 
3778
- var erc20ABI = [
3779
- {
3780
- inputs: [
3781
- ],
3782
- stateMutability: "nonpayable",
3783
- type: "constructor"
3784
- },
3785
- {
3786
- anonymous: false,
3787
- inputs: [
3788
- {
3789
- indexed: true,
3790
- internalType: "address",
3791
- name: "owner",
3792
- type: "address"
3793
- },
3794
- {
3795
- indexed: true,
3796
- internalType: "address",
3797
- name: "spender",
3798
- type: "address"
3799
- },
3800
- {
3801
- indexed: false,
3802
- internalType: "uint256",
3803
- name: "value",
3804
- type: "uint256"
3805
- }
3806
- ],
3807
- name: "Approval",
3808
- type: "event"
3809
- },
3810
- {
3811
- anonymous: false,
3812
- inputs: [
3813
- {
3814
- indexed: true,
3815
- internalType: "address",
3816
- name: "from",
3817
- type: "address"
3818
- },
3819
- {
3820
- indexed: true,
3821
- internalType: "address",
3822
- name: "to",
3823
- type: "address"
3824
- },
3825
- {
3826
- indexed: false,
3827
- internalType: "uint256",
3828
- name: "value",
3829
- type: "uint256"
3830
- }
3831
- ],
3832
- name: "Transfer",
3833
- type: "event"
3834
- },
3835
- {
3836
- inputs: [
3837
- {
3838
- internalType: "address",
3839
- name: "",
3840
- type: "address"
3841
- },
3842
- {
3843
- internalType: "address",
3844
- name: "",
3845
- type: "address"
3846
- }
3847
- ],
3848
- name: "allowance",
3849
- outputs: [
3850
- {
3851
- internalType: "uint256",
3852
- name: "",
3853
- type: "uint256"
3854
- }
3855
- ],
3856
- stateMutability: "view",
3857
- type: "function"
3858
- },
3859
- {
3860
- inputs: [
3861
- {
3862
- internalType: "address",
3863
- name: "spender",
3864
- type: "address"
3865
- },
3866
- {
3867
- internalType: "uint256",
3868
- name: "value",
3869
- type: "uint256"
3870
- }
3871
- ],
3872
- name: "approve",
3873
- outputs: [
3874
- {
3875
- internalType: "bool",
3876
- name: "success",
3877
- type: "bool"
3878
- }
3879
- ],
3880
- stateMutability: "nonpayable",
3881
- type: "function"
3882
- },
3883
- {
3884
- inputs: [
3885
- {
3886
- internalType: "address",
3887
- name: "",
3888
- type: "address"
3889
- }
3890
- ],
3891
- name: "balanceOf",
3892
- outputs: [
3893
- {
3894
- internalType: "uint256",
3895
- name: "",
3896
- type: "uint256"
3897
- }
3898
- ],
3899
- stateMutability: "view",
3900
- type: "function"
3901
- },
3902
- {
3903
- inputs: [
3904
- ],
3905
- name: "decimals",
3906
- outputs: [
3907
- {
3908
- internalType: "uint256",
3909
- name: "",
3910
- type: "uint256"
3911
- }
3912
- ],
3913
- stateMutability: "view",
3914
- type: "function"
3915
- },
3916
- {
3917
- inputs: [
3918
- ],
3919
- name: "name",
3920
- outputs: [
3921
- {
3922
- internalType: "string",
3923
- name: "",
3924
- type: "string"
3925
- }
3926
- ],
3927
- stateMutability: "view",
3928
- type: "function"
3929
- },
3930
- {
3931
- inputs: [
3932
- ],
3933
- name: "symbol",
3934
- outputs: [
3935
- {
3936
- internalType: "string",
3937
- name: "",
3938
- type: "string"
3939
- }
3940
- ],
3941
- stateMutability: "view",
3942
- type: "function"
3943
- },
3944
- {
3945
- inputs: [
3946
- ],
3947
- name: "totalSupply",
3948
- outputs: [
3949
- {
3950
- internalType: "uint256",
3951
- name: "",
3952
- type: "uint256"
3953
- }
3954
- ],
3955
- stateMutability: "view",
3956
- type: "function"
3957
- },
3958
- {
3959
- inputs: [
3960
- {
3961
- internalType: "address",
3962
- name: "to",
3963
- type: "address"
3964
- },
3965
- {
3966
- internalType: "uint256",
3967
- name: "value",
3968
- type: "uint256"
3969
- }
3970
- ],
3971
- name: "transfer",
3972
- outputs: [
3973
- {
3974
- internalType: "bool",
3975
- name: "success",
3976
- type: "bool"
3977
- }
3978
- ],
3979
- stateMutability: "nonpayable",
3980
- type: "function"
3981
- },
3982
- {
3983
- inputs: [
3984
- {
3985
- internalType: "address",
3986
- name: "from",
3987
- type: "address"
3988
- },
3989
- {
3990
- internalType: "address",
3991
- name: "to",
3992
- type: "address"
3993
- },
3994
- {
3995
- internalType: "uint256",
3996
- name: "value",
3997
- type: "uint256"
3998
- }
3999
- ],
4000
- name: "transferFrom",
4001
- outputs: [
4002
- {
4003
- internalType: "bool",
4004
- name: "success",
4005
- type: "bool"
4006
- }
4007
- ],
4008
- stateMutability: "nonpayable",
4009
- type: "function"
4010
- }
4011
- ];
4012
-
4013
- ethers.ethers.BigNumber.from(2).pow(256).sub(1);
4014
- /**
4015
- * Validate the given address.
4016
- *
4017
- * @param {Address} address
4018
- * @returns {boolean} `true` or `false`
4019
- */
4020
- const validateAddress$1 = (address) => {
4021
- try {
4022
- ethers.ethers.utils.getAddress(address);
4023
- return true;
4024
- }
4025
- catch (error) {
4026
- return false;
4027
- }
4028
- };
4029
-
4030
- const getApiKeyQueryParameter = (apiKey) => (!!apiKey ? `&apiKey=${apiKey}` : '');
4031
- /**
4032
- * Filter self txs
4033
- *
4034
- * @returns {T[]}
4035
- *
4036
- **/
4037
- const filterSelfTxs = (txs) => {
4038
- const filterTxs = txs.filter((tx) => tx.from !== tx.to);
4039
- let selfTxs = txs.filter((tx) => tx.from === tx.to);
4040
- while (selfTxs.length) {
4041
- const selfTx = selfTxs[0];
4042
- filterTxs.push(selfTx);
4043
- selfTxs = selfTxs.filter((tx) => tx.hash !== selfTx.hash);
4044
- }
4045
- return filterTxs;
4046
- };
4047
- /**
4048
- * Check if the symbol is valid.
4049
- *
4050
- * @param {string|null|undefined} symbol
4051
- * @returns {boolean} `true` or `false`.
4052
- */
4053
- const validateSymbol = (symbol) => (symbol ? symbol.length >= 3 : false);
4054
- /**
4055
- * Get transactions from ETH transaction
4056
- *
4057
- * @param {ETHTransactionInfo} tx
4058
- * @returns {Tx} The parsed transaction.
4059
- */
4060
- const getTxFromEthTransaction = (tx, gasAsset, decimals) => {
4061
- return {
4062
- asset: gasAsset,
4063
- from: [
4064
- {
4065
- from: tx.from,
4066
- amount: xchainUtil.baseAmount(tx.value, decimals),
4067
- },
4068
- ],
4069
- to: [
4070
- {
4071
- to: tx.to,
4072
- amount: xchainUtil.baseAmount(tx.value, decimals),
4073
- },
4074
- ],
4075
- date: new Date(parseInt(tx.timeStamp) * 1000),
4076
- type: xchainClient.TxType.Transfer,
4077
- hash: tx.hash,
4078
- };
4079
- };
4080
- /**
4081
- * Get transactions from token tx
4082
- *
4083
- * @param {TokenTransactionInfo} tx
4084
- * @returns {Tx|null} The parsed transaction.
4085
- */
4086
- const getTxFromTokenTransaction = (tx, chain, decimals) => {
4087
- const decimal = parseInt(tx.tokenDecimal) || decimals;
4088
- const symbol = tx.tokenSymbol;
4089
- const address = tx.contractAddress;
4090
- if (validateSymbol(symbol) && validateAddress$1(address)) {
4091
- const tokenAsset = xchainUtil.assetFromString(`${chain}.${symbol}-${address}`);
4092
- if (tokenAsset) {
4093
- return {
4094
- asset: tokenAsset,
4095
- from: [
4096
- {
4097
- from: tx.from,
4098
- amount: xchainUtil.baseAmount(tx.value, decimal),
4099
- },
4100
- ],
4101
- to: [
4102
- {
4103
- to: tx.to,
4104
- amount: xchainUtil.baseAmount(tx.value, decimal),
4105
- },
4106
- ],
4107
- date: new Date(parseInt(tx.timeStamp) * 1000),
4108
- type: xchainClient.TxType.Transfer,
4109
- hash: tx.hash,
4110
- };
4111
- }
4112
- }
4113
- return null;
4114
- };
4115
- /**
4116
- * SafeGasPrice, ProposeGasPrice And FastGasPrice returned in string-Gwei
4117
- *
4118
- * @see https://etherscan.io/apis#gastracker
4119
- *
4120
- * @param {string} baseUrl The etherscan node url.
4121
- * @param {string} apiKey The etherscan API key. (optional)
4122
- * @returns {GasOracleResponse} LastBlock, SafeGasPrice, ProposeGasPrice, FastGasPrice
4123
- */
4124
- const getGasOracle = (baseUrl, apiKey) => __awaiter(void 0, void 0, void 0, function* () {
4125
- const url = baseUrl + '/api?module=gastracker&action=gasoracle';
4126
- const result = (yield axios.get(url + getApiKeyQueryParameter(apiKey))).data.result;
4127
- if (typeof result === 'string')
4128
- throw Error(`Can not retrieve gasOracle: ${result}`);
4129
- return result;
4130
- });
4131
- /**
4132
- * Get ETH transaction history
4133
- *
4134
- * @see https://etherscan.io/apis#accounts
4135
- *
4136
- * @param {string} baseUrl The etherscan node url.
4137
- * @param {string} address The address.
4138
- * @param {TransactionHistoryParam} params The search options.
4139
- * @param {string} apiKey The etherscan API key. (optional)
4140
- * @returns {ETHTransactionInfo[]} The ETH transaction history
4141
- */
4142
- const getGasAssetTransactionHistory = ({ gasAsset, gasDecimals, baseUrl, address, page, offset, startblock, endblock, apiKey, }) => __awaiter(void 0, void 0, void 0, function* () {
4143
- let url = baseUrl + `/api?module=account&action=txlist&sort=desc` + getApiKeyQueryParameter(apiKey);
4144
- if (address)
4145
- url += `&address=${address}`;
4146
- if (offset)
4147
- url += `&offset=${offset}`;
4148
- if (page)
4149
- url += `&page=${page}`;
4150
- if (startblock)
4151
- url += `&startblock=${startblock}`;
4152
- if (endblock)
4153
- url += `&endblock=${endblock}`;
4154
- const result = (yield axios.get(url)).data.result;
4155
- if (JSON.stringify(result).includes('Invalid API Key'))
4156
- throw new Error('Invalid API Key');
4157
- if (typeof result !== 'object')
4158
- throw new Error(result);
4159
- return filterSelfTxs(result)
4160
- .filter((tx) => !xchainUtil.bnOrZero(tx.value).isZero())
4161
- .map((tx) => getTxFromEthTransaction(tx, gasAsset, gasDecimals));
4162
- });
4163
- /**
4164
- * Get token transaction history
4165
- *
4166
- * @see https://etherscan.io/apis#accounts
4167
- *
4168
- * @param {string} baseUrl The etherscan node url.
4169
- * @param {string} address The address.
4170
- * @param {TransactionHistoryParam} params The search options.
4171
- * @param {string} apiKey The etherscan API key. (optional)
4172
- * @returns {Tx[]} The token transaction history
4173
- */
4174
- const getTokenTransactionHistory = ({ gasDecimals, baseUrl, address, assetAddress, page, offset, startblock, endblock, apiKey, chain, }) => __awaiter(void 0, void 0, void 0, function* () {
4175
- let url = baseUrl + `/api?module=account&action=tokentx&sort=desc` + getApiKeyQueryParameter(apiKey);
4176
- if (address)
4177
- url += `&address=${address}`;
4178
- if (assetAddress)
4179
- url += `&contractaddress=${assetAddress}`;
4180
- if (offset)
4181
- url += `&offset=${offset}`;
4182
- if (page)
4183
- url += `&page=${page}`;
4184
- if (startblock)
4185
- url += `&startblock=${startblock}`;
4186
- if (endblock)
4187
- url += `&endblock=${endblock}`;
4188
- const result = (yield axios.get(url)).data.result;
4189
- if (JSON.stringify(result).includes('Invalid API Key'))
4190
- throw new Error('Invalid API Key');
4191
- return filterSelfTxs(result)
4192
- .filter((tx) => !xchainUtil.bnOrZero(tx.value).isZero())
4193
- .reduce((acc, cur) => {
4194
- const tx = getTxFromTokenTransaction(cur, chain, gasDecimals);
4195
- return tx ? [...acc, tx] : acc;
4196
- }, []);
4197
- });
4198
-
4199
- class EtherscanProvider {
4200
- constructor(provider, baseUrl, apiKey, chain, nativeAsset, nativeAssetDecimals) {
4201
- this.provider = provider;
4202
- this.baseUrl = baseUrl;
4203
- this.apiKey = apiKey;
4204
- this.chain = chain;
4205
- this.nativeAsset = nativeAsset;
4206
- this.nativeAssetDecimals = nativeAssetDecimals;
4207
- this.nativeAsset;
4208
- this.chain;
4209
- }
4210
- getBalance(address, assets) {
4211
- return __awaiter(this, void 0, void 0, function* () {
4212
- //validate assets are for the correct chain
4213
- assets === null || assets === void 0 ? void 0 : assets.forEach((i) => {
4214
- if (i.chain !== this.chain)
4215
- throw Error(`${xchainUtil.assetToString(i)} is not an asset of ${this.chain}`);
4216
- });
4217
- const balances = [];
4218
- balances.push(yield this.getNativeAssetBalance(address));
4219
- if (assets) {
4220
- for (const asset of assets) {
4221
- const splitSymbol = asset.symbol.split('-');
4222
- const tokenSymbol = splitSymbol[0];
4223
- const contractAddress = splitSymbol[1];
4224
- balances.push(yield this.getTokenBalance(address, contractAddress, tokenSymbol));
4225
- }
4226
- }
4227
- else {
4228
- // Get All Erc-20 txs
4229
- const response = (yield axios.get(`${this.baseUrl}/api?module=account&action=tokentx&address=${address}&sort=asc&apikey=${this.apiKey}`)).data;
4230
- const erc20TokenTxs = this.getUniqueContractAddresses(response.result);
4231
- for (const erc20Token of erc20TokenTxs) {
4232
- balances.push(yield this.getTokenBalance(address, erc20Token.contractAddress, erc20Token.tokenSymbol));
4233
- }
4234
- }
4235
- return balances;
4236
- });
4237
- }
4238
- getNativeAssetBalance(address) {
4239
- return __awaiter(this, void 0, void 0, function* () {
4240
- const gasAssetBalance = yield this.provider.getBalance(address.toLowerCase());
4241
- const amount = xchainUtil.baseAmount(gasAssetBalance.toString(), this.nativeAssetDecimals);
4242
- return {
4243
- asset: this.nativeAsset,
4244
- amount,
4245
- };
4246
- });
4247
- }
4248
- getTokenBalance(address, contractAddress, tokenTicker) {
4249
- return __awaiter(this, void 0, void 0, function* () {
4250
- const asset = {
4251
- chain: this.chain,
4252
- symbol: `${tokenTicker}-${contractAddress}`,
4253
- ticker: tokenTicker,
4254
- type: xchainUtil.AssetType.TOKEN,
4255
- };
4256
- const contract = new ethers.ethers.Contract(contractAddress.toLowerCase(), erc20ABI, this.provider);
4257
- const balance = (yield contract.balanceOf(address.toLowerCase())).toString();
4258
- const decimals = (yield contract.decimals()).toString();
4259
- const amount = xchainUtil.baseAmount(balance, Number.parseInt(decimals));
4260
- return {
4261
- asset,
4262
- amount,
4263
- };
4264
- });
4265
- }
4266
- getUniqueContractAddresses(array) {
4267
- const mySet = new Set();
4268
- return array.filter((x) => {
4269
- const key = x.contractAddress, isNew = !mySet.has(key);
4270
- if (isNew)
4271
- mySet.add(key);
4272
- return isNew;
4273
- });
4274
- }
4275
- getTransactions(params) {
4276
- return __awaiter(this, void 0, void 0, function* () {
4277
- const offset = (params === null || params === void 0 ? void 0 : params.offset) || 0;
4278
- const limit = (params === null || params === void 0 ? void 0 : params.limit) || 10;
4279
- const assetAddress = params === null || params === void 0 ? void 0 : params.asset;
4280
- const maxCount = 10000;
4281
- let transactions;
4282
- if (assetAddress) {
4283
- transactions = yield getTokenTransactionHistory({
4284
- gasDecimals: this.nativeAssetDecimals,
4285
- baseUrl: this.baseUrl,
4286
- address: params === null || params === void 0 ? void 0 : params.address,
4287
- assetAddress,
4288
- page: 0,
4289
- offset: maxCount,
4290
- apiKey: this.apiKey,
4291
- chain: this.chain,
4292
- });
4293
- }
4294
- else {
4295
- transactions = yield getGasAssetTransactionHistory({
4296
- gasAsset: this.nativeAsset,
4297
- gasDecimals: this.nativeAssetDecimals,
4298
- baseUrl: this.baseUrl,
4299
- address: params === null || params === void 0 ? void 0 : params.address,
4300
- page: 0,
4301
- offset: maxCount,
4302
- apiKey: this.apiKey,
4303
- });
4304
- }
4305
- return {
4306
- total: transactions.length,
4307
- txs: transactions.filter((_, index) => index >= offset && index < offset + limit),
4308
- };
4309
- });
4310
- }
4311
- getTransactionData(txHash, assetAddress) {
4312
- var _a, _b;
4313
- return __awaiter(this, void 0, void 0, function* () {
4314
- let tx;
4315
- const txInfo = yield this.provider.getTransaction(txHash);
4316
- if (txInfo) {
4317
- if (assetAddress) {
4318
- tx =
4319
- (_a = (yield getTokenTransactionHistory({
4320
- gasDecimals: this.nativeAssetDecimals,
4321
- baseUrl: this.baseUrl,
4322
- assetAddress,
4323
- address: txInfo.from,
4324
- startblock: txInfo.blockNumber,
4325
- endblock: txInfo.blockNumber ? txInfo.blockNumber + 1 : undefined,
4326
- apiKey: this.apiKey,
4327
- chain: this.chain,
4328
- })).filter((info) => info.hash === txHash)[0]) !== null && _a !== void 0 ? _a : null;
4329
- }
4330
- else {
4331
- tx =
4332
- (_b = (yield getGasAssetTransactionHistory({
4333
- gasAsset: this.nativeAsset,
4334
- gasDecimals: this.nativeAssetDecimals,
4335
- baseUrl: this.baseUrl,
4336
- startblock: txInfo.blockNumber,
4337
- endblock: txInfo.blockNumber ? txInfo.blockNumber + 1 : undefined,
4338
- apiKey: this.apiKey,
4339
- address: txInfo.from,
4340
- })).filter((info) => info.hash === txHash)[0]) !== null && _b !== void 0 ? _b : null;
4341
- }
4342
- }
4343
- if (!tx)
4344
- throw new Error('Could not get transaction history');
4345
- return tx;
4346
- });
4347
- }
4348
- getFeeRates() {
4349
- return __awaiter(this, void 0, void 0, function* () {
4350
- const gasOracleResponse = yield getGasOracle(this.baseUrl, this.apiKey);
4351
- return {
4352
- [xchainClient.FeeOption.Average]: Number(gasOracleResponse.SafeGasPrice) * Math.pow(10, 9),
4353
- [xchainClient.FeeOption.Fast]: Number(gasOracleResponse.ProposeGasPrice) * Math.pow(10, 9),
4354
- [xchainClient.FeeOption.Fastest]: Number(gasOracleResponse.FastGasPrice) * Math.pow(10, 9),
4355
- };
4356
- });
4357
- }
4358
- }
4359
-
4360
- // TODO: Study why this is needed
4361
- const AVAXChain = 'AVAX';
4362
- ({ chain: AVAXChain, symbol: 'AVAX', ticker: 'AVAX', type: xchainUtil.AssetType.NATIVE });
4363
-
4364
- const LOWER_FEE_BOUND = 1000000;
4365
- const UPPER_FEE_BOUND = 1000000000;
4366
- const BASE_GAS_ASSET_DECIMAL = 18;
4367
- const BASEChain = 'BASE';
4368
- // BASE ETH Gas asset
4369
- const AssetBETH = { chain: BASEChain, symbol: 'ETH', ticker: 'ETH', type: xchainUtil.AssetType.NATIVE };
4370
- // Define JSON-RPC providers for mainnet and testnet
4371
- const BASE_MAINNET_ETHERS_PROVIDER = new ethers.ethers.providers.JsonRpcProvider('https://1rpc.io/base');
4372
- const BASE_TESTNET_ETHERS_PROVIDER = new ethers.ethers.providers.JsonRpcProvider('https://base-sepolia-rpc.publicnode.com');
4373
- // Define ethers providers for different networks
4374
- const ethersJSProviders = {
4375
- [xchainClient.Network.Mainnet]: BASE_MAINNET_ETHERS_PROVIDER,
4376
- [xchainClient.Network.Testnet]: BASE_TESTNET_ETHERS_PROVIDER,
4377
- [xchainClient.Network.Stagenet]: BASE_MAINNET_ETHERS_PROVIDER,
4378
- };
4379
- // Define online providers (Etherscan) for mainnet and testnet
4380
- const BASE_ONLINE_PROVIDER_MAINNET = new EtherscanProvider(BASE_MAINNET_ETHERS_PROVIDER, 'https://api.basescan.org', process.env.BASE_API_KEY || '', BASEChain, AssetBETH, 18);
4381
- const BASE_ONLINE_PROVIDER_TESTNET = new EtherscanProvider(BASE_TESTNET_ETHERS_PROVIDER, 'https://api-sepolia.basescan.org', process.env.BASE_API_KEY || '', BASEChain, AssetBETH, 18);
4382
- // Define providers for different networks
4383
- const baseProviders = {
4384
- [xchainClient.Network.Mainnet]: BASE_ONLINE_PROVIDER_MAINNET,
4385
- [xchainClient.Network.Testnet]: BASE_ONLINE_PROVIDER_TESTNET,
4386
- [xchainClient.Network.Stagenet]: BASE_ONLINE_PROVIDER_MAINNET,
4387
- };
4388
- // Define explorer providers for mainnet and testnet
4389
- const BASE_MAINNET_EXPLORER = new xchainClient.ExplorerProvider('https://basescan.org/', 'https://basescan.org/address/%%ADDRESS%%', 'https://basescan.org/tx/%%TX_ID%%');
4390
- const BASE_TESTNET_EXPLORER = new xchainClient.ExplorerProvider('https://sepolia.basescan.org', 'https://sepolia.basescan.org/address/%%ADDRESS%%', 'https://sepolia.basescan.org/tx/%%TX_ID%%');
4391
- // Define explorer providers for different networks
4392
- const baseExplorerProviders = {
4393
- [xchainClient.Network.Mainnet]: BASE_MAINNET_EXPLORER,
4394
- [xchainClient.Network.Testnet]: BASE_TESTNET_EXPLORER,
4395
- [xchainClient.Network.Stagenet]: BASE_MAINNET_EXPLORER,
4396
- };
4397
- // Define root derivation paths for different networks
4398
- const ethRootDerivationPaths = {
4399
- [xchainClient.Network.Mainnet]: `m/44'/60'/0'/0/`,
4400
- [xchainClient.Network.Testnet]: `m/44'/60'/0'/0/`,
4401
- [xchainClient.Network.Stagenet]: `m/44'/60'/0'/0/`,
4402
- };
4403
- // Define default parameters for the Base client
4404
- // TODO: not sure
4405
- const defaults = {
4406
- [xchainClient.Network.Mainnet]: {
4407
- approveGasLimit: ethers.BigNumber.from(200000),
4408
- transferGasAssetGasLimit: ethers.BigNumber.from(23000),
4409
- transferTokenGasLimit: ethers.BigNumber.from(100000),
4410
- gasPrice: ethers.BigNumber.from(0.03 * Math.pow(10, 9)),
4411
- },
4412
- [xchainClient.Network.Testnet]: {
4413
- approveGasLimit: ethers.BigNumber.from(200000),
4414
- transferGasAssetGasLimit: ethers.BigNumber.from(23000),
4415
- transferTokenGasLimit: ethers.BigNumber.from(100000),
4416
- gasPrice: ethers.BigNumber.from(0.03 * Math.pow(10, 9)),
4417
- },
4418
- [xchainClient.Network.Stagenet]: {
4419
- approveGasLimit: ethers.BigNumber.from(200000),
4420
- transferGasAssetGasLimit: ethers.BigNumber.from(23000),
4421
- transferTokenGasLimit: ethers.BigNumber.from(100000),
4422
- gasPrice: ethers.BigNumber.from(0.2 * Math.pow(10, 9)),
4423
- },
4424
- };
4425
- // Define the default parameters for the Base client
4426
- const defaultBaseParams = {
4427
- chain: BASEChain,
4428
- gasAsset: AssetBETH,
4429
- gasAssetDecimals: BASE_GAS_ASSET_DECIMAL,
4430
- defaults,
4431
- providers: ethersJSProviders,
4432
- explorerProviders: baseExplorerProviders,
4433
- dataProviders: [baseProviders],
4434
- network: xchainClient.Network.Mainnet,
4435
- feeBounds: {
4436
- lower: LOWER_FEE_BOUND,
4437
- upper: UPPER_FEE_BOUND,
4438
- },
4439
- rootDerivationPaths: ethRootDerivationPaths,
4440
- };
4441
-
4442
- // Import the Client class from '@xchainjs/xchain-evm' module
4443
- // Create a class called Client that extends the XchainEvmClient class
4444
- class ClientKeystore extends xchainEvm.ClientKeystore {
4445
- // Constructor function that takes an optional config parameter, defaulting to defaultBaseParams
4446
- constructor(config = defaultBaseParams) {
4447
- // Call the constructor of the parent class (XchainEvmClient) with the provided config
4448
- super(Object.assign(Object.assign({}, config), { signer: config.phrase
4449
- ? new xchainEvm.KeystoreSigner({
4450
- phrase: config.phrase,
4451
- provider: config.providers[config.network || xchainClient.Network.Mainnet],
4452
- derivationPath: config.rootDerivationPaths
4453
- ? config.rootDerivationPaths[config.network || xchainClient.Network.Mainnet]
4454
- : '',
4455
- })
4456
- : undefined }));
4457
- }
4458
- }
4459
-
4460
52
  /**
4461
53
  * Check if a chain is EVM and supported by the protocol
4462
54
  * @param {Chain} chain to check
4463
55
  * @returns true if chain is EVM, otherwise, false
4464
56
  */
4465
57
  const isProtocolEVMChain = (chain) => {
4466
- return [xchainEthereum.AssetETH.chain, xchainBsc.AssetBSC.chain, xchainAvax.AssetAVAX.chain].includes(chain);
58
+ return [xchainEthereum.AssetETH.chain, xchainBsc.AssetBSC.chain, xchainAvax.AssetAVAX.chain, xchainBase.AssetBETH.chain].includes(chain);
4467
59
  };
4468
60
  /**
4469
61
  * Check if asset is ERC20
@@ -4472,7 +64,7 @@ const isProtocolEVMChain = (chain) => {
4472
64
  */
4473
65
  const isProtocolERC20Asset = (asset) => {
4474
66
  return isProtocolEVMChain(asset.chain)
4475
- ? [xchainEthereum.AssetETH, xchainAvax.AssetAVAX, xchainBsc.AssetBSC].findIndex((nativeEVMAsset) => xchainUtil.eqAsset(nativeEVMAsset, asset)) === -1 &&
67
+ ? [xchainEthereum.AssetETH, xchainAvax.AssetAVAX, xchainBsc.AssetBSC, xchainBase.AssetBETH].findIndex((nativeEVMAsset) => xchainUtil.eqAsset(nativeEVMAsset, asset)) === -1 &&
4476
68
  !xchainUtil.isSynthAsset(asset)
4477
69
  : false;
4478
70
  };
@@ -4483,8 +75,7 @@ const isProtocolERC20Asset = (asset) => {
4483
75
  */
4484
76
  const isTokenCryptoAmount = (amount) => {
4485
77
  return isProtocolEVMChain(amount.asset.chain)
4486
- ? [xchainEthereum.AssetETH, xchainAvax.AssetAVAX, xchainBsc.AssetBSC].findIndex((nativeEVMAsset) => xchainUtil.eqAsset(nativeEVMAsset, amount.asset)) === -1 &&
4487
- !xchainUtil.isSynthAsset(amount.asset)
78
+ ? [xchainEthereum.AssetETH, xchainAvax.AssetAVAX, xchainBsc.AssetBSC, xchainBase.AssetBETH].findIndex((nativeEVMAsset) => xchainUtil.eqAsset(nativeEVMAsset, amount.asset)) === -1 && !xchainUtil.isSynthAsset(amount.asset)
4488
79
  : false;
4489
80
  };
4490
81
  /**
@@ -4511,8 +102,8 @@ const validateAddress = (network, chain, address) => {
4511
102
  return new xchainAvax.Client(Object.assign(Object.assign({}, xchainAvax.defaultAvaxParams), { network })).validateAddress(address);
4512
103
  case xchainBsc.BSCChain:
4513
104
  return new xchainBsc.Client(Object.assign(Object.assign({}, xchainBsc.defaultBscParams), { network })).validateAddress(address);
4514
- case BASEChain:
4515
- return new ClientKeystore(Object.assign(Object.assign({}, defaultBaseParams), { network })).validateAddress(address);
105
+ case xchainBase.BASEChain:
106
+ return new xchainBase.Client(Object.assign(Object.assign({}, xchainBase.defaultBaseParams), { network })).validateAddress(address);
4516
107
  case xchainCosmos.GAIAChain:
4517
108
  return new xchainCosmos.Client({ network }).validateAddress(address);
4518
109
  case xchainThorchain.THORChain:
@@ -4524,14 +115,14 @@ const validateAddress = (network, chain, address) => {
4524
115
 
4525
116
  class ThorchainAction {
4526
117
  static makeAction(actionParams) {
4527
- return __awaiter$1(this, void 0, void 0, function* () {
118
+ return __awaiter(this, void 0, void 0, function* () {
4528
119
  return this.isNonProtocolParams(actionParams)
4529
120
  ? this.makeNonProtocolAction(actionParams)
4530
121
  : this.makeProtocolAction(actionParams);
4531
122
  });
4532
123
  }
4533
124
  static makeProtocolAction({ wallet, assetAmount, memo }) {
4534
- return __awaiter$1(this, void 0, void 0, function* () {
125
+ return __awaiter(this, void 0, void 0, function* () {
4535
126
  const hash = yield wallet.deposit({
4536
127
  chain: xchainThorchain.THORChain,
4537
128
  asset: assetAmount.asset,
@@ -4545,7 +136,7 @@ class ThorchainAction {
4545
136
  });
4546
137
  }
4547
138
  static makeNonProtocolAction({ wallet, assetAmount, recipient, memo, }) {
4548
- return __awaiter$1(this, void 0, void 0, function* () {
139
+ return __awaiter(this, void 0, void 0, function* () {
4549
140
  // Non EVM actions
4550
141
  if (!isProtocolEVMChain(assetAmount.asset.chain)) {
4551
142
  if (isProtocolBFTChain(assetAmount.asset.chain)) {
@@ -4647,7 +238,7 @@ class ThorchainAMM {
4647
238
  BSC: new xchainBsc.Client(Object.assign(Object.assign({}, xchainBsc.defaultBscParams), { network: xchainClient.Network.Mainnet })),
4648
239
  GAIA: new xchainCosmos.Client({ network: xchainClient.Network.Mainnet }),
4649
240
  THOR: new xchainThorchain.Client(Object.assign(Object.assign({}, xchainThorchain.defaultClientConfig), { network: xchainClient.Network.Mainnet })),
4650
- BASE: new ClientKeystore(Object.assign(Object.assign({}, defaultBaseParams), { network: xchainClient.Network.Mainnet })),
241
+ BASE: new xchainBase.Client(Object.assign(Object.assign({}, xchainBase.defaultBaseParams), { network: xchainClient.Network.Mainnet })),
4651
242
  })) {
4652
243
  this.thorchainQuery = thorchainQuery;
4653
244
  this.wallet = wallet;
@@ -4662,7 +253,7 @@ class ThorchainAMM {
4662
253
  * @returns The estimated swap details.
4663
254
  */
4664
255
  estimateSwap({ fromAddress, fromAsset, amount, destinationAsset, destinationAddress, affiliateAddress = '', affiliateBps = 0, toleranceBps, streamingInterval, streamingQuantity, }) {
4665
- return __awaiter$1(this, void 0, void 0, function* () {
256
+ return __awaiter(this, void 0, void 0, function* () {
4666
257
  const errors = yield this.validateSwap({
4667
258
  fromAddress,
4668
259
  fromAsset,
@@ -4693,7 +284,7 @@ class ThorchainAMM {
4693
284
  * @returns {string[]} the reasons the swap can not be done. If it is empty there are no reason to avoid the swap
4694
285
  */
4695
286
  validateSwap({ fromAsset, fromAddress, destinationAsset, destinationAddress, amount, affiliateAddress, affiliateBps, streamingInterval, streamingQuantity, }) {
4696
- return __awaiter$1(this, void 0, void 0, function* () {
287
+ return __awaiter(this, void 0, void 0, function* () {
4697
288
  const errors = [];
4698
289
  if (destinationAddress &&
4699
290
  !validateAddress(this.thorchainQuery.thorchainCache.midgardQuery.midgardCache.midgard.network, xchainUtil.isSynthAsset(destinationAsset) || xchainUtil.isTradeAsset(destinationAsset) || xchainUtil.isSecuredAsset(destinationAsset)
@@ -4746,7 +337,7 @@ class ThorchainAMM {
4746
337
  * @returns {SwapSubmitted} - The transaction hash, URL of BlockExplorer, and expected wait time.
4747
338
  */
4748
339
  doSwap({ fromAsset, fromAddress, amount, destinationAsset, destinationAddress, affiliateAddress, affiliateBps, toleranceBps, streamingInterval, streamingQuantity, }) {
4749
- return __awaiter$1(this, void 0, void 0, function* () {
340
+ return __awaiter(this, void 0, void 0, function* () {
4750
341
  // Retrieve swap details from ThorchainQuery to ensure validity
4751
342
  const txDetails = yield this.thorchainQuery.quoteSwap({
4752
343
  fromAsset,
@@ -4778,7 +369,7 @@ class ThorchainAMM {
4778
369
  * @returns {Promise<TxSubmitted>} Transaction hash and URL
4779
370
  */
4780
371
  approveRouterToSpend({ asset, amount }) {
4781
- return __awaiter$1(this, void 0, void 0, function* () {
372
+ return __awaiter(this, void 0, void 0, function* () {
4782
373
  // Get inbound details for the asset chain
4783
374
  const inboundDetails = yield this.thorchainQuery.getChainInboundDetails(asset.chain);
4784
375
  if (!inboundDetails.router)
@@ -4800,7 +391,7 @@ class ThorchainAMM {
4800
391
  * @returns {string[]} the reasons the router of the asset is not allowed to spend the amount. If it is empty, the asset router is allowed to spend the amount
4801
392
  */
4802
393
  isRouterApprovedToSpend({ asset, amount, address }) {
4803
- return __awaiter$1(this, void 0, void 0, function* () {
394
+ return __awaiter(this, void 0, void 0, function* () {
4804
395
  const errors = [];
4805
396
  if (!isProtocolERC20Asset(asset)) {
4806
397
  errors.push('Asset should be ERC20');
@@ -4821,7 +412,7 @@ class ThorchainAMM {
4821
412
  * @returns - The estimated liquidity addition object.
4822
413
  */
4823
414
  estimateAddLiquidity(params) {
4824
- return __awaiter$1(this, void 0, void 0, function* () {
415
+ return __awaiter(this, void 0, void 0, function* () {
4825
416
  return yield this.thorchainQuery.estimateAddLP(params);
4826
417
  });
4827
418
  }
@@ -4831,7 +422,7 @@ class ThorchainAMM {
4831
422
  * @returns - The estimated liquidity withdrawal object.
4832
423
  */
4833
424
  estimateWithdrawLiquidity(params) {
4834
- return __awaiter$1(this, void 0, void 0, function* () {
425
+ return __awaiter(this, void 0, void 0, function* () {
4835
426
  return yield this.thorchainQuery.estimateWithdrawLP(params);
4836
427
  });
4837
428
  }
@@ -4842,7 +433,7 @@ class ThorchainAMM {
4842
433
  * @returns
4843
434
  */
4844
435
  addLiquidityPosition(params) {
4845
- return __awaiter$1(this, void 0, void 0, function* () {
436
+ return __awaiter(this, void 0, void 0, function* () {
4846
437
  // Check amounts are greater than fees and use return estimated wait
4847
438
  const checkLPAdd = yield this.thorchainQuery.estimateAddLP(params);
4848
439
  if (!checkLPAdd.canAdd)
@@ -4901,7 +492,7 @@ class ThorchainAMM {
4901
492
  * @return - The array of transaction submissions.
4902
493
  */
4903
494
  withdrawLiquidityPosition(params) {
4904
- return __awaiter$1(this, void 0, void 0, function* () {
495
+ return __awaiter(this, void 0, void 0, function* () {
4905
496
  // Caution Dust Limits: BTC, BCH, LTC chains: 10k sats; DOGE: 1m Sats; ETH: 0 wei; THOR: 0 RUNE.
4906
497
  const withdrawParams = yield this.thorchainQuery.estimateWithdrawLP(params);
4907
498
  const withdrawLiquidity = {
@@ -4958,7 +549,7 @@ class ThorchainAMM {
4958
549
  * @returns The estimated addition to the saver object.
4959
550
  */
4960
551
  estimateAddSaver(addAssetAmount) {
4961
- return __awaiter$1(this, void 0, void 0, function* () {
552
+ return __awaiter(this, void 0, void 0, function* () {
4962
553
  return yield this.thorchainQuery.estimateAddSaver(addAssetAmount);
4963
554
  });
4964
555
  }
@@ -4968,7 +559,7 @@ class ThorchainAMM {
4968
559
  * @returns The estimated withdrawal from the saver object.
4969
560
  */
4970
561
  estimateWithdrawSaver(withdrawParams) {
4971
- return __awaiter$1(this, void 0, void 0, function* () {
562
+ return __awaiter(this, void 0, void 0, function* () {
4972
563
  return yield this.thorchainQuery.estimateWithdrawSaver(withdrawParams);
4973
564
  });
4974
565
  }
@@ -4978,7 +569,7 @@ class ThorchainAMM {
4978
569
  * @returns The saver position object.
4979
570
  */
4980
571
  getSaverPosition(getsaver) {
4981
- return __awaiter$1(this, void 0, void 0, function* () {
572
+ return __awaiter(this, void 0, void 0, function* () {
4982
573
  return yield this.thorchainQuery.getSaverPosition(getsaver);
4983
574
  });
4984
575
  }
@@ -4989,7 +580,7 @@ class ThorchainAMM {
4989
580
  * @returns - The submitted transaction.
4990
581
  */
4991
582
  addSaver(addAssetAmount) {
4992
- return __awaiter$1(this, void 0, void 0, function* () {
583
+ return __awaiter(this, void 0, void 0, function* () {
4993
584
  const addEstimate = yield this.thorchainQuery.estimateAddSaver(addAssetAmount);
4994
585
  if (!addEstimate.canAddSaver)
4995
586
  throw Error(`Cannot add to savers`);
@@ -5007,7 +598,7 @@ class ThorchainAMM {
5007
598
  * @returns The submitted transaction.
5008
599
  */
5009
600
  withdrawSaver(withdrawParams) {
5010
- return __awaiter$1(this, void 0, void 0, function* () {
601
+ return __awaiter(this, void 0, void 0, function* () {
5011
602
  const withdrawEstimate = yield this.thorchainQuery.estimateWithdrawSaver(withdrawParams);
5012
603
  if (withdrawEstimate.errors.length > 0)
5013
604
  throw Error(`${withdrawEstimate.errors}`);
@@ -5025,7 +616,7 @@ class ThorchainAMM {
5025
616
  * @returns The quote for opening the loan.
5026
617
  */
5027
618
  getLoanQuoteOpen(loanOpenParams) {
5028
- return __awaiter$1(this, void 0, void 0, function* () {
619
+ return __awaiter(this, void 0, void 0, function* () {
5029
620
  return yield this.thorchainQuery.getLoanQuoteOpen(loanOpenParams);
5030
621
  });
5031
622
  }
@@ -5035,7 +626,7 @@ class ThorchainAMM {
5035
626
  * @returns The quote for closing the loan.
5036
627
  */
5037
628
  getLoanQuoteClose(loanCloseParams) {
5038
- return __awaiter$1(this, void 0, void 0, function* () {
629
+ return __awaiter(this, void 0, void 0, function* () {
5039
630
  return yield this.thorchainQuery.getLoanQuoteClose(loanCloseParams);
5040
631
  });
5041
632
  }
@@ -5045,7 +636,7 @@ class ThorchainAMM {
5045
636
  * @returns - The submitted transaction.
5046
637
  */
5047
638
  addLoan(loanOpenParams) {
5048
- return __awaiter$1(this, void 0, void 0, function* () {
639
+ return __awaiter(this, void 0, void 0, function* () {
5049
640
  const loanOpen = yield this.thorchainQuery.getLoanQuoteOpen(loanOpenParams);
5050
641
  if (loanOpen.errors.length > 0)
5051
642
  throw Error(`${loanOpen.errors}`);
@@ -5063,7 +654,7 @@ class ThorchainAMM {
5063
654
  * @returns The submitted transaction.
5064
655
  */
5065
656
  withdrawLoan(loanCloseParams) {
5066
- return __awaiter$1(this, void 0, void 0, function* () {
657
+ return __awaiter(this, void 0, void 0, function* () {
5067
658
  const withdrawLoan = yield this.thorchainQuery.getLoanQuoteClose(loanCloseParams);
5068
659
  // Checks if there are any errors in the quote
5069
660
  if (withdrawLoan.errors.length > 0)
@@ -5082,7 +673,7 @@ class ThorchainAMM {
5082
673
  * @returns The Thornames data.
5083
674
  */
5084
675
  getThornamesByAddress(address) {
5085
- return __awaiter$1(this, void 0, void 0, function* () {
676
+ return __awaiter(this, void 0, void 0, function* () {
5086
677
  return this.thorchainQuery.thorchainCache.midgardQuery.midgardCache.midgard.getTHORNameReverseLookup(address);
5087
678
  });
5088
679
  }
@@ -5092,7 +683,7 @@ class ThorchainAMM {
5092
683
  * @returns {QuoteTHORName} Memo to make the registration and the estimation of the operation
5093
684
  */
5094
685
  estimateTHORNameRegistration(params) {
5095
- return __awaiter$1(this, void 0, void 0, function* () {
686
+ return __awaiter(this, void 0, void 0, function* () {
5096
687
  const errors = [];
5097
688
  if (!validateAddress(this.thorchainQuery.thorchainCache.midgardQuery.midgardCache.midgard.network, params.chain, params.chainAddress)) {
5098
689
  errors.push(`Invalid address ${params.chainAddress} for ${params.chain} chain`);
@@ -5129,7 +720,7 @@ class ThorchainAMM {
5129
720
  * @returns {QuoteTHORName} Memo to make the update and the estimation of the operation
5130
721
  */
5131
722
  estimateTHORNameUpdate(params) {
5132
- return __awaiter$1(this, void 0, void 0, function* () {
723
+ return __awaiter(this, void 0, void 0, function* () {
5133
724
  const errors = [];
5134
725
  if ((params.chain && !params.chainAddress) || (!params.chain && params.chainAddress)) {
5135
726
  errors.push(`Alias not provided correctly`);
@@ -5172,7 +763,7 @@ class ThorchainAMM {
5172
763
  * @returns {TxSubmitted} Transaction made to register the THORName
5173
764
  */
5174
765
  registerTHORName(params) {
5175
- return __awaiter$1(this, void 0, void 0, function* () {
766
+ return __awaiter(this, void 0, void 0, function* () {
5176
767
  const quote = yield this.estimateTHORNameRegistration(params);
5177
768
  if (!quote.allowed)
5178
769
  throw Error(`Can not register THORName. ${quote.errors.join(' ')}`);
@@ -5189,7 +780,7 @@ class ThorchainAMM {
5189
780
  * @returns {TxSubmitted} Transaction made to update the THORName
5190
781
  */
5191
782
  updateTHORName(params) {
5192
- return __awaiter$1(this, void 0, void 0, function* () {
783
+ return __awaiter(this, void 0, void 0, function* () {
5193
784
  const quote = yield this.estimateTHORNameUpdate(params);
5194
785
  if (!quote.allowed)
5195
786
  throw Error(`Can not update THORName. ${quote.errors.join(' ')}`);
@@ -5206,7 +797,7 @@ class ThorchainAMM {
5206
797
  * @returns {AddToTradeAccount} Estimation to add amount to trade account
5207
798
  */
5208
799
  estimateAddToTradeAccount({ amount, address }) {
5209
- return __awaiter$1(this, void 0, void 0, function* () {
800
+ return __awaiter(this, void 0, void 0, function* () {
5210
801
  const errors = [];
5211
802
  if (!validateAddress(this.thorchainQuery.thorchainCache.midgardQuery.midgardCache.midgard.network, xchainThorchain.THORChain, address)) {
5212
803
  errors.push('Invalid trade account address');
@@ -5242,7 +833,7 @@ class ThorchainAMM {
5242
833
  * @returns {TxSubmitted} Transaction made to add the trade amount
5243
834
  */
5244
835
  addToTradeAccount({ amount, address }) {
5245
- return __awaiter$1(this, void 0, void 0, function* () {
836
+ return __awaiter(this, void 0, void 0, function* () {
5246
837
  const quote = yield this.estimateAddToTradeAccount({ amount, address });
5247
838
  if (!quote.allowed)
5248
839
  throw Error(`Can not add to trade account. ${quote.errors.join(' ')}`);
@@ -5260,7 +851,7 @@ class ThorchainAMM {
5260
851
  * @returns {WithdrawFromTradeAccount} Estimation to withdraw amount from trade account
5261
852
  */
5262
853
  estimateWithdrawFromTradeAccount({ amount, address, }) {
5263
- return __awaiter$1(this, void 0, void 0, function* () {
854
+ return __awaiter(this, void 0, void 0, function* () {
5264
855
  const errors = [];
5265
856
  if (!validateAddress(this.thorchainQuery.thorchainCache.midgardQuery.midgardCache.midgard.network, amount.asset.chain, address)) {
5266
857
  errors.push('Invalid address to send the withdraw');
@@ -5287,7 +878,7 @@ class ThorchainAMM {
5287
878
  * @returns {TxSubmitted} Estimation to withdraw amount from trade account
5288
879
  */
5289
880
  withdrawFromTradeAccount({ amount, address }) {
5290
- return __awaiter$1(this, void 0, void 0, function* () {
881
+ return __awaiter(this, void 0, void 0, function* () {
5291
882
  const quote = yield this.estimateWithdrawFromTradeAccount({ amount, address });
5292
883
  if (!quote.allowed)
5293
884
  throw Error(`Can not withdraw from trade account. ${quote.errors.join(' ')}`);
@@ -5304,7 +895,7 @@ class ThorchainAMM {
5304
895
  * @returns {EstimateDepositToRunePool} Estimation to make the deposit
5305
896
  */
5306
897
  estimateDepositToRunePool({ amount }) {
5307
- return __awaiter$1(this, void 0, void 0, function* () {
898
+ return __awaiter(this, void 0, void 0, function* () {
5308
899
  const constants = yield this.thorchainQuery.thorchainCache.thornode.getTcConstants();
5309
900
  return {
5310
901
  allowed: true,
@@ -5321,7 +912,7 @@ class ThorchainAMM {
5321
912
  * @returns {TxSubmitted} Transaction made to deposit to Rune pool
5322
913
  */
5323
914
  depositToRunePool(params) {
5324
- return __awaiter$1(this, void 0, void 0, function* () {
915
+ return __awaiter(this, void 0, void 0, function* () {
5325
916
  const quote = yield this.estimateDepositToRunePool(params);
5326
917
  if (!quote.allowed)
5327
918
  throw Error(`Can not deposit to Rune pool. ${quote.errors.join(' ')}`);
@@ -5338,7 +929,7 @@ class ThorchainAMM {
5338
929
  * @returns {EstimateWithdrawFromRunePool} Estimation to make a withdraw from Rune pool
5339
930
  */
5340
931
  estimateWithdrawFromRunePool({ withdrawBps, affiliate, feeBps, }) {
5341
- return __awaiter$1(this, void 0, void 0, function* () {
932
+ return __awaiter(this, void 0, void 0, function* () {
5342
933
  const errors = [];
5343
934
  if (withdrawBps <= 0 || withdrawBps > 10000) {
5344
935
  errors.push('withdrawBps out of range. Range 0-10000');
@@ -5374,7 +965,7 @@ class ThorchainAMM {
5374
965
  * @returns {TxSubmitted} Transaction made to withdraw from Rune pool
5375
966
  */
5376
967
  withdrawFromRunePool(params) {
5377
- return __awaiter$1(this, void 0, void 0, function* () {
968
+ return __awaiter(this, void 0, void 0, function* () {
5378
969
  const quote = yield this.estimateWithdrawFromRunePool(params);
5379
970
  if (!quote.allowed)
5380
971
  throw Error(`Can not withdraw from Rune pool. ${quote.errors.join(' ')}`);
@@ -5386,7 +977,7 @@ class ThorchainAMM {
5386
977
  });
5387
978
  }
5388
979
  isTHORName(thorname) {
5389
- return __awaiter$1(this, void 0, void 0, function* () {
980
+ return __awaiter(this, void 0, void 0, function* () {
5390
981
  const details = yield this.thorchainQuery.getThornameDetails(thorname);
5391
982
  return details.owner !== '';
5392
983
  });