vigor-fetch 1.0.11 → 1.0.13
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 +249 -110
- package/dist/index.d.ts +103 -58
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +472 -155
- package/dist/index.mjs +460 -155
- package/package.json +1 -1
package/dist/index.mjs
CHANGED
|
@@ -1,197 +1,502 @@
|
|
|
1
1
|
class VigorError extends Error {
|
|
2
|
-
constructor(text,
|
|
3
|
-
|
|
4
|
-
|
|
5
|
-
this.
|
|
6
|
-
this.status = status;
|
|
7
|
-
this.message = message || text;
|
|
2
|
+
constructor(text, options) {
|
|
3
|
+
const { type, data, status, response, message, origin } = options;
|
|
4
|
+
super(message || `[VigorError] ${text}`);
|
|
5
|
+
this.name = this.constructor.name;
|
|
8
6
|
this.data = data;
|
|
7
|
+
this.type = type;
|
|
8
|
+
this.status = status;
|
|
9
|
+
this.response = response;
|
|
10
|
+
this.origin = origin;
|
|
11
|
+
if (Error.captureStackTrace) {
|
|
12
|
+
Error.captureStackTrace(this, this.constructor);
|
|
13
|
+
}
|
|
9
14
|
}
|
|
10
15
|
}
|
|
11
|
-
class
|
|
12
|
-
constructor(
|
|
13
|
-
|
|
14
|
-
this.
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
16
|
+
class VigorRetryError extends VigorError {
|
|
17
|
+
constructor(text, options) {
|
|
18
|
+
super(text, options);
|
|
19
|
+
this.message = options.message || `[VigorRetryError] ${text}`;
|
|
20
|
+
}
|
|
21
|
+
}
|
|
22
|
+
class VigorParseError extends VigorError {
|
|
23
|
+
constructor(text, options) {
|
|
24
|
+
super(text, options);
|
|
25
|
+
this.message = options.message || `[VigorParseError] ${text}`;
|
|
26
|
+
}
|
|
27
|
+
}
|
|
28
|
+
class VigorFetchError extends VigorError {
|
|
29
|
+
constructor(text, options) {
|
|
30
|
+
super(text, options);
|
|
31
|
+
this.message = options.message || `[VigorFetchError] ${text}`;
|
|
32
|
+
}
|
|
33
|
+
}
|
|
34
|
+
class VigorAllError extends VigorError {
|
|
35
|
+
constructor(text, options) {
|
|
36
|
+
super(text, options);
|
|
37
|
+
this.message = options.message || `[VigorFetchError] ${text}`;
|
|
38
|
+
}
|
|
39
|
+
}
|
|
40
|
+
/**
|
|
41
|
+
* VigorRetry
|
|
42
|
+
*/
|
|
43
|
+
class VigorRetry {
|
|
44
|
+
constructor(target, args = [], config = {}) {
|
|
45
|
+
this._target = target;
|
|
46
|
+
this._args = args;
|
|
47
|
+
this._config = {
|
|
48
|
+
retry: {
|
|
49
|
+
count: 5, max: 10000, backoff: 1.3, baseDelay: 1000, jitter: 500
|
|
50
|
+
},
|
|
51
|
+
interceptors: {
|
|
52
|
+
before: [], after: [], onRetry: [], onError: []
|
|
53
|
+
},
|
|
54
|
+
...config
|
|
21
55
|
};
|
|
22
56
|
}
|
|
23
57
|
_next(changes) {
|
|
24
|
-
return new
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
backoff(
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
beforeRequest(...arg) { return this._next({ beforeRequest: [...this._config.beforeRequest, ...arg] }); }
|
|
42
|
-
afterRequest(...arg) { return this._next({ afterRequest: [...this._config.afterRequest, ...arg] }); }
|
|
43
|
-
beforeResponse(...arg) { return this._next({ beforeResponse: [...this._config.beforeResponse, ...arg] }); }
|
|
44
|
-
afterResponse(...arg) { return this._next({ afterResponse: [...this._config.afterResponse, ...arg] }); }
|
|
45
|
-
onError(...arg) { return this._next({ onError: [...this._config.onError, ...arg] }); }
|
|
58
|
+
return new this.constructor(this._target, this._args, {
|
|
59
|
+
...this._config,
|
|
60
|
+
...changes,
|
|
61
|
+
retry: { ...this._config.retry, ...(changes.retry || {}) },
|
|
62
|
+
interceptors: { ...this._config.interceptors, ...(changes.interceptors || {}) }
|
|
63
|
+
});
|
|
64
|
+
}
|
|
65
|
+
args(...args) { return new this.constructor(this._target, args, this._config); }
|
|
66
|
+
count(int) { return this._next({ retry: { count: int } }); }
|
|
67
|
+
max(ms) { return this._next({ retry: { max: ms } }); }
|
|
68
|
+
backoff(ms) { return this._next({ retry: { backoff: ms } }); }
|
|
69
|
+
baseDelay(ms) { return this._next({ retry: { baseDelay: ms } }); }
|
|
70
|
+
jitter(ms) { return this._next({ retry: { jitter: ms } }); }
|
|
71
|
+
before(...func) { return this._next({ interceptors: { before: [...this._config.interceptors.before, ...func.flat()] } }); }
|
|
72
|
+
onRetry(...func) { return this._next({ interceptors: { onRetry: [...this._config.interceptors.onRetry, ...func.flat()] } }); }
|
|
73
|
+
after(...func) { return this._next({ interceptors: { after: [...this._config.interceptors.after, ...func.flat()] } }); }
|
|
74
|
+
onError(...func) { return this._next({ interceptors: { onError: [...this._config.interceptors.onError, ...func.flat()] } }); }
|
|
46
75
|
async request() {
|
|
47
|
-
const
|
|
76
|
+
const [target, args, config] = [this._target, this._args, this._config];
|
|
77
|
+
const { retry: { count, max, backoff, baseDelay, jitter }, interceptors: { before, after, onRetry, onError } } = config;
|
|
78
|
+
let ctx = { target, args, attempt: 0, result: null, error: null, try: true, retry: true, max, backoff, jitter, wait: 0, baseDelay };
|
|
48
79
|
try {
|
|
49
|
-
if (
|
|
50
|
-
throw new
|
|
51
|
-
|
|
52
|
-
});
|
|
53
|
-
}
|
|
54
|
-
const originBase = this._origin.endsWith('/') ? this._origin : this._origin + '/';
|
|
55
|
-
const cleanPath = path.replace(/^\//, "");
|
|
56
|
-
const urlObj = cleanPath
|
|
57
|
-
? new URL(cleanPath, originBase)
|
|
58
|
-
: new URL(this._origin);
|
|
59
|
-
Object.entries(query).forEach(([key, value]) => {
|
|
60
|
-
if (value !== null && value !== undefined)
|
|
61
|
-
urlObj.searchParams.append(key, String(value));
|
|
62
|
-
});
|
|
63
|
-
const url = urlObj.href;
|
|
64
|
-
const isJson = Array.isArray(body) || (!!body && Object.getPrototypeOf(body) === Object.prototype);
|
|
65
|
-
const waitTimeout = (time) => new Promise(resolve => setTimeout(resolve, time));
|
|
66
|
-
let option = {
|
|
67
|
-
...offset,
|
|
68
|
-
method: method || (body ? "POST" : "GET"),
|
|
69
|
-
headers: { ...(isJson && { "Content-Type": "application/json" }), ...headers },
|
|
70
|
-
...(body && { body: isJson ? JSON.stringify(body) : body }),
|
|
71
|
-
};
|
|
72
|
-
for (const hook of beforeRequest) {
|
|
73
|
-
const modified = await hook(option);
|
|
74
|
-
if (modified)
|
|
75
|
-
option = { ...option, ...modified };
|
|
76
|
-
}
|
|
77
|
-
let req;
|
|
80
|
+
if (typeof target !== 'function')
|
|
81
|
+
throw new VigorRetryError('target is not a function', { type: "not a function", data: "target" });
|
|
82
|
+
const sleep = (ms) => new Promise(resolve => setTimeout(resolve, ms));
|
|
78
83
|
for (let i = 0; i < count; i++) {
|
|
79
|
-
|
|
80
|
-
|
|
81
|
-
|
|
84
|
+
ctx.attempt = i + 1;
|
|
85
|
+
ctx.error = null;
|
|
86
|
+
ctx.result = null;
|
|
87
|
+
ctx.retry ?? (ctx.retry = true);
|
|
88
|
+
for (const func of before) {
|
|
89
|
+
if (typeof func !== 'function')
|
|
90
|
+
throw new VigorRetryError('Interceptor<before> is not a function', { type: "not a function", data: "before" });
|
|
91
|
+
const next = await func(ctx, ctx.args);
|
|
92
|
+
if (next !== undefined && typeof next === 'object' && !Array.isArray(next))
|
|
93
|
+
ctx = { ...ctx, ...next };
|
|
94
|
+
}
|
|
95
|
+
if (!ctx.try)
|
|
96
|
+
break;
|
|
82
97
|
try {
|
|
83
|
-
|
|
84
|
-
for (const
|
|
85
|
-
|
|
86
|
-
|
|
87
|
-
|
|
88
|
-
|
|
89
|
-
|
|
98
|
+
ctx.result = await ctx.target(...ctx.args);
|
|
99
|
+
for (const func of after) {
|
|
100
|
+
if (typeof func !== 'function')
|
|
101
|
+
throw new VigorRetryError('Interceptor<after> is not a function', { type: "not a function", data: "after" });
|
|
102
|
+
const next = await func(ctx, ctx.result);
|
|
103
|
+
if (next !== undefined && typeof next === 'object' && !Array.isArray(next))
|
|
104
|
+
ctx = { ...ctx, ...next };
|
|
90
105
|
}
|
|
106
|
+
if (ctx.error instanceof Error)
|
|
107
|
+
throw ctx.error;
|
|
108
|
+
if (ctx.result instanceof Error)
|
|
109
|
+
throw ctx.result;
|
|
110
|
+
return ctx.result;
|
|
91
111
|
}
|
|
92
112
|
catch (error) {
|
|
93
|
-
|
|
94
|
-
|
|
95
|
-
|
|
96
|
-
|
|
97
|
-
|
|
98
|
-
|
|
99
|
-
|
|
100
|
-
|
|
101
|
-
const status = req.status;
|
|
102
|
-
if (unretry.has(status))
|
|
103
|
-
throw new VigorError(`[vigor] ${url} >> Unretry ${status}`, { url, status, message: "Unretry", data: status });
|
|
104
|
-
const basic = Math.min(Math.pow(backoff, i) * 1000, wait) + Math.random() * jitter;
|
|
105
|
-
if (status === 429) {
|
|
106
|
-
const rHeader = retryHeader.map(h => req?.headers.get(h)).find(Boolean);
|
|
107
|
-
const delay = rHeader ? (isNaN(Number(rHeader)) ? new Date(rHeader).getTime() - Date.now() : Number(rHeader) * 1000) : 0;
|
|
108
|
-
const parsedDelay = Math.max(0, delay) + Math.random() * jitter;
|
|
109
|
-
if (parsedDelay > wait)
|
|
110
|
-
throw new VigorError(`[vigor] ${url} >> Timeouted ${parsedDelay}ms`, { url, status, message: "Timeouted", data: parsedDelay });
|
|
111
|
-
await waitTimeout(parsedDelay || basic);
|
|
112
|
-
}
|
|
113
|
-
else {
|
|
114
|
-
await waitTimeout(basic);
|
|
113
|
+
ctx.error = error;
|
|
114
|
+
ctx.wait = Math.min(Math.pow(ctx.backoff, ctx.attempt - 1) * ctx.baseDelay, max) + ctx.jitter;
|
|
115
|
+
for (const func of onRetry) {
|
|
116
|
+
if (typeof func !== 'function')
|
|
117
|
+
throw new VigorRetryError('Interceptor<onRetry> is not a function', { type: "not a function", data: "retry" });
|
|
118
|
+
const next = await func(ctx, ctx.error);
|
|
119
|
+
if (next !== undefined && typeof next === 'object' && !Array.isArray(next))
|
|
120
|
+
ctx = { ...ctx, ...next };
|
|
115
121
|
}
|
|
122
|
+
if (!ctx.retry)
|
|
123
|
+
break;
|
|
124
|
+
await sleep(ctx.wait);
|
|
116
125
|
}
|
|
117
126
|
}
|
|
118
|
-
if (
|
|
119
|
-
throw
|
|
120
|
-
|
|
121
|
-
|
|
122
|
-
|
|
127
|
+
if (ctx.error instanceof Error)
|
|
128
|
+
throw ctx.error;
|
|
129
|
+
if (ctx.result instanceof Error)
|
|
130
|
+
throw ctx.result;
|
|
131
|
+
}
|
|
132
|
+
catch (mainError) {
|
|
133
|
+
ctx.mainError = mainError;
|
|
134
|
+
for (const func of onError) {
|
|
135
|
+
if (typeof func !== 'function')
|
|
136
|
+
throw new VigorRetryError('Interceptor<onError> is not a function', { type: "not a function", data: "onError" });
|
|
137
|
+
const next = await func(ctx, ctx.mainError);
|
|
138
|
+
if (next !== undefined && typeof next === 'object' && !Array.isArray(next))
|
|
139
|
+
ctx = { ...ctx, ...next };
|
|
140
|
+
}
|
|
141
|
+
if (ctx.mainError instanceof Error)
|
|
142
|
+
throw ctx.mainError;
|
|
143
|
+
return ctx.mainError;
|
|
144
|
+
}
|
|
145
|
+
return ctx.result;
|
|
146
|
+
}
|
|
147
|
+
}
|
|
148
|
+
/**
|
|
149
|
+
* VigorParse
|
|
150
|
+
*/
|
|
151
|
+
class VigorParse {
|
|
152
|
+
constructor(response, config = {}) {
|
|
153
|
+
this._response = response;
|
|
154
|
+
this._config = {
|
|
155
|
+
settings: { original: false, parse: null },
|
|
156
|
+
interceptors: { before: [], after: [], onError: [] },
|
|
157
|
+
...config,
|
|
158
|
+
};
|
|
159
|
+
}
|
|
160
|
+
_next(changes) {
|
|
161
|
+
return new this.constructor(this._response, {
|
|
162
|
+
...this._config,
|
|
163
|
+
...changes,
|
|
164
|
+
settings: { ...this._config.settings, ...(changes.settings || {}) },
|
|
165
|
+
interceptors: { ...this._config.interceptors, ...(changes.interceptors || {}) }
|
|
166
|
+
});
|
|
167
|
+
}
|
|
168
|
+
original(bool) { return this._next({ settings: { original: bool } }); }
|
|
169
|
+
type(str) { return this._next({ settings: { parse: str } }); }
|
|
170
|
+
before(...func) { return this._next({ interceptors: { before: [...this._config.interceptors.before, ...func.flat()] } }); }
|
|
171
|
+
after(...func) { return this._next({ interceptors: { after: [...this._config.interceptors.after, ...func.flat()] } }); }
|
|
172
|
+
onError(...func) { return this._next({ interceptors: { onError: [...this._config.interceptors.onError, ...func.flat()] } }); }
|
|
173
|
+
async request() {
|
|
174
|
+
const { settings: { original, parse }, interceptors: { before, after, onError } } = this._config;
|
|
175
|
+
let ctx = { original, parse, result: null, response: this._response };
|
|
176
|
+
try {
|
|
177
|
+
for (const func of before) {
|
|
178
|
+
if (typeof func !== 'function')
|
|
179
|
+
throw new VigorParseError('Interceptor<before> is not a function', { type: "not a function", data: "before" });
|
|
180
|
+
const next = await func(ctx, ctx.response);
|
|
181
|
+
if (next !== undefined && typeof next === 'object' && !Array.isArray(next))
|
|
182
|
+
ctx = { ...ctx, ...next };
|
|
123
183
|
}
|
|
124
|
-
|
|
125
|
-
|
|
126
|
-
|
|
127
|
-
if (
|
|
128
|
-
|
|
129
|
-
|
|
130
|
-
|
|
131
|
-
return
|
|
184
|
+
ctx.result = await (async (response) => {
|
|
185
|
+
if (ctx.original)
|
|
186
|
+
return response;
|
|
187
|
+
if (ctx.parse) {
|
|
188
|
+
const method = response[ctx.parse];
|
|
189
|
+
if (!method || typeof method !== 'function')
|
|
190
|
+
throw new VigorParseError(`Invalid method such as ${ctx.parse}`, { type: "Invalid method", data: ctx.parse });
|
|
191
|
+
return await method.call(response);
|
|
132
192
|
}
|
|
133
|
-
const contentType =
|
|
193
|
+
const contentType = response.headers.get("Content-Type") || "";
|
|
134
194
|
if (/json/.test(contentType))
|
|
135
|
-
return await
|
|
195
|
+
return await response.json();
|
|
196
|
+
if (/multipart\/form-data/.test(contentType))
|
|
197
|
+
return await response.formData();
|
|
198
|
+
if (/octet-stream/.test(contentType))
|
|
199
|
+
return await response.arrayBuffer();
|
|
136
200
|
if (/(image|video|audio|pdf)/.test(contentType))
|
|
137
|
-
return await
|
|
138
|
-
return await
|
|
139
|
-
})();
|
|
140
|
-
for (const
|
|
141
|
-
|
|
201
|
+
return await response.blob();
|
|
202
|
+
return await response.text();
|
|
203
|
+
})(ctx.response);
|
|
204
|
+
for (const func of after) {
|
|
205
|
+
if (typeof func !== 'function')
|
|
206
|
+
throw new VigorParseError('Interceptor<after> is not a function', { type: "not a function", data: "after" });
|
|
207
|
+
const next = await func(ctx, ctx.result);
|
|
208
|
+
if (next !== undefined && typeof next === 'object' && !Array.isArray(next))
|
|
209
|
+
ctx = { ...ctx, ...next };
|
|
210
|
+
}
|
|
211
|
+
if (ctx.result instanceof Error)
|
|
212
|
+
throw ctx.result;
|
|
213
|
+
return ctx.result;
|
|
214
|
+
}
|
|
215
|
+
catch (mainError) {
|
|
216
|
+
ctx.mainError = mainError;
|
|
217
|
+
for (const func of onError) {
|
|
218
|
+
if (typeof func !== 'function')
|
|
219
|
+
throw new VigorParseError('Interceptor<onError> is not a function', { type: "not a function", data: "onError" });
|
|
220
|
+
const next = await func(ctx, ctx.mainError);
|
|
221
|
+
if (next !== undefined && typeof next === 'object' && !Array.isArray(next))
|
|
222
|
+
ctx = { ...ctx, ...next };
|
|
142
223
|
}
|
|
143
|
-
|
|
224
|
+
if (ctx.mainError instanceof Error)
|
|
225
|
+
throw ctx.mainError;
|
|
226
|
+
return ctx.mainError;
|
|
144
227
|
}
|
|
145
|
-
|
|
146
|
-
|
|
147
|
-
|
|
148
|
-
|
|
149
|
-
|
|
150
|
-
|
|
151
|
-
|
|
228
|
+
}
|
|
229
|
+
}
|
|
230
|
+
/**
|
|
231
|
+
* VigorFetch
|
|
232
|
+
*/
|
|
233
|
+
class VigorFetch {
|
|
234
|
+
constructor(origin = "", config = {}) {
|
|
235
|
+
this._config = {
|
|
236
|
+
request: {
|
|
237
|
+
origin, path: "", query: {},
|
|
238
|
+
method: "", headers: {}, body: null, offset: {}
|
|
239
|
+
},
|
|
240
|
+
retry: {
|
|
241
|
+
limit: 10000,
|
|
242
|
+
retryHeaders: ["retry-after", "ratelimit-reset", "x-ratelimit-reset", "x-retry-after", "x-amz-retry-after", "chrome-proxy-next-link"],
|
|
243
|
+
unretry: new Set([400, 401, 403, 404, 406, 409, 410, 411, 413, 414, 415, 422]),
|
|
244
|
+
},
|
|
245
|
+
response: { retryConfig: undefined, parseConfig: undefined },
|
|
246
|
+
interceptors: { before: [], after: [], onError: [], result: [] },
|
|
247
|
+
...config
|
|
248
|
+
};
|
|
249
|
+
}
|
|
250
|
+
_next(changes) {
|
|
251
|
+
return new this.constructor(this._config.request.origin, {
|
|
252
|
+
...this._config,
|
|
253
|
+
...changes,
|
|
254
|
+
request: { ...this._config.request, ...(changes.request || {}) },
|
|
255
|
+
retry: { ...this._config.retry, ...(changes.retry || {}) },
|
|
256
|
+
interceptors: { ...this._config.interceptors, ...(changes.interceptors || {}) }
|
|
257
|
+
});
|
|
258
|
+
}
|
|
259
|
+
origin(str) { return this._next({ request: { origin: str } }); }
|
|
260
|
+
path(str) { return this._next({ request: { path: str } }); }
|
|
261
|
+
query(obj) { return this._next({ request: { query: obj } }); }
|
|
262
|
+
method(str) { return this._next({ request: { method: str } }); }
|
|
263
|
+
headers(obj) { return this._next({ request: { headers: obj } }); }
|
|
264
|
+
body(obj) { return this._next({ request: { body: obj } }); }
|
|
265
|
+
offset(obj) { return this._next({ request: { offset: obj } }); }
|
|
266
|
+
maxDelay(ms) { return this._next({ retry: { maxDelay: ms } }); }
|
|
267
|
+
retryHeaders(...str) { return this._next({ retry: { retryHeaders: [...this._config.retry.retryHeaders, ...str.flat()] } }); }
|
|
268
|
+
unretry(...int) { return this._next({ retry: { unretry: new Set(int.flat()) } }); }
|
|
269
|
+
before(...func) { return this._next({ interceptors: { before: [...this._config.interceptors.before, ...func.flat()] } }); }
|
|
270
|
+
after(...func) { return this._next({ interceptors: { after: [...this._config.interceptors.after, ...func.flat()] } }); }
|
|
271
|
+
result(...func) { return this._next({ interceptors: { result: [...this._config.interceptors.result, ...func.flat()] } }); }
|
|
272
|
+
onError(...func) { return this._next({ interceptors: { onError: [...this._config.interceptors.onError, ...func.flat()] } }); }
|
|
273
|
+
retryConfig(func) {
|
|
274
|
+
if (typeof func !== 'function')
|
|
275
|
+
throw new VigorFetchError("retryConfig is not a function", { type: "not a function", data: "retryConfig" });
|
|
276
|
+
const dummyRetry = func(new VigorRetry(async () => { }));
|
|
277
|
+
return this._next({ retry: { retryConfig: dummyRetry['_config'] } });
|
|
278
|
+
}
|
|
279
|
+
parseConfig(func) {
|
|
280
|
+
if (typeof func !== 'function')
|
|
281
|
+
throw new VigorFetchError("parseConfig is not a function", { type: "not a function", data: "parseConfig" });
|
|
282
|
+
const dummyParse = func(new VigorParse(null));
|
|
283
|
+
return this._next({ response: { parseConfig: dummyParse['_config'] } });
|
|
284
|
+
}
|
|
285
|
+
async request() {
|
|
286
|
+
const { request: { origin, path, query, method, headers, body, offset }, retry: { limit, retryHeaders, unretry }, interceptors: { before, after, onError, result }, response: { retryConfig, parseConfig } } = this._config;
|
|
287
|
+
let ctx = { option: null, result: null, path, origin };
|
|
288
|
+
try {
|
|
289
|
+
if (!/^(https?|data|blob|file|about):\/\//.test(origin))
|
|
290
|
+
throw new VigorFetchError(`${origin} Invalid Protocol`, { type: "Invalid Protocol", data: origin, origin: origin, status: 0 });
|
|
291
|
+
const isJson = Array.isArray(body) || (!!body && Object.getPrototypeOf(body) === Object.prototype);
|
|
292
|
+
ctx.option = {
|
|
293
|
+
method: method || (body ? "POST" : "GET"),
|
|
294
|
+
headers: { ...(isJson && { "Content-Type": "application/json" }), ...headers },
|
|
295
|
+
...(body && { body: isJson ? JSON.stringify(body) : body }),
|
|
296
|
+
...offset
|
|
297
|
+
};
|
|
298
|
+
for (const func of before) {
|
|
299
|
+
if (typeof func !== 'function')
|
|
300
|
+
throw new VigorFetchError('Interceptor<before> is not a function', { type: "not a function", data: "before" });
|
|
301
|
+
const next = await func(ctx, ctx.option);
|
|
302
|
+
if (next !== undefined && typeof next === 'object' && !Array.isArray(next))
|
|
303
|
+
ctx = { ...ctx, ...next };
|
|
304
|
+
}
|
|
305
|
+
const originBase = ctx.origin.endsWith('/') ? ctx.origin : ctx.origin + '/';
|
|
306
|
+
const cleanPath = ctx.path.replace(/^\//, "");
|
|
307
|
+
const urlObj = cleanPath ? new URL(cleanPath, originBase) : new URL(ctx.origin);
|
|
308
|
+
Object.entries(query).forEach(([key, value]) => {
|
|
309
|
+
if (value !== null && value !== undefined)
|
|
310
|
+
urlObj.searchParams.append(key, String(value));
|
|
311
|
+
});
|
|
312
|
+
const url = urlObj.href;
|
|
313
|
+
ctx.url = url;
|
|
314
|
+
const fetchTarget = async () => {
|
|
315
|
+
const controller = new AbortController();
|
|
316
|
+
const abort = setTimeout(() => controller.abort(), limit);
|
|
317
|
+
const http = ctx.option;
|
|
318
|
+
http.signal = controller.signal;
|
|
319
|
+
const res = await fetch(url, http);
|
|
320
|
+
clearTimeout(abort);
|
|
321
|
+
return res;
|
|
322
|
+
};
|
|
323
|
+
const handle429 = async (ctx) => {
|
|
324
|
+
const res = ctx.result;
|
|
325
|
+
if (unretry.has(res.status))
|
|
326
|
+
throw new Error(`Unretry ${res.status}`);
|
|
327
|
+
if (!res || res.status !== 429)
|
|
328
|
+
return;
|
|
329
|
+
const rHeader = retryHeaders.map((h) => res.headers.get(h)).find(Boolean);
|
|
330
|
+
let delay = 0;
|
|
331
|
+
if (rHeader) {
|
|
332
|
+
delay = isNaN(Number(rHeader)) ? new Date(rHeader).getTime() - Date.now() : Number(rHeader) * 1000;
|
|
333
|
+
}
|
|
334
|
+
ctx.wait = Math.max(0, delay) + Math.random() * ctx.jitter;
|
|
335
|
+
if (ctx.wait > ctx.max)
|
|
336
|
+
throw new Error(`${url} Timeouted ${ctx.wait}ms`);
|
|
337
|
+
await new Promise(r => setTimeout(r, ctx.wait));
|
|
338
|
+
ctx.retry = true;
|
|
339
|
+
};
|
|
340
|
+
const retryInstance = new VigorRetry(fetchTarget, [], retryConfig).onRetry(handle429);
|
|
341
|
+
ctx.result = await retryInstance.request();
|
|
342
|
+
for (const func of after) {
|
|
343
|
+
if (typeof func !== 'function')
|
|
344
|
+
throw new VigorFetchError('Interceptor<after> is not a function', { type: "not a function", data: "after" });
|
|
345
|
+
const next = await func(ctx, ctx.result);
|
|
346
|
+
if (next !== undefined && typeof next === 'object' && !Array.isArray(next))
|
|
347
|
+
ctx = { ...ctx, ...next };
|
|
348
|
+
}
|
|
349
|
+
const parseInstance = new VigorParse(ctx.result, parseConfig);
|
|
350
|
+
ctx.final = await parseInstance.request();
|
|
351
|
+
for (const func of result) {
|
|
352
|
+
if (typeof func !== 'function')
|
|
353
|
+
throw new VigorFetchError('Interceptor<result> is not a function', { type: "not a function", data: "result" });
|
|
354
|
+
const next = await func(ctx.final);
|
|
355
|
+
if (next !== undefined && typeof next === 'object' && !Array.isArray(next))
|
|
356
|
+
ctx.final = { ...ctx, ...next };
|
|
357
|
+
}
|
|
358
|
+
if (ctx.final instanceof Error)
|
|
359
|
+
throw ctx.final;
|
|
360
|
+
return ctx.final;
|
|
361
|
+
}
|
|
362
|
+
catch (mainError) {
|
|
363
|
+
ctx.mainError = mainError;
|
|
364
|
+
for (const func of onError) {
|
|
365
|
+
if (typeof func !== 'function')
|
|
366
|
+
throw new VigorFetchError('Interceptor<onError> is not a function', { type: "not a function", data: "onError" });
|
|
367
|
+
const next = await func(ctx, ctx.mainError);
|
|
368
|
+
if (next !== undefined && typeof next === 'object' && !Array.isArray(next))
|
|
369
|
+
ctx = { ...ctx, ...next };
|
|
152
370
|
}
|
|
153
|
-
|
|
371
|
+
if (ctx.mainError instanceof Error)
|
|
372
|
+
throw ctx.mainError;
|
|
373
|
+
return ctx.mainError;
|
|
154
374
|
}
|
|
155
375
|
}
|
|
156
376
|
}
|
|
377
|
+
/**
|
|
378
|
+
* VigorAll
|
|
379
|
+
*/
|
|
157
380
|
class VigorAll {
|
|
158
381
|
constructor(config) {
|
|
159
|
-
this._config =
|
|
382
|
+
this._config = {
|
|
383
|
+
settings: { limit: 10, jitter: 1000 },
|
|
384
|
+
request: { promises: [] },
|
|
385
|
+
response: { retryConfig: undefined, parseConfig: undefined },
|
|
386
|
+
interceptors: { before: [], after: [], onError: [] },
|
|
387
|
+
...config
|
|
388
|
+
};
|
|
389
|
+
}
|
|
390
|
+
_next(changes) {
|
|
391
|
+
return new this.constructor({
|
|
392
|
+
...this._config,
|
|
393
|
+
...changes,
|
|
394
|
+
settings: { ...this._config.settings, ...(changes.settings || {}) },
|
|
395
|
+
request: { ...this._config.request, ...(changes.request || {}) },
|
|
396
|
+
interceptors: { ...this._config.interceptors, ...(changes.interceptors || {}) }
|
|
397
|
+
});
|
|
160
398
|
}
|
|
161
|
-
|
|
162
|
-
limit(
|
|
163
|
-
jitter(
|
|
164
|
-
|
|
399
|
+
promises(...func) { return this._next({ request: { promises: [...this._config.request.promises, ...func.flat()] } }); }
|
|
400
|
+
limit(int) { return this._next({ settings: { limit: int } }); }
|
|
401
|
+
jitter(ms) { return this._next({ settings: { jitter: ms } }); }
|
|
402
|
+
before(...func) { return this._next({ interceptors: { before: [...this._config.interceptors.before, ...func.flat()] } }); }
|
|
403
|
+
after(...func) { return this._next({ interceptors: { after: [...this._config.interceptors.after, ...func.flat()] } }); }
|
|
404
|
+
onError(...func) { return this._next({ interceptors: { onError: [...this._config.interceptors.onError, ...func.flat()] } }); }
|
|
165
405
|
async request() {
|
|
166
|
-
const { limit, jitter, promises } = this._config;
|
|
167
|
-
|
|
168
|
-
|
|
169
|
-
|
|
170
|
-
|
|
171
|
-
|
|
172
|
-
|
|
173
|
-
|
|
174
|
-
|
|
175
|
-
|
|
176
|
-
|
|
177
|
-
|
|
406
|
+
const { settings: { limit, jitter }, request: { promises }, interceptors: { before, after, onError } } = this._config;
|
|
407
|
+
let ctx = { limit, jitter, promises, result: null };
|
|
408
|
+
try {
|
|
409
|
+
for (const func of before || []) {
|
|
410
|
+
if (typeof func !== 'function')
|
|
411
|
+
throw new VigorAllError('Interceptor<before> is not a function', { type: "not a function", data: "before" });
|
|
412
|
+
const next = await func(ctx, ctx.promises);
|
|
413
|
+
if (next !== undefined && typeof next === 'object' && !Array.isArray(next))
|
|
414
|
+
ctx = { ...ctx, ...next };
|
|
415
|
+
}
|
|
416
|
+
const results = [];
|
|
417
|
+
const executing = new Set();
|
|
418
|
+
for (const task of ctx.promises) {
|
|
419
|
+
const p = Promise.resolve()
|
|
420
|
+
.then(() => new Promise(res => setTimeout(res, Math.random() * ctx.jitter)))
|
|
421
|
+
.then(() => task());
|
|
422
|
+
results.push(p);
|
|
423
|
+
executing.add(p);
|
|
424
|
+
p.finally(() => executing.delete(p));
|
|
425
|
+
if (executing.size >= ctx.limit) {
|
|
426
|
+
await Promise.race(executing);
|
|
427
|
+
}
|
|
428
|
+
}
|
|
429
|
+
const ready = await Promise.allSettled(results);
|
|
430
|
+
ctx.result = ready.map(i => {
|
|
431
|
+
if (i.status === "fulfilled")
|
|
432
|
+
return i.value;
|
|
433
|
+
return i.reason instanceof VigorAllError ? i.reason : new VigorAllError(i.reason?.message || "Unknown", { message: i.reason?.message || "Unknown" });
|
|
434
|
+
});
|
|
435
|
+
for (const func of after) {
|
|
436
|
+
if (typeof func !== 'function')
|
|
437
|
+
throw new VigorAllError('Interceptor<after> is not a function', { type: "not a function", data: "after" });
|
|
438
|
+
const next = await func(ctx, ctx.result);
|
|
439
|
+
if (next !== undefined && typeof next === 'object' && !Array.isArray(next))
|
|
440
|
+
ctx = { ...ctx, ...next };
|
|
441
|
+
}
|
|
442
|
+
if (ctx.result instanceof Error)
|
|
443
|
+
throw ctx.result;
|
|
444
|
+
return ctx.result;
|
|
445
|
+
}
|
|
446
|
+
catch (mainError) {
|
|
447
|
+
ctx.mainError = mainError;
|
|
448
|
+
for (const func of onError) {
|
|
449
|
+
if (typeof func !== 'function')
|
|
450
|
+
throw new VigorAllError('Interceptor<onError> is not a function', { type: "not a function", data: "onError" });
|
|
451
|
+
const next = await func(ctx, ctx.mainError);
|
|
452
|
+
if (next !== undefined && typeof next === 'object' && !Array.isArray(next))
|
|
453
|
+
ctx = { ...ctx, ...next };
|
|
454
|
+
}
|
|
455
|
+
if (ctx.mainError instanceof Error)
|
|
456
|
+
throw ctx.mainError;
|
|
457
|
+
return ctx.mainError;
|
|
178
458
|
}
|
|
179
|
-
const ready = await Promise.allSettled(results);
|
|
180
|
-
return ready.map(i => {
|
|
181
|
-
if (i.status === "fulfilled")
|
|
182
|
-
return i.value;
|
|
183
|
-
return i.reason instanceof VigorError ? i.reason : new VigorError(i.reason?.message || "Unknown", { message: i.reason?.message || "Unknown" });
|
|
184
|
-
});
|
|
185
459
|
}
|
|
186
460
|
}
|
|
461
|
+
/**
|
|
462
|
+
* Main Vigor Class
|
|
463
|
+
*/
|
|
187
464
|
class Vigor {
|
|
465
|
+
constructor() {
|
|
466
|
+
this._Fetch = VigorFetch;
|
|
467
|
+
this._Retry = VigorRetry;
|
|
468
|
+
this._Parse = VigorParse;
|
|
469
|
+
this._All = VigorAll;
|
|
470
|
+
}
|
|
471
|
+
use(plugin, options = {}) {
|
|
472
|
+
if (typeof plugin === 'function') {
|
|
473
|
+
plugin(this, options);
|
|
474
|
+
}
|
|
475
|
+
return this;
|
|
476
|
+
}
|
|
188
477
|
fetch(origin, config) {
|
|
189
|
-
return new
|
|
478
|
+
return new this._Fetch(origin, config);
|
|
479
|
+
}
|
|
480
|
+
retry(target, args, config) {
|
|
481
|
+
return new this._Retry(target, args, config);
|
|
482
|
+
}
|
|
483
|
+
parse(response, config) {
|
|
484
|
+
return new this._Parse(response, config);
|
|
190
485
|
}
|
|
191
486
|
all(config) {
|
|
192
|
-
return new
|
|
487
|
+
return new this._All(config);
|
|
193
488
|
}
|
|
194
489
|
}
|
|
195
490
|
const vigor = new Vigor();
|
|
491
|
+
const vigorInstance = vigor;
|
|
492
|
+
vigorInstance.VigorError = VigorError;
|
|
493
|
+
vigorInstance.VigorRetryError = VigorRetryError;
|
|
494
|
+
vigorInstance.VigorParseError = VigorParseError;
|
|
495
|
+
vigorInstance.VigorFetchError = VigorFetchError;
|
|
496
|
+
vigorInstance.VigorAllError = VigorAllError;
|
|
497
|
+
vigorInstance.VigorFetch = VigorFetch;
|
|
498
|
+
vigorInstance.VigorRetry = VigorRetry;
|
|
499
|
+
vigorInstance.VigorParse = VigorParse;
|
|
500
|
+
vigorInstance.VigorAll = VigorAll;
|
|
196
501
|
|
|
197
|
-
export { vigor as default };
|
|
502
|
+
export { VigorAll, VigorAllError, VigorError, VigorFetch, VigorFetchError, VigorParse, VigorParseError, VigorRetry, VigorRetryError, vigor as default, vigor };
|