denotify-client 1.0.0

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