@vritti/quantum-ui 0.2.9 → 0.2.10

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