@imtbl/sdk 0.1.8 → 0.1.9-alpha

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/passport.js CHANGED
@@ -1,11 +1,10 @@
1
1
  import { ImmutableX, Config, generateLegacyStarkPrivateKey, createStarkSigner } from '@imtbl/core-sdk';
2
2
  import { UserManager } from 'oidc-client-ts';
3
- import { ethers } from 'ethers';
4
3
  import { Magic } from 'magic-sdk';
5
4
  import { OpenIdExtension } from '@magic-ext/oidc';
6
5
  import BN from 'bn.js';
7
6
  import * as encUtils from 'enc-utils';
8
- import globalAxios from 'axios';
7
+ import { Web3Provider } from '@ethersproject/providers';
9
8
 
10
9
  var Environment;
11
10
  (function (Environment) {
@@ -22,7 +21,7 @@ const createImmutableXConfiguration = ({ basePath, chainID, coreContractAddress,
22
21
  chainID,
23
22
  coreContractAddress,
24
23
  registrationContractAddress,
25
- sdkVersion: 'ts-immutable-sdk-0.0.0',
24
+ sdkVersion: 'ts-immutable-sdk-0.1.9-alpha',
26
25
  });
27
26
  /**
28
27
  * Sets `sdkVersion` at the time of build
@@ -588,6 +587,3214 @@ function convertToSignableToken(token) {
588
587
  }
589
588
  }
590
589
 
590
+ function bind(fn, thisArg) {
591
+ return function wrap() {
592
+ return fn.apply(thisArg, arguments);
593
+ };
594
+ }
595
+
596
+ // utils is a library of generic helper functions non-specific to axios
597
+
598
+ const {toString} = Object.prototype;
599
+ const {getPrototypeOf} = Object;
600
+
601
+ const kindOf = (cache => thing => {
602
+ const str = toString.call(thing);
603
+ return cache[str] || (cache[str] = str.slice(8, -1).toLowerCase());
604
+ })(Object.create(null));
605
+
606
+ const kindOfTest = (type) => {
607
+ type = type.toLowerCase();
608
+ return (thing) => kindOf(thing) === type
609
+ };
610
+
611
+ const typeOfTest = type => thing => typeof thing === type;
612
+
613
+ /**
614
+ * Determine if a value is an Array
615
+ *
616
+ * @param {Object} val The value to test
617
+ *
618
+ * @returns {boolean} True if value is an Array, otherwise false
619
+ */
620
+ const {isArray} = Array;
621
+
622
+ /**
623
+ * Determine if a value is undefined
624
+ *
625
+ * @param {*} val The value to test
626
+ *
627
+ * @returns {boolean} True if the value is undefined, otherwise false
628
+ */
629
+ const isUndefined = typeOfTest('undefined');
630
+
631
+ /**
632
+ * Determine if a value is a Buffer
633
+ *
634
+ * @param {*} val The value to test
635
+ *
636
+ * @returns {boolean} True if value is a Buffer, otherwise false
637
+ */
638
+ function isBuffer(val) {
639
+ return val !== null && !isUndefined(val) && val.constructor !== null && !isUndefined(val.constructor)
640
+ && isFunction(val.constructor.isBuffer) && val.constructor.isBuffer(val);
641
+ }
642
+
643
+ /**
644
+ * Determine if a value is an ArrayBuffer
645
+ *
646
+ * @param {*} val The value to test
647
+ *
648
+ * @returns {boolean} True if value is an ArrayBuffer, otherwise false
649
+ */
650
+ const isArrayBuffer = kindOfTest('ArrayBuffer');
651
+
652
+
653
+ /**
654
+ * Determine if a value is a view on an ArrayBuffer
655
+ *
656
+ * @param {*} val The value to test
657
+ *
658
+ * @returns {boolean} True if value is a view on an ArrayBuffer, otherwise false
659
+ */
660
+ function isArrayBufferView(val) {
661
+ let result;
662
+ if ((typeof ArrayBuffer !== 'undefined') && (ArrayBuffer.isView)) {
663
+ result = ArrayBuffer.isView(val);
664
+ } else {
665
+ result = (val) && (val.buffer) && (isArrayBuffer(val.buffer));
666
+ }
667
+ return result;
668
+ }
669
+
670
+ /**
671
+ * Determine if a value is a String
672
+ *
673
+ * @param {*} val The value to test
674
+ *
675
+ * @returns {boolean} True if value is a String, otherwise false
676
+ */
677
+ const isString = typeOfTest('string');
678
+
679
+ /**
680
+ * Determine if a value is a Function
681
+ *
682
+ * @param {*} val The value to test
683
+ * @returns {boolean} True if value is a Function, otherwise false
684
+ */
685
+ const isFunction = typeOfTest('function');
686
+
687
+ /**
688
+ * Determine if a value is a Number
689
+ *
690
+ * @param {*} val The value to test
691
+ *
692
+ * @returns {boolean} True if value is a Number, otherwise false
693
+ */
694
+ const isNumber = typeOfTest('number');
695
+
696
+ /**
697
+ * Determine if a value is an Object
698
+ *
699
+ * @param {*} thing The value to test
700
+ *
701
+ * @returns {boolean} True if value is an Object, otherwise false
702
+ */
703
+ const isObject = (thing) => thing !== null && typeof thing === 'object';
704
+
705
+ /**
706
+ * Determine if a value is a Boolean
707
+ *
708
+ * @param {*} thing The value to test
709
+ * @returns {boolean} True if value is a Boolean, otherwise false
710
+ */
711
+ const isBoolean = thing => thing === true || thing === false;
712
+
713
+ /**
714
+ * Determine if a value is a plain Object
715
+ *
716
+ * @param {*} val The value to test
717
+ *
718
+ * @returns {boolean} True if value is a plain Object, otherwise false
719
+ */
720
+ const isPlainObject = (val) => {
721
+ if (kindOf(val) !== 'object') {
722
+ return false;
723
+ }
724
+
725
+ const prototype = getPrototypeOf(val);
726
+ return (prototype === null || prototype === Object.prototype || Object.getPrototypeOf(prototype) === null) && !(Symbol.toStringTag in val) && !(Symbol.iterator in val);
727
+ };
728
+
729
+ /**
730
+ * Determine if a value is a Date
731
+ *
732
+ * @param {*} val The value to test
733
+ *
734
+ * @returns {boolean} True if value is a Date, otherwise false
735
+ */
736
+ const isDate = kindOfTest('Date');
737
+
738
+ /**
739
+ * Determine if a value is a File
740
+ *
741
+ * @param {*} val The value to test
742
+ *
743
+ * @returns {boolean} True if value is a File, otherwise false
744
+ */
745
+ const isFile = kindOfTest('File');
746
+
747
+ /**
748
+ * Determine if a value is a Blob
749
+ *
750
+ * @param {*} val The value to test
751
+ *
752
+ * @returns {boolean} True if value is a Blob, otherwise false
753
+ */
754
+ const isBlob = kindOfTest('Blob');
755
+
756
+ /**
757
+ * Determine if a value is a FileList
758
+ *
759
+ * @param {*} val The value to test
760
+ *
761
+ * @returns {boolean} True if value is a File, otherwise false
762
+ */
763
+ const isFileList = kindOfTest('FileList');
764
+
765
+ /**
766
+ * Determine if a value is a Stream
767
+ *
768
+ * @param {*} val The value to test
769
+ *
770
+ * @returns {boolean} True if value is a Stream, otherwise false
771
+ */
772
+ const isStream = (val) => isObject(val) && isFunction(val.pipe);
773
+
774
+ /**
775
+ * Determine if a value is a FormData
776
+ *
777
+ * @param {*} thing The value to test
778
+ *
779
+ * @returns {boolean} True if value is an FormData, otherwise false
780
+ */
781
+ const isFormData = (thing) => {
782
+ let kind;
783
+ return thing && (
784
+ (typeof FormData === 'function' && thing instanceof FormData) || (
785
+ isFunction(thing.append) && (
786
+ (kind = kindOf(thing)) === 'formdata' ||
787
+ // detect form-data instance
788
+ (kind === 'object' && isFunction(thing.toString) && thing.toString() === '[object FormData]')
789
+ )
790
+ )
791
+ )
792
+ };
793
+
794
+ /**
795
+ * Determine if a value is a URLSearchParams object
796
+ *
797
+ * @param {*} val The value to test
798
+ *
799
+ * @returns {boolean} True if value is a URLSearchParams object, otherwise false
800
+ */
801
+ const isURLSearchParams = kindOfTest('URLSearchParams');
802
+
803
+ /**
804
+ * Trim excess whitespace off the beginning and end of a string
805
+ *
806
+ * @param {String} str The String to trim
807
+ *
808
+ * @returns {String} The String freed of excess whitespace
809
+ */
810
+ const trim = (str) => str.trim ?
811
+ str.trim() : str.replace(/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g, '');
812
+
813
+ /**
814
+ * Iterate over an Array or an Object invoking a function for each item.
815
+ *
816
+ * If `obj` is an Array callback will be called passing
817
+ * the value, index, and complete array for each item.
818
+ *
819
+ * If 'obj' is an Object callback will be called passing
820
+ * the value, key, and complete object for each property.
821
+ *
822
+ * @param {Object|Array} obj The object to iterate
823
+ * @param {Function} fn The callback to invoke for each item
824
+ *
825
+ * @param {Boolean} [allOwnKeys = false]
826
+ * @returns {any}
827
+ */
828
+ function forEach(obj, fn, {allOwnKeys = false} = {}) {
829
+ // Don't bother if no value provided
830
+ if (obj === null || typeof obj === 'undefined') {
831
+ return;
832
+ }
833
+
834
+ let i;
835
+ let l;
836
+
837
+ // Force an array if not already something iterable
838
+ if (typeof obj !== 'object') {
839
+ /*eslint no-param-reassign:0*/
840
+ obj = [obj];
841
+ }
842
+
843
+ if (isArray(obj)) {
844
+ // Iterate over array values
845
+ for (i = 0, l = obj.length; i < l; i++) {
846
+ fn.call(null, obj[i], i, obj);
847
+ }
848
+ } else {
849
+ // Iterate over object keys
850
+ const keys = allOwnKeys ? Object.getOwnPropertyNames(obj) : Object.keys(obj);
851
+ const len = keys.length;
852
+ let key;
853
+
854
+ for (i = 0; i < len; i++) {
855
+ key = keys[i];
856
+ fn.call(null, obj[key], key, obj);
857
+ }
858
+ }
859
+ }
860
+
861
+ function findKey(obj, key) {
862
+ key = key.toLowerCase();
863
+ const keys = Object.keys(obj);
864
+ let i = keys.length;
865
+ let _key;
866
+ while (i-- > 0) {
867
+ _key = keys[i];
868
+ if (key === _key.toLowerCase()) {
869
+ return _key;
870
+ }
871
+ }
872
+ return null;
873
+ }
874
+
875
+ const _global = (() => {
876
+ /*eslint no-undef:0*/
877
+ if (typeof globalThis !== "undefined") return globalThis;
878
+ return typeof self !== "undefined" ? self : (typeof window !== 'undefined' ? window : global)
879
+ })();
880
+
881
+ const isContextDefined = (context) => !isUndefined(context) && context !== _global;
882
+
883
+ /**
884
+ * Accepts varargs expecting each argument to be an object, then
885
+ * immutably merges the properties of each object and returns result.
886
+ *
887
+ * When multiple objects contain the same key the later object in
888
+ * the arguments list will take precedence.
889
+ *
890
+ * Example:
891
+ *
892
+ * ```js
893
+ * var result = merge({foo: 123}, {foo: 456});
894
+ * console.log(result.foo); // outputs 456
895
+ * ```
896
+ *
897
+ * @param {Object} obj1 Object to merge
898
+ *
899
+ * @returns {Object} Result of all merge properties
900
+ */
901
+ function merge(/* obj1, obj2, obj3, ... */) {
902
+ const {caseless} = isContextDefined(this) && this || {};
903
+ const result = {};
904
+ const assignValue = (val, key) => {
905
+ const targetKey = caseless && findKey(result, key) || key;
906
+ if (isPlainObject(result[targetKey]) && isPlainObject(val)) {
907
+ result[targetKey] = merge(result[targetKey], val);
908
+ } else if (isPlainObject(val)) {
909
+ result[targetKey] = merge({}, val);
910
+ } else if (isArray(val)) {
911
+ result[targetKey] = val.slice();
912
+ } else {
913
+ result[targetKey] = val;
914
+ }
915
+ };
916
+
917
+ for (let i = 0, l = arguments.length; i < l; i++) {
918
+ arguments[i] && forEach(arguments[i], assignValue);
919
+ }
920
+ return result;
921
+ }
922
+
923
+ /**
924
+ * Extends object a by mutably adding to it the properties of object b.
925
+ *
926
+ * @param {Object} a The object to be extended
927
+ * @param {Object} b The object to copy properties from
928
+ * @param {Object} thisArg The object to bind function to
929
+ *
930
+ * @param {Boolean} [allOwnKeys]
931
+ * @returns {Object} The resulting value of object a
932
+ */
933
+ const extend = (a, b, thisArg, {allOwnKeys}= {}) => {
934
+ forEach(b, (val, key) => {
935
+ if (thisArg && isFunction(val)) {
936
+ a[key] = bind(val, thisArg);
937
+ } else {
938
+ a[key] = val;
939
+ }
940
+ }, {allOwnKeys});
941
+ return a;
942
+ };
943
+
944
+ /**
945
+ * Remove byte order marker. This catches EF BB BF (the UTF-8 BOM)
946
+ *
947
+ * @param {string} content with BOM
948
+ *
949
+ * @returns {string} content value without BOM
950
+ */
951
+ const stripBOM = (content) => {
952
+ if (content.charCodeAt(0) === 0xFEFF) {
953
+ content = content.slice(1);
954
+ }
955
+ return content;
956
+ };
957
+
958
+ /**
959
+ * Inherit the prototype methods from one constructor into another
960
+ * @param {function} constructor
961
+ * @param {function} superConstructor
962
+ * @param {object} [props]
963
+ * @param {object} [descriptors]
964
+ *
965
+ * @returns {void}
966
+ */
967
+ const inherits = (constructor, superConstructor, props, descriptors) => {
968
+ constructor.prototype = Object.create(superConstructor.prototype, descriptors);
969
+ constructor.prototype.constructor = constructor;
970
+ Object.defineProperty(constructor, 'super', {
971
+ value: superConstructor.prototype
972
+ });
973
+ props && Object.assign(constructor.prototype, props);
974
+ };
975
+
976
+ /**
977
+ * Resolve object with deep prototype chain to a flat object
978
+ * @param {Object} sourceObj source object
979
+ * @param {Object} [destObj]
980
+ * @param {Function|Boolean} [filter]
981
+ * @param {Function} [propFilter]
982
+ *
983
+ * @returns {Object}
984
+ */
985
+ const toFlatObject = (sourceObj, destObj, filter, propFilter) => {
986
+ let props;
987
+ let i;
988
+ let prop;
989
+ const merged = {};
990
+
991
+ destObj = destObj || {};
992
+ // eslint-disable-next-line no-eq-null,eqeqeq
993
+ if (sourceObj == null) return destObj;
994
+
995
+ do {
996
+ props = Object.getOwnPropertyNames(sourceObj);
997
+ i = props.length;
998
+ while (i-- > 0) {
999
+ prop = props[i];
1000
+ if ((!propFilter || propFilter(prop, sourceObj, destObj)) && !merged[prop]) {
1001
+ destObj[prop] = sourceObj[prop];
1002
+ merged[prop] = true;
1003
+ }
1004
+ }
1005
+ sourceObj = filter !== false && getPrototypeOf(sourceObj);
1006
+ } while (sourceObj && (!filter || filter(sourceObj, destObj)) && sourceObj !== Object.prototype);
1007
+
1008
+ return destObj;
1009
+ };
1010
+
1011
+ /**
1012
+ * Determines whether a string ends with the characters of a specified string
1013
+ *
1014
+ * @param {String} str
1015
+ * @param {String} searchString
1016
+ * @param {Number} [position= 0]
1017
+ *
1018
+ * @returns {boolean}
1019
+ */
1020
+ const endsWith = (str, searchString, position) => {
1021
+ str = String(str);
1022
+ if (position === undefined || position > str.length) {
1023
+ position = str.length;
1024
+ }
1025
+ position -= searchString.length;
1026
+ const lastIndex = str.indexOf(searchString, position);
1027
+ return lastIndex !== -1 && lastIndex === position;
1028
+ };
1029
+
1030
+
1031
+ /**
1032
+ * Returns new array from array like object or null if failed
1033
+ *
1034
+ * @param {*} [thing]
1035
+ *
1036
+ * @returns {?Array}
1037
+ */
1038
+ const toArray = (thing) => {
1039
+ if (!thing) return null;
1040
+ if (isArray(thing)) return thing;
1041
+ let i = thing.length;
1042
+ if (!isNumber(i)) return null;
1043
+ const arr = new Array(i);
1044
+ while (i-- > 0) {
1045
+ arr[i] = thing[i];
1046
+ }
1047
+ return arr;
1048
+ };
1049
+
1050
+ /**
1051
+ * Checking if the Uint8Array exists and if it does, it returns a function that checks if the
1052
+ * thing passed in is an instance of Uint8Array
1053
+ *
1054
+ * @param {TypedArray}
1055
+ *
1056
+ * @returns {Array}
1057
+ */
1058
+ // eslint-disable-next-line func-names
1059
+ const isTypedArray = (TypedArray => {
1060
+ // eslint-disable-next-line func-names
1061
+ return thing => {
1062
+ return TypedArray && thing instanceof TypedArray;
1063
+ };
1064
+ })(typeof Uint8Array !== 'undefined' && getPrototypeOf(Uint8Array));
1065
+
1066
+ /**
1067
+ * For each entry in the object, call the function with the key and value.
1068
+ *
1069
+ * @param {Object<any, any>} obj - The object to iterate over.
1070
+ * @param {Function} fn - The function to call for each entry.
1071
+ *
1072
+ * @returns {void}
1073
+ */
1074
+ const forEachEntry = (obj, fn) => {
1075
+ const generator = obj && obj[Symbol.iterator];
1076
+
1077
+ const iterator = generator.call(obj);
1078
+
1079
+ let result;
1080
+
1081
+ while ((result = iterator.next()) && !result.done) {
1082
+ const pair = result.value;
1083
+ fn.call(obj, pair[0], pair[1]);
1084
+ }
1085
+ };
1086
+
1087
+ /**
1088
+ * It takes a regular expression and a string, and returns an array of all the matches
1089
+ *
1090
+ * @param {string} regExp - The regular expression to match against.
1091
+ * @param {string} str - The string to search.
1092
+ *
1093
+ * @returns {Array<boolean>}
1094
+ */
1095
+ const matchAll = (regExp, str) => {
1096
+ let matches;
1097
+ const arr = [];
1098
+
1099
+ while ((matches = regExp.exec(str)) !== null) {
1100
+ arr.push(matches);
1101
+ }
1102
+
1103
+ return arr;
1104
+ };
1105
+
1106
+ /* Checking if the kindOfTest function returns true when passed an HTMLFormElement. */
1107
+ const isHTMLForm = kindOfTest('HTMLFormElement');
1108
+
1109
+ const toCamelCase = str => {
1110
+ return str.toLowerCase().replace(/[-_\s]([a-z\d])(\w*)/g,
1111
+ function replacer(m, p1, p2) {
1112
+ return p1.toUpperCase() + p2;
1113
+ }
1114
+ );
1115
+ };
1116
+
1117
+ /* Creating a function that will check if an object has a property. */
1118
+ const hasOwnProperty = (({hasOwnProperty}) => (obj, prop) => hasOwnProperty.call(obj, prop))(Object.prototype);
1119
+
1120
+ /**
1121
+ * Determine if a value is a RegExp object
1122
+ *
1123
+ * @param {*} val The value to test
1124
+ *
1125
+ * @returns {boolean} True if value is a RegExp object, otherwise false
1126
+ */
1127
+ const isRegExp = kindOfTest('RegExp');
1128
+
1129
+ const reduceDescriptors = (obj, reducer) => {
1130
+ const descriptors = Object.getOwnPropertyDescriptors(obj);
1131
+ const reducedDescriptors = {};
1132
+
1133
+ forEach(descriptors, (descriptor, name) => {
1134
+ if (reducer(descriptor, name, obj) !== false) {
1135
+ reducedDescriptors[name] = descriptor;
1136
+ }
1137
+ });
1138
+
1139
+ Object.defineProperties(obj, reducedDescriptors);
1140
+ };
1141
+
1142
+ /**
1143
+ * Makes all methods read-only
1144
+ * @param {Object} obj
1145
+ */
1146
+
1147
+ const freezeMethods = (obj) => {
1148
+ reduceDescriptors(obj, (descriptor, name) => {
1149
+ // skip restricted props in strict mode
1150
+ if (isFunction(obj) && ['arguments', 'caller', 'callee'].indexOf(name) !== -1) {
1151
+ return false;
1152
+ }
1153
+
1154
+ const value = obj[name];
1155
+
1156
+ if (!isFunction(value)) return;
1157
+
1158
+ descriptor.enumerable = false;
1159
+
1160
+ if ('writable' in descriptor) {
1161
+ descriptor.writable = false;
1162
+ return;
1163
+ }
1164
+
1165
+ if (!descriptor.set) {
1166
+ descriptor.set = () => {
1167
+ throw Error('Can not rewrite read-only method \'' + name + '\'');
1168
+ };
1169
+ }
1170
+ });
1171
+ };
1172
+
1173
+ const toObjectSet = (arrayOrString, delimiter) => {
1174
+ const obj = {};
1175
+
1176
+ const define = (arr) => {
1177
+ arr.forEach(value => {
1178
+ obj[value] = true;
1179
+ });
1180
+ };
1181
+
1182
+ isArray(arrayOrString) ? define(arrayOrString) : define(String(arrayOrString).split(delimiter));
1183
+
1184
+ return obj;
1185
+ };
1186
+
1187
+ const noop = () => {};
1188
+
1189
+ const toFiniteNumber = (value, defaultValue) => {
1190
+ value = +value;
1191
+ return Number.isFinite(value) ? value : defaultValue;
1192
+ };
1193
+
1194
+ const ALPHA = 'abcdefghijklmnopqrstuvwxyz';
1195
+
1196
+ const DIGIT = '0123456789';
1197
+
1198
+ const ALPHABET = {
1199
+ DIGIT,
1200
+ ALPHA,
1201
+ ALPHA_DIGIT: ALPHA + ALPHA.toUpperCase() + DIGIT
1202
+ };
1203
+
1204
+ const generateString = (size = 16, alphabet = ALPHABET.ALPHA_DIGIT) => {
1205
+ let str = '';
1206
+ const {length} = alphabet;
1207
+ while (size--) {
1208
+ str += alphabet[Math.random() * length|0];
1209
+ }
1210
+
1211
+ return str;
1212
+ };
1213
+
1214
+ /**
1215
+ * If the thing is a FormData object, return true, otherwise return false.
1216
+ *
1217
+ * @param {unknown} thing - The thing to check.
1218
+ *
1219
+ * @returns {boolean}
1220
+ */
1221
+ function isSpecCompliantForm(thing) {
1222
+ return !!(thing && isFunction(thing.append) && thing[Symbol.toStringTag] === 'FormData' && thing[Symbol.iterator]);
1223
+ }
1224
+
1225
+ const toJSONObject = (obj) => {
1226
+ const stack = new Array(10);
1227
+
1228
+ const visit = (source, i) => {
1229
+
1230
+ if (isObject(source)) {
1231
+ if (stack.indexOf(source) >= 0) {
1232
+ return;
1233
+ }
1234
+
1235
+ if(!('toJSON' in source)) {
1236
+ stack[i] = source;
1237
+ const target = isArray(source) ? [] : {};
1238
+
1239
+ forEach(source, (value, key) => {
1240
+ const reducedValue = visit(value, i + 1);
1241
+ !isUndefined(reducedValue) && (target[key] = reducedValue);
1242
+ });
1243
+
1244
+ stack[i] = undefined;
1245
+
1246
+ return target;
1247
+ }
1248
+ }
1249
+
1250
+ return source;
1251
+ };
1252
+
1253
+ return visit(obj, 0);
1254
+ };
1255
+
1256
+ const isAsyncFn = kindOfTest('AsyncFunction');
1257
+
1258
+ const isThenable = (thing) =>
1259
+ thing && (isObject(thing) || isFunction(thing)) && isFunction(thing.then) && isFunction(thing.catch);
1260
+
1261
+ var utils = {
1262
+ isArray,
1263
+ isArrayBuffer,
1264
+ isBuffer,
1265
+ isFormData,
1266
+ isArrayBufferView,
1267
+ isString,
1268
+ isNumber,
1269
+ isBoolean,
1270
+ isObject,
1271
+ isPlainObject,
1272
+ isUndefined,
1273
+ isDate,
1274
+ isFile,
1275
+ isBlob,
1276
+ isRegExp,
1277
+ isFunction,
1278
+ isStream,
1279
+ isURLSearchParams,
1280
+ isTypedArray,
1281
+ isFileList,
1282
+ forEach,
1283
+ merge,
1284
+ extend,
1285
+ trim,
1286
+ stripBOM,
1287
+ inherits,
1288
+ toFlatObject,
1289
+ kindOf,
1290
+ kindOfTest,
1291
+ endsWith,
1292
+ toArray,
1293
+ forEachEntry,
1294
+ matchAll,
1295
+ isHTMLForm,
1296
+ hasOwnProperty,
1297
+ hasOwnProp: hasOwnProperty, // an alias to avoid ESLint no-prototype-builtins detection
1298
+ reduceDescriptors,
1299
+ freezeMethods,
1300
+ toObjectSet,
1301
+ toCamelCase,
1302
+ noop,
1303
+ toFiniteNumber,
1304
+ findKey,
1305
+ global: _global,
1306
+ isContextDefined,
1307
+ ALPHABET,
1308
+ generateString,
1309
+ isSpecCompliantForm,
1310
+ toJSONObject,
1311
+ isAsyncFn,
1312
+ isThenable
1313
+ };
1314
+
1315
+ /**
1316
+ * Create an Error with the specified message, config, error code, request and response.
1317
+ *
1318
+ * @param {string} message The error message.
1319
+ * @param {string} [code] The error code (for example, 'ECONNABORTED').
1320
+ * @param {Object} [config] The config.
1321
+ * @param {Object} [request] The request.
1322
+ * @param {Object} [response] The response.
1323
+ *
1324
+ * @returns {Error} The created error.
1325
+ */
1326
+ function AxiosError(message, code, config, request, response) {
1327
+ Error.call(this);
1328
+
1329
+ if (Error.captureStackTrace) {
1330
+ Error.captureStackTrace(this, this.constructor);
1331
+ } else {
1332
+ this.stack = (new Error()).stack;
1333
+ }
1334
+
1335
+ this.message = message;
1336
+ this.name = 'AxiosError';
1337
+ code && (this.code = code);
1338
+ config && (this.config = config);
1339
+ request && (this.request = request);
1340
+ response && (this.response = response);
1341
+ }
1342
+
1343
+ utils.inherits(AxiosError, Error, {
1344
+ toJSON: function toJSON() {
1345
+ return {
1346
+ // Standard
1347
+ message: this.message,
1348
+ name: this.name,
1349
+ // Microsoft
1350
+ description: this.description,
1351
+ number: this.number,
1352
+ // Mozilla
1353
+ fileName: this.fileName,
1354
+ lineNumber: this.lineNumber,
1355
+ columnNumber: this.columnNumber,
1356
+ stack: this.stack,
1357
+ // Axios
1358
+ config: utils.toJSONObject(this.config),
1359
+ code: this.code,
1360
+ status: this.response && this.response.status ? this.response.status : null
1361
+ };
1362
+ }
1363
+ });
1364
+
1365
+ const prototype$1 = AxiosError.prototype;
1366
+ const descriptors = {};
1367
+
1368
+ [
1369
+ 'ERR_BAD_OPTION_VALUE',
1370
+ 'ERR_BAD_OPTION',
1371
+ 'ECONNABORTED',
1372
+ 'ETIMEDOUT',
1373
+ 'ERR_NETWORK',
1374
+ 'ERR_FR_TOO_MANY_REDIRECTS',
1375
+ 'ERR_DEPRECATED',
1376
+ 'ERR_BAD_RESPONSE',
1377
+ 'ERR_BAD_REQUEST',
1378
+ 'ERR_CANCELED',
1379
+ 'ERR_NOT_SUPPORT',
1380
+ 'ERR_INVALID_URL'
1381
+ // eslint-disable-next-line func-names
1382
+ ].forEach(code => {
1383
+ descriptors[code] = {value: code};
1384
+ });
1385
+
1386
+ Object.defineProperties(AxiosError, descriptors);
1387
+ Object.defineProperty(prototype$1, 'isAxiosError', {value: true});
1388
+
1389
+ // eslint-disable-next-line func-names
1390
+ AxiosError.from = (error, code, config, request, response, customProps) => {
1391
+ const axiosError = Object.create(prototype$1);
1392
+
1393
+ utils.toFlatObject(error, axiosError, function filter(obj) {
1394
+ return obj !== Error.prototype;
1395
+ }, prop => {
1396
+ return prop !== 'isAxiosError';
1397
+ });
1398
+
1399
+ AxiosError.call(axiosError, error.message, code, config, request, response);
1400
+
1401
+ axiosError.cause = error;
1402
+
1403
+ axiosError.name = error.name;
1404
+
1405
+ customProps && Object.assign(axiosError, customProps);
1406
+
1407
+ return axiosError;
1408
+ };
1409
+
1410
+ // eslint-disable-next-line strict
1411
+ var httpAdapter = null;
1412
+
1413
+ /**
1414
+ * Determines if the given thing is a array or js object.
1415
+ *
1416
+ * @param {string} thing - The object or array to be visited.
1417
+ *
1418
+ * @returns {boolean}
1419
+ */
1420
+ function isVisitable(thing) {
1421
+ return utils.isPlainObject(thing) || utils.isArray(thing);
1422
+ }
1423
+
1424
+ /**
1425
+ * It removes the brackets from the end of a string
1426
+ *
1427
+ * @param {string} key - The key of the parameter.
1428
+ *
1429
+ * @returns {string} the key without the brackets.
1430
+ */
1431
+ function removeBrackets(key) {
1432
+ return utils.endsWith(key, '[]') ? key.slice(0, -2) : key;
1433
+ }
1434
+
1435
+ /**
1436
+ * It takes a path, a key, and a boolean, and returns a string
1437
+ *
1438
+ * @param {string} path - The path to the current key.
1439
+ * @param {string} key - The key of the current object being iterated over.
1440
+ * @param {string} dots - If true, the key will be rendered with dots instead of brackets.
1441
+ *
1442
+ * @returns {string} The path to the current key.
1443
+ */
1444
+ function renderKey(path, key, dots) {
1445
+ if (!path) return key;
1446
+ return path.concat(key).map(function each(token, i) {
1447
+ // eslint-disable-next-line no-param-reassign
1448
+ token = removeBrackets(token);
1449
+ return !dots && i ? '[' + token + ']' : token;
1450
+ }).join(dots ? '.' : '');
1451
+ }
1452
+
1453
+ /**
1454
+ * If the array is an array and none of its elements are visitable, then it's a flat array.
1455
+ *
1456
+ * @param {Array<any>} arr - The array to check
1457
+ *
1458
+ * @returns {boolean}
1459
+ */
1460
+ function isFlatArray(arr) {
1461
+ return utils.isArray(arr) && !arr.some(isVisitable);
1462
+ }
1463
+
1464
+ const predicates = utils.toFlatObject(utils, {}, null, function filter(prop) {
1465
+ return /^is[A-Z]/.test(prop);
1466
+ });
1467
+
1468
+ /**
1469
+ * Convert a data object to FormData
1470
+ *
1471
+ * @param {Object} obj
1472
+ * @param {?Object} [formData]
1473
+ * @param {?Object} [options]
1474
+ * @param {Function} [options.visitor]
1475
+ * @param {Boolean} [options.metaTokens = true]
1476
+ * @param {Boolean} [options.dots = false]
1477
+ * @param {?Boolean} [options.indexes = false]
1478
+ *
1479
+ * @returns {Object}
1480
+ **/
1481
+
1482
+ /**
1483
+ * It converts an object into a FormData object
1484
+ *
1485
+ * @param {Object<any, any>} obj - The object to convert to form data.
1486
+ * @param {string} formData - The FormData object to append to.
1487
+ * @param {Object<string, any>} options
1488
+ *
1489
+ * @returns
1490
+ */
1491
+ function toFormData(obj, formData, options) {
1492
+ if (!utils.isObject(obj)) {
1493
+ throw new TypeError('target must be an object');
1494
+ }
1495
+
1496
+ // eslint-disable-next-line no-param-reassign
1497
+ formData = formData || new (FormData)();
1498
+
1499
+ // eslint-disable-next-line no-param-reassign
1500
+ options = utils.toFlatObject(options, {
1501
+ metaTokens: true,
1502
+ dots: false,
1503
+ indexes: false
1504
+ }, false, function defined(option, source) {
1505
+ // eslint-disable-next-line no-eq-null,eqeqeq
1506
+ return !utils.isUndefined(source[option]);
1507
+ });
1508
+
1509
+ const metaTokens = options.metaTokens;
1510
+ // eslint-disable-next-line no-use-before-define
1511
+ const visitor = options.visitor || defaultVisitor;
1512
+ const dots = options.dots;
1513
+ const indexes = options.indexes;
1514
+ const _Blob = options.Blob || typeof Blob !== 'undefined' && Blob;
1515
+ const useBlob = _Blob && utils.isSpecCompliantForm(formData);
1516
+
1517
+ if (!utils.isFunction(visitor)) {
1518
+ throw new TypeError('visitor must be a function');
1519
+ }
1520
+
1521
+ function convertValue(value) {
1522
+ if (value === null) return '';
1523
+
1524
+ if (utils.isDate(value)) {
1525
+ return value.toISOString();
1526
+ }
1527
+
1528
+ if (!useBlob && utils.isBlob(value)) {
1529
+ throw new AxiosError('Blob is not supported. Use a Buffer instead.');
1530
+ }
1531
+
1532
+ if (utils.isArrayBuffer(value) || utils.isTypedArray(value)) {
1533
+ return useBlob && typeof Blob === 'function' ? new Blob([value]) : Buffer.from(value);
1534
+ }
1535
+
1536
+ return value;
1537
+ }
1538
+
1539
+ /**
1540
+ * Default visitor.
1541
+ *
1542
+ * @param {*} value
1543
+ * @param {String|Number} key
1544
+ * @param {Array<String|Number>} path
1545
+ * @this {FormData}
1546
+ *
1547
+ * @returns {boolean} return true to visit the each prop of the value recursively
1548
+ */
1549
+ function defaultVisitor(value, key, path) {
1550
+ let arr = value;
1551
+
1552
+ if (value && !path && typeof value === 'object') {
1553
+ if (utils.endsWith(key, '{}')) {
1554
+ // eslint-disable-next-line no-param-reassign
1555
+ key = metaTokens ? key : key.slice(0, -2);
1556
+ // eslint-disable-next-line no-param-reassign
1557
+ value = JSON.stringify(value);
1558
+ } else if (
1559
+ (utils.isArray(value) && isFlatArray(value)) ||
1560
+ ((utils.isFileList(value) || utils.endsWith(key, '[]')) && (arr = utils.toArray(value))
1561
+ )) {
1562
+ // eslint-disable-next-line no-param-reassign
1563
+ key = removeBrackets(key);
1564
+
1565
+ arr.forEach(function each(el, index) {
1566
+ !(utils.isUndefined(el) || el === null) && formData.append(
1567
+ // eslint-disable-next-line no-nested-ternary
1568
+ indexes === true ? renderKey([key], index, dots) : (indexes === null ? key : key + '[]'),
1569
+ convertValue(el)
1570
+ );
1571
+ });
1572
+ return false;
1573
+ }
1574
+ }
1575
+
1576
+ if (isVisitable(value)) {
1577
+ return true;
1578
+ }
1579
+
1580
+ formData.append(renderKey(path, key, dots), convertValue(value));
1581
+
1582
+ return false;
1583
+ }
1584
+
1585
+ const stack = [];
1586
+
1587
+ const exposedHelpers = Object.assign(predicates, {
1588
+ defaultVisitor,
1589
+ convertValue,
1590
+ isVisitable
1591
+ });
1592
+
1593
+ function build(value, path) {
1594
+ if (utils.isUndefined(value)) return;
1595
+
1596
+ if (stack.indexOf(value) !== -1) {
1597
+ throw Error('Circular reference detected in ' + path.join('.'));
1598
+ }
1599
+
1600
+ stack.push(value);
1601
+
1602
+ utils.forEach(value, function each(el, key) {
1603
+ const result = !(utils.isUndefined(el) || el === null) && visitor.call(
1604
+ formData, el, utils.isString(key) ? key.trim() : key, path, exposedHelpers
1605
+ );
1606
+
1607
+ if (result === true) {
1608
+ build(el, path ? path.concat(key) : [key]);
1609
+ }
1610
+ });
1611
+
1612
+ stack.pop();
1613
+ }
1614
+
1615
+ if (!utils.isObject(obj)) {
1616
+ throw new TypeError('data must be an object');
1617
+ }
1618
+
1619
+ build(obj);
1620
+
1621
+ return formData;
1622
+ }
1623
+
1624
+ /**
1625
+ * It encodes a string by replacing all characters that are not in the unreserved set with
1626
+ * their percent-encoded equivalents
1627
+ *
1628
+ * @param {string} str - The string to encode.
1629
+ *
1630
+ * @returns {string} The encoded string.
1631
+ */
1632
+ function encode$1(str) {
1633
+ const charMap = {
1634
+ '!': '%21',
1635
+ "'": '%27',
1636
+ '(': '%28',
1637
+ ')': '%29',
1638
+ '~': '%7E',
1639
+ '%20': '+',
1640
+ '%00': '\x00'
1641
+ };
1642
+ return encodeURIComponent(str).replace(/[!'()~]|%20|%00/g, function replacer(match) {
1643
+ return charMap[match];
1644
+ });
1645
+ }
1646
+
1647
+ /**
1648
+ * It takes a params object and converts it to a FormData object
1649
+ *
1650
+ * @param {Object<string, any>} params - The parameters to be converted to a FormData object.
1651
+ * @param {Object<string, any>} options - The options object passed to the Axios constructor.
1652
+ *
1653
+ * @returns {void}
1654
+ */
1655
+ function AxiosURLSearchParams(params, options) {
1656
+ this._pairs = [];
1657
+
1658
+ params && toFormData(params, this, options);
1659
+ }
1660
+
1661
+ const prototype = AxiosURLSearchParams.prototype;
1662
+
1663
+ prototype.append = function append(name, value) {
1664
+ this._pairs.push([name, value]);
1665
+ };
1666
+
1667
+ prototype.toString = function toString(encoder) {
1668
+ const _encode = encoder ? function(value) {
1669
+ return encoder.call(this, value, encode$1);
1670
+ } : encode$1;
1671
+
1672
+ return this._pairs.map(function each(pair) {
1673
+ return _encode(pair[0]) + '=' + _encode(pair[1]);
1674
+ }, '').join('&');
1675
+ };
1676
+
1677
+ /**
1678
+ * It replaces all instances of the characters `:`, `$`, `,`, `+`, `[`, and `]` with their
1679
+ * URI encoded counterparts
1680
+ *
1681
+ * @param {string} val The value to be encoded.
1682
+ *
1683
+ * @returns {string} The encoded value.
1684
+ */
1685
+ function encode(val) {
1686
+ return encodeURIComponent(val).
1687
+ replace(/%3A/gi, ':').
1688
+ replace(/%24/g, '$').
1689
+ replace(/%2C/gi, ',').
1690
+ replace(/%20/g, '+').
1691
+ replace(/%5B/gi, '[').
1692
+ replace(/%5D/gi, ']');
1693
+ }
1694
+
1695
+ /**
1696
+ * Build a URL by appending params to the end
1697
+ *
1698
+ * @param {string} url The base of the url (e.g., http://www.google.com)
1699
+ * @param {object} [params] The params to be appended
1700
+ * @param {?object} options
1701
+ *
1702
+ * @returns {string} The formatted url
1703
+ */
1704
+ function buildURL(url, params, options) {
1705
+ /*eslint no-param-reassign:0*/
1706
+ if (!params) {
1707
+ return url;
1708
+ }
1709
+
1710
+ const _encode = options && options.encode || encode;
1711
+
1712
+ const serializeFn = options && options.serialize;
1713
+
1714
+ let serializedParams;
1715
+
1716
+ if (serializeFn) {
1717
+ serializedParams = serializeFn(params, options);
1718
+ } else {
1719
+ serializedParams = utils.isURLSearchParams(params) ?
1720
+ params.toString() :
1721
+ new AxiosURLSearchParams(params, options).toString(_encode);
1722
+ }
1723
+
1724
+ if (serializedParams) {
1725
+ const hashmarkIndex = url.indexOf("#");
1726
+
1727
+ if (hashmarkIndex !== -1) {
1728
+ url = url.slice(0, hashmarkIndex);
1729
+ }
1730
+ url += (url.indexOf('?') === -1 ? '?' : '&') + serializedParams;
1731
+ }
1732
+
1733
+ return url;
1734
+ }
1735
+
1736
+ class InterceptorManager {
1737
+ constructor() {
1738
+ this.handlers = [];
1739
+ }
1740
+
1741
+ /**
1742
+ * Add a new interceptor to the stack
1743
+ *
1744
+ * @param {Function} fulfilled The function to handle `then` for a `Promise`
1745
+ * @param {Function} rejected The function to handle `reject` for a `Promise`
1746
+ *
1747
+ * @return {Number} An ID used to remove interceptor later
1748
+ */
1749
+ use(fulfilled, rejected, options) {
1750
+ this.handlers.push({
1751
+ fulfilled,
1752
+ rejected,
1753
+ synchronous: options ? options.synchronous : false,
1754
+ runWhen: options ? options.runWhen : null
1755
+ });
1756
+ return this.handlers.length - 1;
1757
+ }
1758
+
1759
+ /**
1760
+ * Remove an interceptor from the stack
1761
+ *
1762
+ * @param {Number} id The ID that was returned by `use`
1763
+ *
1764
+ * @returns {Boolean} `true` if the interceptor was removed, `false` otherwise
1765
+ */
1766
+ eject(id) {
1767
+ if (this.handlers[id]) {
1768
+ this.handlers[id] = null;
1769
+ }
1770
+ }
1771
+
1772
+ /**
1773
+ * Clear all interceptors from the stack
1774
+ *
1775
+ * @returns {void}
1776
+ */
1777
+ clear() {
1778
+ if (this.handlers) {
1779
+ this.handlers = [];
1780
+ }
1781
+ }
1782
+
1783
+ /**
1784
+ * Iterate over all the registered interceptors
1785
+ *
1786
+ * This method is particularly useful for skipping over any
1787
+ * interceptors that may have become `null` calling `eject`.
1788
+ *
1789
+ * @param {Function} fn The function to call for each interceptor
1790
+ *
1791
+ * @returns {void}
1792
+ */
1793
+ forEach(fn) {
1794
+ utils.forEach(this.handlers, function forEachHandler(h) {
1795
+ if (h !== null) {
1796
+ fn(h);
1797
+ }
1798
+ });
1799
+ }
1800
+ }
1801
+
1802
+ var InterceptorManager$1 = InterceptorManager;
1803
+
1804
+ var transitionalDefaults = {
1805
+ silentJSONParsing: true,
1806
+ forcedJSONParsing: true,
1807
+ clarifyTimeoutError: false
1808
+ };
1809
+
1810
+ var URLSearchParams$1 = typeof URLSearchParams !== 'undefined' ? URLSearchParams : AxiosURLSearchParams;
1811
+
1812
+ var FormData$1 = typeof FormData !== 'undefined' ? FormData : null;
1813
+
1814
+ var Blob$1 = typeof Blob !== 'undefined' ? Blob : null;
1815
+
1816
+ /**
1817
+ * Determine if we're running in a standard browser environment
1818
+ *
1819
+ * This allows axios to run in a web worker, and react-native.
1820
+ * Both environments support XMLHttpRequest, but not fully standard globals.
1821
+ *
1822
+ * web workers:
1823
+ * typeof window -> undefined
1824
+ * typeof document -> undefined
1825
+ *
1826
+ * react-native:
1827
+ * navigator.product -> 'ReactNative'
1828
+ * nativescript
1829
+ * navigator.product -> 'NativeScript' or 'NS'
1830
+ *
1831
+ * @returns {boolean}
1832
+ */
1833
+ const isStandardBrowserEnv = (() => {
1834
+ let product;
1835
+ if (typeof navigator !== 'undefined' && (
1836
+ (product = navigator.product) === 'ReactNative' ||
1837
+ product === 'NativeScript' ||
1838
+ product === 'NS')
1839
+ ) {
1840
+ return false;
1841
+ }
1842
+
1843
+ return typeof window !== 'undefined' && typeof document !== 'undefined';
1844
+ })();
1845
+
1846
+ /**
1847
+ * Determine if we're running in a standard browser webWorker environment
1848
+ *
1849
+ * Although the `isStandardBrowserEnv` method indicates that
1850
+ * `allows axios to run in a web worker`, the WebWorker will still be
1851
+ * filtered out due to its judgment standard
1852
+ * `typeof window !== 'undefined' && typeof document !== 'undefined'`.
1853
+ * This leads to a problem when axios post `FormData` in webWorker
1854
+ */
1855
+ const isStandardBrowserWebWorkerEnv = (() => {
1856
+ return (
1857
+ typeof WorkerGlobalScope !== 'undefined' &&
1858
+ // eslint-disable-next-line no-undef
1859
+ self instanceof WorkerGlobalScope &&
1860
+ typeof self.importScripts === 'function'
1861
+ );
1862
+ })();
1863
+
1864
+
1865
+ var platform = {
1866
+ isBrowser: true,
1867
+ classes: {
1868
+ URLSearchParams: URLSearchParams$1,
1869
+ FormData: FormData$1,
1870
+ Blob: Blob$1
1871
+ },
1872
+ isStandardBrowserEnv,
1873
+ isStandardBrowserWebWorkerEnv,
1874
+ protocols: ['http', 'https', 'file', 'blob', 'url', 'data']
1875
+ };
1876
+
1877
+ function toURLEncodedForm(data, options) {
1878
+ return toFormData(data, new platform.classes.URLSearchParams(), Object.assign({
1879
+ visitor: function(value, key, path, helpers) {
1880
+ if (platform.isNode && utils.isBuffer(value)) {
1881
+ this.append(key, value.toString('base64'));
1882
+ return false;
1883
+ }
1884
+
1885
+ return helpers.defaultVisitor.apply(this, arguments);
1886
+ }
1887
+ }, options));
1888
+ }
1889
+
1890
+ /**
1891
+ * It takes a string like `foo[x][y][z]` and returns an array like `['foo', 'x', 'y', 'z']
1892
+ *
1893
+ * @param {string} name - The name of the property to get.
1894
+ *
1895
+ * @returns An array of strings.
1896
+ */
1897
+ function parsePropPath(name) {
1898
+ // foo[x][y][z]
1899
+ // foo.x.y.z
1900
+ // foo-x-y-z
1901
+ // foo x y z
1902
+ return utils.matchAll(/\w+|\[(\w*)]/g, name).map(match => {
1903
+ return match[0] === '[]' ? '' : match[1] || match[0];
1904
+ });
1905
+ }
1906
+
1907
+ /**
1908
+ * Convert an array to an object.
1909
+ *
1910
+ * @param {Array<any>} arr - The array to convert to an object.
1911
+ *
1912
+ * @returns An object with the same keys and values as the array.
1913
+ */
1914
+ function arrayToObject(arr) {
1915
+ const obj = {};
1916
+ const keys = Object.keys(arr);
1917
+ let i;
1918
+ const len = keys.length;
1919
+ let key;
1920
+ for (i = 0; i < len; i++) {
1921
+ key = keys[i];
1922
+ obj[key] = arr[key];
1923
+ }
1924
+ return obj;
1925
+ }
1926
+
1927
+ /**
1928
+ * It takes a FormData object and returns a JavaScript object
1929
+ *
1930
+ * @param {string} formData The FormData object to convert to JSON.
1931
+ *
1932
+ * @returns {Object<string, any> | null} The converted object.
1933
+ */
1934
+ function formDataToJSON(formData) {
1935
+ function buildPath(path, value, target, index) {
1936
+ let name = path[index++];
1937
+ const isNumericKey = Number.isFinite(+name);
1938
+ const isLast = index >= path.length;
1939
+ name = !name && utils.isArray(target) ? target.length : name;
1940
+
1941
+ if (isLast) {
1942
+ if (utils.hasOwnProp(target, name)) {
1943
+ target[name] = [target[name], value];
1944
+ } else {
1945
+ target[name] = value;
1946
+ }
1947
+
1948
+ return !isNumericKey;
1949
+ }
1950
+
1951
+ if (!target[name] || !utils.isObject(target[name])) {
1952
+ target[name] = [];
1953
+ }
1954
+
1955
+ const result = buildPath(path, value, target[name], index);
1956
+
1957
+ if (result && utils.isArray(target[name])) {
1958
+ target[name] = arrayToObject(target[name]);
1959
+ }
1960
+
1961
+ return !isNumericKey;
1962
+ }
1963
+
1964
+ if (utils.isFormData(formData) && utils.isFunction(formData.entries)) {
1965
+ const obj = {};
1966
+
1967
+ utils.forEachEntry(formData, (name, value) => {
1968
+ buildPath(parsePropPath(name), value, obj, 0);
1969
+ });
1970
+
1971
+ return obj;
1972
+ }
1973
+
1974
+ return null;
1975
+ }
1976
+
1977
+ const DEFAULT_CONTENT_TYPE = {
1978
+ 'Content-Type': undefined
1979
+ };
1980
+
1981
+ /**
1982
+ * It takes a string, tries to parse it, and if it fails, it returns the stringified version
1983
+ * of the input
1984
+ *
1985
+ * @param {any} rawValue - The value to be stringified.
1986
+ * @param {Function} parser - A function that parses a string into a JavaScript object.
1987
+ * @param {Function} encoder - A function that takes a value and returns a string.
1988
+ *
1989
+ * @returns {string} A stringified version of the rawValue.
1990
+ */
1991
+ function stringifySafely(rawValue, parser, encoder) {
1992
+ if (utils.isString(rawValue)) {
1993
+ try {
1994
+ (parser || JSON.parse)(rawValue);
1995
+ return utils.trim(rawValue);
1996
+ } catch (e) {
1997
+ if (e.name !== 'SyntaxError') {
1998
+ throw e;
1999
+ }
2000
+ }
2001
+ }
2002
+
2003
+ return (encoder || JSON.stringify)(rawValue);
2004
+ }
2005
+
2006
+ const defaults = {
2007
+
2008
+ transitional: transitionalDefaults,
2009
+
2010
+ adapter: ['xhr', 'http'],
2011
+
2012
+ transformRequest: [function transformRequest(data, headers) {
2013
+ const contentType = headers.getContentType() || '';
2014
+ const hasJSONContentType = contentType.indexOf('application/json') > -1;
2015
+ const isObjectPayload = utils.isObject(data);
2016
+
2017
+ if (isObjectPayload && utils.isHTMLForm(data)) {
2018
+ data = new FormData(data);
2019
+ }
2020
+
2021
+ const isFormData = utils.isFormData(data);
2022
+
2023
+ if (isFormData) {
2024
+ if (!hasJSONContentType) {
2025
+ return data;
2026
+ }
2027
+ return hasJSONContentType ? JSON.stringify(formDataToJSON(data)) : data;
2028
+ }
2029
+
2030
+ if (utils.isArrayBuffer(data) ||
2031
+ utils.isBuffer(data) ||
2032
+ utils.isStream(data) ||
2033
+ utils.isFile(data) ||
2034
+ utils.isBlob(data)
2035
+ ) {
2036
+ return data;
2037
+ }
2038
+ if (utils.isArrayBufferView(data)) {
2039
+ return data.buffer;
2040
+ }
2041
+ if (utils.isURLSearchParams(data)) {
2042
+ headers.setContentType('application/x-www-form-urlencoded;charset=utf-8', false);
2043
+ return data.toString();
2044
+ }
2045
+
2046
+ let isFileList;
2047
+
2048
+ if (isObjectPayload) {
2049
+ if (contentType.indexOf('application/x-www-form-urlencoded') > -1) {
2050
+ return toURLEncodedForm(data, this.formSerializer).toString();
2051
+ }
2052
+
2053
+ if ((isFileList = utils.isFileList(data)) || contentType.indexOf('multipart/form-data') > -1) {
2054
+ const _FormData = this.env && this.env.FormData;
2055
+
2056
+ return toFormData(
2057
+ isFileList ? {'files[]': data} : data,
2058
+ _FormData && new _FormData(),
2059
+ this.formSerializer
2060
+ );
2061
+ }
2062
+ }
2063
+
2064
+ if (isObjectPayload || hasJSONContentType ) {
2065
+ headers.setContentType('application/json', false);
2066
+ return stringifySafely(data);
2067
+ }
2068
+
2069
+ return data;
2070
+ }],
2071
+
2072
+ transformResponse: [function transformResponse(data) {
2073
+ const transitional = this.transitional || defaults.transitional;
2074
+ const forcedJSONParsing = transitional && transitional.forcedJSONParsing;
2075
+ const JSONRequested = this.responseType === 'json';
2076
+
2077
+ if (data && utils.isString(data) && ((forcedJSONParsing && !this.responseType) || JSONRequested)) {
2078
+ const silentJSONParsing = transitional && transitional.silentJSONParsing;
2079
+ const strictJSONParsing = !silentJSONParsing && JSONRequested;
2080
+
2081
+ try {
2082
+ return JSON.parse(data);
2083
+ } catch (e) {
2084
+ if (strictJSONParsing) {
2085
+ if (e.name === 'SyntaxError') {
2086
+ throw AxiosError.from(e, AxiosError.ERR_BAD_RESPONSE, this, null, this.response);
2087
+ }
2088
+ throw e;
2089
+ }
2090
+ }
2091
+ }
2092
+
2093
+ return data;
2094
+ }],
2095
+
2096
+ /**
2097
+ * A timeout in milliseconds to abort a request. If set to 0 (default) a
2098
+ * timeout is not created.
2099
+ */
2100
+ timeout: 0,
2101
+
2102
+ xsrfCookieName: 'XSRF-TOKEN',
2103
+ xsrfHeaderName: 'X-XSRF-TOKEN',
2104
+
2105
+ maxContentLength: -1,
2106
+ maxBodyLength: -1,
2107
+
2108
+ env: {
2109
+ FormData: platform.classes.FormData,
2110
+ Blob: platform.classes.Blob
2111
+ },
2112
+
2113
+ validateStatus: function validateStatus(status) {
2114
+ return status >= 200 && status < 300;
2115
+ },
2116
+
2117
+ headers: {
2118
+ common: {
2119
+ 'Accept': 'application/json, text/plain, */*'
2120
+ }
2121
+ }
2122
+ };
2123
+
2124
+ utils.forEach(['delete', 'get', 'head'], function forEachMethodNoData(method) {
2125
+ defaults.headers[method] = {};
2126
+ });
2127
+
2128
+ utils.forEach(['post', 'put', 'patch'], function forEachMethodWithData(method) {
2129
+ defaults.headers[method] = utils.merge(DEFAULT_CONTENT_TYPE);
2130
+ });
2131
+
2132
+ var defaults$1 = defaults;
2133
+
2134
+ // RawAxiosHeaders whose duplicates are ignored by node
2135
+ // c.f. https://nodejs.org/api/http.html#http_message_headers
2136
+ const ignoreDuplicateOf = utils.toObjectSet([
2137
+ 'age', 'authorization', 'content-length', 'content-type', 'etag',
2138
+ 'expires', 'from', 'host', 'if-modified-since', 'if-unmodified-since',
2139
+ 'last-modified', 'location', 'max-forwards', 'proxy-authorization',
2140
+ 'referer', 'retry-after', 'user-agent'
2141
+ ]);
2142
+
2143
+ /**
2144
+ * Parse headers into an object
2145
+ *
2146
+ * ```
2147
+ * Date: Wed, 27 Aug 2014 08:58:49 GMT
2148
+ * Content-Type: application/json
2149
+ * Connection: keep-alive
2150
+ * Transfer-Encoding: chunked
2151
+ * ```
2152
+ *
2153
+ * @param {String} rawHeaders Headers needing to be parsed
2154
+ *
2155
+ * @returns {Object} Headers parsed into an object
2156
+ */
2157
+ var parseHeaders = rawHeaders => {
2158
+ const parsed = {};
2159
+ let key;
2160
+ let val;
2161
+ let i;
2162
+
2163
+ rawHeaders && rawHeaders.split('\n').forEach(function parser(line) {
2164
+ i = line.indexOf(':');
2165
+ key = line.substring(0, i).trim().toLowerCase();
2166
+ val = line.substring(i + 1).trim();
2167
+
2168
+ if (!key || (parsed[key] && ignoreDuplicateOf[key])) {
2169
+ return;
2170
+ }
2171
+
2172
+ if (key === 'set-cookie') {
2173
+ if (parsed[key]) {
2174
+ parsed[key].push(val);
2175
+ } else {
2176
+ parsed[key] = [val];
2177
+ }
2178
+ } else {
2179
+ parsed[key] = parsed[key] ? parsed[key] + ', ' + val : val;
2180
+ }
2181
+ });
2182
+
2183
+ return parsed;
2184
+ };
2185
+
2186
+ const $internals = Symbol('internals');
2187
+
2188
+ function normalizeHeader(header) {
2189
+ return header && String(header).trim().toLowerCase();
2190
+ }
2191
+
2192
+ function normalizeValue(value) {
2193
+ if (value === false || value == null) {
2194
+ return value;
2195
+ }
2196
+
2197
+ return utils.isArray(value) ? value.map(normalizeValue) : String(value);
2198
+ }
2199
+
2200
+ function parseTokens(str) {
2201
+ const tokens = Object.create(null);
2202
+ const tokensRE = /([^\s,;=]+)\s*(?:=\s*([^,;]+))?/g;
2203
+ let match;
2204
+
2205
+ while ((match = tokensRE.exec(str))) {
2206
+ tokens[match[1]] = match[2];
2207
+ }
2208
+
2209
+ return tokens;
2210
+ }
2211
+
2212
+ const isValidHeaderName = (str) => /^[-_a-zA-Z0-9^`|~,!#$%&'*+.]+$/.test(str.trim());
2213
+
2214
+ function matchHeaderValue(context, value, header, filter, isHeaderNameFilter) {
2215
+ if (utils.isFunction(filter)) {
2216
+ return filter.call(this, value, header);
2217
+ }
2218
+
2219
+ if (isHeaderNameFilter) {
2220
+ value = header;
2221
+ }
2222
+
2223
+ if (!utils.isString(value)) return;
2224
+
2225
+ if (utils.isString(filter)) {
2226
+ return value.indexOf(filter) !== -1;
2227
+ }
2228
+
2229
+ if (utils.isRegExp(filter)) {
2230
+ return filter.test(value);
2231
+ }
2232
+ }
2233
+
2234
+ function formatHeader(header) {
2235
+ return header.trim()
2236
+ .toLowerCase().replace(/([a-z\d])(\w*)/g, (w, char, str) => {
2237
+ return char.toUpperCase() + str;
2238
+ });
2239
+ }
2240
+
2241
+ function buildAccessors(obj, header) {
2242
+ const accessorName = utils.toCamelCase(' ' + header);
2243
+
2244
+ ['get', 'set', 'has'].forEach(methodName => {
2245
+ Object.defineProperty(obj, methodName + accessorName, {
2246
+ value: function(arg1, arg2, arg3) {
2247
+ return this[methodName].call(this, header, arg1, arg2, arg3);
2248
+ },
2249
+ configurable: true
2250
+ });
2251
+ });
2252
+ }
2253
+
2254
+ class AxiosHeaders {
2255
+ constructor(headers) {
2256
+ headers && this.set(headers);
2257
+ }
2258
+
2259
+ set(header, valueOrRewrite, rewrite) {
2260
+ const self = this;
2261
+
2262
+ function setHeader(_value, _header, _rewrite) {
2263
+ const lHeader = normalizeHeader(_header);
2264
+
2265
+ if (!lHeader) {
2266
+ throw new Error('header name must be a non-empty string');
2267
+ }
2268
+
2269
+ const key = utils.findKey(self, lHeader);
2270
+
2271
+ if(!key || self[key] === undefined || _rewrite === true || (_rewrite === undefined && self[key] !== false)) {
2272
+ self[key || _header] = normalizeValue(_value);
2273
+ }
2274
+ }
2275
+
2276
+ const setHeaders = (headers, _rewrite) =>
2277
+ utils.forEach(headers, (_value, _header) => setHeader(_value, _header, _rewrite));
2278
+
2279
+ if (utils.isPlainObject(header) || header instanceof this.constructor) {
2280
+ setHeaders(header, valueOrRewrite);
2281
+ } else if(utils.isString(header) && (header = header.trim()) && !isValidHeaderName(header)) {
2282
+ setHeaders(parseHeaders(header), valueOrRewrite);
2283
+ } else {
2284
+ header != null && setHeader(valueOrRewrite, header, rewrite);
2285
+ }
2286
+
2287
+ return this;
2288
+ }
2289
+
2290
+ get(header, parser) {
2291
+ header = normalizeHeader(header);
2292
+
2293
+ if (header) {
2294
+ const key = utils.findKey(this, header);
2295
+
2296
+ if (key) {
2297
+ const value = this[key];
2298
+
2299
+ if (!parser) {
2300
+ return value;
2301
+ }
2302
+
2303
+ if (parser === true) {
2304
+ return parseTokens(value);
2305
+ }
2306
+
2307
+ if (utils.isFunction(parser)) {
2308
+ return parser.call(this, value, key);
2309
+ }
2310
+
2311
+ if (utils.isRegExp(parser)) {
2312
+ return parser.exec(value);
2313
+ }
2314
+
2315
+ throw new TypeError('parser must be boolean|regexp|function');
2316
+ }
2317
+ }
2318
+ }
2319
+
2320
+ has(header, matcher) {
2321
+ header = normalizeHeader(header);
2322
+
2323
+ if (header) {
2324
+ const key = utils.findKey(this, header);
2325
+
2326
+ return !!(key && this[key] !== undefined && (!matcher || matchHeaderValue(this, this[key], key, matcher)));
2327
+ }
2328
+
2329
+ return false;
2330
+ }
2331
+
2332
+ delete(header, matcher) {
2333
+ const self = this;
2334
+ let deleted = false;
2335
+
2336
+ function deleteHeader(_header) {
2337
+ _header = normalizeHeader(_header);
2338
+
2339
+ if (_header) {
2340
+ const key = utils.findKey(self, _header);
2341
+
2342
+ if (key && (!matcher || matchHeaderValue(self, self[key], key, matcher))) {
2343
+ delete self[key];
2344
+
2345
+ deleted = true;
2346
+ }
2347
+ }
2348
+ }
2349
+
2350
+ if (utils.isArray(header)) {
2351
+ header.forEach(deleteHeader);
2352
+ } else {
2353
+ deleteHeader(header);
2354
+ }
2355
+
2356
+ return deleted;
2357
+ }
2358
+
2359
+ clear(matcher) {
2360
+ const keys = Object.keys(this);
2361
+ let i = keys.length;
2362
+ let deleted = false;
2363
+
2364
+ while (i--) {
2365
+ const key = keys[i];
2366
+ if(!matcher || matchHeaderValue(this, this[key], key, matcher, true)) {
2367
+ delete this[key];
2368
+ deleted = true;
2369
+ }
2370
+ }
2371
+
2372
+ return deleted;
2373
+ }
2374
+
2375
+ normalize(format) {
2376
+ const self = this;
2377
+ const headers = {};
2378
+
2379
+ utils.forEach(this, (value, header) => {
2380
+ const key = utils.findKey(headers, header);
2381
+
2382
+ if (key) {
2383
+ self[key] = normalizeValue(value);
2384
+ delete self[header];
2385
+ return;
2386
+ }
2387
+
2388
+ const normalized = format ? formatHeader(header) : String(header).trim();
2389
+
2390
+ if (normalized !== header) {
2391
+ delete self[header];
2392
+ }
2393
+
2394
+ self[normalized] = normalizeValue(value);
2395
+
2396
+ headers[normalized] = true;
2397
+ });
2398
+
2399
+ return this;
2400
+ }
2401
+
2402
+ concat(...targets) {
2403
+ return this.constructor.concat(this, ...targets);
2404
+ }
2405
+
2406
+ toJSON(asStrings) {
2407
+ const obj = Object.create(null);
2408
+
2409
+ utils.forEach(this, (value, header) => {
2410
+ value != null && value !== false && (obj[header] = asStrings && utils.isArray(value) ? value.join(', ') : value);
2411
+ });
2412
+
2413
+ return obj;
2414
+ }
2415
+
2416
+ [Symbol.iterator]() {
2417
+ return Object.entries(this.toJSON())[Symbol.iterator]();
2418
+ }
2419
+
2420
+ toString() {
2421
+ return Object.entries(this.toJSON()).map(([header, value]) => header + ': ' + value).join('\n');
2422
+ }
2423
+
2424
+ get [Symbol.toStringTag]() {
2425
+ return 'AxiosHeaders';
2426
+ }
2427
+
2428
+ static from(thing) {
2429
+ return thing instanceof this ? thing : new this(thing);
2430
+ }
2431
+
2432
+ static concat(first, ...targets) {
2433
+ const computed = new this(first);
2434
+
2435
+ targets.forEach((target) => computed.set(target));
2436
+
2437
+ return computed;
2438
+ }
2439
+
2440
+ static accessor(header) {
2441
+ const internals = this[$internals] = (this[$internals] = {
2442
+ accessors: {}
2443
+ });
2444
+
2445
+ const accessors = internals.accessors;
2446
+ const prototype = this.prototype;
2447
+
2448
+ function defineAccessor(_header) {
2449
+ const lHeader = normalizeHeader(_header);
2450
+
2451
+ if (!accessors[lHeader]) {
2452
+ buildAccessors(prototype, _header);
2453
+ accessors[lHeader] = true;
2454
+ }
2455
+ }
2456
+
2457
+ utils.isArray(header) ? header.forEach(defineAccessor) : defineAccessor(header);
2458
+
2459
+ return this;
2460
+ }
2461
+ }
2462
+
2463
+ AxiosHeaders.accessor(['Content-Type', 'Content-Length', 'Accept', 'Accept-Encoding', 'User-Agent', 'Authorization']);
2464
+
2465
+ utils.freezeMethods(AxiosHeaders.prototype);
2466
+ utils.freezeMethods(AxiosHeaders);
2467
+
2468
+ var AxiosHeaders$1 = AxiosHeaders;
2469
+
2470
+ /**
2471
+ * Transform the data for a request or a response
2472
+ *
2473
+ * @param {Array|Function} fns A single function or Array of functions
2474
+ * @param {?Object} response The response object
2475
+ *
2476
+ * @returns {*} The resulting transformed data
2477
+ */
2478
+ function transformData(fns, response) {
2479
+ const config = this || defaults$1;
2480
+ const context = response || config;
2481
+ const headers = AxiosHeaders$1.from(context.headers);
2482
+ let data = context.data;
2483
+
2484
+ utils.forEach(fns, function transform(fn) {
2485
+ data = fn.call(config, data, headers.normalize(), response ? response.status : undefined);
2486
+ });
2487
+
2488
+ headers.normalize();
2489
+
2490
+ return data;
2491
+ }
2492
+
2493
+ function isCancel(value) {
2494
+ return !!(value && value.__CANCEL__);
2495
+ }
2496
+
2497
+ /**
2498
+ * A `CanceledError` is an object that is thrown when an operation is canceled.
2499
+ *
2500
+ * @param {string=} message The message.
2501
+ * @param {Object=} config The config.
2502
+ * @param {Object=} request The request.
2503
+ *
2504
+ * @returns {CanceledError} The created error.
2505
+ */
2506
+ function CanceledError(message, config, request) {
2507
+ // eslint-disable-next-line no-eq-null,eqeqeq
2508
+ AxiosError.call(this, message == null ? 'canceled' : message, AxiosError.ERR_CANCELED, config, request);
2509
+ this.name = 'CanceledError';
2510
+ }
2511
+
2512
+ utils.inherits(CanceledError, AxiosError, {
2513
+ __CANCEL__: true
2514
+ });
2515
+
2516
+ /**
2517
+ * Resolve or reject a Promise based on response status.
2518
+ *
2519
+ * @param {Function} resolve A function that resolves the promise.
2520
+ * @param {Function} reject A function that rejects the promise.
2521
+ * @param {object} response The response.
2522
+ *
2523
+ * @returns {object} The response.
2524
+ */
2525
+ function settle(resolve, reject, response) {
2526
+ const validateStatus = response.config.validateStatus;
2527
+ if (!response.status || !validateStatus || validateStatus(response.status)) {
2528
+ resolve(response);
2529
+ } else {
2530
+ reject(new AxiosError(
2531
+ 'Request failed with status code ' + response.status,
2532
+ [AxiosError.ERR_BAD_REQUEST, AxiosError.ERR_BAD_RESPONSE][Math.floor(response.status / 100) - 4],
2533
+ response.config,
2534
+ response.request,
2535
+ response
2536
+ ));
2537
+ }
2538
+ }
2539
+
2540
+ var cookies = platform.isStandardBrowserEnv ?
2541
+
2542
+ // Standard browser envs support document.cookie
2543
+ (function standardBrowserEnv() {
2544
+ return {
2545
+ write: function write(name, value, expires, path, domain, secure) {
2546
+ const cookie = [];
2547
+ cookie.push(name + '=' + encodeURIComponent(value));
2548
+
2549
+ if (utils.isNumber(expires)) {
2550
+ cookie.push('expires=' + new Date(expires).toGMTString());
2551
+ }
2552
+
2553
+ if (utils.isString(path)) {
2554
+ cookie.push('path=' + path);
2555
+ }
2556
+
2557
+ if (utils.isString(domain)) {
2558
+ cookie.push('domain=' + domain);
2559
+ }
2560
+
2561
+ if (secure === true) {
2562
+ cookie.push('secure');
2563
+ }
2564
+
2565
+ document.cookie = cookie.join('; ');
2566
+ },
2567
+
2568
+ read: function read(name) {
2569
+ const match = document.cookie.match(new RegExp('(^|;\\s*)(' + name + ')=([^;]*)'));
2570
+ return (match ? decodeURIComponent(match[3]) : null);
2571
+ },
2572
+
2573
+ remove: function remove(name) {
2574
+ this.write(name, '', Date.now() - 86400000);
2575
+ }
2576
+ };
2577
+ })() :
2578
+
2579
+ // Non standard browser env (web workers, react-native) lack needed support.
2580
+ (function nonStandardBrowserEnv() {
2581
+ return {
2582
+ write: function write() {},
2583
+ read: function read() { return null; },
2584
+ remove: function remove() {}
2585
+ };
2586
+ })();
2587
+
2588
+ /**
2589
+ * Determines whether the specified URL is absolute
2590
+ *
2591
+ * @param {string} url The URL to test
2592
+ *
2593
+ * @returns {boolean} True if the specified URL is absolute, otherwise false
2594
+ */
2595
+ function isAbsoluteURL(url) {
2596
+ // A URL is considered absolute if it begins with "<scheme>://" or "//" (protocol-relative URL).
2597
+ // RFC 3986 defines scheme name as a sequence of characters beginning with a letter and followed
2598
+ // by any combination of letters, digits, plus, period, or hyphen.
2599
+ return /^([a-z][a-z\d+\-.]*:)?\/\//i.test(url);
2600
+ }
2601
+
2602
+ /**
2603
+ * Creates a new URL by combining the specified URLs
2604
+ *
2605
+ * @param {string} baseURL The base URL
2606
+ * @param {string} relativeURL The relative URL
2607
+ *
2608
+ * @returns {string} The combined URL
2609
+ */
2610
+ function combineURLs(baseURL, relativeURL) {
2611
+ return relativeURL
2612
+ ? baseURL.replace(/\/+$/, '') + '/' + relativeURL.replace(/^\/+/, '')
2613
+ : baseURL;
2614
+ }
2615
+
2616
+ /**
2617
+ * Creates a new URL by combining the baseURL with the requestedURL,
2618
+ * only when the requestedURL is not already an absolute URL.
2619
+ * If the requestURL is absolute, this function returns the requestedURL untouched.
2620
+ *
2621
+ * @param {string} baseURL The base URL
2622
+ * @param {string} requestedURL Absolute or relative URL to combine
2623
+ *
2624
+ * @returns {string} The combined full path
2625
+ */
2626
+ function buildFullPath(baseURL, requestedURL) {
2627
+ if (baseURL && !isAbsoluteURL(requestedURL)) {
2628
+ return combineURLs(baseURL, requestedURL);
2629
+ }
2630
+ return requestedURL;
2631
+ }
2632
+
2633
+ var isURLSameOrigin = platform.isStandardBrowserEnv ?
2634
+
2635
+ // Standard browser envs have full support of the APIs needed to test
2636
+ // whether the request URL is of the same origin as current location.
2637
+ (function standardBrowserEnv() {
2638
+ const msie = /(msie|trident)/i.test(navigator.userAgent);
2639
+ const urlParsingNode = document.createElement('a');
2640
+ let originURL;
2641
+
2642
+ /**
2643
+ * Parse a URL to discover it's components
2644
+ *
2645
+ * @param {String} url The URL to be parsed
2646
+ * @returns {Object}
2647
+ */
2648
+ function resolveURL(url) {
2649
+ let href = url;
2650
+
2651
+ if (msie) {
2652
+ // IE needs attribute set twice to normalize properties
2653
+ urlParsingNode.setAttribute('href', href);
2654
+ href = urlParsingNode.href;
2655
+ }
2656
+
2657
+ urlParsingNode.setAttribute('href', href);
2658
+
2659
+ // urlParsingNode provides the UrlUtils interface - http://url.spec.whatwg.org/#urlutils
2660
+ return {
2661
+ href: urlParsingNode.href,
2662
+ protocol: urlParsingNode.protocol ? urlParsingNode.protocol.replace(/:$/, '') : '',
2663
+ host: urlParsingNode.host,
2664
+ search: urlParsingNode.search ? urlParsingNode.search.replace(/^\?/, '') : '',
2665
+ hash: urlParsingNode.hash ? urlParsingNode.hash.replace(/^#/, '') : '',
2666
+ hostname: urlParsingNode.hostname,
2667
+ port: urlParsingNode.port,
2668
+ pathname: (urlParsingNode.pathname.charAt(0) === '/') ?
2669
+ urlParsingNode.pathname :
2670
+ '/' + urlParsingNode.pathname
2671
+ };
2672
+ }
2673
+
2674
+ originURL = resolveURL(window.location.href);
2675
+
2676
+ /**
2677
+ * Determine if a URL shares the same origin as the current location
2678
+ *
2679
+ * @param {String} requestURL The URL to test
2680
+ * @returns {boolean} True if URL shares the same origin, otherwise false
2681
+ */
2682
+ return function isURLSameOrigin(requestURL) {
2683
+ const parsed = (utils.isString(requestURL)) ? resolveURL(requestURL) : requestURL;
2684
+ return (parsed.protocol === originURL.protocol &&
2685
+ parsed.host === originURL.host);
2686
+ };
2687
+ })() :
2688
+
2689
+ // Non standard browser envs (web workers, react-native) lack needed support.
2690
+ (function nonStandardBrowserEnv() {
2691
+ return function isURLSameOrigin() {
2692
+ return true;
2693
+ };
2694
+ })();
2695
+
2696
+ function parseProtocol(url) {
2697
+ const match = /^([-+\w]{1,25})(:?\/\/|:)/.exec(url);
2698
+ return match && match[1] || '';
2699
+ }
2700
+
2701
+ /**
2702
+ * Calculate data maxRate
2703
+ * @param {Number} [samplesCount= 10]
2704
+ * @param {Number} [min= 1000]
2705
+ * @returns {Function}
2706
+ */
2707
+ function speedometer(samplesCount, min) {
2708
+ samplesCount = samplesCount || 10;
2709
+ const bytes = new Array(samplesCount);
2710
+ const timestamps = new Array(samplesCount);
2711
+ let head = 0;
2712
+ let tail = 0;
2713
+ let firstSampleTS;
2714
+
2715
+ min = min !== undefined ? min : 1000;
2716
+
2717
+ return function push(chunkLength) {
2718
+ const now = Date.now();
2719
+
2720
+ const startedAt = timestamps[tail];
2721
+
2722
+ if (!firstSampleTS) {
2723
+ firstSampleTS = now;
2724
+ }
2725
+
2726
+ bytes[head] = chunkLength;
2727
+ timestamps[head] = now;
2728
+
2729
+ let i = tail;
2730
+ let bytesCount = 0;
2731
+
2732
+ while (i !== head) {
2733
+ bytesCount += bytes[i++];
2734
+ i = i % samplesCount;
2735
+ }
2736
+
2737
+ head = (head + 1) % samplesCount;
2738
+
2739
+ if (head === tail) {
2740
+ tail = (tail + 1) % samplesCount;
2741
+ }
2742
+
2743
+ if (now - firstSampleTS < min) {
2744
+ return;
2745
+ }
2746
+
2747
+ const passed = startedAt && now - startedAt;
2748
+
2749
+ return passed ? Math.round(bytesCount * 1000 / passed) : undefined;
2750
+ };
2751
+ }
2752
+
2753
+ function progressEventReducer(listener, isDownloadStream) {
2754
+ let bytesNotified = 0;
2755
+ const _speedometer = speedometer(50, 250);
2756
+
2757
+ return e => {
2758
+ const loaded = e.loaded;
2759
+ const total = e.lengthComputable ? e.total : undefined;
2760
+ const progressBytes = loaded - bytesNotified;
2761
+ const rate = _speedometer(progressBytes);
2762
+ const inRange = loaded <= total;
2763
+
2764
+ bytesNotified = loaded;
2765
+
2766
+ const data = {
2767
+ loaded,
2768
+ total,
2769
+ progress: total ? (loaded / total) : undefined,
2770
+ bytes: progressBytes,
2771
+ rate: rate ? rate : undefined,
2772
+ estimated: rate && total && inRange ? (total - loaded) / rate : undefined,
2773
+ event: e
2774
+ };
2775
+
2776
+ data[isDownloadStream ? 'download' : 'upload'] = true;
2777
+
2778
+ listener(data);
2779
+ };
2780
+ }
2781
+
2782
+ const isXHRAdapterSupported = typeof XMLHttpRequest !== 'undefined';
2783
+
2784
+ var xhrAdapter = isXHRAdapterSupported && function (config) {
2785
+ return new Promise(function dispatchXhrRequest(resolve, reject) {
2786
+ let requestData = config.data;
2787
+ const requestHeaders = AxiosHeaders$1.from(config.headers).normalize();
2788
+ const responseType = config.responseType;
2789
+ let onCanceled;
2790
+ function done() {
2791
+ if (config.cancelToken) {
2792
+ config.cancelToken.unsubscribe(onCanceled);
2793
+ }
2794
+
2795
+ if (config.signal) {
2796
+ config.signal.removeEventListener('abort', onCanceled);
2797
+ }
2798
+ }
2799
+
2800
+ if (utils.isFormData(requestData)) {
2801
+ if (platform.isStandardBrowserEnv || platform.isStandardBrowserWebWorkerEnv) {
2802
+ requestHeaders.setContentType(false); // Let the browser set it
2803
+ } else {
2804
+ requestHeaders.setContentType('multipart/form-data;', false); // mobile/desktop app frameworks
2805
+ }
2806
+ }
2807
+
2808
+ let request = new XMLHttpRequest();
2809
+
2810
+ // HTTP basic authentication
2811
+ if (config.auth) {
2812
+ const username = config.auth.username || '';
2813
+ const password = config.auth.password ? unescape(encodeURIComponent(config.auth.password)) : '';
2814
+ requestHeaders.set('Authorization', 'Basic ' + btoa(username + ':' + password));
2815
+ }
2816
+
2817
+ const fullPath = buildFullPath(config.baseURL, config.url);
2818
+
2819
+ request.open(config.method.toUpperCase(), buildURL(fullPath, config.params, config.paramsSerializer), true);
2820
+
2821
+ // Set the request timeout in MS
2822
+ request.timeout = config.timeout;
2823
+
2824
+ function onloadend() {
2825
+ if (!request) {
2826
+ return;
2827
+ }
2828
+ // Prepare the response
2829
+ const responseHeaders = AxiosHeaders$1.from(
2830
+ 'getAllResponseHeaders' in request && request.getAllResponseHeaders()
2831
+ );
2832
+ const responseData = !responseType || responseType === 'text' || responseType === 'json' ?
2833
+ request.responseText : request.response;
2834
+ const response = {
2835
+ data: responseData,
2836
+ status: request.status,
2837
+ statusText: request.statusText,
2838
+ headers: responseHeaders,
2839
+ config,
2840
+ request
2841
+ };
2842
+
2843
+ settle(function _resolve(value) {
2844
+ resolve(value);
2845
+ done();
2846
+ }, function _reject(err) {
2847
+ reject(err);
2848
+ done();
2849
+ }, response);
2850
+
2851
+ // Clean up request
2852
+ request = null;
2853
+ }
2854
+
2855
+ if ('onloadend' in request) {
2856
+ // Use onloadend if available
2857
+ request.onloadend = onloadend;
2858
+ } else {
2859
+ // Listen for ready state to emulate onloadend
2860
+ request.onreadystatechange = function handleLoad() {
2861
+ if (!request || request.readyState !== 4) {
2862
+ return;
2863
+ }
2864
+
2865
+ // The request errored out and we didn't get a response, this will be
2866
+ // handled by onerror instead
2867
+ // With one exception: request that using file: protocol, most browsers
2868
+ // will return status as 0 even though it's a successful request
2869
+ if (request.status === 0 && !(request.responseURL && request.responseURL.indexOf('file:') === 0)) {
2870
+ return;
2871
+ }
2872
+ // readystate handler is calling before onerror or ontimeout handlers,
2873
+ // so we should call onloadend on the next 'tick'
2874
+ setTimeout(onloadend);
2875
+ };
2876
+ }
2877
+
2878
+ // Handle browser request cancellation (as opposed to a manual cancellation)
2879
+ request.onabort = function handleAbort() {
2880
+ if (!request) {
2881
+ return;
2882
+ }
2883
+
2884
+ reject(new AxiosError('Request aborted', AxiosError.ECONNABORTED, config, request));
2885
+
2886
+ // Clean up request
2887
+ request = null;
2888
+ };
2889
+
2890
+ // Handle low level network errors
2891
+ request.onerror = function handleError() {
2892
+ // Real errors are hidden from us by the browser
2893
+ // onerror should only fire if it's a network error
2894
+ reject(new AxiosError('Network Error', AxiosError.ERR_NETWORK, config, request));
2895
+
2896
+ // Clean up request
2897
+ request = null;
2898
+ };
2899
+
2900
+ // Handle timeout
2901
+ request.ontimeout = function handleTimeout() {
2902
+ let timeoutErrorMessage = config.timeout ? 'timeout of ' + config.timeout + 'ms exceeded' : 'timeout exceeded';
2903
+ const transitional = config.transitional || transitionalDefaults;
2904
+ if (config.timeoutErrorMessage) {
2905
+ timeoutErrorMessage = config.timeoutErrorMessage;
2906
+ }
2907
+ reject(new AxiosError(
2908
+ timeoutErrorMessage,
2909
+ transitional.clarifyTimeoutError ? AxiosError.ETIMEDOUT : AxiosError.ECONNABORTED,
2910
+ config,
2911
+ request));
2912
+
2913
+ // Clean up request
2914
+ request = null;
2915
+ };
2916
+
2917
+ // Add xsrf header
2918
+ // This is only done if running in a standard browser environment.
2919
+ // Specifically not if we're in a web worker, or react-native.
2920
+ if (platform.isStandardBrowserEnv) {
2921
+ // Add xsrf header
2922
+ const xsrfValue = (config.withCredentials || isURLSameOrigin(fullPath))
2923
+ && config.xsrfCookieName && cookies.read(config.xsrfCookieName);
2924
+
2925
+ if (xsrfValue) {
2926
+ requestHeaders.set(config.xsrfHeaderName, xsrfValue);
2927
+ }
2928
+ }
2929
+
2930
+ // Remove Content-Type if data is undefined
2931
+ requestData === undefined && requestHeaders.setContentType(null);
2932
+
2933
+ // Add headers to the request
2934
+ if ('setRequestHeader' in request) {
2935
+ utils.forEach(requestHeaders.toJSON(), function setRequestHeader(val, key) {
2936
+ request.setRequestHeader(key, val);
2937
+ });
2938
+ }
2939
+
2940
+ // Add withCredentials to request if needed
2941
+ if (!utils.isUndefined(config.withCredentials)) {
2942
+ request.withCredentials = !!config.withCredentials;
2943
+ }
2944
+
2945
+ // Add responseType to request if needed
2946
+ if (responseType && responseType !== 'json') {
2947
+ request.responseType = config.responseType;
2948
+ }
2949
+
2950
+ // Handle progress if needed
2951
+ if (typeof config.onDownloadProgress === 'function') {
2952
+ request.addEventListener('progress', progressEventReducer(config.onDownloadProgress, true));
2953
+ }
2954
+
2955
+ // Not all browsers support upload events
2956
+ if (typeof config.onUploadProgress === 'function' && request.upload) {
2957
+ request.upload.addEventListener('progress', progressEventReducer(config.onUploadProgress));
2958
+ }
2959
+
2960
+ if (config.cancelToken || config.signal) {
2961
+ // Handle cancellation
2962
+ // eslint-disable-next-line func-names
2963
+ onCanceled = cancel => {
2964
+ if (!request) {
2965
+ return;
2966
+ }
2967
+ reject(!cancel || cancel.type ? new CanceledError(null, config, request) : cancel);
2968
+ request.abort();
2969
+ request = null;
2970
+ };
2971
+
2972
+ config.cancelToken && config.cancelToken.subscribe(onCanceled);
2973
+ if (config.signal) {
2974
+ config.signal.aborted ? onCanceled() : config.signal.addEventListener('abort', onCanceled);
2975
+ }
2976
+ }
2977
+
2978
+ const protocol = parseProtocol(fullPath);
2979
+
2980
+ if (protocol && platform.protocols.indexOf(protocol) === -1) {
2981
+ reject(new AxiosError('Unsupported protocol ' + protocol + ':', AxiosError.ERR_BAD_REQUEST, config));
2982
+ return;
2983
+ }
2984
+
2985
+
2986
+ // Send the request
2987
+ request.send(requestData || null);
2988
+ });
2989
+ };
2990
+
2991
+ const knownAdapters = {
2992
+ http: httpAdapter,
2993
+ xhr: xhrAdapter
2994
+ };
2995
+
2996
+ utils.forEach(knownAdapters, (fn, value) => {
2997
+ if(fn) {
2998
+ try {
2999
+ Object.defineProperty(fn, 'name', {value});
3000
+ } catch (e) {
3001
+ // eslint-disable-next-line no-empty
3002
+ }
3003
+ Object.defineProperty(fn, 'adapterName', {value});
3004
+ }
3005
+ });
3006
+
3007
+ var adapters = {
3008
+ getAdapter: (adapters) => {
3009
+ adapters = utils.isArray(adapters) ? adapters : [adapters];
3010
+
3011
+ const {length} = adapters;
3012
+ let nameOrAdapter;
3013
+ let adapter;
3014
+
3015
+ for (let i = 0; i < length; i++) {
3016
+ nameOrAdapter = adapters[i];
3017
+ if((adapter = utils.isString(nameOrAdapter) ? knownAdapters[nameOrAdapter.toLowerCase()] : nameOrAdapter)) {
3018
+ break;
3019
+ }
3020
+ }
3021
+
3022
+ if (!adapter) {
3023
+ if (adapter === false) {
3024
+ throw new AxiosError(
3025
+ `Adapter ${nameOrAdapter} is not supported by the environment`,
3026
+ 'ERR_NOT_SUPPORT'
3027
+ );
3028
+ }
3029
+
3030
+ throw new Error(
3031
+ utils.hasOwnProp(knownAdapters, nameOrAdapter) ?
3032
+ `Adapter '${nameOrAdapter}' is not available in the build` :
3033
+ `Unknown adapter '${nameOrAdapter}'`
3034
+ );
3035
+ }
3036
+
3037
+ if (!utils.isFunction(adapter)) {
3038
+ throw new TypeError('adapter is not a function');
3039
+ }
3040
+
3041
+ return adapter;
3042
+ },
3043
+ adapters: knownAdapters
3044
+ };
3045
+
3046
+ /**
3047
+ * Throws a `CanceledError` if cancellation has been requested.
3048
+ *
3049
+ * @param {Object} config The config that is to be used for the request
3050
+ *
3051
+ * @returns {void}
3052
+ */
3053
+ function throwIfCancellationRequested(config) {
3054
+ if (config.cancelToken) {
3055
+ config.cancelToken.throwIfRequested();
3056
+ }
3057
+
3058
+ if (config.signal && config.signal.aborted) {
3059
+ throw new CanceledError(null, config);
3060
+ }
3061
+ }
3062
+
3063
+ /**
3064
+ * Dispatch a request to the server using the configured adapter.
3065
+ *
3066
+ * @param {object} config The config that is to be used for the request
3067
+ *
3068
+ * @returns {Promise} The Promise to be fulfilled
3069
+ */
3070
+ function dispatchRequest(config) {
3071
+ throwIfCancellationRequested(config);
3072
+
3073
+ config.headers = AxiosHeaders$1.from(config.headers);
3074
+
3075
+ // Transform request data
3076
+ config.data = transformData.call(
3077
+ config,
3078
+ config.transformRequest
3079
+ );
3080
+
3081
+ if (['post', 'put', 'patch'].indexOf(config.method) !== -1) {
3082
+ config.headers.setContentType('application/x-www-form-urlencoded', false);
3083
+ }
3084
+
3085
+ const adapter = adapters.getAdapter(config.adapter || defaults$1.adapter);
3086
+
3087
+ return adapter(config).then(function onAdapterResolution(response) {
3088
+ throwIfCancellationRequested(config);
3089
+
3090
+ // Transform response data
3091
+ response.data = transformData.call(
3092
+ config,
3093
+ config.transformResponse,
3094
+ response
3095
+ );
3096
+
3097
+ response.headers = AxiosHeaders$1.from(response.headers);
3098
+
3099
+ return response;
3100
+ }, function onAdapterRejection(reason) {
3101
+ if (!isCancel(reason)) {
3102
+ throwIfCancellationRequested(config);
3103
+
3104
+ // Transform response data
3105
+ if (reason && reason.response) {
3106
+ reason.response.data = transformData.call(
3107
+ config,
3108
+ config.transformResponse,
3109
+ reason.response
3110
+ );
3111
+ reason.response.headers = AxiosHeaders$1.from(reason.response.headers);
3112
+ }
3113
+ }
3114
+
3115
+ return Promise.reject(reason);
3116
+ });
3117
+ }
3118
+
3119
+ const headersToObject = (thing) => thing instanceof AxiosHeaders$1 ? thing.toJSON() : thing;
3120
+
3121
+ /**
3122
+ * Config-specific merge-function which creates a new config-object
3123
+ * by merging two configuration objects together.
3124
+ *
3125
+ * @param {Object} config1
3126
+ * @param {Object} config2
3127
+ *
3128
+ * @returns {Object} New object resulting from merging config2 to config1
3129
+ */
3130
+ function mergeConfig(config1, config2) {
3131
+ // eslint-disable-next-line no-param-reassign
3132
+ config2 = config2 || {};
3133
+ const config = {};
3134
+
3135
+ function getMergedValue(target, source, caseless) {
3136
+ if (utils.isPlainObject(target) && utils.isPlainObject(source)) {
3137
+ return utils.merge.call({caseless}, target, source);
3138
+ } else if (utils.isPlainObject(source)) {
3139
+ return utils.merge({}, source);
3140
+ } else if (utils.isArray(source)) {
3141
+ return source.slice();
3142
+ }
3143
+ return source;
3144
+ }
3145
+
3146
+ // eslint-disable-next-line consistent-return
3147
+ function mergeDeepProperties(a, b, caseless) {
3148
+ if (!utils.isUndefined(b)) {
3149
+ return getMergedValue(a, b, caseless);
3150
+ } else if (!utils.isUndefined(a)) {
3151
+ return getMergedValue(undefined, a, caseless);
3152
+ }
3153
+ }
3154
+
3155
+ // eslint-disable-next-line consistent-return
3156
+ function valueFromConfig2(a, b) {
3157
+ if (!utils.isUndefined(b)) {
3158
+ return getMergedValue(undefined, b);
3159
+ }
3160
+ }
3161
+
3162
+ // eslint-disable-next-line consistent-return
3163
+ function defaultToConfig2(a, b) {
3164
+ if (!utils.isUndefined(b)) {
3165
+ return getMergedValue(undefined, b);
3166
+ } else if (!utils.isUndefined(a)) {
3167
+ return getMergedValue(undefined, a);
3168
+ }
3169
+ }
3170
+
3171
+ // eslint-disable-next-line consistent-return
3172
+ function mergeDirectKeys(a, b, prop) {
3173
+ if (prop in config2) {
3174
+ return getMergedValue(a, b);
3175
+ } else if (prop in config1) {
3176
+ return getMergedValue(undefined, a);
3177
+ }
3178
+ }
3179
+
3180
+ const mergeMap = {
3181
+ url: valueFromConfig2,
3182
+ method: valueFromConfig2,
3183
+ data: valueFromConfig2,
3184
+ baseURL: defaultToConfig2,
3185
+ transformRequest: defaultToConfig2,
3186
+ transformResponse: defaultToConfig2,
3187
+ paramsSerializer: defaultToConfig2,
3188
+ timeout: defaultToConfig2,
3189
+ timeoutMessage: defaultToConfig2,
3190
+ withCredentials: defaultToConfig2,
3191
+ adapter: defaultToConfig2,
3192
+ responseType: defaultToConfig2,
3193
+ xsrfCookieName: defaultToConfig2,
3194
+ xsrfHeaderName: defaultToConfig2,
3195
+ onUploadProgress: defaultToConfig2,
3196
+ onDownloadProgress: defaultToConfig2,
3197
+ decompress: defaultToConfig2,
3198
+ maxContentLength: defaultToConfig2,
3199
+ maxBodyLength: defaultToConfig2,
3200
+ beforeRedirect: defaultToConfig2,
3201
+ transport: defaultToConfig2,
3202
+ httpAgent: defaultToConfig2,
3203
+ httpsAgent: defaultToConfig2,
3204
+ cancelToken: defaultToConfig2,
3205
+ socketPath: defaultToConfig2,
3206
+ responseEncoding: defaultToConfig2,
3207
+ validateStatus: mergeDirectKeys,
3208
+ headers: (a, b) => mergeDeepProperties(headersToObject(a), headersToObject(b), true)
3209
+ };
3210
+
3211
+ utils.forEach(Object.keys(Object.assign({}, config1, config2)), function computeConfigValue(prop) {
3212
+ const merge = mergeMap[prop] || mergeDeepProperties;
3213
+ const configValue = merge(config1[prop], config2[prop], prop);
3214
+ (utils.isUndefined(configValue) && merge !== mergeDirectKeys) || (config[prop] = configValue);
3215
+ });
3216
+
3217
+ return config;
3218
+ }
3219
+
3220
+ const VERSION = "1.4.0";
3221
+
3222
+ const validators$1 = {};
3223
+
3224
+ // eslint-disable-next-line func-names
3225
+ ['object', 'boolean', 'number', 'function', 'string', 'symbol'].forEach((type, i) => {
3226
+ validators$1[type] = function validator(thing) {
3227
+ return typeof thing === type || 'a' + (i < 1 ? 'n ' : ' ') + type;
3228
+ };
3229
+ });
3230
+
3231
+ const deprecatedWarnings = {};
3232
+
3233
+ /**
3234
+ * Transitional option validator
3235
+ *
3236
+ * @param {function|boolean?} validator - set to false if the transitional option has been removed
3237
+ * @param {string?} version - deprecated version / removed since version
3238
+ * @param {string?} message - some message with additional info
3239
+ *
3240
+ * @returns {function}
3241
+ */
3242
+ validators$1.transitional = function transitional(validator, version, message) {
3243
+ function formatMessage(opt, desc) {
3244
+ return '[Axios v' + VERSION + '] Transitional option \'' + opt + '\'' + desc + (message ? '. ' + message : '');
3245
+ }
3246
+
3247
+ // eslint-disable-next-line func-names
3248
+ return (value, opt, opts) => {
3249
+ if (validator === false) {
3250
+ throw new AxiosError(
3251
+ formatMessage(opt, ' has been removed' + (version ? ' in ' + version : '')),
3252
+ AxiosError.ERR_DEPRECATED
3253
+ );
3254
+ }
3255
+
3256
+ if (version && !deprecatedWarnings[opt]) {
3257
+ deprecatedWarnings[opt] = true;
3258
+ // eslint-disable-next-line no-console
3259
+ console.warn(
3260
+ formatMessage(
3261
+ opt,
3262
+ ' has been deprecated since v' + version + ' and will be removed in the near future'
3263
+ )
3264
+ );
3265
+ }
3266
+
3267
+ return validator ? validator(value, opt, opts) : true;
3268
+ };
3269
+ };
3270
+
3271
+ /**
3272
+ * Assert object's properties type
3273
+ *
3274
+ * @param {object} options
3275
+ * @param {object} schema
3276
+ * @param {boolean?} allowUnknown
3277
+ *
3278
+ * @returns {object}
3279
+ */
3280
+
3281
+ function assertOptions(options, schema, allowUnknown) {
3282
+ if (typeof options !== 'object') {
3283
+ throw new AxiosError('options must be an object', AxiosError.ERR_BAD_OPTION_VALUE);
3284
+ }
3285
+ const keys = Object.keys(options);
3286
+ let i = keys.length;
3287
+ while (i-- > 0) {
3288
+ const opt = keys[i];
3289
+ const validator = schema[opt];
3290
+ if (validator) {
3291
+ const value = options[opt];
3292
+ const result = value === undefined || validator(value, opt, options);
3293
+ if (result !== true) {
3294
+ throw new AxiosError('option ' + opt + ' must be ' + result, AxiosError.ERR_BAD_OPTION_VALUE);
3295
+ }
3296
+ continue;
3297
+ }
3298
+ if (allowUnknown !== true) {
3299
+ throw new AxiosError('Unknown option ' + opt, AxiosError.ERR_BAD_OPTION);
3300
+ }
3301
+ }
3302
+ }
3303
+
3304
+ var validator = {
3305
+ assertOptions,
3306
+ validators: validators$1
3307
+ };
3308
+
3309
+ const validators = validator.validators;
3310
+
3311
+ /**
3312
+ * Create a new instance of Axios
3313
+ *
3314
+ * @param {Object} instanceConfig The default config for the instance
3315
+ *
3316
+ * @return {Axios} A new instance of Axios
3317
+ */
3318
+ class Axios {
3319
+ constructor(instanceConfig) {
3320
+ this.defaults = instanceConfig;
3321
+ this.interceptors = {
3322
+ request: new InterceptorManager$1(),
3323
+ response: new InterceptorManager$1()
3324
+ };
3325
+ }
3326
+
3327
+ /**
3328
+ * Dispatch a request
3329
+ *
3330
+ * @param {String|Object} configOrUrl The config specific for this request (merged with this.defaults)
3331
+ * @param {?Object} config
3332
+ *
3333
+ * @returns {Promise} The Promise to be fulfilled
3334
+ */
3335
+ request(configOrUrl, config) {
3336
+ /*eslint no-param-reassign:0*/
3337
+ // Allow for axios('example/url'[, config]) a la fetch API
3338
+ if (typeof configOrUrl === 'string') {
3339
+ config = config || {};
3340
+ config.url = configOrUrl;
3341
+ } else {
3342
+ config = configOrUrl || {};
3343
+ }
3344
+
3345
+ config = mergeConfig(this.defaults, config);
3346
+
3347
+ const {transitional, paramsSerializer, headers} = config;
3348
+
3349
+ if (transitional !== undefined) {
3350
+ validator.assertOptions(transitional, {
3351
+ silentJSONParsing: validators.transitional(validators.boolean),
3352
+ forcedJSONParsing: validators.transitional(validators.boolean),
3353
+ clarifyTimeoutError: validators.transitional(validators.boolean)
3354
+ }, false);
3355
+ }
3356
+
3357
+ if (paramsSerializer != null) {
3358
+ if (utils.isFunction(paramsSerializer)) {
3359
+ config.paramsSerializer = {
3360
+ serialize: paramsSerializer
3361
+ };
3362
+ } else {
3363
+ validator.assertOptions(paramsSerializer, {
3364
+ encode: validators.function,
3365
+ serialize: validators.function
3366
+ }, true);
3367
+ }
3368
+ }
3369
+
3370
+ // Set config.method
3371
+ config.method = (config.method || this.defaults.method || 'get').toLowerCase();
3372
+
3373
+ let contextHeaders;
3374
+
3375
+ // Flatten headers
3376
+ contextHeaders = headers && utils.merge(
3377
+ headers.common,
3378
+ headers[config.method]
3379
+ );
3380
+
3381
+ contextHeaders && utils.forEach(
3382
+ ['delete', 'get', 'head', 'post', 'put', 'patch', 'common'],
3383
+ (method) => {
3384
+ delete headers[method];
3385
+ }
3386
+ );
3387
+
3388
+ config.headers = AxiosHeaders$1.concat(contextHeaders, headers);
3389
+
3390
+ // filter out skipped interceptors
3391
+ const requestInterceptorChain = [];
3392
+ let synchronousRequestInterceptors = true;
3393
+ this.interceptors.request.forEach(function unshiftRequestInterceptors(interceptor) {
3394
+ if (typeof interceptor.runWhen === 'function' && interceptor.runWhen(config) === false) {
3395
+ return;
3396
+ }
3397
+
3398
+ synchronousRequestInterceptors = synchronousRequestInterceptors && interceptor.synchronous;
3399
+
3400
+ requestInterceptorChain.unshift(interceptor.fulfilled, interceptor.rejected);
3401
+ });
3402
+
3403
+ const responseInterceptorChain = [];
3404
+ this.interceptors.response.forEach(function pushResponseInterceptors(interceptor) {
3405
+ responseInterceptorChain.push(interceptor.fulfilled, interceptor.rejected);
3406
+ });
3407
+
3408
+ let promise;
3409
+ let i = 0;
3410
+ let len;
3411
+
3412
+ if (!synchronousRequestInterceptors) {
3413
+ const chain = [dispatchRequest.bind(this), undefined];
3414
+ chain.unshift.apply(chain, requestInterceptorChain);
3415
+ chain.push.apply(chain, responseInterceptorChain);
3416
+ len = chain.length;
3417
+
3418
+ promise = Promise.resolve(config);
3419
+
3420
+ while (i < len) {
3421
+ promise = promise.then(chain[i++], chain[i++]);
3422
+ }
3423
+
3424
+ return promise;
3425
+ }
3426
+
3427
+ len = requestInterceptorChain.length;
3428
+
3429
+ let newConfig = config;
3430
+
3431
+ i = 0;
3432
+
3433
+ while (i < len) {
3434
+ const onFulfilled = requestInterceptorChain[i++];
3435
+ const onRejected = requestInterceptorChain[i++];
3436
+ try {
3437
+ newConfig = onFulfilled(newConfig);
3438
+ } catch (error) {
3439
+ onRejected.call(this, error);
3440
+ break;
3441
+ }
3442
+ }
3443
+
3444
+ try {
3445
+ promise = dispatchRequest.call(this, newConfig);
3446
+ } catch (error) {
3447
+ return Promise.reject(error);
3448
+ }
3449
+
3450
+ i = 0;
3451
+ len = responseInterceptorChain.length;
3452
+
3453
+ while (i < len) {
3454
+ promise = promise.then(responseInterceptorChain[i++], responseInterceptorChain[i++]);
3455
+ }
3456
+
3457
+ return promise;
3458
+ }
3459
+
3460
+ getUri(config) {
3461
+ config = mergeConfig(this.defaults, config);
3462
+ const fullPath = buildFullPath(config.baseURL, config.url);
3463
+ return buildURL(fullPath, config.params, config.paramsSerializer);
3464
+ }
3465
+ }
3466
+
3467
+ // Provide aliases for supported request methods
3468
+ utils.forEach(['delete', 'get', 'head', 'options'], function forEachMethodNoData(method) {
3469
+ /*eslint func-names:0*/
3470
+ Axios.prototype[method] = function(url, config) {
3471
+ return this.request(mergeConfig(config || {}, {
3472
+ method,
3473
+ url,
3474
+ data: (config || {}).data
3475
+ }));
3476
+ };
3477
+ });
3478
+
3479
+ utils.forEach(['post', 'put', 'patch'], function forEachMethodWithData(method) {
3480
+ /*eslint func-names:0*/
3481
+
3482
+ function generateHTTPMethod(isForm) {
3483
+ return function httpMethod(url, data, config) {
3484
+ return this.request(mergeConfig(config || {}, {
3485
+ method,
3486
+ headers: isForm ? {
3487
+ 'Content-Type': 'multipart/form-data'
3488
+ } : {},
3489
+ url,
3490
+ data
3491
+ }));
3492
+ };
3493
+ }
3494
+
3495
+ Axios.prototype[method] = generateHTTPMethod();
3496
+
3497
+ Axios.prototype[method + 'Form'] = generateHTTPMethod(true);
3498
+ });
3499
+
3500
+ var Axios$1 = Axios;
3501
+
3502
+ /**
3503
+ * A `CancelToken` is an object that can be used to request cancellation of an operation.
3504
+ *
3505
+ * @param {Function} executor The executor function.
3506
+ *
3507
+ * @returns {CancelToken}
3508
+ */
3509
+ class CancelToken {
3510
+ constructor(executor) {
3511
+ if (typeof executor !== 'function') {
3512
+ throw new TypeError('executor must be a function.');
3513
+ }
3514
+
3515
+ let resolvePromise;
3516
+
3517
+ this.promise = new Promise(function promiseExecutor(resolve) {
3518
+ resolvePromise = resolve;
3519
+ });
3520
+
3521
+ const token = this;
3522
+
3523
+ // eslint-disable-next-line func-names
3524
+ this.promise.then(cancel => {
3525
+ if (!token._listeners) return;
3526
+
3527
+ let i = token._listeners.length;
3528
+
3529
+ while (i-- > 0) {
3530
+ token._listeners[i](cancel);
3531
+ }
3532
+ token._listeners = null;
3533
+ });
3534
+
3535
+ // eslint-disable-next-line func-names
3536
+ this.promise.then = onfulfilled => {
3537
+ let _resolve;
3538
+ // eslint-disable-next-line func-names
3539
+ const promise = new Promise(resolve => {
3540
+ token.subscribe(resolve);
3541
+ _resolve = resolve;
3542
+ }).then(onfulfilled);
3543
+
3544
+ promise.cancel = function reject() {
3545
+ token.unsubscribe(_resolve);
3546
+ };
3547
+
3548
+ return promise;
3549
+ };
3550
+
3551
+ executor(function cancel(message, config, request) {
3552
+ if (token.reason) {
3553
+ // Cancellation has already been requested
3554
+ return;
3555
+ }
3556
+
3557
+ token.reason = new CanceledError(message, config, request);
3558
+ resolvePromise(token.reason);
3559
+ });
3560
+ }
3561
+
3562
+ /**
3563
+ * Throws a `CanceledError` if cancellation has been requested.
3564
+ */
3565
+ throwIfRequested() {
3566
+ if (this.reason) {
3567
+ throw this.reason;
3568
+ }
3569
+ }
3570
+
3571
+ /**
3572
+ * Subscribe to the cancel signal
3573
+ */
3574
+
3575
+ subscribe(listener) {
3576
+ if (this.reason) {
3577
+ listener(this.reason);
3578
+ return;
3579
+ }
3580
+
3581
+ if (this._listeners) {
3582
+ this._listeners.push(listener);
3583
+ } else {
3584
+ this._listeners = [listener];
3585
+ }
3586
+ }
3587
+
3588
+ /**
3589
+ * Unsubscribe from the cancel signal
3590
+ */
3591
+
3592
+ unsubscribe(listener) {
3593
+ if (!this._listeners) {
3594
+ return;
3595
+ }
3596
+ const index = this._listeners.indexOf(listener);
3597
+ if (index !== -1) {
3598
+ this._listeners.splice(index, 1);
3599
+ }
3600
+ }
3601
+
3602
+ /**
3603
+ * Returns an object that contains a new `CancelToken` and a function that, when called,
3604
+ * cancels the `CancelToken`.
3605
+ */
3606
+ static source() {
3607
+ let cancel;
3608
+ const token = new CancelToken(function executor(c) {
3609
+ cancel = c;
3610
+ });
3611
+ return {
3612
+ token,
3613
+ cancel
3614
+ };
3615
+ }
3616
+ }
3617
+
3618
+ var CancelToken$1 = CancelToken;
3619
+
3620
+ /**
3621
+ * Syntactic sugar for invoking a function and expanding an array for arguments.
3622
+ *
3623
+ * Common use case would be to use `Function.prototype.apply`.
3624
+ *
3625
+ * ```js
3626
+ * function f(x, y, z) {}
3627
+ * var args = [1, 2, 3];
3628
+ * f.apply(null, args);
3629
+ * ```
3630
+ *
3631
+ * With `spread` this example can be re-written.
3632
+ *
3633
+ * ```js
3634
+ * spread(function(x, y, z) {})([1, 2, 3]);
3635
+ * ```
3636
+ *
3637
+ * @param {Function} callback
3638
+ *
3639
+ * @returns {Function}
3640
+ */
3641
+ function spread(callback) {
3642
+ return function wrap(arr) {
3643
+ return callback.apply(null, arr);
3644
+ };
3645
+ }
3646
+
3647
+ /**
3648
+ * Determines whether the payload is an error thrown by Axios
3649
+ *
3650
+ * @param {*} payload The value to test
3651
+ *
3652
+ * @returns {boolean} True if the payload is an error thrown by Axios, otherwise false
3653
+ */
3654
+ function isAxiosError(payload) {
3655
+ return utils.isObject(payload) && (payload.isAxiosError === true);
3656
+ }
3657
+
3658
+ const HttpStatusCode = {
3659
+ Continue: 100,
3660
+ SwitchingProtocols: 101,
3661
+ Processing: 102,
3662
+ EarlyHints: 103,
3663
+ Ok: 200,
3664
+ Created: 201,
3665
+ Accepted: 202,
3666
+ NonAuthoritativeInformation: 203,
3667
+ NoContent: 204,
3668
+ ResetContent: 205,
3669
+ PartialContent: 206,
3670
+ MultiStatus: 207,
3671
+ AlreadyReported: 208,
3672
+ ImUsed: 226,
3673
+ MultipleChoices: 300,
3674
+ MovedPermanently: 301,
3675
+ Found: 302,
3676
+ SeeOther: 303,
3677
+ NotModified: 304,
3678
+ UseProxy: 305,
3679
+ Unused: 306,
3680
+ TemporaryRedirect: 307,
3681
+ PermanentRedirect: 308,
3682
+ BadRequest: 400,
3683
+ Unauthorized: 401,
3684
+ PaymentRequired: 402,
3685
+ Forbidden: 403,
3686
+ NotFound: 404,
3687
+ MethodNotAllowed: 405,
3688
+ NotAcceptable: 406,
3689
+ ProxyAuthenticationRequired: 407,
3690
+ RequestTimeout: 408,
3691
+ Conflict: 409,
3692
+ Gone: 410,
3693
+ LengthRequired: 411,
3694
+ PreconditionFailed: 412,
3695
+ PayloadTooLarge: 413,
3696
+ UriTooLong: 414,
3697
+ UnsupportedMediaType: 415,
3698
+ RangeNotSatisfiable: 416,
3699
+ ExpectationFailed: 417,
3700
+ ImATeapot: 418,
3701
+ MisdirectedRequest: 421,
3702
+ UnprocessableEntity: 422,
3703
+ Locked: 423,
3704
+ FailedDependency: 424,
3705
+ TooEarly: 425,
3706
+ UpgradeRequired: 426,
3707
+ PreconditionRequired: 428,
3708
+ TooManyRequests: 429,
3709
+ RequestHeaderFieldsTooLarge: 431,
3710
+ UnavailableForLegalReasons: 451,
3711
+ InternalServerError: 500,
3712
+ NotImplemented: 501,
3713
+ BadGateway: 502,
3714
+ ServiceUnavailable: 503,
3715
+ GatewayTimeout: 504,
3716
+ HttpVersionNotSupported: 505,
3717
+ VariantAlsoNegotiates: 506,
3718
+ InsufficientStorage: 507,
3719
+ LoopDetected: 508,
3720
+ NotExtended: 510,
3721
+ NetworkAuthenticationRequired: 511,
3722
+ };
3723
+
3724
+ Object.entries(HttpStatusCode).forEach(([key, value]) => {
3725
+ HttpStatusCode[value] = key;
3726
+ });
3727
+
3728
+ var HttpStatusCode$1 = HttpStatusCode;
3729
+
3730
+ /**
3731
+ * Create an instance of Axios
3732
+ *
3733
+ * @param {Object} defaultConfig The default config for the instance
3734
+ *
3735
+ * @returns {Axios} A new instance of Axios
3736
+ */
3737
+ function createInstance(defaultConfig) {
3738
+ const context = new Axios$1(defaultConfig);
3739
+ const instance = bind(Axios$1.prototype.request, context);
3740
+
3741
+ // Copy axios.prototype to instance
3742
+ utils.extend(instance, Axios$1.prototype, context, {allOwnKeys: true});
3743
+
3744
+ // Copy context to instance
3745
+ utils.extend(instance, context, null, {allOwnKeys: true});
3746
+
3747
+ // Factory for creating new instances
3748
+ instance.create = function create(instanceConfig) {
3749
+ return createInstance(mergeConfig(defaultConfig, instanceConfig));
3750
+ };
3751
+
3752
+ return instance;
3753
+ }
3754
+
3755
+ // Create the default instance to be exported
3756
+ const axios = createInstance(defaults$1);
3757
+
3758
+ // Expose Axios class to allow class inheritance
3759
+ axios.Axios = Axios$1;
3760
+
3761
+ // Expose Cancel & CancelToken
3762
+ axios.CanceledError = CanceledError;
3763
+ axios.CancelToken = CancelToken$1;
3764
+ axios.isCancel = isCancel;
3765
+ axios.VERSION = VERSION;
3766
+ axios.toFormData = toFormData;
3767
+
3768
+ // Expose AxiosError class
3769
+ axios.AxiosError = AxiosError;
3770
+
3771
+ // alias for CanceledError for backward compatibility
3772
+ axios.Cancel = axios.CanceledError;
3773
+
3774
+ // Expose all/spread
3775
+ axios.all = function all(promises) {
3776
+ return Promise.all(promises);
3777
+ };
3778
+
3779
+ axios.spread = spread;
3780
+
3781
+ // Expose isAxiosError
3782
+ axios.isAxiosError = isAxiosError;
3783
+
3784
+ // Expose mergeConfig
3785
+ axios.mergeConfig = mergeConfig;
3786
+
3787
+ axios.AxiosHeaders = AxiosHeaders$1;
3788
+
3789
+ axios.formToJSON = thing => formDataToJSON(utils.isHTMLForm(thing) ? new FormData(thing) : thing);
3790
+
3791
+ axios.HttpStatusCode = HttpStatusCode$1;
3792
+
3793
+ axios.default = axios;
3794
+
3795
+ // this module should only have a default export
3796
+ var globalAxios = axios;
3797
+
591
3798
  /* tslint:disable */
592
3799
  /* eslint-disable */
593
3800
  /**
@@ -1036,29 +4243,10 @@ const withPassportError = async (fn, customErrorType) => {
1036
4243
  try {
1037
4244
  return await fn();
1038
4245
  }
1039
- catch (error) {
1040
- const errorMessage = `${customErrorType}: ${error.message}` || 'UnknownError';
1041
- throw new PassportError(errorMessage, customErrorType);
1042
- }
1043
- };
1044
-
1045
- const POLL_INTERVAL = 1 * 1000; // every 1 second
1046
- const MAX_RETRIES = 3;
1047
- const wait = (ms) => new Promise((resolve) => {
1048
- setTimeout(() => resolve(), ms);
1049
- });
1050
- const retryWithDelay = async (fn, options) => {
1051
- const { retries = MAX_RETRIES, interval = POLL_INTERVAL, finalErr = Error('Retry failed'), } = options || {};
1052
- try {
1053
- return await fn();
1054
- }
1055
- catch (err) {
1056
- if (retries <= 0) {
1057
- return Promise.reject(finalErr);
1058
- }
1059
- await wait(interval);
1060
- return retryWithDelay(fn, { retries: retries - 1, finalErr });
1061
- }
4246
+ catch (error) {
4247
+ const errorMessage = `${customErrorType}: ${error.message}` || 'UnknownError';
4248
+ throw new PassportError(errorMessage, customErrorType);
4249
+ }
1062
4250
  };
1063
4251
 
1064
4252
  const getAuthConfiguration = ({ oidcConfiguration, authenticationDomain, }) => {
@@ -1106,6 +4294,8 @@ class AuthManager {
1106
4294
  nickname: oidcUser.profile.nickname,
1107
4295
  },
1108
4296
  etherKey: passport?.ether_key || '',
4297
+ starkKey: passport?.stark_key || '',
4298
+ userAdminKey: passport?.user_admin_key || '',
1109
4299
  };
1110
4300
  };
1111
4301
  async login() {
@@ -1145,49 +4335,77 @@ class AuthManager {
1145
4335
  return AuthManager.mapOidcUserToDomainModel(oidcUser);
1146
4336
  }, PassportErrorType.NOT_LOGGED_IN_ERROR);
1147
4337
  }
1148
- async requestRefreshTokenAfterRegistration() {
1149
- return withPassportError(async () => {
1150
- const updatedUser = await retryWithDelay(async () => {
1151
- const user = await this.userManager.signinSilent();
1152
- const passportMetadata = user?.profile?.passport;
1153
- const metadataExists = !!passportMetadata?.ether_key
1154
- && !!passportMetadata?.stark_key
1155
- && !!passportMetadata?.user_admin_key;
1156
- if (metadataExists) {
1157
- return user;
1158
- }
1159
- return Promise.reject(new Error('user wallet addresses not exist'));
1160
- });
1161
- if (!updatedUser) {
1162
- return null;
1163
- }
1164
- return AuthManager.mapOidcUserToDomainModel(updatedUser);
1165
- }, PassportErrorType.REFRESH_TOKEN_ERROR);
1166
- }
1167
4338
  }
1168
4339
 
1169
4340
  class MagicAdapter {
1170
- magicClient;
1171
4341
  config;
1172
4342
  constructor(config) {
1173
4343
  this.config = config;
1174
- this.magicClient = new Magic(config.magicPublishableApiKey, {
1175
- network: config.network,
1176
- extensions: [new OpenIdExtension()],
1177
- });
1178
4344
  }
1179
- async login(idToken) {
4345
+ async login(idToken, network) {
1180
4346
  return withPassportError(async () => {
1181
- await this.magicClient.openid.loginWithOIDC({
4347
+ const magicClient = new Magic(this.config.magicPublishableApiKey, {
4348
+ extensions: [new OpenIdExtension()],
4349
+ network,
4350
+ });
4351
+ await magicClient.openid.loginWithOIDC({
1182
4352
  jwt: idToken,
1183
4353
  providerId: this.config.magicProviderId,
1184
4354
  });
1185
- return new ethers.providers.Web3Provider(this.magicClient
1186
- .rpcProvider);
4355
+ return magicClient.rpcProvider;
1187
4356
  }, PassportErrorType.WALLET_CONNECTION_ERROR);
1188
4357
  }
1189
4358
  }
1190
4359
 
4360
+ const getStarkSigner = async (signer) => withPassportError(async () => {
4361
+ const privateKey = await generateLegacyStarkPrivateKey(signer);
4362
+ return createStarkSigner(privateKey);
4363
+ }, PassportErrorType.WALLET_CONNECTION_ERROR);
4364
+
4365
+ async function exchangeTransfer({ user, starkSigner, request, exchangesApi, }) {
4366
+ return withPassportError(async () => {
4367
+ const ethAddress = user.etherKey;
4368
+ const transferAmount = request.amount;
4369
+ const signableResult = await exchangesApi.getExchangeSignableTransfer({
4370
+ id: request.transactionID,
4371
+ getSignableTransferRequest: {
4372
+ sender: ethAddress,
4373
+ token: convertToSignableToken(request),
4374
+ amount: transferAmount,
4375
+ receiver: request.receiver,
4376
+ },
4377
+ });
4378
+ const starkAddress = await starkSigner.getAddress();
4379
+ const { payload_hash: payloadHash } = signableResult.data;
4380
+ const starkSignature = await starkSigner.signMessage(payloadHash);
4381
+ const transferSigningParams = {
4382
+ sender_stark_key: signableResult.data.sender_stark_key || starkAddress,
4383
+ sender_vault_id: signableResult.data.sender_vault_id,
4384
+ receiver_stark_key: signableResult.data.receiver_stark_key,
4385
+ receiver_vault_id: signableResult.data.receiver_vault_id,
4386
+ asset_id: signableResult.data.asset_id,
4387
+ amount: signableResult.data.amount,
4388
+ nonce: signableResult.data.nonce,
4389
+ expiration_timestamp: signableResult.data.expiration_timestamp,
4390
+ stark_signature: starkSignature,
4391
+ };
4392
+ const headers = {
4393
+ // eslint-disable-next-line @typescript-eslint/naming-convention
4394
+ Authorization: `Bearer ${user.accessToken}`,
4395
+ };
4396
+ const response = await exchangesApi.createExchangeTransfer({
4397
+ id: request.transactionID,
4398
+ createTransferRequest: transferSigningParams,
4399
+ }, { headers });
4400
+ return {
4401
+ sent_signature: response?.data.sent_signature,
4402
+ status: response?.data.status?.toString(),
4403
+ time: response?.data.time,
4404
+ transfer_id: response?.data.transfer_id,
4405
+ };
4406
+ }, PassportErrorType.EXCHANGE_TRANSFER_ERROR);
4407
+ }
4408
+
1191
4409
  var ReceiveMessage;
1192
4410
  (function (ReceiveMessage) {
1193
4411
  ReceiveMessage["CONFIRMATION_WINDOW_READY"] = "confirmation_window_ready";
@@ -1229,246 +4447,124 @@ const CONFIRMATION_WINDOW_TITLE = 'Confirm this transaction';
1229
4447
  const CONFIRMATION_WINDOW_HEIGHT = 380;
1230
4448
  const CONFIRMATION_WINDOW_WIDTH = 480;
1231
4449
  const CONFIRMATION_WINDOW_CLOSED_POLLING_DURATION = 1000;
1232
- class ConfirmationScreen {
1233
- config;
1234
- constructor(config) {
1235
- this.config = config;
1236
- }
1237
- postMessage(destinationWindow, accessToken, message) {
1238
- destinationWindow.postMessage({
1239
- eventType: PASSPORT_EVENT_TYPE,
1240
- accessToken,
1241
- ...message,
1242
- }, this.config.passportDomain);
1243
- }
1244
- startTransaction(accessToken, transaction, popupOptions) {
1245
- return new Promise((resolve, reject) => {
1246
- const messageHandler = ({ data, origin }) => {
1247
- if (origin !== this.config.passportDomain
1248
- || data.eventType !== PASSPORT_EVENT_TYPE) {
1249
- return;
1250
- }
1251
- switch (data.messageType) {
1252
- case ReceiveMessage.CONFIRMATION_WINDOW_READY: {
1253
- // TODO: remove once fixed
1254
- // eslint-disable-next-line @typescript-eslint/no-use-before-define
1255
- this.postMessage(confirmationWindow, accessToken, {
1256
- messageType: SendMessage.TRANSACTION_START,
1257
- messageData: transaction,
1258
- });
1259
- break;
1260
- }
1261
- case ReceiveMessage.TRANSACTION_CONFIRMED: {
1262
- resolve({ confirmed: true });
1263
- break;
1264
- }
1265
- case ReceiveMessage.TRANSACTION_ERROR: {
1266
- reject(new Error('Transaction error'));
1267
- break;
1268
- }
1269
- default:
1270
- reject(new Error('Unsupported message type'));
1271
- }
1272
- };
1273
- window.addEventListener('message', messageHandler);
1274
- const confirmationWindow = openPopupCenter({
1275
- url: `${this.config.passportDomain}/transaction-confirmation`,
1276
- title: CONFIRMATION_WINDOW_TITLE,
1277
- width: popupOptions?.width || CONFIRMATION_WINDOW_WIDTH,
1278
- height: popupOptions?.height || CONFIRMATION_WINDOW_HEIGHT,
1279
- });
1280
- // https://stackoverflow.com/questions/9388380/capture-the-close-event-of-popup-window-in-javascript/48240128#48240128
1281
- const timer = setInterval(() => {
1282
- if (confirmationWindow.closed) {
1283
- clearInterval(timer);
1284
- window.removeEventListener('message', messageHandler);
1285
- resolve({ confirmed: false });
1286
- }
1287
- }, CONFIRMATION_WINDOW_CLOSED_POLLING_DURATION);
1288
- });
1289
- }
1290
- startGuardianTransaction(transactionId, popupOptions) {
1291
- return new Promise((resolve, reject) => {
1292
- const messageHandler = ({ data, origin }) => {
1293
- if (origin !== this.config.passportDomain
1294
- || data.eventType !== PASSPORT_EVENT_TYPE) {
1295
- return;
1296
- }
1297
- switch (data.messageType) {
1298
- case ReceiveMessage.CONFIRMATION_WINDOW_READY: {
1299
- break;
1300
- }
1301
- case ReceiveMessage.TRANSACTION_CONFIRMED: {
1302
- resolve({ confirmed: true });
1303
- break;
1304
- }
1305
- case ReceiveMessage.TRANSACTION_ERROR: {
1306
- reject(new Error('Transaction error'));
1307
- break;
1308
- }
1309
- default:
1310
- reject(new Error('Unsupported message type'));
1311
- }
1312
- };
1313
- window.addEventListener('message', messageHandler);
1314
- const confirmationWindow = openPopupCenter({
1315
- // eslint-disable-next-line max-len
1316
- url: `${this.config.passportDomain}/transaction-confirmation/transaction.html?transactionId=${transactionId}&chainType=starkex`,
1317
- title: CONFIRMATION_WINDOW_TITLE,
1318
- width: popupOptions?.width || CONFIRMATION_WINDOW_WIDTH,
1319
- height: popupOptions?.height || CONFIRMATION_WINDOW_HEIGHT,
1320
- });
1321
- // https://stackoverflow.com/questions/9388380/capture-the-close-event-of-popup-window-in-javascript/48240128#48240128
1322
- const timer = setInterval(() => {
1323
- if (confirmationWindow.closed) {
1324
- clearInterval(timer);
1325
- window.removeEventListener('message', messageHandler);
1326
- resolve({ confirmed: false });
1327
- }
1328
- }, CONFIRMATION_WINDOW_CLOSED_POLLING_DURATION);
1329
- });
1330
- }
1331
- }
1332
-
1333
- const ERC721$1 = 'ERC721';
1334
- const transferWithGuardian = async ({ accessToken, imxPublicApiDomain, payloadHash, confirmationScreen, }) => {
1335
- const transactionAPI = new TransactionsApi(new Configuration({
1336
- accessToken,
1337
- basePath: imxPublicApiDomain,
1338
- }));
1339
- const starkExTransactionApi = new StarkexTransactionsApi(new Configuration({
1340
- accessToken,
1341
- basePath: imxPublicApiDomain,
1342
- }));
1343
- const transactionRes = await retryWithDelay(async () => transactionAPI.getTransactionByID({
1344
- transactionID: payloadHash,
1345
- chainType: 'starkex',
1346
- }));
1347
- if (!transactionRes.data.id) {
1348
- throw new Error("Transaction doesn't exists");
1349
- }
1350
- const evaluateStarkexRes = await starkExTransactionApi.evaluateStarkexTransaction({
1351
- payloadHash,
1352
- });
1353
- const { confirmationRequired } = evaluateStarkexRes.data;
1354
- if (confirmationRequired) {
1355
- const confirmationResult = await confirmationScreen.startGuardianTransaction(payloadHash);
1356
- if (!confirmationResult.confirmed) {
1357
- throw new Error('Transaction rejected by user');
1358
- }
1359
- }
1360
- };
1361
- async function transfer({ request, transfersApi, starkSigner, user, imxPublicApiDomain, confirmationScreen, }) {
1362
- return withPassportError(async () => {
1363
- const transferAmount = request.type === ERC721$1 ? '1' : request.amount;
1364
- const getSignableTransferRequest = {
1365
- sender: user.etherKey,
1366
- token: convertToSignableToken(request),
1367
- amount: transferAmount,
1368
- receiver: request.receiver,
1369
- };
1370
- const headers = {
1371
- Authorization: `Bearer ${user.accessToken}`,
1372
- };
1373
- const signableResult = await transfersApi.getSignableTransferV1({
1374
- getSignableTransferRequest,
1375
- }, { headers });
1376
- await transferWithGuardian({
1377
- imxPublicApiDomain,
1378
- accessToken: user.accessToken,
1379
- payloadHash: signableResult.data.payload_hash,
1380
- confirmationScreen,
1381
- });
1382
- const signableResultData = signableResult.data;
1383
- const { payload_hash: payloadHash } = signableResultData;
1384
- const starkSignature = await starkSigner.signMessage(payloadHash);
1385
- const senderStarkKey = await starkSigner.getAddress();
1386
- const transferSigningParams = {
1387
- sender_stark_key: signableResultData.sender_stark_key || senderStarkKey,
1388
- sender_vault_id: signableResultData.sender_vault_id,
1389
- receiver_stark_key: signableResultData.receiver_stark_key,
1390
- receiver_vault_id: signableResultData.receiver_vault_id,
1391
- asset_id: signableResultData.asset_id,
1392
- amount: signableResultData.amount,
1393
- nonce: signableResultData.nonce,
1394
- expiration_timestamp: signableResultData.expiration_timestamp,
1395
- stark_signature: starkSignature,
1396
- };
1397
- const createTransferRequest = {
1398
- createTransferRequest: transferSigningParams,
1399
- };
1400
- const { data: responseData } = await transfersApi.createTransferV1(createTransferRequest, { headers });
1401
- return {
1402
- sent_signature: responseData.sent_signature,
1403
- status: responseData.status?.toString(),
1404
- time: responseData.time,
1405
- transfer_id: responseData.transfer_id,
1406
- };
1407
- }, PassportErrorType.TRANSFER_ERROR);
1408
- }
1409
- async function batchNftTransfer({ user, starkSigner, request, transfersApi, confirmationScreen, }) {
1410
- return withPassportError(async () => {
1411
- const ethAddress = user.etherKey;
1412
- const signableRequests = request.map((nftTransfer) => ({
1413
- amount: '1',
1414
- token: convertToSignableToken({
1415
- type: ERC721$1,
1416
- tokenId: nftTransfer.tokenId,
1417
- tokenAddress: nftTransfer.tokenAddress,
1418
- }),
1419
- receiver: nftTransfer.receiver,
1420
- }));
1421
- const getSignableTransferRequestV2 = {
1422
- sender_ether_key: ethAddress,
1423
- signable_requests: signableRequests,
1424
- };
1425
- const signableResult = await transfersApi.getSignableTransfer({
1426
- getSignableTransferRequestV2,
4450
+ class ConfirmationScreen {
4451
+ config;
4452
+ confirmationWindow;
4453
+ constructor(config) {
4454
+ this.config = config;
4455
+ }
4456
+ postMessage(destinationWindow, accessToken, message) {
4457
+ destinationWindow.postMessage({
4458
+ eventType: PASSPORT_EVENT_TYPE,
4459
+ accessToken,
4460
+ ...message,
4461
+ }, this.config.passportDomain);
4462
+ }
4463
+ startTransaction(accessToken, transaction, popupOptions) {
4464
+ return new Promise((resolve, reject) => {
4465
+ const messageHandler = ({ data, origin }) => {
4466
+ if (origin !== this.config.passportDomain
4467
+ || data.eventType !== PASSPORT_EVENT_TYPE) {
4468
+ return;
4469
+ }
4470
+ switch (data.messageType) {
4471
+ case ReceiveMessage.CONFIRMATION_WINDOW_READY: {
4472
+ // TODO: remove once fixed
4473
+ // eslint-disable-next-line @typescript-eslint/no-use-before-define
4474
+ this.postMessage(confirmationWindow, accessToken, {
4475
+ messageType: SendMessage.TRANSACTION_START,
4476
+ messageData: transaction,
4477
+ });
4478
+ break;
4479
+ }
4480
+ case ReceiveMessage.TRANSACTION_CONFIRMED: {
4481
+ resolve({ confirmed: true });
4482
+ break;
4483
+ }
4484
+ case ReceiveMessage.TRANSACTION_ERROR: {
4485
+ reject(new Error('Transaction error'));
4486
+ break;
4487
+ }
4488
+ default:
4489
+ reject(new Error('Unsupported message type'));
4490
+ }
4491
+ };
4492
+ window.addEventListener('message', messageHandler);
4493
+ const confirmationWindow = openPopupCenter({
4494
+ url: `${this.config.passportDomain}/transaction-confirmation`,
4495
+ title: CONFIRMATION_WINDOW_TITLE,
4496
+ width: popupOptions?.width || CONFIRMATION_WINDOW_WIDTH,
4497
+ height: popupOptions?.height || CONFIRMATION_WINDOW_HEIGHT,
4498
+ });
4499
+ // https://stackoverflow.com/questions/9388380/capture-the-close-event-of-popup-window-in-javascript/48240128#48240128
4500
+ const timer = setInterval(() => {
4501
+ if (confirmationWindow.closed) {
4502
+ clearInterval(timer);
4503
+ window.removeEventListener('message', messageHandler);
4504
+ resolve({ confirmed: false });
4505
+ }
4506
+ }, CONFIRMATION_WINDOW_CLOSED_POLLING_DURATION);
1427
4507
  });
1428
- const popupWindowSize = { width: 480, height: 784 };
1429
- const confirmationResult = await confirmationScreen.startTransaction(user.accessToken, {
1430
- transactionType: TransactionTypes.createBatchTransfer,
1431
- transactionData: getSignableTransferRequestV2,
1432
- }, popupWindowSize);
1433
- if (!confirmationResult.confirmed) {
1434
- throw new Error('Transaction rejected by user');
1435
- }
1436
- const requests = await Promise.all(signableResult.data.signable_responses.map(async (resp) => {
1437
- const starkSignature = await starkSigner.signMessage(resp.payload_hash);
1438
- return {
1439
- sender_vault_id: resp.sender_vault_id,
1440
- receiver_stark_key: resp.receiver_stark_key,
1441
- receiver_vault_id: resp.receiver_vault_id,
1442
- asset_id: resp.asset_id,
1443
- amount: resp.amount,
1444
- nonce: resp.nonce,
1445
- expiration_timestamp: resp.expiration_timestamp,
1446
- stark_signature: starkSignature,
4508
+ }
4509
+ startGuardianTransaction(transactionId) {
4510
+ return new Promise((resolve, reject) => {
4511
+ const messageHandler = ({ data, origin }) => {
4512
+ if (origin !== this.config.passportDomain
4513
+ || data.eventType !== PASSPORT_EVENT_TYPE) {
4514
+ return;
4515
+ }
4516
+ switch (data.messageType) {
4517
+ case ReceiveMessage.CONFIRMATION_WINDOW_READY: {
4518
+ break;
4519
+ }
4520
+ case ReceiveMessage.TRANSACTION_CONFIRMED: {
4521
+ resolve({ confirmed: true });
4522
+ break;
4523
+ }
4524
+ case ReceiveMessage.TRANSACTION_ERROR: {
4525
+ reject(new Error('Transaction error'));
4526
+ break;
4527
+ }
4528
+ default:
4529
+ reject(new Error('Unsupported message type'));
4530
+ }
1447
4531
  };
1448
- }));
1449
- const transferSigningParams = {
1450
- sender_stark_key: signableResult.data.sender_stark_key,
1451
- requests,
1452
- };
1453
- const headers = {
1454
- // eslint-disable-next-line @typescript-eslint/naming-convention
1455
- Authorization: `Bearer ${user.accessToken}`,
1456
- };
1457
- const response = await transfersApi.createTransfer({
1458
- createTransferRequestV2: transferSigningParams,
1459
- }, { headers });
1460
- return {
1461
- transfer_ids: response?.data.transfer_ids,
1462
- };
1463
- }, PassportErrorType.TRANSFER_ERROR);
4532
+ window.addEventListener('message', messageHandler);
4533
+ if (!this.confirmationWindow) {
4534
+ resolve({ confirmed: false });
4535
+ return;
4536
+ }
4537
+ // eslint-disable-next-line max-len
4538
+ this.confirmationWindow.location.href = `${this.config.passportDomain}/transaction-confirmation/transaction.html?transactionId=${transactionId}&chainType=starkex`;
4539
+ // https://stackoverflow.com/questions/9388380/capture-the-close-event-of-popup-window-in-javascript/48240128#48240128
4540
+ const timer = setInterval(() => {
4541
+ if (this.confirmationWindow?.closed) {
4542
+ clearInterval(timer);
4543
+ window.removeEventListener('message', messageHandler);
4544
+ resolve({ confirmed: false });
4545
+ }
4546
+ }, CONFIRMATION_WINDOW_CLOSED_POLLING_DURATION);
4547
+ });
4548
+ }
4549
+ loading(popupOptions) {
4550
+ this.confirmationWindow = openPopupCenter({
4551
+ url: `${this.config.passportDomain}/transaction-confirmation/loading.html`,
4552
+ title: CONFIRMATION_WINDOW_TITLE,
4553
+ width: popupOptions?.width || CONFIRMATION_WINDOW_WIDTH,
4554
+ height: popupOptions?.height || CONFIRMATION_WINDOW_HEIGHT,
4555
+ });
4556
+ }
4557
+ closeWindow() {
4558
+ this.confirmationWindow?.close();
4559
+ }
1464
4560
  }
1465
4561
 
1466
- const ERC721 = 'ERC721';
4562
+ const ERC721$1 = 'ERC721';
1467
4563
  async function createOrder({ starkSigner, user, request, ordersApi, confirmationScreen, }) {
1468
4564
  return withPassportError(async () => {
1469
4565
  const ethAddress = user.etherKey;
1470
- const amountSell = request.sell.type === ERC721 ? '1' : request.sell.amount;
1471
- const amountBuy = request.buy.type === ERC721 ? '1' : request.buy.amount;
4566
+ const amountSell = request.sell.type === ERC721$1 ? '1' : request.sell.amount;
4567
+ const amountBuy = request.buy.type === ERC721$1 ? '1' : request.buy.amount;
1472
4568
  const getSignableOrderRequestV3 = {
1473
4569
  user: ethAddress,
1474
4570
  amount_buy: amountBuy,
@@ -1554,97 +4650,243 @@ async function cancelOrder({ user, starkSigner, request, ordersApi, confirmation
1554
4650
  }, PassportErrorType.CANCEL_ORDER_ERROR);
1555
4651
  }
1556
4652
 
1557
- async function exchangeTransfer({ user, starkSigner, request, exchangesApi, }) {
4653
+ async function registerPassport({ ethSigner, starkSigner, usersApi }, authorization) {
4654
+ return withPassportError(async () => {
4655
+ const userAddress = await ethSigner.getAddress();
4656
+ const starkPublicKey = await starkSigner.getAddress();
4657
+ const signableResult = await usersApi.getSignableRegistrationOffchain({
4658
+ getSignableRegistrationRequest: {
4659
+ ether_key: userAddress,
4660
+ stark_key: starkPublicKey,
4661
+ },
4662
+ });
4663
+ const { signable_message: signableMessage, payload_hash: payloadHash } = signableResult.data;
4664
+ const ethSignature = await signRaw(signableMessage, ethSigner);
4665
+ const starkSignature = await starkSigner.signMessage(payloadHash);
4666
+ const response = await usersApi.registerPassportUser({
4667
+ authorization: `Bearer ${authorization}`,
4668
+ registerPassportUserRequest: {
4669
+ eth_signature: ethSignature,
4670
+ ether_key: userAddress,
4671
+ stark_signature: starkSignature,
4672
+ stark_key: starkPublicKey,
4673
+ },
4674
+ });
4675
+ return response.statusText;
4676
+ }, PassportErrorType.USER_REGISTRATION_ERROR);
4677
+ }
4678
+
4679
+ async function createTrade({ request, tradesApi, user, starkSigner, confirmationScreen, }) {
4680
+ return withPassportError(async () => {
4681
+ const ethAddress = user.etherKey;
4682
+ const getSignableTradeRequest = {
4683
+ expiration_timestamp: request.expiration_timestamp,
4684
+ fees: request.fees,
4685
+ order_id: request.order_id,
4686
+ user: ethAddress,
4687
+ };
4688
+ const getSignableTradeResponse = await tradesApi.getSignableTrade({
4689
+ getSignableTradeRequest,
4690
+ });
4691
+ const confirmationResult = await confirmationScreen.startTransaction(user.accessToken, {
4692
+ transactionType: TransactionTypes.createTrade,
4693
+ transactionData: getSignableTradeRequest,
4694
+ });
4695
+ if (!confirmationResult.confirmed) {
4696
+ throw new Error('Transaction rejected by user');
4697
+ }
4698
+ const { payload_hash: payloadHash } = getSignableTradeResponse.data;
4699
+ const starkSignature = await starkSigner.signMessage(payloadHash);
4700
+ const { data: signableResultData } = getSignableTradeResponse;
4701
+ const tradeParams = {
4702
+ createTradeRequest: {
4703
+ include_fees: true,
4704
+ fees: request?.fees,
4705
+ stark_signature: starkSignature,
4706
+ order_id: request?.order_id,
4707
+ fee_info: signableResultData.fee_info,
4708
+ amount_buy: signableResultData.amount_buy,
4709
+ amount_sell: signableResultData.amount_sell,
4710
+ asset_id_buy: signableResultData.asset_id_buy,
4711
+ asset_id_sell: signableResultData.asset_id_sell,
4712
+ expiration_timestamp: signableResultData.expiration_timestamp,
4713
+ nonce: signableResultData.nonce,
4714
+ stark_key: signableResultData.stark_key,
4715
+ vault_id_buy: signableResultData.vault_id_buy,
4716
+ vault_id_sell: signableResultData.vault_id_sell,
4717
+ },
4718
+ };
4719
+ // eslint-disable-next-line @typescript-eslint/naming-convention
4720
+ const headers = { Authorization: `Bearer ${user.accessToken}` };
4721
+ const { data: createTradeResponse } = await tradesApi.createTradeV3(tradeParams, {
4722
+ headers,
4723
+ });
4724
+ return createTradeResponse;
4725
+ }, PassportErrorType.CREATE_TRADE_ERROR);
4726
+ }
4727
+
4728
+ const POLL_INTERVAL = 1 * 1000; // every 1 second
4729
+ const MAX_RETRIES = 3;
4730
+ const wait = (ms) => new Promise((resolve) => {
4731
+ setTimeout(() => resolve(), ms);
4732
+ });
4733
+ const retryWithDelay = async (fn, options) => {
4734
+ const { retries = MAX_RETRIES, interval = POLL_INTERVAL, finalErr = Error('Retry failed'), finallyFn = () => { }, } = options || {};
4735
+ try {
4736
+ return await fn();
4737
+ }
4738
+ catch (err) {
4739
+ if (retries <= 0) {
4740
+ return Promise.reject(finalErr);
4741
+ }
4742
+ await wait(interval);
4743
+ return retryWithDelay(fn, { retries: retries - 1, finalErr, finallyFn });
4744
+ }
4745
+ finally {
4746
+ if (retries <= 0) {
4747
+ finallyFn();
4748
+ }
4749
+ }
4750
+ };
4751
+
4752
+ const ERC721 = 'ERC721';
4753
+ const transferWithGuardian = async ({ accessToken, imxPublicApiDomain, payloadHash, confirmationScreen, }) => {
4754
+ confirmationScreen.loading();
4755
+ const transactionAPI = new TransactionsApi(new Configuration({
4756
+ accessToken,
4757
+ basePath: imxPublicApiDomain,
4758
+ }));
4759
+ const starkExTransactionApi = new StarkexTransactionsApi(new Configuration({
4760
+ accessToken,
4761
+ basePath: imxPublicApiDomain,
4762
+ }));
4763
+ const finallyFn = () => {
4764
+ confirmationScreen.closeWindow();
4765
+ };
4766
+ const transactionRes = await retryWithDelay(async () => transactionAPI.getTransactionByID({
4767
+ transactionID: payloadHash,
4768
+ chainType: 'starkex',
4769
+ }), { finallyFn });
4770
+ if (!transactionRes.data.id) {
4771
+ throw new Error("Transaction doesn't exists");
4772
+ }
4773
+ const evaluateStarkexRes = await starkExTransactionApi.evaluateStarkexTransaction({
4774
+ payloadHash,
4775
+ });
4776
+ const { confirmationRequired } = evaluateStarkexRes.data;
4777
+ if (confirmationRequired) {
4778
+ const confirmationResult = await confirmationScreen.startGuardianTransaction(payloadHash);
4779
+ if (!confirmationResult.confirmed) {
4780
+ throw new Error('Transaction rejected by user');
4781
+ }
4782
+ }
4783
+ else {
4784
+ confirmationScreen.closeWindow();
4785
+ }
4786
+ };
4787
+ async function transfer({ request, transfersApi, starkSigner, user, imxPublicApiDomain, confirmationScreen, }) {
1558
4788
  return withPassportError(async () => {
1559
- const ethAddress = user.etherKey;
1560
- const transferAmount = request.amount;
1561
- const signableResult = await exchangesApi.getExchangeSignableTransfer({
1562
- id: request.transactionID,
1563
- getSignableTransferRequest: {
1564
- sender: ethAddress,
1565
- token: convertToSignableToken(request),
1566
- amount: transferAmount,
1567
- receiver: request.receiver,
1568
- },
4789
+ const transferAmount = request.type === ERC721 ? '1' : request.amount;
4790
+ const getSignableTransferRequest = {
4791
+ sender: user.etherKey,
4792
+ token: convertToSignableToken(request),
4793
+ amount: transferAmount,
4794
+ receiver: request.receiver,
4795
+ };
4796
+ const headers = {
4797
+ Authorization: `Bearer ${user.accessToken}`,
4798
+ };
4799
+ const signableResult = await transfersApi.getSignableTransferV1({
4800
+ getSignableTransferRequest,
4801
+ }, { headers });
4802
+ await transferWithGuardian({
4803
+ imxPublicApiDomain,
4804
+ accessToken: user.accessToken,
4805
+ payloadHash: signableResult.data.payload_hash,
4806
+ confirmationScreen,
1569
4807
  });
1570
- const starkAddress = await starkSigner.getAddress();
1571
- const { payload_hash: payloadHash } = signableResult.data;
4808
+ const signableResultData = signableResult.data;
4809
+ const { payload_hash: payloadHash } = signableResultData;
1572
4810
  const starkSignature = await starkSigner.signMessage(payloadHash);
4811
+ const senderStarkKey = await starkSigner.getAddress();
1573
4812
  const transferSigningParams = {
1574
- sender_stark_key: signableResult.data.sender_stark_key || starkAddress,
1575
- sender_vault_id: signableResult.data.sender_vault_id,
1576
- receiver_stark_key: signableResult.data.receiver_stark_key,
1577
- receiver_vault_id: signableResult.data.receiver_vault_id,
1578
- asset_id: signableResult.data.asset_id,
1579
- amount: signableResult.data.amount,
1580
- nonce: signableResult.data.nonce,
1581
- expiration_timestamp: signableResult.data.expiration_timestamp,
4813
+ sender_stark_key: signableResultData.sender_stark_key || senderStarkKey,
4814
+ sender_vault_id: signableResultData.sender_vault_id,
4815
+ receiver_stark_key: signableResultData.receiver_stark_key,
4816
+ receiver_vault_id: signableResultData.receiver_vault_id,
4817
+ asset_id: signableResultData.asset_id,
4818
+ amount: signableResultData.amount,
4819
+ nonce: signableResultData.nonce,
4820
+ expiration_timestamp: signableResultData.expiration_timestamp,
1582
4821
  stark_signature: starkSignature,
1583
4822
  };
1584
- const headers = {
1585
- // eslint-disable-next-line @typescript-eslint/naming-convention
1586
- Authorization: `Bearer ${user.accessToken}`,
1587
- };
1588
- const response = await exchangesApi.createExchangeTransfer({
1589
- id: request.transactionID,
4823
+ const createTransferRequest = {
1590
4824
  createTransferRequest: transferSigningParams,
1591
- }, { headers });
4825
+ };
4826
+ const { data: responseData } = await transfersApi.createTransferV1(createTransferRequest, { headers });
1592
4827
  return {
1593
- sent_signature: response?.data.sent_signature,
1594
- status: response?.data.status?.toString(),
1595
- time: response?.data.time,
1596
- transfer_id: response?.data.transfer_id,
4828
+ sent_signature: responseData.sent_signature,
4829
+ status: responseData.status?.toString(),
4830
+ time: responseData.time,
4831
+ transfer_id: responseData.transfer_id,
1597
4832
  };
1598
- }, PassportErrorType.EXCHANGE_TRANSFER_ERROR);
4833
+ }, PassportErrorType.TRANSFER_ERROR);
1599
4834
  }
1600
-
1601
- async function createTrade({ request, tradesApi, user, starkSigner, confirmationScreen, }) {
4835
+ async function batchNftTransfer({ user, starkSigner, request, transfersApi, confirmationScreen, }) {
1602
4836
  return withPassportError(async () => {
1603
4837
  const ethAddress = user.etherKey;
1604
- const getSignableTradeRequest = {
1605
- expiration_timestamp: request.expiration_timestamp,
1606
- fees: request.fees,
1607
- order_id: request.order_id,
1608
- user: ethAddress,
4838
+ const signableRequests = request.map((nftTransfer) => ({
4839
+ amount: '1',
4840
+ token: convertToSignableToken({
4841
+ type: ERC721,
4842
+ tokenId: nftTransfer.tokenId,
4843
+ tokenAddress: nftTransfer.tokenAddress,
4844
+ }),
4845
+ receiver: nftTransfer.receiver,
4846
+ }));
4847
+ const getSignableTransferRequestV2 = {
4848
+ sender_ether_key: ethAddress,
4849
+ signable_requests: signableRequests,
1609
4850
  };
1610
- const getSignableTradeResponse = await tradesApi.getSignableTrade({
1611
- getSignableTradeRequest,
4851
+ const signableResult = await transfersApi.getSignableTransfer({
4852
+ getSignableTransferRequestV2,
1612
4853
  });
4854
+ const popupWindowSize = { width: 480, height: 784 };
1613
4855
  const confirmationResult = await confirmationScreen.startTransaction(user.accessToken, {
1614
- transactionType: TransactionTypes.createTrade,
1615
- transactionData: getSignableTradeRequest,
1616
- });
4856
+ transactionType: TransactionTypes.createBatchTransfer,
4857
+ transactionData: getSignableTransferRequestV2,
4858
+ }, popupWindowSize);
1617
4859
  if (!confirmationResult.confirmed) {
1618
4860
  throw new Error('Transaction rejected by user');
1619
4861
  }
1620
- const { payload_hash: payloadHash } = getSignableTradeResponse.data;
1621
- const starkSignature = await starkSigner.signMessage(payloadHash);
1622
- const { data: signableResultData } = getSignableTradeResponse;
1623
- const tradeParams = {
1624
- createTradeRequest: {
1625
- include_fees: true,
1626
- fees: request?.fees,
4862
+ const requests = await Promise.all(signableResult.data.signable_responses.map(async (resp) => {
4863
+ const starkSignature = await starkSigner.signMessage(resp.payload_hash);
4864
+ return {
4865
+ sender_vault_id: resp.sender_vault_id,
4866
+ receiver_stark_key: resp.receiver_stark_key,
4867
+ receiver_vault_id: resp.receiver_vault_id,
4868
+ asset_id: resp.asset_id,
4869
+ amount: resp.amount,
4870
+ nonce: resp.nonce,
4871
+ expiration_timestamp: resp.expiration_timestamp,
1627
4872
  stark_signature: starkSignature,
1628
- order_id: request?.order_id,
1629
- fee_info: signableResultData.fee_info,
1630
- amount_buy: signableResultData.amount_buy,
1631
- amount_sell: signableResultData.amount_sell,
1632
- asset_id_buy: signableResultData.asset_id_buy,
1633
- asset_id_sell: signableResultData.asset_id_sell,
1634
- expiration_timestamp: signableResultData.expiration_timestamp,
1635
- nonce: signableResultData.nonce,
1636
- stark_key: signableResultData.stark_key,
1637
- vault_id_buy: signableResultData.vault_id_buy,
1638
- vault_id_sell: signableResultData.vault_id_sell,
1639
- },
4873
+ };
4874
+ }));
4875
+ const transferSigningParams = {
4876
+ sender_stark_key: signableResult.data.sender_stark_key,
4877
+ requests,
1640
4878
  };
1641
- // eslint-disable-next-line @typescript-eslint/naming-convention
1642
- const headers = { Authorization: `Bearer ${user.accessToken}` };
1643
- const { data: createTradeResponse } = await tradesApi.createTradeV3(tradeParams, {
1644
- headers,
1645
- });
1646
- return createTradeResponse;
1647
- }, PassportErrorType.CREATE_TRADE_ERROR);
4879
+ const headers = {
4880
+ // eslint-disable-next-line @typescript-eslint/naming-convention
4881
+ Authorization: `Bearer ${user.accessToken}`,
4882
+ };
4883
+ const response = await transfersApi.createTransfer({
4884
+ createTransferRequestV2: transferSigningParams,
4885
+ }, { headers });
4886
+ return {
4887
+ transfer_ids: response?.data.transfer_ids,
4888
+ };
4889
+ }, PassportErrorType.TRANSFER_ERROR);
1648
4890
  }
1649
4891
 
1650
4892
  class PassportImxProvider {
@@ -1748,6 +4990,77 @@ class PassportImxProvider {
1748
4990
  }
1749
4991
  }
1750
4992
 
4993
+ class PassportImxProviderFactory {
4994
+ authManager;
4995
+ config;
4996
+ confirmationScreen;
4997
+ immutableXClient;
4998
+ magicAdapter;
4999
+ constructor({ authManager, config, confirmationScreen, immutableXClient, magicAdapter, }) {
5000
+ this.authManager = authManager;
5001
+ this.config = config;
5002
+ this.confirmationScreen = confirmationScreen;
5003
+ this.immutableXClient = immutableXClient;
5004
+ this.magicAdapter = magicAdapter;
5005
+ }
5006
+ async getProvider() {
5007
+ const user = await this.authManager.login();
5008
+ return this.createProviderInstance(user);
5009
+ }
5010
+ async getProviderSilent() {
5011
+ const user = await this.authManager.loginSilent();
5012
+ if (!user) {
5013
+ return null;
5014
+ }
5015
+ return this.createProviderInstance(user);
5016
+ }
5017
+ async createProviderInstance(user) {
5018
+ if (!user.idToken) {
5019
+ throw new PassportError('Failed to initialise', PassportErrorType.WALLET_CONNECTION_ERROR);
5020
+ }
5021
+ const magicRpcProvider = await this.magicAdapter.login(user.idToken, this.config.network);
5022
+ const web3Provider = new Web3Provider(magicRpcProvider);
5023
+ const ethSigner = web3Provider.getSigner();
5024
+ const starkSigner = await getStarkSigner(ethSigner);
5025
+ if (!user.etherKey) {
5026
+ const userWithEtherKey = await this.registerStarkEx(ethSigner, starkSigner, user.accessToken);
5027
+ return new PassportImxProvider({
5028
+ user: userWithEtherKey,
5029
+ starkSigner,
5030
+ immutableXClient: this.immutableXClient,
5031
+ imxPublicApiDomain: this.config.imxPublicApiDomain,
5032
+ confirmationScreen: this.confirmationScreen,
5033
+ });
5034
+ }
5035
+ return new PassportImxProvider({
5036
+ user: user,
5037
+ starkSigner,
5038
+ immutableXClient: this.immutableXClient,
5039
+ imxPublicApiDomain: this.config.imxPublicApiDomain,
5040
+ confirmationScreen: this.confirmationScreen,
5041
+ });
5042
+ }
5043
+ async registerStarkEx(userAdminKeySigner, starkSigner, jwt) {
5044
+ return withPassportError(async () => {
5045
+ await registerPassport({
5046
+ ethSigner: userAdminKeySigner,
5047
+ starkSigner,
5048
+ usersApi: this.immutableXClient.usersApi,
5049
+ }, jwt);
5050
+ // User metadata is updated asynchronously. Poll userinfo endpoint until it is updated.
5051
+ const updatedUser = await retryWithDelay(async () => {
5052
+ const user = await this.authManager.loginSilent();
5053
+ const metadataExists = !!user?.etherKey && !!user?.starkKey && !!user?.userAdminKey;
5054
+ if (metadataExists) {
5055
+ return user;
5056
+ }
5057
+ return Promise.reject(new Error('user wallet addresses not exist'));
5058
+ });
5059
+ return updatedUser;
5060
+ }, PassportErrorType.REFRESH_TOKEN_ERROR);
5061
+ }
5062
+ }
5063
+
1751
5064
  var Networks;
1752
5065
  (function (Networks) {
1753
5066
  Networks["PRODUCTION"] = "mainnet";
@@ -1825,45 +5138,13 @@ class PassportConfiguration {
1825
5138
  }
1826
5139
  }
1827
5140
 
1828
- // TODO: remove this eslint disable once we have a better solution
1829
- // eslint-disable-next-line max-len
1830
- const getStarkSigner = async (signer) => withPassportError(async () => {
1831
- const privateKey = await generateLegacyStarkPrivateKey(signer);
1832
- return createStarkSigner(privateKey);
1833
- }, PassportErrorType.WALLET_CONNECTION_ERROR);
1834
-
1835
- async function registerPassport({ ethSigner, starkSigner, usersApi }, authorization) {
1836
- return withPassportError(async () => {
1837
- const userAddress = await ethSigner.getAddress();
1838
- const starkPublicKey = await starkSigner.getAddress();
1839
- const signableResult = await usersApi.getSignableRegistrationOffchain({
1840
- getSignableRegistrationRequest: {
1841
- ether_key: userAddress,
1842
- stark_key: starkPublicKey,
1843
- },
1844
- });
1845
- const { signable_message: signableMessage, payload_hash: payloadHash } = signableResult.data;
1846
- const ethSignature = await signRaw(signableMessage, ethSigner);
1847
- const starkSignature = await starkSigner.signMessage(payloadHash);
1848
- const response = await usersApi.registerPassportUser({
1849
- authorization: `Bearer ${authorization}`,
1850
- registerPassportUserRequest: {
1851
- eth_signature: ethSignature,
1852
- ether_key: userAddress,
1853
- stark_signature: starkSignature,
1854
- stark_key: starkPublicKey,
1855
- },
1856
- });
1857
- return response.statusText;
1858
- }, PassportErrorType.USER_REGISTRATION_ERROR);
1859
- }
1860
-
1861
5141
  class Passport {
1862
5142
  authManager;
1863
- magicAdapter;
1864
5143
  config;
1865
- immutableXClient;
1866
5144
  confirmationScreen;
5145
+ immutableXClient;
5146
+ magicAdapter;
5147
+ passportImxProviderFactory;
1867
5148
  constructor(passportModuleConfiguration) {
1868
5149
  this.config = new PassportConfiguration(passportModuleConfiguration);
1869
5150
  this.authManager = new AuthManager(this.config);
@@ -1873,43 +5154,19 @@ class Passport {
1873
5154
  || new ImmutableXClient({
1874
5155
  baseConfig: passportModuleConfiguration.baseConfig,
1875
5156
  });
1876
- }
1877
- async getImxProvider(user) {
1878
- if (!user || !user.idToken) {
1879
- throw new PassportError('Failed to initialise', PassportErrorType.WALLET_CONNECTION_ERROR);
1880
- }
1881
- const provider = await this.magicAdapter.login(user.idToken);
1882
- const ethSigner = provider.getSigner();
1883
- const starkSigner = await getStarkSigner(ethSigner);
1884
- if (!user.etherKey) {
1885
- const updatedUser = await this.registerUser(ethSigner, starkSigner, user.accessToken);
1886
- return new PassportImxProvider({
1887
- user: updatedUser,
1888
- starkSigner,
1889
- immutableXClient: this.immutableXClient,
1890
- imxPublicApiDomain: this.config.imxPublicApiDomain,
1891
- confirmationScreen: this.confirmationScreen,
1892
- });
1893
- }
1894
- const userWithEtherKey = user;
1895
- return new PassportImxProvider({
1896
- user: userWithEtherKey,
1897
- starkSigner,
1898
- immutableXClient: this.immutableXClient,
1899
- imxPublicApiDomain: this.config.imxPublicApiDomain,
5157
+ this.passportImxProviderFactory = new PassportImxProviderFactory({
5158
+ authManager: this.authManager,
5159
+ config: this.config,
1900
5160
  confirmationScreen: this.confirmationScreen,
5161
+ immutableXClient: this.immutableXClient,
5162
+ magicAdapter: this.magicAdapter,
1901
5163
  });
1902
5164
  }
1903
5165
  async connectImxSilent() {
1904
- const user = await this.authManager.loginSilent();
1905
- if (!user) {
1906
- return null;
1907
- }
1908
- return this.getImxProvider(user);
5166
+ return this.passportImxProviderFactory.getProviderSilent();
1909
5167
  }
1910
5168
  async connectImx() {
1911
- const user = await this.authManager.login();
1912
- return this.getImxProvider(user);
5169
+ return this.passportImxProviderFactory.getProvider();
1913
5170
  }
1914
5171
  async loginCallback() {
1915
5172
  return this.authManager.loginCallback();
@@ -1929,18 +5186,6 @@ class Passport {
1929
5186
  const user = await this.authManager.getUser();
1930
5187
  return user?.accessToken;
1931
5188
  }
1932
- async registerUser(userAdminKeySigner, starkSigner, jwt) {
1933
- await registerPassport({
1934
- ethSigner: userAdminKeySigner,
1935
- starkSigner,
1936
- usersApi: this.immutableXClient.usersApi,
1937
- }, jwt);
1938
- const updatedUser = await this.authManager.requestRefreshTokenAfterRegistration();
1939
- if (!updatedUser) {
1940
- throw new PassportError('Failed to get refresh token', PassportErrorType.REFRESH_TOKEN_ERROR);
1941
- }
1942
- return updatedUser;
1943
- }
1944
5189
  }
1945
5190
 
1946
5191
  export { Passport, PassportError };