enterprise-fetch 1.0.1 → 2.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1 +1 @@
1
- !function(t,e){"object"==typeof exports&&"undefined"!=typeof module?e(exports,require("cross-fetch")):"function"==typeof define&&define.amd?define(["exports","cross-fetch"],e):e((t="undefined"!=typeof globalThis?globalThis:t||self)["enterprise-fetch"]={},t.fetch)}(this,(function(t,e){"use strict";function r(t){return t&&"object"==typeof t&&"default"in t?t:{default:t}}var o=r(e);function i(t,e,r){return e in t?Object.defineProperty(t,e,{value:r,enumerable:!0,configurable:!0,writable:!0}):t[e]=r,t}function n(t,e){var r=Object.keys(t);if(Object.getOwnPropertySymbols){var o=Object.getOwnPropertySymbols(t);e&&(o=o.filter((function(e){return Object.getOwnPropertyDescriptor(t,e).enumerable}))),r.push.apply(r,o)}return r}function s(t){for(var e=1;e<arguments.length;e++){var r=null!=arguments[e]?arguments[e]:{};e%2?n(Object(r),!0).forEach((function(e){i(t,e,r[e])})):Object.getOwnPropertyDescriptors?Object.defineProperties(t,Object.getOwnPropertyDescriptors(r)):n(Object(r)).forEach((function(e){Object.defineProperty(t,e,Object.getOwnPropertyDescriptor(r,e))}))}return t}function u(t,e){if(null==t)return{};var r,o,i=function(t,e){if(null==t)return{};var r,o,i={},n=Object.keys(t);for(o=0;o<n.length;o++)r=n[o],e.indexOf(r)>=0||(i[r]=t[r]);return i}(t,e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(t);for(o=0;o<n.length;o++)r=n[o],e.indexOf(r)>=0||Object.prototype.propertyIsEnumerable.call(t,r)&&(i[r]=t[r])}return i}function a(t,e){for(const r in e)Object.defineProperty(t,r,{value:e[r],enumerable:!0,configurable:!0});return t}var c=function(t,e,r){if(!t||"string"==typeof t)throw new TypeError("Please pass an Error to err-code");r||(r={}),"object"==typeof e&&(r=e,e=void 0),null!=e&&(r.code=e);try{return a(t,r)}catch(e){r.message=t.message,r.stack=t.stack;const o=function(){};return o.prototype=Object.create(Object.getPrototypeOf(t)),a(new o,r)}};function f(t,e){"boolean"==typeof e&&(e={forever:e}),this._originalTimeouts=JSON.parse(JSON.stringify(t)),this._timeouts=t,this._options=e||{},this._maxRetryTime=e&&e.maxRetryTime||1/0,this._fn=null,this._errors=[],this._attempts=1,this._operationTimeout=null,this._operationTimeoutCb=null,this._timeout=null,this._operationStart=null,this._options.forever&&(this._cachedTimeouts=this._timeouts.slice(0))}var p=f;f.prototype.reset=function(){this._attempts=1,this._timeouts=this._originalTimeouts},f.prototype.stop=function(){this._timeout&&clearTimeout(this._timeout),this._timeouts=[],this._cachedTimeouts=null},f.prototype.retry=function(t){if(this._timeout&&clearTimeout(this._timeout),!t)return!1;var e=(new Date).getTime();if(t&&e-this._operationStart>=this._maxRetryTime)return this._errors.unshift(new Error("RetryOperation timeout occurred")),!1;this._errors.push(t);var r=this._timeouts.shift();if(void 0===r){if(!this._cachedTimeouts)return!1;this._errors.splice(this._errors.length-1,this._errors.length),this._timeouts=this._cachedTimeouts.slice(0),r=this._timeouts.shift()}var o=this,i=setTimeout((function(){o._attempts++,o._operationTimeoutCb&&(o._timeout=setTimeout((function(){o._operationTimeoutCb(o._attempts)}),o._operationTimeout),o._options.unref&&o._timeout.unref()),o._fn(o._attempts)}),r);return this._options.unref&&i.unref(),!0},f.prototype.attempt=function(t,e){this._fn=t,e&&(e.timeout&&(this._operationTimeout=e.timeout),e.cb&&(this._operationTimeoutCb=e.cb));var r=this;this._operationTimeoutCb&&(this._timeout=setTimeout((function(){r._operationTimeoutCb()}),r._operationTimeout)),this._operationStart=(new Date).getTime(),this._fn(this._attempts)},f.prototype.try=function(t){console.log("Using RetryOperation.try() is deprecated"),this.attempt(t)},f.prototype.start=function(t){console.log("Using RetryOperation.start() is deprecated"),this.attempt(t)},f.prototype.start=f.prototype.try,f.prototype.errors=function(){return this._errors},f.prototype.attempts=function(){return this._attempts},f.prototype.mainError=function(){if(0===this._errors.length)return null;for(var t={},e=null,r=0,o=0;o<this._errors.length;o++){var i=this._errors[o],n=i.message,s=(t[n]||0)+1;t[n]=s,s>=r&&(e=i,r=s)}return e};var m=function(t){var e={exports:{}};return t(e,e.exports),e.exports}((function(t,e){e.operation=function(t){var r=e.timeouts(t);return new p(r,{forever:t&&t.forever,unref:t&&t.unref,maxRetryTime:t&&t.maxRetryTime})},e.timeouts=function(t){if(t instanceof Array)return[].concat(t);var e={retries:10,factor:2,minTimeout:1e3,maxTimeout:1/0,randomize:!1};for(var r in t)e[r]=t[r];if(e.minTimeout>e.maxTimeout)throw new Error("minTimeout is greater than maxTimeout");for(var o=[],i=0;i<e.retries;i++)o.push(this.createTimeout(i,e));return t&&t.forever&&!o.length&&o.push(this.createTimeout(i,e)),o.sort((function(t,e){return t-e})),o},e.createTimeout=function(t,e){var r=e.randomize?Math.random()+1:1,o=Math.round(r*e.minTimeout*Math.pow(e.factor,t));return o=Math.min(o,e.maxTimeout)},e.wrap=function(t,r,o){if(r instanceof Array&&(o=r,r=null),!o)for(var i in o=[],t)"function"==typeof t[i]&&o.push(i);for(var n=0;n<o.length;n++){var s=o[n],u=t[s];t[s]=function(o){var i=e.operation(r),n=Array.prototype.slice.call(arguments,1),s=n.pop();n.push((function(t){i.retry(t)||(t&&(arguments[0]=i.mainError()),s.apply(this,arguments))})),i.attempt((function(){o.apply(t,n)}))}.bind(t,u),t[s].options=r}}})),h=Object.prototype.hasOwnProperty;function l(t){return t&&"EPROMISERETRY"===t.code&&h.call(t,"retried")}var y=function(t,e){var r,o;return"object"==typeof t&&"function"==typeof e&&(r=e,e=t,t=r),o=m.operation(e),new Promise((function(e,r){o.attempt((function(i){Promise.resolve().then((function(){return t((function(t){throw l(t)&&(t=t.retried),c(new Error("Retrying"),"EPROMISERETRY",{retried:t})}),i)})).then(e,(function(t){l(t)&&(t=t.retried,o.retry(t||new Error))||r(t)}))}))}))};const{AbortController:_,AbortSignal:d}="undefined"!=typeof self?self:"undefined"!=typeof window?window:void 0;var b=_,T=d,g=_;b.AbortSignal=T,b.default=g;const v={timeout:6e4,retry:{retries:3,minTimeout:400,factor:2},doRetry:async(t,e,{url:r,options:o})=>{const{retry:i=v.retry}=o;if(t<=i.retries){const o=`${t}/${i.retries}`;if(!e.status||e.status>=400&&404!==e.status)return"message"in e?console.warn(`[fetch] Attempt ${o} ${e.name}: ${e.message} ${r}`):console.warn(`[fetch] Attempt ${o} ${e.status}: ${e.statusText} ${r}`),!0}return!1}},w=t=>"function"==typeof t,O="undefined"!=typeof window?window.fetch:o.default,j=(t=v)=>async(e,r={})=>await y((async(o,i)=>{const{retry:n=t.retry,timeout:a=t.timeout,doRetry:c=t.doRetry||v.doRetry}=r,f=u(r,["retry","timeout","doRetry"]),p=a||t.timeout||6e4,m=new b,h=setTimeout((()=>{m.abort()}),p),[l,y]=await(_=O(e,s(s(s({},f),await(async()=>{const t="undefined"!=typeof process&&process.env.http_proxy||!1;if(t){process.env.NODE_TLS_REJECT_UNAUTHORIZED="0";const{HttpsProxyAgent:e}=await"https-proxy-agent";return{agent:new e(t)}}return{}})()),{},{signal:m.signal})),_.then((function(t){return[null,t]})).catch((function(t){return d&&Object.assign(t,d),[t,void 0]})));var _,d;if(l)throw clearTimeout(h),w(c)&&await c(i,l,{url:e,options:r})&&o(l),l;return y.ok?(clearTimeout(h),y):(clearTimeout(h),w(c)&&await c(i,y,{url:e,options:r})&&o(y),y)}),r.retry||t.retry);var R=j(v);t.default=R,t.fetchWithDefaults=j,Object.defineProperty(t,"__esModule",{value:!0})}));
1
+ !function(t,e){"object"==typeof exports&&"undefined"!=typeof module?e(exports):"function"==typeof define&&define.amd?define(["exports"],e):e((t="undefined"!=typeof globalThis?globalThis:t||self)["enterprise-fetch"]={})}(this,function(t){"use strict";function e(t){return t&&t.__esModule&&Object.prototype.hasOwnProperty.call(t,"default")?t.default:t}var r,o={exports:{}};var i,n,s=function(){if(r)return o.exports;r=1;const{AbortController:t,AbortSignal:e}="undefined"!=typeof self?self:"undefined"!=typeof window?window:void 0;return o.exports=t,o.exports.AbortSignal=e,o.exports.default=t,o.exports}(),u=e(s);var a,f,c,p,m,h,l,y={};function _(){return c||(c=1,function(t){var e=function(){if(f)return a;function t(t,e){"boolean"==typeof e&&(e={forever:e}),this._originalTimeouts=JSON.parse(JSON.stringify(t)),this._timeouts=t,this._options=e||{},this._maxRetryTime=e&&e.maxRetryTime||1/0,this._fn=null,this._errors=[],this._attempts=1,this._operationTimeout=null,this._operationTimeoutCb=null,this._timeout=null,this._operationStart=null,this._options.forever&&(this._cachedTimeouts=this._timeouts.slice(0))}return f=1,a=t,t.prototype.reset=function(){this._attempts=1,this._timeouts=this._originalTimeouts},t.prototype.stop=function(){this._timeout&&clearTimeout(this._timeout),this._timeouts=[],this._cachedTimeouts=null},t.prototype.retry=function(t){if(this._timeout&&clearTimeout(this._timeout),!t)return!1;var e=(new Date).getTime();if(t&&e-this._operationStart>=this._maxRetryTime)return this._errors.unshift(new Error("RetryOperation timeout occurred")),!1;this._errors.push(t);var r=this._timeouts.shift();if(void 0===r){if(!this._cachedTimeouts)return!1;this._errors.splice(this._errors.length-1,this._errors.length),this._timeouts=this._cachedTimeouts.slice(0),r=this._timeouts.shift()}var o=this,i=setTimeout(function(){o._attempts++,o._operationTimeoutCb&&(o._timeout=setTimeout(function(){o._operationTimeoutCb(o._attempts)},o._operationTimeout),o._options.unref&&o._timeout.unref()),o._fn(o._attempts)},r);return this._options.unref&&i.unref(),!0},t.prototype.attempt=function(t,e){this._fn=t,e&&(e.timeout&&(this._operationTimeout=e.timeout),e.cb&&(this._operationTimeoutCb=e.cb));var r=this;this._operationTimeoutCb&&(this._timeout=setTimeout(function(){r._operationTimeoutCb()},r._operationTimeout)),this._operationStart=(new Date).getTime(),this._fn(this._attempts)},t.prototype.try=function(t){console.log("Using RetryOperation.try() is deprecated"),this.attempt(t)},t.prototype.start=function(t){console.log("Using RetryOperation.start() is deprecated"),this.attempt(t)},t.prototype.start=t.prototype.try,t.prototype.errors=function(){return this._errors},t.prototype.attempts=function(){return this._attempts},t.prototype.mainError=function(){if(0===this._errors.length)return null;for(var t={},e=null,r=0,o=0;o<this._errors.length;o++){var i=this._errors[o],n=i.message,s=(t[n]||0)+1;t[n]=s,s>=r&&(e=i,r=s)}return e},a}();t.operation=function(r){var o=t.timeouts(r);return new e(o,{forever:r&&r.forever,unref:r&&r.unref,maxRetryTime:r&&r.maxRetryTime})},t.timeouts=function(t){if(t instanceof Array)return[].concat(t);var e={retries:10,factor:2,minTimeout:1e3,maxTimeout:1/0,randomize:!1};for(var r in t)e[r]=t[r];if(e.minTimeout>e.maxTimeout)throw new Error("minTimeout is greater than maxTimeout");for(var o=[],i=0;i<e.retries;i++)o.push(this.createTimeout(i,e));return t&&t.forever&&!o.length&&o.push(this.createTimeout(i,e)),o.sort(function(t,e){return t-e}),o},t.createTimeout=function(t,e){var r=e.randomize?Math.random()+1:1,o=Math.round(r*e.minTimeout*Math.pow(e.factor,t));return o=Math.min(o,e.maxTimeout)},t.wrap=function(e,r,o){if(r instanceof Array&&(o=r,r=null),!o)for(var i in o=[],e)"function"==typeof e[i]&&o.push(i);for(var n=0;n<o.length;n++){var s=o[n],u=e[s];e[s]=function(o){var i=t.operation(r),n=Array.prototype.slice.call(arguments,1),s=n.pop();n.push(function(t){i.retry(t)||(t&&(arguments[0]=i.mainError()),s.apply(this,arguments))}),i.attempt(function(){o.apply(e,n)})}.bind(e,u),e[s].options=r}}}(y)),y}function d(){return m?p:(m=1,p=_())}var T=function(){if(l)return h;l=1;var t=function(){if(n)return i;function t(t,e){for(const r in e)Object.defineProperty(t,r,{value:e[r],enumerable:!0,configurable:!0});return t}return n=1,i=function(e,r,o){if(!e||"string"==typeof e)throw new TypeError("Please pass an Error to err-code");o||(o={}),"object"==typeof r&&(o=r,r=void 0),null!=r&&(o.code=r);try{return t(e,o)}catch(r){o.message=e.message,o.stack=e.stack;const i=function(){};return i.prototype=Object.create(Object.getPrototypeOf(e)),t(new i,o)}}}(),e=d(),r=Object.prototype.hasOwnProperty;function o(t){return t&&"EPROMISERETRY"===t.code&&r.call(t,"retried")}return h=function(r,i){var n,s;return"object"==typeof r&&"function"==typeof i&&(n=i,i=r,r=n),s=e.operation(i),new Promise(function(e,i){s.attempt(function(n){Promise.resolve().then(function(){return r(function(e){throw o(e)&&(e=e.retried),t(new Error("Retrying"),"EPROMISERETRY",{retried:e})},n)}).then(e,function(t){o(t)&&(t=t.retried,s.retry(t||new Error))||i(t)})})})}}(),g=e(T);const w={timeout:6e4,retry:{retries:3,minTimeout:400,factor:2},doRetry:async(t,e,{url:r,options:o})=>{const{retry:i=w.retry}=o;if(t<=i.retries){const o=`${t}/${i.retries}`;if(!e.status||e.status>=400&&404!==e.status)return"message"in e?console.warn(`[fetch] Attempt ${o} ${e.name}: ${e.message} ${r}`):console.warn(`[fetch] Attempt ${o} ${e.status}: ${e.statusText} ${r}`),!0}return!1}},v=()=>"undefined"!=typeof window,b=async()=>{const t=!v()&&"undefined"!=typeof process&&process.env.http_proxy||!1;if(t){process.env.NODE_TLS_REJECT_UNAUTHORIZED="0";const{HttpsProxyAgent:e}=await"https-proxy-agent";return{agent:new e(t)}}return{}},x=t=>"function"==typeof t,R=(t=w)=>async(e,r={})=>{const o=await(async()=>v()?window.fetch:"function"==typeof globalThis.fetch?globalThis.fetch:(await"node-fetch").default)(),i=await g(async(i,n)=>{const{retry:s=t.retry,timeout:a=t.timeout,doRetry:f=t.doRetry||w.doRetry,...c}=r,p=a||t.timeout||6e4,m=new u,h=setTimeout(()=>{m.abort()},p),[l,y]=await(_=o(e,{...c,...await b(),signal:m.signal}),_.then(function(t){return[null,t]}).catch(function(t){return[t,void 0]}));var _;if(l)throw clearTimeout(h),x(f)&&await f(n,l,{url:e.toString(),options:r})&&i(l),l;return y.ok?(clearTimeout(h),y):(clearTimeout(h),x(f)&&await f(n,y,{url:e.toString(),options:r})&&i(y),y)},r.retry||t.retry);return i},E=R(w);t.default=E,t.fetch=E,t.fetchWithDefaults=R,Object.defineProperty(t,"__esModule",{value:!0})});
@@ -2,158 +2,126 @@
2
2
 
