denotify-client 1.1.7 → 1.1.9

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