@snail-js/api 0.1.0

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,2951 @@
1
+ var __defProp = Object.defineProperty;
2
+ var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
3
+ var __publicField = (obj, key, value) => __defNormalProp(obj, typeof key !== "symbol" ? key + "" : key, value);
4
+ const apiKey = (apiInstance) => {
5
+ const { version, method, url, params, headers } = apiInstance;
6
+ return `[${method}]${version ? `-v${version}` : ""}-${url}${params ? `-${recordToString(params)}` : ""}${headers ? `-${recordToString(headers)}` : ""}`;
7
+ };
8
+ function recordToString(record) {
9
+ return Object.keys(record).map((key) => {
10
+ return `${key}=${record[key]}`;
11
+ }).sort((a, b) => a.localeCompare(b)).join("&");
12
+ }
13
+ function getResponseDataFromCache(cacheKey) {
14
+ return cacheKey;
15
+ }
16
+ function deepCopy(obj) {
17
+ if (typeof obj !== "object" || obj === null) {
18
+ return obj;
19
+ }
20
+ if (Array.isArray(obj)) {
21
+ return obj.map((item) => deepCopy(item));
22
+ }
23
+ const copy = {};
24
+ for (const key in obj) {
25
+ if (Object.prototype.hasOwnProperty.call(obj, key)) {
26
+ copy[key] = deepCopy(obj[key]);
27
+ }
28
+ }
29
+ return copy;
30
+ }
31
+ var RequestMethod = /* @__PURE__ */ ((RequestMethod2) => {
32
+ RequestMethod2["GET"] = "GET";
33
+ RequestMethod2["HEAD"] = "HEAD";
34
+ RequestMethod2["POST"] = "POST";
35
+ RequestMethod2["PUT"] = "PUT";
36
+ RequestMethod2["DELETE"] = "DELETE";
37
+ RequestMethod2["PATCH"] = "PATCH";
38
+ RequestMethod2["OPTIONS"] = "OPTIONS";
39
+ return RequestMethod2;
40
+ })(RequestMethod || {});
41
+ var VersioningType = /* @__PURE__ */ ((VersioningType2) => {
42
+ VersioningType2[VersioningType2["Uri"] = 0] = "Uri";
43
+ VersioningType2[VersioningType2["Header"] = 1] = "Header";
44
+ VersioningType2[VersioningType2["Query"] = 2] = "Query";
45
+ VersioningType2[VersioningType2["Custom"] = 3] = "Custom";
46
+ return VersioningType2;
47
+ })(VersioningType || {});
48
+ var CacheType = /* @__PURE__ */ ((CacheType2) => {
49
+ CacheType2[CacheType2["Memory"] = 0] = "Memory";
50
+ CacheType2[CacheType2["IndexDB"] = 1] = "IndexDB";
51
+ CacheType2[CacheType2["LocalStorage"] = 2] = "LocalStorage";
52
+ return CacheType2;
53
+ })(CacheType || {});
54
+ const versionHandlers = {
55
+ [VersioningType.Uri]: (version, versioning) => {
56
+ const prefix = versioning.prefix || "v";
57
+ return {
58
+ url: `${prefix}${version}`
59
+ };
60
+ },
61
+ [VersioningType.Header]: (version, versioning) => {
62
+ const headers = {
63
+ [versioning.header]: version
64
+ };
65
+ return {
66
+ headers
67
+ };
68
+ },
69
+ [VersioningType.Query]: (version, versioning) => {
70
+ const key = versioning.key || "version";
71
+ const separator = "?";
72
+ return {
73
+ url: `${separator}${key}=${version}`
74
+ };
75
+ },
76
+ [VersioningType.Custom]: (version, versioning) => {
77
+ return versioning.extractor({
78
+ version
79
+ });
80
+ }
81
+ };
82
+ function applyVersioning(version, versioning) {
83
+ const handler = versionHandlers[versioning.type];
84
+ return handler(
85
+ version,
86
+ versioning
87
+ );
88
+ }
89
+ class Api {
90
+ constructor(method, url, context, config) {
91
+ __publicField(this, "baseURL");
92
+ __publicField(this, "url");
93
+ __publicField(this, "data");
94
+ __publicField(this, "params");
95
+ __publicField(this, "headers");
96
+ __publicField(this, "key");
97
+ // public config: ApiConfig<R> | undefined;
98
+ __publicField(this, "method");
99
+ __publicField(this, "hitCache");
100
+ __publicField(this, "context");
101
+ __publicField(this, "version");
102
+ __publicField(this, "versioning");
103
+ __publicField(this, "name");
104
+ __publicField(this, "hitSource");
105
+ __publicField(this, "timeout");
106
+ __publicField(this, "transform");
107
+ __publicField(this, "pipes", []);
108
+ var _a;
109
+ const instance = this;
110
+ instance.name = config == null ? void 0 : config.name;
111
+ instance.name ?? this.context.cacheSource.push(this);
112
+ instance.hitSource = config == null ? void 0 : config.hitSource;
113
+ instance.method = method;
114
+ instance.url = url;
115
+ instance.params = config == null ? void 0 : config.params;
116
+ instance.headers = config == null ? void 0 : config.headers;
117
+ instance.transform = config == null ? void 0 : config.transform;
118
+ instance.context = context;
119
+ instance.version = (config == null ? void 0 : config.version) || ((_a = instance.context.versioning) == null ? void 0 : _a.defaultVersion);
120
+ this.timeout = (config == null ? void 0 : config.timeout) || this.context.options.timeout || 5e3;
121
+ this.handleVersioning();
122
+ this.key = apiKey(this);
123
+ }
124
+ handleVersioning(version) {
125
+ if (!this.context) return;
126
+ const { versioning } = this.context;
127
+ if (versioning) {
128
+ const { url, headers } = applyVersioning(
129
+ version || this.version,
130
+ versioning
131
+ );
132
+ this.versioning = {
133
+ url,
134
+ headers
135
+ };
136
+ }
137
+ return;
138
+ }
139
+ /**
140
+ *
141
+ * @param options 发送配置:子项params,data
142
+ * 泛型<R = any, E = any>R返回数据类型, E返回错误类型(code!=0)
143
+ * @returns
144
+ */
145
+ send(options) {
146
+ this.data = options == null ? void 0 : options.data;
147
+ this.params = options == null ? void 0 : options.params;
148
+ if ((options == null ? void 0 : options.params) || (options == null ? void 0 : options.data)) {
149
+ this.key = apiKey(this);
150
+ }
151
+ const version = (options == null ? void 0 : options.version) || this.version;
152
+ console.log("send version:", version);
153
+ this.handleVersioning(version);
154
+ return new Promise(async (resolve, reject) => {
155
+ var _a, _b, _c;
156
+ const { data, headers } = this.processRequestPipes();
157
+ this.data = data;
158
+ this.headers = headers;
159
+ this.key = apiKey(this);
160
+ const cachedResponse = await this.checkCache(version);
161
+ if (cachedResponse) {
162
+ const versionUrl = ((_a = this.versioning) == null ? void 0 : _a.url) ? (_b = this.versioning) == null ? void 0 : _b.url : "";
163
+ console.warn(
164
+ `请求[${this.context.baseURL}/${versionUrl == "" ? "" : `${versionUrl}/`}${this.url}]命中缓存`
165
+ );
166
+ return resolve({
167
+ error: null,
168
+ data: cachedResponse,
169
+ hitCache: this.hitCache,
170
+ Catch: (handler) => handler()
171
+ });
172
+ }
173
+ try {
174
+ const response = await this.sendRequest();
175
+ const { code, data: data2, message } = response.data;
176
+ if (code !== 0) {
177
+ reject({
178
+ error: new Error(message, { cause: { code, data: data2 } }),
179
+ data: null,
180
+ hitCache: false,
181
+ Catch: (handler) => handler()
182
+ });
183
+ }
184
+ const transformedData = this.transform ? this.transform(data2) : data2;
185
+ (_c = this.context.cacheStorage) == null ? void 0 : _c.set(this.key, transformedData);
186
+ resolve({
187
+ error: null,
188
+ data: transformedData,
189
+ hitCache: false,
190
+ Catch: (handler) => handler()
191
+ });
192
+ this.lapsed(version);
193
+ } catch (error) {
194
+ resolve({
195
+ error,
196
+ data: null,
197
+ hitCache: false,
198
+ Catch: (handler) => handler(error)
199
+ });
200
+ }
201
+ });
202
+ }
203
+ async checkCache(version) {
204
+ if (!this.context.cacheStorage) return null;
205
+ return new Promise(async (resolve) => {
206
+ if (!this.context.cacheStorage) {
207
+ return resolve(null);
208
+ }
209
+ let tempKey;
210
+ if (version) {
211
+ tempKey = apiKey({
212
+ ...this,
213
+ version
214
+ });
215
+ }
216
+ const { error, data } = await this.context.cacheStorage.get(
217
+ tempKey ? tempKey : this.key
218
+ );
219
+ if (error) {
220
+ console.warn(error);
221
+ return resolve(null);
222
+ }
223
+ this.hitCache = true;
224
+ return resolve(data);
225
+ });
226
+ }
227
+ async delCache(version) {
228
+ let tempKey;
229
+ if (version) {
230
+ tempKey = apiKey({
231
+ ...this,
232
+ version
233
+ });
234
+ }
235
+ await this.context.cacheStorage.delete(tempKey ? tempKey : this.key);
236
+ }
237
+ use(pipe) {
238
+ this.pipes.push(pipe);
239
+ }
240
+ processRequestPipes() {
241
+ let requestData = this.data;
242
+ let requestHeaders = this.headers || {};
243
+ if (this.pipes.length > 0) {
244
+ const pipeResult = this.pipes.reduce(
245
+ (result, pipe) => {
246
+ return pipe(result.data, result.headers);
247
+ },
248
+ { data: requestData, headers: requestHeaders }
249
+ );
250
+ requestData = pipeResult.data;
251
+ requestHeaders = pipeResult.headers;
252
+ }
253
+ return { data: requestData, headers: requestHeaders };
254
+ }
255
+ async sendRequest() {
256
+ var _a, _b, _c;
257
+ const headers = {
258
+ ...this.headers,
259
+ ...(_a = this.versioning) == null ? void 0 : _a.headers
260
+ };
261
+ const versionUrl = ((_b = this.versioning) == null ? void 0 : _b.url) ? (_c = this.versioning) == null ? void 0 : _c.url : "";
262
+ return await this.context.axiosInstance.request({
263
+ url: `${versionUrl}/${this.url}`,
264
+ method: this.method,
265
+ data: this.data,
266
+ headers,
267
+ params: this.params,
268
+ timeout: this.timeout
269
+ });
270
+ }
271
+ async lapsed(version) {
272
+ if (!this.hitSource) return;
273
+ if (typeof this.hitSource === "string") {
274
+ const { cacheSource } = this.context;
275
+ const source = cacheSource.find((api) => api.name == this.hitSource);
276
+ source ?? source.delCache(version);
277
+ } else {
278
+ this.hitSource.delCache(version);
279
+ }
280
+ }
281
+ }
282
+ function bind(fn, thisArg) {
283
+ return function wrap() {
284
+ return fn.apply(thisArg, arguments);
285
+ };
286
+ }
287
+ const { toString } = Object.prototype;
288
+ const { getPrototypeOf } = Object;
289
+ const kindOf = /* @__PURE__ */ ((cache) => (thing) => {
290
+ const str = toString.call(thing);
291
+ return cache[str] || (cache[str] = str.slice(8, -1).toLowerCase());
292
+ })(/* @__PURE__ */ Object.create(null));
293
+ const kindOfTest = (type) => {
294
+ type = type.toLowerCase();
295
+ return (thing) => kindOf(thing) === type;
296
+ };
297
+ const typeOfTest = (type) => (thing) => typeof thing === type;
298
+ const { isArray } = Array;
299
+ const isUndefined = typeOfTest("undefined");
300
+ function isBuffer(val) {
301
+ return val !== null && !isUndefined(val) && val.constructor !== null && !isUndefined(val.constructor) && isFunction(val.constructor.isBuffer) && val.constructor.isBuffer(val);
302
+ }
303
+ const isArrayBuffer = kindOfTest("ArrayBuffer");
304
+ function isArrayBufferView(val) {
305
+ let result;
306
+ if (typeof ArrayBuffer !== "undefined" && ArrayBuffer.isView) {
307
+ result = ArrayBuffer.isView(val);
308
+ } else {
309
+ result = val && val.buffer && isArrayBuffer(val.buffer);
310
+ }
311
+ return result;
312
+ }
313
+ const isString = typeOfTest("string");
314
+ const isFunction = typeOfTest("function");
315
+ const isNumber = typeOfTest("number");
316
+ const isObject = (thing) => thing !== null && typeof thing === "object";
317
+ const isBoolean = (thing) => thing === true || thing === false;
318
+ const isPlainObject = (val) => {
319
+ if (kindOf(val) !== "object") {
320
+ return false;
321
+ }
322
+ const prototype2 = getPrototypeOf(val);
323
+ return (prototype2 === null || prototype2 === Object.prototype || Object.getPrototypeOf(prototype2) === null) && !(Symbol.toStringTag in val) && !(Symbol.iterator in val);
324
+ };
325
+ const isDate = kindOfTest("Date");
326
+ const isFile = kindOfTest("File");
327
+ const isBlob = kindOfTest("Blob");
328
+ const isFileList = kindOfTest("FileList");
329
+ const isStream = (val) => isObject(val) && isFunction(val.pipe);
330
+ const isFormData = (thing) => {
331
+ let kind;
332
+ return thing && (typeof FormData === "function" && thing instanceof FormData || isFunction(thing.append) && ((kind = kindOf(thing)) === "formdata" || // detect form-data instance
333
+ kind === "object" && isFunction(thing.toString) && thing.toString() === "[object FormData]"));
334
+ };
335
+ const isURLSearchParams = kindOfTest("URLSearchParams");
336
+ const [isReadableStream, isRequest, isResponse, isHeaders] = ["ReadableStream", "Request", "Response", "Headers"].map(kindOfTest);
337
+ const trim = (str) => str.trim ? str.trim() : str.replace(/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g, "");
338
+ function forEach(obj, fn, { allOwnKeys = false } = {}) {
339
+ if (obj === null || typeof obj === "undefined") {
340
+ return;
341
+ }
342
+ let i;
343
+ let l;
344
+ if (typeof obj !== "object") {
345
+ obj = [obj];
346
+ }
347
+ if (isArray(obj)) {
348
+ for (i = 0, l = obj.length; i < l; i++) {
349
+ fn.call(null, obj[i], i, obj);
350
+ }
351
+ } else {
352
+ const keys = allOwnKeys ? Object.getOwnPropertyNames(obj) : Object.keys(obj);
353
+ const len = keys.length;
354
+ let key;
355
+ for (i = 0; i < len; i++) {
356
+ key = keys[i];
357
+ fn.call(null, obj[key], key, obj);
358
+ }
359
+ }
360
+ }
361
+ function findKey(obj, key) {
362
+ key = key.toLowerCase();
363
+ const keys = Object.keys(obj);
364
+ let i = keys.length;
365
+ let _key;
366
+ while (i-- > 0) {
367
+ _key = keys[i];
368
+ if (key === _key.toLowerCase()) {
369
+ return _key;
370
+ }
371
+ }
372
+ return null;
373
+ }
374
+ const _global = (() => {
375
+ if (typeof globalThis !== "undefined") return globalThis;
376
+ return typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : global;
377
+ })();
378
+ const isContextDefined = (context) => !isUndefined(context) && context !== _global;
379
+ function merge() {
380
+ const { caseless } = isContextDefined(this) && this || {};
381
+ const result = {};
382
+ const assignValue = (val, key) => {
383
+ const targetKey = caseless && findKey(result, key) || key;
384
+ if (isPlainObject(result[targetKey]) && isPlainObject(val)) {
385
+ result[targetKey] = merge(result[targetKey], val);
386
+ } else if (isPlainObject(val)) {
387
+ result[targetKey] = merge({}, val);
388
+ } else if (isArray(val)) {
389
+ result[targetKey] = val.slice();
390
+ } else {
391
+ result[targetKey] = val;
392
+ }
393
+ };
394
+ for (let i = 0, l = arguments.length; i < l; i++) {
395
+ arguments[i] && forEach(arguments[i], assignValue);
396
+ }
397
+ return result;
398
+ }
399
+ const extend = (a, b, thisArg, { allOwnKeys } = {}) => {
400
+ forEach(b, (val, key) => {
401
+ if (thisArg && isFunction(val)) {
402
+ a[key] = bind(val, thisArg);
403
+ } else {
404
+ a[key] = val;
405
+ }
406
+ }, { allOwnKeys });
407
+ return a;
408
+ };
409
+ const stripBOM = (content) => {
410
+ if (content.charCodeAt(0) === 65279) {
411
+ content = content.slice(1);
412
+ }
413
+ return content;
414
+ };
415
+ const inherits = (constructor, superConstructor, props, descriptors2) => {
416
+ constructor.prototype = Object.create(superConstructor.prototype, descriptors2);
417
+ constructor.prototype.constructor = constructor;
418
+ Object.defineProperty(constructor, "super", {
419
+ value: superConstructor.prototype
420
+ });
421
+ props && Object.assign(constructor.prototype, props);
422
+ };
423
+ const toFlatObject = (sourceObj, destObj, filter2, propFilter) => {
424
+ let props;
425
+ let i;
426
+ let prop;
427
+ const merged = {};
428
+ destObj = destObj || {};
429
+ if (sourceObj == null) return destObj;
430
+ do {
431
+ props = Object.getOwnPropertyNames(sourceObj);
432
+ i = props.length;
433
+ while (i-- > 0) {
434
+ prop = props[i];
435
+ if ((!propFilter || propFilter(prop, sourceObj, destObj)) && !merged[prop]) {
436
+ destObj[prop] = sourceObj[prop];
437
+ merged[prop] = true;
438
+ }
439
+ }
440
+ sourceObj = filter2 !== false && getPrototypeOf(sourceObj);
441
+ } while (sourceObj && (!filter2 || filter2(sourceObj, destObj)) && sourceObj !== Object.prototype);
442
+ return destObj;
443
+ };
444
+ const endsWith = (str, searchString, position) => {
445
+ str = String(str);
446
+ if (position === void 0 || position > str.length) {
447
+ position = str.length;
448
+ }
449
+ position -= searchString.length;
450
+ const lastIndex = str.indexOf(searchString, position);
451
+ return lastIndex !== -1 && lastIndex === position;
452
+ };
453
+ const toArray = (thing) => {
454
+ if (!thing) return null;
455
+ if (isArray(thing)) return thing;
456
+ let i = thing.length;
457
+ if (!isNumber(i)) return null;
458
+ const arr = new Array(i);
459
+ while (i-- > 0) {
460
+ arr[i] = thing[i];
461
+ }
462
+ return arr;
463
+ };
464
+ const isTypedArray = /* @__PURE__ */ ((TypedArray) => {
465
+ return (thing) => {
466
+ return TypedArray && thing instanceof TypedArray;
467
+ };
468
+ })(typeof Uint8Array !== "undefined" && getPrototypeOf(Uint8Array));
469
+ const forEachEntry = (obj, fn) => {
470
+ const generator = obj && obj[Symbol.iterator];
471
+ const iterator = generator.call(obj);
472
+ let result;
473
+ while ((result = iterator.next()) && !result.done) {
474
+ const pair = result.value;
475
+ fn.call(obj, pair[0], pair[1]);
476
+ }
477
+ };
478
+ const matchAll = (regExp, str) => {
479
+ let matches;
480
+ const arr = [];
481
+ while ((matches = regExp.exec(str)) !== null) {
482
+ arr.push(matches);
483
+ }
484
+ return arr;
485
+ };
486
+ const isHTMLForm = kindOfTest("HTMLFormElement");
487
+ const toCamelCase = (str) => {
488
+ return str.toLowerCase().replace(
489
+ /[-_\s]([a-z\d])(\w*)/g,
490
+ function replacer(m, p1, p2) {
491
+ return p1.toUpperCase() + p2;
492
+ }
493
+ );
494
+ };
495
+ const hasOwnProperty = (({ hasOwnProperty: hasOwnProperty2 }) => (obj, prop) => hasOwnProperty2.call(obj, prop))(Object.prototype);
496
+ const isRegExp = kindOfTest("RegExp");
497
+ const reduceDescriptors = (obj, reducer) => {
498
+ const descriptors2 = Object.getOwnPropertyDescriptors(obj);
499
+ const reducedDescriptors = {};
500
+ forEach(descriptors2, (descriptor, name) => {
501
+ let ret;
502
+ if ((ret = reducer(descriptor, name, obj)) !== false) {
503
+ reducedDescriptors[name] = ret || descriptor;
504
+ }
505
+ });
506
+ Object.defineProperties(obj, reducedDescriptors);
507
+ };
508
+ const freezeMethods = (obj) => {
509
+ reduceDescriptors(obj, (descriptor, name) => {
510
+ if (isFunction(obj) && ["arguments", "caller", "callee"].indexOf(name) !== -1) {
511
+ return false;
512
+ }
513
+ const value = obj[name];
514
+ if (!isFunction(value)) return;
515
+ descriptor.enumerable = false;
516
+ if ("writable" in descriptor) {
517
+ descriptor.writable = false;
518
+ return;
519
+ }
520
+ if (!descriptor.set) {
521
+ descriptor.set = () => {
522
+ throw Error("Can not rewrite read-only method '" + name + "'");
523
+ };
524
+ }
525
+ });
526
+ };
527
+ const toObjectSet = (arrayOrString, delimiter) => {
528
+ const obj = {};
529
+ const define = (arr) => {
530
+ arr.forEach((value) => {
531
+ obj[value] = true;
532
+ });
533
+ };
534
+ isArray(arrayOrString) ? define(arrayOrString) : define(String(arrayOrString).split(delimiter));
535
+ return obj;
536
+ };
537
+ const noop = () => {
538
+ };
539
+ const toFiniteNumber = (value, defaultValue) => {
540
+ return value != null && Number.isFinite(value = +value) ? value : defaultValue;
541
+ };
542
+ const ALPHA = "abcdefghijklmnopqrstuvwxyz";
543
+ const DIGIT = "0123456789";
544
+ const ALPHABET = {
545
+ DIGIT,
546
+ ALPHA,
547
+ ALPHA_DIGIT: ALPHA + ALPHA.toUpperCase() + DIGIT
548
+ };
549
+ const generateString = (size = 16, alphabet = ALPHABET.ALPHA_DIGIT) => {
550
+ let str = "";
551
+ const { length } = alphabet;
552
+ while (size--) {
553
+ str += alphabet[Math.random() * length | 0];
554
+ }
555
+ return str;
556
+ };
557
+ function isSpecCompliantForm(thing) {
558
+ return !!(thing && isFunction(thing.append) && thing[Symbol.toStringTag] === "FormData" && thing[Symbol.iterator]);
559
+ }
560
+ const toJSONObject = (obj) => {
561
+ const stack = new Array(10);
562
+ const visit = (source, i) => {
563
+ if (isObject(source)) {
564
+ if (stack.indexOf(source) >= 0) {
565
+ return;
566
+ }
567
+ if (!("toJSON" in source)) {
568
+ stack[i] = source;
569
+ const target = isArray(source) ? [] : {};
570
+ forEach(source, (value, key) => {
571
+ const reducedValue = visit(value, i + 1);
572
+ !isUndefined(reducedValue) && (target[key] = reducedValue);
573
+ });
574
+ stack[i] = void 0;
575
+ return target;
576
+ }
577
+ }
578
+ return source;
579
+ };
580
+ return visit(obj, 0);
581
+ };
582
+ const isAsyncFn = kindOfTest("AsyncFunction");
583
+ const isThenable = (thing) => thing && (isObject(thing) || isFunction(thing)) && isFunction(thing.then) && isFunction(thing.catch);
584
+ const _setImmediate = ((setImmediateSupported, postMessageSupported) => {
585
+ if (setImmediateSupported) {
586
+ return setImmediate;
587
+ }
588
+ return postMessageSupported ? ((token, callbacks) => {
589
+ _global.addEventListener("message", ({ source, data }) => {
590
+ if (source === _global && data === token) {
591
+ callbacks.length && callbacks.shift()();
592
+ }
593
+ }, false);
594
+ return (cb) => {
595
+ callbacks.push(cb);
596
+ _global.postMessage(token, "*");
597
+ };
598
+ })(`axios@${Math.random()}`, []) : (cb) => setTimeout(cb);
599
+ })(
600
+ typeof setImmediate === "function",
601
+ isFunction(_global.postMessage)
602
+ );
603
+ const asap = typeof queueMicrotask !== "undefined" ? queueMicrotask.bind(_global) : typeof process !== "undefined" && process.nextTick || _setImmediate;
604
+ const utils$1 = {
605
+ isArray,
606
+ isArrayBuffer,
607
+ isBuffer,
608
+ isFormData,
609
+ isArrayBufferView,
610
+ isString,
611
+ isNumber,
612
+ isBoolean,
613
+ isObject,
614
+ isPlainObject,
615
+ isReadableStream,
616
+ isRequest,
617
+ isResponse,
618
+ isHeaders,
619
+ isUndefined,
620
+ isDate,
621
+ isFile,
622
+ isBlob,
623
+ isRegExp,
624
+ isFunction,
625
+ isStream,
626
+ isURLSearchParams,
627
+ isTypedArray,
628
+ isFileList,
629
+ forEach,
630
+ merge,
631
+ extend,
632
+ trim,
633
+ stripBOM,
634
+ inherits,
635
+ toFlatObject,
636
+ kindOf,
637
+ kindOfTest,
638
+ endsWith,
639
+ toArray,
640
+ forEachEntry,
641
+ matchAll,
642
+ isHTMLForm,
643
+ hasOwnProperty,
644
+ hasOwnProp: hasOwnProperty,
645
+ // an alias to avoid ESLint no-prototype-builtins detection
646
+ reduceDescriptors,
647
+ freezeMethods,
648
+ toObjectSet,
649
+ toCamelCase,
650
+ noop,
651
+ toFiniteNumber,
652
+ findKey,
653
+ global: _global,
654
+ isContextDefined,
655
+ ALPHABET,
656
+ generateString,
657
+ isSpecCompliantForm,
658
+ toJSONObject,
659
+ isAsyncFn,
660
+ isThenable,
661
+ setImmediate: _setImmediate,
662
+ asap
663
+ };
664
+ function AxiosError(message, code, config, request, response) {
665
+ Error.call(this);
666
+ if (Error.captureStackTrace) {
667
+ Error.captureStackTrace(this, this.constructor);
668
+ } else {
669
+ this.stack = new Error().stack;
670
+ }
671
+ this.message = message;
672
+ this.name = "AxiosError";
673
+ code && (this.code = code);
674
+ config && (this.config = config);
675
+ request && (this.request = request);
676
+ if (response) {
677
+ this.response = response;
678
+ this.status = response.status ? response.status : null;
679
+ }
680
+ }
681
+ utils$1.inherits(AxiosError, Error, {
682
+ toJSON: function toJSON() {
683
+ return {
684
+ // Standard
685
+ message: this.message,
686
+ name: this.name,
687
+ // Microsoft
688
+ description: this.description,
689
+ number: this.number,
690
+ // Mozilla
691
+ fileName: this.fileName,
692
+ lineNumber: this.lineNumber,
693
+ columnNumber: this.columnNumber,
694
+ stack: this.stack,
695
+ // Axios
696
+ config: utils$1.toJSONObject(this.config),
697
+ code: this.code,
698
+ status: this.status
699
+ };
700
+ }
701
+ });
702
+ const prototype$1 = AxiosError.prototype;
703
+ const descriptors = {};
704
+ [
705
+ "ERR_BAD_OPTION_VALUE",
706
+ "ERR_BAD_OPTION",
707
+ "ECONNABORTED",
708
+ "ETIMEDOUT",
709
+ "ERR_NETWORK",
710
+ "ERR_FR_TOO_MANY_REDIRECTS",
711
+ "ERR_DEPRECATED",
712
+ "ERR_BAD_RESPONSE",
713
+ "ERR_BAD_REQUEST",
714
+ "ERR_CANCELED",
715
+ "ERR_NOT_SUPPORT",
716
+ "ERR_INVALID_URL"
717
+ // eslint-disable-next-line func-names
718
+ ].forEach((code) => {
719
+ descriptors[code] = { value: code };
720
+ });
721
+ Object.defineProperties(AxiosError, descriptors);
722
+ Object.defineProperty(prototype$1, "isAxiosError", { value: true });
723
+ AxiosError.from = (error, code, config, request, response, customProps) => {
724
+ const axiosError = Object.create(prototype$1);
725
+ utils$1.toFlatObject(error, axiosError, function filter2(obj) {
726
+ return obj !== Error.prototype;
727
+ }, (prop) => {
728
+ return prop !== "isAxiosError";
729
+ });
730
+ AxiosError.call(axiosError, error.message, code, config, request, response);
731
+ axiosError.cause = error;
732
+ axiosError.name = error.name;
733
+ customProps && Object.assign(axiosError, customProps);
734
+ return axiosError;
735
+ };
736
+ const httpAdapter = null;
737
+ function isVisitable(thing) {
738
+ return utils$1.isPlainObject(thing) || utils$1.isArray(thing);
739
+ }
740
+ function removeBrackets(key) {
741
+ return utils$1.endsWith(key, "[]") ? key.slice(0, -2) : key;
742
+ }
743
+ function renderKey(path, key, dots) {
744
+ if (!path) return key;
745
+ return path.concat(key).map(function each(token, i) {
746
+ token = removeBrackets(token);
747
+ return !dots && i ? "[" + token + "]" : token;
748
+ }).join(dots ? "." : "");
749
+ }
750
+ function isFlatArray(arr) {
751
+ return utils$1.isArray(arr) && !arr.some(isVisitable);
752
+ }
753
+ const predicates = utils$1.toFlatObject(utils$1, {}, null, function filter(prop) {
754
+ return /^is[A-Z]/.test(prop);
755
+ });
756
+ function toFormData(obj, formData, options) {
757
+ if (!utils$1.isObject(obj)) {
758
+ throw new TypeError("target must be an object");
759
+ }
760
+ formData = formData || new FormData();
761
+ options = utils$1.toFlatObject(options, {
762
+ metaTokens: true,
763
+ dots: false,
764
+ indexes: false
765
+ }, false, function defined(option, source) {
766
+ return !utils$1.isUndefined(source[option]);
767
+ });
768
+ const metaTokens = options.metaTokens;
769
+ const visitor = options.visitor || defaultVisitor;
770
+ const dots = options.dots;
771
+ const indexes = options.indexes;
772
+ const _Blob = options.Blob || typeof Blob !== "undefined" && Blob;
773
+ const useBlob = _Blob && utils$1.isSpecCompliantForm(formData);
774
+ if (!utils$1.isFunction(visitor)) {
775
+ throw new TypeError("visitor must be a function");
776
+ }
777
+ function convertValue(value) {
778
+ if (value === null) return "";
779
+ if (utils$1.isDate(value)) {
780
+ return value.toISOString();
781
+ }
782
+ if (!useBlob && utils$1.isBlob(value)) {
783
+ throw new AxiosError("Blob is not supported. Use a Buffer instead.");
784
+ }
785
+ if (utils$1.isArrayBuffer(value) || utils$1.isTypedArray(value)) {
786
+ return useBlob && typeof Blob === "function" ? new Blob([value]) : Buffer.from(value);
787
+ }
788
+ return value;
789
+ }
790
+ function defaultVisitor(value, key, path) {
791
+ let arr = value;
792
+ if (value && !path && typeof value === "object") {
793
+ if (utils$1.endsWith(key, "{}")) {
794
+ key = metaTokens ? key : key.slice(0, -2);
795
+ value = JSON.stringify(value);
796
+ } else if (utils$1.isArray(value) && isFlatArray(value) || (utils$1.isFileList(value) || utils$1.endsWith(key, "[]")) && (arr = utils$1.toArray(value))) {
797
+ key = removeBrackets(key);
798
+ arr.forEach(function each(el, index) {
799
+ !(utils$1.isUndefined(el) || el === null) && formData.append(
800
+ // eslint-disable-next-line no-nested-ternary
801
+ indexes === true ? renderKey([key], index, dots) : indexes === null ? key : key + "[]",
802
+ convertValue(el)
803
+ );
804
+ });
805
+ return false;
806
+ }
807
+ }
808
+ if (isVisitable(value)) {
809
+ return true;
810
+ }
811
+ formData.append(renderKey(path, key, dots), convertValue(value));
812
+ return false;
813
+ }
814
+ const stack = [];
815
+ const exposedHelpers = Object.assign(predicates, {
816
+ defaultVisitor,
817
+ convertValue,
818
+ isVisitable
819
+ });
820
+ function build(value, path) {
821
+ if (utils$1.isUndefined(value)) return;
822
+ if (stack.indexOf(value) !== -1) {
823
+ throw Error("Circular reference detected in " + path.join("."));
824
+ }
825
+ stack.push(value);
826
+ utils$1.forEach(value, function each(el, key) {
827
+ const result = !(utils$1.isUndefined(el) || el === null) && visitor.call(
828
+ formData,
829
+ el,
830
+ utils$1.isString(key) ? key.trim() : key,
831
+ path,
832
+ exposedHelpers
833
+ );
834
+ if (result === true) {
835
+ build(el, path ? path.concat(key) : [key]);
836
+ }
837
+ });
838
+ stack.pop();
839
+ }
840
+ if (!utils$1.isObject(obj)) {
841
+ throw new TypeError("data must be an object");
842
+ }
843
+ build(obj);
844
+ return formData;
845
+ }
846
+ function encode$1(str) {
847
+ const charMap = {
848
+ "!": "%21",
849
+ "'": "%27",
850
+ "(": "%28",
851
+ ")": "%29",
852
+ "~": "%7E",
853
+ "%20": "+",
854
+ "%00": "\0"
855
+ };
856
+ return encodeURIComponent(str).replace(/[!'()~]|%20|%00/g, function replacer(match) {
857
+ return charMap[match];
858
+ });
859
+ }
860
+ function AxiosURLSearchParams(params, options) {
861
+ this._pairs = [];
862
+ params && toFormData(params, this, options);
863
+ }
864
+ const prototype = AxiosURLSearchParams.prototype;
865
+ prototype.append = function append(name, value) {
866
+ this._pairs.push([name, value]);
867
+ };
868
+ prototype.toString = function toString2(encoder) {
869
+ const _encode = encoder ? function(value) {
870
+ return encoder.call(this, value, encode$1);
871
+ } : encode$1;
872
+ return this._pairs.map(function each(pair) {
873
+ return _encode(pair[0]) + "=" + _encode(pair[1]);
874
+ }, "").join("&");
875
+ };
876
+ function encode(val) {
877
+ return encodeURIComponent(val).replace(/%3A/gi, ":").replace(/%24/g, "$").replace(/%2C/gi, ",").replace(/%20/g, "+").replace(/%5B/gi, "[").replace(/%5D/gi, "]");
878
+ }
879
+ function buildURL(url, params, options) {
880
+ if (!params) {
881
+ return url;
882
+ }
883
+ const _encode = options && options.encode || encode;
884
+ if (utils$1.isFunction(options)) {
885
+ options = {
886
+ serialize: options
887
+ };
888
+ }
889
+ const serializeFn = options && options.serialize;
890
+ let serializedParams;
891
+ if (serializeFn) {
892
+ serializedParams = serializeFn(params, options);
893
+ } else {
894
+ serializedParams = utils$1.isURLSearchParams(params) ? params.toString() : new AxiosURLSearchParams(params, options).toString(_encode);
895
+ }
896
+ if (serializedParams) {
897
+ const hashmarkIndex = url.indexOf("#");
898
+ if (hashmarkIndex !== -1) {
899
+ url = url.slice(0, hashmarkIndex);
900
+ }
901
+ url += (url.indexOf("?") === -1 ? "?" : "&") + serializedParams;
902
+ }
903
+ return url;
904
+ }
905
+ class InterceptorManager {
906
+ constructor() {
907
+ this.handlers = [];
908
+ }
909
+ /**
910
+ * Add a new interceptor to the stack
911
+ *
912
+ * @param {Function} fulfilled The function to handle `then` for a `Promise`
913
+ * @param {Function} rejected The function to handle `reject` for a `Promise`
914
+ *
915
+ * @return {Number} An ID used to remove interceptor later
916
+ */
917
+ use(fulfilled, rejected, options) {
918
+ this.handlers.push({
919
+ fulfilled,
920
+ rejected,
921
+ synchronous: options ? options.synchronous : false,
922
+ runWhen: options ? options.runWhen : null
923
+ });
924
+ return this.handlers.length - 1;
925
+ }
926
+ /**
927
+ * Remove an interceptor from the stack
928
+ *
929
+ * @param {Number} id The ID that was returned by `use`
930
+ *
931
+ * @returns {Boolean} `true` if the interceptor was removed, `false` otherwise
932
+ */
933
+ eject(id) {
934
+ if (this.handlers[id]) {
935
+ this.handlers[id] = null;
936
+ }
937
+ }
938
+ /**
939
+ * Clear all interceptors from the stack
940
+ *
941
+ * @returns {void}
942
+ */
943
+ clear() {
944
+ if (this.handlers) {
945
+ this.handlers = [];
946
+ }
947
+ }
948
+ /**
949
+ * Iterate over all the registered interceptors
950
+ *
951
+ * This method is particularly useful for skipping over any
952
+ * interceptors that may have become `null` calling `eject`.
953
+ *
954
+ * @param {Function} fn The function to call for each interceptor
955
+ *
956
+ * @returns {void}
957
+ */
958
+ forEach(fn) {
959
+ utils$1.forEach(this.handlers, function forEachHandler(h) {
960
+ if (h !== null) {
961
+ fn(h);
962
+ }
963
+ });
964
+ }
965
+ }
966
+ const transitionalDefaults = {
967
+ silentJSONParsing: true,
968
+ forcedJSONParsing: true,
969
+ clarifyTimeoutError: false
970
+ };
971
+ const URLSearchParams$1 = typeof URLSearchParams !== "undefined" ? URLSearchParams : AxiosURLSearchParams;
972
+ const FormData$1 = typeof FormData !== "undefined" ? FormData : null;
973
+ const Blob$1 = typeof Blob !== "undefined" ? Blob : null;
974
+ const platform$1 = {
975
+ isBrowser: true,
976
+ classes: {
977
+ URLSearchParams: URLSearchParams$1,
978
+ FormData: FormData$1,
979
+ Blob: Blob$1
980
+ },
981
+ protocols: ["http", "https", "file", "blob", "url", "data"]
982
+ };
983
+ const hasBrowserEnv = typeof window !== "undefined" && typeof document !== "undefined";
984
+ const _navigator = typeof navigator === "object" && navigator || void 0;
985
+ const hasStandardBrowserEnv = hasBrowserEnv && (!_navigator || ["ReactNative", "NativeScript", "NS"].indexOf(_navigator.product) < 0);
986
+ const hasStandardBrowserWebWorkerEnv = (() => {
987
+ return typeof WorkerGlobalScope !== "undefined" && // eslint-disable-next-line no-undef
988
+ self instanceof WorkerGlobalScope && typeof self.importScripts === "function";
989
+ })();
990
+ const origin = hasBrowserEnv && window.location.href || "http://localhost";
991
+ const utils = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({
992
+ __proto__: null,
993
+ hasBrowserEnv,
994
+ hasStandardBrowserEnv,
995
+ hasStandardBrowserWebWorkerEnv,
996
+ navigator: _navigator,
997
+ origin
998
+ }, Symbol.toStringTag, { value: "Module" }));
999
+ const platform = {
1000
+ ...utils,
1001
+ ...platform$1
1002
+ };
1003
+ function toURLEncodedForm(data, options) {
1004
+ return toFormData(data, new platform.classes.URLSearchParams(), Object.assign({
1005
+ visitor: function(value, key, path, helpers) {
1006
+ if (platform.isNode && utils$1.isBuffer(value)) {
1007
+ this.append(key, value.toString("base64"));
1008
+ return false;
1009
+ }
1010
+ return helpers.defaultVisitor.apply(this, arguments);
1011
+ }
1012
+ }, options));
1013
+ }
1014
+ function parsePropPath(name) {
1015
+ return utils$1.matchAll(/\w+|\[(\w*)]/g, name).map((match) => {
1016
+ return match[0] === "[]" ? "" : match[1] || match[0];
1017
+ });
1018
+ }
1019
+ function arrayToObject(arr) {
1020
+ const obj = {};
1021
+ const keys = Object.keys(arr);
1022
+ let i;
1023
+ const len = keys.length;
1024
+ let key;
1025
+ for (i = 0; i < len; i++) {
1026
+ key = keys[i];
1027
+ obj[key] = arr[key];
1028
+ }
1029
+ return obj;
1030
+ }
1031
+ function formDataToJSON(formData) {
1032
+ function buildPath(path, value, target, index) {
1033
+ let name = path[index++];
1034
+ if (name === "__proto__") return true;
1035
+ const isNumericKey = Number.isFinite(+name);
1036
+ const isLast = index >= path.length;
1037
+ name = !name && utils$1.isArray(target) ? target.length : name;
1038
+ if (isLast) {
1039
+ if (utils$1.hasOwnProp(target, name)) {
1040
+ target[name] = [target[name], value];
1041
+ } else {
1042
+ target[name] = value;
1043
+ }
1044
+ return !isNumericKey;
1045
+ }
1046
+ if (!target[name] || !utils$1.isObject(target[name])) {
1047
+ target[name] = [];
1048
+ }
1049
+ const result = buildPath(path, value, target[name], index);
1050
+ if (result && utils$1.isArray(target[name])) {
1051
+ target[name] = arrayToObject(target[name]);
1052
+ }
1053
+ return !isNumericKey;
1054
+ }
1055
+ if (utils$1.isFormData(formData) && utils$1.isFunction(formData.entries)) {
1056
+ const obj = {};
1057
+ utils$1.forEachEntry(formData, (name, value) => {
1058
+ buildPath(parsePropPath(name), value, obj, 0);
1059
+ });
1060
+ return obj;
1061
+ }
1062
+ return null;
1063
+ }
1064
+ function stringifySafely(rawValue, parser, encoder) {
1065
+ if (utils$1.isString(rawValue)) {
1066
+ try {
1067
+ (parser || JSON.parse)(rawValue);
1068
+ return utils$1.trim(rawValue);
1069
+ } catch (e) {
1070
+ if (e.name !== "SyntaxError") {
1071
+ throw e;
1072
+ }
1073
+ }
1074
+ }
1075
+ return (0, JSON.stringify)(rawValue);
1076
+ }
1077
+ const defaults = {
1078
+ transitional: transitionalDefaults,
1079
+ adapter: ["xhr", "http", "fetch"],
1080
+ transformRequest: [function transformRequest(data, headers) {
1081
+ const contentType = headers.getContentType() || "";
1082
+ const hasJSONContentType = contentType.indexOf("application/json") > -1;
1083
+ const isObjectPayload = utils$1.isObject(data);
1084
+ if (isObjectPayload && utils$1.isHTMLForm(data)) {
1085
+ data = new FormData(data);
1086
+ }
1087
+ const isFormData2 = utils$1.isFormData(data);
1088
+ if (isFormData2) {
1089
+ return hasJSONContentType ? JSON.stringify(formDataToJSON(data)) : data;
1090
+ }
1091
+ if (utils$1.isArrayBuffer(data) || utils$1.isBuffer(data) || utils$1.isStream(data) || utils$1.isFile(data) || utils$1.isBlob(data) || utils$1.isReadableStream(data)) {
1092
+ return data;
1093
+ }
1094
+ if (utils$1.isArrayBufferView(data)) {
1095
+ return data.buffer;
1096
+ }
1097
+ if (utils$1.isURLSearchParams(data)) {
1098
+ headers.setContentType("application/x-www-form-urlencoded;charset=utf-8", false);
1099
+ return data.toString();
1100
+ }
1101
+ let isFileList2;
1102
+ if (isObjectPayload) {
1103
+ if (contentType.indexOf("application/x-www-form-urlencoded") > -1) {
1104
+ return toURLEncodedForm(data, this.formSerializer).toString();
1105
+ }
1106
+ if ((isFileList2 = utils$1.isFileList(data)) || contentType.indexOf("multipart/form-data") > -1) {
1107
+ const _FormData = this.env && this.env.FormData;
1108
+ return toFormData(
1109
+ isFileList2 ? { "files[]": data } : data,
1110
+ _FormData && new _FormData(),
1111
+ this.formSerializer
1112
+ );
1113
+ }
1114
+ }
1115
+ if (isObjectPayload || hasJSONContentType) {
1116
+ headers.setContentType("application/json", false);
1117
+ return stringifySafely(data);
1118
+ }
1119
+ return data;
1120
+ }],
1121
+ transformResponse: [function transformResponse(data) {
1122
+ const transitional2 = this.transitional || defaults.transitional;
1123
+ const forcedJSONParsing = transitional2 && transitional2.forcedJSONParsing;
1124
+ const JSONRequested = this.responseType === "json";
1125
+ if (utils$1.isResponse(data) || utils$1.isReadableStream(data)) {
1126
+ return data;
1127
+ }
1128
+ if (data && utils$1.isString(data) && (forcedJSONParsing && !this.responseType || JSONRequested)) {
1129
+ const silentJSONParsing = transitional2 && transitional2.silentJSONParsing;
1130
+ const strictJSONParsing = !silentJSONParsing && JSONRequested;
1131
+ try {
1132
+ return JSON.parse(data);
1133
+ } catch (e) {
1134
+ if (strictJSONParsing) {
1135
+ if (e.name === "SyntaxError") {
1136
+ throw AxiosError.from(e, AxiosError.ERR_BAD_RESPONSE, this, null, this.response);
1137
+ }
1138
+ throw e;
1139
+ }
1140
+ }
1141
+ }
1142
+ return data;
1143
+ }],
1144
+ /**
1145
+ * A timeout in milliseconds to abort a request. If set to 0 (default) a
1146
+ * timeout is not created.
1147
+ */
1148
+ timeout: 0,
1149
+ xsrfCookieName: "XSRF-TOKEN",
1150
+ xsrfHeaderName: "X-XSRF-TOKEN",
1151
+ maxContentLength: -1,
1152
+ maxBodyLength: -1,
1153
+ env: {
1154
+ FormData: platform.classes.FormData,
1155
+ Blob: platform.classes.Blob
1156
+ },
1157
+ validateStatus: function validateStatus(status) {
1158
+ return status >= 200 && status < 300;
1159
+ },
1160
+ headers: {
1161
+ common: {
1162
+ "Accept": "application/json, text/plain, */*",
1163
+ "Content-Type": void 0
1164
+ }
1165
+ }
1166
+ };
1167
+ utils$1.forEach(["delete", "get", "head", "post", "put", "patch"], (method) => {
1168
+ defaults.headers[method] = {};
1169
+ });
1170
+ const ignoreDuplicateOf = utils$1.toObjectSet([
1171
+ "age",
1172
+ "authorization",
1173
+ "content-length",
1174
+ "content-type",
1175
+ "etag",
1176
+ "expires",
1177
+ "from",
1178
+ "host",
1179
+ "if-modified-since",
1180
+ "if-unmodified-since",
1181
+ "last-modified",
1182
+ "location",
1183
+ "max-forwards",
1184
+ "proxy-authorization",
1185
+ "referer",
1186
+ "retry-after",
1187
+ "user-agent"
1188
+ ]);
1189
+ const parseHeaders = (rawHeaders) => {
1190
+ const parsed = {};
1191
+ let key;
1192
+ let val;
1193
+ let i;
1194
+ rawHeaders && rawHeaders.split("\n").forEach(function parser(line) {
1195
+ i = line.indexOf(":");
1196
+ key = line.substring(0, i).trim().toLowerCase();
1197
+ val = line.substring(i + 1).trim();
1198
+ if (!key || parsed[key] && ignoreDuplicateOf[key]) {
1199
+ return;
1200
+ }
1201
+ if (key === "set-cookie") {
1202
+ if (parsed[key]) {
1203
+ parsed[key].push(val);
1204
+ } else {
1205
+ parsed[key] = [val];
1206
+ }
1207
+ } else {
1208
+ parsed[key] = parsed[key] ? parsed[key] + ", " + val : val;
1209
+ }
1210
+ });
1211
+ return parsed;
1212
+ };
1213
+ const $internals = Symbol("internals");
1214
+ function normalizeHeader(header) {
1215
+ return header && String(header).trim().toLowerCase();
1216
+ }
1217
+ function normalizeValue(value) {
1218
+ if (value === false || value == null) {
1219
+ return value;
1220
+ }
1221
+ return utils$1.isArray(value) ? value.map(normalizeValue) : String(value);
1222
+ }
1223
+ function parseTokens(str) {
1224
+ const tokens = /* @__PURE__ */ Object.create(null);
1225
+ const tokensRE = /([^\s,;=]+)\s*(?:=\s*([^,;]+))?/g;
1226
+ let match;
1227
+ while (match = tokensRE.exec(str)) {
1228
+ tokens[match[1]] = match[2];
1229
+ }
1230
+ return tokens;
1231
+ }
1232
+ const isValidHeaderName = (str) => /^[-_a-zA-Z0-9^`|~,!#$%&'*+.]+$/.test(str.trim());
1233
+ function matchHeaderValue(context, value, header, filter2, isHeaderNameFilter) {
1234
+ if (utils$1.isFunction(filter2)) {
1235
+ return filter2.call(this, value, header);
1236
+ }
1237
+ if (isHeaderNameFilter) {
1238
+ value = header;
1239
+ }
1240
+ if (!utils$1.isString(value)) return;
1241
+ if (utils$1.isString(filter2)) {
1242
+ return value.indexOf(filter2) !== -1;
1243
+ }
1244
+ if (utils$1.isRegExp(filter2)) {
1245
+ return filter2.test(value);
1246
+ }
1247
+ }
1248
+ function formatHeader(header) {
1249
+ return header.trim().toLowerCase().replace(/([a-z\d])(\w*)/g, (w, char, str) => {
1250
+ return char.toUpperCase() + str;
1251
+ });
1252
+ }
1253
+ function buildAccessors(obj, header) {
1254
+ const accessorName = utils$1.toCamelCase(" " + header);
1255
+ ["get", "set", "has"].forEach((methodName) => {
1256
+ Object.defineProperty(obj, methodName + accessorName, {
1257
+ value: function(arg1, arg2, arg3) {
1258
+ return this[methodName].call(this, header, arg1, arg2, arg3);
1259
+ },
1260
+ configurable: true
1261
+ });
1262
+ });
1263
+ }
1264
+ class AxiosHeaders {
1265
+ constructor(headers) {
1266
+ headers && this.set(headers);
1267
+ }
1268
+ set(header, valueOrRewrite, rewrite) {
1269
+ const self2 = this;
1270
+ function setHeader(_value, _header, _rewrite) {
1271
+ const lHeader = normalizeHeader(_header);
1272
+ if (!lHeader) {
1273
+ throw new Error("header name must be a non-empty string");
1274
+ }
1275
+ const key = utils$1.findKey(self2, lHeader);
1276
+ if (!key || self2[key] === void 0 || _rewrite === true || _rewrite === void 0 && self2[key] !== false) {
1277
+ self2[key || _header] = normalizeValue(_value);
1278
+ }
1279
+ }
1280
+ const setHeaders = (headers, _rewrite) => utils$1.forEach(headers, (_value, _header) => setHeader(_value, _header, _rewrite));
1281
+ if (utils$1.isPlainObject(header) || header instanceof this.constructor) {
1282
+ setHeaders(header, valueOrRewrite);
1283
+ } else if (utils$1.isString(header) && (header = header.trim()) && !isValidHeaderName(header)) {
1284
+ setHeaders(parseHeaders(header), valueOrRewrite);
1285
+ } else if (utils$1.isHeaders(header)) {
1286
+ for (const [key, value] of header.entries()) {
1287
+ setHeader(value, key, rewrite);
1288
+ }
1289
+ } else {
1290
+ header != null && setHeader(valueOrRewrite, header, rewrite);
1291
+ }
1292
+ return this;
1293
+ }
1294
+ get(header, parser) {
1295
+ header = normalizeHeader(header);
1296
+ if (header) {
1297
+ const key = utils$1.findKey(this, header);
1298
+ if (key) {
1299
+ const value = this[key];
1300
+ if (!parser) {
1301
+ return value;
1302
+ }
1303
+ if (parser === true) {
1304
+ return parseTokens(value);
1305
+ }
1306
+ if (utils$1.isFunction(parser)) {
1307
+ return parser.call(this, value, key);
1308
+ }
1309
+ if (utils$1.isRegExp(parser)) {
1310
+ return parser.exec(value);
1311
+ }
1312
+ throw new TypeError("parser must be boolean|regexp|function");
1313
+ }
1314
+ }
1315
+ }
1316
+ has(header, matcher) {
1317
+ header = normalizeHeader(header);
1318
+ if (header) {
1319
+ const key = utils$1.findKey(this, header);
1320
+ return !!(key && this[key] !== void 0 && (!matcher || matchHeaderValue(this, this[key], key, matcher)));
1321
+ }
1322
+ return false;
1323
+ }
1324
+ delete(header, matcher) {
1325
+ const self2 = this;
1326
+ let deleted = false;
1327
+ function deleteHeader(_header) {
1328
+ _header = normalizeHeader(_header);
1329
+ if (_header) {
1330
+ const key = utils$1.findKey(self2, _header);
1331
+ if (key && (!matcher || matchHeaderValue(self2, self2[key], key, matcher))) {
1332
+ delete self2[key];
1333
+ deleted = true;
1334
+ }
1335
+ }
1336
+ }
1337
+ if (utils$1.isArray(header)) {
1338
+ header.forEach(deleteHeader);
1339
+ } else {
1340
+ deleteHeader(header);
1341
+ }
1342
+ return deleted;
1343
+ }
1344
+ clear(matcher) {
1345
+ const keys = Object.keys(this);
1346
+ let i = keys.length;
1347
+ let deleted = false;
1348
+ while (i--) {
1349
+ const key = keys[i];
1350
+ if (!matcher || matchHeaderValue(this, this[key], key, matcher, true)) {
1351
+ delete this[key];
1352
+ deleted = true;
1353
+ }
1354
+ }
1355
+ return deleted;
1356
+ }
1357
+ normalize(format) {
1358
+ const self2 = this;
1359
+ const headers = {};
1360
+ utils$1.forEach(this, (value, header) => {
1361
+ const key = utils$1.findKey(headers, header);
1362
+ if (key) {
1363
+ self2[key] = normalizeValue(value);
1364
+ delete self2[header];
1365
+ return;
1366
+ }
1367
+ const normalized = format ? formatHeader(header) : String(header).trim();
1368
+ if (normalized !== header) {
1369
+ delete self2[header];
1370
+ }
1371
+ self2[normalized] = normalizeValue(value);
1372
+ headers[normalized] = true;
1373
+ });
1374
+ return this;
1375
+ }
1376
+ concat(...targets) {
1377
+ return this.constructor.concat(this, ...targets);
1378
+ }
1379
+ toJSON(asStrings) {
1380
+ const obj = /* @__PURE__ */ Object.create(null);
1381
+ utils$1.forEach(this, (value, header) => {
1382
+ value != null && value !== false && (obj[header] = asStrings && utils$1.isArray(value) ? value.join(", ") : value);
1383
+ });
1384
+ return obj;
1385
+ }
1386
+ [Symbol.iterator]() {
1387
+ return Object.entries(this.toJSON())[Symbol.iterator]();
1388
+ }
1389
+ toString() {
1390
+ return Object.entries(this.toJSON()).map(([header, value]) => header + ": " + value).join("\n");
1391
+ }
1392
+ get [Symbol.toStringTag]() {
1393
+ return "AxiosHeaders";
1394
+ }
1395
+ static from(thing) {
1396
+ return thing instanceof this ? thing : new this(thing);
1397
+ }
1398
+ static concat(first, ...targets) {
1399
+ const computed = new this(first);
1400
+ targets.forEach((target) => computed.set(target));
1401
+ return computed;
1402
+ }
1403
+ static accessor(header) {
1404
+ const internals = this[$internals] = this[$internals] = {
1405
+ accessors: {}
1406
+ };
1407
+ const accessors = internals.accessors;
1408
+ const prototype2 = this.prototype;
1409
+ function defineAccessor(_header) {
1410
+ const lHeader = normalizeHeader(_header);
1411
+ if (!accessors[lHeader]) {
1412
+ buildAccessors(prototype2, _header);
1413
+ accessors[lHeader] = true;
1414
+ }
1415
+ }
1416
+ utils$1.isArray(header) ? header.forEach(defineAccessor) : defineAccessor(header);
1417
+ return this;
1418
+ }
1419
+ }
1420
+ AxiosHeaders.accessor(["Content-Type", "Content-Length", "Accept", "Accept-Encoding", "User-Agent", "Authorization"]);
1421
+ utils$1.reduceDescriptors(AxiosHeaders.prototype, ({ value }, key) => {
1422
+ let mapped = key[0].toUpperCase() + key.slice(1);
1423
+ return {
1424
+ get: () => value,
1425
+ set(headerValue) {
1426
+ this[mapped] = headerValue;
1427
+ }
1428
+ };
1429
+ });
1430
+ utils$1.freezeMethods(AxiosHeaders);
1431
+ function transformData(fns, response) {
1432
+ const config = this || defaults;
1433
+ const context = response || config;
1434
+ const headers = AxiosHeaders.from(context.headers);
1435
+ let data = context.data;
1436
+ utils$1.forEach(fns, function transform(fn) {
1437
+ data = fn.call(config, data, headers.normalize(), response ? response.status : void 0);
1438
+ });
1439
+ headers.normalize();
1440
+ return data;
1441
+ }
1442
+ function isCancel(value) {
1443
+ return !!(value && value.__CANCEL__);
1444
+ }
1445
+ function CanceledError(message, config, request) {
1446
+ AxiosError.call(this, message == null ? "canceled" : message, AxiosError.ERR_CANCELED, config, request);
1447
+ this.name = "CanceledError";
1448
+ }
1449
+ utils$1.inherits(CanceledError, AxiosError, {
1450
+ __CANCEL__: true
1451
+ });
1452
+ function settle(resolve, reject, response) {
1453
+ const validateStatus2 = response.config.validateStatus;
1454
+ if (!response.status || !validateStatus2 || validateStatus2(response.status)) {
1455
+ resolve(response);
1456
+ } else {
1457
+ reject(new AxiosError(
1458
+ "Request failed with status code " + response.status,
1459
+ [AxiosError.ERR_BAD_REQUEST, AxiosError.ERR_BAD_RESPONSE][Math.floor(response.status / 100) - 4],
1460
+ response.config,
1461
+ response.request,
1462
+ response
1463
+ ));
1464
+ }
1465
+ }
1466
+ function parseProtocol(url) {
1467
+ const match = /^([-+\w]{1,25})(:?\/\/|:)/.exec(url);
1468
+ return match && match[1] || "";
1469
+ }
1470
+ function speedometer(samplesCount, min) {
1471
+ samplesCount = samplesCount || 10;
1472
+ const bytes = new Array(samplesCount);
1473
+ const timestamps = new Array(samplesCount);
1474
+ let head = 0;
1475
+ let tail = 0;
1476
+ let firstSampleTS;
1477
+ min = min !== void 0 ? min : 1e3;
1478
+ return function push(chunkLength) {
1479
+ const now = Date.now();
1480
+ const startedAt = timestamps[tail];
1481
+ if (!firstSampleTS) {
1482
+ firstSampleTS = now;
1483
+ }
1484
+ bytes[head] = chunkLength;
1485
+ timestamps[head] = now;
1486
+ let i = tail;
1487
+ let bytesCount = 0;
1488
+ while (i !== head) {
1489
+ bytesCount += bytes[i++];
1490
+ i = i % samplesCount;
1491
+ }
1492
+ head = (head + 1) % samplesCount;
1493
+ if (head === tail) {
1494
+ tail = (tail + 1) % samplesCount;
1495
+ }
1496
+ if (now - firstSampleTS < min) {
1497
+ return;
1498
+ }
1499
+ const passed = startedAt && now - startedAt;
1500
+ return passed ? Math.round(bytesCount * 1e3 / passed) : void 0;
1501
+ };
1502
+ }
1503
+ function throttle(fn, freq) {
1504
+ let timestamp = 0;
1505
+ let threshold = 1e3 / freq;
1506
+ let lastArgs;
1507
+ let timer;
1508
+ const invoke = (args, now = Date.now()) => {
1509
+ timestamp = now;
1510
+ lastArgs = null;
1511
+ if (timer) {
1512
+ clearTimeout(timer);
1513
+ timer = null;
1514
+ }
1515
+ fn.apply(null, args);
1516
+ };
1517
+ const throttled = (...args) => {
1518
+ const now = Date.now();
1519
+ const passed = now - timestamp;
1520
+ if (passed >= threshold) {
1521
+ invoke(args, now);
1522
+ } else {
1523
+ lastArgs = args;
1524
+ if (!timer) {
1525
+ timer = setTimeout(() => {
1526
+ timer = null;
1527
+ invoke(lastArgs);
1528
+ }, threshold - passed);
1529
+ }
1530
+ }
1531
+ };
1532
+ const flush = () => lastArgs && invoke(lastArgs);
1533
+ return [throttled, flush];
1534
+ }
1535
+ const progressEventReducer = (listener, isDownloadStream, freq = 3) => {
1536
+ let bytesNotified = 0;
1537
+ const _speedometer = speedometer(50, 250);
1538
+ return throttle((e) => {
1539
+ const loaded = e.loaded;
1540
+ const total = e.lengthComputable ? e.total : void 0;
1541
+ const progressBytes = loaded - bytesNotified;
1542
+ const rate = _speedometer(progressBytes);
1543
+ const inRange = loaded <= total;
1544
+ bytesNotified = loaded;
1545
+ const data = {
1546
+ loaded,
1547
+ total,
1548
+ progress: total ? loaded / total : void 0,
1549
+ bytes: progressBytes,
1550
+ rate: rate ? rate : void 0,
1551
+ estimated: rate && total && inRange ? (total - loaded) / rate : void 0,
1552
+ event: e,
1553
+ lengthComputable: total != null,
1554
+ [isDownloadStream ? "download" : "upload"]: true
1555
+ };
1556
+ listener(data);
1557
+ }, freq);
1558
+ };
1559
+ const progressEventDecorator = (total, throttled) => {
1560
+ const lengthComputable = total != null;
1561
+ return [(loaded) => throttled[0]({
1562
+ lengthComputable,
1563
+ total,
1564
+ loaded
1565
+ }), throttled[1]];
1566
+ };
1567
+ const asyncDecorator = (fn) => (...args) => utils$1.asap(() => fn(...args));
1568
+ const isURLSameOrigin = platform.hasStandardBrowserEnv ? /* @__PURE__ */ ((origin2, isMSIE) => (url) => {
1569
+ url = new URL(url, platform.origin);
1570
+ return origin2.protocol === url.protocol && origin2.host === url.host && (isMSIE || origin2.port === url.port);
1571
+ })(
1572
+ new URL(platform.origin),
1573
+ platform.navigator && /(msie|trident)/i.test(platform.navigator.userAgent)
1574
+ ) : () => true;
1575
+ const cookies = platform.hasStandardBrowserEnv ? (
1576
+ // Standard browser envs support document.cookie
1577
+ {
1578
+ write(name, value, expires, path, domain, secure) {
1579
+ const cookie = [name + "=" + encodeURIComponent(value)];
1580
+ utils$1.isNumber(expires) && cookie.push("expires=" + new Date(expires).toGMTString());
1581
+ utils$1.isString(path) && cookie.push("path=" + path);
1582
+ utils$1.isString(domain) && cookie.push("domain=" + domain);
1583
+ secure === true && cookie.push("secure");
1584
+ document.cookie = cookie.join("; ");
1585
+ },
1586
+ read(name) {
1587
+ const match = document.cookie.match(new RegExp("(^|;\\s*)(" + name + ")=([^;]*)"));
1588
+ return match ? decodeURIComponent(match[3]) : null;
1589
+ },
1590
+ remove(name) {
1591
+ this.write(name, "", Date.now() - 864e5);
1592
+ }
1593
+ }
1594
+ ) : (
1595
+ // Non-standard browser env (web workers, react-native) lack needed support.
1596
+ {
1597
+ write() {
1598
+ },
1599
+ read() {
1600
+ return null;
1601
+ },
1602
+ remove() {
1603
+ }
1604
+ }
1605
+ );
1606
+ function isAbsoluteURL(url) {
1607
+ return /^([a-z][a-z\d+\-.]*:)?\/\//i.test(url);
1608
+ }
1609
+ function combineURLs(baseURL, relativeURL) {
1610
+ return relativeURL ? baseURL.replace(/\/?\/$/, "") + "/" + relativeURL.replace(/^\/+/, "") : baseURL;
1611
+ }
1612
+ function buildFullPath(baseURL, requestedURL) {
1613
+ if (baseURL && !isAbsoluteURL(requestedURL)) {
1614
+ return combineURLs(baseURL, requestedURL);
1615
+ }
1616
+ return requestedURL;
1617
+ }
1618
+ const headersToObject = (thing) => thing instanceof AxiosHeaders ? { ...thing } : thing;
1619
+ function mergeConfig(config1, config2) {
1620
+ config2 = config2 || {};
1621
+ const config = {};
1622
+ function getMergedValue(target, source, prop, caseless) {
1623
+ if (utils$1.isPlainObject(target) && utils$1.isPlainObject(source)) {
1624
+ return utils$1.merge.call({ caseless }, target, source);
1625
+ } else if (utils$1.isPlainObject(source)) {
1626
+ return utils$1.merge({}, source);
1627
+ } else if (utils$1.isArray(source)) {
1628
+ return source.slice();
1629
+ }
1630
+ return source;
1631
+ }
1632
+ function mergeDeepProperties(a, b, prop, caseless) {
1633
+ if (!utils$1.isUndefined(b)) {
1634
+ return getMergedValue(a, b, prop, caseless);
1635
+ } else if (!utils$1.isUndefined(a)) {
1636
+ return getMergedValue(void 0, a, prop, caseless);
1637
+ }
1638
+ }
1639
+ function valueFromConfig2(a, b) {
1640
+ if (!utils$1.isUndefined(b)) {
1641
+ return getMergedValue(void 0, b);
1642
+ }
1643
+ }
1644
+ function defaultToConfig2(a, b) {
1645
+ if (!utils$1.isUndefined(b)) {
1646
+ return getMergedValue(void 0, b);
1647
+ } else if (!utils$1.isUndefined(a)) {
1648
+ return getMergedValue(void 0, a);
1649
+ }
1650
+ }
1651
+ function mergeDirectKeys(a, b, prop) {
1652
+ if (prop in config2) {
1653
+ return getMergedValue(a, b);
1654
+ } else if (prop in config1) {
1655
+ return getMergedValue(void 0, a);
1656
+ }
1657
+ }
1658
+ const mergeMap = {
1659
+ url: valueFromConfig2,
1660
+ method: valueFromConfig2,
1661
+ data: valueFromConfig2,
1662
+ baseURL: defaultToConfig2,
1663
+ transformRequest: defaultToConfig2,
1664
+ transformResponse: defaultToConfig2,
1665
+ paramsSerializer: defaultToConfig2,
1666
+ timeout: defaultToConfig2,
1667
+ timeoutMessage: defaultToConfig2,
1668
+ withCredentials: defaultToConfig2,
1669
+ withXSRFToken: defaultToConfig2,
1670
+ adapter: defaultToConfig2,
1671
+ responseType: defaultToConfig2,
1672
+ xsrfCookieName: defaultToConfig2,
1673
+ xsrfHeaderName: defaultToConfig2,
1674
+ onUploadProgress: defaultToConfig2,
1675
+ onDownloadProgress: defaultToConfig2,
1676
+ decompress: defaultToConfig2,
1677
+ maxContentLength: defaultToConfig2,
1678
+ maxBodyLength: defaultToConfig2,
1679
+ beforeRedirect: defaultToConfig2,
1680
+ transport: defaultToConfig2,
1681
+ httpAgent: defaultToConfig2,
1682
+ httpsAgent: defaultToConfig2,
1683
+ cancelToken: defaultToConfig2,
1684
+ socketPath: defaultToConfig2,
1685
+ responseEncoding: defaultToConfig2,
1686
+ validateStatus: mergeDirectKeys,
1687
+ headers: (a, b, prop) => mergeDeepProperties(headersToObject(a), headersToObject(b), prop, true)
1688
+ };
1689
+ utils$1.forEach(Object.keys(Object.assign({}, config1, config2)), function computeConfigValue(prop) {
1690
+ const merge2 = mergeMap[prop] || mergeDeepProperties;
1691
+ const configValue = merge2(config1[prop], config2[prop], prop);
1692
+ utils$1.isUndefined(configValue) && merge2 !== mergeDirectKeys || (config[prop] = configValue);
1693
+ });
1694
+ return config;
1695
+ }
1696
+ const resolveConfig = (config) => {
1697
+ const newConfig = mergeConfig({}, config);
1698
+ let { data, withXSRFToken, xsrfHeaderName, xsrfCookieName, headers, auth } = newConfig;
1699
+ newConfig.headers = headers = AxiosHeaders.from(headers);
1700
+ newConfig.url = buildURL(buildFullPath(newConfig.baseURL, newConfig.url), config.params, config.paramsSerializer);
1701
+ if (auth) {
1702
+ headers.set(
1703
+ "Authorization",
1704
+ "Basic " + btoa((auth.username || "") + ":" + (auth.password ? unescape(encodeURIComponent(auth.password)) : ""))
1705
+ );
1706
+ }
1707
+ let contentType;
1708
+ if (utils$1.isFormData(data)) {
1709
+ if (platform.hasStandardBrowserEnv || platform.hasStandardBrowserWebWorkerEnv) {
1710
+ headers.setContentType(void 0);
1711
+ } else if ((contentType = headers.getContentType()) !== false) {
1712
+ const [type, ...tokens] = contentType ? contentType.split(";").map((token) => token.trim()).filter(Boolean) : [];
1713
+ headers.setContentType([type || "multipart/form-data", ...tokens].join("; "));
1714
+ }
1715
+ }
1716
+ if (platform.hasStandardBrowserEnv) {
1717
+ withXSRFToken && utils$1.isFunction(withXSRFToken) && (withXSRFToken = withXSRFToken(newConfig));
1718
+ if (withXSRFToken || withXSRFToken !== false && isURLSameOrigin(newConfig.url)) {
1719
+ const xsrfValue = xsrfHeaderName && xsrfCookieName && cookies.read(xsrfCookieName);
1720
+ if (xsrfValue) {
1721
+ headers.set(xsrfHeaderName, xsrfValue);
1722
+ }
1723
+ }
1724
+ }
1725
+ return newConfig;
1726
+ };
1727
+ const isXHRAdapterSupported = typeof XMLHttpRequest !== "undefined";
1728
+ const xhrAdapter = isXHRAdapterSupported && function(config) {
1729
+ return new Promise(function dispatchXhrRequest(resolve, reject) {
1730
+ const _config = resolveConfig(config);
1731
+ let requestData = _config.data;
1732
+ const requestHeaders = AxiosHeaders.from(_config.headers).normalize();
1733
+ let { responseType, onUploadProgress, onDownloadProgress } = _config;
1734
+ let onCanceled;
1735
+ let uploadThrottled, downloadThrottled;
1736
+ let flushUpload, flushDownload;
1737
+ function done() {
1738
+ flushUpload && flushUpload();
1739
+ flushDownload && flushDownload();
1740
+ _config.cancelToken && _config.cancelToken.unsubscribe(onCanceled);
1741
+ _config.signal && _config.signal.removeEventListener("abort", onCanceled);
1742
+ }
1743
+ let request = new XMLHttpRequest();
1744
+ request.open(_config.method.toUpperCase(), _config.url, true);
1745
+ request.timeout = _config.timeout;
1746
+ function onloadend() {
1747
+ if (!request) {
1748
+ return;
1749
+ }
1750
+ const responseHeaders = AxiosHeaders.from(
1751
+ "getAllResponseHeaders" in request && request.getAllResponseHeaders()
1752
+ );
1753
+ const responseData = !responseType || responseType === "text" || responseType === "json" ? request.responseText : request.response;
1754
+ const response = {
1755
+ data: responseData,
1756
+ status: request.status,
1757
+ statusText: request.statusText,
1758
+ headers: responseHeaders,
1759
+ config,
1760
+ request
1761
+ };
1762
+ settle(function _resolve(value) {
1763
+ resolve(value);
1764
+ done();
1765
+ }, function _reject(err) {
1766
+ reject(err);
1767
+ done();
1768
+ }, response);
1769
+ request = null;
1770
+ }
1771
+ if ("onloadend" in request) {
1772
+ request.onloadend = onloadend;
1773
+ } else {
1774
+ request.onreadystatechange = function handleLoad() {
1775
+ if (!request || request.readyState !== 4) {
1776
+ return;
1777
+ }
1778
+ if (request.status === 0 && !(request.responseURL && request.responseURL.indexOf("file:") === 0)) {
1779
+ return;
1780
+ }
1781
+ setTimeout(onloadend);
1782
+ };
1783
+ }
1784
+ request.onabort = function handleAbort() {
1785
+ if (!request) {
1786
+ return;
1787
+ }
1788
+ reject(new AxiosError("Request aborted", AxiosError.ECONNABORTED, config, request));
1789
+ request = null;
1790
+ };
1791
+ request.onerror = function handleError() {
1792
+ reject(new AxiosError("Network Error", AxiosError.ERR_NETWORK, config, request));
1793
+ request = null;
1794
+ };
1795
+ request.ontimeout = function handleTimeout() {
1796
+ let timeoutErrorMessage = _config.timeout ? "timeout of " + _config.timeout + "ms exceeded" : "timeout exceeded";
1797
+ const transitional2 = _config.transitional || transitionalDefaults;
1798
+ if (_config.timeoutErrorMessage) {
1799
+ timeoutErrorMessage = _config.timeoutErrorMessage;
1800
+ }
1801
+ reject(new AxiosError(
1802
+ timeoutErrorMessage,
1803
+ transitional2.clarifyTimeoutError ? AxiosError.ETIMEDOUT : AxiosError.ECONNABORTED,
1804
+ config,
1805
+ request
1806
+ ));
1807
+ request = null;
1808
+ };
1809
+ requestData === void 0 && requestHeaders.setContentType(null);
1810
+ if ("setRequestHeader" in request) {
1811
+ utils$1.forEach(requestHeaders.toJSON(), function setRequestHeader(val, key) {
1812
+ request.setRequestHeader(key, val);
1813
+ });
1814
+ }
1815
+ if (!utils$1.isUndefined(_config.withCredentials)) {
1816
+ request.withCredentials = !!_config.withCredentials;
1817
+ }
1818
+ if (responseType && responseType !== "json") {
1819
+ request.responseType = _config.responseType;
1820
+ }
1821
+ if (onDownloadProgress) {
1822
+ [downloadThrottled, flushDownload] = progressEventReducer(onDownloadProgress, true);
1823
+ request.addEventListener("progress", downloadThrottled);
1824
+ }
1825
+ if (onUploadProgress && request.upload) {
1826
+ [uploadThrottled, flushUpload] = progressEventReducer(onUploadProgress);
1827
+ request.upload.addEventListener("progress", uploadThrottled);
1828
+ request.upload.addEventListener("loadend", flushUpload);
1829
+ }
1830
+ if (_config.cancelToken || _config.signal) {
1831
+ onCanceled = (cancel) => {
1832
+ if (!request) {
1833
+ return;
1834
+ }
1835
+ reject(!cancel || cancel.type ? new CanceledError(null, config, request) : cancel);
1836
+ request.abort();
1837
+ request = null;
1838
+ };
1839
+ _config.cancelToken && _config.cancelToken.subscribe(onCanceled);
1840
+ if (_config.signal) {
1841
+ _config.signal.aborted ? onCanceled() : _config.signal.addEventListener("abort", onCanceled);
1842
+ }
1843
+ }
1844
+ const protocol = parseProtocol(_config.url);
1845
+ if (protocol && platform.protocols.indexOf(protocol) === -1) {
1846
+ reject(new AxiosError("Unsupported protocol " + protocol + ":", AxiosError.ERR_BAD_REQUEST, config));
1847
+ return;
1848
+ }
1849
+ request.send(requestData || null);
1850
+ });
1851
+ };
1852
+ const composeSignals = (signals, timeout) => {
1853
+ const { length } = signals = signals ? signals.filter(Boolean) : [];
1854
+ if (timeout || length) {
1855
+ let controller = new AbortController();
1856
+ let aborted;
1857
+ const onabort = function(reason) {
1858
+ if (!aborted) {
1859
+ aborted = true;
1860
+ unsubscribe();
1861
+ const err = reason instanceof Error ? reason : this.reason;
1862
+ controller.abort(err instanceof AxiosError ? err : new CanceledError(err instanceof Error ? err.message : err));
1863
+ }
1864
+ };
1865
+ let timer = timeout && setTimeout(() => {
1866
+ timer = null;
1867
+ onabort(new AxiosError(`timeout ${timeout} of ms exceeded`, AxiosError.ETIMEDOUT));
1868
+ }, timeout);
1869
+ const unsubscribe = () => {
1870
+ if (signals) {
1871
+ timer && clearTimeout(timer);
1872
+ timer = null;
1873
+ signals.forEach((signal2) => {
1874
+ signal2.unsubscribe ? signal2.unsubscribe(onabort) : signal2.removeEventListener("abort", onabort);
1875
+ });
1876
+ signals = null;
1877
+ }
1878
+ };
1879
+ signals.forEach((signal2) => signal2.addEventListener("abort", onabort));
1880
+ const { signal } = controller;
1881
+ signal.unsubscribe = () => utils$1.asap(unsubscribe);
1882
+ return signal;
1883
+ }
1884
+ };
1885
+ const streamChunk = function* (chunk, chunkSize) {
1886
+ let len = chunk.byteLength;
1887
+ if (len < chunkSize) {
1888
+ yield chunk;
1889
+ return;
1890
+ }
1891
+ let pos = 0;
1892
+ let end;
1893
+ while (pos < len) {
1894
+ end = pos + chunkSize;
1895
+ yield chunk.slice(pos, end);
1896
+ pos = end;
1897
+ }
1898
+ };
1899
+ const readBytes = async function* (iterable, chunkSize) {
1900
+ for await (const chunk of readStream(iterable)) {
1901
+ yield* streamChunk(chunk, chunkSize);
1902
+ }
1903
+ };
1904
+ const readStream = async function* (stream) {
1905
+ if (stream[Symbol.asyncIterator]) {
1906
+ yield* stream;
1907
+ return;
1908
+ }
1909
+ const reader = stream.getReader();
1910
+ try {
1911
+ for (; ; ) {
1912
+ const { done, value } = await reader.read();
1913
+ if (done) {
1914
+ break;
1915
+ }
1916
+ yield value;
1917
+ }
1918
+ } finally {
1919
+ await reader.cancel();
1920
+ }
1921
+ };
1922
+ const trackStream = (stream, chunkSize, onProgress, onFinish) => {
1923
+ const iterator = readBytes(stream, chunkSize);
1924
+ let bytes = 0;
1925
+ let done;
1926
+ let _onFinish = (e) => {
1927
+ if (!done) {
1928
+ done = true;
1929
+ onFinish && onFinish(e);
1930
+ }
1931
+ };
1932
+ return new ReadableStream({
1933
+ async pull(controller) {
1934
+ try {
1935
+ const { done: done2, value } = await iterator.next();
1936
+ if (done2) {
1937
+ _onFinish();
1938
+ controller.close();
1939
+ return;
1940
+ }
1941
+ let len = value.byteLength;
1942
+ if (onProgress) {
1943
+ let loadedBytes = bytes += len;
1944
+ onProgress(loadedBytes);
1945
+ }
1946
+ controller.enqueue(new Uint8Array(value));
1947
+ } catch (err) {
1948
+ _onFinish(err);
1949
+ throw err;
1950
+ }
1951
+ },
1952
+ cancel(reason) {
1953
+ _onFinish(reason);
1954
+ return iterator.return();
1955
+ }
1956
+ }, {
1957
+ highWaterMark: 2
1958
+ });
1959
+ };
1960
+ const isFetchSupported = typeof fetch === "function" && typeof Request === "function" && typeof Response === "function";
1961
+ const isReadableStreamSupported = isFetchSupported && typeof ReadableStream === "function";
1962
+ const encodeText = isFetchSupported && (typeof TextEncoder === "function" ? /* @__PURE__ */ ((encoder) => (str) => encoder.encode(str))(new TextEncoder()) : async (str) => new Uint8Array(await new Response(str).arrayBuffer()));
1963
+ const test = (fn, ...args) => {
1964
+ try {
1965
+ return !!fn(...args);
1966
+ } catch (e) {
1967
+ return false;
1968
+ }
1969
+ };
1970
+ const supportsRequestStream = isReadableStreamSupported && test(() => {
1971
+ let duplexAccessed = false;
1972
+ const hasContentType = new Request(platform.origin, {
1973
+ body: new ReadableStream(),
1974
+ method: "POST",
1975
+ get duplex() {
1976
+ duplexAccessed = true;
1977
+ return "half";
1978
+ }
1979
+ }).headers.has("Content-Type");
1980
+ return duplexAccessed && !hasContentType;
1981
+ });
1982
+ const DEFAULT_CHUNK_SIZE = 64 * 1024;
1983
+ const supportsResponseStream = isReadableStreamSupported && test(() => utils$1.isReadableStream(new Response("").body));
1984
+ const resolvers = {
1985
+ stream: supportsResponseStream && ((res) => res.body)
1986
+ };
1987
+ isFetchSupported && ((res) => {
1988
+ ["text", "arrayBuffer", "blob", "formData", "stream"].forEach((type) => {
1989
+ !resolvers[type] && (resolvers[type] = utils$1.isFunction(res[type]) ? (res2) => res2[type]() : (_, config) => {
1990
+ throw new AxiosError(`Response type '${type}' is not supported`, AxiosError.ERR_NOT_SUPPORT, config);
1991
+ });
1992
+ });
1993
+ })(new Response());
1994
+ const getBodyLength = async (body) => {
1995
+ if (body == null) {
1996
+ return 0;
1997
+ }
1998
+ if (utils$1.isBlob(body)) {
1999
+ return body.size;
2000
+ }
2001
+ if (utils$1.isSpecCompliantForm(body)) {
2002
+ const _request = new Request(platform.origin, {
2003
+ method: "POST",
2004
+ body
2005
+ });
2006
+ return (await _request.arrayBuffer()).byteLength;
2007
+ }
2008
+ if (utils$1.isArrayBufferView(body) || utils$1.isArrayBuffer(body)) {
2009
+ return body.byteLength;
2010
+ }
2011
+ if (utils$1.isURLSearchParams(body)) {
2012
+ body = body + "";
2013
+ }
2014
+ if (utils$1.isString(body)) {
2015
+ return (await encodeText(body)).byteLength;
2016
+ }
2017
+ };
2018
+ const resolveBodyLength = async (headers, body) => {
2019
+ const length = utils$1.toFiniteNumber(headers.getContentLength());
2020
+ return length == null ? getBodyLength(body) : length;
2021
+ };
2022
+ const fetchAdapter = isFetchSupported && (async (config) => {
2023
+ let {
2024
+ url,
2025
+ method,
2026
+ data,
2027
+ signal,
2028
+ cancelToken,
2029
+ timeout,
2030
+ onDownloadProgress,
2031
+ onUploadProgress,
2032
+ responseType,
2033
+ headers,
2034
+ withCredentials = "same-origin",
2035
+ fetchOptions
2036
+ } = resolveConfig(config);
2037
+ responseType = responseType ? (responseType + "").toLowerCase() : "text";
2038
+ let composedSignal = composeSignals([signal, cancelToken && cancelToken.toAbortSignal()], timeout);
2039
+ let request;
2040
+ const unsubscribe = composedSignal && composedSignal.unsubscribe && (() => {
2041
+ composedSignal.unsubscribe();
2042
+ });
2043
+ let requestContentLength;
2044
+ try {
2045
+ if (onUploadProgress && supportsRequestStream && method !== "get" && method !== "head" && (requestContentLength = await resolveBodyLength(headers, data)) !== 0) {
2046
+ let _request = new Request(url, {
2047
+ method: "POST",
2048
+ body: data,
2049
+ duplex: "half"
2050
+ });
2051
+ let contentTypeHeader;
2052
+ if (utils$1.isFormData(data) && (contentTypeHeader = _request.headers.get("content-type"))) {
2053
+ headers.setContentType(contentTypeHeader);
2054
+ }
2055
+ if (_request.body) {
2056
+ const [onProgress, flush] = progressEventDecorator(
2057
+ requestContentLength,
2058
+ progressEventReducer(asyncDecorator(onUploadProgress))
2059
+ );
2060
+ data = trackStream(_request.body, DEFAULT_CHUNK_SIZE, onProgress, flush);
2061
+ }
2062
+ }
2063
+ if (!utils$1.isString(withCredentials)) {
2064
+ withCredentials = withCredentials ? "include" : "omit";
2065
+ }
2066
+ const isCredentialsSupported = "credentials" in Request.prototype;
2067
+ request = new Request(url, {
2068
+ ...fetchOptions,
2069
+ signal: composedSignal,
2070
+ method: method.toUpperCase(),
2071
+ headers: headers.normalize().toJSON(),
2072
+ body: data,
2073
+ duplex: "half",
2074
+ credentials: isCredentialsSupported ? withCredentials : void 0
2075
+ });
2076
+ let response = await fetch(request);
2077
+ const isStreamResponse = supportsResponseStream && (responseType === "stream" || responseType === "response");
2078
+ if (supportsResponseStream && (onDownloadProgress || isStreamResponse && unsubscribe)) {
2079
+ const options = {};
2080
+ ["status", "statusText", "headers"].forEach((prop) => {
2081
+ options[prop] = response[prop];
2082
+ });
2083
+ const responseContentLength = utils$1.toFiniteNumber(response.headers.get("content-length"));
2084
+ const [onProgress, flush] = onDownloadProgress && progressEventDecorator(
2085
+ responseContentLength,
2086
+ progressEventReducer(asyncDecorator(onDownloadProgress), true)
2087
+ ) || [];
2088
+ response = new Response(
2089
+ trackStream(response.body, DEFAULT_CHUNK_SIZE, onProgress, () => {
2090
+ flush && flush();
2091
+ unsubscribe && unsubscribe();
2092
+ }),
2093
+ options
2094
+ );
2095
+ }
2096
+ responseType = responseType || "text";
2097
+ let responseData = await resolvers[utils$1.findKey(resolvers, responseType) || "text"](response, config);
2098
+ !isStreamResponse && unsubscribe && unsubscribe();
2099
+ return await new Promise((resolve, reject) => {
2100
+ settle(resolve, reject, {
2101
+ data: responseData,
2102
+ headers: AxiosHeaders.from(response.headers),
2103
+ status: response.status,
2104
+ statusText: response.statusText,
2105
+ config,
2106
+ request
2107
+ });
2108
+ });
2109
+ } catch (err) {
2110
+ unsubscribe && unsubscribe();
2111
+ if (err && err.name === "TypeError" && /fetch/i.test(err.message)) {
2112
+ throw Object.assign(
2113
+ new AxiosError("Network Error", AxiosError.ERR_NETWORK, config, request),
2114
+ {
2115
+ cause: err.cause || err
2116
+ }
2117
+ );
2118
+ }
2119
+ throw AxiosError.from(err, err && err.code, config, request);
2120
+ }
2121
+ });
2122
+ const knownAdapters = {
2123
+ http: httpAdapter,
2124
+ xhr: xhrAdapter,
2125
+ fetch: fetchAdapter
2126
+ };
2127
+ utils$1.forEach(knownAdapters, (fn, value) => {
2128
+ if (fn) {
2129
+ try {
2130
+ Object.defineProperty(fn, "name", { value });
2131
+ } catch (e) {
2132
+ }
2133
+ Object.defineProperty(fn, "adapterName", { value });
2134
+ }
2135
+ });
2136
+ const renderReason = (reason) => `- ${reason}`;
2137
+ const isResolvedHandle = (adapter) => utils$1.isFunction(adapter) || adapter === null || adapter === false;
2138
+ const adapters = {
2139
+ getAdapter: (adapters2) => {
2140
+ adapters2 = utils$1.isArray(adapters2) ? adapters2 : [adapters2];
2141
+ const { length } = adapters2;
2142
+ let nameOrAdapter;
2143
+ let adapter;
2144
+ const rejectedReasons = {};
2145
+ for (let i = 0; i < length; i++) {
2146
+ nameOrAdapter = adapters2[i];
2147
+ let id;
2148
+ adapter = nameOrAdapter;
2149
+ if (!isResolvedHandle(nameOrAdapter)) {
2150
+ adapter = knownAdapters[(id = String(nameOrAdapter)).toLowerCase()];
2151
+ if (adapter === void 0) {
2152
+ throw new AxiosError(`Unknown adapter '${id}'`);
2153
+ }
2154
+ }
2155
+ if (adapter) {
2156
+ break;
2157
+ }
2158
+ rejectedReasons[id || "#" + i] = adapter;
2159
+ }
2160
+ if (!adapter) {
2161
+ const reasons = Object.entries(rejectedReasons).map(
2162
+ ([id, state]) => `adapter ${id} ` + (state === false ? "is not supported by the environment" : "is not available in the build")
2163
+ );
2164
+ let s = length ? reasons.length > 1 ? "since :\n" + reasons.map(renderReason).join("\n") : " " + renderReason(reasons[0]) : "as no adapter specified";
2165
+ throw new AxiosError(
2166
+ `There is no suitable adapter to dispatch the request ` + s,
2167
+ "ERR_NOT_SUPPORT"
2168
+ );
2169
+ }
2170
+ return adapter;
2171
+ },
2172
+ adapters: knownAdapters
2173
+ };
2174
+ function throwIfCancellationRequested(config) {
2175
+ if (config.cancelToken) {
2176
+ config.cancelToken.throwIfRequested();
2177
+ }
2178
+ if (config.signal && config.signal.aborted) {
2179
+ throw new CanceledError(null, config);
2180
+ }
2181
+ }
2182
+ function dispatchRequest(config) {
2183
+ throwIfCancellationRequested(config);
2184
+ config.headers = AxiosHeaders.from(config.headers);
2185
+ config.data = transformData.call(
2186
+ config,
2187
+ config.transformRequest
2188
+ );
2189
+ if (["post", "put", "patch"].indexOf(config.method) !== -1) {
2190
+ config.headers.setContentType("application/x-www-form-urlencoded", false);
2191
+ }
2192
+ const adapter = adapters.getAdapter(config.adapter || defaults.adapter);
2193
+ return adapter(config).then(function onAdapterResolution(response) {
2194
+ throwIfCancellationRequested(config);
2195
+ response.data = transformData.call(
2196
+ config,
2197
+ config.transformResponse,
2198
+ response
2199
+ );
2200
+ response.headers = AxiosHeaders.from(response.headers);
2201
+ return response;
2202
+ }, function onAdapterRejection(reason) {
2203
+ if (!isCancel(reason)) {
2204
+ throwIfCancellationRequested(config);
2205
+ if (reason && reason.response) {
2206
+ reason.response.data = transformData.call(
2207
+ config,
2208
+ config.transformResponse,
2209
+ reason.response
2210
+ );
2211
+ reason.response.headers = AxiosHeaders.from(reason.response.headers);
2212
+ }
2213
+ }
2214
+ return Promise.reject(reason);
2215
+ });
2216
+ }
2217
+ const VERSION = "1.7.9";
2218
+ const validators$1 = {};
2219
+ ["object", "boolean", "number", "function", "string", "symbol"].forEach((type, i) => {
2220
+ validators$1[type] = function validator2(thing) {
2221
+ return typeof thing === type || "a" + (i < 1 ? "n " : " ") + type;
2222
+ };
2223
+ });
2224
+ const deprecatedWarnings = {};
2225
+ validators$1.transitional = function transitional(validator2, version, message) {
2226
+ function formatMessage(opt, desc) {
2227
+ return "[Axios v" + VERSION + "] Transitional option '" + opt + "'" + desc + (message ? ". " + message : "");
2228
+ }
2229
+ return (value, opt, opts) => {
2230
+ if (validator2 === false) {
2231
+ throw new AxiosError(
2232
+ formatMessage(opt, " has been removed" + (version ? " in " + version : "")),
2233
+ AxiosError.ERR_DEPRECATED
2234
+ );
2235
+ }
2236
+ if (version && !deprecatedWarnings[opt]) {
2237
+ deprecatedWarnings[opt] = true;
2238
+ console.warn(
2239
+ formatMessage(
2240
+ opt,
2241
+ " has been deprecated since v" + version + " and will be removed in the near future"
2242
+ )
2243
+ );
2244
+ }
2245
+ return validator2 ? validator2(value, opt, opts) : true;
2246
+ };
2247
+ };
2248
+ validators$1.spelling = function spelling(correctSpelling) {
2249
+ return (value, opt) => {
2250
+ console.warn(`${opt} is likely a misspelling of ${correctSpelling}`);
2251
+ return true;
2252
+ };
2253
+ };
2254
+ function assertOptions(options, schema, allowUnknown) {
2255
+ if (typeof options !== "object") {
2256
+ throw new AxiosError("options must be an object", AxiosError.ERR_BAD_OPTION_VALUE);
2257
+ }
2258
+ const keys = Object.keys(options);
2259
+ let i = keys.length;
2260
+ while (i-- > 0) {
2261
+ const opt = keys[i];
2262
+ const validator2 = schema[opt];
2263
+ if (validator2) {
2264
+ const value = options[opt];
2265
+ const result = value === void 0 || validator2(value, opt, options);
2266
+ if (result !== true) {
2267
+ throw new AxiosError("option " + opt + " must be " + result, AxiosError.ERR_BAD_OPTION_VALUE);
2268
+ }
2269
+ continue;
2270
+ }
2271
+ if (allowUnknown !== true) {
2272
+ throw new AxiosError("Unknown option " + opt, AxiosError.ERR_BAD_OPTION);
2273
+ }
2274
+ }
2275
+ }
2276
+ const validator = {
2277
+ assertOptions,
2278
+ validators: validators$1
2279
+ };
2280
+ const validators = validator.validators;
2281
+ class Axios {
2282
+ constructor(instanceConfig) {
2283
+ this.defaults = instanceConfig;
2284
+ this.interceptors = {
2285
+ request: new InterceptorManager(),
2286
+ response: new InterceptorManager()
2287
+ };
2288
+ }
2289
+ /**
2290
+ * Dispatch a request
2291
+ *
2292
+ * @param {String|Object} configOrUrl The config specific for this request (merged with this.defaults)
2293
+ * @param {?Object} config
2294
+ *
2295
+ * @returns {Promise} The Promise to be fulfilled
2296
+ */
2297
+ async request(configOrUrl, config) {
2298
+ try {
2299
+ return await this._request(configOrUrl, config);
2300
+ } catch (err) {
2301
+ if (err instanceof Error) {
2302
+ let dummy = {};
2303
+ Error.captureStackTrace ? Error.captureStackTrace(dummy) : dummy = new Error();
2304
+ const stack = dummy.stack ? dummy.stack.replace(/^.+\n/, "") : "";
2305
+ try {
2306
+ if (!err.stack) {
2307
+ err.stack = stack;
2308
+ } else if (stack && !String(err.stack).endsWith(stack.replace(/^.+\n.+\n/, ""))) {
2309
+ err.stack += "\n" + stack;
2310
+ }
2311
+ } catch (e) {
2312
+ }
2313
+ }
2314
+ throw err;
2315
+ }
2316
+ }
2317
+ _request(configOrUrl, config) {
2318
+ if (typeof configOrUrl === "string") {
2319
+ config = config || {};
2320
+ config.url = configOrUrl;
2321
+ } else {
2322
+ config = configOrUrl || {};
2323
+ }
2324
+ config = mergeConfig(this.defaults, config);
2325
+ const { transitional: transitional2, paramsSerializer, headers } = config;
2326
+ if (transitional2 !== void 0) {
2327
+ validator.assertOptions(transitional2, {
2328
+ silentJSONParsing: validators.transitional(validators.boolean),
2329
+ forcedJSONParsing: validators.transitional(validators.boolean),
2330
+ clarifyTimeoutError: validators.transitional(validators.boolean)
2331
+ }, false);
2332
+ }
2333
+ if (paramsSerializer != null) {
2334
+ if (utils$1.isFunction(paramsSerializer)) {
2335
+ config.paramsSerializer = {
2336
+ serialize: paramsSerializer
2337
+ };
2338
+ } else {
2339
+ validator.assertOptions(paramsSerializer, {
2340
+ encode: validators.function,
2341
+ serialize: validators.function
2342
+ }, true);
2343
+ }
2344
+ }
2345
+ validator.assertOptions(config, {
2346
+ baseUrl: validators.spelling("baseURL"),
2347
+ withXsrfToken: validators.spelling("withXSRFToken")
2348
+ }, true);
2349
+ config.method = (config.method || this.defaults.method || "get").toLowerCase();
2350
+ let contextHeaders = headers && utils$1.merge(
2351
+ headers.common,
2352
+ headers[config.method]
2353
+ );
2354
+ headers && utils$1.forEach(
2355
+ ["delete", "get", "head", "post", "put", "patch", "common"],
2356
+ (method) => {
2357
+ delete headers[method];
2358
+ }
2359
+ );
2360
+ config.headers = AxiosHeaders.concat(contextHeaders, headers);
2361
+ const requestInterceptorChain = [];
2362
+ let synchronousRequestInterceptors = true;
2363
+ this.interceptors.request.forEach(function unshiftRequestInterceptors(interceptor) {
2364
+ if (typeof interceptor.runWhen === "function" && interceptor.runWhen(config) === false) {
2365
+ return;
2366
+ }
2367
+ synchronousRequestInterceptors = synchronousRequestInterceptors && interceptor.synchronous;
2368
+ requestInterceptorChain.unshift(interceptor.fulfilled, interceptor.rejected);
2369
+ });
2370
+ const responseInterceptorChain = [];
2371
+ this.interceptors.response.forEach(function pushResponseInterceptors(interceptor) {
2372
+ responseInterceptorChain.push(interceptor.fulfilled, interceptor.rejected);
2373
+ });
2374
+ let promise;
2375
+ let i = 0;
2376
+ let len;
2377
+ if (!synchronousRequestInterceptors) {
2378
+ const chain = [dispatchRequest.bind(this), void 0];
2379
+ chain.unshift.apply(chain, requestInterceptorChain);
2380
+ chain.push.apply(chain, responseInterceptorChain);
2381
+ len = chain.length;
2382
+ promise = Promise.resolve(config);
2383
+ while (i < len) {
2384
+ promise = promise.then(chain[i++], chain[i++]);
2385
+ }
2386
+ return promise;
2387
+ }
2388
+ len = requestInterceptorChain.length;
2389
+ let newConfig = config;
2390
+ i = 0;
2391
+ while (i < len) {
2392
+ const onFulfilled = requestInterceptorChain[i++];
2393
+ const onRejected = requestInterceptorChain[i++];
2394
+ try {
2395
+ newConfig = onFulfilled(newConfig);
2396
+ } catch (error) {
2397
+ onRejected.call(this, error);
2398
+ break;
2399
+ }
2400
+ }
2401
+ try {
2402
+ promise = dispatchRequest.call(this, newConfig);
2403
+ } catch (error) {
2404
+ return Promise.reject(error);
2405
+ }
2406
+ i = 0;
2407
+ len = responseInterceptorChain.length;
2408
+ while (i < len) {
2409
+ promise = promise.then(responseInterceptorChain[i++], responseInterceptorChain[i++]);
2410
+ }
2411
+ return promise;
2412
+ }
2413
+ getUri(config) {
2414
+ config = mergeConfig(this.defaults, config);
2415
+ const fullPath = buildFullPath(config.baseURL, config.url);
2416
+ return buildURL(fullPath, config.params, config.paramsSerializer);
2417
+ }
2418
+ }
2419
+ utils$1.forEach(["delete", "get", "head", "options"], function forEachMethodNoData(method) {
2420
+ Axios.prototype[method] = function(url, config) {
2421
+ return this.request(mergeConfig(config || {}, {
2422
+ method,
2423
+ url,
2424
+ data: (config || {}).data
2425
+ }));
2426
+ };
2427
+ });
2428
+ utils$1.forEach(["post", "put", "patch"], function forEachMethodWithData(method) {
2429
+ function generateHTTPMethod(isForm) {
2430
+ return function httpMethod(url, data, config) {
2431
+ return this.request(mergeConfig(config || {}, {
2432
+ method,
2433
+ headers: isForm ? {
2434
+ "Content-Type": "multipart/form-data"
2435
+ } : {},
2436
+ url,
2437
+ data
2438
+ }));
2439
+ };
2440
+ }
2441
+ Axios.prototype[method] = generateHTTPMethod();
2442
+ Axios.prototype[method + "Form"] = generateHTTPMethod(true);
2443
+ });
2444
+ class CancelToken {
2445
+ constructor(executor) {
2446
+ if (typeof executor !== "function") {
2447
+ throw new TypeError("executor must be a function.");
2448
+ }
2449
+ let resolvePromise;
2450
+ this.promise = new Promise(function promiseExecutor(resolve) {
2451
+ resolvePromise = resolve;
2452
+ });
2453
+ const token = this;
2454
+ this.promise.then((cancel) => {
2455
+ if (!token._listeners) return;
2456
+ let i = token._listeners.length;
2457
+ while (i-- > 0) {
2458
+ token._listeners[i](cancel);
2459
+ }
2460
+ token._listeners = null;
2461
+ });
2462
+ this.promise.then = (onfulfilled) => {
2463
+ let _resolve;
2464
+ const promise = new Promise((resolve) => {
2465
+ token.subscribe(resolve);
2466
+ _resolve = resolve;
2467
+ }).then(onfulfilled);
2468
+ promise.cancel = function reject() {
2469
+ token.unsubscribe(_resolve);
2470
+ };
2471
+ return promise;
2472
+ };
2473
+ executor(function cancel(message, config, request) {
2474
+ if (token.reason) {
2475
+ return;
2476
+ }
2477
+ token.reason = new CanceledError(message, config, request);
2478
+ resolvePromise(token.reason);
2479
+ });
2480
+ }
2481
+ /**
2482
+ * Throws a `CanceledError` if cancellation has been requested.
2483
+ */
2484
+ throwIfRequested() {
2485
+ if (this.reason) {
2486
+ throw this.reason;
2487
+ }
2488
+ }
2489
+ /**
2490
+ * Subscribe to the cancel signal
2491
+ */
2492
+ subscribe(listener) {
2493
+ if (this.reason) {
2494
+ listener(this.reason);
2495
+ return;
2496
+ }
2497
+ if (this._listeners) {
2498
+ this._listeners.push(listener);
2499
+ } else {
2500
+ this._listeners = [listener];
2501
+ }
2502
+ }
2503
+ /**
2504
+ * Unsubscribe from the cancel signal
2505
+ */
2506
+ unsubscribe(listener) {
2507
+ if (!this._listeners) {
2508
+ return;
2509
+ }
2510
+ const index = this._listeners.indexOf(listener);
2511
+ if (index !== -1) {
2512
+ this._listeners.splice(index, 1);
2513
+ }
2514
+ }
2515
+ toAbortSignal() {
2516
+ const controller = new AbortController();
2517
+ const abort = (err) => {
2518
+ controller.abort(err);
2519
+ };
2520
+ this.subscribe(abort);
2521
+ controller.signal.unsubscribe = () => this.unsubscribe(abort);
2522
+ return controller.signal;
2523
+ }
2524
+ /**
2525
+ * Returns an object that contains a new `CancelToken` and a function that, when called,
2526
+ * cancels the `CancelToken`.
2527
+ */
2528
+ static source() {
2529
+ let cancel;
2530
+ const token = new CancelToken(function executor(c) {
2531
+ cancel = c;
2532
+ });
2533
+ return {
2534
+ token,
2535
+ cancel
2536
+ };
2537
+ }
2538
+ }
2539
+ function spread(callback) {
2540
+ return function wrap(arr) {
2541
+ return callback.apply(null, arr);
2542
+ };
2543
+ }
2544
+ function isAxiosError(payload) {
2545
+ return utils$1.isObject(payload) && payload.isAxiosError === true;
2546
+ }
2547
+ const HttpStatusCode = {
2548
+ Continue: 100,
2549
+ SwitchingProtocols: 101,
2550
+ Processing: 102,
2551
+ EarlyHints: 103,
2552
+ Ok: 200,
2553
+ Created: 201,
2554
+ Accepted: 202,
2555
+ NonAuthoritativeInformation: 203,
2556
+ NoContent: 204,
2557
+ ResetContent: 205,
2558
+ PartialContent: 206,
2559
+ MultiStatus: 207,
2560
+ AlreadyReported: 208,
2561
+ ImUsed: 226,
2562
+ MultipleChoices: 300,
2563
+ MovedPermanently: 301,
2564
+ Found: 302,
2565
+ SeeOther: 303,
2566
+ NotModified: 304,
2567
+ UseProxy: 305,
2568
+ Unused: 306,
2569
+ TemporaryRedirect: 307,
2570
+ PermanentRedirect: 308,
2571
+ BadRequest: 400,
2572
+ Unauthorized: 401,
2573
+ PaymentRequired: 402,
2574
+ Forbidden: 403,
2575
+ NotFound: 404,
2576
+ MethodNotAllowed: 405,
2577
+ NotAcceptable: 406,
2578
+ ProxyAuthenticationRequired: 407,
2579
+ RequestTimeout: 408,
2580
+ Conflict: 409,
2581
+ Gone: 410,
2582
+ LengthRequired: 411,
2583
+ PreconditionFailed: 412,
2584
+ PayloadTooLarge: 413,
2585
+ UriTooLong: 414,
2586
+ UnsupportedMediaType: 415,
2587
+ RangeNotSatisfiable: 416,
2588
+ ExpectationFailed: 417,
2589
+ ImATeapot: 418,
2590
+ MisdirectedRequest: 421,
2591
+ UnprocessableEntity: 422,
2592
+ Locked: 423,
2593
+ FailedDependency: 424,
2594
+ TooEarly: 425,
2595
+ UpgradeRequired: 426,
2596
+ PreconditionRequired: 428,
2597
+ TooManyRequests: 429,
2598
+ RequestHeaderFieldsTooLarge: 431,
2599
+ UnavailableForLegalReasons: 451,
2600
+ InternalServerError: 500,
2601
+ NotImplemented: 501,
2602
+ BadGateway: 502,
2603
+ ServiceUnavailable: 503,
2604
+ GatewayTimeout: 504,
2605
+ HttpVersionNotSupported: 505,
2606
+ VariantAlsoNegotiates: 506,
2607
+ InsufficientStorage: 507,
2608
+ LoopDetected: 508,
2609
+ NotExtended: 510,
2610
+ NetworkAuthenticationRequired: 511
2611
+ };
2612
+ Object.entries(HttpStatusCode).forEach(([key, value]) => {
2613
+ HttpStatusCode[value] = key;
2614
+ });
2615
+ function createInstance(defaultConfig) {
2616
+ const context = new Axios(defaultConfig);
2617
+ const instance = bind(Axios.prototype.request, context);
2618
+ utils$1.extend(instance, Axios.prototype, context, { allOwnKeys: true });
2619
+ utils$1.extend(instance, context, null, { allOwnKeys: true });
2620
+ instance.create = function create(instanceConfig) {
2621
+ return createInstance(mergeConfig(defaultConfig, instanceConfig));
2622
+ };
2623
+ return instance;
2624
+ }
2625
+ const axios = createInstance(defaults);
2626
+ axios.Axios = Axios;
2627
+ axios.CanceledError = CanceledError;
2628
+ axios.CancelToken = CancelToken;
2629
+ axios.isCancel = isCancel;
2630
+ axios.VERSION = VERSION;
2631
+ axios.toFormData = toFormData;
2632
+ axios.AxiosError = AxiosError;
2633
+ axios.Cancel = axios.CanceledError;
2634
+ axios.all = function all(promises) {
2635
+ return Promise.all(promises);
2636
+ };
2637
+ axios.spread = spread;
2638
+ axios.isAxiosError = isAxiosError;
2639
+ axios.mergeConfig = mergeConfig;
2640
+ axios.AxiosHeaders = AxiosHeaders;
2641
+ axios.formToJSON = (thing) => formDataToJSON(utils$1.isHTMLForm(thing) ? new FormData(thing) : thing);
2642
+ axios.getAdapter = adapters.getAdapter;
2643
+ axios.HttpStatusCode = HttpStatusCode;
2644
+ axios.default = axios;
2645
+ class MemoryCache {
2646
+ constructor(ttl) {
2647
+ __publicField(this, "cache", {});
2648
+ __publicField(this, "ttl");
2649
+ this.ttl = ttl;
2650
+ }
2651
+ async get(key) {
2652
+ const cacheRecord = this.cache;
2653
+ return new Promise((resolve, reject) => {
2654
+ try {
2655
+ const cacheItem = cacheRecord[key];
2656
+ if (!cacheItem) {
2657
+ return resolve({ error: "[MemoryCache]未找到缓存,将执行请求", data: null });
2658
+ }
2659
+ const { data, exp } = cacheItem;
2660
+ if (exp < Math.ceil((/* @__PURE__ */ new Date()).getTime() / 1e3)) {
2661
+ this.delete(key);
2662
+ return resolve({ error: "[MemoryCache]缓存已过期,将执行请求", data: null });
2663
+ }
2664
+ resolve({ error: null, data });
2665
+ } catch (error) {
2666
+ reject({ error, data: null });
2667
+ }
2668
+ });
2669
+ }
2670
+ async set(key, value) {
2671
+ return new Promise((resolve, reject) => {
2672
+ try {
2673
+ this.cache[key] = {
2674
+ data: value,
2675
+ exp: Math.ceil((/* @__PURE__ */ new Date()).getTime() / 1e3) + this.ttl
2676
+ };
2677
+ resolve({ error: null, data: true });
2678
+ } catch (error) {
2679
+ reject({ error, data: null });
2680
+ }
2681
+ });
2682
+ }
2683
+ async delete(key) {
2684
+ return new Promise((resolve, reject) => {
2685
+ try {
2686
+ delete this.cache[key];
2687
+ resolve({ error: null, data: true });
2688
+ } catch (error) {
2689
+ reject({ error, data: null });
2690
+ }
2691
+ });
2692
+ }
2693
+ }
2694
+ class LocalStorageCache {
2695
+ constructor(ttl) {
2696
+ __publicField(this, "ttl");
2697
+ this.ttl = ttl;
2698
+ }
2699
+ async get(key) {
2700
+ return new Promise((resolve, reject) => {
2701
+ try {
2702
+ const cacheItem = localStorage.getItem(key);
2703
+ if (!cacheItem) {
2704
+ return resolve({ error: `未找到${key}的缓存`, data: null });
2705
+ }
2706
+ const { data, exp } = JSON.parse(cacheItem);
2707
+ if (exp < Math.ceil((/* @__PURE__ */ new Date()).getTime() / 1e3)) {
2708
+ this.delete(key);
2709
+ return resolve({ error: `${key}的缓存已过期`, data: null });
2710
+ }
2711
+ resolve({ error: null, data });
2712
+ } catch (error) {
2713
+ reject({ error, data: null });
2714
+ }
2715
+ });
2716
+ }
2717
+ async set(key, value) {
2718
+ return new Promise((resolve, reject) => {
2719
+ try {
2720
+ localStorage.setItem(
2721
+ key,
2722
+ JSON.stringify({
2723
+ data: value,
2724
+ exp: Math.ceil((/* @__PURE__ */ new Date()).getTime() / 1e3) + this.ttl
2725
+ })
2726
+ );
2727
+ resolve({ error: null, data: true });
2728
+ } catch (error) {
2729
+ reject({ error, data: null });
2730
+ }
2731
+ });
2732
+ }
2733
+ async delete(key) {
2734
+ return new Promise((resolve, reject) => {
2735
+ try {
2736
+ localStorage.removeItem(key);
2737
+ resolve({ error: null, data: true });
2738
+ } catch (error) {
2739
+ reject({ error, data: null });
2740
+ }
2741
+ });
2742
+ }
2743
+ }
2744
+ const INDEXDB_DATABASE_NAME = "SNAIL_CACHE";
2745
+ const INDEXDB_VERSION = 3;
2746
+ const INDEXDB_OBJECT_STORE_NAME = "SNAIL_CACHE_OBJECT";
2747
+ const INDEXDB_INDEX_NAME = "SNAIL_CACHE_INDEX";
2748
+ class IndexDBCache {
2749
+ constructor(ttl) {
2750
+ __publicField(this, "ttl");
2751
+ __publicField(this, "db", null);
2752
+ this.ttl = ttl;
2753
+ }
2754
+ async init() {
2755
+ this.db = await this.openDB();
2756
+ }
2757
+ async openDB() {
2758
+ return new Promise((resolve, reject) => {
2759
+ const request = indexedDB.open(INDEXDB_DATABASE_NAME, INDEXDB_VERSION);
2760
+ request.onupgradeneeded = function(event) {
2761
+ const db = event.target.result;
2762
+ const objectStore = db.createObjectStore(INDEXDB_OBJECT_STORE_NAME, {
2763
+ keyPath: "key"
2764
+ });
2765
+ objectStore.createIndex(INDEXDB_INDEX_NAME, "key", {
2766
+ unique: false
2767
+ });
2768
+ };
2769
+ request.onsuccess = function(event) {
2770
+ const db = event.target.result;
2771
+ resolve(db);
2772
+ };
2773
+ request.onerror = (event) => {
2774
+ console.error(`[indexDB]连接数据库错误:${event.target}`);
2775
+ reject(null);
2776
+ };
2777
+ });
2778
+ }
2779
+ async get(key) {
2780
+ return new Promise((resolve, reject) => {
2781
+ if (this.db === null) {
2782
+ return reject({ error: new Error("数据库未初始化"), data: null });
2783
+ }
2784
+ const select = this.db.transaction(INDEXDB_OBJECT_STORE_NAME, "readonly").objectStore(INDEXDB_OBJECT_STORE_NAME).get(key);
2785
+ select.onsuccess = () => {
2786
+ const result = select.result;
2787
+ if (!result || result.exp < Math.ceil((/* @__PURE__ */ new Date()).getTime() / 1e3)) {
2788
+ this.delete(key);
2789
+ return resolve({ error: new Error("缓存已过期"), data: null });
2790
+ }
2791
+ resolve({ error: null, data: result.data });
2792
+ };
2793
+ select.onerror = (event) => {
2794
+ reject({
2795
+ error: new Error(`查询数据错误:${event.target}`),
2796
+ data: null
2797
+ });
2798
+ };
2799
+ });
2800
+ }
2801
+ async set(key, value) {
2802
+ return new Promise((resolve, reject) => {
2803
+ if (this.db === null) {
2804
+ return reject({ error: new Error("数据库未初始化"), data: null });
2805
+ }
2806
+ const select = this.db.transaction(INDEXDB_OBJECT_STORE_NAME, "readwrite").objectStore(INDEXDB_OBJECT_STORE_NAME).put(
2807
+ {
2808
+ data: value,
2809
+ exp: Math.ceil((/* @__PURE__ */ new Date()).getTime() / 1e3) + this.ttl,
2810
+ key
2811
+ }
2812
+ );
2813
+ select.onsuccess = () => {
2814
+ resolve({ error: null, data: true });
2815
+ };
2816
+ select.onerror = (event) => {
2817
+ reject({
2818
+ error: new Error(`插入数据错误:${event.target}`),
2819
+ data: null
2820
+ });
2821
+ };
2822
+ });
2823
+ }
2824
+ async delete(key) {
2825
+ return new Promise((resolve, reject) => {
2826
+ if (this.db === null) {
2827
+ return reject({ error: new Error("数据库未初始化"), data: null });
2828
+ }
2829
+ const select = this.db.transaction(INDEXDB_OBJECT_STORE_NAME, "readwrite").objectStore(INDEXDB_OBJECT_STORE_NAME).delete(key);
2830
+ select.onsuccess = () => {
2831
+ resolve({ error: null, data: true });
2832
+ };
2833
+ select.onerror = (event) => {
2834
+ reject({
2835
+ error: new Error(`删除数据错误:${event.target}`),
2836
+ data: null
2837
+ });
2838
+ };
2839
+ });
2840
+ }
2841
+ }
2842
+ function createCache(type, ttl) {
2843
+ if (type === CacheType.Memory) {
2844
+ return new MemoryCache(ttl);
2845
+ }
2846
+ if (type === CacheType.LocalStorage) {
2847
+ return new LocalStorageCache(ttl);
2848
+ }
2849
+ if (type === CacheType.IndexDB) {
2850
+ const db = new IndexDBCache(ttl);
2851
+ db.init();
2852
+ return db;
2853
+ }
2854
+ return void 0;
2855
+ }
2856
+ const DEFAULT_CONFIG = {
2857
+ timeout: 5e3,
2858
+ // 默认开启内存缓存
2859
+ CacheManage: {
2860
+ type: CacheType.Memory,
2861
+ // 默认缓存时间为5分钟(单位秒)
2862
+ ttl: 300
2863
+ }
2864
+ };
2865
+ class Snail {
2866
+ constructor(options) {
2867
+ __publicField(this, "axiosInstance");
2868
+ __publicField(this, "baseURL", "");
2869
+ __publicField(this, "versioning");
2870
+ __publicField(this, "options");
2871
+ __publicField(this, "cacheStorage");
2872
+ __publicField(this, "cacheSource");
2873
+ const instance = this;
2874
+ const SnailOptions = {
2875
+ ...DEFAULT_CONFIG,
2876
+ ...options
2877
+ };
2878
+ this.baseURL = SnailOptions.baseURL || "";
2879
+ this.versioning = SnailOptions.Versioning;
2880
+ this.options = SnailOptions;
2881
+ instance.axiosInstance = axios.create({
2882
+ baseURL: instance.baseURL,
2883
+ timeout: instance.options.timeout || 5e3
2884
+ });
2885
+ if (SnailOptions.requestInterceptors) {
2886
+ instance.axiosInstance.interceptors.request.use(
2887
+ (config) => {
2888
+ var _a, _b;
2889
+ const result = (_b = (_a = SnailOptions.requestInterceptors) == null ? void 0 : _a.onFulfilled) == null ? void 0 : _b.call(_a, config);
2890
+ return result ? result : config;
2891
+ },
2892
+ SnailOptions.requestInterceptors.onRejected,
2893
+ SnailOptions.requestInterceptors.options
2894
+ );
2895
+ }
2896
+ if (SnailOptions.responseInterceptors) {
2897
+ instance.axiosInstance.interceptors.response.use(
2898
+ (response) => {
2899
+ var _a, _b;
2900
+ const result = (_b = (_a = SnailOptions.responseInterceptors) == null ? void 0 : _a.onFulfilled) == null ? void 0 : _b.call(_a, response);
2901
+ return result ? result : response;
2902
+ },
2903
+ (error) => {
2904
+ var _a, _b;
2905
+ const result = (_b = (_a = SnailOptions.responseInterceptors) == null ? void 0 : _a.onRejected) == null ? void 0 : _b.call(_a, error);
2906
+ return Promise.reject(result || error);
2907
+ }
2908
+ );
2909
+ }
2910
+ if (instance.options.CacheManage) {
2911
+ const { type, ttl } = instance.options.CacheManage;
2912
+ instance.cacheStorage = createCache(type, ttl || 300);
2913
+ }
2914
+ }
2915
+ Get(url, options) {
2916
+ return new Api(RequestMethod.GET, url, this, options);
2917
+ }
2918
+ Post(url, options) {
2919
+ return new Api(RequestMethod.POST, url, this, options);
2920
+ }
2921
+ Put(url, options) {
2922
+ return new Api(RequestMethod.PUT, url, this, options);
2923
+ }
2924
+ Delete(url, options) {
2925
+ return new Api(RequestMethod.DELETE, url, this, options);
2926
+ }
2927
+ Patch(url, options) {
2928
+ return new Api(RequestMethod.PATCH, url, this, options);
2929
+ }
2930
+ Head(url, options) {
2931
+ return new Api(RequestMethod.HEAD, url, this, options);
2932
+ }
2933
+ Options(url, options) {
2934
+ return new Api(RequestMethod.OPTIONS, url, this, options);
2935
+ }
2936
+ }
2937
+ const createSnail = (option) => {
2938
+ return new Snail(option);
2939
+ };
2940
+ export {
2941
+ Api,
2942
+ CacheType,
2943
+ RequestMethod,
2944
+ Snail,
2945
+ VersioningType,
2946
+ apiKey,
2947
+ createSnail,
2948
+ deepCopy,
2949
+ getResponseDataFromCache,
2950
+ recordToString
2951
+ };