3
3
  Object.defineProperty(exports, '__esModule', { value: true });
4
4
 
5
- var fetch = require('cross-fetch');
6
- var promiseRetry = require('promise-retry');
7
5
  var AbortController = require('abort-controller');
8
- var to = require('await-to-js');
9
-
10
- function _interopDefaultLegacy (e) { return e && typeof e === 'object' && 'default' in e ? e : { 'default': e }; }
11
-
12
- function _interopNamespace(e) {
13
- if (e && e.__esModule) return e;
14
- var n = Object.create(null);
15
- if (e) {
16
- Object.keys(e).forEach(function (k) {
17
- if (k !== 'default') {
18
- var d = Object.getOwnPropertyDescriptor(e, k);
19
- Object.defineProperty(n, k, d.get ? d : {
20
- enumerable: true,
21
- get: function () {
22
- return e[k];
23
- }
24
- });
25
- }
26
- });
27
- }
28
- n['default'] = e;
29
- return Object.freeze(n);
30
- }
31
-
32
- var fetch__default = /*#__PURE__*/_interopDefaultLegacy(fetch);
33
- var promiseRetry__default = /*#__PURE__*/_interopDefaultLegacy(promiseRetry);
34
- var AbortController__default = /*#__PURE__*/_interopDefaultLegacy(AbortController);
35
- var to__default = /*#__PURE__*/_interopDefaultLegacy(to);
6
+ var awaitToJs = require('await-to-js');
7
+ var promiseRetry = require('promise-retry');
36
8
 
