proto-sudoku-wc 0.0.484 → 0.0.486

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.
@@ -246,2021 +246,485 @@ const createStore = (defaultState, shouldUpdate) => {
246
246
  return map;
247
247
  };
248
248
 
249
- var bind = function bind(fn, thisArg) {
250
- return function wrap() {
251
- var args = new Array(arguments.length);
252
- for (var i = 0; i < args.length; i++) {
253
- args[i] = arguments[i];
254
- }
255
- return fn.apply(thisArg, args);
256
- };
257
- };
258
-
259
- // utils is a library of generic helper functions non-specific to axios
260
-
261
- var toString = Object.prototype.toString;
262
-
263
- // eslint-disable-next-line func-names
264
- var kindOf = (function(cache) {
265
- // eslint-disable-next-line func-names
266
- return function(thing) {
267
- var str = toString.call(thing);
268
- return cache[str] || (cache[str] = str.slice(8, -1).toLowerCase());
269
- };
270
- })(Object.create(null));
271
-
272
- function kindOfTest(type) {
273
- type = type.toLowerCase();
274
- return function isKindOf(thing) {
275
- return kindOf(thing) === type;
276
- };
277
- }
278
-
279
- /**
280
- * Determine if a value is an Array
281
- *
282
- * @param {Object} val The value to test
283
- * @returns {boolean} True if value is an Array, otherwise false
284
- */
285
- function isArray(val) {
286
- return Array.isArray(val);
287
- }
288
-
289
- /**
290
- * Determine if a value is undefined
291
- *
292
- * @param {Object} val The value to test
293
- * @returns {boolean} True if the value is undefined, otherwise false
294
- */
295
- function isUndefined(val) {
296
- return typeof val === 'undefined';
297
- }
298
-
299
- /**
300
- * Determine if a value is a Buffer
301
- *
302
- * @param {Object} val The value to test
303
- * @returns {boolean} True if value is a Buffer, otherwise false
304
- */
305
- function isBuffer(val) {
306
- return val !== null && !isUndefined(val) && val.constructor !== null && !isUndefined(val.constructor)
307
- && typeof val.constructor.isBuffer === 'function' && val.constructor.isBuffer(val);
308
- }
309
-
310
- /**
311
- * Determine if a value is an ArrayBuffer
312
- *
313
- * @function
314
- * @param {Object} val The value to test
315
- * @returns {boolean} True if value is an ArrayBuffer, otherwise false
316
- */
317
- var isArrayBuffer = kindOfTest('ArrayBuffer');
318
-
319
-
320
- /**
321
- * Determine if a value is a view on an ArrayBuffer
322
- *
323
- * @param {Object} val The value to test
324
- * @returns {boolean} True if value is a view on an ArrayBuffer, otherwise false
325
- */
326
- function isArrayBufferView(val) {
327
- var result;
328
- if ((typeof ArrayBuffer !== 'undefined') && (ArrayBuffer.isView)) {
329
- result = ArrayBuffer.isView(val);
330
- } else {
331
- result = (val) && (val.buffer) && (isArrayBuffer(val.buffer));
332
- }
333
- return result;
334
- }
335
-
336
- /**
337
- * Determine if a value is a String
338
- *
339
- * @param {Object} val The value to test
340
- * @returns {boolean} True if value is a String, otherwise false
341
- */
342
- function isString(val) {
343
- return typeof val === 'string';
344
- }
345
-
346
- /**
347
- * Determine if a value is a Number
348
- *
349
- * @param {Object} val The value to test
350
- * @returns {boolean} True if value is a Number, otherwise false
351
- */
352
- function isNumber(val) {
353
- return typeof val === 'number';
354
- }
355
-
356
- /**
357
- * Determine if a value is an Object
358
- *
359
- * @param {Object} val The value to test
360
- * @returns {boolean} True if value is an Object, otherwise false
361
- */
362
- function isObject(val) {
363
- return val !== null && typeof val === 'object';
364
- }
365
-
366
- /**
367
- * Determine if a value is a plain Object
368
- *
369
- * @param {Object} val The value to test
370
- * @return {boolean} True if value is a plain Object, otherwise false
371
- */
372
- function isPlainObject(val) {
373
- if (kindOf(val) !== 'object') {
374
- return false;
375
- }
376
-
377
- var prototype = Object.getPrototypeOf(val);
378
- return prototype === null || prototype === Object.prototype;
379
- }
380
-
381
- /**
382
- * Determine if a value is a Date
383
- *
384
- * @function
385
- * @param {Object} val The value to test
386
- * @returns {boolean} True if value is a Date, otherwise false
387
- */
388
- var isDate = kindOfTest('Date');
389
-
390
- /**
391
- * Determine if a value is a File
392
- *
393
- * @function
394
- * @param {Object} val The value to test
395
- * @returns {boolean} True if value is a File, otherwise false
396
- */
397
- var isFile = kindOfTest('File');
398
-
399
- /**
400
- * Determine if a value is a Blob
401
- *
402
- * @function
403
- * @param {Object} val The value to test
404
- * @returns {boolean} True if value is a Blob, otherwise false
405
- */
406
- var isBlob = kindOfTest('Blob');
407
-
408
- /**
409
- * Determine if a value is a FileList
410
- *
411
- * @function
412
- * @param {Object} val The value to test
413
- * @returns {boolean} True if value is a File, otherwise false
414
- */
415
- var isFileList = kindOfTest('FileList');
416
-
417
- /**
418
- * Determine if a value is a Function
419
- *
420
- * @param {Object} val The value to test
421
- * @returns {boolean} True if value is a Function, otherwise false
422
- */
423
- function isFunction(val) {
424
- return toString.call(val) === '[object Function]';
425
- }
426
-
427
- /**
428
- * Determine if a value is a Stream
429
- *
430
- * @param {Object} val The value to test
431
- * @returns {boolean} True if value is a Stream, otherwise false
432
- */
433
- function isStream(val) {
434
- return isObject(val) && isFunction(val.pipe);
435
- }
436
-
437
- /**
438
- * Determine if a value is a FormData
439
- *
440
- * @param {Object} thing The value to test
441
- * @returns {boolean} True if value is an FormData, otherwise false
442
- */
443
- function isFormData(thing) {
444
- var pattern = '[object FormData]';
445
- return thing && (
446
- (typeof FormData === 'function' && thing instanceof FormData) ||
447
- toString.call(thing) === pattern ||
448
- (isFunction(thing.toString) && thing.toString() === pattern)
449
- );
450
- }
451
-
452
- /**
453
- * Determine if a value is a URLSearchParams object
454
- * @function
455
- * @param {Object} val The value to test
456
- * @returns {boolean} True if value is a URLSearchParams object, otherwise false
457
- */
458
- var isURLSearchParams = kindOfTest('URLSearchParams');
459
-
460
- /**
461
- * Trim excess whitespace off the beginning and end of a string
462
- *
463
- * @param {String} str The String to trim
464
- * @returns {String} The String freed of excess whitespace
465
- */
466
- function trim(str) {
467
- return str.trim ? str.trim() : str.replace(/^\s+|\s+$/g, '');
468
- }
469
-
470
- /**
471
- * Determine if we're running in a standard browser environment
472
- *
473
- * This allows axios to run in a web worker, and react-native.
474
- * Both environments support XMLHttpRequest, but not fully standard globals.
475
- *
476
- * web workers:
477
- * typeof window -> undefined
478
- * typeof document -> undefined
479
- *
480
- * react-native:
481
- * navigator.product -> 'ReactNative'
482
- * nativescript
483
- * navigator.product -> 'NativeScript' or 'NS'
484
- */
485
- function isStandardBrowserEnv() {
486
- if (typeof navigator !== 'undefined' && (navigator.product === 'ReactNative' ||
487
- navigator.product === 'NativeScript' ||
488
- navigator.product === 'NS')) {
489
- return false;
490
- }
491
- return (
492
- typeof window !== 'undefined' &&
493
- typeof document !== 'undefined'
494
- );
495
- }
496
-
497
- /**
498
- * Iterate over an Array or an Object invoking a function for each item.
499
- *
500
- * If `obj` is an Array callback will be called passing
501
- * the value, index, and complete array for each item.
502
- *
503
- * If 'obj' is an Object callback will be called passing
504
- * the value, key, and complete object for each property.
505
- *
506
- * @param {Object|Array} obj The object to iterate
507
- * @param {Function} fn The callback to invoke for each item
508
- */
509
- function forEach(obj, fn) {
510
- // Don't bother if no value provided
511
- if (obj === null || typeof obj === 'undefined') {
512
- return;
513
- }
514
-
515
- // Force an array if not already something iterable
516
- if (typeof obj !== 'object') {
517
- /*eslint no-param-reassign:0*/
518
- obj = [obj];
519
- }
520
-
521
- if (isArray(obj)) {
522
- // Iterate over array values
523
- for (var i = 0, l = obj.length; i < l; i++) {
524
- fn.call(null, obj[i], i, obj);
525
- }
526
- } else {
527
- // Iterate over object keys
528
- for (var key in obj) {
529
- if (Object.prototype.hasOwnProperty.call(obj, key)) {
530
- fn.call(null, obj[key], key, obj);
531
- }
532
- }
533
- }
534
- }
535
-
536
- /**
537
- * Accepts varargs expecting each argument to be an object, then
538
- * immutably merges the properties of each object and returns result.
539
- *
540
- * When multiple objects contain the same key the later object in
541
- * the arguments list will take precedence.
542
- *
543
- * Example:
544
- *
545
- * ```js
546
- * var result = merge({foo: 123}, {foo: 456});
547
- * console.log(result.foo); // outputs 456
548
- * ```
549
- *
550
- * @param {Object} obj1 Object to merge
551
- * @returns {Object} Result of all merge properties
552
- */
553
- function merge(/* obj1, obj2, obj3, ... */) {
554
- var result = {};
555
- function assignValue(val, key) {
556
- if (isPlainObject(result[key]) && isPlainObject(val)) {
557
- result[key] = merge(result[key], val);
558
- } else if (isPlainObject(val)) {
559
- result[key] = merge({}, val);
560
- } else if (isArray(val)) {
561
- result[key] = val.slice();
562
- } else {
563
- result[key] = val;
564
- }
565
- }
566
-
567
- for (var i = 0, l = arguments.length; i < l; i++) {
568
- forEach(arguments[i], assignValue);
569
- }
570
- return result;
571
- }
572
-
573
- /**
574
- * Extends object a by mutably adding to it the properties of object b.
575
- *
576
- * @param {Object} a The object to be extended
577
- * @param {Object} b The object to copy properties from
578
- * @param {Object} thisArg The object to bind function to
579
- * @return {Object} The resulting value of object a
580
- */
581
- function extend(a, b, thisArg) {
582
- forEach(b, function assignValue(val, key) {
583
- if (thisArg && typeof val === 'function') {
584
- a[key] = bind(val, thisArg);
585
- } else {
586
- a[key] = val;
587
- }
588
- });
589
- return a;
590
- }
591
-
592
- /**
593
- * Remove byte order marker. This catches EF BB BF (the UTF-8 BOM)
594
- *
595
- * @param {string} content with BOM
596
- * @return {string} content value without BOM
597
- */
598
- function stripBOM(content) {
599
- if (content.charCodeAt(0) === 0xFEFF) {
600
- content = content.slice(1);
601
- }
602
- return content;
603
- }
604
-
605
- /**
606
- * Inherit the prototype methods from one constructor into another
607
- * @param {function} constructor
608
- * @param {function} superConstructor
609
- * @param {object} [props]
610
- * @param {object} [descriptors]
611
- */
612
-
613
- function inherits(constructor, superConstructor, props, descriptors) {
614
- constructor.prototype = Object.create(superConstructor.prototype, descriptors);
615
- constructor.prototype.constructor = constructor;
616
- props && Object.assign(constructor.prototype, props);
617
- }
618
-
619
- /**
620
- * Resolve object with deep prototype chain to a flat object
621
- * @param {Object} sourceObj source object
622
- * @param {Object} [destObj]
623
- * @param {Function} [filter]
624
- * @returns {Object}
625
- */
626
-
627
- function toFlatObject(sourceObj, destObj, filter) {
628
- var props;
629
- var i;
630
- var prop;
631
- var merged = {};
632
-
633
- destObj = destObj || {};
634
-
635
- do {
636
- props = Object.getOwnPropertyNames(sourceObj);
637
- i = props.length;
638
- while (i-- > 0) {
639
- prop = props[i];
640
- if (!merged[prop]) {
641
- destObj[prop] = sourceObj[prop];
642
- merged[prop] = true;
643
- }
644
- }
645
- sourceObj = Object.getPrototypeOf(sourceObj);
646
- } while (sourceObj && (!filter || filter(sourceObj, destObj)) && sourceObj !== Object.prototype);
647
-
648
- return destObj;
649
- }
650
-
651
- /*
652
- * determines whether a string ends with the characters of a specified string
653
- * @param {String} str
654
- * @param {String} searchString
655
- * @param {Number} [position= 0]
656
- * @returns {boolean}
657
- */
658
- function endsWith(str, searchString, position) {
659
- str = String(str);
660
- if (position === undefined || position > str.length) {
661
- position = str.length;
662
- }
663
- position -= searchString.length;
664
- var lastIndex = str.indexOf(searchString, position);
665
- return lastIndex !== -1 && lastIndex === position;
666
- }
667
-
668
-
669
- /**
670
- * Returns new array from array like object
671
- * @param {*} [thing]
672
- * @returns {Array}
673
- */
674
- function toArray(thing) {
675
- if (!thing) return null;
676
- var i = thing.length;
677
- if (isUndefined(i)) return null;
678
- var arr = new Array(i);
679
- while (i-- > 0) {
680
- arr[i] = thing[i];
681
- }
682
- return arr;
683
- }
684
-
685
- // eslint-disable-next-line func-names
686
- var isTypedArray = (function(TypedArray) {
687
- // eslint-disable-next-line func-names
688
- return function(thing) {
689
- return TypedArray && thing instanceof TypedArray;
690
- };
691
- })(typeof Uint8Array !== 'undefined' && Object.getPrototypeOf(Uint8Array));
692
-
693
- var utils = {
694
- isArray: isArray,
695
- isArrayBuffer: isArrayBuffer,
696
- isBuffer: isBuffer,
697
- isFormData: isFormData,
698
- isArrayBufferView: isArrayBufferView,
699
- isString: isString,
700
- isNumber: isNumber,
701
- isObject: isObject,
702
- isPlainObject: isPlainObject,
703
- isUndefined: isUndefined,
704
- isDate: isDate,
705
- isFile: isFile,
706
- isBlob: isBlob,
707
- isFunction: isFunction,
708
- isStream: isStream,
709
- isURLSearchParams: isURLSearchParams,
710
- isStandardBrowserEnv: isStandardBrowserEnv,
711
- forEach: forEach,
712
- merge: merge,
713
- extend: extend,
714
- trim: trim,
715
- stripBOM: stripBOM,
716
- inherits: inherits,
717
- toFlatObject: toFlatObject,
718
- kindOf: kindOf,
719
- kindOfTest: kindOfTest,
720
- endsWith: endsWith,
721
- toArray: toArray,
722
- isTypedArray: isTypedArray,
723
- isFileList: isFileList
724
- };
725
-
726
- function encode(val) {
727
- return encodeURIComponent(val).
728
- replace(/%3A/gi, ':').
729
- replace(/%24/g, '$').
730
- replace(/%2C/gi, ',').
731
- replace(/%20/g, '+').
732
- replace(/%5B/gi, '[').
733
- replace(/%5D/gi, ']');
734
- }
735
-
736
- /**
737
- * Build a URL by appending params to the end
738
- *
739
- * @param {string} url The base of the url (e.g., http://www.google.com)
740
- * @param {object} [params] The params to be appended
741
- * @returns {string} The formatted url
742
- */
743
- var buildURL = function buildURL(url, params, paramsSerializer) {
744
- /*eslint no-param-reassign:0*/
745
- if (!params) {
746
- return url;
747
- }
748
-
749
- var serializedParams;
750
- if (paramsSerializer) {
751
- serializedParams = paramsSerializer(params);
752
- } else if (utils.isURLSearchParams(params)) {
753
- serializedParams = params.toString();
754
- } else {
755
- var parts = [];
756
-
757
- utils.forEach(params, function serialize(val, key) {
758
- if (val === null || typeof val === 'undefined') {
759
- return;
760
- }
761
-
762
- if (utils.isArray(val)) {
763
- key = key + '[]';
764
- } else {
765
- val = [val];
766
- }
767
-
768
- utils.forEach(val, function parseValue(v) {
769
- if (utils.isDate(v)) {
770
- v = v.toISOString();
771
- } else if (utils.isObject(v)) {
772
- v = JSON.stringify(v);
773
- }
774
- parts.push(encode(key) + '=' + encode(v));
775
- });
776
- });
777
-
778
- serializedParams = parts.join('&');
779
- }
780
-
781
- if (serializedParams) {
782
- var hashmarkIndex = url.indexOf('#');
783
- if (hashmarkIndex !== -1) {
784
- url = url.slice(0, hashmarkIndex);
785
- }
786
-
787
- url += (url.indexOf('?') === -1 ? '?' : '&') + serializedParams;
788
- }
789
-
790
- return url;
791
- };
792
-
793
- function InterceptorManager() {
794
- this.handlers = [];
795
- }
796
-
797
- /**
798
- * Add a new interceptor to the stack
799
- *
800
- * @param {Function} fulfilled The function to handle `then` for a `Promise`
801
- * @param {Function} rejected The function to handle `reject` for a `Promise`
802
- *
803
- * @return {Number} An ID used to remove interceptor later
804
- */
805
- InterceptorManager.prototype.use = function use(fulfilled, rejected, options) {
806
- this.handlers.push({
807
- fulfilled: fulfilled,
808
- rejected: rejected,
809
- synchronous: options ? options.synchronous : false,
810
- runWhen: options ? options.runWhen : null
811
- });
812
- return this.handlers.length - 1;
813
- };
814
-
815
- /**
816
- * Remove an interceptor from the stack
817
- *
818
- * @param {Number} id The ID that was returned by `use`
819
- */
820
- InterceptorManager.prototype.eject = function eject(id) {
821
- if (this.handlers[id]) {
822
- this.handlers[id] = null;
823
- }
824
- };
825
-
826
- /**
827
- * Iterate over all the registered interceptors
828
- *
829
- * This method is particularly useful for skipping over any
830
- * interceptors that may have become `null` calling `eject`.
831
- *
832
- * @param {Function} fn The function to call for each interceptor
833
- */
834
- InterceptorManager.prototype.forEach = function forEach(fn) {
835
- utils.forEach(this.handlers, function forEachHandler(h) {
836
- if (h !== null) {
837
- fn(h);
838
- }
839
- });
840
- };
841
-
842
- var InterceptorManager_1 = InterceptorManager;
843
-
844
- var normalizeHeaderName = function normalizeHeaderName(headers, normalizedName) {
845
- utils.forEach(headers, function processHeader(value, name) {
846
- if (name !== normalizedName && name.toUpperCase() === normalizedName.toUpperCase()) {
847
- headers[normalizedName] = value;
848
- delete headers[name];
849
- }
850
- });
851
- };
852
-
853
- /**
854
- * Create an Error with the specified message, config, error code, request and response.
855
- *
856
- * @param {string} message The error message.
857
- * @param {string} [code] The error code (for example, 'ECONNABORTED').
858
- * @param {Object} [config] The config.
859
- * @param {Object} [request] The request.
860
- * @param {Object} [response] The response.
861
- * @returns {Error} The created error.
862
- */
863
- function AxiosError(message, code, config, request, response) {
864
- Error.call(this);
865
- this.message = message;
866
- this.name = 'AxiosError';
867
- code && (this.code = code);
868
- config && (this.config = config);
869
- request && (this.request = request);
870
- response && (this.response = response);
871
- }
872
-
873
- utils.inherits(AxiosError, Error, {
874
- toJSON: function toJSON() {
875
- return {
876
- // Standard
877
- message: this.message,
878
- name: this.name,
879
- // Microsoft
880
- description: this.description,
881
- number: this.number,
882
- // Mozilla
883
- fileName: this.fileName,
884
- lineNumber: this.lineNumber,
885
- columnNumber: this.columnNumber,
886
- stack: this.stack,
887
- // Axios
888
- config: this.config,
889
- code: this.code,
890
- status: this.response && this.response.status ? this.response.status : null
891
- };
892
- }
893
- });
894
-
895
- var prototype = AxiosError.prototype;
896
- var descriptors = {};
897
-
898
- [
899
- 'ERR_BAD_OPTION_VALUE',
900
- 'ERR_BAD_OPTION',
901
- 'ECONNABORTED',
902
- 'ETIMEDOUT',
903
- 'ERR_NETWORK',
904
- 'ERR_FR_TOO_MANY_REDIRECTS',
905
- 'ERR_DEPRECATED',
906
- 'ERR_BAD_RESPONSE',
907
- 'ERR_BAD_REQUEST',
908
- 'ERR_CANCELED'
909
- // eslint-disable-next-line func-names
910
- ].forEach(function(code) {
911
- descriptors[code] = {value: code};
912
- });
913
-
914
- Object.defineProperties(AxiosError, descriptors);
915
- Object.defineProperty(prototype, 'isAxiosError', {value: true});
916
-
917
- // eslint-disable-next-line func-names
918
- AxiosError.from = function(error, code, config, request, response, customProps) {
919
- var axiosError = Object.create(prototype);
920
-
921
- utils.toFlatObject(error, axiosError, function filter(obj) {
922
- return obj !== Error.prototype;
923
- });
924
-
925
- AxiosError.call(axiosError, error.message, code, config, request, response);
926
-
927
- axiosError.name = error.name;
928
-
929
- customProps && Object.assign(axiosError, customProps);
930
-
931
- return axiosError;
932
- };
933
-
934
- var AxiosError_1 = AxiosError;
935
-
936
- var transitional = {
937
- silentJSONParsing: true,
938
- forcedJSONParsing: true,
939
- clarifyTimeoutError: false
940
- };
941
-
942
- /**
943
- * Convert a data object to FormData
944
- * @param {Object} obj
945
- * @param {?Object} [formData]
946
- * @returns {Object}
947
- **/
948
-
949
- function toFormData(obj, formData) {
950
- // eslint-disable-next-line no-param-reassign
951
- formData = formData || new FormData();
952
-
953
- var stack = [];
954
-
955
- function convertValue(value) {
956
- if (value === null) return '';
957
-
958
- if (utils.isDate(value)) {
959
- return value.toISOString();
960
- }
961
-
962
- if (utils.isArrayBuffer(value) || utils.isTypedArray(value)) {
963
- return typeof Blob === 'function' ? new Blob([value]) : Buffer.from(value);
964
- }
965
-
966
- return value;
967
- }
968
-
969
- function build(data, parentKey) {
970
- if (utils.isPlainObject(data) || utils.isArray(data)) {
971
- if (stack.indexOf(data) !== -1) {
972
- throw Error('Circular reference detected in ' + parentKey);
973
- }
974
-
975
- stack.push(data);
976
-
977
- utils.forEach(data, function each(value, key) {
978
- if (utils.isUndefined(value)) return;
979
- var fullKey = parentKey ? parentKey + '.' + key : key;
980
- var arr;
981
-
982
- if (value && !parentKey && typeof value === 'object') {
983
- if (utils.endsWith(key, '{}')) {
984
- // eslint-disable-next-line no-param-reassign
985
- value = JSON.stringify(value);
986
- } else if (utils.endsWith(key, '[]') && (arr = utils.toArray(value))) {
987
- // eslint-disable-next-line func-names
988
- arr.forEach(function(el) {
989
- !utils.isUndefined(el) && formData.append(fullKey, convertValue(el));
990
- });
991
- return;
992
- }
993
- }
994
-
995
- build(value, fullKey);
996
- });
997
-
998
- stack.pop();
999
- } else {
1000
- formData.append(parentKey, convertValue(data));
1001
- }
1002
- }
1003
-
1004
- build(obj);
1005
-
1006
- return formData;
1007
- }
1008
-
1009
- var toFormData_1 = toFormData;
1010
-
1011
- /**
1012
- * Resolve or reject a Promise based on response status.
1013
- *
1014
- * @param {Function} resolve A function that resolves the promise.
1015
- * @param {Function} reject A function that rejects the promise.
1016
- * @param {object} response The response.
1017
- */
1018
- var settle = function settle(resolve, reject, response) {
1019
- var validateStatus = response.config.validateStatus;
1020
- if (!response.status || !validateStatus || validateStatus(response.status)) {
1021
- resolve(response);
1022
- } else {
1023
- reject(new AxiosError_1(
1024
- 'Request failed with status code ' + response.status,
1025
- [AxiosError_1.ERR_BAD_REQUEST, AxiosError_1.ERR_BAD_RESPONSE][Math.floor(response.status / 100) - 4],
1026
- response.config,
1027
- response.request,
1028
- response
1029
- ));
1030
- }
1031
- };
1032
-
1033
- var cookies = (
1034
- utils.isStandardBrowserEnv() ?
1035
-
1036
- // Standard browser envs support document.cookie
1037
- (function standardBrowserEnv() {
1038
- return {
1039
- write: function write(name, value, expires, path, domain, secure) {
1040
- var cookie = [];
1041
- cookie.push(name + '=' + encodeURIComponent(value));
1042
-
1043
- if (utils.isNumber(expires)) {
1044
- cookie.push('expires=' + new Date(expires).toGMTString());
1045
- }
1046
-
1047
- if (utils.isString(path)) {
1048
- cookie.push('path=' + path);
1049
- }
1050
-
1051
- if (utils.isString(domain)) {
1052
- cookie.push('domain=' + domain);
1053
- }
1054
-
1055
- if (secure === true) {
1056
- cookie.push('secure');
1057
- }
1058
-
1059
- document.cookie = cookie.join('; ');
1060
- },
1061
-
1062
- read: function read(name) {
1063
- var match = document.cookie.match(new RegExp('(^|;\\s*)(' + name + ')=([^;]*)'));
1064
- return (match ? decodeURIComponent(match[3]) : null);
1065
- },
1066
-
1067
- remove: function remove(name) {
1068
- this.write(name, '', Date.now() - 86400000);
1069
- }
1070
- };
1071
- })() :
1072
-
1073
- // Non standard browser env (web workers, react-native) lack needed support.
1074
- (function nonStandardBrowserEnv() {
1075
- return {
1076
- write: function write() {},
1077
- read: function read() { return null; },
1078
- remove: function remove() {}
1079
- };
1080
- })()
1081
- );
1082
-
1083
- /**
1084
- * Determines whether the specified URL is absolute
1085
- *
1086
- * @param {string} url The URL to test
1087
- * @returns {boolean} True if the specified URL is absolute, otherwise false
1088
- */
1089
- var isAbsoluteURL = function isAbsoluteURL(url) {
1090
- // A URL is considered absolute if it begins with "<scheme>://" or "//" (protocol-relative URL).
1091
- // RFC 3986 defines scheme name as a sequence of characters beginning with a letter and followed
1092
- // by any combination of letters, digits, plus, period, or hyphen.
1093
- return /^([a-z][a-z\d+\-.]*:)?\/\//i.test(url);
1094
- };
1095
-
1096
- /**
1097
- * Creates a new URL by combining the specified URLs
1098
- *
1099
- * @param {string} baseURL The base URL
1100
- * @param {string} relativeURL The relative URL
1101
- * @returns {string} The combined URL
1102
- */
1103
- var combineURLs = function combineURLs(baseURL, relativeURL) {
1104
- return relativeURL
1105
- ? baseURL.replace(/\/+$/, '') + '/' + relativeURL.replace(/^\/+/, '')
1106
- : baseURL;
1107
- };
1108
-
1109
- /**
1110
- * Creates a new URL by combining the baseURL with the requestedURL,
1111
- * only when the requestedURL is not already an absolute URL.
1112
- * If the requestURL is absolute, this function returns the requestedURL untouched.
1113
- *
1114
- * @param {string} baseURL The base URL
1115
- * @param {string} requestedURL Absolute or relative URL to combine
1116
- * @returns {string} The combined full path
1117
- */
1118
- var buildFullPath = function buildFullPath(baseURL, requestedURL) {
1119
- if (baseURL && !isAbsoluteURL(requestedURL)) {
1120
- return combineURLs(baseURL, requestedURL);
1121
- }
1122
- return requestedURL;
1123
- };
1124
-
1125
- // Headers whose duplicates are ignored by node
1126
- // c.f. https://nodejs.org/api/http.html#http_message_headers
1127
- var ignoreDuplicateOf = [
1128
- 'age', 'authorization', 'content-length', 'content-type', 'etag',
1129
- 'expires', 'from', 'host', 'if-modified-since', 'if-unmodified-since',
1130
- 'last-modified', 'location', 'max-forwards', 'proxy-authorization',
1131
- 'referer', 'retry-after', 'user-agent'
1132
- ];
1133
-
1134
- /**
1135
- * Parse headers into an object
1136
- *
1137
- * ```
1138
- * Date: Wed, 27 Aug 2014 08:58:49 GMT
1139
- * Content-Type: application/json
1140
- * Connection: keep-alive
1141
- * Transfer-Encoding: chunked
1142
- * ```
1143
- *
1144
- * @param {String} headers Headers needing to be parsed
1145
- * @returns {Object} Headers parsed into an object
1146
- */
1147
- var parseHeaders = function parseHeaders(headers) {
1148
- var parsed = {};
1149
- var key;
1150
- var val;
1151
- var i;
1152
-
1153
- if (!headers) { return parsed; }
1154
-
1155
- utils.forEach(headers.split('\n'), function parser(line) {
1156
- i = line.indexOf(':');
1157
- key = utils.trim(line.substr(0, i)).toLowerCase();
1158
- val = utils.trim(line.substr(i + 1));
1159
-
1160
- if (key) {
1161
- if (parsed[key] && ignoreDuplicateOf.indexOf(key) >= 0) {
1162
- return;
1163
- }
1164
- if (key === 'set-cookie') {
1165
- parsed[key] = (parsed[key] ? parsed[key] : []).concat([val]);
1166
- } else {
1167
- parsed[key] = parsed[key] ? parsed[key] + ', ' + val : val;
1168
- }
1169
- }
1170
- });
1171
-
1172
- return parsed;
1173
- };
1174
-
1175
- var isURLSameOrigin = (
1176
- utils.isStandardBrowserEnv() ?
1177
-
1178
- // Standard browser envs have full support of the APIs needed to test
1179
- // whether the request URL is of the same origin as current location.
1180
- (function standardBrowserEnv() {
1181
- var msie = /(msie|trident)/i.test(navigator.userAgent);
1182
- var urlParsingNode = document.createElement('a');
1183
- var originURL;
1184
-
1185
- /**
1186
- * Parse a URL to discover it's components
1187
- *
1188
- * @param {String} url The URL to be parsed
1189
- * @returns {Object}
1190
- */
1191
- function resolveURL(url) {
1192
- var href = url;
1193
-
1194
- if (msie) {
1195
- // IE needs attribute set twice to normalize properties
1196
- urlParsingNode.setAttribute('href', href);
1197
- href = urlParsingNode.href;
1198
- }
1199
-
1200
- urlParsingNode.setAttribute('href', href);
1201
-
1202
- // urlParsingNode provides the UrlUtils interface - http://url.spec.whatwg.org/#urlutils
1203
- return {
1204
- href: urlParsingNode.href,
1205
- protocol: urlParsingNode.protocol ? urlParsingNode.protocol.replace(/:$/, '') : '',
1206
- host: urlParsingNode.host,
1207
- search: urlParsingNode.search ? urlParsingNode.search.replace(/^\?/, '') : '',
1208
- hash: urlParsingNode.hash ? urlParsingNode.hash.replace(/^#/, '') : '',
1209
- hostname: urlParsingNode.hostname,
1210
- port: urlParsingNode.port,
1211
- pathname: (urlParsingNode.pathname.charAt(0) === '/') ?
1212
- urlParsingNode.pathname :
1213
- '/' + urlParsingNode.pathname
1214
- };
1215
- }
1216
-
1217
- originURL = resolveURL(window.location.href);
1218
-
1219
- /**
1220
- * Determine if a URL shares the same origin as the current location
1221
- *
1222
- * @param {String} requestURL The URL to test
1223
- * @returns {boolean} True if URL shares the same origin, otherwise false
1224
- */
1225
- return function isURLSameOrigin(requestURL) {
1226
- var parsed = (utils.isString(requestURL)) ? resolveURL(requestURL) : requestURL;
1227
- return (parsed.protocol === originURL.protocol &&
1228
- parsed.host === originURL.host);
1229
- };
1230
- })() :
1231
-
1232
- // Non standard browser envs (web workers, react-native) lack needed support.
1233
- (function nonStandardBrowserEnv() {
1234
- return function isURLSameOrigin() {
1235
- return true;
1236
- };
1237
- })()
1238
- );
1239
-
1240
- /**
1241
- * A `CanceledError` is an object that is thrown when an operation is canceled.
1242
- *
1243
- * @class
1244
- * @param {string=} message The message.
1245
- */
1246
- function CanceledError(message) {
1247
- // eslint-disable-next-line no-eq-null,eqeqeq
1248
- AxiosError_1.call(this, message == null ? 'canceled' : message, AxiosError_1.ERR_CANCELED);
1249
- this.name = 'CanceledError';
1250
- }
1251
-
1252
- utils.inherits(CanceledError, AxiosError_1, {
1253
- __CANCEL__: true
1254
- });
1255
-
1256
- var CanceledError_1 = CanceledError;
1257
-
1258
- var parseProtocol = function parseProtocol(url) {
1259
- var match = /^([-+\w]{1,25})(:?\/\/|:)/.exec(url);
1260
- return match && match[1] || '';
1261
- };
1262
-
1263
- var xhr = function xhrAdapter(config) {
1264
- return new Promise(function dispatchXhrRequest(resolve, reject) {
1265
- var requestData = config.data;
1266
- var requestHeaders = config.headers;
1267
- var responseType = config.responseType;
1268
- var onCanceled;
1269
- function done() {
1270
- if (config.cancelToken) {
1271
- config.cancelToken.unsubscribe(onCanceled);
1272
- }
1273
-
1274
- if (config.signal) {
1275
- config.signal.removeEventListener('abort', onCanceled);
1276
- }
1277
- }
1278
-
1279
- if (utils.isFormData(requestData) && utils.isStandardBrowserEnv()) {
1280
- delete requestHeaders['Content-Type']; // Let the browser set it
1281
- }
1282
-
1283
- var request = new XMLHttpRequest();
1284
-
1285
- // HTTP basic authentication
1286
- if (config.auth) {
1287
- var username = config.auth.username || '';
1288
- var password = config.auth.password ? unescape(encodeURIComponent(config.auth.password)) : '';
1289
- requestHeaders.Authorization = 'Basic ' + btoa(username + ':' + password);
1290
- }
1291
-
1292
- var fullPath = buildFullPath(config.baseURL, config.url);
1293
-
1294
- request.open(config.method.toUpperCase(), buildURL(fullPath, config.params, config.paramsSerializer), true);
1295
-
1296
- // Set the request timeout in MS
1297
- request.timeout = config.timeout;
1298
-
1299
- function onloadend() {
1300
- if (!request) {
1301
- return;
1302
- }
1303
- // Prepare the response
1304
- var responseHeaders = 'getAllResponseHeaders' in request ? parseHeaders(request.getAllResponseHeaders()) : null;
1305
- var responseData = !responseType || responseType === 'text' || responseType === 'json' ?
1306
- request.responseText : request.response;
1307
- var response = {
1308
- data: responseData,
1309
- status: request.status,
1310
- statusText: request.statusText,
1311
- headers: responseHeaders,
1312
- config: config,
1313
- request: request
1314
- };
1315
-
1316
- settle(function _resolve(value) {
1317
- resolve(value);
1318
- done();
1319
- }, function _reject(err) {
1320
- reject(err);
1321
- done();
1322
- }, response);
1323
-
1324
- // Clean up request
1325
- request = null;
1326
- }
1327
-
1328
- if ('onloadend' in request) {
1329
- // Use onloadend if available
1330
- request.onloadend = onloadend;
1331
- } else {
1332
- // Listen for ready state to emulate onloadend
1333
- request.onreadystatechange = function handleLoad() {
1334
- if (!request || request.readyState !== 4) {
1335
- return;
1336
- }
1337
-
1338
- // The request errored out and we didn't get a response, this will be
1339
- // handled by onerror instead
1340
- // With one exception: request that using file: protocol, most browsers
1341
- // will return status as 0 even though it's a successful request
1342
- if (request.status === 0 && !(request.responseURL && request.responseURL.indexOf('file:') === 0)) {
1343
- return;
1344
- }
1345
- // readystate handler is calling before onerror or ontimeout handlers,
1346
- // so we should call onloadend on the next 'tick'
1347
- setTimeout(onloadend);
1348
- };
1349
- }
1350
-
1351
- // Handle browser request cancellation (as opposed to a manual cancellation)
1352
- request.onabort = function handleAbort() {
1353
- if (!request) {
1354
- return;
1355
- }
1356
-
1357
- reject(new AxiosError_1('Request aborted', AxiosError_1.ECONNABORTED, config, request));
1358
-
1359
- // Clean up request
1360
- request = null;
1361
- };
1362
-
1363
- // Handle low level network errors
1364
- request.onerror = function handleError() {
1365
- // Real errors are hidden from us by the browser
1366
- // onerror should only fire if it's a network error
1367
- reject(new AxiosError_1('Network Error', AxiosError_1.ERR_NETWORK, config, request, request));
1368
-
1369
- // Clean up request
1370
- request = null;
1371
- };
1372
-
1373
- // Handle timeout
1374
- request.ontimeout = function handleTimeout() {
1375
- var timeoutErrorMessage = config.timeout ? 'timeout of ' + config.timeout + 'ms exceeded' : 'timeout exceeded';
1376
- var transitional$1 = config.transitional || transitional;
1377
- if (config.timeoutErrorMessage) {
1378
- timeoutErrorMessage = config.timeoutErrorMessage;
1379
- }
1380
- reject(new AxiosError_1(
1381
- timeoutErrorMessage,
1382
- transitional$1.clarifyTimeoutError ? AxiosError_1.ETIMEDOUT : AxiosError_1.ECONNABORTED,
1383
- config,
1384
- request));
1385
-
1386
- // Clean up request
1387
- request = null;
1388
- };
1389
-
1390
- // Add xsrf header
1391
- // This is only done if running in a standard browser environment.
1392
- // Specifically not if we're in a web worker, or react-native.
1393
- if (utils.isStandardBrowserEnv()) {
1394
- // Add xsrf header
1395
- var xsrfValue = (config.withCredentials || isURLSameOrigin(fullPath)) && config.xsrfCookieName ?
1396
- cookies.read(config.xsrfCookieName) :
1397
- undefined;
1398
-
1399
- if (xsrfValue) {
1400
- requestHeaders[config.xsrfHeaderName] = xsrfValue;
1401
- }
1402
- }
1403
-
1404
- // Add headers to the request
1405
- if ('setRequestHeader' in request) {
1406
- utils.forEach(requestHeaders, function setRequestHeader(val, key) {
1407
- if (typeof requestData === 'undefined' && key.toLowerCase() === 'content-type') {
1408
- // Remove Content-Type if data is undefined
1409
- delete requestHeaders[key];
1410
- } else {
1411
- // Otherwise add header to the request
1412
- request.setRequestHeader(key, val);
1413
- }
1414
- });
1415
- }
1416
-
1417
- // Add withCredentials to request if needed
1418
- if (!utils.isUndefined(config.withCredentials)) {
1419
- request.withCredentials = !!config.withCredentials;
1420
- }
1421
-
1422
- // Add responseType to request if needed
1423
- if (responseType && responseType !== 'json') {
1424
- request.responseType = config.responseType;
1425
- }
1426
-
1427
- // Handle progress if needed
1428
- if (typeof config.onDownloadProgress === 'function') {
1429
- request.addEventListener('progress', config.onDownloadProgress);
1430
- }
1431
-
1432
- // Not all browsers support upload events
1433
- if (typeof config.onUploadProgress === 'function' && request.upload) {
1434
- request.upload.addEventListener('progress', config.onUploadProgress);
1435
- }
1436
-
1437
- if (config.cancelToken || config.signal) {
1438
- // Handle cancellation
1439
- // eslint-disable-next-line func-names
1440
- onCanceled = function(cancel) {
1441
- if (!request) {
1442
- return;
1443
- }
1444
- reject(!cancel || (cancel && cancel.type) ? new CanceledError_1() : cancel);
1445
- request.abort();
1446
- request = null;
1447
- };
1448
-
1449
- config.cancelToken && config.cancelToken.subscribe(onCanceled);
1450
- if (config.signal) {
1451
- config.signal.aborted ? onCanceled() : config.signal.addEventListener('abort', onCanceled);
1452
- }
1453
- }
1454
-
1455
- if (!requestData) {
1456
- requestData = null;
1457
- }
1458
-
1459
- var protocol = parseProtocol(fullPath);
1460
-
1461
- if (protocol && [ 'http', 'https', 'file' ].indexOf(protocol) === -1) {
1462
- reject(new AxiosError_1('Unsupported protocol ' + protocol + ':', AxiosError_1.ERR_BAD_REQUEST, config));
1463
- return;
1464
- }
1465
-
1466
-
1467
- // Send the request
1468
- request.send(requestData);
1469
- });
1470
- };
1471
-
1472
- // eslint-disable-next-line strict
1473
- var _null = null;
1474
-
1475
- var DEFAULT_CONTENT_TYPE = {
1476
- 'Content-Type': 'application/x-www-form-urlencoded'
1477
- };
1478
-
1479
- function setContentTypeIfUnset(headers, value) {
1480
- if (!utils.isUndefined(headers) && utils.isUndefined(headers['Content-Type'])) {
1481
- headers['Content-Type'] = value;
1482
- }
1483
- }
1484
-
1485
- function getDefaultAdapter() {
1486
- var adapter;
1487
- if (typeof XMLHttpRequest !== 'undefined') {
1488
- // For browsers use XHR adapter
1489
- adapter = xhr;
1490
- } else if (typeof process !== 'undefined' && Object.prototype.toString.call(process) === '[object process]') {
1491
- // For node use HTTP adapter
1492
- adapter = xhr;
1493
- }
1494
- return adapter;
1495
- }
1496
-
1497
- function stringifySafely(rawValue, parser, encoder) {
1498
- if (utils.isString(rawValue)) {
1499
- try {
1500
- (parser || JSON.parse)(rawValue);
1501
- return utils.trim(rawValue);
1502
- } catch (e) {
1503
- if (e.name !== 'SyntaxError') {
1504
- throw e;
1505
- }
1506
- }
1507
- }
1508
-
1509
- return (encoder || JSON.stringify)(rawValue);
1510
- }
1511
-
1512
- var defaults = {
1513
-
1514
- transitional: transitional,
1515
-
1516
- adapter: getDefaultAdapter(),
1517
-
1518
- transformRequest: [function transformRequest(data, headers) {
1519
- normalizeHeaderName(headers, 'Accept');
1520
- normalizeHeaderName(headers, 'Content-Type');
1521
-
1522
- if (utils.isFormData(data) ||
1523
- utils.isArrayBuffer(data) ||
1524
- utils.isBuffer(data) ||
1525
- utils.isStream(data) ||
1526
- utils.isFile(data) ||
1527
- utils.isBlob(data)
1528
- ) {
1529
- return data;
1530
- }
1531
- if (utils.isArrayBufferView(data)) {
1532
- return data.buffer;
1533
- }
1534
- if (utils.isURLSearchParams(data)) {
1535
- setContentTypeIfUnset(headers, 'application/x-www-form-urlencoded;charset=utf-8');
1536
- return data.toString();
1537
- }
1538
-
1539
- var isObjectPayload = utils.isObject(data);
1540
- var contentType = headers && headers['Content-Type'];
1541
-
1542
- var isFileList;
1543
-
1544
- if ((isFileList = utils.isFileList(data)) || (isObjectPayload && contentType === 'multipart/form-data')) {
1545
- var _FormData = this.env && this.env.FormData;
1546
- return toFormData_1(isFileList ? {'files[]': data} : data, _FormData && new _FormData());
1547
- } else if (isObjectPayload || contentType === 'application/json') {
1548
- setContentTypeIfUnset(headers, 'application/json');
1549
- return stringifySafely(data);
1550
- }
1551
-
1552
- return data;
1553
- }],
1554
-
1555
- transformResponse: [function transformResponse(data) {
1556
- var transitional = this.transitional || defaults.transitional;
1557
- var silentJSONParsing = transitional && transitional.silentJSONParsing;
1558
- var forcedJSONParsing = transitional && transitional.forcedJSONParsing;
1559
- var strictJSONParsing = !silentJSONParsing && this.responseType === 'json';
1560
-
1561
- if (strictJSONParsing || (forcedJSONParsing && utils.isString(data) && data.length)) {
1562
- try {
1563
- return JSON.parse(data);
1564
- } catch (e) {
1565
- if (strictJSONParsing) {
1566
- if (e.name === 'SyntaxError') {
1567
- throw AxiosError_1.from(e, AxiosError_1.ERR_BAD_RESPONSE, this, null, this.response);
1568
- }
1569
- throw e;
1570
- }
1571
- }
1572
- }
1573
-
1574
- return data;
1575
- }],
1576
-
1577
- /**
1578
- * A timeout in milliseconds to abort a request. If set to 0 (default) a
1579
- * timeout is not created.
1580
- */
1581
- timeout: 0,
1582
-
1583
- xsrfCookieName: 'XSRF-TOKEN',
1584
- xsrfHeaderName: 'X-XSRF-TOKEN',
1585
-
1586
- maxContentLength: -1,
1587
- maxBodyLength: -1,
1588
-
1589
- env: {
1590
- FormData: _null
1591
- },
1592
-
1593
- validateStatus: function validateStatus(status) {
1594
- return status >= 200 && status < 300;
1595
- },
1596
-
1597
- headers: {
1598
- common: {
1599
- 'Accept': 'application/json, text/plain, */*'
1600
- }
1601
- }
1602
- };
1603
-
1604
- utils.forEach(['delete', 'get', 'head'], function forEachMethodNoData(method) {
1605
- defaults.headers[method] = {};
1606
- });
1607
-
1608
- utils.forEach(['post', 'put', 'patch'], function forEachMethodWithData(method) {
1609
- defaults.headers[method] = utils.merge(DEFAULT_CONTENT_TYPE);
1610
- });
1611
-
1612
- var defaults_1 = defaults;
1613
-
1614
- /**
1615
- * Transform the data for a request or a response
1616
- *
1617
- * @param {Object|String} data The data to be transformed
1618
- * @param {Array} headers The headers for the request or response
1619
- * @param {Array|Function} fns A single function or Array of functions
1620
- * @returns {*} The resulting transformed data
1621
- */
1622
- var transformData = function transformData(data, headers, fns) {
1623
- var context = this || defaults_1;
1624
- /*eslint no-param-reassign:0*/
1625
- utils.forEach(fns, function transform(fn) {
1626
- data = fn.call(context, data, headers);
1627
- });
1628
-
1629
- return data;
1630
- };
1631
-
1632
- var isCancel = function isCancel(value) {
1633
- return !!(value && value.__CANCEL__);
1634
- };
1635
-
1636
- /**
1637
- * Throws a `CanceledError` if cancellation has been requested.
1638
- */
1639
- function throwIfCancellationRequested(config) {
1640
- if (config.cancelToken) {
1641
- config.cancelToken.throwIfRequested();
1642
- }
1643
-
1644
- if (config.signal && config.signal.aborted) {
1645
- throw new CanceledError_1();
1646
- }
1647
- }
1648
-
1649
- /**
1650
- * Dispatch a request to the server using the configured adapter.
1651
- *
1652
- * @param {object} config The config that is to be used for the request
1653
- * @returns {Promise} The Promise to be fulfilled
1654
- */
1655
- var dispatchRequest = function dispatchRequest(config) {
1656
- throwIfCancellationRequested(config);
1657
-
1658
- // Ensure headers exist
1659
- config.headers = config.headers || {};
1660
-
1661
- // Transform request data
1662
- config.data = transformData.call(
1663
- config,
1664
- config.data,
1665
- config.headers,
1666
- config.transformRequest
1667
- );
1668
-
1669
- // Flatten headers
1670
- config.headers = utils.merge(
1671
- config.headers.common || {},
1672
- config.headers[config.method] || {},
1673
- config.headers
1674
- );
1675
-
1676
- utils.forEach(
1677
- ['delete', 'get', 'head', 'post', 'put', 'patch', 'common'],
1678
- function cleanHeaderConfig(method) {
1679
- delete config.headers[method];
1680
- }
1681
- );
1682
-
1683
- var adapter = config.adapter || defaults_1.adapter;
1684
-
1685
- return adapter(config).then(function onAdapterResolution(response) {
1686
- throwIfCancellationRequested(config);
1687
-
1688
- // Transform response data
1689
- response.data = transformData.call(
1690
- config,
1691
- response.data,
1692
- response.headers,
1693
- config.transformResponse
1694
- );
1695
-
1696
- return response;
1697
- }, function onAdapterRejection(reason) {
1698
- if (!isCancel(reason)) {
1699
- throwIfCancellationRequested(config);
1700
-
1701
- // Transform response data
1702
- if (reason && reason.response) {
1703
- reason.response.data = transformData.call(
1704
- config,
1705
- reason.response.data,
1706
- reason.response.headers,
1707
- config.transformResponse
1708
- );
1709
- }
1710
- }
1711
-
1712
- return Promise.reject(reason);
1713
- });
1714
- };
1715
-
1716
- /**
1717
- * Config-specific merge-function which creates a new config-object
1718
- * by merging two configuration objects together.
1719
- *
1720
- * @param {Object} config1
1721
- * @param {Object} config2
1722
- * @returns {Object} New object resulting from merging config2 to config1
1723
- */
1724
- var mergeConfig = function mergeConfig(config1, config2) {
1725
- // eslint-disable-next-line no-param-reassign
1726
- config2 = config2 || {};
1727
- var config = {};
1728
-
1729
- function getMergedValue(target, source) {
1730
- if (utils.isPlainObject(target) && utils.isPlainObject(source)) {
1731
- return utils.merge(target, source);
1732
- } else if (utils.isPlainObject(source)) {
1733
- return utils.merge({}, source);
1734
- } else if (utils.isArray(source)) {
1735
- return source.slice();
1736
- }
1737
- return source;
1738
- }
1739
-
1740
- // eslint-disable-next-line consistent-return
1741
- function mergeDeepProperties(prop) {
1742
- if (!utils.isUndefined(config2[prop])) {
1743
- return getMergedValue(config1[prop], config2[prop]);
1744
- } else if (!utils.isUndefined(config1[prop])) {
1745
- return getMergedValue(undefined, config1[prop]);
249
+ // eslint-lint-disable-next-line @typescript-eslint/naming-convention
250
+ class HTTPError extends Error {
251
+ constructor(response, request, options) {
252
+ const code = (response.status || response.status === 0) ? response.status : '';
253
+ const title = response.statusText || '';
254
+ const status = `${code} ${title}`.trim();
255
+ const reason = status ? `status code ${status}` : 'an unknown error';
256
+ super(`Request failed with ${reason}`);
257
+ Object.defineProperty(this, "response", {
258
+ enumerable: true,
259
+ configurable: true,
260
+ writable: true,
261
+ value: void 0
262
+ });
263
+ Object.defineProperty(this, "request", {
264
+ enumerable: true,
265
+ configurable: true,
266
+ writable: true,
267
+ value: void 0
268
+ });
269
+ Object.defineProperty(this, "options", {
270
+ enumerable: true,
271
+ configurable: true,
272
+ writable: true,
273
+ value: void 0
274
+ });
275
+ this.name = 'HTTPError';
276
+ this.response = response;
277
+ this.request = request;
278
+ this.options = options;
1746
279
  }
1747
- }
280
+ }
1748
281
 
1749
- // eslint-disable-next-line consistent-return
1750
- function valueFromConfig2(prop) {
1751
- if (!utils.isUndefined(config2[prop])) {
1752
- return getMergedValue(undefined, config2[prop]);
282
+ class TimeoutError extends Error {
283
+ constructor(request) {
284
+ super('Request timed out');
285
+ Object.defineProperty(this, "request", {
286
+ enumerable: true,
287
+ configurable: true,
288
+ writable: true,
289
+ value: void 0
290
+ });
291
+ this.name = 'TimeoutError';
292
+ this.request = request;
1753
293
  }
1754
- }
294
+ }
1755
295
 
1756
- // eslint-disable-next-line consistent-return
1757
- function defaultToConfig2(prop) {
1758
- if (!utils.isUndefined(config2[prop])) {
1759
- return getMergedValue(undefined, config2[prop]);
1760
- } else if (!utils.isUndefined(config1[prop])) {
1761
- return getMergedValue(undefined, config1[prop]);
1762
- }
1763
- }
296
+ // eslint-disable-next-line @typescript-eslint/ban-types
297
+ const isObject = (value) => value !== null && typeof value === 'object';
1764
298
 
1765
- // eslint-disable-next-line consistent-return
1766
- function mergeDirectKeys(prop) {
1767
- if (prop in config2) {
1768
- return getMergedValue(config1[prop], config2[prop]);
1769
- } else if (prop in config1) {
1770
- return getMergedValue(undefined, config1[prop]);
299
+ const validateAndMerge = (...sources) => {
300
+ for (const source of sources) {
301
+ if ((!isObject(source) || Array.isArray(source)) && typeof source !== 'undefined') {
302
+ throw new TypeError('The `options` argument must be an object');
303
+ }
1771
304
  }
1772
- }
1773
-
1774
- var mergeMap = {
1775
- 'url': valueFromConfig2,
1776
- 'method': valueFromConfig2,
1777
- 'data': valueFromConfig2,
1778
- 'baseURL': defaultToConfig2,
1779
- 'transformRequest': defaultToConfig2,
1780
- 'transformResponse': defaultToConfig2,
1781
- 'paramsSerializer': defaultToConfig2,
1782
- 'timeout': defaultToConfig2,
1783
- 'timeoutMessage': defaultToConfig2,
1784
- 'withCredentials': defaultToConfig2,
1785
- 'adapter': defaultToConfig2,
1786
- 'responseType': defaultToConfig2,
1787
- 'xsrfCookieName': defaultToConfig2,
1788
- 'xsrfHeaderName': defaultToConfig2,
1789
- 'onUploadProgress': defaultToConfig2,
1790
- 'onDownloadProgress': defaultToConfig2,
1791
- 'decompress': defaultToConfig2,
1792
- 'maxContentLength': defaultToConfig2,
1793
- 'maxBodyLength': defaultToConfig2,
1794
- 'beforeRedirect': defaultToConfig2,
1795
- 'transport': defaultToConfig2,
1796
- 'httpAgent': defaultToConfig2,
1797
- 'httpsAgent': defaultToConfig2,
1798
- 'cancelToken': defaultToConfig2,
1799
- 'socketPath': defaultToConfig2,
1800
- 'responseEncoding': defaultToConfig2,
1801
- 'validateStatus': mergeDirectKeys
1802
- };
1803
-
1804
- utils.forEach(Object.keys(config1).concat(Object.keys(config2)), function computeConfigValue(prop) {
1805
- var merge = mergeMap[prop] || mergeDeepProperties;
1806
- var configValue = merge(prop);
1807
- (utils.isUndefined(configValue) && merge !== mergeDirectKeys) || (config[prop] = configValue);
1808
- });
1809
-
1810
- return config;
305
+ return deepMerge({}, ...sources);
1811
306
  };
1812
-
1813
- var data = {
1814
- "version": "0.27.2"
1815
- };
1816
-
1817
- var VERSION = data.version;
1818
-
1819
-
1820
- var validators$1 = {};
1821
-
1822
- // eslint-disable-next-line func-names
1823
- ['object', 'boolean', 'number', 'function', 'string', 'symbol'].forEach(function(type, i) {
1824
- validators$1[type] = function validator(thing) {
1825
- return typeof thing === type || 'a' + (i < 1 ? 'n ' : ' ') + type;
1826
- };
1827
- });
1828
-
1829
- var deprecatedWarnings = {};
1830
-
1831
- /**
1832
- * Transitional option validator
1833
- * @param {function|boolean?} validator - set to false if the transitional option has been removed
1834
- * @param {string?} version - deprecated version / removed since version
1835
- * @param {string?} message - some message with additional info
1836
- * @returns {function}
1837
- */
1838
- validators$1.transitional = function transitional(validator, version, message) {
1839
- function formatMessage(opt, desc) {
1840
- return '[Axios v' + VERSION + '] Transitional option \'' + opt + '\'' + desc + (message ? '. ' + message : '');
1841
- }
1842
-
1843
- // eslint-disable-next-line func-names
1844
- return function(value, opt, opts) {
1845
- if (validator === false) {
1846
- throw new AxiosError_1(
1847
- formatMessage(opt, ' has been removed' + (version ? ' in ' + version : '')),
1848
- AxiosError_1.ERR_DEPRECATED
1849
- );
1850
- }
1851
-
1852
- if (version && !deprecatedWarnings[opt]) {
1853
- deprecatedWarnings[opt] = true;
1854
- // eslint-disable-next-line no-console
1855
- console.warn(
1856
- formatMessage(
1857
- opt,
1858
- ' has been deprecated since v' + version + ' and will be removed in the near future'
1859
- )
1860
- );
307
+ const mergeHeaders = (source1 = {}, source2 = {}) => {
308
+ const result = new globalThis.Headers(source1);
309
+ const isHeadersInstance = source2 instanceof globalThis.Headers;
310
+ const source = new globalThis.Headers(source2);
311
+ for (const [key, value] of source.entries()) {
312
+ if ((isHeadersInstance && value === 'undefined') || value === undefined) {
313
+ result.delete(key);
314
+ }
315
+ else {
316
+ result.set(key, value);
317
+ }
1861
318
  }
1862
-
1863
- return validator ? validator(value, opt, opts) : true;
1864
- };
319
+ return result;
1865
320
  };
1866
-
1867
- /**
1868
- * Assert object's properties type
1869
- * @param {object} options
1870
- * @param {object} schema
1871
- * @param {boolean?} allowUnknown
1872
- */
1873
-
1874
- function assertOptions(options, schema, allowUnknown) {
1875
- if (typeof options !== 'object') {
1876
- throw new AxiosError_1('options must be an object', AxiosError_1.ERR_BAD_OPTION_VALUE);
1877
- }
1878
- var keys = Object.keys(options);
1879
- var i = keys.length;
1880
- while (i-- > 0) {
1881
- var opt = keys[i];
1882
- var validator = schema[opt];
1883
- if (validator) {
1884
- var value = options[opt];
1885
- var result = value === undefined || validator(value, opt, options);
1886
- if (result !== true) {
1887
- throw new AxiosError_1('option ' + opt + ' must be ' + result, AxiosError_1.ERR_BAD_OPTION_VALUE);
1888
- }
1889
- continue;
1890
- }
1891
- if (allowUnknown !== true) {
1892
- throw new AxiosError_1('Unknown option ' + opt, AxiosError_1.ERR_BAD_OPTION);
321
+ // TODO: Make this strongly-typed (no `any`).
322
+ const deepMerge = (...sources) => {
323
+ let returnValue = {};
324
+ let headers = {};
325
+ for (const source of sources) {
326
+ if (Array.isArray(source)) {
327
+ if (!Array.isArray(returnValue)) {
328
+ returnValue = [];
329
+ }
330
+ returnValue = [...returnValue, ...source];
331
+ }
332
+ else if (isObject(source)) {
333
+ for (let [key, value] of Object.entries(source)) {
334
+ if (isObject(value) && key in returnValue) {
335
+ value = deepMerge(returnValue[key], value);
336
+ }
337
+ returnValue = { ...returnValue, [key]: value };
338
+ }
339
+ if (isObject(source.headers)) {
340
+ headers = mergeHeaders(headers, source.headers);
341
+ returnValue.headers = headers;
342
+ }
343
+ }
1893
344
  }
1894
- }
1895
- }
1896
-
1897
- var validator = {
1898
- assertOptions: assertOptions,
1899
- validators: validators$1
1900
- };
1901
-
1902
- var validators = validator.validators;
1903
- /**
1904
- * Create a new instance of Axios
1905
- *
1906
- * @param {Object} instanceConfig The default config for the instance
1907
- */
1908
- function Axios(instanceConfig) {
1909
- this.defaults = instanceConfig;
1910
- this.interceptors = {
1911
- request: new InterceptorManager_1(),
1912
- response: new InterceptorManager_1()
1913
- };
1914
- }
1915
-
1916
- /**
1917
- * Dispatch a request
1918
- *
1919
- * @param {Object} config The config specific for this request (merged with this.defaults)
1920
- */
1921
- Axios.prototype.request = function request(configOrUrl, config) {
1922
- /*eslint no-param-reassign:0*/
1923
- // Allow for axios('example/url'[, config]) a la fetch API
1924
- if (typeof configOrUrl === 'string') {
1925
- config = config || {};
1926
- config.url = configOrUrl;
1927
- } else {
1928
- config = configOrUrl || {};
1929
- }
1930
-
1931
- config = mergeConfig(this.defaults, config);
1932
-
1933
- // Set config.method
1934
- if (config.method) {
1935
- config.method = config.method.toLowerCase();
1936
- } else if (this.defaults.method) {
1937
- config.method = this.defaults.method.toLowerCase();
1938
- } else {
1939
- config.method = 'get';
1940
- }
1941
-
1942
- var transitional = config.transitional;
1943
-
1944
- if (transitional !== undefined) {
1945
- validator.assertOptions(transitional, {
1946
- silentJSONParsing: validators.transitional(validators.boolean),
1947
- forcedJSONParsing: validators.transitional(validators.boolean),
1948
- clarifyTimeoutError: validators.transitional(validators.boolean)
1949
- }, false);
1950
- }
1951
-
1952
- // filter out skipped interceptors
1953
- var requestInterceptorChain = [];
1954
- var synchronousRequestInterceptors = true;
1955
- this.interceptors.request.forEach(function unshiftRequestInterceptors(interceptor) {
1956
- if (typeof interceptor.runWhen === 'function' && interceptor.runWhen(config) === false) {
1957
- return;
345
+ return returnValue;
346
+ };
347
+
348
+ const supportsStreams = (() => {
349
+ let duplexAccessed = false;
350
+ let hasContentType = false;
351
+ const supportsReadableStream = typeof globalThis.ReadableStream === 'function';
352
+ if (supportsReadableStream) {
353
+ hasContentType = new globalThis.Request('https://a.com', {
354
+ body: new globalThis.ReadableStream(),
355
+ method: 'POST',
356
+ // @ts-expect-error - Types are outdated.
357
+ get duplex() {
358
+ duplexAccessed = true;
359
+ return 'half';
360
+ },
361
+ }).headers.has('Content-Type');
362
+ }
363
+ return duplexAccessed && !hasContentType;
364
+ })();
365
+ const supportsAbortController = typeof globalThis.AbortController === 'function';
366
+ const supportsFormData = typeof globalThis.FormData === 'function';
367
+ const requestMethods = ['get', 'post', 'put', 'patch', 'head', 'delete'];
368
+ const responseTypes = {
369
+ json: 'application/json',
370
+ text: 'text/*',
371
+ formData: 'multipart/form-data',
372
+ arrayBuffer: '*/*',
373
+ blob: '*/*',
374
+ };
375
+ // The maximum value of a 32bit int (see issue #117)
376
+ const maxSafeTimeout = 2147483647;
377
+ const stop = Symbol('stop');
378
+
379
+ const normalizeRequestMethod = (input) => requestMethods.includes(input) ? input.toUpperCase() : input;
380
+ const retryMethods = ['get', 'put', 'head', 'delete', 'options', 'trace'];
381
+ const retryStatusCodes = [408, 413, 429, 500, 502, 503, 504];
382
+ const retryAfterStatusCodes = [413, 429, 503];
383
+ const defaultRetryOptions = {
384
+ limit: 2,
385
+ methods: retryMethods,
386
+ statusCodes: retryStatusCodes,
387
+ afterStatusCodes: retryAfterStatusCodes,
388
+ maxRetryAfter: Number.POSITIVE_INFINITY,
389
+ };
390
+ const normalizeRetryOptions = (retry = {}) => {
391
+ if (typeof retry === 'number') {
392
+ return {
393
+ ...defaultRetryOptions,
394
+ limit: retry,
395
+ };
1958
396
  }
1959
-
1960
- synchronousRequestInterceptors = synchronousRequestInterceptors && interceptor.synchronous;
1961
-
1962
- requestInterceptorChain.unshift(interceptor.fulfilled, interceptor.rejected);
1963
- });
1964
-
1965
- var responseInterceptorChain = [];
1966
- this.interceptors.response.forEach(function pushResponseInterceptors(interceptor) {
1967
- responseInterceptorChain.push(interceptor.fulfilled, interceptor.rejected);
1968
- });
1969
-
1970
- var promise;
1971
-
1972
- if (!synchronousRequestInterceptors) {
1973
- var chain = [dispatchRequest, undefined];
1974
-
1975
- Array.prototype.unshift.apply(chain, requestInterceptorChain);
1976
- chain = chain.concat(responseInterceptorChain);
1977
-
1978
- promise = Promise.resolve(config);
1979
- while (chain.length) {
1980
- promise = promise.then(chain.shift(), chain.shift());
397
+ if (retry.methods && !Array.isArray(retry.methods)) {
398
+ throw new Error('retry.methods must be an array');
1981
399
  }
1982
-
1983
- return promise;
1984
- }
1985
-
1986
-
1987
- var newConfig = config;
1988
- while (requestInterceptorChain.length) {
1989
- var onFulfilled = requestInterceptorChain.shift();
1990
- var onRejected = requestInterceptorChain.shift();
1991
- try {
1992
- newConfig = onFulfilled(newConfig);
1993
- } catch (error) {
1994
- onRejected(error);
1995
- break;
400
+ if (retry.statusCodes && !Array.isArray(retry.statusCodes)) {
401
+ throw new Error('retry.statusCodes must be an array');
1996
402
  }
1997
- }
1998
-
1999
- try {
2000
- promise = dispatchRequest(newConfig);
2001
- } catch (error) {
2002
- return Promise.reject(error);
2003
- }
2004
-
2005
- while (responseInterceptorChain.length) {
2006
- promise = promise.then(responseInterceptorChain.shift(), responseInterceptorChain.shift());
2007
- }
2008
-
2009
- return promise;
2010
- };
2011
-
2012
- Axios.prototype.getUri = function getUri(config) {
2013
- config = mergeConfig(this.defaults, config);
2014
- var fullPath = buildFullPath(config.baseURL, config.url);
2015
- return buildURL(fullPath, config.params, config.paramsSerializer);
403
+ return {
404
+ ...defaultRetryOptions,
405
+ ...retry,
406
+ afterStatusCodes: retryAfterStatusCodes,
407
+ };
2016
408
  };
2017
409
 
2018
- // Provide aliases for supported request methods
2019
- utils.forEach(['delete', 'get', 'head', 'options'], function forEachMethodNoData(method) {
2020
- /*eslint func-names:0*/
2021
- Axios.prototype[method] = function(url, config) {
2022
- return this.request(mergeConfig(config || {}, {
2023
- method: method,
2024
- url: url,
2025
- data: (config || {}).data
2026
- }));
2027
- };
410
+ // `Promise.race()` workaround (#91)
411
+ const timeout = async (request, abortController, options) => new Promise((resolve, reject) => {
412
+ const timeoutId = setTimeout(() => {
413
+ if (abortController) {
414
+ abortController.abort();
415
+ }
416
+ reject(new TimeoutError(request));
417
+ }, options.timeout);
418
+ void options
419
+ .fetch(request)
420
+ .then(resolve)
421
+ .catch(reject)
422
+ .then(() => {
423
+ clearTimeout(timeoutId);
424
+ });
2028
425
  });
2029
-
2030
- utils.forEach(['post', 'put', 'patch'], function forEachMethodWithData(method) {
2031
- /*eslint func-names:0*/
2032
-
2033
- function generateHTTPMethod(isForm) {
2034
- return function httpMethod(url, data, config) {
2035
- return this.request(mergeConfig(config || {}, {
2036
- method: method,
2037
- headers: isForm ? {
2038
- 'Content-Type': 'multipart/form-data'
2039
- } : {},
2040
- url: url,
2041
- data: data
2042
- }));
2043
- };
2044
- }
2045
-
2046
- Axios.prototype[method] = generateHTTPMethod();
2047
-
2048
- Axios.prototype[method + 'Form'] = generateHTTPMethod(true);
426
+ const delay = async (ms) => new Promise(resolve => {
427
+ setTimeout(resolve, ms);
2049
428
  });
2050
429
 
2051
- var Axios_1 = Axios;
2052
-
2053
- /**
2054
- * A `CancelToken` is an object that can be used to request cancellation of an operation.
2055
- *
2056
- * @class
2057
- * @param {Function} executor The executor function.
2058
- */
2059
- function CancelToken(executor) {
2060
- if (typeof executor !== 'function') {
2061
- throw new TypeError('executor must be a function.');
2062
- }
2063
-
2064
- var resolvePromise;
2065
-
2066
- this.promise = new Promise(function promiseExecutor(resolve) {
2067
- resolvePromise = resolve;
2068
- });
2069
-
2070
- var token = this;
2071
-
2072
- // eslint-disable-next-line func-names
2073
- this.promise.then(function(cancel) {
2074
- if (!token._listeners) return;
2075
-
2076
- var i;
2077
- var l = token._listeners.length;
2078
-
2079
- for (i = 0; i < l; i++) {
2080
- token._listeners[i](cancel);
430
+ class Ky {
431
+ // eslint-disable-next-line complexity
432
+ constructor(input, options = {}) {
433
+ Object.defineProperty(this, "request", {
434
+ enumerable: true,
435
+ configurable: true,
436
+ writable: true,
437
+ value: void 0
438
+ });
439
+ Object.defineProperty(this, "abortController", {
440
+ enumerable: true,
441
+ configurable: true,
442
+ writable: true,
443
+ value: void 0
444
+ });
445
+ Object.defineProperty(this, "_retryCount", {
446
+ enumerable: true,
447
+ configurable: true,
448
+ writable: true,
449
+ value: 0
450
+ });
451
+ Object.defineProperty(this, "_input", {
452
+ enumerable: true,
453
+ configurable: true,
454
+ writable: true,
455
+ value: void 0
456
+ });
457
+ Object.defineProperty(this, "_options", {
458
+ enumerable: true,
459
+ configurable: true,
460
+ writable: true,
461
+ value: void 0
462
+ });
463
+ this._input = input;
464
+ this._options = {
465
+ // TODO: credentials can be removed when the spec change is implemented in all browsers. Context: https://www.chromestatus.com/feature/4539473312350208
466
+ credentials: this._input.credentials || 'same-origin',
467
+ ...options,
468
+ headers: mergeHeaders(this._input.headers, options.headers),
469
+ hooks: deepMerge({
470
+ beforeRequest: [],
471
+ beforeRetry: [],
472
+ beforeError: [],
473
+ afterResponse: [],
474
+ }, options.hooks),
475
+ method: normalizeRequestMethod(options.method ?? this._input.method),
476
+ // eslint-disable-next-line @typescript-eslint/prefer-nullish-coalescing
477
+ prefixUrl: String(options.prefixUrl || ''),
478
+ retry: normalizeRetryOptions(options.retry),
479
+ throwHttpErrors: options.throwHttpErrors !== false,
480
+ timeout: typeof options.timeout === 'undefined' ? 10000 : options.timeout,
481
+ fetch: options.fetch ?? globalThis.fetch.bind(globalThis),
482
+ };
483
+ if (typeof this._input !== 'string' && !(this._input instanceof URL || this._input instanceof globalThis.Request)) {
484
+ throw new TypeError('`input` must be a string, URL, or Request');
485
+ }
486
+ if (this._options.prefixUrl && typeof this._input === 'string') {
487
+ if (this._input.startsWith('/')) {
488
+ throw new Error('`input` must not begin with a slash when using `prefixUrl`');
489
+ }
490
+ if (!this._options.prefixUrl.endsWith('/')) {
491
+ this._options.prefixUrl += '/';
492
+ }
493
+ this._input = this._options.prefixUrl + this._input;
494
+ }
495
+ if (supportsAbortController) {
496
+ this.abortController = new globalThis.AbortController();
497
+ if (this._options.signal) {
498
+ this._options.signal.addEventListener('abort', () => {
499
+ this.abortController.abort();
500
+ });
501
+ }
502
+ this._options.signal = this.abortController.signal;
503
+ }
504
+ this.request = new globalThis.Request(this._input, this._options);
505
+ if (supportsStreams) {
506
+ // @ts-expect-error - Types are outdated.
507
+ this.request.duplex = 'half';
508
+ }
509
+ if (this._options.searchParams) {
510
+ // eslint-disable-next-line unicorn/prevent-abbreviations
511
+ const textSearchParams = typeof this._options.searchParams === 'string'
512
+ ? this._options.searchParams.replace(/^\?/, '')
513
+ : new URLSearchParams(this._options.searchParams).toString();
514
+ // eslint-disable-next-line unicorn/prevent-abbreviations
515
+ const searchParams = '?' + textSearchParams;
516
+ const url = this.request.url.replace(/(?:\?.*?)?(?=#|$)/, searchParams);
517
+ // To provide correct form boundary, Content-Type header should be deleted each time when new Request instantiated from another one
518
+ if (((supportsFormData && this._options.body instanceof globalThis.FormData)
519
+ || this._options.body instanceof URLSearchParams) && !(this._options.headers && this._options.headers['content-type'])) {
520
+ this.request.headers.delete('content-type');
521
+ }
522
+ this.request = new globalThis.Request(new globalThis.Request(url, this.request), this._options);
523
+ }
524
+ if (this._options.json !== undefined) {
525
+ this._options.body = JSON.stringify(this._options.json);
526
+ this.request.headers.set('content-type', this._options.headers.get('content-type') ?? 'application/json');
527
+ this.request = new globalThis.Request(this.request, { body: this._options.body });
528
+ }
2081
529
  }
2082
- token._listeners = null;
2083
- });
2084
-
2085
- // eslint-disable-next-line func-names
2086
- this.promise.then = function(onfulfilled) {
2087
- var _resolve;
2088
- // eslint-disable-next-line func-names
2089
- var promise = new Promise(function(resolve) {
2090
- token.subscribe(resolve);
2091
- _resolve = resolve;
2092
- }).then(onfulfilled);
2093
-
2094
- promise.cancel = function reject() {
2095
- token.unsubscribe(_resolve);
2096
- };
2097
-
2098
- return promise;
2099
- };
2100
-
2101
- executor(function cancel(message) {
2102
- if (token.reason) {
2103
- // Cancellation has already been requested
2104
- return;
530
+ // eslint-disable-next-line @typescript-eslint/promise-function-async
531
+ static create(input, options) {
532
+ const ky = new Ky(input, options);
533
+ const fn = async () => {
534
+ if (ky._options.timeout > maxSafeTimeout) {
535
+ throw new RangeError(`The \`timeout\` option cannot be greater than ${maxSafeTimeout}`);
536
+ }
537
+ // Delay the fetch so that body method shortcuts can set the Accept header
538
+ await Promise.resolve();
539
+ let response = await ky._fetch();
540
+ for (const hook of ky._options.hooks.afterResponse) {
541
+ // eslint-disable-next-line no-await-in-loop
542
+ const modifiedResponse = await hook(ky.request, ky._options, ky._decorateResponse(response.clone()));
543
+ if (modifiedResponse instanceof globalThis.Response) {
544
+ response = modifiedResponse;
545
+ }
546
+ }
547
+ ky._decorateResponse(response);
548
+ if (!response.ok && ky._options.throwHttpErrors) {
549
+ let error = new HTTPError(response, ky.request, ky._options);
550
+ for (const hook of ky._options.hooks.beforeError) {
551
+ // eslint-disable-next-line no-await-in-loop
552
+ error = await hook(error);
553
+ }
554
+ throw error;
555
+ }
556
+ // If `onDownloadProgress` is passed, it uses the stream API internally
557
+ /* istanbul ignore next */
558
+ if (ky._options.onDownloadProgress) {
559
+ if (typeof ky._options.onDownloadProgress !== 'function') {
560
+ throw new TypeError('The `onDownloadProgress` option must be a function');
561
+ }
562
+ if (!supportsStreams) {
563
+ throw new Error('Streams are not supported in your environment. `ReadableStream` is missing.');
564
+ }
565
+ return ky._stream(response.clone(), ky._options.onDownloadProgress);
566
+ }
567
+ return response;
568
+ };
569
+ const isRetriableMethod = ky._options.retry.methods.includes(ky.request.method.toLowerCase());
570
+ const result = (isRetriableMethod ? ky._retry(fn) : fn());
571
+ for (const [type, mimeType] of Object.entries(responseTypes)) {
572
+ result[type] = async () => {
573
+ // eslint-disable-next-line @typescript-eslint/prefer-nullish-coalescing
574
+ ky.request.headers.set('accept', ky.request.headers.get('accept') || mimeType);
575
+ const awaitedResult = await result;
576
+ const response = awaitedResult.clone();
577
+ if (type === 'json') {
578
+ if (response.status === 204) {
579
+ return '';
580
+ }
581
+ if (options.parseJson) {
582
+ return options.parseJson(await response.text());
583
+ }
584
+ }
585
+ return response[type]();
586
+ };
587
+ }
588
+ return result;
589
+ }
590
+ _calculateRetryDelay(error) {
591
+ this._retryCount++;
592
+ if (this._retryCount < this._options.retry.limit && !(error instanceof TimeoutError)) {
593
+ if (error instanceof HTTPError) {
594
+ if (!this._options.retry.statusCodes.includes(error.response.status)) {
595
+ return 0;
596
+ }
597
+ const retryAfter = error.response.headers.get('Retry-After');
598
+ if (retryAfter && this._options.retry.afterStatusCodes.includes(error.response.status)) {
599
+ let after = Number(retryAfter);
600
+ if (Number.isNaN(after)) {
601
+ after = Date.parse(retryAfter) - Date.now();
602
+ }
603
+ else {
604
+ after *= 1000;
605
+ }
606
+ if (typeof this._options.retry.maxRetryAfter !== 'undefined' && after > this._options.retry.maxRetryAfter) {
607
+ return 0;
608
+ }
609
+ return after;
610
+ }
611
+ if (error.response.status === 413) {
612
+ return 0;
613
+ }
614
+ }
615
+ const BACKOFF_FACTOR = 0.3;
616
+ return BACKOFF_FACTOR * (2 ** (this._retryCount - 1)) * 1000;
617
+ }
618
+ return 0;
619
+ }
620
+ _decorateResponse(response) {
621
+ if (this._options.parseJson) {
622
+ response.json = async () => this._options.parseJson(await response.text());
623
+ }
624
+ return response;
625
+ }
626
+ async _retry(fn) {
627
+ try {
628
+ return await fn();
629
+ // eslint-disable-next-line @typescript-eslint/no-implicit-any-catch
630
+ }
631
+ catch (error) {
632
+ const ms = Math.min(this._calculateRetryDelay(error), maxSafeTimeout);
633
+ if (ms !== 0 && this._retryCount > 0) {
634
+ await delay(ms);
635
+ for (const hook of this._options.hooks.beforeRetry) {
636
+ // eslint-disable-next-line no-await-in-loop
637
+ const hookResult = await hook({
638
+ request: this.request,
639
+ options: this._options,
640
+ error: error,
641
+ retryCount: this._retryCount,
642
+ });
643
+ // If `stop` is returned from the hook, the retry process is stopped
644
+ if (hookResult === stop) {
645
+ return;
646
+ }
647
+ }
648
+ return this._retry(fn);
649
+ }
650
+ throw error;
651
+ }
652
+ }
653
+ async _fetch() {
654
+ for (const hook of this._options.hooks.beforeRequest) {
655
+ // eslint-disable-next-line no-await-in-loop
656
+ const result = await hook(this.request, this._options);
657
+ if (result instanceof Request) {
658
+ this.request = result;
659
+ break;
660
+ }
661
+ if (result instanceof Response) {
662
+ return result;
663
+ }
664
+ }
665
+ if (this._options.timeout === false) {
666
+ return this._options.fetch(this.request.clone());
667
+ }
668
+ return timeout(this.request.clone(), this.abortController, this._options);
669
+ }
670
+ /* istanbul ignore next */
671
+ _stream(response, onDownloadProgress) {
672
+ const totalBytes = Number(response.headers.get('content-length')) || 0;
673
+ let transferredBytes = 0;
674
+ if (response.status === 204) {
675
+ if (onDownloadProgress) {
676
+ onDownloadProgress({ percent: 1, totalBytes, transferredBytes }, new Uint8Array());
677
+ }
678
+ return new globalThis.Response(null, {
679
+ status: response.status,
680
+ statusText: response.statusText,
681
+ headers: response.headers,
682
+ });
683
+ }
684
+ return new globalThis.Response(new globalThis.ReadableStream({
685
+ async start(controller) {
686
+ const reader = response.body.getReader();
687
+ if (onDownloadProgress) {
688
+ onDownloadProgress({ percent: 0, transferredBytes: 0, totalBytes }, new Uint8Array());
689
+ }
690
+ async function read() {
691
+ const { done, value } = await reader.read();
692
+ if (done) {
693
+ controller.close();
694
+ return;
695
+ }
696
+ if (onDownloadProgress) {
697
+ transferredBytes += value.byteLength;
698
+ const percent = totalBytes === 0 ? 0 : transferredBytes / totalBytes;
699
+ onDownloadProgress({ percent, transferredBytes, totalBytes }, value);
700
+ }
701
+ controller.enqueue(value);
702
+ await read();
703
+ }
704
+ await read();
705
+ },
706
+ }), {
707
+ status: response.status,
708
+ statusText: response.statusText,
709
+ headers: response.headers,
710
+ });
2105
711
  }
2106
-
2107
- token.reason = new CanceledError_1(message);
2108
- resolvePromise(token.reason);
2109
- });
2110
- }
2111
-
2112
- /**
2113
- * Throws a `CanceledError` if cancellation has been requested.
2114
- */
2115
- CancelToken.prototype.throwIfRequested = function throwIfRequested() {
2116
- if (this.reason) {
2117
- throw this.reason;
2118
- }
2119
- };
2120
-
2121
- /**
2122
- * Subscribe to the cancel signal
2123
- */
2124
-
2125
- CancelToken.prototype.subscribe = function subscribe(listener) {
2126
- if (this.reason) {
2127
- listener(this.reason);
2128
- return;
2129
- }
2130
-
2131
- if (this._listeners) {
2132
- this._listeners.push(listener);
2133
- } else {
2134
- this._listeners = [listener];
2135
- }
2136
- };
2137
-
2138
- /**
2139
- * Unsubscribe from the cancel signal
2140
- */
2141
-
2142
- CancelToken.prototype.unsubscribe = function unsubscribe(listener) {
2143
- if (!this._listeners) {
2144
- return;
2145
- }
2146
- var index = this._listeners.indexOf(listener);
2147
- if (index !== -1) {
2148
- this._listeners.splice(index, 1);
2149
- }
2150
- };
2151
-
2152
- /**
2153
- * Returns an object that contains a new `CancelToken` and a function that, when called,
2154
- * cancels the `CancelToken`.
2155
- */
2156
- CancelToken.source = function source() {
2157
- var cancel;
2158
- var token = new CancelToken(function executor(c) {
2159
- cancel = c;
2160
- });
2161
- return {
2162
- token: token,
2163
- cancel: cancel
2164
- };
2165
- };
2166
-
2167
- var CancelToken_1 = CancelToken;
2168
-
2169
- /**
2170
- * Syntactic sugar for invoking a function and expanding an array for arguments.
2171
- *
2172
- * Common use case would be to use `Function.prototype.apply`.
2173
- *
2174
- * ```js
2175
- * function f(x, y, z) {}
2176
- * var args = [1, 2, 3];
2177
- * f.apply(null, args);
2178
- * ```
2179
- *
2180
- * With `spread` this example can be re-written.
2181
- *
2182
- * ```js
2183
- * spread(function(x, y, z) {})([1, 2, 3]);
2184
- * ```
2185
- *
2186
- * @param {Function} callback
2187
- * @returns {Function}
2188
- */
2189
- var spread = function spread(callback) {
2190
- return function wrap(arr) {
2191
- return callback.apply(null, arr);
2192
- };
2193
- };
2194
-
2195
- /**
2196
- * Determines whether the payload is an error thrown by Axios
2197
- *
2198
- * @param {*} payload The value to test
2199
- * @returns {boolean} True if the payload is an error thrown by Axios, otherwise false
2200
- */
2201
- var isAxiosError = function isAxiosError(payload) {
2202
- return utils.isObject(payload) && (payload.isAxiosError === true);
2203
- };
2204
-
2205
- /**
2206
- * Create an instance of Axios
2207
- *
2208
- * @param {Object} defaultConfig The default config for the instance
2209
- * @return {Axios} A new instance of Axios
2210
- */
2211
- function createInstance(defaultConfig) {
2212
- var context = new Axios_1(defaultConfig);
2213
- var instance = bind(Axios_1.prototype.request, context);
2214
-
2215
- // Copy axios.prototype to instance
2216
- utils.extend(instance, Axios_1.prototype, context);
2217
-
2218
- // Copy context to instance
2219
- utils.extend(instance, context);
2220
-
2221
- // Factory for creating new instances
2222
- instance.create = function create(instanceConfig) {
2223
- return createInstance(mergeConfig(defaultConfig, instanceConfig));
2224
- };
2225
-
2226
- return instance;
2227
712
  }
2228
713
 
2229
- // Create the default instance to be exported
2230
- var axios$1 = createInstance(defaults_1);
2231
-
2232
- // Expose Axios class to allow class inheritance
2233
- axios$1.Axios = Axios_1;
2234
-
2235
- // Expose Cancel & CancelToken
2236
- axios$1.CanceledError = CanceledError_1;
2237
- axios$1.CancelToken = CancelToken_1;
2238
- axios$1.isCancel = isCancel;
2239
- axios$1.VERSION = data.version;
2240
- axios$1.toFormData = toFormData_1;
2241
-
2242
- // Expose AxiosError class
2243
- axios$1.AxiosError = AxiosError_1;
2244
-
2245
- // alias for CanceledError for backward compatibility
2246
- axios$1.Cancel = axios$1.CanceledError;
2247
-
2248
- // Expose all/spread
2249
- axios$1.all = function all(promises) {
2250
- return Promise.all(promises);
714
+ /*! MIT License © Sindre Sorhus */
715
+ const createInstance = (defaults) => {
716
+ // eslint-disable-next-line @typescript-eslint/promise-function-async
717
+ const ky = (input, options) => Ky.create(input, validateAndMerge(defaults, options));
718
+ for (const method of requestMethods) {
719
+ // eslint-disable-next-line @typescript-eslint/promise-function-async
720
+ ky[method] = (input, options) => Ky.create(input, validateAndMerge(defaults, options, { method }));
721
+ }
722
+ ky.create = (newDefaults) => createInstance(validateAndMerge(newDefaults));
723
+ ky.extend = (newDefaults) => createInstance(validateAndMerge(defaults, newDefaults));
724
+ ky.stop = stop;
725
+ return ky;
2251
726
  };
2252
- axios$1.spread = spread;
2253
-
2254
- // Expose isAxiosError
2255
- axios$1.isAxiosError = isAxiosError;
2256
-
2257
- var axios_1 = axios$1;
2258
-
2259
- // Allow use of default import syntax in TypeScript
2260
- var _default = axios$1;
2261
- axios_1.default = _default;
2262
-
2263
- var axios = axios_1;
727
+ const ky = createInstance();
2264
728
 
2265
729
  // --------------------------------------------------------[ mutable store ]
2266
730
  const storeDef = {
@@ -2397,10 +861,17 @@ const processPick = (next) => {
2397
861
  savePick(state.pick);
2398
862
  };
2399
863
  // --------------------------------------------------------[ utils ]
2400
- const api = axios.create({
2401
- baseURL: 'https://sudoku-rust-api.vercel.app/api/',
864
+ const api = ky.extend({
865
+ hooks: {
866
+ beforeRequest: [
867
+ request => {
868
+ request.headers.set('X-Requested-With', 'ky');
869
+ request.headers.set('X-Custom-Header', 'foobar');
870
+ },
871
+ ],
872
+ },
873
+ prefixUrl: 'https://sudoku-rust-api.vercel.app/api',
2402
874
  timeout: 10000,
2403
- headers: { 'X-Custom-Header': 'foobar' },
2404
875
  });
2405
876
  const saveInputs = (inputs) => {
2406
877
  bag.inputs.store(inputs);
@@ -2441,27 +912,26 @@ const initApp = () => {
2441
912
  }
2442
913
  }
2443
914
  };
2444
- const refresh = () => {
915
+ const refresh = async () => {
2445
916
  clearStore(true);
2446
917
  saveInputs([]);
2447
918
  savePick(state.pick);
2448
- // fetch a new puzzle from the api...
2449
- api
2450
- .get('/puzzle')
2451
- .then(({ data }) => {
919
+ try {
920
+ // fetch a new puzzle from the api...
921
+ const data = await api.get('puzzle').json();
2452
922
  updateStore(data);
2453
- })
2454
- .catch(error => {
923
+ }
924
+ catch (err) {
2455
925
  // handle error...
2456
- const { message } = error;
926
+ const { message } = err;
2457
927
  console.log('-- ', message);
2458
- console.log(error);
928
+ console.log(err);
2459
929
  state.error = message;
2460
- })
2461
- .then(() => {
930
+ }
931
+ finally {
2462
932
  // always executed
2463
933
  state.loading = false;
2464
- });
934
+ }
2465
935
  };
2466
936
  const select = (cell) => {
2467
937
  processPick(cell);