rate-limited-fetch 0.2.0 → 0.3.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.
package/README.md CHANGED
@@ -46,7 +46,7 @@ The returned function is `typeof fetch`, so you can pass it to any client that a
46
46
 
47
47
  ## Custom detectors
48
48
 
49
- A detector receives the response and the request, and returns `undefined` when the response is not rate limited, or `{ reason, waitMs? }` when it is. It may be async. When `waitMs` is 0 or missing, `defaultRetryAfterMs` is used.
49
+ A detector receives the response, the request and the attempt number (1 for the first response, 2 for the first retry, and so on), and returns `undefined` when the response is not rate limited, or `{ reason, waitMs? }` when it is. It may be async. When `waitMs` is 0 or missing, `defaultRetryAfterMs` is used.
50
50
 
51
51
  ```ts
52
52
  import { detect429, getRateLimitedFetch, type DetectThrottle } from 'rate-limited-fetch';
@@ -67,6 +67,7 @@ const apiFetch = getRateLimitedFetch({ limit: 4, detect });
67
67
  - **Never consume `res`**: read `res.clone()`, otherwise the caller receives a used body.
68
68
  - The detector runs while the request still holds its slot, so the pause is set before any queued request can start. Keep it fast.
69
69
  - If the detector throws, the error is passed to the caller.
70
+ - `attempt` lets a detector back off, for example doubling the wait when the API does not send `Retry-After`.
70
71
  - Passing `detect` replaces `detect429`. Call it from your detector to keep handling 429.
71
72
 
72
73
  ## How it works
package/dist/index.cjs CHANGED
@@ -1 +1 @@
1
- Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});function e(e,t=Date.now()){if(!e||!e.trim())return;let n=Number(e);if(!isNaN(n))return n>=0?Math.ceil(n*1e3):void 0;let r=Date.parse(e);return isNaN(r)?void 0:Math.max(0,r-t)}const t=t=>t.status===429?{reason:`429`,waitMs:e(t.headers.get(`retry-after`))}:void 0,n=1e3;function r(e=1/0,t=1/0){let r=[],i=[],a=0,o=0,s,c=()=>{for(;r.length&&a<e;){let e=Date.now();for(;i.length&&i[0]<=e-n;)i.shift();let l=o>e?o:i.length>=t?i[0]+n:0;if(l){clearTimeout(s),s=setTimeout(c,l-e);return}t<1/0&&i.push(e),a++,r.shift()()}};return{schedule:(e,t,n)=>new Promise((i,o)=>{if(t?.aborted)return o(t.reason);let s=()=>{r.splice(r.indexOf(u),1),o(t.reason)},l=e=>t=>{a--,e(t),c()},u=()=>{t?.removeEventListener(`abort`,s),e().then(l(i),l(o))};t?.addEventListener(`abort`,s),n?r.unshift(u):r.push(u),c()}),pause:e=>{o=Math.max(o,Date.now()+e)}}}exports.detect429=t,exports.getRateLimitedFetch=function(e={}){let{limit:n,throttle:i,fetch:a,detect:o=t,maxRetries:s=5,defaultRetryAfterMs:c=1e3,onThrottle:l}=e,u=r(n,i),d=e=>a?a(e):globalThis.fetch(e);return async(e,t)=>{let n=new Request(e,t);for(let e=1;;e++){let[t,r]=await u.schedule(async()=>{let t=await d(n.clone()),r=await o(t,n);if(!r)return[t,void 0];let i=r.waitMs||c;return u.pause(i),[t,{...r,waitMs:i,url:n.url,attempt:e}]},n.signal,e>1);if(!r||e>s)return t;l?.(r),t.body?.cancel().catch(()=>{})}}},exports.parseRetryAfter=e;
1
+ Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});function e(e,t=Date.now()){if(!e||!e.trim())return;let n=Number(e);if(!isNaN(n))return n>=0?Math.ceil(n*1e3):void 0;let r=Date.parse(e);return isNaN(r)?void 0:Math.max(0,r-t)}const t=t=>t.status===429?{reason:`429`,waitMs:e(t.headers.get(`retry-after`))}:void 0,n=1e3;function r(e=1/0,t=1/0){let r=[],i=[],a=0,o=0,s,c=()=>{for(;r.length&&a<e;){let e=Date.now();for(;i.length&&i[0]<=e-n;)i.shift();let l=o>e?o:i.length>=t?i[0]+n:0;if(l){clearTimeout(s),s=setTimeout(c,l-e);return}t<1/0&&i.push(e),a++,r.shift()()}};return{schedule:(e,t,n)=>new Promise((i,o)=>{if(t?.aborted)return o(t.reason);let s=()=>{r.splice(r.indexOf(u),1),o(t.reason)},l=e=>t=>{a--,e(t),c()},u=()=>{t?.removeEventListener(`abort`,s),e().then(l(i),l(o))};t?.addEventListener(`abort`,s),n?r.unshift(u):r.push(u),c()}),pause:e=>{o=Math.max(o,Date.now()+e)}}}exports.detect429=t,exports.getRateLimitedFetch=function(e={}){let{limit:n,throttle:i,fetch:a,detect:o=t,maxRetries:s=5,defaultRetryAfterMs:c=1e3,onThrottle:l}=e,u=r(n,i),d=e=>a?a(e):globalThis.fetch(e);return async(e,t)=>{let n=new Request(e,t);for(let e=1;;e++){let[t,r]=await u.schedule(async()=>{let t=await d(n.clone()),r=await o(t,n,e);if(!r)return[t,void 0];let i=r.waitMs||c;return u.pause(i),[t,{...r,waitMs:i,url:n.url,attempt:e}]},n.signal,e>1);if(!r||e>s)return t;l?.(r),t.body?.cancel().catch(()=>{})}}},exports.parseRetryAfter=e;
package/dist/index.d.cts CHANGED
@@ -7,9 +7,9 @@ interface Throttled {
7
7
  /**
8
8
  * Tells whether a response was rate limited. Returns `undefined` when it was not.
9
9
  * It runs while the request still holds its slot, so keep it fast, and it must never consume
10
- * `res`: read `res.clone()` instead.
10
+ * `res`: read `res.clone()` instead. `attempt` is 1 for the first response, 2 for the first retry, ...
11
11
  */
12
- type DetectThrottle = (res: Response, req: Request) => Throttled | undefined | Promise<Throttled | undefined>;
12
+ type DetectThrottle = (res: Response, req: Request, attempt: number) => Throttled | undefined | Promise<Throttled | undefined>;
13
13
  interface ThrottleInfo extends Throttled {
14
14
  url: string;
15
15
  /** 1 for the first retry, 2 for the second, ... */
package/dist/index.d.ts CHANGED
@@ -7,9 +7,9 @@ interface Throttled {
7
7
  /**
8
8
  * Tells whether a response was rate limited. Returns `undefined` when it was not.
9
9
  * It runs while the request still holds its slot, so keep it fast, and it must never consume
10
- * `res`: read `res.clone()` instead.
10
+ * `res`: read `res.clone()` instead. `attempt` is 1 for the first response, 2 for the first retry, ...
11
11
  */
12
- type DetectThrottle = (res: Response, req: Request) => Throttled | undefined | Promise<Throttled | undefined>;
12
+ type DetectThrottle = (res: Response, req: Request, attempt: number) => Throttled | undefined | Promise<Throttled | undefined>;
13
13
  interface ThrottleInfo extends Throttled {
14
14
  url: string;
15
15
  /** 1 for the first retry, 2 for the second, ... */
package/dist/index.js CHANGED
@@ -1 +1 @@
1
- function e(e,t=Date.now()){if(!e||!e.trim())return;let n=Number(e);if(!isNaN(n))return n>=0?Math.ceil(n*1e3):void 0;let r=Date.parse(e);return isNaN(r)?void 0:Math.max(0,r-t)}const t=t=>t.status===429?{reason:`429`,waitMs:e(t.headers.get(`retry-after`))}:void 0,n=1e3;function r(e=1/0,t=1/0){let r=[],i=[],a=0,o=0,s,c=()=>{for(;r.length&&a<e;){let e=Date.now();for(;i.length&&i[0]<=e-n;)i.shift();let l=o>e?o:i.length>=t?i[0]+n:0;if(l){clearTimeout(s),s=setTimeout(c,l-e);return}t<1/0&&i.push(e),a++,r.shift()()}};return{schedule:(e,t,n)=>new Promise((i,o)=>{if(t?.aborted)return o(t.reason);let s=()=>{r.splice(r.indexOf(u),1),o(t.reason)},l=e=>t=>{a--,e(t),c()},u=()=>{t?.removeEventListener(`abort`,s),e().then(l(i),l(o))};t?.addEventListener(`abort`,s),n?r.unshift(u):r.push(u),c()}),pause:e=>{o=Math.max(o,Date.now()+e)}}}function i(e={}){let{limit:n,throttle:i,fetch:a,detect:o=t,maxRetries:s=5,defaultRetryAfterMs:c=1e3,onThrottle:l}=e,u=r(n,i),d=e=>a?a(e):globalThis.fetch(e);return async(e,t)=>{let n=new Request(e,t);for(let e=1;;e++){let[t,r]=await u.schedule(async()=>{let t=await d(n.clone()),r=await o(t,n);if(!r)return[t,void 0];let i=r.waitMs||c;return u.pause(i),[t,{...r,waitMs:i,url:n.url,attempt:e}]},n.signal,e>1);if(!r||e>s)return t;l?.(r),t.body?.cancel().catch(()=>{})}}}export{t as detect429,i as getRateLimitedFetch,e as parseRetryAfter};
1
+ function e(e,t=Date.now()){if(!e||!e.trim())return;let n=Number(e);if(!isNaN(n))return n>=0?Math.ceil(n*1e3):void 0;let r=Date.parse(e);return isNaN(r)?void 0:Math.max(0,r-t)}const t=t=>t.status===429?{reason:`429`,waitMs:e(t.headers.get(`retry-after`))}:void 0,n=1e3;function r(e=1/0,t=1/0){let r=[],i=[],a=0,o=0,s,c=()=>{for(;r.length&&a<e;){let e=Date.now();for(;i.length&&i[0]<=e-n;)i.shift();let l=o>e?o:i.length>=t?i[0]+n:0;if(l){clearTimeout(s),s=setTimeout(c,l-e);return}t<1/0&&i.push(e),a++,r.shift()()}};return{schedule:(e,t,n)=>new Promise((i,o)=>{if(t?.aborted)return o(t.reason);let s=()=>{r.splice(r.indexOf(u),1),o(t.reason)},l=e=>t=>{a--,e(t),c()},u=()=>{t?.removeEventListener(`abort`,s),e().then(l(i),l(o))};t?.addEventListener(`abort`,s),n?r.unshift(u):r.push(u),c()}),pause:e=>{o=Math.max(o,Date.now()+e)}}}function i(e={}){let{limit:n,throttle:i,fetch:a,detect:o=t,maxRetries:s=5,defaultRetryAfterMs:c=1e3,onThrottle:l}=e,u=r(n,i),d=e=>a?a(e):globalThis.fetch(e);return async(e,t)=>{let n=new Request(e,t);for(let e=1;;e++){let[t,r]=await u.schedule(async()=>{let t=await d(n.clone()),r=await o(t,n,e);if(!r)return[t,void 0];let i=r.waitMs||c;return u.pause(i),[t,{...r,waitMs:i,url:n.url,attempt:e}]},n.signal,e>1);if(!r||e>s)return t;l?.(r),t.body?.cancel().catch(()=>{})}}}export{t as detect429,i as getRateLimitedFetch,e as parseRetryAfter};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "rate-limited-fetch",
3
- "version": "0.2.0",
3
+ "version": "0.3.0",
4
4
  "description": "Tiny rate-limited fetch: concurrency limit, per-second throttle, automatic wait and retry on rate limits (HTTP 429 with Retry-After by default, or your own detector). Works in browsers, Node and browser extensions.",
5
5
  "license": "MIT",
6
6
  "author": "JEF S.r.l.",