37
9
  const fetchDefaults = {
38
- // The timeout to apply to requests that do not supply a timeout option
39
- timeout: 60 * 1000,
40
- // Retry policy for all fetch requests
41
- retry: {
42
- retries: 3,
43
- minTimeout: 400,
44
- factor: 2
45
- },
46
- // Do retry function to examine failures and apply custom retry logic
47
- // return true to retry the fetch call
48
- doRetry: async (attempt, res, {
49
- url,
50
- options
51
- }) => {
52
- // Get the retry policy from options or fetchDefaults
53
- const {
54
- retry = fetchDefaults.retry
55
- } = options;
56
-
57
- if (attempt <= retry.retries) {
58
- const counter = `${attempt}/${retry.retries}`; // Retry request on any network error,
59
- // or 4xx or 5xx status codes. No retry on 404
10
+ // The timeout to apply to requests that do not supply a timeout option
11
+ timeout: 60 * 1000,
12
+ // Retry policy for all fetch requests
13
+ retry: {
14
+ retries: 3,
15
+ minTimeout: 400,
16
+ factor: 2,
17
+ },
18
+ // Do retry function to examine failures and apply custom retry logic
19
+ // return true to retry the fetch call
20
+ doRetry: async (attempt, res, { url, options }) => {
21
+ // Get the retry policy from options or fetchDefaults
22
+ const { retry = fetchDefaults.retry } = options;
23
+ if (attempt <= retry.retries) {
24
+ const counter = `${attempt}/${retry.retries}`;
25
+ // Retry request on any network error,
26
+ // or 4xx or 5xx status codes. No retry on 404
27
+ if (!res.status || (res.status >= 400 && res.status !== 404)) {
28
+ if ('message' in res)
29
+ console.warn(`[fetch] Attempt ${counter} ${res.name}: ${res.message} ${url}`);
30
+ else
31
+ console.warn(`[fetch] Attempt ${counter} ${res.status}: ${res.statusText} ${url}`);
32
+ return true;
33
+ }
34
+ }
35
+ return false;
36
+ },
37
+ };
60
38
 
61
- if (!res.status || res.status >= 400 && res.status !== 404) {
62
- 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}`);
63
- return true;
64
- }
65
- }
39
+ const isClient = () => typeof window !== 'undefined';
66
40
 
67
- return false;
68
- }
41
+ const resolveFetch = async () => {
42
+ if (isClient())
43
+ return window.fetch;
44
+ if (typeof globalThis.fetch === 'function')
45
+ return globalThis.fetch;
46
+ const nodeFetch = await import('node-fetch');
47
+ // recast node-fetch to keep typescript happy
48
+ return nodeFetch.default;
69
49
  };
70
50
 
71
51
  // Setting http_proxy in env will inject a proxy agent header and disable certificate verification
72
52
  const proxyAgent = async () => {
73
- const proxyUri = typeof process !== 'undefined' && process.env.http_proxy || false;
74
-
75
- if (proxyUri) {
76
- // console.info(`Proxying via http_proxy: ${process.env.http_proxy}`);
77
- process.env.NODE_TLS_REJECT_UNAUTHORIZED = '0';
78
- const {
79
- HttpsProxyAgent
80
- } = await Promise.resolve().then(function () { return /*#__PURE__*/_interopNamespace(require('https-proxy-agent')); });
81
- return {
82
- agent: new HttpsProxyAgent(proxyUri)
83
- };
84
- }
85
-
86
- return {};
53
+ const proxyUri = (!isClient() && typeof process !== 'undefined' && process.env.http_proxy) ||
54
+ false;
55
+ if (proxyUri) {
56
+ // console.info(`Proxying via http_proxy: ${process.env.http_proxy}`);
57
+ process.env.NODE_TLS_REJECT_UNAUTHORIZED = '0';
58
+ // NOTE: This uses the HttpsProxyAgent class from https-proxy-agent v7.x
59
+ // Will break in v8+ where only a default factory function is exported
60
+ const { HttpsProxyAgent } = await import('https-proxy-agent');
61
+ return { agent: new HttpsProxyAgent(proxyUri) };
62
+ }
63
+ return {};
87
64
  };
88
65
 
89
- const isFunc = func => typeof func === 'function';
90
-
91
- const isClient = () => typeof window !== 'undefined';
92
-
93
- const thisFetch = isClient() ? window.fetch : fetch__default['default'];
66
+ const isFunc = (func) => typeof func === 'function';
94
67
 
95
68
  const fetchWithDefaults = (fetchDefaults$1 = fetchDefaults) => {
96
- // Fetch function using hoisted defaults wrapped in a promise
97
- // retry function adhering to a default or supplied policy calling
98
- // a doRetry function on each failure that requires a boolean return
99
- const enterpriseFetch = async (url, init = {}) => {
100
- const fetchResponse = await promiseRetry__default['default'](async (retry, attempt) => {
101
- const {
102
- retry: retryPolicy = fetchDefaults$1.retry,
103
- timeout: rtimeout = fetchDefaults$1.timeout,
104
- doRetry = fetchDefaults$1.doRetry || fetchDefaults.doRetry,
105
- ...options
106
- } = init;
107
- const timeoutMs = rtimeout || fetchDefaults$1.timeout || 60 * 1000; // Abort signal pattern
108
-
109
- const controller = new AbortController__default['default']();
110
- const timeoutId = setTimeout(() => {
111
- controller.abort();
112
- }, timeoutMs); // Try fetching, wait for error or response
113
-
114
- const [error, response] = await to__default['default'](thisFetch(url, { // Standard fetch options
115
- ...options,
116
- // Conditionally add a proxy agent to debug requests
117
- ...(await proxyAgent()),
118
- // The signal will recieve abort() after timeout elapsed
119
- signal: controller.signal
120
- }));
121
-
122
- if (error) {
123
- clearTimeout(timeoutId);
124
-
125
- if (isFunc(doRetry) && (await doRetry(attempt, error, {
126
- url,
127
- options: init
128
- }))) {
129
- retry(error);
130
- }
131
-
132
- throw error;
133
- }
134
-
135
- if (!response.ok) {
136
- clearTimeout(timeoutId);
137
-
138
- if (isFunc(doRetry) && (await doRetry(attempt, response, {
139
- url,
140
- options: init
141
- }))) {
142
- retry(response);
143
- }
144
-
145
- return response;
146
- }
147
-
148
- clearTimeout(timeoutId);
149
- return response;
150
- }, init.retry || fetchDefaults$1.retry);
151
- return fetchResponse;
152
- };
153
-
154
- return enterpriseFetch;
69
+ // Fetch function using hoisted defaults wrapped in a promise
70
+ // retry function adhering to a default or supplied policy calling
71
+ // a doRetry function on each failure that requires a boolean return
72
+ const enterpriseFetch = async (url, init = {}) => {
73
+ const thisFetch = await resolveFetch();
74
+ const fetchResponse = await promiseRetry(async (retry, attempt) => {
75
+ const {
76
+ // eslint-disable-next-line @typescript-eslint/no-unused-vars
77
+ retry: retryPolicy = fetchDefaults$1.retry, timeout: rtimeout = fetchDefaults$1.timeout, doRetry = fetchDefaults$1.doRetry || fetchDefaults.doRetry, ...options } = init;
78
+ const timeoutMs = rtimeout || fetchDefaults$1.timeout || 60 * 1000;
79
+ // Abort signal pattern
80
+ // Since v15.4.0 Node.js comes with AbortController out of the box
81
+ const controller = new AbortController();
82
+ const timeoutId = setTimeout(() => {
83
+ controller.abort();
84
+ }, timeoutMs);
85
+ // Try fetching, wait for error or response
86
+ const [error, response] = await awaitToJs.to(thisFetch(url, {
87
+ // Standard fetch options
88
+ ...options,
89
+ // Conditionally add a proxy agent to debug requests
90
+ ...(await proxyAgent()),
91
+ // The signal will recieve abort() after timeout elapsed
92
+ signal: controller.signal,
93
+ }));
94
+ if (error) {
95
+ clearTimeout(timeoutId);
96
+ if (isFunc(doRetry) &&
97
+ (await doRetry(attempt, error, {
98
+ url: url.toString(),
99
+ options: init,
100
+ }))) {
101
+ retry(error);
102
+ }
103
+ throw error;
104
+ }
105
+ if (!response.ok) {
106
+ clearTimeout(timeoutId);
107
+ if (isFunc(doRetry) &&
108
+ (await doRetry(attempt, response, {
109
+ url: url.toString(),
110
+ options: init,
111
+ }))) {
112
+ retry(response);
113
+ }
114
+ return response;
115
+ }
116
+ clearTimeout(timeoutId);
117
+ return response;
118
+ }, init.retry || fetchDefaults$1.retry);
119
+ return fetchResponse;
120
+ };
121
+ return enterpriseFetch;
155
122
  };
156
- var enterpriseFetch = fetchWithDefaults(fetchDefaults);
123
+ const fetch = fetchWithDefaults(fetchDefaults);
157
124
 
158
- exports.default = enterpriseFetch;
125
+ exports.default = fetch;
126
+ exports.fetch = fetch;
159
127
  exports.fetchWithDefaults = fetchWithDefaults;
@@ -1,6 +1,5 @@
1
- import { FetchInit, Fetch } from './models';
2
- export * from './models';
3
- declare const fetchWithDefaults: (fetchDefaults?: FetchInit) => Fetch;
4
- export { fetchWithDefaults };
5
- declare const _default: Fetch;
6
- export default _default;
1
+ import { FetchInit, Fetch } from './models';
2
+ export * from './models';
3
+ export declare const fetchWithDefaults: (fetchDefaults?: FetchInit) => Fetch;
4
+ export declare const fetch: Fetch;
5
+ export default fetch;
@@ -1,128 +1,122 @@
1
- import fetch from 'cross-fetch';
2
- import promiseRetry from 'promise-retry';
3
1
  import AbortController from 'abort-controller';
4
- import to from 'await-to-js';
2
+ import { to } from 'await-to-js';
3
+ import promiseRetry from 'promise-retry';
5
4
 
6
5
  const fetchDefaults = {
7
- // The timeout to apply to requests that do not supply a timeout option
8
- timeout: 60 * 1000,
9
- // Retry policy for all fetch requests
10
- retry: {
11
- retries: 3,
12
- minTimeout: 400,
13
- factor: 2
14
- },
15
- // Do retry function to examine failures and apply custom retry logic
16
- // return true to retry the fetch call
17
- doRetry: async (attempt, res, {
18
- url,
19
- options
20
- }) => {
21
- // Get the retry policy from options or fetchDefaults
22
- const {
23
- retry = fetchDefaults.retry
24
- } = options;
25
-
26
- if (attempt <= retry.retries) {
27
- const counter = `${attempt}/${retry.retries}`; // Retry request on any network error,
28
- // or 4xx or 5xx status codes. No retry on 404
6
+ // The timeout to apply to requests that do not supply a timeout option
7
+ timeout: 60 * 1000,
8
+ // Retry policy for all fetch requests
9
+ retry: {
10
+ retries: 3,
11
+ minTimeout: 400,
12
+ factor: 2,
13
+ },
14
+ // Do retry function to examine failures and apply custom retry logic
15
+ // return true to retry the fetch call
16
+ doRetry: async (attempt, res, { url, options }) => {
17
+ // Get the retry policy from options or fetchDefaults
18
+ const { retry = fetchDefaults.retry } = options;
19
+ if (attempt <= retry.retries) {
20
+ const counter = `${attempt}/${retry.retries}`;
21
+ // Retry request on any network error,
22
+ // or 4xx or 5xx status codes. No retry on 404
23
+ if (!res.status || (res.status >= 400 && res.status !== 404)) {
24
+ if ('message' in res)
25
+ console.warn(`[fetch] Attempt ${counter} ${res.name}: ${res.message} ${url}`);
26
+ else
27
+ console.warn(`[fetch] Attempt ${counter} ${res.status}: ${res.statusText} ${url}`);
28
+ return true;
29
+ }
30
+ }
31
+ return false;
32
+ },
33
+ };
29
34
 
30
- if (!res.status || res.status >= 400 && res.status !== 404) {
31
- 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}`);
32
- return true;
33
- }
34
- }
35
+ const isClient = () => typeof window !== 'undefined';
35
36
 
