react-unified-auth 1.0.1

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