proto-sudoku-wc 0.0.485 → 0.0.487

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.
@@ -250,2940 +250,485 @@ const createStore = (defaultState, shouldUpdate) => {
250
250
  return map;
251
251
  };
252
252
 
253
- function bind(fn, thisArg) {
254
- return function wrap() {
255
- return fn.apply(thisArg, arguments);
256
- };
257
- }
258
-
259
- // utils is a library of generic helper functions non-specific to axios
260
-
261
- const {toString} = Object.prototype;
262
- const {getPrototypeOf} = Object;
263
-
264
- const kindOf = (cache => thing => {
265
- const str = toString.call(thing);
266
- return cache[str] || (cache[str] = str.slice(8, -1).toLowerCase());
267
- })(Object.create(null));
268
-
269
- const kindOfTest = (type) => {
270
- type = type.toLowerCase();
271
- return (thing) => kindOf(thing) === type
272
- };
273
-
274
- const typeOfTest = type => thing => typeof thing === type;
275
-
276
- /**
277
- * Determine if a value is an Array
278
- *
279
- * @param {Object} val The value to test
280
- *
281
- * @returns {boolean} True if value is an Array, otherwise false
282
- */
283
- const {isArray} = Array;
284
-
285
- /**
286
- * Determine if a value is undefined
287
- *
288
- * @param {*} val The value to test
289
- *
290
- * @returns {boolean} True if the value is undefined, otherwise false
291
- */
292
- const isUndefined = typeOfTest('undefined');
293
-
294
- /**
295
- * Determine if a value is a Buffer
296
- *
297
- * @param {*} val The value to test
298
- *
299
- * @returns {boolean} True if value is a Buffer, otherwise false
300
- */
301
- function isBuffer(val) {
302
- return val !== null && !isUndefined(val) && val.constructor !== null && !isUndefined(val.constructor)
303
- && isFunction(val.constructor.isBuffer) && val.constructor.isBuffer(val);
304
- }
305
-
306
- /**
307
- * Determine if a value is an ArrayBuffer
308
- *
309
- * @param {*} val The value to test
310
- *
311
- * @returns {boolean} True if value is an ArrayBuffer, otherwise false
312
- */
313
- const isArrayBuffer = kindOfTest('ArrayBuffer');
314
-
315
-
316
- /**
317
- * Determine if a value is a view on an ArrayBuffer
318
- *
319
- * @param {*} val The value to test
320
- *
321
- * @returns {boolean} True if value is a view on an ArrayBuffer, otherwise false
322
- */
323
- function isArrayBufferView(val) {
324
- let result;
325
- if ((typeof ArrayBuffer !== 'undefined') && (ArrayBuffer.isView)) {
326
- result = ArrayBuffer.isView(val);
327
- } else {
328
- result = (val) && (val.buffer) && (isArrayBuffer(val.buffer));
329
- }
330
- return result;
331
- }
332
-
333
- /**
334
- * Determine if a value is a String
335
- *
336
- * @param {*} val The value to test
337
- *
338
- * @returns {boolean} True if value is a String, otherwise false
339
- */
340
- const isString = typeOfTest('string');
341
-
342
- /**
343
- * Determine if a value is a Function
344
- *
345
- * @param {*} val The value to test
346
- * @returns {boolean} True if value is a Function, otherwise false
347
- */
348
- const isFunction = typeOfTest('function');
349
-
350
- /**
351
- * Determine if a value is a Number
352
- *
353
- * @param {*} val The value to test
354
- *
355
- * @returns {boolean} True if value is a Number, otherwise false
356
- */
357
- const isNumber = typeOfTest('number');
358
-
359
- /**
360
- * Determine if a value is an Object
361
- *
362
- * @param {*} thing The value to test
363
- *
364
- * @returns {boolean} True if value is an Object, otherwise false
365
- */
366
- const isObject = (thing) => thing !== null && typeof thing === 'object';
367
-
368
- /**
369
- * Determine if a value is a Boolean
370
- *
371
- * @param {*} thing The value to test
372
- * @returns {boolean} True if value is a Boolean, otherwise false
373
- */
374
- const isBoolean = thing => thing === true || thing === false;
375
-
376
- /**
377
- * Determine if a value is a plain Object
378
- *
379
- * @param {*} val The value to test
380
- *
381
- * @returns {boolean} True if value is a plain Object, otherwise false
382
- */
383
- const isPlainObject = (val) => {
384
- if (kindOf(val) !== 'object') {
385
- return false;
386
- }
387
-
388
- const prototype = getPrototypeOf(val);
389
- return prototype === null || prototype === Object.prototype;
390
- };
391
-
392
- /**
393
- * Determine if a value is a Date
394
- *
395
- * @param {*} val The value to test
396
- *
397
- * @returns {boolean} True if value is a Date, otherwise false
398
- */
399
- const isDate = kindOfTest('Date');
400
-
401
- /**
402
- * Determine if a value is a File
403
- *
404
- * @param {*} val The value to test
405
- *
406
- * @returns {boolean} True if value is a File, otherwise false
407
- */
408
- const isFile = kindOfTest('File');
409
-
410
- /**
411
- * Determine if a value is a Blob
412
- *
413
- * @param {*} val The value to test
414
- *
415
- * @returns {boolean} True if value is a Blob, otherwise false
416
- */
417
- const isBlob = kindOfTest('Blob');
418
-
419
- /**
420
- * Determine if a value is a FileList
421
- *
422
- * @param {*} val The value to test
423
- *
424
- * @returns {boolean} True if value is a File, otherwise false
425
- */
426
- const isFileList = kindOfTest('FileList');
427
-
428
- /**
429
- * Determine if a value is a Stream
430
- *
431
- * @param {*} val The value to test
432
- *
433
- * @returns {boolean} True if value is a Stream, otherwise false
434
- */
435
- const isStream = (val) => isObject(val) && isFunction(val.pipe);
436
-
437
- /**
438
- * Determine if a value is a FormData
439
- *
440
- * @param {*} thing The value to test
441
- *
442
- * @returns {boolean} True if value is an FormData, otherwise false
443
- */
444
- const isFormData = (thing) => {
445
- const pattern = '[object FormData]';
446
- return thing && (
447
- (typeof FormData === 'function' && thing instanceof FormData) ||
448
- toString.call(thing) === pattern ||
449
- (isFunction(thing.toString) && thing.toString() === pattern)
450
- );
451
- };
452
-
453
- /**
454
- * Determine if a value is a URLSearchParams object
455
- *
456
- * @param {*} val The value to test
457
- *
458
- * @returns {boolean} True if value is a URLSearchParams object, otherwise false
459
- */
460
- const isURLSearchParams = kindOfTest('URLSearchParams');
461
-
462
- /**
463
- * Trim excess whitespace off the beginning and end of a string
464
- *
465
- * @param {String} str The String to trim
466
- *
467
- * @returns {String} The String freed of excess whitespace
468
- */
469
- const trim = (str) => str.trim ?
470
- str.trim() : str.replace(/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g, '');
471
-
472
- /**
473
- * Iterate over an Array or an Object invoking a function for each item.
474
- *
475
- * If `obj` is an Array callback will be called passing
476
- * the value, index, and complete array for each item.
477
- *
478
- * If 'obj' is an Object callback will be called passing
479
- * the value, key, and complete object for each property.
480
- *
481
- * @param {Object|Array} obj The object to iterate
482
- * @param {Function} fn The callback to invoke for each item
483
- *
484
- * @param {Boolean} [allOwnKeys = false]
485
- * @returns {void}
486
- */
487
- function forEach(obj, fn, {allOwnKeys = false} = {}) {
488
- // Don't bother if no value provided
489
- if (obj === null || typeof obj === 'undefined') {
490
- return;
491
- }
492
-
493
- let i;
494
- let l;
495
-
496
- // Force an array if not already something iterable
497
- if (typeof obj !== 'object') {
498
- /*eslint no-param-reassign:0*/
499
- obj = [obj];
500
- }
501
-
502
- if (isArray(obj)) {
503
- // Iterate over array values
504
- for (i = 0, l = obj.length; i < l; i++) {
505
- fn.call(null, obj[i], i, obj);
506
- }
507
- } else {
508
- // Iterate over object keys
509
- const keys = allOwnKeys ? Object.getOwnPropertyNames(obj) : Object.keys(obj);
510
- const len = keys.length;
511
- let key;
512
-
513
- for (i = 0; i < len; i++) {
514
- key = keys[i];
515
- fn.call(null, obj[key], key, obj);
516
- }
517
- }
518
- }
519
-
520
- /**
521
- * Accepts varargs expecting each argument to be an object, then
522
- * immutably merges the properties of each object and returns result.
523
- *
524
- * When multiple objects contain the same key the later object in
525
- * the arguments list will take precedence.
526
- *
527
- * Example:
528
- *
529
- * ```js
530
- * var result = merge({foo: 123}, {foo: 456});
531
- * console.log(result.foo); // outputs 456
532
- * ```
533
- *
534
- * @param {Object} obj1 Object to merge
535
- *
536
- * @returns {Object} Result of all merge properties
537
- */
538
- function merge(/* obj1, obj2, obj3, ... */) {
539
- const result = {};
540
- const assignValue = (val, key) => {
541
- if (isPlainObject(result[key]) && isPlainObject(val)) {
542
- result[key] = merge(result[key], val);
543
- } else if (isPlainObject(val)) {
544
- result[key] = merge({}, val);
545
- } else if (isArray(val)) {
546
- result[key] = val.slice();
547
- } else {
548
- result[key] = val;
549
- }
550
- };
551
-
552
- for (let i = 0, l = arguments.length; i < l; i++) {
553
- arguments[i] && forEach(arguments[i], assignValue);
554
- }
555
- return result;
556
- }
557
-
558
- /**
559
- * Extends object a by mutably adding to it the properties of object b.
560
- *
561
- * @param {Object} a The object to be extended
562
- * @param {Object} b The object to copy properties from
563
- * @param {Object} thisArg The object to bind function to
564
- *
565
- * @param {Boolean} [allOwnKeys]
566
- * @returns {Object} The resulting value of object a
567
- */
568
- const extend = (a, b, thisArg, {allOwnKeys}= {}) => {
569
- forEach(b, (val, key) => {
570
- if (thisArg && isFunction(val)) {
571
- a[key] = bind(val, thisArg);
572
- } else {
573
- a[key] = val;
574
- }
575
- }, {allOwnKeys});
576
- return a;
577
- };
578
-
579
- /**
580
- * Remove byte order marker. This catches EF BB BF (the UTF-8 BOM)
581
- *
582
- * @param {string} content with BOM
583
- *
584
- * @returns {string} content value without BOM
585
- */
586
- const stripBOM = (content) => {
587
- if (content.charCodeAt(0) === 0xFEFF) {
588
- content = content.slice(1);
589
- }
590
- return content;
591
- };
592
-
593
- /**
594
- * Inherit the prototype methods from one constructor into another
595
- * @param {function} constructor
596
- * @param {function} superConstructor
597
- * @param {object} [props]
598
- * @param {object} [descriptors]
599
- *
600
- * @returns {void}
601
- */
602
- const inherits = (constructor, superConstructor, props, descriptors) => {
603
- constructor.prototype = Object.create(superConstructor.prototype, descriptors);
604
- constructor.prototype.constructor = constructor;
605
- Object.defineProperty(constructor, 'super', {
606
- value: superConstructor.prototype
607
- });
608
- props && Object.assign(constructor.prototype, props);
609
- };
610
-
611
- /**
612
- * Resolve object with deep prototype chain to a flat object
613
- * @param {Object} sourceObj source object
614
- * @param {Object} [destObj]
615
- * @param {Function|Boolean} [filter]
616
- * @param {Function} [propFilter]
617
- *
618
- * @returns {Object}
619
- */
620
- const toFlatObject = (sourceObj, destObj, filter, propFilter) => {
621
- let props;
622
- let i;
623
- let prop;
624
- const merged = {};
625
-
626
- destObj = destObj || {};
627
- // eslint-disable-next-line no-eq-null,eqeqeq
628
- if (sourceObj == null) return destObj;
629
-
630
- do {
631
- props = Object.getOwnPropertyNames(sourceObj);
632
- i = props.length;
633
- while (i-- > 0) {
634
- prop = props[i];
635
- if ((!propFilter || propFilter(prop, sourceObj, destObj)) && !merged[prop]) {
636
- destObj[prop] = sourceObj[prop];
637
- merged[prop] = true;
638
- }
639
- }
640
- sourceObj = filter !== false && getPrototypeOf(sourceObj);
641
- } while (sourceObj && (!filter || filter(sourceObj, destObj)) && sourceObj !== Object.prototype);
642
-
643
- return destObj;
644
- };
645
-
646
- /**
647
- * Determines whether a string ends with the characters of a specified string
648
- *
649
- * @param {String} str
650
- * @param {String} searchString
651
- * @param {Number} [position= 0]
652
- *
653
- * @returns {boolean}
654
- */
655
- const endsWith = (str, searchString, position) => {
656
- str = String(str);
657
- if (position === undefined || position > str.length) {
658
- position = str.length;
659
- }
660
- position -= searchString.length;
661
- const lastIndex = str.indexOf(searchString, position);
662
- return lastIndex !== -1 && lastIndex === position;
663
- };
664
-
665
-
666
- /**
667
- * Returns new array from array like object or null if failed
668
- *
669
- * @param {*} [thing]
670
- *
671
- * @returns {?Array}
672
- */
673
- const toArray = (thing) => {
674
- if (!thing) return null;
675
- if (isArray(thing)) return thing;
676
- let i = thing.length;
677
- if (!isNumber(i)) return null;
678
- const arr = new Array(i);
679
- while (i-- > 0) {
680
- arr[i] = thing[i];
681
- }
682
- return arr;
683
- };
684
-
685
- /**
686
- * Checking if the Uint8Array exists and if it does, it returns a function that checks if the
687
- * thing passed in is an instance of Uint8Array
688
- *
689
- * @param {TypedArray}
690
- *
691
- * @returns {Array}
692
- */
693
- // eslint-disable-next-line func-names
694
- const isTypedArray = (TypedArray => {
695
- // eslint-disable-next-line func-names
696
- return thing => {
697
- return TypedArray && thing instanceof TypedArray;
698
- };
699
- })(typeof Uint8Array !== 'undefined' && getPrototypeOf(Uint8Array));
700
-
701
- /**
702
- * For each entry in the object, call the function with the key and value.
703
- *
704
- * @param {Object<any, any>} obj - The object to iterate over.
705
- * @param {Function} fn - The function to call for each entry.
706
- *
707
- * @returns {void}
708
- */
709
- const forEachEntry = (obj, fn) => {
710
- const generator = obj && obj[Symbol.iterator];
711
-
712
- const iterator = generator.call(obj);
713
-
714
- let result;
715
-
716
- while ((result = iterator.next()) && !result.done) {
717
- const pair = result.value;
718
- fn.call(obj, pair[0], pair[1]);
719
- }
720
- };
721
-
722
- /**
723
- * It takes a regular expression and a string, and returns an array of all the matches
724
- *
725
- * @param {string} regExp - The regular expression to match against.
726
- * @param {string} str - The string to search.
727
- *
728
- * @returns {Array<boolean>}
729
- */
730
- const matchAll = (regExp, str) => {
731
- let matches;
732
- const arr = [];
733
-
734
- while ((matches = regExp.exec(str)) !== null) {
735
- arr.push(matches);
736
- }
737
-
738
- return arr;
739
- };
740
-
741
- /* Checking if the kindOfTest function returns true when passed an HTMLFormElement. */
742
- const isHTMLForm = kindOfTest('HTMLFormElement');
743
-
744
- const toCamelCase = str => {
745
- return str.toLowerCase().replace(/[_-\s]([a-z\d])(\w*)/g,
746
- function replacer(m, p1, p2) {
747
- return p1.toUpperCase() + p2;
748
- }
749
- );
750
- };
751
-
752
- /* Creating a function that will check if an object has a property. */
753
- const hasOwnProperty = (({hasOwnProperty}) => (obj, prop) => hasOwnProperty.call(obj, prop))(Object.prototype);
754
-
755
- /**
756
- * Determine if a value is a RegExp object
757
- *
758
- * @param {*} val The value to test
759
- *
760
- * @returns {boolean} True if value is a RegExp object, otherwise false
761
- */
762
- const isRegExp = kindOfTest('RegExp');
763
-
764
- const reduceDescriptors = (obj, reducer) => {
765
- const descriptors = Object.getOwnPropertyDescriptors(obj);
766
- const reducedDescriptors = {};
767
-
768
- forEach(descriptors, (descriptor, name) => {
769
- if (reducer(descriptor, name, obj) !== false) {
770
- reducedDescriptors[name] = descriptor;
771
- }
772
- });
773
-
774
- Object.defineProperties(obj, reducedDescriptors);
775
- };
776
-
777
- /**
778
- * Makes all methods read-only
779
- * @param {Object} obj
780
- */
781
-
782
- const freezeMethods = (obj) => {
783
- reduceDescriptors(obj, (descriptor, name) => {
784
- const value = obj[name];
785
-
786
- if (!isFunction(value)) return;
787
-
788
- descriptor.enumerable = false;
789
-
790
- if ('writable' in descriptor) {
791
- descriptor.writable = false;
792
- return;
793
- }
794
-
795
- if (!descriptor.set) {
796
- descriptor.set = () => {
797
- throw Error('Can not read-only method \'' + name + '\'');
798
- };
799
- }
800
- });
801
- };
802
-
803
- const toObjectSet = (arrayOrString, delimiter) => {
804
- const obj = {};
805
-
806
- const define = (arr) => {
807
- arr.forEach(value => {
808
- obj[value] = true;
809
- });
810
- };
811
-
812
- isArray(arrayOrString) ? define(arrayOrString) : define(String(arrayOrString).split(delimiter));
813
-
814
- return obj;
815
- };
816
-
817
- const noop = () => {};
818
-
819
- const toFiniteNumber = (value, defaultValue) => {
820
- value = +value;
821
- return Number.isFinite(value) ? value : defaultValue;
822
- };
823
-
824
- const utils = {
825
- isArray,
826
- isArrayBuffer,
827
- isBuffer,
828
- isFormData,
829
- isArrayBufferView,
830
- isString,
831
- isNumber,
832
- isBoolean,
833
- isObject,
834
- isPlainObject,
835
- isUndefined,
836
- isDate,
837
- isFile,
838
- isBlob,
839
- isRegExp,
840
- isFunction,
841
- isStream,
842
- isURLSearchParams,
843
- isTypedArray,
844
- isFileList,
845
- forEach,
846
- merge,
847
- extend,
848
- trim,
849
- stripBOM,
850
- inherits,
851
- toFlatObject,
852
- kindOf,
853
- kindOfTest,
854
- endsWith,
855
- toArray,
856
- forEachEntry,
857
- matchAll,
858
- isHTMLForm,
859
- hasOwnProperty,
860
- hasOwnProp: hasOwnProperty, // an alias to avoid ESLint no-prototype-builtins detection
861
- reduceDescriptors,
862
- freezeMethods,
863
- toObjectSet,
864
- toCamelCase,
865
- noop,
866
- toFiniteNumber
867
- };
868
-
869
- /**
870
- * Create an Error with the specified message, config, error code, request and response.
871
- *
872
- * @param {string} message The error message.
873
- * @param {string} [code] The error code (for example, 'ECONNABORTED').
874
- * @param {Object} [config] The config.
875
- * @param {Object} [request] The request.
876
- * @param {Object} [response] The response.
877
- *
878
- * @returns {Error} The created error.
879
- */
880
- function AxiosError(message, code, config, request, response) {
881
- Error.call(this);
882
-
883
- if (Error.captureStackTrace) {
884
- Error.captureStackTrace(this, this.constructor);
885
- } else {
886
- this.stack = (new Error()).stack;
887
- }
888
-
889
- this.message = message;
890
- this.name = 'AxiosError';
891
- code && (this.code = code);
892
- config && (this.config = config);
893
- request && (this.request = request);
894
- response && (this.response = response);
895
- }
896
-
897
- utils.inherits(AxiosError, Error, {
898
- toJSON: function toJSON() {
899
- return {
900
- // Standard
901
- message: this.message,
902
- name: this.name,
903
- // Microsoft
904
- description: this.description,
905
- number: this.number,
906
- // Mozilla
907
- fileName: this.fileName,
908
- lineNumber: this.lineNumber,
909
- columnNumber: this.columnNumber,
910
- stack: this.stack,
911
- // Axios
912
- config: this.config,
913
- code: this.code,
914
- status: this.response && this.response.status ? this.response.status : null
915
- };
916
- }
917
- });
918
-
919
- const prototype$1 = AxiosError.prototype;
920
- const descriptors = {};
921
-
922
- [
923
- 'ERR_BAD_OPTION_VALUE',
924
- 'ERR_BAD_OPTION',
925
- 'ECONNABORTED',
926
- 'ETIMEDOUT',
927
- 'ERR_NETWORK',
928
- 'ERR_FR_TOO_MANY_REDIRECTS',
929
- 'ERR_DEPRECATED',
930
- 'ERR_BAD_RESPONSE',
931
- 'ERR_BAD_REQUEST',
932
- 'ERR_CANCELED',
933
- 'ERR_NOT_SUPPORT',
934
- 'ERR_INVALID_URL'
935
- // eslint-disable-next-line func-names
936
- ].forEach(code => {
937
- descriptors[code] = {value: code};
938
- });
939
-
940
- Object.defineProperties(AxiosError, descriptors);
941
- Object.defineProperty(prototype$1, 'isAxiosError', {value: true});
942
-
943
- // eslint-disable-next-line func-names
944
- AxiosError.from = (error, code, config, request, response, customProps) => {
945
- const axiosError = Object.create(prototype$1);
946
-
947
- utils.toFlatObject(error, axiosError, function filter(obj) {
948
- return obj !== Error.prototype;
949
- }, prop => {
950
- return prop !== 'isAxiosError';
951
- });
952
-
953
- AxiosError.call(axiosError, error.message, code, config, request, response);
954
-
955
- axiosError.cause = error;
956
-
957
- axiosError.name = error.name;
958
-
959
- customProps && Object.assign(axiosError, customProps);
960
-
961
- return axiosError;
962
- };
963
-
964
- /* eslint-env browser */
965
- var browser = typeof self == 'object' ? self.FormData : window.FormData;
966
-
967
- /**
968
- * Determines if the given thing is a array or js object.
969
- *
970
- * @param {string} thing - The object or array to be visited.
971
- *
972
- * @returns {boolean}
973
- */
974
- function isVisitable(thing) {
975
- return utils.isPlainObject(thing) || utils.isArray(thing);
976
- }
977
-
978
- /**
979
- * It removes the brackets from the end of a string
980
- *
981
- * @param {string} key - The key of the parameter.
982
- *
983
- * @returns {string} the key without the brackets.
984
- */
985
- function removeBrackets(key) {
986
- return utils.endsWith(key, '[]') ? key.slice(0, -2) : key;
987
- }
988
-
989
- /**
990
- * It takes a path, a key, and a boolean, and returns a string
991
- *
992
- * @param {string} path - The path to the current key.
993
- * @param {string} key - The key of the current object being iterated over.
994
- * @param {string} dots - If true, the key will be rendered with dots instead of brackets.
995
- *
996
- * @returns {string} The path to the current key.
997
- */
998
- function renderKey(path, key, dots) {
999
- if (!path) return key;
1000
- return path.concat(key).map(function each(token, i) {
1001
- // eslint-disable-next-line no-param-reassign
1002
- token = removeBrackets(token);
1003
- return !dots && i ? '[' + token + ']' : token;
1004
- }).join(dots ? '.' : '');
1005
- }
1006
-
1007
- /**
1008
- * If the array is an array and none of its elements are visitable, then it's a flat array.
1009
- *
1010
- * @param {Array<any>} arr - The array to check
1011
- *
1012
- * @returns {boolean}
1013
- */
1014
- function isFlatArray(arr) {
1015
- return utils.isArray(arr) && !arr.some(isVisitable);
1016
- }
1017
-
1018
- const predicates = utils.toFlatObject(utils, {}, null, function filter(prop) {
1019
- return /^is[A-Z]/.test(prop);
1020
- });
1021
-
1022
- /**
1023
- * If the thing is a FormData object, return true, otherwise return false.
1024
- *
1025
- * @param {unknown} thing - The thing to check.
1026
- *
1027
- * @returns {boolean}
1028
- */
1029
- function isSpecCompliant(thing) {
1030
- return thing && utils.isFunction(thing.append) && thing[Symbol.toStringTag] === 'FormData' && thing[Symbol.iterator];
1031
- }
1032
-
1033
- /**
1034
- * Convert a data object to FormData
1035
- *
1036
- * @param {Object} obj
1037
- * @param {?Object} [formData]
1038
- * @param {?Object} [options]
1039
- * @param {Function} [options.visitor]
1040
- * @param {Boolean} [options.metaTokens = true]
1041
- * @param {Boolean} [options.dots = false]
1042
- * @param {?Boolean} [options.indexes = false]
1043
- *
1044
- * @returns {Object}
1045
- **/
1046
-
1047
- /**
1048
- * It converts an object into a FormData object
1049
- *
1050
- * @param {Object<any, any>} obj - The object to convert to form data.
1051
- * @param {string} formData - The FormData object to append to.
1052
- * @param {Object<string, any>} options
1053
- *
1054
- * @returns
1055
- */
1056
- function toFormData(obj, formData, options) {
1057
- if (!utils.isObject(obj)) {
1058
- throw new TypeError('target must be an object');
1059
- }
1060
-
1061
- // eslint-disable-next-line no-param-reassign
1062
- formData = formData || new (browser || FormData)();
1063
-
1064
- // eslint-disable-next-line no-param-reassign
1065
- options = utils.toFlatObject(options, {
1066
- metaTokens: true,
1067
- dots: false,
1068
- indexes: false
1069
- }, false, function defined(option, source) {
1070
- // eslint-disable-next-line no-eq-null,eqeqeq
1071
- return !utils.isUndefined(source[option]);
1072
- });
1073
-
1074
- const metaTokens = options.metaTokens;
1075
- // eslint-disable-next-line no-use-before-define
1076
- const visitor = options.visitor || defaultVisitor;
1077
- const dots = options.dots;
1078
- const indexes = options.indexes;
1079
- const _Blob = options.Blob || typeof Blob !== 'undefined' && Blob;
1080
- const useBlob = _Blob && isSpecCompliant(formData);
1081
-
1082
- if (!utils.isFunction(visitor)) {
1083
- throw new TypeError('visitor must be a function');
1084
- }
1085
-
1086
- function convertValue(value) {
1087
- if (value === null) return '';
1088
-
1089
- if (utils.isDate(value)) {
1090
- return value.toISOString();
1091
- }
1092
-
1093
- if (!useBlob && utils.isBlob(value)) {
1094
- throw new AxiosError('Blob is not supported. Use a Buffer instead.');
1095
- }
1096
-
1097
- if (utils.isArrayBuffer(value) || utils.isTypedArray(value)) {
1098
- return useBlob && typeof Blob === 'function' ? new Blob([value]) : Buffer.from(value);
1099
- }
1100
-
1101
- return value;
1102
- }
1103
-
1104
- /**
1105
- * Default visitor.
1106
- *
1107
- * @param {*} value
1108
- * @param {String|Number} key
1109
- * @param {Array<String|Number>} path
1110
- * @this {FormData}
1111
- *
1112
- * @returns {boolean} return true to visit the each prop of the value recursively
1113
- */
1114
- function defaultVisitor(value, key, path) {
1115
- let arr = value;
1116
-
1117
- if (value && !path && typeof value === 'object') {
1118
- if (utils.endsWith(key, '{}')) {
1119
- // eslint-disable-next-line no-param-reassign
1120
- key = metaTokens ? key : key.slice(0, -2);
1121
- // eslint-disable-next-line no-param-reassign
1122
- value = JSON.stringify(value);
1123
- } else if (
1124
- (utils.isArray(value) && isFlatArray(value)) ||
1125
- (utils.isFileList(value) || utils.endsWith(key, '[]') && (arr = utils.toArray(value))
1126
- )) {
1127
- // eslint-disable-next-line no-param-reassign
1128
- key = removeBrackets(key);
1129
-
1130
- arr.forEach(function each(el, index) {
1131
- !utils.isUndefined(el) && formData.append(
1132
- // eslint-disable-next-line no-nested-ternary
1133
- indexes === true ? renderKey([key], index, dots) : (indexes === null ? key : key + '[]'),
1134
- convertValue(el)
1135
- );
1136
- });
1137
- return false;
1138
- }
1139
- }
1140
-
1141
- if (isVisitable(value)) {
1142
- return true;
1143
- }
1144
-
1145
- formData.append(renderKey(path, key, dots), convertValue(value));
1146
-
1147
- return false;
1148
- }
1149
-
1150
- const stack = [];
1151
-
1152
- const exposedHelpers = Object.assign(predicates, {
1153
- defaultVisitor,
1154
- convertValue,
1155
- isVisitable
1156
- });
1157
-
1158
- function build(value, path) {
1159
- if (utils.isUndefined(value)) return;
1160
-
1161
- if (stack.indexOf(value) !== -1) {
1162
- throw Error('Circular reference detected in ' + path.join('.'));
1163
- }
1164
-
1165
- stack.push(value);
1166
-
1167
- utils.forEach(value, function each(el, key) {
1168
- const result = !utils.isUndefined(el) && visitor.call(
1169
- formData, el, utils.isString(key) ? key.trim() : key, path, exposedHelpers
1170
- );
1171
-
1172
- if (result === true) {
1173
- build(el, path ? path.concat(key) : [key]);
1174
- }
1175
- });
1176
-
1177
- stack.pop();
1178
- }
1179
-
1180
- if (!utils.isObject(obj)) {
1181
- throw new TypeError('data must be an object');
1182
- }
1183
-
1184
- build(obj);
1185
-
1186
- return formData;
1187
- }
1188
-
1189
- /**
1190
- * It encodes a string by replacing all characters that are not in the unreserved set with
1191
- * their percent-encoded equivalents
1192
- *
1193
- * @param {string} str - The string to encode.
1194
- *
1195
- * @returns {string} The encoded string.
1196
- */
1197
- function encode$1(str) {
1198
- const charMap = {
1199
- '!': '%21',
1200
- "'": '%27',
1201
- '(': '%28',
1202
- ')': '%29',
1203
- '~': '%7E',
1204
- '%20': '+',
1205
- '%00': '\x00'
1206
- };
1207
- return encodeURIComponent(str).replace(/[!'()~]|%20|%00/g, function replacer(match) {
1208
- return charMap[match];
1209
- });
1210
- }
1211
-
1212
- /**
1213
- * It takes a params object and converts it to a FormData object
1214
- *
1215
- * @param {Object<string, any>} params - The parameters to be converted to a FormData object.
1216
- * @param {Object<string, any>} options - The options object passed to the Axios constructor.
1217
- *
1218
- * @returns {void}
1219
- */
1220
- function AxiosURLSearchParams(params, options) {
1221
- this._pairs = [];
1222
-
1223
- params && toFormData(params, this, options);
1224
- }
1225
-
1226
- const prototype = AxiosURLSearchParams.prototype;
1227
-
1228
- prototype.append = function append(name, value) {
1229
- this._pairs.push([name, value]);
1230
- };
1231
-
1232
- prototype.toString = function toString(encoder) {
1233
- const _encode = encoder ? function(value) {
1234
- return encoder.call(this, value, encode$1);
1235
- } : encode$1;
1236
-
1237
- return this._pairs.map(function each(pair) {
1238
- return _encode(pair[0]) + '=' + _encode(pair[1]);
1239
- }, '').join('&');
1240
- };
1241
-
1242
- /**
1243
- * It replaces all instances of the characters `:`, `$`, `,`, `+`, `[`, and `]` with their
1244
- * URI encoded counterparts
1245
- *
1246
- * @param {string} val The value to be encoded.
1247
- *
1248
- * @returns {string} The encoded value.
1249
- */
1250
- function encode(val) {
1251
- return encodeURIComponent(val).
1252
- replace(/%3A/gi, ':').
1253
- replace(/%24/g, '$').
1254
- replace(/%2C/gi, ',').
1255
- replace(/%20/g, '+').
1256
- replace(/%5B/gi, '[').
1257
- replace(/%5D/gi, ']');
1258
- }
1259
-
1260
- /**
1261
- * Build a URL by appending params to the end
1262
- *
1263
- * @param {string} url The base of the url (e.g., http://www.google.com)
1264
- * @param {object} [params] The params to be appended
1265
- * @param {?object} options
1266
- *
1267
- * @returns {string} The formatted url
1268
- */
1269
- function buildURL(url, params, options) {
1270
- /*eslint no-param-reassign:0*/
1271
- if (!params) {
1272
- return url;
1273
- }
1274
-
1275
- const hashmarkIndex = url.indexOf('#');
1276
-
1277
- if (hashmarkIndex !== -1) {
1278
- url = url.slice(0, hashmarkIndex);
1279
- }
1280
-
1281
- const _encode = options && options.encode || encode;
1282
-
1283
- const serializerParams = utils.isURLSearchParams(params) ?
1284
- params.toString() :
1285
- new AxiosURLSearchParams(params, options).toString(_encode);
1286
-
1287
- if (serializerParams) {
1288
- url += (url.indexOf('?') === -1 ? '?' : '&') + serializerParams;
1289
- }
1290
-
1291
- return url;
1292
- }
1293
-
1294
- class InterceptorManager {
1295
- constructor() {
1296
- this.handlers = [];
1297
- }
1298
-
1299
- /**
1300
- * Add a new interceptor to the stack
1301
- *
1302
- * @param {Function} fulfilled The function to handle `then` for a `Promise`
1303
- * @param {Function} rejected The function to handle `reject` for a `Promise`
1304
- *
1305
- * @return {Number} An ID used to remove interceptor later
1306
- */
1307
- use(fulfilled, rejected, options) {
1308
- this.handlers.push({
1309
- fulfilled,
1310
- rejected,
1311
- synchronous: options ? options.synchronous : false,
1312
- runWhen: options ? options.runWhen : null
1313
- });
1314
- return this.handlers.length - 1;
1315
- }
1316
-
1317
- /**
1318
- * Remove an interceptor from the stack
1319
- *
1320
- * @param {Number} id The ID that was returned by `use`
1321
- *
1322
- * @returns {Boolean} `true` if the interceptor was removed, `false` otherwise
1323
- */
1324
- eject(id) {
1325
- if (this.handlers[id]) {
1326
- this.handlers[id] = null;
1327
- }
1328
- }
1329
-
1330
- /**
1331
- * Clear all interceptors from the stack
1332
- *
1333
- * @returns {void}
1334
- */
1335
- clear() {
1336
- if (this.handlers) {
1337
- this.handlers = [];
1338
- }
1339
- }
1340
-
1341
- /**
1342
- * Iterate over all the registered interceptors
1343
- *
1344
- * This method is particularly useful for skipping over any
1345
- * interceptors that may have become `null` calling `eject`.
1346
- *
1347
- * @param {Function} fn The function to call for each interceptor
1348
- *
1349
- * @returns {void}
1350
- */
1351
- forEach(fn) {
1352
- utils.forEach(this.handlers, function forEachHandler(h) {
1353
- if (h !== null) {
1354
- fn(h);
1355
- }
1356
- });
1357
- }
1358
- }
1359
-
1360
- const transitionalDefaults = {
1361
- silentJSONParsing: true,
1362
- forcedJSONParsing: true,
1363
- clarifyTimeoutError: false
1364
- };
1365
-
1366
- const URLSearchParams$1 = typeof URLSearchParams !== 'undefined' ? URLSearchParams : AxiosURLSearchParams;
1367
-
1368
- const FormData$1 = FormData;
1369
-
1370
- /**
1371
- * Determine if we're running in a standard browser environment
1372
- *
1373
- * This allows axios to run in a web worker, and react-native.
1374
- * Both environments support XMLHttpRequest, but not fully standard globals.
1375
- *
1376
- * web workers:
1377
- * typeof window -> undefined
1378
- * typeof document -> undefined
1379
- *
1380
- * react-native:
1381
- * navigator.product -> 'ReactNative'
1382
- * nativescript
1383
- * navigator.product -> 'NativeScript' or 'NS'
1384
- *
1385
- * @returns {boolean}
1386
- */
1387
- const isStandardBrowserEnv = (() => {
1388
- let product;
1389
- if (typeof navigator !== 'undefined' && (
1390
- (product = navigator.product) === 'ReactNative' ||
1391
- product === 'NativeScript' ||
1392
- product === 'NS')
1393
- ) {
1394
- return false;
1395
- }
1396
-
1397
- return typeof window !== 'undefined' && typeof document !== 'undefined';
1398
- })();
1399
-
1400
- const platform = {
1401
- isBrowser: true,
1402
- classes: {
1403
- URLSearchParams: URLSearchParams$1,
1404
- FormData: FormData$1,
1405
- Blob
1406
- },
1407
- isStandardBrowserEnv,
1408
- protocols: ['http', 'https', 'file', 'blob', 'url', 'data']
1409
- };
1410
-
1411
- function toURLEncodedForm(data, options) {
1412
- return toFormData(data, new platform.classes.URLSearchParams(), Object.assign({
1413
- visitor: function(value, key, path, helpers) {
1414
-
1415
- return helpers.defaultVisitor.apply(this, arguments);
1416
- }
1417
- }, options));
1418
- }
1419
-
1420
- /**
1421
- * It takes a string like `foo[x][y][z]` and returns an array like `['foo', 'x', 'y', 'z']
1422
- *
1423
- * @param {string} name - The name of the property to get.
1424
- *
1425
- * @returns An array of strings.
1426
- */
1427
- function parsePropPath(name) {
1428
- // foo[x][y][z]
1429
- // foo.x.y.z
1430
- // foo-x-y-z
1431
- // foo x y z
1432
- return utils.matchAll(/\w+|\[(\w*)]/g, name).map(match => {
1433
- return match[0] === '[]' ? '' : match[1] || match[0];
1434
- });
1435
- }
1436
-
1437
- /**
1438
- * Convert an array to an object.
1439
- *
1440
- * @param {Array<any>} arr - The array to convert to an object.
1441
- *
1442
- * @returns An object with the same keys and values as the array.
1443
- */
1444
- function arrayToObject(arr) {
1445
- const obj = {};
1446
- const keys = Object.keys(arr);
1447
- let i;
1448
- const len = keys.length;
1449
- let key;
1450
- for (i = 0; i < len; i++) {
1451
- key = keys[i];
1452
- obj[key] = arr[key];
1453
- }
1454
- return obj;
1455
- }
1456
-
1457
- /**
1458
- * It takes a FormData object and returns a JavaScript object
1459
- *
1460
- * @param {string} formData The FormData object to convert to JSON.
1461
- *
1462
- * @returns {Object<string, any> | null} The converted object.
1463
- */
1464
- function formDataToJSON(formData) {
1465
- function buildPath(path, value, target, index) {
1466
- let name = path[index++];
1467
- const isNumericKey = Number.isFinite(+name);
1468
- const isLast = index >= path.length;
1469
- name = !name && utils.isArray(target) ? target.length : name;
1470
-
1471
- if (isLast) {
1472
- if (utils.hasOwnProp(target, name)) {
1473
- target[name] = [target[name], value];
1474
- } else {
1475
- target[name] = value;
1476
- }
1477
-
1478
- return !isNumericKey;
1479
- }
1480
-
1481
- if (!target[name] || !utils.isObject(target[name])) {
1482
- target[name] = [];
1483
- }
1484
-
1485
- const result = buildPath(path, value, target[name], index);
1486
-
1487
- if (result && utils.isArray(target[name])) {
1488
- target[name] = arrayToObject(target[name]);
1489
- }
1490
-
1491
- return !isNumericKey;
1492
- }
1493
-
1494
- if (utils.isFormData(formData) && utils.isFunction(formData.entries)) {
1495
- const obj = {};
1496
-
1497
- utils.forEachEntry(formData, (name, value) => {
1498
- buildPath(parsePropPath(name), value, obj, 0);
1499
- });
1500
-
1501
- return obj;
1502
- }
1503
-
1504
- return null;
1505
- }
1506
-
1507
- /**
1508
- * Resolve or reject a Promise based on response status.
1509
- *
1510
- * @param {Function} resolve A function that resolves the promise.
1511
- * @param {Function} reject A function that rejects the promise.
1512
- * @param {object} response The response.
1513
- *
1514
- * @returns {object} The response.
1515
- */
1516
- function settle(resolve, reject, response) {
1517
- const validateStatus = response.config.validateStatus;
1518
- if (!response.status || !validateStatus || validateStatus(response.status)) {
1519
- resolve(response);
1520
- } else {
1521
- reject(new AxiosError(
1522
- 'Request failed with status code ' + response.status,
1523
- [AxiosError.ERR_BAD_REQUEST, AxiosError.ERR_BAD_RESPONSE][Math.floor(response.status / 100) - 4],
1524
- response.config,
1525
- response.request,
1526
- response
1527
- ));
1528
- }
1529
- }
1530
-
1531
- const cookies = platform.isStandardBrowserEnv ?
1532
-
1533
- // Standard browser envs support document.cookie
1534
- (function standardBrowserEnv() {
1535
- return {
1536
- write: function write(name, value, expires, path, domain, secure) {
1537
- const cookie = [];
1538
- cookie.push(name + '=' + encodeURIComponent(value));
1539
-
1540
- if (utils.isNumber(expires)) {
1541
- cookie.push('expires=' + new Date(expires).toGMTString());
1542
- }
1543
-
1544
- if (utils.isString(path)) {
1545
- cookie.push('path=' + path);
1546
- }
1547
-
1548
- if (utils.isString(domain)) {
1549
- cookie.push('domain=' + domain);
1550
- }
1551
-
1552
- if (secure === true) {
1553
- cookie.push('secure');
1554
- }
1555
-
1556
- document.cookie = cookie.join('; ');
1557
- },
1558
-
1559
- read: function read(name) {
1560
- const match = document.cookie.match(new RegExp('(^|;\\s*)(' + name + ')=([^;]*)'));
1561
- return (match ? decodeURIComponent(match[3]) : null);
1562
- },
1563
-
1564
- remove: function remove(name) {
1565
- this.write(name, '', Date.now() - 86400000);
1566
- }
1567
- };
1568
- })() :
1569
-
1570
- // Non standard browser env (web workers, react-native) lack needed support.
1571
- (function nonStandardBrowserEnv() {
1572
- return {
1573
- write: function write() {},
1574
- read: function read() { return null; },
1575
- remove: function remove() {}
1576
- };
1577
- })();
1578
-
1579
- /**
1580
- * Determines whether the specified URL is absolute
1581
- *
1582
- * @param {string} url The URL to test
1583
- *
1584
- * @returns {boolean} True if the specified URL is absolute, otherwise false
1585
- */
1586
- function isAbsoluteURL(url) {
1587
- // A URL is considered absolute if it begins with "<scheme>://" or "//" (protocol-relative URL).
1588
- // RFC 3986 defines scheme name as a sequence of characters beginning with a letter and followed
1589
- // by any combination of letters, digits, plus, period, or hyphen.
1590
- return /^([a-z][a-z\d+\-.]*:)?\/\//i.test(url);
1591
- }
1592
-
1593
- /**
1594
- * Creates a new URL by combining the specified URLs
1595
- *
1596
- * @param {string} baseURL The base URL
1597
- * @param {string} relativeURL The relative URL
1598
- *
1599
- * @returns {string} The combined URL
1600
- */
1601
- function combineURLs(baseURL, relativeURL) {
1602
- return relativeURL
1603
- ? baseURL.replace(/\/+$/, '') + '/' + relativeURL.replace(/^\/+/, '')
1604
- : baseURL;
1605
- }
1606
-
1607
- /**
1608
- * Creates a new URL by combining the baseURL with the requestedURL,
1609
- * only when the requestedURL is not already an absolute URL.
1610
- * If the requestURL is absolute, this function returns the requestedURL untouched.
1611
- *
1612
- * @param {string} baseURL The base URL
1613
- * @param {string} requestedURL Absolute or relative URL to combine
1614
- *
1615
- * @returns {string} The combined full path
1616
- */
1617
- function buildFullPath(baseURL, requestedURL) {
1618
- if (baseURL && !isAbsoluteURL(requestedURL)) {
1619
- return combineURLs(baseURL, requestedURL);
1620
- }
1621
- return requestedURL;
1622
- }
1623
-
1624
- const isURLSameOrigin = platform.isStandardBrowserEnv ?
1625
-
1626
- // Standard browser envs have full support of the APIs needed to test
1627
- // whether the request URL is of the same origin as current location.
1628
- (function standardBrowserEnv() {
1629
- const msie = /(msie|trident)/i.test(navigator.userAgent);
1630
- const urlParsingNode = document.createElement('a');
1631
- let originURL;
1632
-
1633
- /**
1634
- * Parse a URL to discover it's components
1635
- *
1636
- * @param {String} url The URL to be parsed
1637
- * @returns {Object}
1638
- */
1639
- function resolveURL(url) {
1640
- let href = url;
1641
-
1642
- if (msie) {
1643
- // IE needs attribute set twice to normalize properties
1644
- urlParsingNode.setAttribute('href', href);
1645
- href = urlParsingNode.href;
1646
- }
1647
-
1648
- urlParsingNode.setAttribute('href', href);
1649
-
1650
- // urlParsingNode provides the UrlUtils interface - http://url.spec.whatwg.org/#urlutils
1651
- return {
1652
- href: urlParsingNode.href,
1653
- protocol: urlParsingNode.protocol ? urlParsingNode.protocol.replace(/:$/, '') : '',
1654
- host: urlParsingNode.host,
1655
- search: urlParsingNode.search ? urlParsingNode.search.replace(/^\?/, '') : '',
1656
- hash: urlParsingNode.hash ? urlParsingNode.hash.replace(/^#/, '') : '',
1657
- hostname: urlParsingNode.hostname,
1658
- port: urlParsingNode.port,
1659
- pathname: (urlParsingNode.pathname.charAt(0) === '/') ?
1660
- urlParsingNode.pathname :
1661
- '/' + urlParsingNode.pathname
1662
- };
1663
- }
1664
-
1665
- originURL = resolveURL(window.location.href);
1666
-
1667
- /**
1668
- * Determine if a URL shares the same origin as the current location
1669
- *
1670
- * @param {String} requestURL The URL to test
1671
- * @returns {boolean} True if URL shares the same origin, otherwise false
1672
- */
1673
- return function isURLSameOrigin(requestURL) {
1674
- const parsed = (utils.isString(requestURL)) ? resolveURL(requestURL) : requestURL;
1675
- return (parsed.protocol === originURL.protocol &&
1676
- parsed.host === originURL.host);
1677
- };
1678
- })() :
1679
-
1680
- // Non standard browser envs (web workers, react-native) lack needed support.
1681
- (function nonStandardBrowserEnv() {
1682
- return function isURLSameOrigin() {
1683
- return true;
1684
- };
1685
- })();
1686
-
1687
- /**
1688
- * A `CanceledError` is an object that is thrown when an operation is canceled.
1689
- *
1690
- * @param {string=} message The message.
1691
- * @param {Object=} config The config.
1692
- * @param {Object=} request The request.
1693
- *
1694
- * @returns {CanceledError} The created error.
1695
- */
1696
- function CanceledError(message, config, request) {
1697
- // eslint-disable-next-line no-eq-null,eqeqeq
1698
- AxiosError.call(this, message == null ? 'canceled' : message, AxiosError.ERR_CANCELED, config, request);
1699
- this.name = 'CanceledError';
1700
- }
1701
-
1702
- utils.inherits(CanceledError, AxiosError, {
1703
- __CANCEL__: true
1704
- });
1705
-
1706
- function parseProtocol(url) {
1707
- const match = /^([-+\w]{1,25})(:?\/\/|:)/.exec(url);
1708
- return match && match[1] || '';
1709
- }
1710
-
1711
- // RawAxiosHeaders whose duplicates are ignored by node
1712
- // c.f. https://nodejs.org/api/http.html#http_message_headers
1713
- const ignoreDuplicateOf = utils.toObjectSet([
1714
- 'age', 'authorization', 'content-length', 'content-type', 'etag',
1715
- 'expires', 'from', 'host', 'if-modified-since', 'if-unmodified-since',
1716
- 'last-modified', 'location', 'max-forwards', 'proxy-authorization',
1717
- 'referer', 'retry-after', 'user-agent'
1718
- ]);
1719
-
1720
- /**
1721
- * Parse headers into an object
1722
- *
1723
- * ```
1724
- * Date: Wed, 27 Aug 2014 08:58:49 GMT
1725
- * Content-Type: application/json
1726
- * Connection: keep-alive
1727
- * Transfer-Encoding: chunked
1728
- * ```
1729
- *
1730
- * @param {String} rawHeaders Headers needing to be parsed
1731
- *
1732
- * @returns {Object} Headers parsed into an object
1733
- */
1734
- const parseHeaders = rawHeaders => {
1735
- const parsed = {};
1736
- let key;
1737
- let val;
1738
- let i;
1739
-
1740
- rawHeaders && rawHeaders.split('\n').forEach(function parser(line) {
1741
- i = line.indexOf(':');
1742
- key = line.substring(0, i).trim().toLowerCase();
1743
- val = line.substring(i + 1).trim();
1744
-
1745
- if (!key || (parsed[key] && ignoreDuplicateOf[key])) {
1746
- return;
1747
- }
1748
-
1749
- if (key === 'set-cookie') {
1750
- if (parsed[key]) {
1751
- parsed[key].push(val);
1752
- } else {
1753
- parsed[key] = [val];
1754
- }
1755
- } else {
1756
- parsed[key] = parsed[key] ? parsed[key] + ', ' + val : val;
1757
- }
1758
- });
1759
-
1760
- return parsed;
1761
- };
1762
-
1763
- const $internals = Symbol('internals');
1764
- const $defaults = Symbol('defaults');
1765
-
1766
- function normalizeHeader(header) {
1767
- return header && String(header).trim().toLowerCase();
1768
- }
1769
-
1770
- function normalizeValue(value) {
1771
- if (value === false || value == null) {
1772
- return value;
1773
- }
1774
-
1775
- return String(value);
1776
- }
1777
-
1778
- function parseTokens(str) {
1779
- const tokens = Object.create(null);
1780
- const tokensRE = /([^\s,;=]+)\s*(?:=\s*([^,;]+))?/g;
1781
- let match;
1782
-
1783
- while ((match = tokensRE.exec(str))) {
1784
- tokens[match[1]] = match[2];
1785
- }
1786
-
1787
- return tokens;
1788
- }
1789
-
1790
- function matchHeaderValue(context, value, header, filter) {
1791
- if (utils.isFunction(filter)) {
1792
- return filter.call(this, value, header);
1793
- }
1794
-
1795
- if (!utils.isString(value)) return;
1796
-
1797
- if (utils.isString(filter)) {
1798
- return value.indexOf(filter) !== -1;
1799
- }
1800
-
1801
- if (utils.isRegExp(filter)) {
1802
- return filter.test(value);
1803
- }
1804
- }
1805
-
1806
- function formatHeader(header) {
1807
- return header.trim()
1808
- .toLowerCase().replace(/([a-z\d])(\w*)/g, (w, char, str) => {
1809
- return char.toUpperCase() + str;
1810
- });
1811
- }
1812
-
1813
- function buildAccessors(obj, header) {
1814
- const accessorName = utils.toCamelCase(' ' + header);
1815
-
1816
- ['get', 'set', 'has'].forEach(methodName => {
1817
- Object.defineProperty(obj, methodName + accessorName, {
1818
- value: function(arg1, arg2, arg3) {
1819
- return this[methodName].call(this, header, arg1, arg2, arg3);
1820
- },
1821
- configurable: true
1822
- });
1823
- });
1824
- }
1825
-
1826
- function findKey(obj, key) {
1827
- key = key.toLowerCase();
1828
- const keys = Object.keys(obj);
1829
- let i = keys.length;
1830
- let _key;
1831
- while (i-- > 0) {
1832
- _key = keys[i];
1833
- if (key === _key.toLowerCase()) {
1834
- return _key;
1835
- }
1836
- }
1837
- return null;
1838
- }
1839
-
1840
- function AxiosHeaders(headers, defaults) {
1841
- headers && this.set(headers);
1842
- this[$defaults] = defaults || null;
1843
- }
1844
-
1845
- Object.assign(AxiosHeaders.prototype, {
1846
- set: function(header, valueOrRewrite, rewrite) {
1847
- const self = this;
1848
-
1849
- function setHeader(_value, _header, _rewrite) {
1850
- const lHeader = normalizeHeader(_header);
1851
-
1852
- if (!lHeader) {
1853
- throw new Error('header name must be a non-empty string');
1854
- }
1855
-
1856
- const key = findKey(self, lHeader);
1857
-
1858
- if (key && _rewrite !== true && (self[key] === false || _rewrite === false)) {
1859
- return;
1860
- }
1861
-
1862
- if (utils.isArray(_value)) {
1863
- _value = _value.map(normalizeValue);
1864
- } else {
1865
- _value = normalizeValue(_value);
1866
- }
1867
-
1868
- self[key || _header] = _value;
1869
- }
1870
-
1871
- if (utils.isPlainObject(header)) {
1872
- utils.forEach(header, (_value, _header) => {
1873
- setHeader(_value, _header, valueOrRewrite);
1874
- });
1875
- } else {
1876
- setHeader(valueOrRewrite, header, rewrite);
1877
- }
1878
-
1879
- return this;
1880
- },
1881
-
1882
- get: function(header, parser) {
1883
- header = normalizeHeader(header);
1884
-
1885
- if (!header) return undefined;
1886
-
1887
- const key = findKey(this, header);
1888
-
1889
- if (key) {
1890
- const value = this[key];
1891
-
1892
- if (!parser) {
1893
- return value;
1894
- }
1895
-
1896
- if (parser === true) {
1897
- return parseTokens(value);
1898
- }
1899
-
1900
- if (utils.isFunction(parser)) {
1901
- return parser.call(this, value, key);
1902
- }
1903
-
1904
- if (utils.isRegExp(parser)) {
1905
- return parser.exec(value);
1906
- }
1907
-
1908
- throw new TypeError('parser must be boolean|regexp|function');
1909
- }
1910
- },
1911
-
1912
- has: function(header, matcher) {
1913
- header = normalizeHeader(header);
1914
-
1915
- if (header) {
1916
- const key = findKey(this, header);
1917
-
1918
- return !!(key && (!matcher || matchHeaderValue(this, this[key], key, matcher)));
1919
- }
1920
-
1921
- return false;
1922
- },
1923
-
1924
- delete: function(header, matcher) {
1925
- const self = this;
1926
- let deleted = false;
1927
-
1928
- function deleteHeader(_header) {
1929
- _header = normalizeHeader(_header);
1930
-
1931
- if (_header) {
1932
- const key = findKey(self, _header);
1933
-
1934
- if (key && (!matcher || matchHeaderValue(self, self[key], key, matcher))) {
1935
- delete self[key];
1936
-
1937
- deleted = true;
1938
- }
1939
- }
1940
- }
1941
-
1942
- if (utils.isArray(header)) {
1943
- header.forEach(deleteHeader);
1944
- } else {
1945
- deleteHeader(header);
1946
- }
1947
-
1948
- return deleted;
1949
- },
1950
-
1951
- clear: function() {
1952
- return Object.keys(this).forEach(this.delete.bind(this));
1953
- },
1954
-
1955
- normalize: function(format) {
1956
- const self = this;
1957
- const headers = {};
1958
-
1959
- utils.forEach(this, (value, header) => {
1960
- const key = findKey(headers, header);
1961
-
1962
- if (key) {
1963
- self[key] = normalizeValue(value);
1964
- delete self[header];
1965
- return;
1966
- }
1967
-
1968
- const normalized = format ? formatHeader(header) : String(header).trim();
1969
-
1970
- if (normalized !== header) {
1971
- delete self[header];
1972
- }
1973
-
1974
- self[normalized] = normalizeValue(value);
1975
-
1976
- headers[normalized] = true;
1977
- });
1978
-
1979
- return this;
1980
- },
1981
-
1982
- toJSON: function() {
1983
- const obj = Object.create(null);
1984
-
1985
- utils.forEach(Object.assign({}, this[$defaults] || null, this),
1986
- (value, header) => {
1987
- if (value == null || value === false) return;
1988
- obj[header] = utils.isArray(value) ? value.join(', ') : value;
1989
- });
1990
-
1991
- return obj;
1992
- }
1993
- });
1994
-
1995
- Object.assign(AxiosHeaders, {
1996
- from: function(thing) {
1997
- if (utils.isString(thing)) {
1998
- return new this(parseHeaders(thing));
1999
- }
2000
- return thing instanceof this ? thing : new this(thing);
2001
- },
2002
-
2003
- accessor: function(header) {
2004
- const internals = this[$internals] = (this[$internals] = {
2005
- accessors: {}
2006
- });
2007
-
2008
- const accessors = internals.accessors;
2009
- const prototype = this.prototype;
2010
-
2011
- function defineAccessor(_header) {
2012
- const lHeader = normalizeHeader(_header);
2013
-
2014
- if (!accessors[lHeader]) {
2015
- buildAccessors(prototype, _header);
2016
- accessors[lHeader] = true;
2017
- }
2018
- }
2019
-
2020
- utils.isArray(header) ? header.forEach(defineAccessor) : defineAccessor(header);
2021
-
2022
- return this;
2023
- }
2024
- });
2025
-
2026
- AxiosHeaders.accessor(['Content-Type', 'Content-Length', 'Accept', 'Accept-Encoding', 'User-Agent']);
2027
-
2028
- utils.freezeMethods(AxiosHeaders.prototype);
2029
- utils.freezeMethods(AxiosHeaders);
2030
-
2031
- /**
2032
- * Calculate data maxRate
2033
- * @param {Number} [samplesCount= 10]
2034
- * @param {Number} [min= 1000]
2035
- * @returns {Function}
2036
- */
2037
- function speedometer(samplesCount, min) {
2038
- samplesCount = samplesCount || 10;
2039
- const bytes = new Array(samplesCount);
2040
- const timestamps = new Array(samplesCount);
2041
- let head = 0;
2042
- let tail = 0;
2043
- let firstSampleTS;
2044
-
2045
- min = min !== undefined ? min : 1000;
2046
-
2047
- return function push(chunkLength) {
2048
- const now = Date.now();
2049
-
2050
- const startedAt = timestamps[tail];
2051
-
2052
- if (!firstSampleTS) {
2053
- firstSampleTS = now;
2054
- }
2055
-
2056
- bytes[head] = chunkLength;
2057
- timestamps[head] = now;
2058
-
2059
- let i = tail;
2060
- let bytesCount = 0;
2061
-
2062
- while (i !== head) {
2063
- bytesCount += bytes[i++];
2064
- i = i % samplesCount;
2065
- }
2066
-
2067
- head = (head + 1) % samplesCount;
2068
-
2069
- if (head === tail) {
2070
- tail = (tail + 1) % samplesCount;
2071
- }
2072
-
2073
- if (now - firstSampleTS < min) {
2074
- return;
2075
- }
2076
-
2077
- const passed = startedAt && now - startedAt;
2078
-
2079
- return passed ? Math.round(bytesCount * 1000 / passed) : undefined;
2080
- };
2081
- }
2082
-
2083
- function progressEventReducer(listener, isDownloadStream) {
2084
- let bytesNotified = 0;
2085
- const _speedometer = speedometer(50, 250);
2086
-
2087
- return e => {
2088
- const loaded = e.loaded;
2089
- const total = e.lengthComputable ? e.total : undefined;
2090
- const progressBytes = loaded - bytesNotified;
2091
- const rate = _speedometer(progressBytes);
2092
- const inRange = loaded <= total;
2093
-
2094
- bytesNotified = loaded;
2095
-
2096
- const data = {
2097
- loaded,
2098
- total,
2099
- progress: total ? (loaded / total) : undefined,
2100
- bytes: progressBytes,
2101
- rate: rate ? rate : undefined,
2102
- estimated: rate && total && inRange ? (total - loaded) / rate : undefined
2103
- };
2104
-
2105
- data[isDownloadStream ? 'download' : 'upload'] = true;
2106
-
2107
- listener(data);
2108
- };
2109
- }
2110
-
2111
- function xhrAdapter(config) {
2112
- return new Promise(function dispatchXhrRequest(resolve, reject) {
2113
- let requestData = config.data;
2114
- const requestHeaders = AxiosHeaders.from(config.headers).normalize();
2115
- const responseType = config.responseType;
2116
- let onCanceled;
2117
- function done() {
2118
- if (config.cancelToken) {
2119
- config.cancelToken.unsubscribe(onCanceled);
2120
- }
2121
-
2122
- if (config.signal) {
2123
- config.signal.removeEventListener('abort', onCanceled);
2124
- }
2125
- }
2126
-
2127
- if (utils.isFormData(requestData) && platform.isStandardBrowserEnv) {
2128
- requestHeaders.setContentType(false); // Let the browser set it
2129
- }
2130
-
2131
- let request = new XMLHttpRequest();
2132
-
2133
- // HTTP basic authentication
2134
- if (config.auth) {
2135
- const username = config.auth.username || '';
2136
- const password = config.auth.password ? unescape(encodeURIComponent(config.auth.password)) : '';
2137
- requestHeaders.set('Authorization', 'Basic ' + btoa(username + ':' + password));
2138
- }
2139
-
2140
- const fullPath = buildFullPath(config.baseURL, config.url);
2141
-
2142
- request.open(config.method.toUpperCase(), buildURL(fullPath, config.params, config.paramsSerializer), true);
2143
-
2144
- // Set the request timeout in MS
2145
- request.timeout = config.timeout;
2146
-
2147
- function onloadend() {
2148
- if (!request) {
2149
- return;
2150
- }
2151
- // Prepare the response
2152
- const responseHeaders = AxiosHeaders.from(
2153
- 'getAllResponseHeaders' in request && request.getAllResponseHeaders()
2154
- );
2155
- const responseData = !responseType || responseType === 'text' || responseType === 'json' ?
2156
- request.responseText : request.response;
2157
- const response = {
2158
- data: responseData,
2159
- status: request.status,
2160
- statusText: request.statusText,
2161
- headers: responseHeaders,
2162
- config,
2163
- request
2164
- };
2165
-
2166
- settle(function _resolve(value) {
2167
- resolve(value);
2168
- done();
2169
- }, function _reject(err) {
2170
- reject(err);
2171
- done();
2172
- }, response);
2173
-
2174
- // Clean up request
2175
- request = null;
2176
- }
2177
-
2178
- if ('onloadend' in request) {
2179
- // Use onloadend if available
2180
- request.onloadend = onloadend;
2181
- } else {
2182
- // Listen for ready state to emulate onloadend
2183
- request.onreadystatechange = function handleLoad() {
2184
- if (!request || request.readyState !== 4) {
2185
- return;
2186
- }
2187
-
2188
- // The request errored out and we didn't get a response, this will be
2189
- // handled by onerror instead
2190
- // With one exception: request that using file: protocol, most browsers
2191
- // will return status as 0 even though it's a successful request
2192
- if (request.status === 0 && !(request.responseURL && request.responseURL.indexOf('file:') === 0)) {
2193
- return;
2194
- }
2195
- // readystate handler is calling before onerror or ontimeout handlers,
2196
- // so we should call onloadend on the next 'tick'
2197
- setTimeout(onloadend);
2198
- };
2199
- }
2200
-
2201
- // Handle browser request cancellation (as opposed to a manual cancellation)
2202
- request.onabort = function handleAbort() {
2203
- if (!request) {
2204
- return;
2205
- }
2206
-
2207
- reject(new AxiosError('Request aborted', AxiosError.ECONNABORTED, config, request));
2208
-
2209
- // Clean up request
2210
- request = null;
2211
- };
2212
-
2213
- // Handle low level network errors
2214
- request.onerror = function handleError() {
2215
- // Real errors are hidden from us by the browser
2216
- // onerror should only fire if it's a network error
2217
- reject(new AxiosError('Network Error', AxiosError.ERR_NETWORK, config, request));
2218
-
2219
- // Clean up request
2220
- request = null;
2221
- };
2222
-
2223
- // Handle timeout
2224
- request.ontimeout = function handleTimeout() {
2225
- let timeoutErrorMessage = config.timeout ? 'timeout of ' + config.timeout + 'ms exceeded' : 'timeout exceeded';
2226
- const transitional = config.transitional || transitionalDefaults;
2227
- if (config.timeoutErrorMessage) {
2228
- timeoutErrorMessage = config.timeoutErrorMessage;
2229
- }
2230
- reject(new AxiosError(
2231
- timeoutErrorMessage,
2232
- transitional.clarifyTimeoutError ? AxiosError.ETIMEDOUT : AxiosError.ECONNABORTED,
2233
- config,
2234
- request));
2235
-
2236
- // Clean up request
2237
- request = null;
2238
- };
2239
-
2240
- // Add xsrf header
2241
- // This is only done if running in a standard browser environment.
2242
- // Specifically not if we're in a web worker, or react-native.
2243
- if (platform.isStandardBrowserEnv) {
2244
- // Add xsrf header
2245
- const xsrfValue = (config.withCredentials || isURLSameOrigin(fullPath))
2246
- && config.xsrfCookieName && cookies.read(config.xsrfCookieName);
2247
-
2248
- if (xsrfValue) {
2249
- requestHeaders.set(config.xsrfHeaderName, xsrfValue);
2250
- }
2251
- }
2252
-
2253
- // Remove Content-Type if data is undefined
2254
- requestData === undefined && requestHeaders.setContentType(null);
2255
-
2256
- // Add headers to the request
2257
- if ('setRequestHeader' in request) {
2258
- utils.forEach(requestHeaders.toJSON(), function setRequestHeader(val, key) {
2259
- request.setRequestHeader(key, val);
2260
- });
2261
- }
2262
-
2263
- // Add withCredentials to request if needed
2264
- if (!utils.isUndefined(config.withCredentials)) {
2265
- request.withCredentials = !!config.withCredentials;
2266
- }
2267
-
2268
- // Add responseType to request if needed
2269
- if (responseType && responseType !== 'json') {
2270
- request.responseType = config.responseType;
2271
- }
2272
-
2273
- // Handle progress if needed
2274
- if (typeof config.onDownloadProgress === 'function') {
2275
- request.addEventListener('progress', progressEventReducer(config.onDownloadProgress, true));
2276
- }
2277
-
2278
- // Not all browsers support upload events
2279
- if (typeof config.onUploadProgress === 'function' && request.upload) {
2280
- request.upload.addEventListener('progress', progressEventReducer(config.onUploadProgress));
2281
- }
2282
-
2283
- if (config.cancelToken || config.signal) {
2284
- // Handle cancellation
2285
- // eslint-disable-next-line func-names
2286
- onCanceled = cancel => {
2287
- if (!request) {
2288
- return;
2289
- }
2290
- reject(!cancel || cancel.type ? new CanceledError(null, config, request) : cancel);
2291
- request.abort();
2292
- request = null;
2293
- };
2294
-
2295
- config.cancelToken && config.cancelToken.subscribe(onCanceled);
2296
- if (config.signal) {
2297
- config.signal.aborted ? onCanceled() : config.signal.addEventListener('abort', onCanceled);
2298
- }
2299
- }
2300
-
2301
- const protocol = parseProtocol(fullPath);
2302
-
2303
- if (protocol && platform.protocols.indexOf(protocol) === -1) {
2304
- reject(new AxiosError('Unsupported protocol ' + protocol + ':', AxiosError.ERR_BAD_REQUEST, config));
2305
- return;
2306
- }
2307
-
2308
-
2309
- // Send the request
2310
- request.send(requestData || null);
2311
- });
2312
- }
2313
-
2314
- const adapters = {
2315
- http: xhrAdapter,
2316
- xhr: xhrAdapter
2317
- };
2318
-
2319
- const adapters$1 = {
2320
- getAdapter: (nameOrAdapter) => {
2321
- if(utils.isString(nameOrAdapter)){
2322
- const adapter = adapters[nameOrAdapter];
2323
-
2324
- if (!nameOrAdapter) {
2325
- throw Error(
2326
- utils.hasOwnProp(nameOrAdapter) ?
2327
- `Adapter '${nameOrAdapter}' is not available in the build` :
2328
- `Can not resolve adapter '${nameOrAdapter}'`
2329
- );
2330
- }
2331
-
2332
- return adapter
2333
- }
2334
-
2335
- if (!utils.isFunction(nameOrAdapter)) {
2336
- throw new TypeError('adapter is not a function');
2337
- }
2338
-
2339
- return nameOrAdapter;
2340
- },
2341
- adapters
2342
- };
2343
-
2344
- const DEFAULT_CONTENT_TYPE = {
2345
- 'Content-Type': 'application/x-www-form-urlencoded'
2346
- };
2347
-
2348
- /**
2349
- * If the browser has an XMLHttpRequest object, use the XHR adapter, otherwise use the HTTP
2350
- * adapter
2351
- *
2352
- * @returns {Function}
2353
- */
2354
- function getDefaultAdapter() {
2355
- let adapter;
2356
- if (typeof XMLHttpRequest !== 'undefined') {
2357
- // For browsers use XHR adapter
2358
- adapter = adapters$1.getAdapter('xhr');
2359
- } else if (typeof process !== 'undefined' && utils.kindOf(process) === 'process') {
2360
- // For node use HTTP adapter
2361
- adapter = adapters$1.getAdapter('http');
2362
- }
2363
- return adapter;
2364
- }
2365
-
2366
- /**
2367
- * It takes a string, tries to parse it, and if it fails, it returns the stringified version
2368
- * of the input
2369
- *
2370
- * @param {any} rawValue - The value to be stringified.
2371
- * @param {Function} parser - A function that parses a string into a JavaScript object.
2372
- * @param {Function} encoder - A function that takes a value and returns a string.
2373
- *
2374
- * @returns {string} A stringified version of the rawValue.
2375
- */
2376
- function stringifySafely(rawValue, parser, encoder) {
2377
- if (utils.isString(rawValue)) {
2378
- try {
2379
- (parser || JSON.parse)(rawValue);
2380
- return utils.trim(rawValue);
2381
- } catch (e) {
2382
- if (e.name !== 'SyntaxError') {
2383
- throw e;
2384
- }
2385
- }
2386
- }
2387
-
2388
- return (encoder || JSON.stringify)(rawValue);
2389
- }
2390
-
2391
- const defaults = {
2392
-
2393
- transitional: transitionalDefaults,
2394
-
2395
- adapter: getDefaultAdapter(),
2396
-
2397
- transformRequest: [function transformRequest(data, headers) {
2398
- const contentType = headers.getContentType() || '';
2399
- const hasJSONContentType = contentType.indexOf('application/json') > -1;
2400
- const isObjectPayload = utils.isObject(data);
2401
-
2402
- if (isObjectPayload && utils.isHTMLForm(data)) {
2403
- data = new FormData(data);
2404
- }
2405
-
2406
- const isFormData = utils.isFormData(data);
2407
-
2408
- if (isFormData) {
2409
- if (!hasJSONContentType) {
2410
- return data;
2411
- }
2412
- return hasJSONContentType ? JSON.stringify(formDataToJSON(data)) : data;
2413
- }
2414
-
2415
- if (utils.isArrayBuffer(data) ||
2416
- utils.isBuffer(data) ||
2417
- utils.isStream(data) ||
2418
- utils.isFile(data) ||
2419
- utils.isBlob(data)
2420
- ) {
2421
- return data;
2422
- }
2423
- if (utils.isArrayBufferView(data)) {
2424
- return data.buffer;
2425
- }
2426
- if (utils.isURLSearchParams(data)) {
2427
- headers.setContentType('application/x-www-form-urlencoded;charset=utf-8', false);
2428
- return data.toString();
2429
- }
2430
-
2431
- let isFileList;
2432
-
2433
- if (isObjectPayload) {
2434
- if (contentType.indexOf('application/x-www-form-urlencoded') > -1) {
2435
- return toURLEncodedForm(data, this.formSerializer).toString();
2436
- }
2437
-
2438
- if ((isFileList = utils.isFileList(data)) || contentType.indexOf('multipart/form-data') > -1) {
2439
- const _FormData = this.env && this.env.FormData;
2440
-
2441
- return toFormData(
2442
- isFileList ? {'files[]': data} : data,
2443
- _FormData && new _FormData(),
2444
- this.formSerializer
2445
- );
2446
- }
2447
- }
2448
-
2449
- if (isObjectPayload || hasJSONContentType ) {
2450
- headers.setContentType('application/json', false);
2451
- return stringifySafely(data);
2452
- }
2453
-
2454
- return data;
2455
- }],
2456
-
2457
- transformResponse: [function transformResponse(data) {
2458
- const transitional = this.transitional || defaults.transitional;
2459
- const forcedJSONParsing = transitional && transitional.forcedJSONParsing;
2460
- const JSONRequested = this.responseType === 'json';
2461
-
2462
- if (data && utils.isString(data) && ((forcedJSONParsing && !this.responseType) || JSONRequested)) {
2463
- const silentJSONParsing = transitional && transitional.silentJSONParsing;
2464
- const strictJSONParsing = !silentJSONParsing && JSONRequested;
2465
-
2466
- try {
2467
- return JSON.parse(data);
2468
- } catch (e) {
2469
- if (strictJSONParsing) {
2470
- if (e.name === 'SyntaxError') {
2471
- throw AxiosError.from(e, AxiosError.ERR_BAD_RESPONSE, this, null, this.response);
2472
- }
2473
- throw e;
2474
- }
2475
- }
2476
- }
2477
-
2478
- return data;
2479
- }],
2480
-
2481
- /**
2482
- * A timeout in milliseconds to abort a request. If set to 0 (default) a
2483
- * timeout is not created.
2484
- */
2485
- timeout: 0,
2486
-
2487
- xsrfCookieName: 'XSRF-TOKEN',
2488
- xsrfHeaderName: 'X-XSRF-TOKEN',
2489
-
2490
- maxContentLength: -1,
2491
- maxBodyLength: -1,
2492
-
2493
- env: {
2494
- FormData: platform.classes.FormData,
2495
- Blob: platform.classes.Blob
2496
- },
2497
-
2498
- validateStatus: function validateStatus(status) {
2499
- return status >= 200 && status < 300;
2500
- },
2501
-
2502
- headers: {
2503
- common: {
2504
- 'Accept': 'application/json, text/plain, */*'
2505
- }
2506
- }
2507
- };
2508
-
2509
- utils.forEach(['delete', 'get', 'head'], function forEachMethodNoData(method) {
2510
- defaults.headers[method] = {};
2511
- });
2512
-
2513
- utils.forEach(['post', 'put', 'patch'], function forEachMethodWithData(method) {
2514
- defaults.headers[method] = utils.merge(DEFAULT_CONTENT_TYPE);
2515
- });
2516
-
2517
- /**
2518
- * Transform the data for a request or a response
2519
- *
2520
- * @param {Array|Function} fns A single function or Array of functions
2521
- * @param {?Object} response The response object
2522
- *
2523
- * @returns {*} The resulting transformed data
2524
- */
2525
- function transformData(fns, response) {
2526
- const config = this || defaults;
2527
- const context = response || config;
2528
- const headers = AxiosHeaders.from(context.headers);
2529
- let data = context.data;
2530
-
2531
- utils.forEach(fns, function transform(fn) {
2532
- data = fn.call(config, data, headers.normalize(), response ? response.status : undefined);
2533
- });
2534
-
2535
- headers.normalize();
2536
-
2537
- return data;
2538
- }
2539
-
2540
- function isCancel(value) {
2541
- return !!(value && value.__CANCEL__);
2542
- }
2543
-
2544
- /**
2545
- * Throws a `CanceledError` if cancellation has been requested.
2546
- *
2547
- * @param {Object} config The config that is to be used for the request
2548
- *
2549
- * @returns {void}
2550
- */
2551
- function throwIfCancellationRequested(config) {
2552
- if (config.cancelToken) {
2553
- config.cancelToken.throwIfRequested();
2554
- }
2555
-
2556
- if (config.signal && config.signal.aborted) {
2557
- throw new CanceledError();
2558
- }
2559
- }
2560
-
2561
- /**
2562
- * Dispatch a request to the server using the configured adapter.
2563
- *
2564
- * @param {object} config The config that is to be used for the request
2565
- *
2566
- * @returns {Promise} The Promise to be fulfilled
2567
- */
2568
- function dispatchRequest(config) {
2569
- throwIfCancellationRequested(config);
2570
-
2571
- config.headers = AxiosHeaders.from(config.headers);
2572
-
2573
- // Transform request data
2574
- config.data = transformData.call(
2575
- config,
2576
- config.transformRequest
2577
- );
2578
-
2579
- const adapter = config.adapter || defaults.adapter;
2580
-
2581
- return adapter(config).then(function onAdapterResolution(response) {
2582
- throwIfCancellationRequested(config);
2583
-
2584
- // Transform response data
2585
- response.data = transformData.call(
2586
- config,
2587
- config.transformResponse,
2588
- response
2589
- );
2590
-
2591
- response.headers = AxiosHeaders.from(response.headers);
2592
-
2593
- return response;
2594
- }, function onAdapterRejection(reason) {
2595
- if (!isCancel(reason)) {
2596
- throwIfCancellationRequested(config);
2597
-
2598
- // Transform response data
2599
- if (reason && reason.response) {
2600
- reason.response.data = transformData.call(
2601
- config,
2602
- config.transformResponse,
2603
- reason.response
2604
- );
2605
- reason.response.headers = AxiosHeaders.from(reason.response.headers);
2606
- }
253
+ // eslint-lint-disable-next-line @typescript-eslint/naming-convention
254
+ class HTTPError extends Error {
255
+ constructor(response, request, options) {
256
+ const code = (response.status || response.status === 0) ? response.status : '';
257
+ const title = response.statusText || '';
258
+ const status = `${code} ${title}`.trim();
259
+ const reason = status ? `status code ${status}` : 'an unknown error';
260
+ super(`Request failed with ${reason}`);
261
+ Object.defineProperty(this, "response", {
262
+ enumerable: true,
263
+ configurable: true,
264
+ writable: true,
265
+ value: void 0
266
+ });
267
+ Object.defineProperty(this, "request", {
268
+ enumerable: true,
269
+ configurable: true,
270
+ writable: true,
271
+ value: void 0
272
+ });
273
+ Object.defineProperty(this, "options", {
274
+ enumerable: true,
275
+ configurable: true,
276
+ writable: true,
277
+ value: void 0
278
+ });
279
+ this.name = 'HTTPError';
280
+ this.response = response;
281
+ this.request = request;
282
+ this.options = options;
2607
283
  }
2608
-
2609
- return Promise.reject(reason);
2610
- });
2611
284
  }
2612
285
 
2613
- /**
2614
- * Config-specific merge-function which creates a new config-object
2615
- * by merging two configuration objects together.
2616
- *
2617
- * @param {Object} config1
2618
- * @param {Object} config2
2619
- *
2620
- * @returns {Object} New object resulting from merging config2 to config1
2621
- */
2622
- function mergeConfig(config1, config2) {
2623
- // eslint-disable-next-line no-param-reassign
2624
- config2 = config2 || {};
2625
- const config = {};
2626
-
2627
- function getMergedValue(target, source) {
2628
- if (utils.isPlainObject(target) && utils.isPlainObject(source)) {
2629
- return utils.merge(target, source);
2630
- } else if (utils.isPlainObject(source)) {
2631
- return utils.merge({}, source);
2632
- } else if (utils.isArray(source)) {
2633
- return source.slice();
2634
- }
2635
- return source;
2636
- }
2637
-
2638
- // eslint-disable-next-line consistent-return
2639
- function mergeDeepProperties(prop) {
2640
- if (!utils.isUndefined(config2[prop])) {
2641
- return getMergedValue(config1[prop], config2[prop]);
2642
- } else if (!utils.isUndefined(config1[prop])) {
2643
- return getMergedValue(undefined, config1[prop]);
2644
- }
2645
- }
2646
-
2647
- // eslint-disable-next-line consistent-return
2648
- function valueFromConfig2(prop) {
2649
- if (!utils.isUndefined(config2[prop])) {
2650
- return getMergedValue(undefined, config2[prop]);
2651
- }
2652
- }
2653
-
2654
- // eslint-disable-next-line consistent-return
2655
- function defaultToConfig2(prop) {
2656
- if (!utils.isUndefined(config2[prop])) {
2657
- return getMergedValue(undefined, config2[prop]);
2658
- } else if (!utils.isUndefined(config1[prop])) {
2659
- return getMergedValue(undefined, config1[prop]);
2660
- }
2661
- }
2662
-
2663
- // eslint-disable-next-line consistent-return
2664
- function mergeDirectKeys(prop) {
2665
- if (prop in config2) {
2666
- return getMergedValue(config1[prop], config2[prop]);
2667
- } else if (prop in config1) {
2668
- return getMergedValue(undefined, config1[prop]);
286
+ class TimeoutError extends Error {
287
+ constructor(request) {
288
+ super('Request timed out');
289
+ Object.defineProperty(this, "request", {
290
+ enumerable: true,
291
+ configurable: true,
292
+ writable: true,
293
+ value: void 0
294
+ });
295
+ this.name = 'TimeoutError';
296
+ this.request = request;
2669
297
  }
2670
- }
2671
-
2672
- const mergeMap = {
2673
- 'url': valueFromConfig2,
2674
- 'method': valueFromConfig2,
2675
- 'data': valueFromConfig2,
2676
- 'baseURL': defaultToConfig2,
2677
- 'transformRequest': defaultToConfig2,
2678
- 'transformResponse': defaultToConfig2,
2679
- 'paramsSerializer': defaultToConfig2,
2680
- 'timeout': defaultToConfig2,
2681
- 'timeoutMessage': defaultToConfig2,
2682
- 'withCredentials': defaultToConfig2,
2683
- 'adapter': defaultToConfig2,
2684
- 'responseType': defaultToConfig2,
2685
- 'xsrfCookieName': defaultToConfig2,
2686
- 'xsrfHeaderName': defaultToConfig2,
2687
- 'onUploadProgress': defaultToConfig2,
2688
- 'onDownloadProgress': defaultToConfig2,
2689
- 'decompress': defaultToConfig2,
2690
- 'maxContentLength': defaultToConfig2,
2691
- 'maxBodyLength': defaultToConfig2,
2692
- 'beforeRedirect': defaultToConfig2,
2693
- 'transport': defaultToConfig2,
2694
- 'httpAgent': defaultToConfig2,
2695
- 'httpsAgent': defaultToConfig2,
2696
- 'cancelToken': defaultToConfig2,
2697
- 'socketPath': defaultToConfig2,
2698
- 'responseEncoding': defaultToConfig2,
2699
- 'validateStatus': mergeDirectKeys
2700
- };
2701
-
2702
- utils.forEach(Object.keys(config1).concat(Object.keys(config2)), function computeConfigValue(prop) {
2703
- const merge = mergeMap[prop] || mergeDeepProperties;
2704
- const configValue = merge(prop);
2705
- (utils.isUndefined(configValue) && merge !== mergeDirectKeys) || (config[prop] = configValue);
2706
- });
2707
-
2708
- return config;
2709
298
  }
2710
299
 
2711
- const VERSION = "1.0.0";
2712
-
2713
- const validators$1 = {};
2714
-
2715
- // eslint-disable-next-line func-names
2716
- ['object', 'boolean', 'number', 'function', 'string', 'symbol'].forEach((type, i) => {
2717
- validators$1[type] = function validator(thing) {
2718
- return typeof thing === type || 'a' + (i < 1 ? 'n ' : ' ') + type;
2719
- };
2720
- });
2721
-
2722
- const deprecatedWarnings = {};
2723
-
2724
- /**
2725
- * Transitional option validator
2726
- *
2727
- * @param {function|boolean?} validator - set to false if the transitional option has been removed
2728
- * @param {string?} version - deprecated version / removed since version
2729
- * @param {string?} message - some message with additional info
2730
- *
2731
- * @returns {function}
2732
- */
2733
- validators$1.transitional = function transitional(validator, version, message) {
2734
- function formatMessage(opt, desc) {
2735
- return '[Axios v' + VERSION + '] Transitional option \'' + opt + '\'' + desc + (message ? '. ' + message : '');
2736
- }
2737
-
2738
- // eslint-disable-next-line func-names
2739
- return (value, opt, opts) => {
2740
- if (validator === false) {
2741
- throw new AxiosError(
2742
- formatMessage(opt, ' has been removed' + (version ? ' in ' + version : '')),
2743
- AxiosError.ERR_DEPRECATED
2744
- );
2745
- }
300
+ // eslint-disable-next-line @typescript-eslint/ban-types
301
+ const isObject = (value) => value !== null && typeof value === 'object';
2746
302
 
2747
- if (version && !deprecatedWarnings[opt]) {
2748
- deprecatedWarnings[opt] = true;
2749
- // eslint-disable-next-line no-console
2750
- console.warn(
2751
- formatMessage(
2752
- opt,
2753
- ' has been deprecated since v' + version + ' and will be removed in the near future'
2754
- )
2755
- );
303
+ const validateAndMerge = (...sources) => {
304
+ for (const source of sources) {
305
+ if ((!isObject(source) || Array.isArray(source)) && typeof source !== 'undefined') {
306
+ throw new TypeError('The `options` argument must be an object');
307
+ }
2756
308
  }
2757
-
2758
- return validator ? validator(value, opt, opts) : true;
2759
- };
309
+ return deepMerge({}, ...sources);
2760
310
  };
2761
-
2762
- /**
2763
- * Assert object's properties type
2764
- *
2765
- * @param {object} options
2766
- * @param {object} schema
2767
- * @param {boolean?} allowUnknown
2768
- *
2769
- * @returns {object}
2770
- */
2771
-
2772
- function assertOptions(options, schema, allowUnknown) {
2773
- if (typeof options !== 'object') {
2774
- throw new AxiosError('options must be an object', AxiosError.ERR_BAD_OPTION_VALUE);
2775
- }
2776
- const keys = Object.keys(options);
2777
- let i = keys.length;
2778
- while (i-- > 0) {
2779
- const opt = keys[i];
2780
- const validator = schema[opt];
2781
- if (validator) {
2782
- const value = options[opt];
2783
- const result = value === undefined || validator(value, opt, options);
2784
- if (result !== true) {
2785
- throw new AxiosError('option ' + opt + ' must be ' + result, AxiosError.ERR_BAD_OPTION_VALUE);
2786
- }
2787
- continue;
2788
- }
2789
- if (allowUnknown !== true) {
2790
- throw new AxiosError('Unknown option ' + opt, AxiosError.ERR_BAD_OPTION);
311
+ const mergeHeaders = (source1 = {}, source2 = {}) => {
312
+ const result = new globalThis.Headers(source1);
313
+ const isHeadersInstance = source2 instanceof globalThis.Headers;
314
+ const source = new globalThis.Headers(source2);
315
+ for (const [key, value] of source.entries()) {
316
+ if ((isHeadersInstance && value === 'undefined') || value === undefined) {
317
+ result.delete(key);
318
+ }
319
+ else {
320
+ result.set(key, value);
321
+ }
2791
322
  }
2792
- }
2793
- }
2794
-
2795
- const validator = {
2796
- assertOptions,
2797
- validators: validators$1
323
+ return result;
2798
324
  };
2799
-
2800
- const validators = validator.validators;
2801
-
2802
- /**
2803
- * Create a new instance of Axios
2804
- *
2805
- * @param {Object} instanceConfig The default config for the instance
2806
- *
2807
- * @return {Axios} A new instance of Axios
2808
- */
2809
- class Axios {
2810
- constructor(instanceConfig) {
2811
- this.defaults = instanceConfig;
2812
- this.interceptors = {
2813
- request: new InterceptorManager(),
2814
- response: new InterceptorManager()
2815
- };
2816
- }
2817
-
2818
- /**
2819
- * Dispatch a request
2820
- *
2821
- * @param {String|Object} configOrUrl The config specific for this request (merged with this.defaults)
2822
- * @param {?Object} config
2823
- *
2824
- * @returns {Promise} The Promise to be fulfilled
2825
- */
2826
- request(configOrUrl, config) {
2827
- /*eslint no-param-reassign:0*/
2828
- // Allow for axios('example/url'[, config]) a la fetch API
2829
- if (typeof configOrUrl === 'string') {
2830
- config = config || {};
2831
- config.url = configOrUrl;
2832
- } else {
2833
- config = configOrUrl || {};
2834
- }
2835
-
2836
- config = mergeConfig(this.defaults, config);
2837
-
2838
- const transitional = config.transitional;
2839
-
2840
- if (transitional !== undefined) {
2841
- validator.assertOptions(transitional, {
2842
- silentJSONParsing: validators.transitional(validators.boolean),
2843
- forcedJSONParsing: validators.transitional(validators.boolean),
2844
- clarifyTimeoutError: validators.transitional(validators.boolean)
2845
- }, false);
2846
- }
2847
-
2848
- // Set config.method
2849
- config.method = (config.method || this.defaults.method || 'get').toLowerCase();
2850
-
2851
- // Flatten headers
2852
- const defaultHeaders = config.headers && utils.merge(
2853
- config.headers.common,
2854
- config.headers[config.method]
2855
- );
2856
-
2857
- defaultHeaders && utils.forEach(
2858
- ['delete', 'get', 'head', 'post', 'put', 'patch', 'common'],
2859
- function cleanHeaderConfig(method) {
2860
- delete config.headers[method];
2861
- }
2862
- );
2863
-
2864
- config.headers = new AxiosHeaders(config.headers, defaultHeaders);
2865
-
2866
- // filter out skipped interceptors
2867
- const requestInterceptorChain = [];
2868
- let synchronousRequestInterceptors = true;
2869
- this.interceptors.request.forEach(function unshiftRequestInterceptors(interceptor) {
2870
- if (typeof interceptor.runWhen === 'function' && interceptor.runWhen(config) === false) {
2871
- return;
2872
- }
2873
-
2874
- synchronousRequestInterceptors = synchronousRequestInterceptors && interceptor.synchronous;
2875
-
2876
- requestInterceptorChain.unshift(interceptor.fulfilled, interceptor.rejected);
2877
- });
2878
-
2879
- const responseInterceptorChain = [];
2880
- this.interceptors.response.forEach(function pushResponseInterceptors(interceptor) {
2881
- responseInterceptorChain.push(interceptor.fulfilled, interceptor.rejected);
2882
- });
2883
-
2884
- let promise;
2885
- let i = 0;
2886
- let len;
2887
-
2888
- if (!synchronousRequestInterceptors) {
2889
- const chain = [dispatchRequest.bind(this), undefined];
2890
- chain.unshift.apply(chain, requestInterceptorChain);
2891
- chain.push.apply(chain, responseInterceptorChain);
2892
- len = chain.length;
2893
-
2894
- promise = Promise.resolve(config);
2895
-
2896
- while (i < len) {
2897
- promise = promise.then(chain[i++], chain[i++]);
2898
- }
2899
-
2900
- return promise;
325
+ // TODO: Make this strongly-typed (no `any`).
326
+ const deepMerge = (...sources) => {
327
+ let returnValue = {};
328
+ let headers = {};
329
+ for (const source of sources) {
330
+ if (Array.isArray(source)) {
331
+ if (!Array.isArray(returnValue)) {
332
+ returnValue = [];
333
+ }
334
+ returnValue = [...returnValue, ...source];
335
+ }
336
+ else if (isObject(source)) {
337
+ for (let [key, value] of Object.entries(source)) {
338
+ if (isObject(value) && key in returnValue) {
339
+ value = deepMerge(returnValue[key], value);
340
+ }
341
+ returnValue = { ...returnValue, [key]: value };
342
+ }
343
+ if (isObject(source.headers)) {
344
+ headers = mergeHeaders(headers, source.headers);
345
+ returnValue.headers = headers;
346
+ }
347
+ }
2901
348
  }
2902
-
2903
- len = requestInterceptorChain.length;
2904
-
2905
- let newConfig = config;
2906
-
2907
- i = 0;
2908
-
2909
- while (i < len) {
2910
- const onFulfilled = requestInterceptorChain[i++];
2911
- const onRejected = requestInterceptorChain[i++];
2912
- try {
2913
- newConfig = onFulfilled(newConfig);
2914
- } catch (error) {
2915
- onRejected.call(this, error);
2916
- break;
2917
- }
349
+ return returnValue;
350
+ };
351
+
352
+ const supportsStreams = (() => {
353
+ let duplexAccessed = false;
354
+ let hasContentType = false;
355
+ const supportsReadableStream = typeof globalThis.ReadableStream === 'function';
356
+ if (supportsReadableStream) {
357
+ hasContentType = new globalThis.Request('https://a.com', {
358
+ body: new globalThis.ReadableStream(),
359
+ method: 'POST',
360
+ // @ts-expect-error - Types are outdated.
361
+ get duplex() {
362
+ duplexAccessed = true;
363
+ return 'half';
364
+ },
365
+ }).headers.has('Content-Type');
2918
366
  }
2919
-
2920
- try {
2921
- promise = dispatchRequest.call(this, newConfig);
2922
- } catch (error) {
2923
- return Promise.reject(error);
367
+ return duplexAccessed && !hasContentType;
368
+ })();
369
+ const supportsAbortController = typeof globalThis.AbortController === 'function';
370
+ const supportsFormData = typeof globalThis.FormData === 'function';
371
+ const requestMethods = ['get', 'post', 'put', 'patch', 'head', 'delete'];
372
+ const responseTypes = {
373
+ json: 'application/json',
374
+ text: 'text/*',
375
+ formData: 'multipart/form-data',
376
+ arrayBuffer: '*/*',
377
+ blob: '*/*',
378
+ };
379
+ // The maximum value of a 32bit int (see issue #117)
380
+ const maxSafeTimeout = 2147483647;
381
+ const stop = Symbol('stop');
382
+
383
+ const normalizeRequestMethod = (input) => requestMethods.includes(input) ? input.toUpperCase() : input;
384
+ const retryMethods = ['get', 'put', 'head', 'delete', 'options', 'trace'];
385
+ const retryStatusCodes = [408, 413, 429, 500, 502, 503, 504];
386
+ const retryAfterStatusCodes = [413, 429, 503];
387
+ const defaultRetryOptions = {
388
+ limit: 2,
389
+ methods: retryMethods,
390
+ statusCodes: retryStatusCodes,
391
+ afterStatusCodes: retryAfterStatusCodes,
392
+ maxRetryAfter: Number.POSITIVE_INFINITY,
393
+ };
394
+ const normalizeRetryOptions = (retry = {}) => {
395
+ if (typeof retry === 'number') {
396
+ return {
397
+ ...defaultRetryOptions,
398
+ limit: retry,
399
+ };
2924
400
  }
2925
-
2926
- i = 0;
2927
- len = responseInterceptorChain.length;
2928
-
2929
- while (i < len) {
2930
- promise = promise.then(responseInterceptorChain[i++], responseInterceptorChain[i++]);
401
+ if (retry.methods && !Array.isArray(retry.methods)) {
402
+ throw new Error('retry.methods must be an array');
2931
403
  }
2932
-
2933
- return promise;
2934
- }
2935
-
2936
- getUri(config) {
2937
- config = mergeConfig(this.defaults, config);
2938
- const fullPath = buildFullPath(config.baseURL, config.url);
2939
- return buildURL(fullPath, config.params, config.paramsSerializer);
2940
- }
2941
- }
2942
-
2943
- // Provide aliases for supported request methods
2944
- utils.forEach(['delete', 'get', 'head', 'options'], function forEachMethodNoData(method) {
2945
- /*eslint func-names:0*/
2946
- Axios.prototype[method] = function(url, config) {
2947
- return this.request(mergeConfig(config || {}, {
2948
- method,
2949
- url,
2950
- data: (config || {}).data
2951
- }));
2952
- };
2953
- });
2954
-
2955
- utils.forEach(['post', 'put', 'patch'], function forEachMethodWithData(method) {
2956
- /*eslint func-names:0*/
2957
-
2958
- function generateHTTPMethod(isForm) {
2959
- return function httpMethod(url, data, config) {
2960
- return this.request(mergeConfig(config || {}, {
2961
- method,
2962
- headers: isForm ? {
2963
- 'Content-Type': 'multipart/form-data'
2964
- } : {},
2965
- url,
2966
- data
2967
- }));
2968
- };
2969
- }
2970
-
2971
- Axios.prototype[method] = generateHTTPMethod();
2972
-
2973
- Axios.prototype[method + 'Form'] = generateHTTPMethod(true);
2974
- });
2975
-
2976
- /**
2977
- * A `CancelToken` is an object that can be used to request cancellation of an operation.
2978
- *
2979
- * @param {Function} executor The executor function.
2980
- *
2981
- * @returns {CancelToken}
2982
- */
2983
- class CancelToken {
2984
- constructor(executor) {
2985
- if (typeof executor !== 'function') {
2986
- throw new TypeError('executor must be a function.');
404
+ if (retry.statusCodes && !Array.isArray(retry.statusCodes)) {
405
+ throw new Error('retry.statusCodes must be an array');
2987
406
  }
2988
-
2989
- let resolvePromise;
2990
-
2991
- this.promise = new Promise(function promiseExecutor(resolve) {
2992
- resolvePromise = resolve;
2993
- });
2994
-
2995
- const token = this;
2996
-
2997
- // eslint-disable-next-line func-names
2998
- this.promise.then(cancel => {
2999
- if (!token._listeners) return;
3000
-
3001
- let i = token._listeners.length;
3002
-
3003
- while (i-- > 0) {
3004
- token._listeners[i](cancel);
3005
- }
3006
- token._listeners = null;
3007
- });
3008
-
3009
- // eslint-disable-next-line func-names
3010
- this.promise.then = onfulfilled => {
3011
- let _resolve;
3012
- // eslint-disable-next-line func-names
3013
- const promise = new Promise(resolve => {
3014
- token.subscribe(resolve);
3015
- _resolve = resolve;
3016
- }).then(onfulfilled);
3017
-
3018
- promise.cancel = function reject() {
3019
- token.unsubscribe(_resolve);
3020
- };
3021
-
3022
- return promise;
407
+ return {
408
+ ...defaultRetryOptions,
409
+ ...retry,
410
+ afterStatusCodes: retryAfterStatusCodes,
3023
411
  };
412
+ };
3024
413
 
3025
- executor(function cancel(message, config, request) {
3026
- if (token.reason) {
3027
- // Cancellation has already been requested
3028
- return;
3029
- }
3030
-
3031
- token.reason = new CanceledError(message, config, request);
3032
- resolvePromise(token.reason);
414
+ // `Promise.race()` workaround (#91)
415
+ const timeout = async (request, abortController, options) => new Promise((resolve, reject) => {
416
+ const timeoutId = setTimeout(() => {
417
+ if (abortController) {
418
+ abortController.abort();
419
+ }
420
+ reject(new TimeoutError(request));
421
+ }, options.timeout);
422
+ void options
423
+ .fetch(request)
424
+ .then(resolve)
425
+ .catch(reject)
426
+ .then(() => {
427
+ clearTimeout(timeoutId);
3033
428
  });
3034
- }
429
+ });
430
+ const delay = async (ms) => new Promise(resolve => {
431
+ setTimeout(resolve, ms);
432
+ });
3035
433
 
3036
- /**
3037
- * Throws a `CanceledError` if cancellation has been requested.
3038
- */
3039
- throwIfRequested() {
3040
- if (this.reason) {
3041
- throw this.reason;
434
+ class Ky {
435
+ // eslint-disable-next-line complexity
436
+ constructor(input, options = {}) {
437
+ Object.defineProperty(this, "request", {
438
+ enumerable: true,
439
+ configurable: true,
440
+ writable: true,
441
+ value: void 0
442
+ });
443
+ Object.defineProperty(this, "abortController", {
444
+ enumerable: true,
445
+ configurable: true,
446
+ writable: true,
447
+ value: void 0
448
+ });
449
+ Object.defineProperty(this, "_retryCount", {
450
+ enumerable: true,
451
+ configurable: true,
452
+ writable: true,
453
+ value: 0
454
+ });
455
+ Object.defineProperty(this, "_input", {
456
+ enumerable: true,
457
+ configurable: true,
458
+ writable: true,
459
+ value: void 0
460
+ });
461
+ Object.defineProperty(this, "_options", {
462
+ enumerable: true,
463
+ configurable: true,
464
+ writable: true,
465
+ value: void 0
466
+ });
467
+ this._input = input;
468
+ this._options = {
469
+ // TODO: credentials can be removed when the spec change is implemented in all browsers. Context: https://www.chromestatus.com/feature/4539473312350208
470
+ credentials: this._input.credentials || 'same-origin',
471
+ ...options,
472
+ headers: mergeHeaders(this._input.headers, options.headers),
473
+ hooks: deepMerge({
474
+ beforeRequest: [],
475
+ beforeRetry: [],
476
+ beforeError: [],
477
+ afterResponse: [],
478
+ }, options.hooks),
479
+ method: normalizeRequestMethod(options.method ?? this._input.method),
480
+ // eslint-disable-next-line @typescript-eslint/prefer-nullish-coalescing
481
+ prefixUrl: String(options.prefixUrl || ''),
482
+ retry: normalizeRetryOptions(options.retry),
483
+ throwHttpErrors: options.throwHttpErrors !== false,
484
+ timeout: typeof options.timeout === 'undefined' ? 10000 : options.timeout,
485
+ fetch: options.fetch ?? globalThis.fetch.bind(globalThis),
486
+ };
487
+ if (typeof this._input !== 'string' && !(this._input instanceof URL || this._input instanceof globalThis.Request)) {
488
+ throw new TypeError('`input` must be a string, URL, or Request');
489
+ }
490
+ if (this._options.prefixUrl && typeof this._input === 'string') {
491
+ if (this._input.startsWith('/')) {
492
+ throw new Error('`input` must not begin with a slash when using `prefixUrl`');
493
+ }
494
+ if (!this._options.prefixUrl.endsWith('/')) {
495
+ this._options.prefixUrl += '/';
496
+ }
497
+ this._input = this._options.prefixUrl + this._input;
498
+ }
499
+ if (supportsAbortController) {
500
+ this.abortController = new globalThis.AbortController();
501
+ if (this._options.signal) {
502
+ this._options.signal.addEventListener('abort', () => {
503
+ this.abortController.abort();
504
+ });
505
+ }
506
+ this._options.signal = this.abortController.signal;
507
+ }
508
+ this.request = new globalThis.Request(this._input, this._options);
509
+ if (supportsStreams) {
510
+ // @ts-expect-error - Types are outdated.
511
+ this.request.duplex = 'half';
512
+ }
513
+ if (this._options.searchParams) {
514
+ // eslint-disable-next-line unicorn/prevent-abbreviations
515
+ const textSearchParams = typeof this._options.searchParams === 'string'
516
+ ? this._options.searchParams.replace(/^\?/, '')
517
+ : new URLSearchParams(this._options.searchParams).toString();
518
+ // eslint-disable-next-line unicorn/prevent-abbreviations
519
+ const searchParams = '?' + textSearchParams;
520
+ const url = this.request.url.replace(/(?:\?.*?)?(?=#|$)/, searchParams);
521
+ // To provide correct form boundary, Content-Type header should be deleted each time when new Request instantiated from another one
522
+ if (((supportsFormData && this._options.body instanceof globalThis.FormData)
523
+ || this._options.body instanceof URLSearchParams) && !(this._options.headers && this._options.headers['content-type'])) {
524
+ this.request.headers.delete('content-type');
525
+ }
526
+ this.request = new globalThis.Request(new globalThis.Request(url, this.request), this._options);
527
+ }
528
+ if (this._options.json !== undefined) {
529
+ this._options.body = JSON.stringify(this._options.json);
530
+ this.request.headers.set('content-type', this._options.headers.get('content-type') ?? 'application/json');
531
+ this.request = new globalThis.Request(this.request, { body: this._options.body });
532
+ }
3042
533
  }
3043
- }
3044
-
3045
- /**
3046
- * Subscribe to the cancel signal
3047
- */
3048
-
3049
- subscribe(listener) {
3050
- if (this.reason) {
3051
- listener(this.reason);
3052
- return;
534
+ // eslint-disable-next-line @typescript-eslint/promise-function-async
535
+ static create(input, options) {
536
+ const ky = new Ky(input, options);
537
+ const fn = async () => {
538
+ if (ky._options.timeout > maxSafeTimeout) {
539
+ throw new RangeError(`The \`timeout\` option cannot be greater than ${maxSafeTimeout}`);
540
+ }
541
+ // Delay the fetch so that body method shortcuts can set the Accept header
542
+ await Promise.resolve();
543
+ let response = await ky._fetch();
544
+ for (const hook of ky._options.hooks.afterResponse) {
545
+ // eslint-disable-next-line no-await-in-loop
546
+ const modifiedResponse = await hook(ky.request, ky._options, ky._decorateResponse(response.clone()));
547
+ if (modifiedResponse instanceof globalThis.Response) {
548
+ response = modifiedResponse;
549
+ }
550
+ }
551
+ ky._decorateResponse(response);
552
+ if (!response.ok && ky._options.throwHttpErrors) {
553
+ let error = new HTTPError(response, ky.request, ky._options);
554
+ for (const hook of ky._options.hooks.beforeError) {
555
+ // eslint-disable-next-line no-await-in-loop
556
+ error = await hook(error);
557
+ }
558
+ throw error;
559
+ }
560
+ // If `onDownloadProgress` is passed, it uses the stream API internally
561
+ /* istanbul ignore next */
562
+ if (ky._options.onDownloadProgress) {
563
+ if (typeof ky._options.onDownloadProgress !== 'function') {
564
+ throw new TypeError('The `onDownloadProgress` option must be a function');
565
+ }
566
+ if (!supportsStreams) {
567
+ throw new Error('Streams are not supported in your environment. `ReadableStream` is missing.');
568
+ }
569
+ return ky._stream(response.clone(), ky._options.onDownloadProgress);
570
+ }
571
+ return response;
572
+ };
573
+ const isRetriableMethod = ky._options.retry.methods.includes(ky.request.method.toLowerCase());
574
+ const result = (isRetriableMethod ? ky._retry(fn) : fn());
575
+ for (const [type, mimeType] of Object.entries(responseTypes)) {
576
+ result[type] = async () => {
577
+ // eslint-disable-next-line @typescript-eslint/prefer-nullish-coalescing
578
+ ky.request.headers.set('accept', ky.request.headers.get('accept') || mimeType);
579
+ const awaitedResult = await result;
580
+ const response = awaitedResult.clone();
581
+ if (type === 'json') {
582
+ if (response.status === 204) {
583
+ return '';
584
+ }
585
+ if (options.parseJson) {
586
+ return options.parseJson(await response.text());
587
+ }
588
+ }
589
+ return response[type]();
590
+ };
591
+ }
592
+ return result;
593
+ }
594
+ _calculateRetryDelay(error) {
595
+ this._retryCount++;
596
+ if (this._retryCount < this._options.retry.limit && !(error instanceof TimeoutError)) {
597
+ if (error instanceof HTTPError) {
598
+ if (!this._options.retry.statusCodes.includes(error.response.status)) {
599
+ return 0;
600
+ }
601
+ const retryAfter = error.response.headers.get('Retry-After');
602
+ if (retryAfter && this._options.retry.afterStatusCodes.includes(error.response.status)) {
603
+ let after = Number(retryAfter);
604
+ if (Number.isNaN(after)) {
605
+ after = Date.parse(retryAfter) - Date.now();
606
+ }
607
+ else {
608
+ after *= 1000;
609
+ }
610
+ if (typeof this._options.retry.maxRetryAfter !== 'undefined' && after > this._options.retry.maxRetryAfter) {
611
+ return 0;
612
+ }
613
+ return after;
614
+ }
615
+ if (error.response.status === 413) {
616
+ return 0;
617
+ }
618
+ }
619
+ const BACKOFF_FACTOR = 0.3;
620
+ return BACKOFF_FACTOR * (2 ** (this._retryCount - 1)) * 1000;
621
+ }
622
+ return 0;
3053
623
  }
3054
-
3055
- if (this._listeners) {
3056
- this._listeners.push(listener);
3057
- } else {
3058
- this._listeners = [listener];
624
+ _decorateResponse(response) {
625
+ if (this._options.parseJson) {
626
+ response.json = async () => this._options.parseJson(await response.text());
627
+ }
628
+ return response;
3059
629
  }
3060
- }
3061
-
3062
- /**
3063
- * Unsubscribe from the cancel signal
3064
- */
3065
-
3066
- unsubscribe(listener) {
3067
- if (!this._listeners) {
3068
- return;
630
+ async _retry(fn) {
631
+ try {
632
+ return await fn();
633
+ // eslint-disable-next-line @typescript-eslint/no-implicit-any-catch
634
+ }
635
+ catch (error) {
636
+ const ms = Math.min(this._calculateRetryDelay(error), maxSafeTimeout);
637
+ if (ms !== 0 && this._retryCount > 0) {
638
+ await delay(ms);
639
+ for (const hook of this._options.hooks.beforeRetry) {
640
+ // eslint-disable-next-line no-await-in-loop
641
+ const hookResult = await hook({
642
+ request: this.request,
643
+ options: this._options,
644
+ error: error,
645
+ retryCount: this._retryCount,
646
+ });
647
+ // If `stop` is returned from the hook, the retry process is stopped
648
+ if (hookResult === stop) {
649
+ return;
650
+ }
651
+ }
652
+ return this._retry(fn);
653
+ }
654
+ throw error;
655
+ }
3069
656
  }
3070
- const index = this._listeners.indexOf(listener);
3071
- if (index !== -1) {
3072
- this._listeners.splice(index, 1);
657
+ async _fetch() {
658
+ for (const hook of this._options.hooks.beforeRequest) {
659
+ // eslint-disable-next-line no-await-in-loop
660
+ const result = await hook(this.request, this._options);
661
+ if (result instanceof Request) {
662
+ this.request = result;
663
+ break;
664
+ }
665
+ if (result instanceof Response) {
666
+ return result;
667
+ }
668
+ }
669
+ if (this._options.timeout === false) {
670
+ return this._options.fetch(this.request.clone());
671
+ }
672
+ return timeout(this.request.clone(), this.abortController, this._options);
673
+ }
674
+ /* istanbul ignore next */
675
+ _stream(response, onDownloadProgress) {
676
+ const totalBytes = Number(response.headers.get('content-length')) || 0;
677
+ let transferredBytes = 0;
678
+ if (response.status === 204) {
679
+ if (onDownloadProgress) {
680
+ onDownloadProgress({ percent: 1, totalBytes, transferredBytes }, new Uint8Array());
681
+ }
682
+ return new globalThis.Response(null, {
683
+ status: response.status,
684
+ statusText: response.statusText,
685
+ headers: response.headers,
686
+ });
687
+ }
688
+ return new globalThis.Response(new globalThis.ReadableStream({
689
+ async start(controller) {
690
+ const reader = response.body.getReader();
691
+ if (onDownloadProgress) {
692
+ onDownloadProgress({ percent: 0, transferredBytes: 0, totalBytes }, new Uint8Array());
693
+ }
694
+ async function read() {
695
+ const { done, value } = await reader.read();
696
+ if (done) {
697
+ controller.close();
698
+ return;
699
+ }
700
+ if (onDownloadProgress) {
701
+ transferredBytes += value.byteLength;
702
+ const percent = totalBytes === 0 ? 0 : transferredBytes / totalBytes;
703
+ onDownloadProgress({ percent, transferredBytes, totalBytes }, value);
704
+ }
705
+ controller.enqueue(value);
706
+ await read();
707
+ }
708
+ await read();
709
+ },
710
+ }), {
711
+ status: response.status,
712
+ statusText: response.statusText,
713
+ headers: response.headers,
714
+ });
3073
715
  }
3074
- }
3075
-
3076
- /**
3077
- * Returns an object that contains a new `CancelToken` and a function that, when called,
3078
- * cancels the `CancelToken`.
3079
- */
3080
- static source() {
3081
- let cancel;
3082
- const token = new CancelToken(function executor(c) {
3083
- cancel = c;
3084
- });
3085
- return {
3086
- token,
3087
- cancel
3088
- };
3089
- }
3090
- }
3091
-
3092
- /**
3093
- * Syntactic sugar for invoking a function and expanding an array for arguments.
3094
- *
3095
- * Common use case would be to use `Function.prototype.apply`.
3096
- *
3097
- * ```js
3098
- * function f(x, y, z) {}
3099
- * var args = [1, 2, 3];
3100
- * f.apply(null, args);
3101
- * ```
3102
- *
3103
- * With `spread` this example can be re-written.
3104
- *
3105
- * ```js
3106
- * spread(function(x, y, z) {})([1, 2, 3]);
3107
- * ```
3108
- *
3109
- * @param {Function} callback
3110
- *
3111
- * @returns {Function}
3112
- */
3113
- function spread(callback) {
3114
- return function wrap(arr) {
3115
- return callback.apply(null, arr);
3116
- };
3117
- }
3118
-
3119
- /**
3120
- * Determines whether the payload is an error thrown by Axios
3121
- *
3122
- * @param {*} payload The value to test
3123
- *
3124
- * @returns {boolean} True if the payload is an error thrown by Axios, otherwise false
3125
- */
3126
- function isAxiosError(payload) {
3127
- return utils.isObject(payload) && (payload.isAxiosError === true);
3128
- }
3129
-
3130
- /**
3131
- * Create an instance of Axios
3132
- *
3133
- * @param {Object} defaultConfig The default config for the instance
3134
- *
3135
- * @returns {Axios} A new instance of Axios
3136
- */
3137
- function createInstance(defaultConfig) {
3138
- const context = new Axios(defaultConfig);
3139
- const instance = bind(Axios.prototype.request, context);
3140
-
3141
- // Copy axios.prototype to instance
3142
- utils.extend(instance, Axios.prototype, context, {allOwnKeys: true});
3143
-
3144
- // Copy context to instance
3145
- utils.extend(instance, context, null, {allOwnKeys: true});
3146
-
3147
- // Factory for creating new instances
3148
- instance.create = function create(instanceConfig) {
3149
- return createInstance(mergeConfig(defaultConfig, instanceConfig));
3150
- };
3151
-
3152
- return instance;
3153
716
  }
3154
717
 
3155
- // Create the default instance to be exported
3156
- const axios = createInstance(defaults);
3157
-
3158
- // Expose Axios class to allow class inheritance
3159
- axios.Axios = Axios;
3160
-
3161
- // Expose Cancel & CancelToken
3162
- axios.CanceledError = CanceledError;
3163
- axios.CancelToken = CancelToken;
3164
- axios.isCancel = isCancel;
3165
- axios.VERSION = VERSION;
3166
- axios.toFormData = toFormData;
3167
-
3168
- // Expose AxiosError class
3169
- axios.AxiosError = AxiosError;
3170
-
3171
- // alias for CanceledError for backward compatibility
3172
- axios.Cancel = axios.CanceledError;
3173
-
3174
- // Expose all/spread
3175
- axios.all = function all(promises) {
3176
- return Promise.all(promises);
3177
- };
3178
-
3179
- axios.spread = spread;
3180
-
3181
- // Expose isAxiosError
3182
- axios.isAxiosError = isAxiosError;
3183
-
3184
- axios.formToJSON = thing => {
3185
- return formDataToJSON(utils.isHTMLForm(thing) ? new FormData(thing) : thing);
718
+ /*! MIT License © Sindre Sorhus */
719
+ const createInstance = (defaults) => {
720
+ // eslint-disable-next-line @typescript-eslint/promise-function-async
721
+ const ky = (input, options) => Ky.create(input, validateAndMerge(defaults, options));
722
+ for (const method of requestMethods) {
723
+ // eslint-disable-next-line @typescript-eslint/promise-function-async
724
+ ky[method] = (input, options) => Ky.create(input, validateAndMerge(defaults, options, { method }));
725
+ }
726
+ ky.create = (newDefaults) => createInstance(validateAndMerge(newDefaults));
727
+ ky.extend = (newDefaults) => createInstance(validateAndMerge(defaults, newDefaults));
728
+ ky.stop = stop;
729
+ return ky;
3186
730
  };
731
+ const ky = createInstance();
3187
732
 
3188
733
  // --------------------------------------------------------[ mutable store ]
3189
734
  const storeDef = {
@@ -3320,10 +865,17 @@ const processPick = (next) => {
3320
865
  savePick(state.pick);
3321
866
  };
3322
867
  // --------------------------------------------------------[ utils ]
3323
- const api = axios.create({
3324
- baseURL: 'https://sudoku-rust-api.vercel.app/api/',
868
+ const api = ky.extend({
869
+ hooks: {
870
+ beforeRequest: [
871
+ request => {
872
+ request.headers.set('X-Requested-With', 'ky');
873
+ request.headers.set('X-Custom-Header', 'foobar');
874
+ },
875
+ ],
876
+ },
877
+ prefixUrl: 'https://sudoku-rust-api.vercel.app/api',
3325
878
  timeout: 10000,
3326
- headers: { 'X-Custom-Header': 'foobar' },
3327
879
  });
3328
880
  const saveInputs = (inputs) => {
3329
881
  bag.inputs.store(inputs);
@@ -3364,27 +916,26 @@ const initApp = () => {
3364
916
  }
3365
917
  }
3366
918
  };
3367
- const refresh = () => {
919
+ const refresh = async () => {
3368
920
  clearStore(true);
3369
921
  saveInputs([]);
3370
922
  savePick(state.pick);
3371
- // fetch a new puzzle from the api...
3372
- api
3373
- .get('/puzzle')
3374
- .then(({ data }) => {
923
+ try {
924
+ // fetch a new puzzle from the api...
925
+ const data = await api.get('puzzle').json();
3375
926
  updateStore(data);
3376
- })
3377
- .catch(error => {
927
+ }
928
+ catch (err) {
3378
929
  // handle error...
3379
- const { message } = error;
930
+ const { message } = err;
3380
931
  console.log('-- ', message);
3381
- console.log(error);
932
+ console.log(err);
3382
933
  state.error = message;
3383
- })
3384
- .then(() => {
934
+ }
935
+ finally {
3385
936
  // always executed
3386
937
  state.loading = false;
3387
- });
938
+ }
3388
939
  };
3389
940
  const select = (cell) => {
3390
941
  processPick(cell);