36
- return false;
37
- }
37
+ const resolveFetch = async () => {
38
+ if (isClient())
39
+ return window.fetch;
40
+ if (typeof globalThis.fetch === 'function')
41
+ return globalThis.fetch;
42
+ const nodeFetch = await import('node-fetch');
43
+ // recast node-fetch to keep typescript happy
44
+ return nodeFetch.default;
38
45
  };
39
46
 
40
47
  // Setting http_proxy in env will inject a proxy agent header and disable certificate verification
41
48
  const proxyAgent = async () => {
42
- const proxyUri = typeof process !== 'undefined' && process.env.http_proxy || false;
43
-
44
- if (proxyUri) {
45
- // console.info(`Proxying via http_proxy: ${process.env.http_proxy}`);
46
- process.env.NODE_TLS_REJECT_UNAUTHORIZED = '0';
47
- const {
48
- HttpsProxyAgent
49
- } = await import('https-proxy-agent');
50
- return {
51
- agent: new HttpsProxyAgent(proxyUri)
52
- };
53
- }
54
-
55
- return {};
49
+ const proxyUri = (!isClient() && typeof process !== 'undefined' && process.env.http_proxy) ||
50
+ false;
51
+ if (proxyUri) {
52
+ // console.info(`Proxying via http_proxy: ${process.env.http_proxy}`);
53
+ process.env.NODE_TLS_REJECT_UNAUTHORIZED = '0';
54
+ // NOTE: This uses the HttpsProxyAgent class from https-proxy-agent v7.x
55
+ // Will break in v8+ where only a default factory function is exported
56
+ const { HttpsProxyAgent } = await import('https-proxy-agent');
57
+ return { agent: new HttpsProxyAgent(proxyUri) };
58
+ }
59
+ return {};
56
60
  };
