@jjrawlins/cdk-iam-policy-builder-helper 0.0.0 → 0.0.2

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 (62) hide show
  1. package/.jsii +375 -24
  2. package/README.md +1 -1
  3. package/{layerborncdkiampolicybuilderhelper → jjrawlinscdkiampolicybuilderhelper}/README.md +1 -1
  4. package/jjrawlinscdkiampolicybuilderhelper/go.mod +13 -0
  5. package/{layerborncdkiampolicybuilderhelper → jjrawlinscdkiampolicybuilderhelper}/jsii/jsii.go +2 -2
  6. package/jjrawlinscdkiampolicybuilderhelper/version +1 -0
  7. package/lib/bin/create-actions-json.js +1 -1
  8. package/lib/bin/download-actions-json.js +1 -1
  9. package/lib/bin/download-managed-policies-json.js +1 -1
  10. package/lib/constructs/Actions.d.ts +1151 -0
  11. package/lib/constructs/Actions.js +1165 -14
  12. package/methods_list.txt +1118 -1
  13. package/node_modules/axios/CHANGELOG.md +880 -774
  14. package/node_modules/axios/README.md +60 -15
  15. package/node_modules/axios/dist/axios.js +1108 -294
  16. package/node_modules/axios/dist/axios.js.map +1 -1
  17. package/node_modules/axios/dist/axios.min.js +1 -1
  18. package/node_modules/axios/dist/axios.min.js.map +1 -1
  19. package/node_modules/axios/dist/browser/axios.cjs +764 -308
  20. package/node_modules/axios/dist/browser/axios.cjs.map +1 -1
  21. package/node_modules/axios/dist/esm/axios.js +764 -308
  22. package/node_modules/axios/dist/esm/axios.js.map +1 -1
  23. package/node_modules/axios/dist/esm/axios.min.js +1 -1
  24. package/node_modules/axios/dist/esm/axios.min.js.map +1 -1
  25. package/node_modules/axios/dist/node/axios.cjs +777 -388
  26. package/node_modules/axios/dist/node/axios.cjs.map +1 -1
  27. package/node_modules/axios/index.d.cts +5 -2
  28. package/node_modules/axios/index.d.ts +5 -2
  29. package/node_modules/axios/lib/adapters/adapters.js +3 -1
  30. package/node_modules/axios/lib/adapters/fetch.js +229 -0
  31. package/node_modules/axios/lib/adapters/http.js +26 -16
  32. package/node_modules/axios/lib/adapters/xhr.js +36 -99
  33. package/node_modules/axios/lib/core/Axios.js +9 -6
  34. package/node_modules/axios/lib/core/AxiosHeaders.js +4 -0
  35. package/node_modules/axios/lib/defaults/index.js +7 -2
  36. package/node_modules/axios/lib/env/data.js +1 -1
  37. package/node_modules/axios/lib/helpers/AxiosTransformStream.js +3 -51
  38. package/node_modules/axios/lib/helpers/composeSignals.js +46 -0
  39. package/node_modules/axios/lib/helpers/progressEventReducer.js +44 -0
  40. package/node_modules/axios/lib/helpers/resolveConfig.js +57 -0
  41. package/node_modules/axios/lib/helpers/throttle.js +30 -19
  42. package/node_modules/axios/lib/helpers/trackStream.js +67 -0
  43. package/node_modules/axios/lib/platform/common/utils.js +4 -1
  44. package/node_modules/axios/lib/utils.js +40 -3
  45. package/node_modules/axios/package.json +4 -3
  46. package/package.json +26 -22
  47. package/layerborncdkiampolicybuilderhelper/go.mod +0 -13
  48. package/layerborncdkiampolicybuilderhelper/version +0 -1
  49. package/node_modules/@aws-sdk/util-utf8-browser/dist-cjs/index.js +0 -9
  50. package/node_modules/@aws-sdk/util-utf8-browser/dist-cjs/pureJs.js +0 -47
  51. package/node_modules/@aws-sdk/util-utf8-browser/dist-cjs/whatwgEncodingApi.js +0 -11
  52. package/node_modules/@aws-sdk/util-utf8-browser/dist-es/index.js +0 -4
  53. package/node_modules/@aws-sdk/util-utf8-browser/dist-es/pureJs.js +0 -42
  54. package/node_modules/@aws-sdk/util-utf8-browser/dist-es/whatwgEncodingApi.js +0 -6
  55. package/node_modules/@aws-sdk/util-utf8-browser/dist-types/index.d.ts +0 -2
  56. package/node_modules/@aws-sdk/util-utf8-browser/dist-types/pureJs.d.ts +0 -17
  57. package/node_modules/@aws-sdk/util-utf8-browser/dist-types/ts3.4/index.d.ts +0 -2
  58. package/node_modules/@aws-sdk/util-utf8-browser/dist-types/ts3.4/pureJs.d.ts +0 -2
  59. package/node_modules/@aws-sdk/util-utf8-browser/dist-types/ts3.4/whatwgEncodingApi.d.ts +0 -2
  60. package/node_modules/@aws-sdk/util-utf8-browser/dist-types/whatwgEncodingApi.d.ts +0 -2
  61. package/node_modules/combined-stream/yarn.lock +0 -17
  62. /package/{layerborncdkiampolicybuilderhelper → jjrawlinscdkiampolicybuilderhelper}/LICENSE +0 -0
@@ -1,4 +1,4 @@
1
- // Axios v1.6.8 Copyright (c) 2024 Matt Zabriskie and contributors
1
+ // Axios v1.7.4 Copyright (c) 2024 Matt Zabriskie and contributors
2
2
  'use strict';
3
3
 
4
4
  const FormData$1 = require('form-data');
