@npora/request 0.1.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.
- package/LICENSE +21 -0
- package/README.md +174 -0
- package/dist/index.cjs +999 -0
- package/dist/index.d.cts +316 -0
- package/dist/index.d.ts +316 -0
- package/dist/index.js +960 -0
- package/package.json +68 -0
package/dist/index.js
ADDED
|
@@ -0,0 +1,960 @@
|
|
|
1
|
+
// src/errors/RequestError.ts
|
|
2
|
+
var RequestError = class extends Error {
|
|
3
|
+
constructor(message, options) {
|
|
4
|
+
super(message);
|
|
5
|
+
this.name = "RequestError";
|
|
6
|
+
this.code = options.code;
|
|
7
|
+
this.status = options.status;
|
|
8
|
+
this.cause = options.cause;
|
|
9
|
+
Object.setPrototypeOf(this, new.target.prototype);
|
|
10
|
+
}
|
|
11
|
+
};
|
|
12
|
+
|
|
13
|
+
// src/utils/createTimeoutSignal.ts
|
|
14
|
+
function createTimeoutSignal(signal, timeout) {
|
|
15
|
+
if (!timeout || timeout <= 0) {
|
|
16
|
+
return {
|
|
17
|
+
signal,
|
|
18
|
+
clear: noop
|
|
19
|
+
};
|
|
20
|
+
}
|
|
21
|
+
const controller = new AbortController();
|
|
22
|
+
const timer = setTimeout(() => {
|
|
23
|
+
controller.abort(
|
|
24
|
+
new RequestError(`Request timeout after ${timeout}ms`, {
|
|
25
|
+
code: "TIMEOUT_ERROR"
|
|
26
|
+
})
|
|
27
|
+
);
|
|
28
|
+
}, timeout);
|
|
29
|
+
if (signal) {
|
|
30
|
+
if (signal.aborted) {
|
|
31
|
+
controller.abort(signal.reason);
|
|
32
|
+
} else {
|
|
33
|
+
signal.addEventListener(
|
|
34
|
+
"abort",
|
|
35
|
+
() => {
|
|
36
|
+
controller.abort(
|
|
37
|
+
signal.reason ?? new RequestError("Request aborted", {
|
|
38
|
+
code: "ABORT_ERROR"
|
|
39
|
+
})
|
|
40
|
+
);
|
|
41
|
+
},
|
|
42
|
+
{
|
|
43
|
+
once: true
|
|
44
|
+
}
|
|
45
|
+
);
|
|
46
|
+
}
|
|
47
|
+
}
|
|
48
|
+
return {
|
|
49
|
+
signal: controller.signal,
|
|
50
|
+
clear: () => {
|
|
51
|
+
clearTimeout(timer);
|
|
52
|
+
}
|
|
53
|
+
};
|
|
54
|
+
}
|
|
55
|
+
function noop() {
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
// src/utils/buildRequest.ts
|
|
59
|
+
function buildRequest(config) {
|
|
60
|
+
const headers = new Headers(config.headers);
|
|
61
|
+
const body = buildBody(config, headers);
|
|
62
|
+
const timeoutSignal = createTimeoutSignal(config.signal, config.timeout);
|
|
63
|
+
return {
|
|
64
|
+
url: buildURL(config),
|
|
65
|
+
init: {
|
|
66
|
+
method: config.method ?? "GET",
|
|
67
|
+
headers,
|
|
68
|
+
body,
|
|
69
|
+
signal: timeoutSignal.signal
|
|
70
|
+
},
|
|
71
|
+
clear: timeoutSignal.clear
|
|
72
|
+
};
|
|
73
|
+
}
|
|
74
|
+
function buildURL(config) {
|
|
75
|
+
const baseURL = config.baseURL ?? "";
|
|
76
|
+
const url = `${baseURL}${config.url}`;
|
|
77
|
+
if (!config.query) {
|
|
78
|
+
return url;
|
|
79
|
+
}
|
|
80
|
+
const query = stringifyQuery(config.query);
|
|
81
|
+
if (!query) {
|
|
82
|
+
return url;
|
|
83
|
+
}
|
|
84
|
+
return url.includes("?") ? `${url}&${query}` : `${url}?${query}`;
|
|
85
|
+
}
|
|
86
|
+
function stringifyQuery(query) {
|
|
87
|
+
const params = new URLSearchParams();
|
|
88
|
+
for (const [key, value] of Object.entries(query)) {
|
|
89
|
+
appendQuery(params, key, value);
|
|
90
|
+
}
|
|
91
|
+
return params.toString();
|
|
92
|
+
}
|
|
93
|
+
function appendQuery(params, key, value) {
|
|
94
|
+
if (value === null || value === void 0) {
|
|
95
|
+
return;
|
|
96
|
+
}
|
|
97
|
+
if (Array.isArray(value)) {
|
|
98
|
+
for (const item of value) {
|
|
99
|
+
appendQuery(params, key, item);
|
|
100
|
+
}
|
|
101
|
+
return;
|
|
102
|
+
}
|
|
103
|
+
params.append(key, String(value));
|
|
104
|
+
}
|
|
105
|
+
function buildBody(config, headers) {
|
|
106
|
+
if (config.json !== void 0) {
|
|
107
|
+
setContentType(headers, "application/json");
|
|
108
|
+
return JSON.stringify(config.json);
|
|
109
|
+
}
|
|
110
|
+
if (config.form !== void 0) {
|
|
111
|
+
setContentType(
|
|
112
|
+
headers,
|
|
113
|
+
"application/x-www-form-urlencoded;charset=UTF-8"
|
|
114
|
+
);
|
|
115
|
+
return buildURLSearchParams(config.form);
|
|
116
|
+
}
|
|
117
|
+
if (config.formData !== void 0) {
|
|
118
|
+
return buildFormData(config.formData);
|
|
119
|
+
}
|
|
120
|
+
if (config.body === null || config.body === void 0) {
|
|
121
|
+
return void 0;
|
|
122
|
+
}
|
|
123
|
+
if (isPlainObject(config.body)) {
|
|
124
|
+
setContentType(headers, "application/json");
|
|
125
|
+
return JSON.stringify(config.body);
|
|
126
|
+
}
|
|
127
|
+
return config.body;
|
|
128
|
+
}
|
|
129
|
+
function buildURLSearchParams(form) {
|
|
130
|
+
if (form instanceof URLSearchParams) {
|
|
131
|
+
return form;
|
|
132
|
+
}
|
|
133
|
+
const params = new URLSearchParams();
|
|
134
|
+
for (const [key, value] of Object.entries(form)) {
|
|
135
|
+
appendQuery(params, key, value);
|
|
136
|
+
}
|
|
137
|
+
return params;
|
|
138
|
+
}
|
|
139
|
+
function buildFormData(input) {
|
|
140
|
+
if (input instanceof FormData) {
|
|
141
|
+
return input;
|
|
142
|
+
}
|
|
143
|
+
const formData = new FormData();
|
|
144
|
+
for (const [key, value] of Object.entries(input)) {
|
|
145
|
+
appendFormDataValue(formData, key, value);
|
|
146
|
+
}
|
|
147
|
+
return formData;
|
|
148
|
+
}
|
|
149
|
+
function appendFormDataValue(formData, key, value) {
|
|
150
|
+
if (value === null || value === void 0) {
|
|
151
|
+
return;
|
|
152
|
+
}
|
|
153
|
+
if (Array.isArray(value)) {
|
|
154
|
+
for (const item of value) {
|
|
155
|
+
appendFormDataValue(formData, key, item);
|
|
156
|
+
}
|
|
157
|
+
return;
|
|
158
|
+
}
|
|
159
|
+
if (value instanceof Blob) {
|
|
160
|
+
formData.append(key, value);
|
|
161
|
+
return;
|
|
162
|
+
}
|
|
163
|
+
formData.append(key, String(value));
|
|
164
|
+
}
|
|
165
|
+
function setContentType(headers, value) {
|
|
166
|
+
if (!headers.has("content-type")) {
|
|
167
|
+
headers.set("content-type", value);
|
|
168
|
+
}
|
|
169
|
+
}
|
|
170
|
+
function isPlainObject(value) {
|
|
171
|
+
return Object.prototype.toString.call(value) === "[object Object]";
|
|
172
|
+
}
|
|
173
|
+
|
|
174
|
+
// src/utils/parseResponse.ts
|
|
175
|
+
async function parseResponse(response, config) {
|
|
176
|
+
if (response.status === 204 || response.status === 205) {
|
|
177
|
+
return void 0;
|
|
178
|
+
}
|
|
179
|
+
const responseType = config.responseType ?? detectResponseType(response);
|
|
180
|
+
try {
|
|
181
|
+
switch (responseType) {
|
|
182
|
+
case "json":
|
|
183
|
+
return await response.json();
|
|
184
|
+
case "text":
|
|
185
|
+
return await response.text();
|
|
186
|
+
case "blob":
|
|
187
|
+
return await response.blob();
|
|
188
|
+
case "arrayBuffer":
|
|
189
|
+
return await response.arrayBuffer();
|
|
190
|
+
case "stream":
|
|
191
|
+
return response.body;
|
|
192
|
+
default:
|
|
193
|
+
return await response.text();
|
|
194
|
+
}
|
|
195
|
+
} catch (error) {
|
|
196
|
+
throw new RequestError("Failed to parse response", {
|
|
197
|
+
code: "PARSER_ERROR",
|
|
198
|
+
status: response.status,
|
|
199
|
+
cause: error
|
|
200
|
+
});
|
|
201
|
+
}
|
|
202
|
+
}
|
|
203
|
+
function detectResponseType(response) {
|
|
204
|
+
const contentType = response.headers.get("content-type") ?? "";
|
|
205
|
+
if (contentType.includes("application/json") || contentType.includes("+json")) {
|
|
206
|
+
return "json";
|
|
207
|
+
}
|
|
208
|
+
return "text";
|
|
209
|
+
}
|
|
210
|
+
|
|
211
|
+
// src/adapters/FetchAdapter.ts
|
|
212
|
+
var FetchAdapter = class {
|
|
213
|
+
async request(config) {
|
|
214
|
+
const request = buildRequest(config);
|
|
215
|
+
try {
|
|
216
|
+
const response = await fetch(request.url, request.init);
|
|
217
|
+
const validateStatus = config.validateStatus ?? defaultValidateStatus;
|
|
218
|
+
if (!validateStatus(response.status)) {
|
|
219
|
+
throw new RequestError(response.statusText || "Request failed", {
|
|
220
|
+
code: "HTTP_ERROR",
|
|
221
|
+
status: response.status
|
|
222
|
+
});
|
|
223
|
+
}
|
|
224
|
+
const data = await parseResponse(response, config);
|
|
225
|
+
return {
|
|
226
|
+
data,
|
|
227
|
+
status: response.status,
|
|
228
|
+
statusText: response.statusText,
|
|
229
|
+
headers: response.headers,
|
|
230
|
+
config,
|
|
231
|
+
raw: response
|
|
232
|
+
};
|
|
233
|
+
} catch (error) {
|
|
234
|
+
if (error instanceof RequestError) {
|
|
235
|
+
throw error;
|
|
236
|
+
}
|
|
237
|
+
const signal = request.init.signal;
|
|
238
|
+
const reason = signal?.reason;
|
|
239
|
+
if (signal?.aborted) {
|
|
240
|
+
if (reason instanceof RequestError) {
|
|
241
|
+
throw reason;
|
|
242
|
+
}
|
|
243
|
+
throw new RequestError("Request aborted", {
|
|
244
|
+
code: "ABORT_ERROR",
|
|
245
|
+
cause: error
|
|
246
|
+
});
|
|
247
|
+
}
|
|
248
|
+
throw new RequestError("Network request failed", {
|
|
249
|
+
code: "NETWORK_ERROR",
|
|
250
|
+
cause: error
|
|
251
|
+
});
|
|
252
|
+
} finally {
|
|
253
|
+
request.clear();
|
|
254
|
+
}
|
|
255
|
+
}
|
|
256
|
+
};
|
|
257
|
+
function defaultValidateStatus(status) {
|
|
258
|
+
return status >= 200 && status < 300;
|
|
259
|
+
}
|
|
260
|
+
|
|
261
|
+
// src/adapters/MockAdapter.ts
|
|
262
|
+
var MockAdapter = class {
|
|
263
|
+
constructor(options = {}) {
|
|
264
|
+
this.handlers = /* @__PURE__ */ new Map();
|
|
265
|
+
Object.entries(options.handlers ?? {}).forEach(([key, handler]) => {
|
|
266
|
+
this.handlers.set(key, handler);
|
|
267
|
+
});
|
|
268
|
+
}
|
|
269
|
+
on(url, handler) {
|
|
270
|
+
this.handlers.set(url, handler);
|
|
271
|
+
return this;
|
|
272
|
+
}
|
|
273
|
+
async request(config) {
|
|
274
|
+
const handler = this.handlers.get(config.url);
|
|
275
|
+
if (!handler) {
|
|
276
|
+
throw new Error(`No mock handler found for ${config.url}`);
|
|
277
|
+
}
|
|
278
|
+
const data = await handler(config);
|
|
279
|
+
return {
|
|
280
|
+
data,
|
|
281
|
+
status: 200,
|
|
282
|
+
statusText: "OK",
|
|
283
|
+
headers: new Headers(),
|
|
284
|
+
config,
|
|
285
|
+
raw: new Response(JSON.stringify(data), {
|
|
286
|
+
status: 200,
|
|
287
|
+
headers: {
|
|
288
|
+
"content-type": "application/json"
|
|
289
|
+
}
|
|
290
|
+
})
|
|
291
|
+
};
|
|
292
|
+
}
|
|
293
|
+
};
|
|
294
|
+
|
|
295
|
+
// src/core/ConfigMerger.ts
|
|
296
|
+
var ConfigMerger = class {
|
|
297
|
+
/**
|
|
298
|
+
* Merge request configuration.
|
|
299
|
+
*/
|
|
300
|
+
static merge(defaults, config) {
|
|
301
|
+
return {
|
|
302
|
+
...defaults,
|
|
303
|
+
...config,
|
|
304
|
+
headers: this.mergeHeaders(
|
|
305
|
+
defaults.headers,
|
|
306
|
+
config.headers
|
|
307
|
+
)
|
|
308
|
+
};
|
|
309
|
+
}
|
|
310
|
+
/**
|
|
311
|
+
* Merge request headers.
|
|
312
|
+
*/
|
|
313
|
+
static mergeHeaders(defaults, headers) {
|
|
314
|
+
if (!defaults && !headers) {
|
|
315
|
+
return void 0;
|
|
316
|
+
}
|
|
317
|
+
return {
|
|
318
|
+
...this.normalizeHeaders(defaults),
|
|
319
|
+
...this.normalizeHeaders(headers)
|
|
320
|
+
};
|
|
321
|
+
}
|
|
322
|
+
/**
|
|
323
|
+
* Normalize headers.
|
|
324
|
+
*/
|
|
325
|
+
static normalizeHeaders(headers) {
|
|
326
|
+
if (!headers) {
|
|
327
|
+
return {};
|
|
328
|
+
}
|
|
329
|
+
if (headers instanceof Headers) {
|
|
330
|
+
const result = {};
|
|
331
|
+
headers.forEach((value, key) => {
|
|
332
|
+
result[key] = value;
|
|
333
|
+
});
|
|
334
|
+
return result;
|
|
335
|
+
}
|
|
336
|
+
if (Array.isArray(headers)) {
|
|
337
|
+
return Object.fromEntries(headers);
|
|
338
|
+
}
|
|
339
|
+
return headers;
|
|
340
|
+
}
|
|
341
|
+
};
|
|
342
|
+
|
|
343
|
+
// src/core/RequestContext.ts
|
|
344
|
+
var RequestContext = class {
|
|
345
|
+
constructor(config) {
|
|
346
|
+
this.config = config;
|
|
347
|
+
this.startTime = Date.now();
|
|
348
|
+
}
|
|
349
|
+
};
|
|
350
|
+
|
|
351
|
+
// src/core/Pipeline.ts
|
|
352
|
+
var Pipeline = class {
|
|
353
|
+
constructor(adapter, interceptors, hooks) {
|
|
354
|
+
this.adapter = adapter;
|
|
355
|
+
this.interceptors = interceptors;
|
|
356
|
+
this.hooks = hooks;
|
|
357
|
+
}
|
|
358
|
+
async execute(config) {
|
|
359
|
+
const context = new RequestContext(config);
|
|
360
|
+
try {
|
|
361
|
+
context.config = await this.interceptors.request.run(context.config);
|
|
362
|
+
await this.hooks.runRequest(context);
|
|
363
|
+
if (context.response) {
|
|
364
|
+
return context.response;
|
|
365
|
+
}
|
|
366
|
+
let attempt = 0;
|
|
367
|
+
while (true) {
|
|
368
|
+
try {
|
|
369
|
+
context.response = await this.adapter.request(context.config);
|
|
370
|
+
context.response = await this.interceptors.response.run(
|
|
371
|
+
context.response
|
|
372
|
+
);
|
|
373
|
+
await this.hooks.runResponse(context);
|
|
374
|
+
return context.response;
|
|
375
|
+
} catch (error) {
|
|
376
|
+
context.error = error;
|
|
377
|
+
await this.hooks.runError(context);
|
|
378
|
+
const decision = await this.hooks.resolveRetry(context, attempt);
|
|
379
|
+
if (!decision.retry) {
|
|
380
|
+
context.error = await this.interceptors.error.run(context.error);
|
|
381
|
+
throw context.error;
|
|
382
|
+
}
|
|
383
|
+
context.error = void 0;
|
|
384
|
+
context.response = void 0;
|
|
385
|
+
attempt += 1;
|
|
386
|
+
if (decision.delay && decision.delay > 0) {
|
|
387
|
+
await sleep(decision.delay);
|
|
388
|
+
}
|
|
389
|
+
}
|
|
390
|
+
}
|
|
391
|
+
} finally {
|
|
392
|
+
context.endTime = Date.now();
|
|
393
|
+
}
|
|
394
|
+
}
|
|
395
|
+
};
|
|
396
|
+
function sleep(milliseconds) {
|
|
397
|
+
return new Promise((resolve) => {
|
|
398
|
+
setTimeout(resolve, milliseconds);
|
|
399
|
+
});
|
|
400
|
+
}
|
|
401
|
+
|
|
402
|
+
// src/interceptors/InterceptorManager.ts
|
|
403
|
+
var InterceptorManager = class {
|
|
404
|
+
constructor() {
|
|
405
|
+
this.id = 0;
|
|
406
|
+
this.interceptors = /* @__PURE__ */ new Map();
|
|
407
|
+
}
|
|
408
|
+
use(interceptor) {
|
|
409
|
+
const id = this.id++;
|
|
410
|
+
this.interceptors.set(id, interceptor);
|
|
411
|
+
return id;
|
|
412
|
+
}
|
|
413
|
+
eject(id) {
|
|
414
|
+
this.interceptors.delete(id);
|
|
415
|
+
}
|
|
416
|
+
clear() {
|
|
417
|
+
this.interceptors.clear();
|
|
418
|
+
}
|
|
419
|
+
async run(value) {
|
|
420
|
+
let result = value;
|
|
421
|
+
for (const interceptor of this.interceptors.values()) {
|
|
422
|
+
result = await interceptor(result);
|
|
423
|
+
}
|
|
424
|
+
return result;
|
|
425
|
+
}
|
|
426
|
+
};
|
|
427
|
+
|
|
428
|
+
// src/interceptors/PluginHooks.ts
|
|
429
|
+
var PluginHooks = class {
|
|
430
|
+
constructor() {
|
|
431
|
+
this.requestHooks = [];
|
|
432
|
+
this.responseHooks = [];
|
|
433
|
+
this.errorHooks = [];
|
|
434
|
+
this.retryHooks = [];
|
|
435
|
+
}
|
|
436
|
+
onRequest(hook) {
|
|
437
|
+
this.requestHooks.push(hook);
|
|
438
|
+
}
|
|
439
|
+
onResponse(hook) {
|
|
440
|
+
this.responseHooks.push(hook);
|
|
441
|
+
}
|
|
442
|
+
onError(hook) {
|
|
443
|
+
this.errorHooks.push(hook);
|
|
444
|
+
}
|
|
445
|
+
onRetry(hook) {
|
|
446
|
+
this.retryHooks.push(hook);
|
|
447
|
+
}
|
|
448
|
+
async runRequest(context) {
|
|
449
|
+
for (const hook of this.requestHooks) {
|
|
450
|
+
await hook(context);
|
|
451
|
+
}
|
|
452
|
+
}
|
|
453
|
+
async runResponse(context) {
|
|
454
|
+
for (const hook of this.responseHooks) {
|
|
455
|
+
await hook(context);
|
|
456
|
+
}
|
|
457
|
+
}
|
|
458
|
+
async runError(context) {
|
|
459
|
+
for (const hook of this.errorHooks) {
|
|
460
|
+
await hook(context);
|
|
461
|
+
}
|
|
462
|
+
}
|
|
463
|
+
async resolveRetry(context, attempt) {
|
|
464
|
+
for (const hook of this.retryHooks) {
|
|
465
|
+
const decision = await hook(context, attempt);
|
|
466
|
+
if (decision) {
|
|
467
|
+
return decision;
|
|
468
|
+
}
|
|
469
|
+
}
|
|
470
|
+
return {
|
|
471
|
+
retry: false,
|
|
472
|
+
delay: 0
|
|
473
|
+
};
|
|
474
|
+
}
|
|
475
|
+
};
|
|
476
|
+
|
|
477
|
+
// src/client/Client.ts
|
|
478
|
+
var Client = class {
|
|
479
|
+
constructor(options = {}) {
|
|
480
|
+
this.installedPlugins = /* @__PURE__ */ new Set();
|
|
481
|
+
this.hooks = new PluginHooks();
|
|
482
|
+
this.interceptors = {
|
|
483
|
+
request: new InterceptorManager(),
|
|
484
|
+
response: new InterceptorManager(),
|
|
485
|
+
error: new InterceptorManager()
|
|
486
|
+
};
|
|
487
|
+
const { adapter = new FetchAdapter(), ...defaults } = options;
|
|
488
|
+
this.defaults = defaults;
|
|
489
|
+
this.pipeline = this.createPipeline(adapter);
|
|
490
|
+
}
|
|
491
|
+
use(plugin) {
|
|
492
|
+
if (this.installedPlugins.has(plugin.name)) {
|
|
493
|
+
return this;
|
|
494
|
+
}
|
|
495
|
+
plugin.install({
|
|
496
|
+
interceptors: this.interceptors,
|
|
497
|
+
hooks: this.hooks
|
|
498
|
+
});
|
|
499
|
+
this.installedPlugins.add(plugin.name);
|
|
500
|
+
return this;
|
|
501
|
+
}
|
|
502
|
+
async request(config) {
|
|
503
|
+
const mergedConfig = ConfigMerger.merge(this.defaults, config);
|
|
504
|
+
const response = await this.pipeline.execute(mergedConfig);
|
|
505
|
+
return response.data;
|
|
506
|
+
}
|
|
507
|
+
get(url, config = {}) {
|
|
508
|
+
return this.request({
|
|
509
|
+
...config,
|
|
510
|
+
url,
|
|
511
|
+
method: "GET"
|
|
512
|
+
});
|
|
513
|
+
}
|
|
514
|
+
post(url, config = {}) {
|
|
515
|
+
return this.request({
|
|
516
|
+
...config,
|
|
517
|
+
url,
|
|
518
|
+
method: "POST"
|
|
519
|
+
});
|
|
520
|
+
}
|
|
521
|
+
put(url, config = {}) {
|
|
522
|
+
return this.request({
|
|
523
|
+
...config,
|
|
524
|
+
url,
|
|
525
|
+
method: "PUT"
|
|
526
|
+
});
|
|
527
|
+
}
|
|
528
|
+
patch(url, config = {}) {
|
|
529
|
+
return this.request({
|
|
530
|
+
...config,
|
|
531
|
+
url,
|
|
532
|
+
method: "PATCH"
|
|
533
|
+
});
|
|
534
|
+
}
|
|
535
|
+
delete(url, config = {}) {
|
|
536
|
+
return this.request({
|
|
537
|
+
...config,
|
|
538
|
+
url,
|
|
539
|
+
method: "DELETE"
|
|
540
|
+
});
|
|
541
|
+
}
|
|
542
|
+
createPipeline(adapter) {
|
|
543
|
+
return new Pipeline(adapter, this.interceptors, this.hooks);
|
|
544
|
+
}
|
|
545
|
+
};
|
|
546
|
+
|
|
547
|
+
// src/client/createClient.ts
|
|
548
|
+
function createClient(options = {}) {
|
|
549
|
+
return new Client(options);
|
|
550
|
+
}
|
|
551
|
+
|
|
552
|
+
// src/plugins/authPlugin.ts
|
|
553
|
+
function authPlugin(options = {}) {
|
|
554
|
+
let refreshPromise;
|
|
555
|
+
const refreshedContexts = /* @__PURE__ */ new WeakSet();
|
|
556
|
+
return {
|
|
557
|
+
name: "auth",
|
|
558
|
+
install(context) {
|
|
559
|
+
context.interceptors.request.use(async (config) => {
|
|
560
|
+
return applyAuthorization(config, options);
|
|
561
|
+
});
|
|
562
|
+
context.hooks.onRetry(async (requestContext) => {
|
|
563
|
+
if (!options.refreshToken || !requestContext.error) {
|
|
564
|
+
return void 0;
|
|
565
|
+
}
|
|
566
|
+
if (refreshedContexts.has(requestContext)) {
|
|
567
|
+
return void 0;
|
|
568
|
+
}
|
|
569
|
+
const shouldRefresh = options.shouldRefresh ?? defaultShouldRefresh;
|
|
570
|
+
if (!await shouldRefresh(requestContext.error)) {
|
|
571
|
+
return void 0;
|
|
572
|
+
}
|
|
573
|
+
refreshedContexts.add(requestContext);
|
|
574
|
+
try {
|
|
575
|
+
const refreshedToken = await refreshAccessToken(
|
|
576
|
+
options.refreshToken
|
|
577
|
+
);
|
|
578
|
+
if (refreshedToken) {
|
|
579
|
+
await options.storage?.set(refreshedToken);
|
|
580
|
+
}
|
|
581
|
+
const token = refreshedToken || await resolvePluginToken(options);
|
|
582
|
+
if (!token) {
|
|
583
|
+
return void 0;
|
|
584
|
+
}
|
|
585
|
+
requestContext.config = setAuthorizationHeader(
|
|
586
|
+
requestContext.config,
|
|
587
|
+
token,
|
|
588
|
+
options.scheme
|
|
589
|
+
);
|
|
590
|
+
return {
|
|
591
|
+
retry: true,
|
|
592
|
+
delay: 0
|
|
593
|
+
};
|
|
594
|
+
} catch {
|
|
595
|
+
return void 0;
|
|
596
|
+
}
|
|
597
|
+
});
|
|
598
|
+
}
|
|
599
|
+
};
|
|
600
|
+
async function refreshAccessToken(refreshToken) {
|
|
601
|
+
if (!refreshPromise) {
|
|
602
|
+
refreshPromise = Promise.resolve(refreshToken()).finally(() => {
|
|
603
|
+
refreshPromise = void 0;
|
|
604
|
+
});
|
|
605
|
+
}
|
|
606
|
+
return refreshPromise;
|
|
607
|
+
}
|
|
608
|
+
}
|
|
609
|
+
async function applyAuthorization(config, options) {
|
|
610
|
+
const requestAuth = config.auth;
|
|
611
|
+
const token = requestAuth?.token ? await resolveToken(requestAuth.token) : await resolvePluginToken(options);
|
|
612
|
+
if (!token) {
|
|
613
|
+
return config;
|
|
614
|
+
}
|
|
615
|
+
return setAuthorizationHeader(
|
|
616
|
+
config,
|
|
617
|
+
token,
|
|
618
|
+
requestAuth?.scheme ?? options.scheme
|
|
619
|
+
);
|
|
620
|
+
}
|
|
621
|
+
async function resolvePluginToken(options) {
|
|
622
|
+
const configuredToken = await resolveToken(options.token);
|
|
623
|
+
if (configuredToken) {
|
|
624
|
+
return configuredToken;
|
|
625
|
+
}
|
|
626
|
+
const storedToken = await options.storage?.get();
|
|
627
|
+
return storedToken ?? "";
|
|
628
|
+
}
|
|
629
|
+
async function resolveToken(token) {
|
|
630
|
+
if (!token) {
|
|
631
|
+
return "";
|
|
632
|
+
}
|
|
633
|
+
return typeof token === "function" ? await token() : token;
|
|
634
|
+
}
|
|
635
|
+
function setAuthorizationHeader(config, token, scheme = "Bearer") {
|
|
636
|
+
const headers = new Headers(config.headers);
|
|
637
|
+
headers.set("authorization", `${scheme} ${token}`);
|
|
638
|
+
return {
|
|
639
|
+
...config,
|
|
640
|
+
headers
|
|
641
|
+
};
|
|
642
|
+
}
|
|
643
|
+
function defaultShouldRefresh(error) {
|
|
644
|
+
return error instanceof RequestError && error.code === "HTTP_ERROR" && error.status === 401;
|
|
645
|
+
}
|
|
646
|
+
|
|
647
|
+
// src/plugins/cachePlugin.ts
|
|
648
|
+
var cacheStore = /* @__PURE__ */ new Map();
|
|
649
|
+
function cachePlugin() {
|
|
650
|
+
return {
|
|
651
|
+
name: "cache",
|
|
652
|
+
install(context) {
|
|
653
|
+
context.hooks.onRequest((requestContext) => {
|
|
654
|
+
const cache = requestContext.config.cache;
|
|
655
|
+
if (!cache?.enabled) {
|
|
656
|
+
return;
|
|
657
|
+
}
|
|
658
|
+
const key = createCacheKey(requestContext.config);
|
|
659
|
+
const record = cacheStore.get(key);
|
|
660
|
+
if (!record) {
|
|
661
|
+
return;
|
|
662
|
+
}
|
|
663
|
+
if (Date.now() > record.expiresAt) {
|
|
664
|
+
cacheStore.delete(key);
|
|
665
|
+
return;
|
|
666
|
+
}
|
|
667
|
+
requestContext.response = {
|
|
668
|
+
data: record.data,
|
|
669
|
+
status: 200,
|
|
670
|
+
statusText: "OK",
|
|
671
|
+
headers: new Headers(),
|
|
672
|
+
config: requestContext.config,
|
|
673
|
+
raw: new Response()
|
|
674
|
+
};
|
|
675
|
+
});
|
|
676
|
+
context.hooks.onResponse((requestContext) => {
|
|
677
|
+
const cache = requestContext.config.cache;
|
|
678
|
+
if (!cache?.enabled || !requestContext.response) {
|
|
679
|
+
return;
|
|
680
|
+
}
|
|
681
|
+
const key = createCacheKey(requestContext.config);
|
|
682
|
+
const ttl = cache.ttl ?? 3e4;
|
|
683
|
+
cacheStore.set(key, {
|
|
684
|
+
data: requestContext.response.data,
|
|
685
|
+
expiresAt: Date.now() + ttl
|
|
686
|
+
});
|
|
687
|
+
});
|
|
688
|
+
}
|
|
689
|
+
};
|
|
690
|
+
}
|
|
691
|
+
function clearCache() {
|
|
692
|
+
cacheStore.clear();
|
|
693
|
+
}
|
|
694
|
+
function createCacheKey(config) {
|
|
695
|
+
if (config.cache?.key) {
|
|
696
|
+
return config.cache.key;
|
|
697
|
+
}
|
|
698
|
+
return JSON.stringify({
|
|
699
|
+
method: config.method ?? "GET",
|
|
700
|
+
baseURL: config.baseURL,
|
|
701
|
+
url: config.url,
|
|
702
|
+
query: config.query
|
|
703
|
+
});
|
|
704
|
+
}
|
|
705
|
+
|
|
706
|
+
// src/plugins/downloadPlugin.ts
|
|
707
|
+
function downloadPlugin() {
|
|
708
|
+
return {
|
|
709
|
+
name: "download",
|
|
710
|
+
install(context) {
|
|
711
|
+
context.interceptors.request.use((config) => {
|
|
712
|
+
if (!config.download) {
|
|
713
|
+
return config;
|
|
714
|
+
}
|
|
715
|
+
const responseType = config.download.onProgress ? "stream" : config.responseType ?? "blob";
|
|
716
|
+
return {
|
|
717
|
+
...config,
|
|
718
|
+
responseType
|
|
719
|
+
};
|
|
720
|
+
});
|
|
721
|
+
context.interceptors.response.use(async (response) => {
|
|
722
|
+
const download = response.config.download;
|
|
723
|
+
const onProgress = download?.onProgress;
|
|
724
|
+
if (!download || !onProgress) {
|
|
725
|
+
return response;
|
|
726
|
+
}
|
|
727
|
+
const stream = response.data;
|
|
728
|
+
if (!(stream instanceof ReadableStream)) {
|
|
729
|
+
throw new RequestError(
|
|
730
|
+
"Download response stream is unavailable",
|
|
731
|
+
{
|
|
732
|
+
code: "PARSER_ERROR",
|
|
733
|
+
status: response.status
|
|
734
|
+
}
|
|
735
|
+
);
|
|
736
|
+
}
|
|
737
|
+
const blob = await consumeDownloadStream(
|
|
738
|
+
stream,
|
|
739
|
+
response,
|
|
740
|
+
onProgress
|
|
741
|
+
);
|
|
742
|
+
return {
|
|
743
|
+
...response,
|
|
744
|
+
data: blob
|
|
745
|
+
};
|
|
746
|
+
});
|
|
747
|
+
}
|
|
748
|
+
};
|
|
749
|
+
}
|
|
750
|
+
async function consumeDownloadStream(stream, response, onProgress) {
|
|
751
|
+
const reader = stream.getReader();
|
|
752
|
+
const chunks = [];
|
|
753
|
+
const total = parseContentLength(
|
|
754
|
+
response.headers.get("content-length")
|
|
755
|
+
);
|
|
756
|
+
let loaded = 0;
|
|
757
|
+
try {
|
|
758
|
+
while (true) {
|
|
759
|
+
const result = await reader.read();
|
|
760
|
+
if (result.done) {
|
|
761
|
+
break;
|
|
762
|
+
}
|
|
763
|
+
const chunk = result.value;
|
|
764
|
+
const buffer = copyToArrayBuffer(chunk);
|
|
765
|
+
chunks.push(buffer);
|
|
766
|
+
loaded += chunk.byteLength;
|
|
767
|
+
onProgress(createProgress(loaded, total));
|
|
768
|
+
}
|
|
769
|
+
} finally {
|
|
770
|
+
reader.releaseLock();
|
|
771
|
+
}
|
|
772
|
+
return new Blob(chunks, {
|
|
773
|
+
type: response.headers.get("content-type") ?? ""
|
|
774
|
+
});
|
|
775
|
+
}
|
|
776
|
+
function copyToArrayBuffer(chunk) {
|
|
777
|
+
const copy = new Uint8Array(chunk.byteLength);
|
|
778
|
+
copy.set(chunk);
|
|
779
|
+
return copy.buffer;
|
|
780
|
+
}
|
|
781
|
+
function parseContentLength(value) {
|
|
782
|
+
if (!value) {
|
|
783
|
+
return void 0;
|
|
784
|
+
}
|
|
785
|
+
const total = Number(value);
|
|
786
|
+
if (!Number.isFinite(total) || total < 0) {
|
|
787
|
+
return void 0;
|
|
788
|
+
}
|
|
789
|
+
return total;
|
|
790
|
+
}
|
|
791
|
+
function createProgress(loaded, total) {
|
|
792
|
+
if (total === void 0 || total === 0) {
|
|
793
|
+
return {
|
|
794
|
+
loaded,
|
|
795
|
+
total
|
|
796
|
+
};
|
|
797
|
+
}
|
|
798
|
+
return {
|
|
799
|
+
loaded,
|
|
800
|
+
total,
|
|
801
|
+
progress: Math.min(loaded / total, 1)
|
|
802
|
+
};
|
|
803
|
+
}
|
|
804
|
+
|
|
805
|
+
// src/plugins/loggerPlugin.ts
|
|
806
|
+
function loggerPlugin(defaultOptions = {}) {
|
|
807
|
+
return {
|
|
808
|
+
name: "logger",
|
|
809
|
+
install(context) {
|
|
810
|
+
context.interceptors.request.use((config) => {
|
|
811
|
+
const logger = config.logger ?? defaultOptions;
|
|
812
|
+
if (logger.enabled === false) {
|
|
813
|
+
return config;
|
|
814
|
+
}
|
|
815
|
+
console.log("[Npora Request]", {
|
|
816
|
+
type: "request",
|
|
817
|
+
method: config.method ?? "GET",
|
|
818
|
+
url: config.url
|
|
819
|
+
});
|
|
820
|
+
return config;
|
|
821
|
+
});
|
|
822
|
+
context.interceptors.response.use((response) => {
|
|
823
|
+
const logger = response.config.logger ?? defaultOptions;
|
|
824
|
+
if (logger.enabled === false) {
|
|
825
|
+
return response;
|
|
826
|
+
}
|
|
827
|
+
console.log("[Npora Request]", {
|
|
828
|
+
type: "response",
|
|
829
|
+
method: response.config.method ?? "GET",
|
|
830
|
+
url: response.config.url,
|
|
831
|
+
status: response.status
|
|
832
|
+
});
|
|
833
|
+
return response;
|
|
834
|
+
});
|
|
835
|
+
context.interceptors.error.use((error) => {
|
|
836
|
+
console.error("[Npora Request]", {
|
|
837
|
+
type: "error",
|
|
838
|
+
error
|
|
839
|
+
});
|
|
840
|
+
return error;
|
|
841
|
+
});
|
|
842
|
+
}
|
|
843
|
+
};
|
|
844
|
+
}
|
|
845
|
+
|
|
846
|
+
// src/plugins/retryPlugin.ts
|
|
847
|
+
function retryPlugin(defaultOptions = {}) {
|
|
848
|
+
return {
|
|
849
|
+
name: "retry",
|
|
850
|
+
install(context) {
|
|
851
|
+
context.hooks.onRetry(async (requestContext, attempt) => {
|
|
852
|
+
if (!requestContext.error) {
|
|
853
|
+
return void 0;
|
|
854
|
+
}
|
|
855
|
+
const retryOptions = normalizeRetryOptions(
|
|
856
|
+
requestContext.config.retry,
|
|
857
|
+
defaultOptions
|
|
858
|
+
);
|
|
859
|
+
if (attempt >= retryOptions.retries) {
|
|
860
|
+
return void 0;
|
|
861
|
+
}
|
|
862
|
+
const shouldRetry = await retryOptions.shouldRetry(
|
|
863
|
+
requestContext.error,
|
|
864
|
+
attempt
|
|
865
|
+
);
|
|
866
|
+
if (!shouldRetry) {
|
|
867
|
+
return void 0;
|
|
868
|
+
}
|
|
869
|
+
return {
|
|
870
|
+
retry: true,
|
|
871
|
+
delay: await retryOptions.delay(
|
|
872
|
+
attempt,
|
|
873
|
+
requestContext.error
|
|
874
|
+
)
|
|
875
|
+
};
|
|
876
|
+
});
|
|
877
|
+
}
|
|
878
|
+
};
|
|
879
|
+
}
|
|
880
|
+
function normalizeRetryOptions(retry, defaults = {}) {
|
|
881
|
+
if (typeof retry === "number") {
|
|
882
|
+
return {
|
|
883
|
+
retries: normalizeRetries(retry),
|
|
884
|
+
delay: normalizeDelay(defaults.delay),
|
|
885
|
+
shouldRetry: defaults.shouldRetry ?? defaultShouldRetry
|
|
886
|
+
};
|
|
887
|
+
}
|
|
888
|
+
return {
|
|
889
|
+
retries: normalizeRetries(
|
|
890
|
+
retry?.retries ?? defaults.retries ?? 0
|
|
891
|
+
),
|
|
892
|
+
delay: normalizeDelay(
|
|
893
|
+
retry?.delay ?? defaults.delay
|
|
894
|
+
),
|
|
895
|
+
shouldRetry: retry?.shouldRetry ?? defaults.shouldRetry ?? defaultShouldRetry
|
|
896
|
+
};
|
|
897
|
+
}
|
|
898
|
+
function normalizeRetries(retries) {
|
|
899
|
+
if (!Number.isFinite(retries)) {
|
|
900
|
+
return 0;
|
|
901
|
+
}
|
|
902
|
+
return Math.max(0, Math.floor(retries));
|
|
903
|
+
}
|
|
904
|
+
function normalizeDelay(delay) {
|
|
905
|
+
if (typeof delay === "number") {
|
|
906
|
+
const normalizedDelay = Math.max(0, delay);
|
|
907
|
+
return () => normalizedDelay;
|
|
908
|
+
}
|
|
909
|
+
return delay ?? defaultRetryDelay;
|
|
910
|
+
}
|
|
911
|
+
function defaultRetryDelay(attempt) {
|
|
912
|
+
return Math.min(100 * 2 ** attempt, 1e3);
|
|
913
|
+
}
|
|
914
|
+
function defaultShouldRetry(error) {
|
|
915
|
+
if (!(error instanceof RequestError)) {
|
|
916
|
+
return false;
|
|
917
|
+
}
|
|
918
|
+
if (error.code === "NETWORK_ERROR") {
|
|
919
|
+
return true;
|
|
920
|
+
}
|
|
921
|
+
if (error.status === void 0) {
|
|
922
|
+
return false;
|
|
923
|
+
}
|
|
924
|
+
return error.status === 408 || error.status === 429 || error.status >= 500;
|
|
925
|
+
}
|
|
926
|
+
|
|
927
|
+
// src/plugins/uploadPlugin.ts
|
|
928
|
+
function uploadPlugin() {
|
|
929
|
+
return {
|
|
930
|
+
name: "upload",
|
|
931
|
+
install(context) {
|
|
932
|
+
context.interceptors.request.use((config) => {
|
|
933
|
+
if (!config.upload) {
|
|
934
|
+
return config;
|
|
935
|
+
}
|
|
936
|
+
return {
|
|
937
|
+
...config,
|
|
938
|
+
method: config.method ?? "POST",
|
|
939
|
+
formData: config.upload.data,
|
|
940
|
+
upload: void 0
|
|
941
|
+
};
|
|
942
|
+
});
|
|
943
|
+
}
|
|
944
|
+
};
|
|
945
|
+
}
|
|
946
|
+
export {
|
|
947
|
+
Client,
|
|
948
|
+
FetchAdapter,
|
|
949
|
+
InterceptorManager,
|
|
950
|
+
MockAdapter,
|
|
951
|
+
RequestError,
|
|
952
|
+
authPlugin,
|
|
953
|
+
cachePlugin,
|
|
954
|
+
clearCache,
|
|
955
|
+
createClient,
|
|
956
|
+
downloadPlugin,
|
|
957
|
+
loggerPlugin,
|
|
958
|
+
retryPlugin,
|
|
959
|
+
uploadPlugin
|
|
960
|
+
};
|