57
61
 
58
- const isFunc = func => typeof func === 'function';
59
-
60
- const isClient = () => typeof window !== 'undefined';
61
-
62
- const thisFetch = isClient() ? window.fetch : fetch;
62
+ const isFunc = (func) => typeof func === 'function';
63
63
 
64
64
  const fetchWithDefaults = (fetchDefaults$1 = fetchDefaults) => {
65
- // Fetch function using hoisted defaults wrapped in a promise
66
- // retry function adhering to a default or supplied policy calling
67
- // a doRetry function on each failure that requires a boolean return
68
- const enterpriseFetch = async (url, init = {}) => {
69
- const fetchResponse = await promiseRetry(async (retry, attempt) => {
70
- const {
71
- retry: retryPolicy = fetchDefaults$1.retry,
72
- timeout: rtimeout = fetchDefaults$1.timeout,
73
- doRetry = fetchDefaults$1.doRetry || fetchDefaults.doRetry,
74
- ...options
75
- } = init;
76
- const timeoutMs = rtimeout || fetchDefaults$1.timeout || 60 * 1000; // Abort signal pattern
77
-
78
- const controller = new AbortController();
79
- const timeoutId = setTimeout(() => {
80
- controller.abort();
81
- }, timeoutMs); // Try fetching, wait for error or response
82
-
83
- const [error, response] = await to(thisFetch(url, { // Standard fetch options
84
- ...options,
85
- // Conditionally add a proxy agent to debug requests
86
- ...(await proxyAgent()),
87
- // The signal will recieve abort() after timeout elapsed
88
- signal: controller.signal
89
- }));
90
-
91
- if (error) {
92
- clearTimeout(timeoutId);
93
-
94
- if (isFunc(doRetry) && (await doRetry(attempt, error, {
95
- url,
96
- options: init
97
- }))) {
98
- retry(error);
99
- }
100
-
101
- throw error;
102
- }
103
-
104
- if (!response.ok) {
105
- clearTimeout(timeoutId);
106
-
107
- if (isFunc(doRetry) && (await doRetry(attempt, response, {
108
- url,
109
- options: init
110
- }))) {
111
- retry(response);
112
- }
113
-
114
- return response;
115
- }
116
-
117
- clearTimeout(timeoutId);
118
- return response;
119
- }, init.retry || fetchDefaults$1.retry);
120
- return fetchResponse;
121
- };
122
-
123
- return enterpriseFetch;
65
+ // Fetch function using hoisted defaults wrapped in a promise
66
+ // retry function adhering to a default or supplied policy calling
67
+ // a doRetry function on each failure that requires a boolean return
68
+ const enterpriseFetch = async (url, init = {}) => {
69
+ const thisFetch = await resolveFetch();
70
+ const fetchResponse = await promiseRetry(async (retry, attempt) => {
71
+ const {
72
+ // eslint-disable-next-line @typescript-eslint/no-unused-vars
73
+ retry: retryPolicy = fetchDefaults$1.retry, timeout: rtimeout = fetchDefaults$1.timeout, doRetry = fetchDefaults$1.doRetry || fetchDefaults.doRetry, ...options } = init;
74
+ const timeoutMs = rtimeout || fetchDefaults$1.timeout || 60 * 1000;
75
+ // Abort signal pattern
76
+ // Since v15.4.0 Node.js comes with AbortController out of the box
77
+ const controller = new AbortController();
78
+ const timeoutId = setTimeout(() => {
79
+ controller.abort();
80
+ }, timeoutMs);
81
+ // Try fetching, wait for error or response
82
+ const [error, response] = await to(thisFetch(url, {
83
+ // Standard fetch options
84
+ ...options,
85
+ // Conditionally add a proxy agent to debug requests
86
+ ...(await proxyAgent()),
87
+ // The signal will recieve abort() after timeout elapsed
88
+ signal: controller.signal,
89
+ }));
90
+ if (error) {
91
+ clearTimeout(timeoutId);
92
+ if (isFunc(doRetry) &&
93
+ (await doRetry(attempt, error, {
94
+ url: url.toString(),
95
+ options: init,
96
+ }))) {
97
+ retry(error);
98
+ }
99
+ throw error;
100
+ }
101
+ if (!response.ok) {
102
+ clearTimeout(timeoutId);
103
+ if (isFunc(doRetry) &&
104
+ (await doRetry(attempt, response, {
105
+ url: url.toString(),
106
+ options: init,
107
+ }))) {
108
+ retry(response);
109
+ }
110
+ return response;
111
+ }
112
+ clearTimeout(timeoutId);
113
+ return response;
114
+ }, init.retry || fetchDefaults$1.retry);
115
+ return fetchResponse;
116
+ };
117
+ return enterpriseFetch;
124
118
  };
