enterprise-fetch 1.0.1 → 2.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,612 +1,608 @@
1
1
  (function (global, factory) {
2
- typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports, require('cross-fetch')) :
3
- typeof define === 'function' && define.amd ? define(['exports', 'cross-fetch'], factory) :
4
- (global = typeof globalThis !== 'undefined' ? globalThis : global || self, factory(global['enterprise-fetch'] = {}, global.fetch));
5
- }(this, (function (exports, fetch) { 'use strict';
6
-
7
- function _interopDefaultLegacy (e) { return e && typeof e === 'object' && 'default' in e ? e : { 'default': e }; }
8
-
9
- var fetch__default = /*#__PURE__*/_interopDefaultLegacy(fetch);
10
-
11
- function _defineProperty(obj, key, value) {
12
- if (key in obj) {
13
- Object.defineProperty(obj, key, {
14
- value: value,
15
- enumerable: true,
16
- configurable: true,
17
- writable: true
18
- });
19
- } else {
20
- obj[key] = value;
21
- }
22
-
23
- return obj;
24
- }
25
-
26
- function ownKeys(object, enumerableOnly) {
27
- var keys = Object.keys(object);
28
-
29
- if (Object.getOwnPropertySymbols) {
30
- var symbols = Object.getOwnPropertySymbols(object);
31
- if (enumerableOnly) symbols = symbols.filter(function (sym) {
32
- return Object.getOwnPropertyDescriptor(object, sym).enumerable;
33
- });
34
- keys.push.apply(keys, symbols);
35
- }
36
-
37
- return keys;
38
- }
39
-
40
- function _objectSpread2(target) {
41
- for (var i = 1; i < arguments.length; i++) {
42
- var source = arguments[i] != null ? arguments[i] : {};
43
-
44
- if (i % 2) {
45
- ownKeys(Object(source), true).forEach(function (key) {
46
- _defineProperty(target, key, source[key]);
47
- });
48
- } else if (Object.getOwnPropertyDescriptors) {
49
- Object.defineProperties(target, Object.getOwnPropertyDescriptors(source));
50
- } else {
51
- ownKeys(Object(source)).forEach(function (key) {
52
- Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key));
53
- });
54
- }
55
- }
56
-
57
- return target;
58
- }
59
-
60
- function _objectWithoutPropertiesLoose(source, excluded) {
61
- if (source == null) return {};
62
- var target = {};
63
- var sourceKeys = Object.keys(source);
64
- var key, i;
65
-
66
- for (i = 0; i < sourceKeys.length; i++) {
67
- key = sourceKeys[i];
68
- if (excluded.indexOf(key) >= 0) continue;
69
- target[key] = source[key];
70
- }
71
-
72
- return target;
73
- }
74
-
75
- function _objectWithoutProperties(source, excluded) {
76
- if (source == null) return {};
77
-
78
- var target = _objectWithoutPropertiesLoose(source, excluded);
79
-
80
- var key, i;
81
-
82
- if (Object.getOwnPropertySymbols) {
83
- var sourceSymbolKeys = Object.getOwnPropertySymbols(source);
84
-
85
- for (i = 0; i < sourceSymbolKeys.length; i++) {
86
- key = sourceSymbolKeys[i];
87
- if (excluded.indexOf(key) >= 0) continue;
88
- if (!Object.prototype.propertyIsEnumerable.call(source, key)) continue;
89
- target[key] = source[key];
90
- }
91
- }
92
-
93
- return target;
94
- }
95
-
96
- function assign(obj, props) {
97
- for (const key in props) {
98
- Object.defineProperty(obj, key, {
99
- value: props[key],
100
- enumerable: true,
101
- configurable: true,
102
- });
103
- }
104
-
105
- return obj;
106
- }
107
-
108
- function createError(err, code, props) {
109
- if (!err || typeof err === 'string') {
110
- throw new TypeError('Please pass an Error to err-code');
111
- }
112
-
113
- if (!props) {
114
- props = {};
115
- }
116
-
117
- if (typeof code === 'object') {
118
- props = code;
119
- code = undefined;
120
- }
121
-
122
- if (code != null) {
123
- props.code = code;
124
- }
125
-
126
- try {
127
- return assign(err, props);
128
- } catch (_) {
129
- props.message = err.message;
130
- props.stack = err.stack;
131
-
132
- const ErrClass = function () {};
133
-
134
- ErrClass.prototype = Object.create(Object.getPrototypeOf(err));
135
-
136
- return assign(new ErrClass(), props);
137
- }
138
- }
139
-
140
- var errCode = createError;
141
-
142
- function createCommonjsModule(fn) {
143
- var module = { exports: {} };
144
- return fn(module, module.exports), module.exports;
145
- }
146
-
147
- function RetryOperation(timeouts, options) {
148
- // Compatibility for the old (timeouts, retryForever) signature
149
- if (typeof options === 'boolean') {
150
- options = { forever: options };
151
- }
152
-
153
- this._originalTimeouts = JSON.parse(JSON.stringify(timeouts));
154
- this._timeouts = timeouts;
155
- this._options = options || {};
156
- this._maxRetryTime = options && options.maxRetryTime || Infinity;
157
- this._fn = null;
158
- this._errors = [];
159
- this._attempts = 1;
160
- this._operationTimeout = null;
161
- this._operationTimeoutCb = null;
162
- this._timeout = null;
163
- this._operationStart = null;
164
-
165
- if (this._options.forever) {
166
- this._cachedTimeouts = this._timeouts.slice(0);
167
- }
168
- }
169
- var retry_operation = RetryOperation;
170
-
171
- RetryOperation.prototype.reset = function() {
172
- this._attempts = 1;
173
- this._timeouts = this._originalTimeouts;
174
- };
175
-
176
- RetryOperation.prototype.stop = function() {
177
- if (this._timeout) {
178
- clearTimeout(this._timeout);
179
- }
180
-
181
- this._timeouts = [];
182
- this._cachedTimeouts = null;
183
- };
184
-
185
- RetryOperation.prototype.retry = function(err) {
186
- if (this._timeout) {
187
- clearTimeout(this._timeout);
188
- }
189
-
190
- if (!err) {
191
- return false;
192
- }
193
- var currentTime = new Date().getTime();
194
- if (err && currentTime - this._operationStart >= this._maxRetryTime) {
195
- this._errors.unshift(new Error('RetryOperation timeout occurred'));
196
- return false;
197
- }
198
-
199
- this._errors.push(err);
200
-
201
- var timeout = this._timeouts.shift();
202
- if (timeout === undefined) {
203
- if (this._cachedTimeouts) {
204
- // retry forever, only keep last error
205
- this._errors.splice(this._errors.length - 1, this._errors.length);
206
- this._timeouts = this._cachedTimeouts.slice(0);
207
- timeout = this._timeouts.shift();
208
- } else {
209
- return false;
210
- }
211
- }
212
-
213
- var self = this;
214
- var timer = setTimeout(function() {
215
- self._attempts++;
216
-
217
- if (self._operationTimeoutCb) {
218
- self._timeout = setTimeout(function() {
219
- self._operationTimeoutCb(self._attempts);
220
- }, self._operationTimeout);
221
-
222
- if (self._options.unref) {
223
- self._timeout.unref();
224
- }
225
- }
226
-
227
- self._fn(self._attempts);
228
- }, timeout);
229
-
230
- if (this._options.unref) {
231
- timer.unref();
232
- }
233
-
234
- return true;
235
- };
236
-
237
- RetryOperation.prototype.attempt = function(fn, timeoutOps) {
238
- this._fn = fn;
239
-
240
- if (timeoutOps) {
241
- if (timeoutOps.timeout) {
242
- this._operationTimeout = timeoutOps.timeout;
243
- }
244
- if (timeoutOps.cb) {
245
- this._operationTimeoutCb = timeoutOps.cb;
246
- }
247
- }
248
-
249
- var self = this;
250
- if (this._operationTimeoutCb) {
251
- this._timeout = setTimeout(function() {
252
- self._operationTimeoutCb();
253
- }, self._operationTimeout);
254
- }
255
-
256
- this._operationStart = new Date().getTime();
257
-
258
- this._fn(this._attempts);
259
- };
260
-
261
- RetryOperation.prototype.try = function(fn) {
262
- console.log('Using RetryOperation.try() is deprecated');
263
- this.attempt(fn);
264
- };
265
-
266
- RetryOperation.prototype.start = function(fn) {
267
- console.log('Using RetryOperation.start() is deprecated');
268
- this.attempt(fn);
269
- };
270
-
271
- RetryOperation.prototype.start = RetryOperation.prototype.try;
272
-
273
- RetryOperation.prototype.errors = function() {
274
- return this._errors;
275
- };
276
-
277
- RetryOperation.prototype.attempts = function() {
278
- return this._attempts;
279
- };
280
-
281
- RetryOperation.prototype.mainError = function() {
282
- if (this._errors.length === 0) {
283
- return null;
284
- }
285
-
286
- var counts = {};
287
- var mainError = null;
288
- var mainErrorCount = 0;
289
-
290
- for (var i = 0; i < this._errors.length; i++) {
291
- var error = this._errors[i];
292
- var message = error.message;
293
- var count = (counts[message] || 0) + 1;
294
-
295
- counts[message] = count;
296
-
297
- if (count >= mainErrorCount) {
298
- mainError = error;
299
- mainErrorCount = count;
300
- }
301
- }
302
-
303
- return mainError;
304
- };
305
-
306
- var retry$1 = createCommonjsModule(function (module, exports) {
307
- exports.operation = function(options) {
308
- var timeouts = exports.timeouts(options);
309
- return new retry_operation(timeouts, {
310
- forever: options && options.forever,
311
- unref: options && options.unref,
312
- maxRetryTime: options && options.maxRetryTime
313
- });
314
- };
315
-
316
- exports.timeouts = function(options) {
317
- if (options instanceof Array) {
318
- return [].concat(options);
319
- }
320
-
321
- var opts = {
322
- retries: 10,
323
- factor: 2,
324
- minTimeout: 1 * 1000,
325
- maxTimeout: Infinity,
326
- randomize: false
327
- };
328
- for (var key in options) {
329
- opts[key] = options[key];
330
- }
331
-
332
- if (opts.minTimeout > opts.maxTimeout) {
333
- throw new Error('minTimeout is greater than maxTimeout');
334
- }
335
-
336
- var timeouts = [];
337
- for (var i = 0; i < opts.retries; i++) {
338
- timeouts.push(this.createTimeout(i, opts));
339
- }
340
-
341
- if (options && options.forever && !timeouts.length) {
342
- timeouts.push(this.createTimeout(i, opts));
343
- }
344
-
345
- // sort the array numerically ascending
346
- timeouts.sort(function(a,b) {
347
- return a - b;
348
- });
349
-
350
- return timeouts;
351
- };
352
-
353
- exports.createTimeout = function(attempt, opts) {
354
- var random = (opts.randomize)
355
- ? (Math.random() + 1)
356
- : 1;
357
-
358
- var timeout = Math.round(random * opts.minTimeout * Math.pow(opts.factor, attempt));
359
- timeout = Math.min(timeout, opts.maxTimeout);
360
-
361
- return timeout;
362
- };
363
-
364
- exports.wrap = function(obj, options, methods) {
365
- if (options instanceof Array) {
366
- methods = options;
367
- options = null;
368
- }
369
-
370
- if (!methods) {
371
- methods = [];
372
- for (var key in obj) {
373
- if (typeof obj[key] === 'function') {
374
- methods.push(key);
375
- }
376
- }
377
- }
378
-
379
- for (var i = 0; i < methods.length; i++) {
380
- var method = methods[i];
381
- var original = obj[method];
382
-
383
- obj[method] = function retryWrapper(original) {
384
- var op = exports.operation(options);
385
- var args = Array.prototype.slice.call(arguments, 1);
386
- var callback = args.pop();
387
-
388
- args.push(function(err) {
389
- if (op.retry(err)) {
390
- return;
391
- }
392
- if (err) {
393
- arguments[0] = op.mainError();
394
- }
395
- callback.apply(this, arguments);
396
- });
397
-
398
- op.attempt(function() {
399
- original.apply(obj, args);
400
- });
401
- }.bind(obj, original);
402
- obj[method].options = options;
403
- }
404
- };
405
- });
406
-
407
- var retry = retry$1;
408
-
409
- var hasOwn = Object.prototype.hasOwnProperty;
410
-
411
- function isRetryError(err) {
412
- return err && err.code === 'EPROMISERETRY' && hasOwn.call(err, 'retried');
413
- }
414
-
415
- function promiseRetry(fn, options) {
416
- var temp;
417
- var operation;
418
-
419
- if (typeof fn === 'object' && typeof options === 'function') {
420
- // Swap options and fn when using alternate signature (options, fn)
421
- temp = options;
422
- options = fn;
423
- fn = temp;
424
- }
425
-
426
- operation = retry.operation(options);
427
-
428
- return new Promise(function (resolve, reject) {
429
- operation.attempt(function (number) {
430
- Promise.resolve()
431
- .then(function () {
432
- return fn(function (err) {
433
- if (isRetryError(err)) {
434
- err = err.retried;
435
- }
436
-
437
- throw errCode(new Error('Retrying'), 'EPROMISERETRY', { retried: err });
438
- }, number);
439
- })
440
- .then(resolve, function (err) {
441
- if (isRetryError(err)) {
442
- err = err.retried;
443
-
444
- if (operation.retry(err || new Error())) {
445
- return;
446
- }
447
- }
448
-
449
- reject(err);
450
- });
451
- });
452
- });
453
- }
454
-
455
- var promiseRetry_1 = promiseRetry;
456
-
457
- /*globals self, window */
458
-
459
- /*eslint-disable @mysticatea/prettier */
460
- const { AbortController, AbortSignal } =
461
- typeof self !== "undefined" ? self :
462
- typeof window !== "undefined" ? window :
463
- /* otherwise */ undefined;
464
- /*eslint-enable @mysticatea/prettier */
465
-
466
- var browser = AbortController;
467
- var AbortSignal_1 = AbortSignal;
468
- var _default = AbortController;
469
- browser.AbortSignal = AbortSignal_1;
470
- browser.default = _default;
471
-
472
- /**
473
- * @param { Promise } promise
474
- * @param { Object= } errorExt - Additional Information you can pass to the err object
475
- * @return { Promise }
476
- */
477
- function to(promise, errorExt) {
478
- return promise
479
- .then(function (data) { return [null, data]; })
480
- .catch(function (err) {
481
- if (errorExt) {
482
- Object.assign(err, errorExt);
483
- }
484
- return [err, undefined];
485
- });
486
- }
487
-
488
- const fetchDefaults = {
489
- // The timeout to apply to requests that do not supply a timeout option
490
- timeout: 60 * 1000,
491
- // Retry policy for all fetch requests
492
- retry: {
493
- retries: 3,
494
- minTimeout: 400,
495
- factor: 2
496
- },
497
- // Do retry function to examine failures and apply custom retry logic
498
- // return true to retry the fetch call
499
- doRetry: async (attempt, res, {
500
- url,
501
- options
502
- }) => {
503
- // Get the retry policy from options or fetchDefaults
504
- const {
505
- retry = fetchDefaults.retry
506
- } = options;
507
-
508
- if (attempt <= retry.retries) {
509
- const counter = `${attempt}/${retry.retries}`; // Retry request on any network error,
510
- // or 4xx or 5xx status codes. No retry on 404
511
-
512
- if (!res.status || res.status >= 400 && res.status !== 404) {
513
- if ('message' in res) console.warn(`[fetch] Attempt ${counter} ${res.name}: ${res.message} ${url}`);else console.warn(`[fetch] Attempt ${counter} ${res.status}: ${res.statusText} ${url}`);
514
- return true;
515
- }
516
- }
517
-
518
- return false;
519
- }
520
- };
521
-
522
- // Setting http_proxy in env will inject a proxy agent header and disable certificate verification
523
- const proxyAgent = async () => {
524
- const proxyUri = typeof process !== 'undefined' && process.env.http_proxy || false;
525
-
526
- if (proxyUri) {
527
- // console.info(`Proxying via http_proxy: ${process.env.http_proxy}`);
528
- process.env.NODE_TLS_REJECT_UNAUTHORIZED = '0';
529
- const {
530
- HttpsProxyAgent
531
- } = await ('https-proxy-agent');
532
- return {
533
- agent: new HttpsProxyAgent(proxyUri)
534
- };
535
- }
536
-
537
- return {};
538
- };
539
-
540
- const isFunc = func => typeof func === 'function';
541
-
542
- const isClient = () => typeof window !== 'undefined';
543
-
544
- const thisFetch = isClient() ? window.fetch : fetch__default['default'];
545
-
546
- const fetchWithDefaults = (fetchDefaults$1 = fetchDefaults) => {
547
- // Fetch function using hoisted defaults wrapped in a promise
548
- // retry function adhering to a default or supplied policy calling
549
- // a doRetry function on each failure that requires a boolean return
550
- const enterpriseFetch = async (url, init = {}) => {
551
- const fetchResponse = await promiseRetry_1(async (retry, attempt) => {
552
- const {
553
- retry: retryPolicy = fetchDefaults$1.retry,
554
- timeout: rtimeout = fetchDefaults$1.timeout,
555
- doRetry = fetchDefaults$1.doRetry || fetchDefaults.doRetry
556
- } = init,
557
- options = _objectWithoutProperties(init, ["retry", "timeout", "doRetry"]);
558
-
559
- const timeoutMs = rtimeout || fetchDefaults$1.timeout || 60 * 1000; // Abort signal pattern
560
-
561
- const controller = new browser();
562
- const timeoutId = setTimeout(() => {
563
- controller.abort();
564
- }, timeoutMs); // Try fetching, wait for error or response
565
-
566
- const [error, response] = await to(thisFetch(url, _objectSpread2(_objectSpread2(_objectSpread2({}, options), await proxyAgent()), {}, {
567
- // The signal will recieve abort() after timeout elapsed
568
- signal: controller.signal
569
- })));
570
-
571
- if (error) {
572
- clearTimeout(timeoutId);
573
-
574
- if (isFunc(doRetry) && (await doRetry(attempt, error, {
575
- url,
576
- options: init
577
- }))) {
578
- retry(error);
579
- }
580
-
581
- throw error;
582
- }
583
-
584
- if (!response.ok) {
585
- clearTimeout(timeoutId);
586
-
587
- if (isFunc(doRetry) && (await doRetry(attempt, response, {
588
- url,
589
- options: init
590
- }))) {
591
- retry(response);
592
- }
593
-
594
- return response;
595
- }
596
-
597
- clearTimeout(timeoutId);
598
- return response;
599
- }, init.retry || fetchDefaults$1.retry);
600
- return fetchResponse;
601
- };
602
-
603
- return enterpriseFetch;
604
- };
605
- var enterpriseFetch = fetchWithDefaults(fetchDefaults);
606
-
607
- exports.default = enterpriseFetch;
608
- exports.fetchWithDefaults = fetchWithDefaults;
609
-
610
- Object.defineProperty(exports, '__esModule', { value: true });
611
-
612
- })));
2
+ typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports) :
3
+ typeof define === 'function' && define.amd ? define(['exports'], factory) :
4
+ (global = typeof globalThis !== 'undefined' ? globalThis : global || self, factory(global["enterprise-fetch"] = {}));
5
+ })(this, (function (exports) { 'use strict';
6
+
7
+ function getDefaultExportFromCjs (x) {
8
+ return x && x.__esModule && Object.prototype.hasOwnProperty.call(x, 'default') ? x['default'] : x;
9
+ }
10
+
11
+ var browser = {exports: {}};
12
+
13
+ /*globals self, window */
14
+
15
+ var hasRequiredBrowser;
16
+
17
+ function requireBrowser () {
18
+ if (hasRequiredBrowser) return browser.exports;
19
+ hasRequiredBrowser = 1;
20
+
21
+ /*eslint-disable @mysticatea/prettier */
22
+ const { AbortController, AbortSignal } =
23
+ typeof self !== "undefined" ? self :
24
+ typeof window !== "undefined" ? window :
25
+ /* otherwise */ undefined;
26
+ /*eslint-enable @mysticatea/prettier */
27
+
28
+ browser.exports = AbortController;
29
+ browser.exports.AbortSignal = AbortSignal;
30
+ browser.exports.default = AbortController;
31
+ return browser.exports;
32
+ }
33
+
34
+ var browserExports = requireBrowser();
35
+ var AbortController = /*@__PURE__*/getDefaultExportFromCjs(browserExports);
36
+
37
+ /**
38
+ * @param { Promise } promise
39
+ * @param { Object= } errorExt - Additional Information you can pass to the err object
40
+ * @return { Promise }
41
+ */
42
+ function to(promise, errorExt) {
43
+ return promise
44
+ .then(function (data) { return [null, data]; })
45
+ .catch(function (err) {
46
+ return [err, undefined];
47
+ });
48
+ }
49
+
50
+ var errCode;
51
+ var hasRequiredErrCode;
52
+
53
+ function requireErrCode () {
54
+ if (hasRequiredErrCode) return errCode;
55
+ hasRequiredErrCode = 1;
56
+
57
+ function assign(obj, props) {
58
+ for (const key in props) {
59
+ Object.defineProperty(obj, key, {
60
+ value: props[key],
61
+ enumerable: true,
62
+ configurable: true,
63
+ });
64
+ }
65
+
66
+ return obj;
67
+ }
68
+
69
+ function createError(err, code, props) {
70
+ if (!err || typeof err === 'string') {
71
+ throw new TypeError('Please pass an Error to err-code');
72
+ }
73
+
74
+ if (!props) {
75
+ props = {};
76
+ }
77
+
78
+ if (typeof code === 'object') {
79
+ props = code;
80
+ code = undefined;
81
+ }
82
+
83
+ if (code != null) {
84
+ props.code = code;
85
+ }
86
+
87
+ try {
88
+ return assign(err, props);
89
+ } catch (_) {
90
+ props.message = err.message;
91
+ props.stack = err.stack;
92
+
93
+ const ErrClass = function () {};
94
+
95
+ ErrClass.prototype = Object.create(Object.getPrototypeOf(err));
96
+
97
+ return assign(new ErrClass(), props);
98
+ }
99
+ }
100
+
101
+ errCode = createError;
102
+ return errCode;
103
+ }
104
+
105
+ var retry$1 = {};
106
+
107
+ var retry_operation;
108
+ var hasRequiredRetry_operation;
109
+
110
+ function requireRetry_operation () {
111
+ if (hasRequiredRetry_operation) return retry_operation;
112
+ hasRequiredRetry_operation = 1;
113
+ function RetryOperation(timeouts, options) {
114
+ // Compatibility for the old (timeouts, retryForever) signature
115
+ if (typeof options === 'boolean') {
116
+ options = { forever: options };
117
+ }
118
+
119
+ this._originalTimeouts = JSON.parse(JSON.stringify(timeouts));
120
+ this._timeouts = timeouts;
121
+ this._options = options || {};
122
+ this._maxRetryTime = options && options.maxRetryTime || Infinity;
123
+ this._fn = null;
124
+ this._errors = [];
125
+ this._attempts = 1;
126
+ this._operationTimeout = null;
127
+ this._operationTimeoutCb = null;
128
+ this._timeout = null;
129
+ this._operationStart = null;
130
+
131
+ if (this._options.forever) {
132
+ this._cachedTimeouts = this._timeouts.slice(0);
133
+ }
134
+ }
135
+ retry_operation = RetryOperation;
136
+
137
+ RetryOperation.prototype.reset = function() {
138
+ this._attempts = 1;
139
+ this._timeouts = this._originalTimeouts;
140
+ };
141
+
142
+ RetryOperation.prototype.stop = function() {
143
+ if (this._timeout) {
144
+ clearTimeout(this._timeout);
145
+ }
146
+
147
+ this._timeouts = [];
148
+ this._cachedTimeouts = null;
149
+ };
150
+
151
+ RetryOperation.prototype.retry = function(err) {
152
+ if (this._timeout) {
153
+ clearTimeout(this._timeout);
154
+ }
155
+
156
+ if (!err) {
157
+ return false;
158
+ }
159
+ var currentTime = new Date().getTime();
160
+ if (err && currentTime - this._operationStart >= this._maxRetryTime) {
161
+ this._errors.unshift(new Error('RetryOperation timeout occurred'));
162
+ return false;
163
+ }
164
+
165
+ this._errors.push(err);
166
+
167
+ var timeout = this._timeouts.shift();
168
+ if (timeout === undefined) {
169
+ if (this._cachedTimeouts) {
170
+ // retry forever, only keep last error
171
+ this._errors.splice(this._errors.length - 1, this._errors.length);
172
+ this._timeouts = this._cachedTimeouts.slice(0);
173
+ timeout = this._timeouts.shift();
174
+ } else {
175
+ return false;
176
+ }
177
+ }
178
+
179
+ var self = this;
180
+ var timer = setTimeout(function() {
181
+ self._attempts++;
182
+
183
+ if (self._operationTimeoutCb) {
184
+ self._timeout = setTimeout(function() {
185
+ self._operationTimeoutCb(self._attempts);
186
+ }, self._operationTimeout);
187
+
188
+ if (self._options.unref) {
189
+ self._timeout.unref();
190
+ }
191
+ }
192
+
193
+ self._fn(self._attempts);
194
+ }, timeout);
195
+
196
+ if (this._options.unref) {
197
+ timer.unref();
198
+ }
199
+
200
+ return true;
201
+ };
202
+
203
+ RetryOperation.prototype.attempt = function(fn, timeoutOps) {
204
+ this._fn = fn;
205
+
206
+ if (timeoutOps) {
207
+ if (timeoutOps.timeout) {
208
+ this._operationTimeout = timeoutOps.timeout;
209
+ }
210
+ if (timeoutOps.cb) {
211
+ this._operationTimeoutCb = timeoutOps.cb;
212
+ }
213
+ }
214
+
215
+ var self = this;
216
+ if (this._operationTimeoutCb) {
217
+ this._timeout = setTimeout(function() {
218
+ self._operationTimeoutCb();
219
+ }, self._operationTimeout);
220
+ }
221
+
222
+ this._operationStart = new Date().getTime();
223
+
224
+ this._fn(this._attempts);
225
+ };
226
+
227
+ RetryOperation.prototype.try = function(fn) {
228
+ console.log('Using RetryOperation.try() is deprecated');
229
+ this.attempt(fn);
230
+ };
231
+
232
+ RetryOperation.prototype.start = function(fn) {
233
+ console.log('Using RetryOperation.start() is deprecated');
234
+ this.attempt(fn);
235
+ };
236
+
237
+ RetryOperation.prototype.start = RetryOperation.prototype.try;
238
+
239
+ RetryOperation.prototype.errors = function() {
240
+ return this._errors;
241
+ };
242
+
243
+ RetryOperation.prototype.attempts = function() {
244
+ return this._attempts;
245
+ };
246
+
247
+ RetryOperation.prototype.mainError = function() {
248
+ if (this._errors.length === 0) {
249
+ return null;
250
+ }
251
+
252
+ var counts = {};
253
+ var mainError = null;
254
+ var mainErrorCount = 0;
255
+
256
+ for (var i = 0; i < this._errors.length; i++) {
257
+ var error = this._errors[i];
258
+ var message = error.message;
259
+ var count = (counts[message] || 0) + 1;
260
+
261
+ counts[message] = count;
262
+
263
+ if (count >= mainErrorCount) {
264
+ mainError = error;
265
+ mainErrorCount = count;
266
+ }
267
+ }
268
+
269
+ return mainError;
270
+ };
271
+ return retry_operation;
272
+ }
273
+
274
+ var hasRequiredRetry$1;
275
+
276
+ function requireRetry$1 () {
277
+ if (hasRequiredRetry$1) return retry$1;
278
+ hasRequiredRetry$1 = 1;
279
+ (function (exports) {
280
+ var RetryOperation = requireRetry_operation();
281
+
282
+ exports.operation = function(options) {
283
+ var timeouts = exports.timeouts(options);
284
+ return new RetryOperation(timeouts, {
285
+ forever: options && options.forever,
286
+ unref: options && options.unref,
287
+ maxRetryTime: options && options.maxRetryTime
288
+ });
289
+ };
290
+
291
+ exports.timeouts = function(options) {
292
+ if (options instanceof Array) {
293
+ return [].concat(options);
294
+ }
295
+
296
+ var opts = {
297
+ retries: 10,
298
+ factor: 2,
299
+ minTimeout: 1 * 1000,
300
+ maxTimeout: Infinity,
301
+ randomize: false
302
+ };
303
+ for (var key in options) {
304
+ opts[key] = options[key];
305
+ }
306
+
307
+ if (opts.minTimeout > opts.maxTimeout) {
308
+ throw new Error('minTimeout is greater than maxTimeout');
309
+ }
310
+
311
+ var timeouts = [];
312
+ for (var i = 0; i < opts.retries; i++) {
313
+ timeouts.push(this.createTimeout(i, opts));
314
+ }
315
+
316
+ if (options && options.forever && !timeouts.length) {
317
+ timeouts.push(this.createTimeout(i, opts));
318
+ }
319
+
320
+ // sort the array numerically ascending
321
+ timeouts.sort(function(a,b) {
322
+ return a - b;
323
+ });
324
+
325
+ return timeouts;
326
+ };
327
+
328
+ exports.createTimeout = function(attempt, opts) {
329
+ var random = (opts.randomize)
330
+ ? (Math.random() + 1)
331
+ : 1;
332
+
333
+ var timeout = Math.round(random * opts.minTimeout * Math.pow(opts.factor, attempt));
334
+ timeout = Math.min(timeout, opts.maxTimeout);
335
+
336
+ return timeout;
337
+ };
338
+
339
+ exports.wrap = function(obj, options, methods) {
340
+ if (options instanceof Array) {
341
+ methods = options;
342
+ options = null;
343
+ }
344
+
345
+ if (!methods) {
346
+ methods = [];
347
+ for (var key in obj) {
348
+ if (typeof obj[key] === 'function') {
349
+ methods.push(key);
350
+ }
351
+ }
352
+ }
353
+
354
+ for (var i = 0; i < methods.length; i++) {
355
+ var method = methods[i];
356
+ var original = obj[method];
357
+
358
+ obj[method] = function retryWrapper(original) {
359
+ var op = exports.operation(options);
360
+ var args = Array.prototype.slice.call(arguments, 1);
361
+ var callback = args.pop();
362
+
363
+ args.push(function(err) {
364
+ if (op.retry(err)) {
365
+ return;
366
+ }
367
+ if (err) {
368
+ arguments[0] = op.mainError();
369
+ }
370
+ callback.apply(this, arguments);
371
+ });
372
+
373
+ op.attempt(function() {
374
+ original.apply(obj, args);
375
+ });
376
+ }.bind(obj, original);
377
+ obj[method].options = options;
378
+ }
379
+ };
380
+ } (retry$1));
381
+ return retry$1;
382
+ }
383
+
384
+ var retry;
385
+ var hasRequiredRetry;
386
+
387
+ function requireRetry () {
388
+ if (hasRequiredRetry) return retry;
389
+ hasRequiredRetry = 1;
390
+ retry = requireRetry$1();
391
+ return retry;
392
+ }
393
+
394
+ var promiseRetry_1;
395
+ var hasRequiredPromiseRetry;
396
+
397
+ function requirePromiseRetry () {
398
+ if (hasRequiredPromiseRetry) return promiseRetry_1;
399
+ hasRequiredPromiseRetry = 1;
400
+
401
+ var errcode = requireErrCode();
402
+ var retry = requireRetry();
403
+
404
+ var hasOwn = Object.prototype.hasOwnProperty;
405
+
406
+ function isRetryError(err) {
407
+ return err && err.code === 'EPROMISERETRY' && hasOwn.call(err, 'retried');
408
+ }
409
+
410
+ function promiseRetry(fn, options) {
411
+ var temp;
412
+ var operation;
413
+
414
+ if (typeof fn === 'object' && typeof options === 'function') {
415
+ // Swap options and fn when using alternate signature (options, fn)
416
+ temp = options;
417
+ options = fn;
418
+ fn = temp;
419
+ }
420
+
421
+ operation = retry.operation(options);
422
+
423
+ return new Promise(function (resolve, reject) {
424
+ operation.attempt(function (number) {
425
+ Promise.resolve()
426
+ .then(function () {
427
+ return fn(function (err) {
428
+ if (isRetryError(err)) {
429
+ err = err.retried;
430
+ }
431
+
432
+ throw errcode(new Error('Retrying'), 'EPROMISERETRY', { retried: err });
433
+ }, number);
434
+ })
435
+ .then(resolve, function (err) {
436
+ if (isRetryError(err)) {
437
+ err = err.retried;
438
+
439
+ if (operation.retry(err || new Error())) {
440
+ return;
441
+ }
442
+ }
443
+
444
+ reject(err);
445
+ });
446
+ });
447
+ });
448
+ }
449
+
450
+ promiseRetry_1 = promiseRetry;
451
+ return promiseRetry_1;
452
+ }
453
+
454
+ var promiseRetryExports = requirePromiseRetry();
455
+ var promiseRetry = /*@__PURE__*/getDefaultExportFromCjs(promiseRetryExports);
456
+
457
+ const fetchDefaults = {
458
+ // The timeout to apply to requests that do not supply a timeout option
459
+ timeout: 60 * 1000,
460
+ // Retry policy for all fetch requests
461
+ retry: {
462
+ retries: 3,
463
+ minTimeout: 400,
464
+ factor: 2
465
+ },
466
+ // Do retry function to examine failures and apply custom retry logic
467
+ // return true to retry the fetch call
468
+ doRetry: async (attempt, res, {
469
+ url,
470
+ options
471
+ }) => {
472
+ // Get the retry policy from options or fetchDefaults
473
+ const {
474
+ retry = fetchDefaults.retry
475
+ } = options;
476
+ if (attempt <= retry.retries) {
477
+ const counter = `${attempt}/${retry.retries}`;
478
+ // Retry request on any network error,
479
+ // or 4xx or 5xx status codes. No retry on 404
480
+ if (!res.status || res.status >= 400 && res.status !== 404) {
481
+ if ('message' in res) console.warn(`[fetch] Attempt ${counter} ${res.name}: ${res.message} ${url}`);else console.warn(`[fetch] Attempt ${counter} ${res.status}: ${res.statusText} ${url}`);
482
+ return true;
483
+ }
484
+ }
485
+ return false;
486
+ }
487
+ };
488
+
489
+ const isClient = () => typeof window !== 'undefined';
490
+
491
+ const isNode = () => {
492
+ if (isClient()) return false;
493
+ if (!globalThis.fallbackFetch && typeof globalThis.fetch === 'function') return 'node';
494
+ return 'node-fetch';
495
+ };
496
+
497
+ const resolveFetch = async () => {
498
+ const node = isNode();
499
+ if (!node) return window.fetch;
500
+ if (node !== 'node') {
501
+ globalThis.fallbackFetch = true;
502
+ globalThis.fetch = (await ('node-fetch')).default;
503
+ }
504
+ return globalThis.fetch;
505
+ };
506
+
507
+ // Setting http_proxy in env will inject a proxy agent header and disable certificate verification
508
+ const proxyAgent = async () => {
509
+ const proxyUri = !isClient() && process.env.http_proxy;
510
+ if (proxyUri) {
511
+ process.env.NODE_TLS_REJECT_UNAUTHORIZED = '0';
512
+ if (globalThis.fallbackFetch) {
513
+ // https://www.npmjs.com/package/node-fetch#custom-agent
514
+ // NOTE: This uses the HttpsProxyAgent class from https-proxy-agent v7.x
515
+ // Will break in v8+ where only a default factory function is exported
516
+ const {
517
+ HttpsProxyAgent
518
+ } = await ('https-proxy-agent');
519
+ return {
520
+ agent: new HttpsProxyAgent(proxyUri)
521
+ };
522
+ } else {
523
+ // EnvHttpProxyAgent automatically reads the proxy configuration from the
524
+ // environment variables http_proxy, https_proxy, and no_proxy and sets up
525
+ // the proxy agents accordingly. When http_proxy and https_proxy are set,
526
+ // http_proxy is used for HTTP requests and https_proxy is used for HTTPS requests.
527
+ // If only http_proxy is set, http_proxy is used for both HTTP and HTTPS requests.
528
+ // If only https_proxy is set, it is only used for HTTPS requests.
529
+ // https://undici.nodejs.org/#/docs/api/EnvHttpProxyAgent.md
530
+ const {
531
+ EnvHttpProxyAgent
532
+ } = await ('undici');
533
+ return {
534
+ dispatcher: new EnvHttpProxyAgent()
535
+ };
536
+ }
537
+ }
538
+ return {};
539
+ };
540
+
541
+ const isFunc = func => typeof func === 'function';
542
+
543
+ const fetchWithDefaults = (fetchDefaults$1 = fetchDefaults) => {
544
+ // Fetch function using hoisted defaults wrapped in a promise
545
+ // retry function adhering to a default or supplied policy calling
546
+ // a doRetry function on each failure that requires a boolean return
547
+ const enterpriseFetch = async (url, init = {}) => {
548
+ const thisFetch = await resolveFetch();
549
+ const fetchResponse = await promiseRetry(async (retry, attempt) => {
550
+ const {
551
+ // eslint-disable-next-line @typescript-eslint/no-unused-vars
552
+ retry: retryPolicy = fetchDefaults$1.retry,
553
+ timeout: rtimeout = fetchDefaults$1.timeout,
554
+ doRetry = fetchDefaults$1.doRetry || fetchDefaults.doRetry,
555
+ ...options
556
+ } = init;
557
+ const timeoutMs = rtimeout || fetchDefaults$1.timeout || 60 * 1000;
558
+ // Abort signal pattern
559
+ // Since v15.4.0 Node.js comes with AbortController out of the box
560
+ const controller = new AbortController();
561
+ const timeoutId = setTimeout(() => {
562
+ controller.abort();
563
+ }, timeoutMs);
564
+ // Try fetching, wait for error or response
565
+ const [error, response] = await to(thisFetch(url, {
566
+ // Standard fetch options
567
+ ...options,
568
+ // Conditionally add a proxy agent to debug requests
569
+ ...(await proxyAgent()),
570
+ // The signal will recieve abort() after timeout elapsed
571
+ signal: controller.signal
572
+ }));
573
+ if (error) {
574
+ clearTimeout(timeoutId);
575
+ if (isFunc(doRetry) && (await doRetry(attempt, error, {
576
+ url: url.toString(),
577
+ options: init
578
+ }))) {
579
+ retry(error);
580
+ }
581
+ throw error;
582
+ }
583
+ if (!response.ok) {
584
+ clearTimeout(timeoutId);
585
+ if (isFunc(doRetry) && (await doRetry(attempt, response, {
586
+ url: url.toString(),
587
+ options: init
588
+ }))) {
589
+ retry(response);
590
+ }
591
+ return response;
592
+ }
593
+ clearTimeout(timeoutId);
594
+ return response;
595
+ }, init.retry || fetchDefaults$1.retry);
596
+ return fetchResponse;
597
+ };
598
+ return enterpriseFetch;
599
+ };
600
+ const fetch = fetchWithDefaults(fetchDefaults);
601
+
602
+ exports.default = fetch;
603
+ exports.fetch = fetch;
604
+ exports.fetchWithDefaults = fetchWithDefaults;
605
+
606
+ Object.defineProperty(exports, '__esModule', { value: true });
607
+
608
+ }));