vigor-fetch 1.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.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) [2024] [Uav1010 / Your Full Name]
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,59 @@
1
+ # vigor-fetch 🚀
2
+
3
+ **Vigor** is a lightweight, zero-dependency HTTP client designed for resilience. It intelligently handles server rate limits (429 Too Many Requests) and network instability with built-in retry mechanisms.
4
+
5
+ ## ✨ Features
6
+
7
+ - 🛡️ **Smart Resilience:** Automatically handles 429 errors by respecting `Retry-After` headers.
8
+ - 📈 **Exponential Backoff & Jitter:** Prevents server hammering by increasing wait times with random variation.
9
+ - ⚡ **Zero Dependencies:** Built using native Fetch API and AbortController.
10
+ - 🎯 **Fully Type-Safe:** Written in TypeScript for excellent developer experience and auto-completion.
11
+
12
+ ## 📦 Installation
13
+
14
+ npm install vigor-fetch
15
+
16
+ ## 🚀 Quick Start
17
+ ```import Vigor from 'vigor-fetch';
18
+
19
+ const api = new Vigor("https://api.example.com")
20
+ .path("/v1/data")
21
+ .method("POST")
22
+ .headers({ "X-API-KEY": "123" })
23
+ .query({ limit: 10, page: 1 })
24
+ .body({ name: "Uav1010" })
25
+ .count(5)
26
+ .max(5000)
27
+ .wait(10000)
28
+ .backoff(1.5)
29
+ .jitter(500)
30
+ .unretry([401, 404])
31
+ .parse("json")
32
+ .beforeRequest((opt) => {
33
+ console.log("Sending...");
34
+ })
35
+ .afterResponse((res) => {
36
+ return { ...res, timestamp: Date.now() };
37
+ });
38
+
39
+ const data = await api.request();```
40
+
41
+ ## 🛠️ API Reference
42
+
43
+ | Method | Type | Description |
44
+ | :--- | :--- | :--- |
45
+ | .path(string) | string | Appends path to origin. |
46
+ | .method(string) | string | Sets HTTP method (GET, POST, etc). |
47
+ | .query(object) | Record | Key-value pairs for URL search params. |
48
+ | .headers(object) | Record | Custom HTTP headers. |
49
+ | .body(any) | any | Request payload (auto-detects JSON). |
50
+ | .count(number) | number | Max retry attempts (Default: 5). |
51
+ | .max(ms) | number | Timeout for each fetch attempt (Default: 5000ms). |
52
+ | .wait(ms) | number | Max delay allowed. If exceeded, throws error. |
53
+ | .backoff(number) | number | Retry interval multiplier (Default: 1.3). |
54
+ | .jitter(ms) | number | Randomness to avoid thundering herd (Default: 500ms). |
55
+ | .unretry(codes[]) | number[] | Status codes that stop retrying (e.g. 404). |
56
+ | .original(bool) | boolean | If true, returns raw Response object. |
57
+ | .parse(type) | string | json, text, blob, arrayBuffer, formData. |
58
+ | .beforeRequest() | function | Async hook to modify options before fetch. |
59
+ | .afterResponse() | function | Async hook to transform data after fetch. |
@@ -0,0 +1,42 @@
1
+ interface VigorConfig {
2
+ path: string;
3
+ method: string | null;
4
+ offset: RequestInit;
5
+ headers: Record<string, string>;
6
+ body: any;
7
+ count: number;
8
+ max: number;
9
+ wait: number;
10
+ backoff: number;
11
+ unretry: Set<number>;
12
+ original: boolean;
13
+ parse: keyof Response | null;
14
+ beforeRequest: ((option: RequestInit) => Promise<RequestInit | void> | RequestInit | void)[];
15
+ afterResponse: ((res: any) => Promise<any> | any)[];
16
+ query: Record<string, string | number | boolean | null | undefined>;
17
+ jitter: number;
18
+ }
19
+ export default class Vigor {
20
+ private _origin;
21
+ private _config;
22
+ constructor(origin: string, config?: VigorConfig);
23
+ private _next;
24
+ path(arg: string): Vigor;
25
+ method(arg: string): Vigor;
26
+ offset(arg: RequestInit): Vigor;
27
+ headers(arg: Record<string, string>): Vigor;
28
+ body(arg: any): Vigor;
29
+ count(arg: number): Vigor;
30
+ max(arg: number): Vigor;
31
+ wait(arg: number): Vigor;
32
+ backoff(arg: number): Vigor;
33
+ unretry(arg: number[]): Vigor;
34
+ original(arg: boolean): Vigor;
35
+ beforeRequest(...arg: VigorConfig['beforeRequest']): Vigor;
36
+ afterResponse(...arg: VigorConfig['afterResponse']): Vigor;
37
+ parse(arg: VigorConfig['parse']): Vigor;
38
+ query(arg: VigorConfig['query']): Vigor;
39
+ jitter(arg: number): Vigor;
40
+ request<T = any>(): Promise<T>;
41
+ }
42
+ export {};
package/dist/index.js ADDED
@@ -0,0 +1,158 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ class VigorError extends Error {
4
+ constructor(text, { url, status, message, data = null }) {
5
+ super(text);
6
+ this.name = "VigorError";
7
+ this.url = url;
8
+ this.status = status;
9
+ this.message = message;
10
+ this.data = data;
11
+ }
12
+ }
13
+ class Vigor {
14
+ constructor(origin, config) {
15
+ this._origin = origin;
16
+ this._config = config || {
17
+ path: "",
18
+ method: null,
19
+ offset: {},
20
+ headers: {},
21
+ body: null,
22
+ count: 5,
23
+ max: 5000,
24
+ wait: 10000,
25
+ backoff: 1.3,
26
+ unretry: new Set([400, 401, 403, 404, 405, 413, 422]),
27
+ original: false,
28
+ parse: null,
29
+ beforeRequest: [],
30
+ afterResponse: [],
31
+ query: {},
32
+ jitter: 500
33
+ };
34
+ }
35
+ _next(changes) {
36
+ return new Vigor(this._origin, { ...this._config, ...changes });
37
+ }
38
+ path(arg) { return this._next({ path: arg }); }
39
+ method(arg) { return this._next({ method: arg }); }
40
+ offset(arg) { return this._next({ offset: arg }); }
41
+ headers(arg) { return this._next({ headers: arg }); }
42
+ body(arg) { return this._next({ body: arg }); }
43
+ count(arg) { return this._next({ count: arg }); }
44
+ max(arg) { return this._next({ max: arg }); }
45
+ wait(arg) { return this._next({ wait: arg }); }
46
+ backoff(arg) { return this._next({ backoff: arg }); }
47
+ unretry(arg) { return this._next({ unretry: new Set(arg) }); }
48
+ original(arg) { return this._next({ original: arg }); }
49
+ beforeRequest(...arg) {
50
+ return this._next({ beforeRequest: [...this._config.beforeRequest, ...arg] });
51
+ }
52
+ afterResponse(...arg) {
53
+ return this._next({ afterResponse: [...this._config.afterResponse, ...arg] });
54
+ }
55
+ parse(arg) { return this._next({ parse: arg }); }
56
+ query(arg) { return this._next({ query: { ...this._config.query, ...arg } }); }
57
+ jitter(arg) { return this._next({ jitter: arg }); }
58
+ async request() {
59
+ const { path, method, offset, headers, body, count, max, wait, backoff, unretry, original, beforeRequest, afterResponse, parse, query, jitter } = this._config;
60
+ if (!/^(https?|data|blob|file|about):\/\//.test(this._origin)) {
61
+ throw new VigorError(`[vigor] ${this._origin} >> Invalid Protocol`, {
62
+ url: this._origin, status: 0, message: "Invalid Protocol"
63
+ });
64
+ }
65
+ const urlObj = new URL(path.replace(/^\//, ""), this._origin + "/");
66
+ Object.entries(query).forEach(([key, value]) => {
67
+ if (value !== null && value !== undefined) {
68
+ urlObj.searchParams.append(key, String(value));
69
+ }
70
+ });
71
+ const url = urlObj.href;
72
+ const isJson = Array.isArray(body) || (!!body && Object.getPrototypeOf(body) === Object.prototype);
73
+ const waitTimeout = (time) => new Promise(resolve => setTimeout(resolve, time));
74
+ let option = {
75
+ ...offset,
76
+ method: method || (body ? "POST" : "GET"),
77
+ headers: {
78
+ ...(isJson && { "Content-Type": "application/json" }),
79
+ ...headers
80
+ },
81
+ ...(body && { body: isJson ? JSON.stringify(body) : body }),
82
+ };
83
+ for (const hook of beforeRequest) {
84
+ const modified = await hook(option);
85
+ option = { ...option, ...(modified || {}) };
86
+ }
87
+ let req;
88
+ for (let i = 0; i < count; i++) {
89
+ const controller = new AbortController();
90
+ const abort = setTimeout(() => controller.abort(), max);
91
+ option.signal = controller.signal;
92
+ try {
93
+ req = await fetch(url, option);
94
+ if (req.ok) {
95
+ clearTimeout(abort);
96
+ break;
97
+ }
98
+ }
99
+ catch (error) {
100
+ clearTimeout(abort);
101
+ if (i === count - 1)
102
+ throw new VigorError(`[vigor] ${url} >> Network Error`, {
103
+ url, status: 0, message: "Network Error"
104
+ });
105
+ }
106
+ finally {
107
+ clearTimeout(abort);
108
+ }
109
+ if (req) {
110
+ const status = req.status;
111
+ if (unretry.has(status))
112
+ throw new VigorError(`[vigor] ${url} >> Unretry ${status}`, {
113
+ url, status, message: "Unretry", data: status
114
+ });
115
+ const basic = Math.min(Math.pow(backoff, i) * 1000, wait) + Math.random() * jitter;
116
+ if (status === 429) {
117
+ const retryHeaders = ["retry-after", "ratelimit-reset", "x-ratelimit-reset", "x-retry-after", "x-amz-retry-after", "chrome-proxy-next-link"];
118
+ const retryAfter = retryHeaders.map(h => req?.headers.get(h)).find(Boolean);
119
+ const delay = (Number(retryAfter) * 1000 || (new Date(retryAfter).getTime() - Date.now()));
120
+ const parsedDelay = Math.max(0, delay) + Math.random() * jitter;
121
+ if (parsedDelay > wait)
122
+ throw new VigorError(`[vigor] ${url} >> Timeouted ${parsedDelay}ms`, {
123
+ url, status, message: "Timeouted", data: parsedDelay
124
+ });
125
+ await waitTimeout(parsedDelay || basic);
126
+ }
127
+ else {
128
+ await waitTimeout(basic);
129
+ }
130
+ }
131
+ }
132
+ if (!req || !req.ok)
133
+ throw new VigorError(`[vigor] ${url} >> Failed`, {
134
+ url, status: req?.status || 0, message: "Failed"
135
+ });
136
+ let res = await (async () => {
137
+ if (original)
138
+ return req;
139
+ if (parse)
140
+ return await req[parse]();
141
+ const contentType = req.headers.get("Content-Type") || "";
142
+ if (/json/.test(contentType))
143
+ return await req.json();
144
+ if (/(image|video|audio|pdf)/.test(contentType))
145
+ return await req.blob();
146
+ if (/octet-stream/.test(contentType))
147
+ return await req.arrayBuffer();
148
+ if (/form-data/.test(contentType))
149
+ return await req.formData();
150
+ return await req.text();
151
+ })();
152
+ for (const hook of afterResponse) {
153
+ res = await hook(res);
154
+ }
155
+ return res;
156
+ }
157
+ }
158
+ exports.default = Vigor;
package/package.json ADDED
@@ -0,0 +1,31 @@
1
+ {
2
+ "name": "vigor-fetch",
3
+ "version": "1.0.0",
4
+ "description": "Smart, zero-dependency HTTP client with self-healing retries for rate-limited servers.",
5
+ "main": "dist/index.js",
6
+ "module": "dist/index.mjs",
7
+ "types": "dist/index.d.ts",
8
+ "files": [
9
+ "dist"
10
+ ],
11
+ "scripts": {
12
+ "build": "tsc",
13
+ "prepublishOnly": "npm run build"
14
+ },
15
+ "keywords": [
16
+ "fetch",
17
+ "retry",
18
+ "backoff",
19
+ "ratelimit",
20
+ "typescript",
21
+ "zero-dependency"
22
+ ],
23
+ "author": "Your Name",
24
+ "license": "MIT",
25
+ "devDependencies": {
26
+ "typescript": "^5.9.3"
27
+ },
28
+ "engines": {
29
+ "node": ">=18.0.0"
30
+ }
31
+ }