@@ -236,6 +236,8 @@ const isFormData = (thing) => {
236
236
  */
237
237
  const isURLSearchParams = kindOfTest('URLSearchParams');
238
238
 
239
+ const [isReadableStream, isRequest, isResponse, isHeaders] = ['ReadableStream', 'Request', 'Response', 'Headers'].map(kindOfTest);
240
+
239
241
  /**
240
242
  * Trim excess whitespace off the beginning and end of a string
241
243
  *
@@ -624,8 +626,7 @@ const toObjectSet = (arrayOrString, delimiter) => {
624
626
  const noop = () => {};
625
627
 
626
628
  const toFiniteNumber = (value, defaultValue) => {
627
- value = +value;
628
- return Number.isFinite(value) ? value : defaultValue;
629
+ return value != null && Number.isFinite(value = +value) ? value : defaultValue;
629
630
  };
630
631
 
631
632
  const ALPHA = 'abcdefghijklmnopqrstuvwxyz';
@@ -695,6 +696,36 @@ const isAsyncFn = kindOfTest('AsyncFunction');
695
696
  const isThenable = (thing) =>
696
697
  thing && (isObject(thing) || isFunction(thing)) && isFunction(thing.then) && isFunction(thing.catch);
697
698
 
699
+ // original code
700
+ // https://github.com/DigitalBrainJS/AxiosPromise/blob/16deab13710ec09779922131f3fa5954320f83ab/lib/utils.js#L11-L34
701
+
702
+ const _setImmediate = ((setImmediateSupported, postMessageSupported) => {
703
+ if (setImmediateSupported) {
704
+ return setImmediate;
705
+ }
706
+
707
+ return postMessageSupported ? ((token, callbacks) => {
708
+ _global.addEventListener("message", ({source, data}) => {
709
+ if (source === _global && data === token) {
710
+ callbacks.length && callbacks.shift()();
711
+ }
712
+ }, false);
713
+
714
+ return (cb) => {
715
+ callbacks.push(cb);
716
+ _global.postMessage(token, "*");
717
+ }
718
+ })(`axios@${Math.random()}`, []) : (cb) => setTimeout(cb);
719
+ })(
720
+ typeof setImmediate === 'function',
721
+ isFunction(_global.postMessage)
722
+ );
723
+
724
+ const asap = typeof queueMicrotask !== 'undefined' ?
725
+ queueMicrotask.bind(_global) : ( typeof process !== 'undefined' && process.nextTick || _setImmediate);
726
+
727
+ // *********************
728
+
698
729
  const utils$1 = {
699
730
  isArray,
700
731
  isArrayBuffer,
@@ -706,6 +737,10 @@ const utils$1 = {
706
737
  isBoolean,
707
738
  isObject,
708
739
  isPlainObject,
740
+ isReadableStream,
741
+ isRequest,
742
+ isResponse,
743
+ isHeaders,
709
744
  isUndefined,
710
745
  isDate,
711
746
  isFile,
@@ -746,7 +781,9 @@ const utils$1 = {
746
781
  isSpecCompliantForm,
747
782
  toJSONObject,
748
783
  isAsyncFn,
749
- isThenable
784
+ isThenable,
785
+ setImmediate: _setImmediate,
786
+ asap
750
787
  };
751
788
 
752
789
  /**
@@ -1295,11 +1332,14 @@ const hasStandardBrowserWebWorkerEnv = (() => {
1295
1332
  );
1296
1333
  })();
1297
1334
 
1335
+ const origin = hasBrowserEnv && window.location.href || 'http://localhost';
1336
+
1298
1337
  const utils = /*#__PURE__*/Object.freeze({
1299
1338
  __proto__: null,
1300
1339
  hasBrowserEnv: hasBrowserEnv,
1301
1340
  hasStandardBrowserWebWorkerEnv: hasStandardBrowserWebWorkerEnv,
1302
- hasStandardBrowserEnv: hasStandardBrowserEnv
1341
+ hasStandardBrowserEnv: hasStandardBrowserEnv,
1342
+ origin: origin
1303
1343
  });
1304
1344
 
1305
1345
  const platform = {
@@ -1439,7 +1479,7 @@ const defaults = {
1439
1479
 
1440
1480
  transitional: transitionalDefaults,
1441
1481
 
1442
- adapter: ['xhr', 'http'],
1482
+ adapter: ['xhr', 'http', 'fetch'],
1443
1483
 
1444
1484
  transformRequest: [function transformRequest(data, headers) {
1445
1485
  const contentType = headers.getContentType() || '';
@@ -1460,7 +1500,8 @@ const defaults = {
1460
1500
  utils$1.isBuffer(data) ||
1461
1501
  utils$1.isStream(data) ||
1462
1502
  utils$1.isFile(data) ||
1463
- utils$1.isBlob(data)
1503
+ utils$1.isBlob(data) ||
1504
+ utils$1.isReadableStream(data)
1464
1505
  ) {
1465
1506
  return data;
1466
1507
  }
@@ -1503,6 +1544,10 @@ const defaults = {
1503
1544
  const forcedJSONParsing = transitional && transitional.forcedJSONParsing;
1504
1545
  const JSONRequested = this.responseType === 'json';
1505
1546
 
1547
+ if (utils$1.isResponse(data) || utils$1.isReadableStream(data)) {
1548
+ return data;
1549
+ }
1550
+
1506
1551
  if (data && utils$1.isString(data) && ((forcedJSONParsing && !this.responseType) || JSONRequested)) {
1507
1552
  const silentJSONParsing = transitional && transitional.silentJSONParsing;
1508
1553
  const strictJSONParsing = !silentJSONParsing && JSONRequested;
@@ -1706,6 +1751,10 @@ class AxiosHeaders {
1706
1751
  setHeaders(header, valueOrRewrite);
1707
1752
  } else if(utils$1.isString(header) && (header = header.trim()) && !isValidHeaderName(header)) {
1708
1753
  setHeaders(parseHeaders(header), valueOrRewrite);
1754
+ } else if (utils$1.isHeaders(header)) {
1755
+ for (const [key, value] of header.entries()) {
1756
+ setHeader(value, key, rewrite);
1757
+ }
1709
1758
  } else {
1710
1759
  header != null && setHeader(valueOrRewrite, header, rewrite);
1711
1760
  }
@@ -2018,7 +2067,7 @@ function buildFullPath(baseURL, requestedURL) {
2018
2067
  return requestedURL;
2019
2068
  }
2020
2069
 
2021
- const VERSION = "1.6.8";
2070
+ const VERSION = "1.7.4";
2022
2071
 
2023
2072
  function parseProtocol(url) {
2024
2073
  const match = /^([-+\w]{1,25})(:?\/\/|:)/.exec(url);
@@ -2073,88 +2122,6 @@ function fromDataURI(uri, asBlob, options) {
2073
2122
  throw new AxiosError('Unsupported protocol ' + protocol, AxiosError.ERR_NOT_SUPPORT);
2074
2123
  }
2075
2124
 
2076
- /**
2077
- * Throttle decorator
2078
- * @param {Function} fn
2079
- * @param {Number} freq
2080
- * @return {Function}
2081
- */
2082
- function throttle(fn, freq) {
2083
- let timestamp = 0;
2084
- const threshold = 1000 / freq;
2085
- let timer = null;
2086
- return function throttled(force, args) {
2087
- const now = Date.now();
2088
- if (force || now - timestamp > threshold) {
2089
- if (timer) {
2090
- clearTimeout(timer);
2091
- timer = null;
2092
- }
2093
- timestamp = now;
2094
- return fn.apply(null, args);
2095
- }
2096
- if (!timer) {
2097
- timer = setTimeout(() => {
2098
- timer = null;
2099
- timestamp = Date.now();
2100
- return fn.apply(null, args);
2101
- }, threshold - (now - timestamp));
2102
- }
2103
- };
2104
- }
2105
-
2106
- /**
2107
- * Calculate data maxRate
2108
- * @param {Number} [samplesCount= 10]
2109
- * @param {Number} [min= 1000]
2110
- * @returns {Function}
2111
- */
2112
- function speedometer(samplesCount, min) {
2113
- samplesCount = samplesCount || 10;
2114
- const bytes = new Array(samplesCount);
2115
- const timestamps = new Array(samplesCount);
2116
- let head = 0;
2117
- let tail = 0;
2118
- let firstSampleTS;
2119
-
2120
- min = min !== undefined ? min : 1000;
2121
-
2122
- return function push(chunkLength) {
2123
- const now = Date.now();
2124
-
2125
- const startedAt = timestamps[tail];
2126
-
2127
- if (!firstSampleTS) {
2128
- firstSampleTS = now;
2129
- }
2130
-
2131
- bytes[head] = chunkLength;
2132
- timestamps[head] = now;
2133
-
2134
- let i = tail;
2135
- let bytesCount = 0;
2136
-
2137
- while (i !== head) {
2138
- bytesCount += bytes[i++];
2139
- i = i % samplesCount;
2140
- }
2141
-
2142
- head = (head + 1) % samplesCount;
2143
-
2144
- if (head === tail) {
2145
- tail = (tail + 1) % samplesCount;
2146
- }
2147
-
2148
- if (now - firstSampleTS < min) {
2149
- return;
2150
- }
2151
-
2152
- const passed = startedAt && now - startedAt;
2153
-
2154
- return passed ? Math.round(bytesCount * 1000 / passed) : undefined;
2155
- };
2156
- }
2157
-
2158
2125
  const kInternals = Symbol('internals');
2159
2126
 
2160
2127
  class AxiosTransformStream extends stream__default["default"].Transform{
@@ -2174,12 +2141,8 @@ class AxiosTransformStream extends stream__default["default"].Transform{
2174
2141
  readableHighWaterMark: options.chunkSize
2175
2142
  });
2176
2143
 
2177
- const self = this;
2178
-
2179
2144
  const internals = this[kInternals] = {
2180
- length: options.length,
2181
2145
  timeWindow: options.timeWindow,
2182
- ticksRate: options.ticksRate,
2183
2146
  chunkSize: options.chunkSize,
2184
2147
  maxRate: options.maxRate,
2185
2148
  minChunkSize: options.minChunkSize,
@@ -2191,8 +2154,6 @@ class AxiosTransformStream extends stream__default["default"].Transform{
2191
2154
  onReadCallback: null
2192
2155
  };
2193
2156
 
2194
- const _speedometer = speedometer(internals.ticksRate * options.samplesCount, internals.timeWindow);
2195
-
2196
2157
  this.on('newListener', event => {
2197
2158
  if (event === 'progress') {
2198
2159
  if (!internals.isCaptured) {
@@ -2200,38 +2161,6 @@ class AxiosTransformStream extends stream__default["default"].Transform{
2200
2161
  }
2201
2162
  }
2202
2163
  });
2203
-
2204
- let bytesNotified = 0;
2205
-
2206
- internals.updateProgress = throttle(function throttledHandler() {
2207
- const totalBytes = internals.length;
2208
- const bytesTransferred = internals.bytesSeen;
2209
- const progressBytes = bytesTransferred - bytesNotified;
2210
- if (!progressBytes || self.destroyed) return;
2211
-
2212
- const rate = _speedometer(progressBytes);
2213
-
2214
- bytesNotified = bytesTransferred;
2215
-
2216
- process.nextTick(() => {
2217
- self.emit('progress', {
2218
- 'loaded': bytesTransferred,
2219
- 'total': totalBytes,
2220
- 'progress': totalBytes ? (bytesTransferred / totalBytes) : undefined,
2221
- 'bytes': progressBytes,
2222
- 'rate': rate ? rate : undefined,
2223
- 'estimated': rate && totalBytes && bytesTransferred <= totalBytes ?
2224
- (totalBytes - bytesTransferred) / rate : undefined
2225
- });
2226
- });
2227
- }, internals.ticksRate);
2228
-
2229
- const onFinish = () => {
2230
- internals.updateProgress(true);
2231
- };
2232
-
2233
- this.once('end', onFinish);
2234
- this.once('error', onFinish);
2235
2164
  }
2236
2165
 
2237
2166
  _read(size) {
@@ -2245,7 +2174,6 @@ class AxiosTransformStream extends stream__default["default"].Transform{
2245
2174
  }
2246
2175
 
2247
2176
  _transform(chunk, encoding, callback) {
2248
- const self = this;
2249
2177
  const internals = this[kInternals];
2250
2178
  const maxRate = internals.maxRate;
2251
2179
 
@@ -2257,16 +2185,14 @@ class AxiosTransformStream extends stream__default["default"].Transform{
2257
2185
  const bytesThreshold = (maxRate / divider);
2258
2186
  const minChunkSize = internals.minChunkSize !== false ? Math.max(internals.minChunkSize, bytesThreshold * 0.01) : 0;
2259
2187
 
2260
- function pushChunk(_chunk, _callback) {
2188
+ const pushChunk = (_chunk, _callback) => {
2261
2189
  const bytes = Buffer.byteLength(_chunk);
2262
2190
  internals.bytesSeen += bytes;
2263
2191
  internals.bytes += bytes;
2264
2192
 
2265
- if (internals.isCaptured) {
2266
- internals.updateProgress();
2267
- }
2193
+ internals.isCaptured && this.emit('progress', internals.bytesSeen);
2268
2194
 
2269
- if (self.push(_chunk)) {
2195
+ if (this.push(_chunk)) {
2270
2196
  process.nextTick(_callback);
2271
2197
  } else {
2272
2198
  internals.onReadCallback = () => {
@@ -2274,7 +2200,7 @@ class AxiosTransformStream extends stream__default["default"].Transform{
2274
2200
  process.nextTick(_callback);
2275
2201
  };
2276
2202
  }
2277
- }
2203
+ };
2278
2204
 
2279
2205
  const transformChunk = (_chunk, _callback) => {
2280
2206
  const chunkSize = Buffer.byteLength(_chunk);
@@ -2331,11 +2257,6 @@ class AxiosTransformStream extends stream__default["default"].Transform{
2331
2257
  }
2332
2258
  });
2333
2259
  }
2334
-
2335
- setLength(length) {
2336
- this[kInternals].length = +length;
2337
- return this;
2338
- }
2339
2260
  }
2340
2261
 
2341
2262
  const AxiosTransformStream$1 = AxiosTransformStream;
@@ -2503,6 +2424,142 @@ const callbackify = (fn, reducer) => {
2503
2424
 
2504
2425
  const callbackify$1 = callbackify;
2505
2426
 
2427
+ /**
2428
+ * Calculate data maxRate
2429
+ * @param {Number} [samplesCount= 10]
2430
+ * @param {Number} [min= 1000]
2431
+ * @returns {Function}
2432
+ */
2433
+ function speedometer(samplesCount, min) {
2434
+ samplesCount = samplesCount || 10;
2435
+ const bytes = new Array(samplesCount);
2436
+ const timestamps = new Array(samplesCount);
2437
+ let head = 0;
2438
+ let tail = 0;
2439
+ let firstSampleTS;
2440
+
2441
+ min = min !== undefined ? min : 1000;
2442
+
2443
+ return function push(chunkLength) {
2444
+ const now = Date.now();
2445
+
2446
+ const startedAt = timestamps[tail];
2447
+
2448
+ if (!firstSampleTS) {
2449
+ firstSampleTS = now;
2450
+ }
2451
+
2452
+ bytes[head] = chunkLength;
2453
+ timestamps[head] = now;
2454
+
2455
+ let i = tail;
2456
+ let bytesCount = 0;
2457
+
2458
+ while (i !== head) {
2459
+ bytesCount += bytes[i++];
2460
+ i = i % samplesCount;
2461
+ }
2462
+
2463
+ head = (head + 1) % samplesCount;
2464
+
2465
+ if (head === tail) {
2466
+ tail = (tail + 1) % samplesCount;
2467
+ }
2468
+
2469
+ if (now - firstSampleTS < min) {
2470
+ return;
2471
+ }
2472
+
2473
+ const passed = startedAt && now - startedAt;
2474
+
2475
+ return passed ? Math.round(bytesCount * 1000 / passed) : undefined;
2476
+ };
2477
+ }
2478
+
2479
+ /**
2480
+ * Throttle decorator
2481
+ * @param {Function} fn
2482
+ * @param {Number} freq
2483
+ * @return {Function}
2484
+ */
2485
+ function throttle(fn, freq) {
2486
+ let timestamp = 0;
2487
+ let threshold = 1000 / freq;
2488
+ let lastArgs;
2489
+ let timer;
2490
+
2491
+ const invoke = (args, now = Date.now()) => {
2492
+ timestamp = now;
2493
+ lastArgs = null;
2494
+ if (timer) {
2495
+ clearTimeout(timer);
2496
+ timer = null;
2497
+ }
2498
+ fn.apply(null, args);
2499
+ };
2500
+
2501
+ const throttled = (...args) => {
2502
+ const now = Date.now();
2503
+ const passed = now - timestamp;
2504
+ if ( passed >= threshold) {
2505
+ invoke(args, now);
2506
+ } else {
2507
+ lastArgs = args;
2508
+ if (!timer) {
2509
+ timer = setTimeout(() => {
2510
+ timer = null;
2511
+ invoke(lastArgs);
2512
+ }, threshold - passed);
2513
+ }
2514
+ }
2515
+ };
2516
+
2517
+ const flush = () => lastArgs && invoke(lastArgs);
2518
+
2519
+ return [throttled, flush];
2520
+ }
2521
+
2522
+ const progressEventReducer = (listener, isDownloadStream, freq = 3) => {
2523
+ let bytesNotified = 0;
2524
+ const _speedometer = speedometer(50, 250);
2525
+
2526
+ return throttle(e => {
2527
+ const loaded = e.loaded;
2528
+ const total = e.lengthComputable ? e.total : undefined;
2529
+ const progressBytes = loaded - bytesNotified;
2530
+ const rate = _speedometer(progressBytes);
2531
+ const inRange = loaded <= total;
2532
+
2533
+ bytesNotified = loaded;
2534
+
2535
+ const data = {
2536
+ loaded,
2537
+ total,
2538
+ progress: total ? (loaded / total) : undefined,
2539
+ bytes: progressBytes,
2540
+ rate: rate ? rate : undefined,
2541
+ estimated: rate && total && inRange ? (total - loaded) / rate : undefined,
2542
+ event: e,
2543
+ lengthComputable: total != null,
2544
+ [isDownloadStream ? 'download' : 'upload']: true
2545
+ };
2546
+
2547
+ listener(data);
2548
+ }, freq);
2549
+ };
2550
+
2551
+ const progressEventDecorator = (total, throttled) => {
2552
+ const lengthComputable = total != null;
2553
+
2554
+ return [(loaded) => throttled[0]({
2555
+ lengthComputable,
2556
+ total,
2557
+ loaded
2558
+ }), throttled[1]];
2559
+ };
2560
+
2561
+ const asyncDecorator = (fn) => (...args) => utils$1.asap(() => fn(...args));
2562
+
2506
2563
  const zlibOptions = {
2507
2564
  flush: zlib__default["default"].constants.Z_SYNC_FLUSH,
2508
2565
  finishFlush: zlib__default["default"].constants.Z_SYNC_FLUSH
@@ -2523,6 +2580,14 @@ const supportedProtocols = platform.protocols.map(protocol => {
2523
2580
  return protocol + ':';
2524
2581
  });
2525
2582
 
2583
+ const flushOnFinish = (stream, [throttled, flush]) => {
2584
+ stream
2585
+ .on('end', flush)
2586
+ .on('error', flush);
2587
+
2588
+ return throttled;
2589
+ };
2590
+
2526
2591
  /**
2527
2592
  * If the proxy or config beforeRedirects functions are defined, call them with the options
2528
2593
  * object.
@@ -2698,7 +2763,7 @@ const httpAdapter = isHttpAdapterSupported && function httpAdapter(config) {
2698
2763
 
2699
2764
  // Parse url
2700
2765
  const fullPath = buildFullPath(config.baseURL, config.url);
2701
- const parsed = new URL(fullPath, 'http://localhost');
2766
+ const parsed = new URL(fullPath, utils$1.hasBrowserEnv ? platform.origin : undefined);
2702
2767
  const protocol = parsed.protocol || supportedProtocols[0];
2703
2768
 
2704
2769
  if (protocol === 'data:') {
@@ -2756,8 +2821,7 @@ const httpAdapter = isHttpAdapterSupported && function httpAdapter(config) {
2756
2821
  // Only set header if it hasn't been set in config
2757
2822
  headers.set('User-Agent', 'axios/' + VERSION, false);
2758
2823
 
2759
- const onDownloadProgress = config.onDownloadProgress;
2760
- const onUploadProgress = config.onUploadProgress;
2824
+ const {onUploadProgress, onDownloadProgress} = config;
2761
2825
  const maxRate = config.maxRate;
2762
2826
  let maxUploadRate = undefined;
2763
2827
  let maxDownloadRate = undefined;
@@ -2828,15 +2892,16 @@ const httpAdapter = isHttpAdapterSupported && function httpAdapter(config) {
2828
2892
  }
2829
2893
 
2830
2894
  data = stream__default["default"].pipeline([data, new AxiosTransformStream$1({
2831
- length: contentLength,
2832
2895
  maxRate: utils$1.toFiniteNumber(maxUploadRate)
2833
2896
  })], utils$1.noop);
2834
2897
 
2835
- onUploadProgress && data.on('progress', progress => {
2836
- onUploadProgress(Object.assign(progress, {
2837
- upload: true
2838
- }));
2839
- });
2898
+ onUploadProgress && data.on('progress', flushOnFinish(
2899
+ data,
2900
+ progressEventDecorator(
2901
+ contentLength,
2902
+ progressEventReducer(asyncDecorator(onUploadProgress), false, 3)
2903
+ )
2904
+ ));
2840
2905
  }
2841
2906
 
2842
2907
  // HTTP basic authentication
@@ -2935,17 +3000,18 @@ const httpAdapter = isHttpAdapterSupported && function httpAdapter(config) {
2935
3000
 
2936
3001
  const responseLength = +res.headers['content-length'];
2937
3002
 
2938
- if (onDownloadProgress) {
3003
+ if (onDownloadProgress || maxDownloadRate) {
2939
3004
  const transformStream = new AxiosTransformStream$1({
2940
- length: utils$1.toFiniteNumber(responseLength),
2941
3005
  maxRate: utils$1.toFiniteNumber(maxDownloadRate)
2942
3006
  });
2943
3007
 
2944
- onDownloadProgress && transformStream.on('progress', progress => {
2945
- onDownloadProgress(Object.assign(progress, {
2946
- download: true
2947
- }));
2948
- });
3008
+ onDownloadProgress && transformStream.on('progress', flushOnFinish(
3009
+ transformStream,
3010
+ progressEventDecorator(
3011
+ responseLength,
3012
+ progressEventReducer(asyncDecorator(onDownloadProgress), true, 3)
3013
+ )
3014
+ ));
2949
3015
 
2950
3016
  streams.push(transformStream);
2951
3017
  }
@@ -3158,45 +3224,6 @@ const httpAdapter = isHttpAdapterSupported && function httpAdapter(config) {
3158
3224
  });
3159
3225
  };
3160
3226
 
3161
- const cookies = platform.hasStandardBrowserEnv ?
3162
-
3163
- // Standard browser envs support document.cookie
3164
- {
3165
- write(name, value, expires, path, domain, secure) {
3166
- const cookie = [name + '=' + encodeURIComponent(value)];
3167
-
3168
- utils$1.isNumber(expires) && cookie.push('expires=' + new Date(expires).toGMTString());
3169
-
3170
- utils$1.isString(path) && cookie.push('path=' + path);
3171
-
3172
- utils$1.isString(domain) && cookie.push('domain=' + domain);
3173
-
3174
- secure === true && cookie.push('secure');
3175
-
3176
- document.cookie = cookie.join('; ');
3177
- },
3178
-
3179
- read(name) {
3180
- const match = document.cookie.match(new RegExp('(^|;\\s*)(' + name + ')=([^;]*)'));
3181
- return (match ? decodeURIComponent(match[3]) : null);
3182
- },
3183
-
3184
- remove(name) {
3185
- this.write(name, '', Date.now() - 86400000);
3186
- }
3187
- }
3188
-
3189
- :
3190
-
3191
- // Non-standard browser env (web workers, react-native) lack needed support.
3192
- {
3193
- write() {},
3194
- read() {
3195
- return null;
3196
- },
3197
- remove() {}
3198
- };
3199
-
3200
3227
  const isURLSameOrigin = platform.hasStandardBrowserEnv ?
3201
3228
 
3202
3229
  // Standard browser envs have full support of the APIs needed to test
@@ -3260,80 +3287,222 @@ const isURLSameOrigin = platform.hasStandardBrowserEnv ?
3260
3287
  };
3261
3288
  })();
3262
3289
 
3263
- function progressEventReducer(listener, isDownloadStream) {
3264
- let bytesNotified = 0;
3265
- const _speedometer = speedometer(50, 250);
3290
+ const cookies = platform.hasStandardBrowserEnv ?
3266
3291
 
3267
- return e => {
3268
- const loaded = e.loaded;
3269
- const total = e.lengthComputable ? e.total : undefined;
3270
- const progressBytes = loaded - bytesNotified;
3271
- const rate = _speedometer(progressBytes);
3272
- const inRange = loaded <= total;
3292
+ // Standard browser envs support document.cookie
3293
+ {
3294
+ write(name, value, expires, path, domain, secure) {
3295
+ const cookie = [name + '=' + encodeURIComponent(value)];
3273
3296
 
3274
- bytesNotified = loaded;
3297
+ utils$1.isNumber(expires) && cookie.push('expires=' + new Date(expires).toGMTString());
3275
3298
 
3276
- const data = {
3277
- loaded,
3278
- total,
3279
- progress: total ? (loaded / total) : undefined,
3280
- bytes: progressBytes,
3281
- rate: rate ? rate : undefined,
3282
- estimated: rate && total && inRange ? (total - loaded) / rate : undefined,
3283
- event: e
3284
- };
3299
+ utils$1.isString(path) && cookie.push('path=' + path);
3285
3300
 
3286
- data[isDownloadStream ? 'download' : 'upload'] = true;
3301
+ utils$1.isString(domain) && cookie.push('domain=' + domain);
3287
3302
 
3288
- listener(data);
3303
+ secure === true && cookie.push('secure');
3304
+
3305
+ document.cookie = cookie.join('; ');
3306
+ },
3307
+
3308
+ read(name) {
3309
+ const match = document.cookie.match(new RegExp('(^|;\\s*)(' + name + ')=([^;]*)'));
3310
+ return (match ? decodeURIComponent(match[3]) : null);
3311
+ },
3312
+
3313
+ remove(name) {
3314
+ this.write(name, '', Date.now() - 86400000);
3315
+ }
3316
+ }
3317
+
3318
+ :
3319
+
3320
+ // Non-standard browser env (web workers, react-native) lack needed support.
3321
+ {
3322
+ write() {},
3323
+ read() {
3324
+ return null;
3325
+ },
3326
+ remove() {}
3327
+ };
3328
+
3329
+ const headersToObject = (thing) => thing instanceof AxiosHeaders$1 ? { ...thing } : thing;
3330
+
3331
+ /**
3332
+ * Config-specific merge-function which creates a new config-object
3333
+ * by merging two configuration objects together.
3334
+ *
3335
+ * @param {Object} config1
3336
+ * @param {Object} config2
3337
+ *
3338
+ * @returns {Object} New object resulting from merging config2 to config1
3339
+ */
3340
+ function mergeConfig(config1, config2) {
3341
+ // eslint-disable-next-line no-param-reassign
3342
+ config2 = config2 || {};
3343
+ const config = {};
3344
+
3345
+ function getMergedValue(target, source, caseless) {
3346
+ if (utils$1.isPlainObject(target) && utils$1.isPlainObject(source)) {
3347
+ return utils$1.merge.call({caseless}, target, source);
3348
+ } else if (utils$1.isPlainObject(source)) {
3349
+ return utils$1.merge({}, source);
3350
+ } else if (utils$1.isArray(source)) {
3351
+ return source.slice();
3352
+ }
3353
+ return source;
3354
+ }
3355
+
3356
+ // eslint-disable-next-line consistent-return
3357
+ function mergeDeepProperties(a, b, caseless) {
3358
+ if (!utils$1.isUndefined(b)) {
3359
+ return getMergedValue(a, b, caseless);
3360
+ } else if (!utils$1.isUndefined(a)) {
3361
+ return getMergedValue(undefined, a, caseless);
3362
+ }
3363
+ }
3364
+
3365
+ // eslint-disable-next-line consistent-return
3366
+ function valueFromConfig2(a, b) {
3367
+ if (!utils$1.isUndefined(b)) {
3368
+ return getMergedValue(undefined, b);
3369
+ }
3370
+ }
3371
+
3372
+ // eslint-disable-next-line consistent-return
3373
+ function defaultToConfig2(a, b) {
3374
+ if (!utils$1.isUndefined(b)) {
3375
+ return getMergedValue(undefined, b);
3376
+ } else if (!utils$1.isUndefined(a)) {
3377
+ return getMergedValue(undefined, a);
3378
+ }
3379
+ }
3380
+
3381
+ // eslint-disable-next-line consistent-return
3382
+ function mergeDirectKeys(a, b, prop) {
3383
+ if (prop in config2) {
3384
+ return getMergedValue(a, b);
3385
+ } else if (prop in config1) {
3386
+ return getMergedValue(undefined, a);
3387
+ }
3388
+ }
3389
+
3390
+ const mergeMap = {
3391
+ url: valueFromConfig2,
3392
+ method: valueFromConfig2,
3393
+ data: valueFromConfig2,
3394
+ baseURL: defaultToConfig2,
3395
+ transformRequest: defaultToConfig2,
3396
+ transformResponse: defaultToConfig2,
3397
+ paramsSerializer: defaultToConfig2,
3398
+ timeout: defaultToConfig2,
3399
+ timeoutMessage: defaultToConfig2,
3400
+ withCredentials: defaultToConfig2,
3401
+ withXSRFToken: defaultToConfig2,
3402
+ adapter: defaultToConfig2,
3403
+ responseType: defaultToConfig2,
3404
+ xsrfCookieName: defaultToConfig2,
3405
+ xsrfHeaderName: defaultToConfig2,
3406
+ onUploadProgress: defaultToConfig2,
3407
+ onDownloadProgress: defaultToConfig2,
3408
+ decompress: defaultToConfig2,
3409
+ maxContentLength: defaultToConfig2,
3410
+ maxBodyLength: defaultToConfig2,
3411
+ beforeRedirect: defaultToConfig2,
3412
+ transport: defaultToConfig2,
3413
+ httpAgent: defaultToConfig2,
3414
+ httpsAgent: defaultToConfig2,
3415
+ cancelToken: defaultToConfig2,
3416
+ socketPath: defaultToConfig2,
3417
+ responseEncoding: defaultToConfig2,
3418
+ validateStatus: mergeDirectKeys,
3419
+ headers: (a, b) => mergeDeepProperties(headersToObject(a), headersToObject(b), true)
3289
3420
  };
3421
+
3422
+ utils$1.forEach(Object.keys(Object.assign({}, config1, config2)), function computeConfigValue(prop) {
3423
+ const merge = mergeMap[prop] || mergeDeepProperties;
3424
+ const configValue = merge(config1[prop], config2[prop], prop);
3425
+ (utils$1.isUndefined(configValue) && merge !== mergeDirectKeys) || (config[prop] = configValue);
3426
+ });
3427
+
3428
+ return config;
3290
3429
  }
3291
3430
 
3292
- const isXHRAdapterSupported = typeof XMLHttpRequest !== 'undefined';
3431
+ const resolveConfig = (config) => {
3432
+ const newConfig = mergeConfig({}, config);
3293
3433
 
3294
- const xhrAdapter = isXHRAdapterSupported && function (config) {
3295
- return new Promise(function dispatchXhrRequest(resolve, reject) {
3296
- let requestData = config.data;
3297
- const requestHeaders = AxiosHeaders$1.from(config.headers).normalize();
3298
- let {responseType, withXSRFToken} = config;
3299
- let onCanceled;
3300
- function done() {
3301
- if (config.cancelToken) {
3302
- config.cancelToken.unsubscribe(onCanceled);
3303
- }
3434
+ let {data, withXSRFToken, xsrfHeaderName, xsrfCookieName, headers, auth} = newConfig;
3304
3435
 
3305
- if (config.signal) {
3306
- config.signal.removeEventListener('abort', onCanceled);
3307
- }
3436
+ newConfig.headers = headers = AxiosHeaders$1.from(headers);
3437
+
3438
+ newConfig.url = buildURL(buildFullPath(newConfig.baseURL, newConfig.url), config.params, config.paramsSerializer);
3439
+
3440
+ // HTTP basic authentication
3441
+ if (auth) {
3442
+ headers.set('Authorization', 'Basic ' +
3443
+ btoa((auth.username || '') + ':' + (auth.password ? unescape(encodeURIComponent(auth.password)) : ''))
3444
+ );
3445
+ }
3446
+
3447
+ let contentType;
3448
+
3449
+ if (utils$1.isFormData(data)) {
3450
+ if (platform.hasStandardBrowserEnv || platform.hasStandardBrowserWebWorkerEnv) {
3451
+ headers.setContentType(undefined); // Let the browser set it
3452
+ } else if ((contentType = headers.getContentType()) !== false) {
3453
+ // fix semicolon duplication issue for ReactNative FormData implementation
3454
+ const [type, ...tokens] = contentType ? contentType.split(';').map(token => token.trim()).filter(Boolean) : [];
3455
+ headers.setContentType([type || 'multipart/form-data', ...tokens].join('; '));
3308
3456
  }
3457
+ }
3458
+
3459
+ // Add xsrf header
3460
+ // This is only done if running in a standard browser environment.
3461
+ // Specifically not if we're in a web worker, or react-native.
3462
+
3463
+ if (platform.hasStandardBrowserEnv) {
3464
+ withXSRFToken && utils$1.isFunction(withXSRFToken) && (withXSRFToken = withXSRFToken(newConfig));
3309
3465
 
3310
- let contentType;
3466
+ if (withXSRFToken || (withXSRFToken !== false && isURLSameOrigin(newConfig.url))) {
3467
+ // Add xsrf header
3468
+ const xsrfValue = xsrfHeaderName && xsrfCookieName && cookies.read(xsrfCookieName);
3311
3469
 
3312
- if (utils$1.isFormData(requestData)) {
3313
- if (platform.hasStandardBrowserEnv || platform.hasStandardBrowserWebWorkerEnv) {
3314
- requestHeaders.setContentType(false); // Let the browser set it
3315
- } else if ((contentType = requestHeaders.getContentType()) !== false) {
3316
- // fix semicolon duplication issue for ReactNative FormData implementation
3317
- const [type, ...tokens] = contentType ? contentType.split(';').map(token => token.trim()).filter(Boolean) : [];
3318
- requestHeaders.setContentType([type || 'multipart/form-data', ...tokens].join('; '));
3470
+ if (xsrfValue) {
3471
+ headers.set(xsrfHeaderName, xsrfValue);
3319
3472
  }
3320
3473
  }
3474
+ }
3321
3475
 
3322
- let request = new XMLHttpRequest();
3476
+ return newConfig;
3477
+ };
3323
3478
 
3324
- // HTTP basic authentication
3325
- if (config.auth) {
3326
- const username = config.auth.username || '';
3327
- const password = config.auth.password ? unescape(encodeURIComponent(config.auth.password)) : '';
3328
- requestHeaders.set('Authorization', 'Basic ' + btoa(username + ':' + password));
3479
+ const isXHRAdapterSupported = typeof XMLHttpRequest !== 'undefined';
3480
+
3481
+ const xhrAdapter = isXHRAdapterSupported && function (config) {
3482
+ return new Promise(function dispatchXhrRequest(resolve, reject) {
3483
+ const _config = resolveConfig(config);
3484
+ let requestData = _config.data;
3485
+ const requestHeaders = AxiosHeaders$1.from(_config.headers).normalize();
3486
+ let {responseType, onUploadProgress, onDownloadProgress} = _config;
3487
+ let onCanceled;
3488
+ let uploadThrottled, downloadThrottled;
3489
+ let flushUpload, flushDownload;
3490
+
3491
+ function done() {
3492
+ flushUpload && flushUpload(); // flush events
3493
+ flushDownload && flushDownload(); // flush events
3494
+
3495
+ _config.cancelToken && _config.cancelToken.unsubscribe(onCanceled);
3496
+
3497
+ _config.signal && _config.signal.removeEventListener('abort', onCanceled);
3329
3498
  }
3330
3499
 
3331
- const fullPath = buildFullPath(config.baseURL, config.url);
3500
+ let request = new XMLHttpRequest();
3332
3501
 
3333
- request.open(config.method.toUpperCase(), buildURL(fullPath, config.params, config.paramsSerializer), true);
3502
+ request.open(_config.method.toUpperCase(), _config.url, true);
3334
3503
 
3335
3504
  // Set the request timeout in MS
3336
- request.timeout = config.timeout;
3505
+ request.timeout = _config.timeout;
3337
3506
 
3338
3507
  function onloadend() {
3339
3508
  if (!request) {
@@ -3413,10 +3582,10 @@ const xhrAdapter = isXHRAdapterSupported && function (config) {
3413
3582
 
3414
3583
  // Handle timeout
3415
3584
  request.ontimeout = function handleTimeout() {
3416
- let timeoutErrorMessage = config.timeout ? 'timeout of ' + config.timeout + 'ms exceeded' : 'timeout exceeded';
3417
- const transitional = config.transitional || transitionalDefaults;
3418
- if (config.timeoutErrorMessage) {
3419
- timeoutErrorMessage = config.timeoutErrorMessage;
3585
+ let timeoutErrorMessage = _config.timeout ? 'timeout of ' + _config.timeout + 'ms exceeded' : 'timeout exceeded';
3586
+ const transitional = _config.transitional || transitionalDefaults;
3587
+ if (_config.timeoutErrorMessage) {
3588
+ timeoutErrorMessage = _config.timeoutErrorMessage;
3420
3589
  }
3421
3590
  reject(new AxiosError(
3422
3591
  timeoutErrorMessage,
@@ -3428,22 +3597,6 @@ const xhrAdapter = isXHRAdapterSupported && function (config) {
3428
3597
  request = null;
3429
3598
  };
3430
3599
 
3431
- // Add xsrf header
3432
- // This is only done if running in a standard browser environment.
3433
- // Specifically not if we're in a web worker, or react-native.
3434
- if(platform.hasStandardBrowserEnv) {
3435
- withXSRFToken && utils$1.isFunction(withXSRFToken) && (withXSRFToken = withXSRFToken(config));
3436
-
3437
- if (withXSRFToken || (withXSRFToken !== false && isURLSameOrigin(fullPath))) {
3438
- // Add xsrf header
3439
- const xsrfValue = config.xsrfHeaderName && config.xsrfCookieName && cookies.read(config.xsrfCookieName);
3440
-
3441
- if (xsrfValue) {
3442
- requestHeaders.set(config.xsrfHeaderName, xsrfValue);
3443
- }
3444
- }
3445
- }
3446
-
3447
3600
  // Remove Content-Type if data is undefined
3448
3601
  requestData === undefined && requestHeaders.setContentType(null);
3449
3602
 
@@ -3455,26 +3608,31 @@ const xhrAdapter = isXHRAdapterSupported && function (config) {
3455
3608
  }
3456
3609
 
3457
3610
  // Add withCredentials to request if needed
3458
- if (!utils$1.isUndefined(config.withCredentials)) {
3459
- request.withCredentials = !!config.withCredentials;
3611
+ if (!utils$1.isUndefined(_config.withCredentials)) {
3612
+ request.withCredentials = !!_config.withCredentials;
3460
3613
  }
3461
3614
 
3462
3615
  // Add responseType to request if needed
3463
3616
  if (responseType && responseType !== 'json') {
3464
- request.responseType = config.responseType;
3617
+ request.responseType = _config.responseType;
3465
3618
  }
3466
3619
 
3467
3620
  // Handle progress if needed
3468
- if (typeof config.onDownloadProgress === 'function') {
3469
- request.addEventListener('progress', progressEventReducer(config.onDownloadProgress, true));
3621
+ if (onDownloadProgress) {
3622
+ ([downloadThrottled, flushDownload] = progressEventReducer(onDownloadProgress, true));
3623
+ request.addEventListener('progress', downloadThrottled);
3470
3624
  }
3471
3625
 
3472
3626
  // Not all browsers support upload events
3473
- if (typeof config.onUploadProgress === 'function' && request.upload) {
3474
- request.upload.addEventListener('progress', progressEventReducer(config.onUploadProgress));
3627
+ if (onUploadProgress && request.upload) {
3628
+ ([uploadThrottled, flushUpload] = progressEventReducer(onUploadProgress));
3629
+
3630
+ request.upload.addEventListener('progress', uploadThrottled);
3631
+
3632
+ request.upload.addEventListener('loadend', flushUpload);
3475
3633
  }
3476
3634
 
3477
- if (config.cancelToken || config.signal) {
3635
+ if (_config.cancelToken || _config.signal) {
3478
3636
  // Handle cancellation
3479
3637
  // eslint-disable-next-line func-names
3480
3638
  onCanceled = cancel => {
@@ -3486,13 +3644,13 @@ const xhrAdapter = isXHRAdapterSupported && function (config) {
3486
3644
  request = null;
3487
3645
  };
3488
3646
 
3489
- config.cancelToken && config.cancelToken.subscribe(onCanceled);
3490
- if (config.signal) {
3491
- config.signal.aborted ? onCanceled() : config.signal.addEventListener('abort', onCanceled);
3647
+ _config.cancelToken && _config.cancelToken.subscribe(onCanceled);
3648
+ if (_config.signal) {
3649
+ _config.signal.aborted ? onCanceled() : _config.signal.addEventListener('abort', onCanceled);
3492
3650
  }
3493
3651
  }
3494
3652
 
3495
- const protocol = parseProtocol(fullPath);
3653
+ const protocol = parseProtocol(_config.url);
3496
3654
 
3497
3655
  if (protocol && platform.protocols.indexOf(protocol) === -1) {
3498
3656
  reject(new AxiosError('Unsupported protocol ' + protocol + ':', AxiosError.ERR_BAD_REQUEST, config));
@@ -3505,9 +3663,339 @@ const xhrAdapter = isXHRAdapterSupported && function (config) {
3505
3663
  });
3506
3664
  };
3507
3665
 
3666
+ const composeSignals = (signals, timeout) => {
3667
+ let controller = new AbortController();
3668
+
3669
+ let aborted;
3670
+
3671
+ const onabort = function (cancel) {
3672
+ if (!aborted) {
3673
+ aborted = true;
3674
+ unsubscribe();
3675
+ const err = cancel instanceof Error ? cancel : this.reason;
3676
+ controller.abort(err instanceof AxiosError ? err : new CanceledError(err instanceof Error ? err.message : err));
3677
+ }
3678
+ };
3679
+
3680
+ let timer = timeout && setTimeout(() => {
3681
+ onabort(new AxiosError(`timeout ${timeout} of ms exceeded`, AxiosError.ETIMEDOUT));
3682
+ }, timeout);
3683
+
3684
+ const unsubscribe = () => {
3685
+ if (signals) {
3686
+ timer && clearTimeout(timer);
3687
+ timer = null;
3688
+ signals.forEach(signal => {
3689
+ signal &&
3690
+ (signal.removeEventListener ? signal.removeEventListener('abort', onabort) : signal.unsubscribe(onabort));
3691
+ });
3692
+ signals = null;
3693
+ }
3694
+ };
3695
+
3696
+ signals.forEach((signal) => signal && signal.addEventListener && signal.addEventListener('abort', onabort));
3697
+
3698
+ const {signal} = controller;
3699
+
3700
+ signal.unsubscribe = unsubscribe;
3701
+
3702
+ return [signal, () => {
3703
+ timer && clearTimeout(timer);
3704
+ timer = null;
3705
+ }];
3706
+ };
3707
+
3708
+ const composeSignals$1 = composeSignals;
3709
+
3710
+ const streamChunk = function* (chunk, chunkSize) {
3711
+ let len = chunk.byteLength;
3712
+
3713
+ if (!chunkSize || len < chunkSize) {
3714
+ yield chunk;
3715
+ return;
3716
+ }
3717
+
3718
+ let pos = 0;
3719
+ let end;
3720
+
3721
+ while (pos < len) {
3722
+ end = pos + chunkSize;
3723
+ yield chunk.slice(pos, end);
3724
+ pos = end;
3725
+ }
3726
+ };
3727
+
3728
+ const readBytes = async function* (iterable, chunkSize, encode) {
3729
+ for await (const chunk of iterable) {
3730
+ yield* streamChunk(ArrayBuffer.isView(chunk) ? chunk : (await encode(String(chunk))), chunkSize);
3731
+ }
3732
+ };
3733
+
3734
+ const trackStream = (stream, chunkSize, onProgress, onFinish, encode) => {
3735
+ const iterator = readBytes(stream, chunkSize, encode);
3736
+
3737
+ let bytes = 0;
3738
+ let done;
3739
+ let _onFinish = (e) => {
3740
+ if (!done) {
3741
+ done = true;
3742
+ onFinish && onFinish(e);
3743
+ }
3744
+ };
3745
+
3746
+ return new ReadableStream({
3747
+ async pull(controller) {
3748
+ try {
3749
+ const {done, value} = await iterator.next();
3750
+
3751
+ if (done) {
3752
+ _onFinish();
3753
+ controller.close();
3754
+ return;
3755
+ }
3756
+
3757
+ let len = value.byteLength;
3758
+ if (onProgress) {
3759
+ let loadedBytes = bytes += len;
3760
+ onProgress(loadedBytes);
3761
+ }
3762
+ controller.enqueue(new Uint8Array(value));
3763
+ } catch (err) {
3764
+ _onFinish(err);
3765
+ throw err;
3766
+ }
3767
+ },
3768
+ cancel(reason) {
3769
+ _onFinish(reason);
3770
+ return iterator.return();
3771
+ }
3772
+ }, {
3773
+ highWaterMark: 2
3774
+ })
3775
+ };
3776
+
3777
+ const isFetchSupported = typeof fetch === 'function' && typeof Request === 'function' && typeof Response === 'function';
3778
+ const isReadableStreamSupported = isFetchSupported && typeof ReadableStream === 'function';
3779
+
3780
+ // used only inside the fetch adapter
3781
+ const encodeText = isFetchSupported && (typeof TextEncoder === 'function' ?
3782
+ ((encoder) => (str) => encoder.encode(str))(new TextEncoder()) :
3783
+ async (str) => new Uint8Array(await new Response(str).arrayBuffer())
3784
+ );
3785
+
3786
+ const test = (fn, ...args) => {
3787
+ try {
3788
+ return !!fn(...args);
3789
+ } catch (e) {
3790
+ return false
3791
+ }
3792
+ };
3793
+
3794
+ const supportsRequestStream = isReadableStreamSupported && test(() => {
3795
+ let duplexAccessed = false;
3796
+
3797
+ const hasContentType = new Request(platform.origin, {
3798
+ body: new ReadableStream(),
3799
+ method: 'POST',
3800
+ get duplex() {
3801
+ duplexAccessed = true;
3802
+ return 'half';
3803
+ },
3804
+ }).headers.has('Content-Type');
3805
+
3806
+ return duplexAccessed && !hasContentType;
3807
+ });
3808
+
3809
+ const DEFAULT_CHUNK_SIZE = 64 * 1024;
3810
+
3811
+ const supportsResponseStream = isReadableStreamSupported &&
3812
+ test(() => utils$1.isReadableStream(new Response('').body));
3813
+
3814
+
3815
+ const resolvers = {
3816
+ stream: supportsResponseStream && ((res) => res.body)
3817
+ };
3818
+
3819
+ isFetchSupported && (((res) => {
3820
+ ['text', 'arrayBuffer', 'blob', 'formData', 'stream'].forEach(type => {
3821
+ !resolvers[type] && (resolvers[type] = utils$1.isFunction(res[type]) ? (res) => res[type]() :
3822
+ (_, config) => {
3823
+ throw new AxiosError(`Response type '${type}' is not supported`, AxiosError.ERR_NOT_SUPPORT, config);
3824
+ });
3825
+ });
3826
+ })(new Response));
3827
+
3828
+ const getBodyLength = async (body) => {
3829
+ if (body == null) {
3830
+ return 0;
3831
+ }
3832
+
3833
+ if(utils$1.isBlob(body)) {
3834
+ return body.size;
3835
+ }
3836
+
3837
+ if(utils$1.isSpecCompliantForm(body)) {
3838
+ return (await new Request(body).arrayBuffer()).byteLength;
3839
+ }
3840
+
3841
+ if(utils$1.isArrayBufferView(body) || utils$1.isArrayBuffer(body)) {
3842
+ return body.byteLength;
3843
+ }
3844
+
3845
+ if(utils$1.isURLSearchParams(body)) {
3846
+ body = body + '';
3847
+ }
3848
+
3849
+ if(utils$1.isString(body)) {
3850
+ return (await encodeText(body)).byteLength;
3851
+ }
3852
+ };
3853
+
3854
+ const resolveBodyLength = async (headers, body) => {
3855
+ const length = utils$1.toFiniteNumber(headers.getContentLength());
3856
+
3857
+ return length == null ? getBodyLength(body) : length;
3858
+ };
3859
+
3860
+ const fetchAdapter = isFetchSupported && (async (config) => {
3861
+ let {
3862
+ url,
3863
+ method,
3864
+ data,
3865
+ signal,
3866
+ cancelToken,
3867
+ timeout,
3868
+ onDownloadProgress,
3869
+ onUploadProgress,
3870
+ responseType,
3871
+ headers,
3872
+ withCredentials = 'same-origin',
3873
+ fetchOptions
3874
+ } = resolveConfig(config);
3875
+
3876
+ responseType = responseType ? (responseType + '').toLowerCase() : 'text';
3877
+
3878
+ let [composedSignal, stopTimeout] = (signal || cancelToken || timeout) ?
3879
+ composeSignals$1([signal, cancelToken], timeout) : [];
3880
+
3881
+ let finished, request;
3882
+
3883
+ const onFinish = () => {
3884
+ !finished && setTimeout(() => {
3885
+ composedSignal && composedSignal.unsubscribe();
3886
+ });
3887
+
3888
+ finished = true;
3889
+ };
3890
+
3891
+ let requestContentLength;
3892
+
3893
+ try {
3894
+ if (
3895
+ onUploadProgress && supportsRequestStream && method !== 'get' && method !== 'head' &&
3896
+ (requestContentLength = await resolveBodyLength(headers, data)) !== 0
3897
+ ) {
3898
+ let _request = new Request(url, {
3899
+ method: 'POST',
3900
+ body: data,
3901
+ duplex: "half"
3902
+ });
3903
+
3904
+ let contentTypeHeader;
3905
+
3906
+ if (utils$1.isFormData(data) && (contentTypeHeader = _request.headers.get('content-type'))) {
3907
+ headers.setContentType(contentTypeHeader);
3908
+ }
3909
+
3910
+ if (_request.body) {
3911
+ const [onProgress, flush] = progressEventDecorator(
3912
+ requestContentLength,
3913
+ progressEventReducer(asyncDecorator(onUploadProgress))
3914
+ );
3915
+
3916
+ data = trackStream(_request.body, DEFAULT_CHUNK_SIZE, onProgress, flush, encodeText);
3917
+ }
3918
+ }
3919
+
3920
+ if (!utils$1.isString(withCredentials)) {
3921
+ withCredentials = withCredentials ? 'include' : 'omit';
3922
+ }
3923
+
3924
+ request = new Request(url, {
3925
+ ...fetchOptions,
3926
+ signal: composedSignal,
3927
+ method: method.toUpperCase(),
3928
+ headers: headers.normalize().toJSON(),
3929
+ body: data,
3930
+ duplex: "half",
3931
+ credentials: withCredentials
3932
+ });
3933
+
3934
+ let response = await fetch(request);
3935
+
3936
+ const isStreamResponse = supportsResponseStream && (responseType === 'stream' || responseType === 'response');
3937
+
3938
+ if (supportsResponseStream && (onDownloadProgress || isStreamResponse)) {
3939
+ const options = {};
3940
+
3941
+ ['status', 'statusText', 'headers'].forEach(prop => {
3942
+ options[prop] = response[prop];
3943
+ });
3944
+
3945
+ const responseContentLength = utils$1.toFiniteNumber(response.headers.get('content-length'));
3946
+
3947
+ const [onProgress, flush] = onDownloadProgress && progressEventDecorator(
3948
+ responseContentLength,
3949
+ progressEventReducer(asyncDecorator(onDownloadProgress), true)
3950
+ ) || [];
3951
+
3952
+ response = new Response(
3953
+ trackStream(response.body, DEFAULT_CHUNK_SIZE, onProgress, () => {
3954
+ flush && flush();
3955
+ isStreamResponse && onFinish();
3956
+ }, encodeText),
3957
+ options
3958
+ );
3959
+ }
3960
+
3961
+ responseType = responseType || 'text';
3962
+
3963
+ let responseData = await resolvers[utils$1.findKey(resolvers, responseType) || 'text'](response, config);
3964
+
3965
+ !isStreamResponse && onFinish();
3966
+
3967
+ stopTimeout && stopTimeout();
3968
+
3969
+ return await new Promise((resolve, reject) => {
3970
+ settle(resolve, reject, {
3971
+ data: responseData,
3972
+ headers: AxiosHeaders$1.from(response.headers),
3973
+ status: response.status,
3974
+ statusText: response.statusText,
3975
+ config,
3976
+ request
3977
+ });
3978
+ })
3979
+ } catch (err) {
3980
+ onFinish();
3981
+
3982
+ if (err && err.name === 'TypeError' && /fetch/i.test(err.message)) {
3983
+ throw Object.assign(
3984
+ new AxiosError('Network Error', AxiosError.ERR_NETWORK, config, request),
3985
+ {
3986
+ cause: err.cause || err
3987
+ }
3988
+ )
3989
+ }
3990
+
3991
+ throw AxiosError.from(err, err && err.code, config, request);
3992
+ }
3993
+ });
3994
+
3508
3995
  const knownAdapters = {
3509
3996
  http: httpAdapter,
3510
- xhr: xhrAdapter
3997
+ xhr: xhrAdapter,
3998
+ fetch: fetchAdapter
3511
3999
  };
3512
4000
 
3513
4001
  utils$1.forEach(knownAdapters, (fn, value) => {
@@ -3651,108 +4139,6 @@ function dispatchRequest(config) {
3651
4139
  });
3652
4140
  }
3653
4141
 
3654
- const headersToObject = (thing) => thing instanceof AxiosHeaders$1 ? { ...thing } : thing;
3655
-
3656
- /**
3657
- * Config-specific merge-function which creates a new config-object
3658
- * by merging two configuration objects together.
3659
- *
3660
- * @param {Object} config1
3661
- * @param {Object} config2
3662
- *
3663
- * @returns {Object} New object resulting from merging config2 to config1
3664
- */
3665
- function mergeConfig(config1, config2) {
3666
- // eslint-disable-next-line no-param-reassign
3667
- config2 = config2 || {};
3668
- const config = {};
3669
-
3670
- function getMergedValue(target, source, caseless) {
3671
- if (utils$1.isPlainObject(target) && utils$1.isPlainObject(source)) {
3672
- return utils$1.merge.call({caseless}, target, source);
3673
- } else if (utils$1.isPlainObject(source)) {
3674
- return utils$1.merge({}, source);
3675
- } else if (utils$1.isArray(source)) {
3676
- return source.slice();
3677
- }
3678
- return source;
3679
- }
3680
-
3681
- // eslint-disable-next-line consistent-return
3682
- function mergeDeepProperties(a, b, caseless) {
3683
- if (!utils$1.isUndefined(b)) {
3684
- return getMergedValue(a, b, caseless);
3685
- } else if (!utils$1.isUndefined(a)) {
3686
- return getMergedValue(undefined, a, caseless);
3687
- }
3688
- }
3689
-
3690
- // eslint-disable-next-line consistent-return
3691
- function valueFromConfig2(a, b) {
3692
- if (!utils$1.isUndefined(b)) {
3693
- return getMergedValue(undefined, b);
3694
- }
3695
- }
3696
-
3697
- // eslint-disable-next-line consistent-return
3698
- function defaultToConfig2(a, b) {
3699
- if (!utils$1.isUndefined(b)) {
3700
- return getMergedValue(undefined, b);
3701
- } else if (!utils$1.isUndefined(a)) {
3702
- return getMergedValue(undefined, a);
3703
- }
3704
- }
3705
-
3706
- // eslint-disable-next-line consistent-return
3707
- function mergeDirectKeys(a, b, prop) {
3708
- if (prop in config2) {
3709
- return getMergedValue(a, b);
3710
- } else if (prop in config1) {
3711
- return getMergedValue(undefined, a);
3712
- }
3713
- }
3714
-
3715
- const mergeMap = {
3716
- url: valueFromConfig2,
3717
- method: valueFromConfig2,
3718
- data: valueFromConfig2,
3719
- baseURL: defaultToConfig2,
3720
- transformRequest: defaultToConfig2,
3721
- transformResponse: defaultToConfig2,
3722
- paramsSerializer: defaultToConfig2,
3723
- timeout: defaultToConfig2,
3724
- timeoutMessage: defaultToConfig2,
3725
- withCredentials: defaultToConfig2,
3726
- withXSRFToken: defaultToConfig2,
3727
- adapter: defaultToConfig2,
3728
- responseType: defaultToConfig2,
3729
- xsrfCookieName: defaultToConfig2,
3730
- xsrfHeaderName: defaultToConfig2,
3731
- onUploadProgress: defaultToConfig2,
3732
- onDownloadProgress: defaultToConfig2,
3733
- decompress: defaultToConfig2,
3734
- maxContentLength: defaultToConfig2,
3735
- maxBodyLength: defaultToConfig2,
3736
- beforeRedirect: defaultToConfig2,
3737
- transport: defaultToConfig2,
3738
- httpAgent: defaultToConfig2,
3739
- httpsAgent: defaultToConfig2,
3740
- cancelToken: defaultToConfig2,
3741
- socketPath: defaultToConfig2,
3742
- responseEncoding: defaultToConfig2,
3743
- validateStatus: mergeDirectKeys,
3744
- headers: (a, b) => mergeDeepProperties(headersToObject(a), headersToObject(b), true)
3745
- };
3746
-
3747
- utils$1.forEach(Object.keys(Object.assign({}, config1, config2)), function computeConfigValue(prop) {
3748
- const merge = mergeMap[prop] || mergeDeepProperties;
3749
- const configValue = merge(config1[prop], config2[prop], prop);
3750
- (utils$1.isUndefined(configValue) && merge !== mergeDirectKeys) || (config[prop] = configValue);
3751
- });
3752
-
3753
- return config;
3754
- }
3755
-
3756
4142
  const validators$1 = {};
3757
4143
 
3758
4144
  // eslint-disable-next-line func-names
@@ -3877,12 +4263,15 @@ class Axios {
3877
4263
 
3878
4264
  // slice off the Error: ... line
3879
4265
  const stack = dummy.stack ? dummy.stack.replace(/^.+\n/, '') : '';
3880
-
3881
- if (!err.stack) {
3882
- err.stack = stack;
3883
- // match without the 2 top stack lines
3884
- } else if (stack && !String(err.stack).endsWith(stack.replace(/^.+\n.+\n/, ''))) {
3885
- err.stack += '\n' + stack;
4266
+ try {
4267
+ if (!err.stack) {
4268
+ err.stack = stack;
4269
+ // match without the 2 top stack lines
4270
+ } else if (stack && !String(err.stack).endsWith(stack.replace(/^.+\n.+\n/, ''))) {
4271
+ err.stack += '\n' + stack;
4272
+ }
4273
+ } catch (e) {
4274
+ // ignore the case where "stack" is an un-writable property
3886
4275
  }
3887
4276
  }
3888
4277