125
- var enterpriseFetch = fetchWithDefaults(fetchDefaults);
119
+ const fetch = fetchWithDefaults(fetchDefaults);
126
120
 
127
- export default enterpriseFetch;
128
- export { fetchWithDefaults };
121
+ export { fetch as default, fetch, fetchWithDefaults };
122
+ //# sourceMappingURL=enterprise-fetch.esm.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"enterprise-fetch.esm.js","sources":["../src/fetch-defaults.ts","../src/util/client/is-client.ts","../src/util/resolve.ts","../src/util/server/proxy-agent.ts","../src/util/typeguards.ts","../src/enterprise-fetch.ts"],"sourcesContent":[null,null,null,null,null,null],"names":["fetchDefaults","FetchDefaults"],"mappings":";;;;AAEA,MAAM,aAAa,GAAG;;IAEpB,OAAO,EAAE,EAAE,GAAG,IAAI;;AAElB,IAAA,KAAK,EAAE;AACL,QAAA,OAAO,EAAE,CAAC;AACV,QAAA,UAAU,EAAE,GAAG;AACf,QAAA,MAAM,EAAE,CAAC;AACV,KAAA;;;AAGD,IAAA,OAAO,EAAE,OAAO,OAAO,EAAE,GAAG,EAAE,EAAE,GAAG,EAAE,OAAO,EAAE,KAAI;;QAEhD,MAAM,EAAE,KAAK,GAAG,aAAa,CAAC,KAAK,EAAE,GAAG,OAAO;AAC/C,QAAA,IAAI,OAAO,IAAI,KAAK,CAAC,OAAO,EAAE;YAC5B,MAAM,OAAO,GAAG,CAAA,EAAG,OAAO,IAAI,KAAK,CAAC,OAAO,CAAA,CAAE;;;AAI7C,YAAA,IAAI,CAAC,GAAG,CAAC,MAAM,KAAK,GAAG,CAAC,MAAM,IAAI,GAAG,IAAI,GAAG,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AAC,EACH;oBACA,KAAK,CAAC,KAAK,CAAC;gBACd;AACA,gBAAA,MAAM,KAAK;YACb;AAEA,YAAA,IAAI,CAAC,QAAQ,CAAC,EAAE,EAAE;gBAChB,YAAY,CAAC,SAAS,CAAC;gBACvB,IACE,MAAM,CAAC,OAAO,CAAC;AACf,qBAAC,MAAM,OAAO,CAAC,OAAO,EAAE,QAAQ,EAAE;AAChC,wBAAA,GAAG,EAAE,GAAG,CAAC,QAAQ,EAAE;AACnB,wBAAA,OAAO,EAAE,IAAI;qBACd,CAAC,CAAC,EACH;oBACA,KAAK,CAAC,QAAQ,CAAC;gBACjB;AACA,gBAAA,OAAO,QAAQ;YACjB;YAEA,YAAY,CAAC,SAAS,CAAC;AACvB,YAAA,OAAO,QAAQ;QACjB,CAAC,EAAE,IAAI,CAAC,KAAK,IAAIA,eAAa,CAAC,KAAK,CAAC;AAErC,QAAA,OAAO,aAAa;AACtB,IAAA,CAAC;AACD,IAAA,OAAO,eAAe;AACxB;MAEa,KAAK,GAAG,iBAAiB,CAACC,aAAa;;;;"}
@@ -1,3 +1,3 @@
1
- import { FetchInit } from './models/EnterpriseFetch';
2
- declare const fetchDefaults: FetchInit;
3
- export default fetchDefaults;
1
+ import { FetchInit } from './models/EnterpriseFetch';
2
+ declare const fetchDefaults: FetchInit;
3
+ export default fetchDefaults;
@@ -1,27 +1,27 @@
1
- export declare type AppError = (Error & ApiErrorResponse) | ApiErrorResponse;
2
- declare type InnerDataArray = [
3
- {
4
- field: string;
5
- message: string;
6
- }
7
- ];
8
- export declare type ApiErrorResponse = {
9
- name?: string;
10
- error?: {
11
- code: string;
12
- message: string;
13
- };
14
- code?: string;
15
- type?: string;
16
- timeout?: number;
17
- status?: number;
18
- statusText?: string;
19
- url?: string;
20
- data?: {
21
- logId: string;
22
- message: string;
23
- data: InnerDataArray;
24
- type: string;
25
- } | any;
26
- };
27
- export {};
1
+ export type AppError = (Error & ApiErrorResponse) | ApiErrorResponse;
2
+ type InnerDataArray = [
3
+ {
4
+ field: string;
5
+ message: string;
6
+ }
7
+ ];
8
+ export type ApiErrorResponse = {
9
+ name?: string;
10
+ error?: {
11
+ code: string;
12
+ message: string;
13
+ };
14
+ code?: string;
15
+ type?: string;
16
+ timeout?: number;
17
+ status?: number;
18
+ statusText?: string;
19
+ url?: string;
20
+ data?: {
21
+ logId: string;
22
+ message: string;
23
+ data: InnerDataArray;
24
+ type: string;
25
+ } | any;
26
+ };
27
+ export {};