@hyperttp/core 1.4.8 → 1.5.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/Core/HyperCore.d.ts +3 -15
- package/Core/HyperCore.d.ts.map +1 -1
- package/Core/HyperCore.js +2 -576
- package/Core/HyperCore.js.map +7 -1
- package/Core/RequestBuilder.d.ts +11 -0
- package/Core/RequestBuilder.d.ts.map +1 -0
- package/Core/RequestBuilder.js +2 -0
- package/Core/RequestBuilder.js.map +7 -0
- package/Core/index.js +2 -2
- package/Core/index.js.map +7 -1
- package/README.md +30 -0
- package/defaultConfig.js +2 -19
- package/defaultConfig.js.map +7 -1
- package/index.js +2 -3
- package/index.js.map +7 -1
- package/package.json +1 -1
- package/transports/browser.d.ts.map +1 -1
- package/transports/browser.js +2 -113
- package/transports/browser.js.map +7 -1
- package/transports/manager.d.ts +0 -33
- package/transports/manager.d.ts.map +1 -1
- package/transports/manager.js +7 -349
- package/transports/manager.js.map +7 -1
- package/transports/node.d.ts +1 -0
- package/transports/node.d.ts.map +1 -1
- package/transports/node.js +2 -380
- package/transports/node.js.map +7 -1
- package/utils/errors.d.ts +0 -11
- package/utils/errors.d.ts.map +1 -1
- package/utils/errors.js +2 -53
- package/utils/errors.js.map +7 -1
- package/utils/merge.js +2 -29
- package/utils/merge.js.map +7 -1
- package/utils/normalize.d.ts +12 -7
- package/utils/normalize.d.ts.map +1 -1
- package/utils/normalize.js +2 -285
- package/utils/normalize.js.map +7 -1
- package/utils/pipeline.js +2 -193
- package/utils/pipeline.js.map +7 -1
- package/utils/response.d.ts +0 -14
- package/utils/response.d.ts.map +1 -1
- package/utils/response.js +2 -389
- package/utils/response.js.map +7 -1
- package/utils/retryUtils.js +2 -55
- package/utils/retryUtils.js.map +7 -1
package/Core/HyperCore.d.ts
CHANGED
|
@@ -12,6 +12,9 @@ export declare class HyperCore implements IHyperCore {
|
|
|
12
12
|
private readonly defaultHeaders;
|
|
13
13
|
private readonly pluginCtx;
|
|
14
14
|
private readonly pipelines;
|
|
15
|
+
private readonly requestBuilder;
|
|
16
|
+
private readonly requestPool;
|
|
17
|
+
private semaphore;
|
|
15
18
|
private hasRequestPlugins;
|
|
16
19
|
private hasResponseDataPlugins;
|
|
17
20
|
private hasResponsePlugins;
|
|
@@ -196,27 +199,12 @@ export declare class HyperCore implements IHyperCore {
|
|
|
196
199
|
* @returns The populated internal request object.
|
|
197
200
|
*/
|
|
198
201
|
private acquireReq;
|
|
199
|
-
private ensureCacheSpace;
|
|
200
202
|
/**
|
|
201
203
|
* @ru Возвращает объект запроса в пул для переиспользования, очищая ссылки для GC.
|
|
202
204
|
* @en Returns the request object to the pool for reuse, clearing references for GC.
|
|
203
205
|
* @param req - The internal request object to recycle.
|
|
204
206
|
*/
|
|
205
207
|
private recycleRequest;
|
|
206
|
-
/**
|
|
207
|
-
* @ru Разрешает и кэширует URL, нормализуя его через URL API при необходимости.
|
|
208
|
-
* @en Resolves and caches the URL, normalizing it via the URL API when necessary.
|
|
209
|
-
* @param url - The raw URL string.
|
|
210
|
-
* @returns The resolved and cached URL string.
|
|
211
|
-
*/
|
|
212
|
-
private resolveUrl;
|
|
213
|
-
/**
|
|
214
|
-
* @ru Добавляет query-параметры к объект URL, поддерживая массивы значений.
|
|
215
|
-
* @en Appends query parameters to the URL object, supporting arrays of values.
|
|
216
|
-
* @param url - The URL object to modify.
|
|
217
|
-
* @param query - Record of query parameter key-value pairs.
|
|
218
|
-
*/
|
|
219
|
-
private appendQueryParams;
|
|
220
208
|
/**
|
|
221
209
|
* @ru Выполняет быстрый запрос с автоматическим определением HTTP-метода.
|
|
222
210
|
* @en Performs a shortcut request with automatic HTTP method detection.
|
package/Core/HyperCore.d.ts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"HyperCore.d.ts","sourceRoot":"","sources":["../../src/Core/HyperCore.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EACV,UAAU,EACV,cAAc,EACd,iBAAiB,EAEjB,WAAW,EACX,eAAe,EACf,YAAY,EAEZ,gBAAgB,EAChB,cAAc,EACd,eAAe,
|
|
1
|
+
{"version":3,"file":"HyperCore.d.ts","sourceRoot":"","sources":["../../src/Core/HyperCore.ts"],"names":[],"mappings":"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"}
|
package/Core/HyperCore.js
CHANGED
|
@@ -1,576 +1,2 @@
|
|
|
1
|
-
import
|
|
2
|
-
|
|
3
|
-
import { TransportManager } from "../transports/manager.js";
|
|
4
|
-
import { createPipelines, executeErrorPipeline, executeRequestPipeline, executeResponsePipeline, executeResponseDataPipeline, insertHookSorted, } from "../utils/pipeline.js";
|
|
5
|
-
import { normalizeBody, normalizeHeaders, normalizeUrl } from "../utils/normalize.js";
|
|
6
|
-
/**
|
|
7
|
-
* @ru Глобальный кэш URL для избежания повторного парсинга через `new URL()`.
|
|
8
|
-
* Использует `Object.create(null)` для быстрого доступа без прототипа.
|
|
9
|
-
* @en Global URL cache to avoid repeated parsing via `new URL()`.
|
|
10
|
-
* Uses `Object.create(null)` for fast prototype-less access.
|
|
11
|
-
*/
|
|
12
|
-
let urlCache = Object.create(null);
|
|
13
|
-
let urlCacheCount = 0;
|
|
14
|
-
const MAX_CACHE_SIZE = 512;
|
|
15
|
-
/**
|
|
16
|
-
* @ru Пул переиспользуемых объектов InternalRequest для zero-allocation в горячем пути.
|
|
17
|
-
* @en Pool of reusable InternalRequest objects for zero-allocation in the hot path.
|
|
18
|
-
*/
|
|
19
|
-
const requestPool = [];
|
|
20
|
-
const MAX_POOL_SIZE = 64;
|
|
21
|
-
/**
|
|
22
|
-
* @ru Ядро HTTP-клиента Hyperttp. Обеспечивает диспетчеризацию запросов через
|
|
23
|
-
* конвейер плагинов, пулинг объектов запросов и кэширование URL.
|
|
24
|
-
* @en Hyperttp HTTP client core. Provides request dispatching through the
|
|
25
|
-
* plugin pipeline, request object pooling, and URL caching.
|
|
26
|
-
*/
|
|
27
|
-
export class HyperCore {
|
|
28
|
-
config;
|
|
29
|
-
transportManager;
|
|
30
|
-
transportReady;
|
|
31
|
-
defaultHeaders;
|
|
32
|
-
pluginCtx;
|
|
33
|
-
pipelines = createPipelines();
|
|
34
|
-
hasRequestPlugins = false;
|
|
35
|
-
hasResponseDataPlugins = false;
|
|
36
|
-
hasResponsePlugins = false;
|
|
37
|
-
hasErrorPlugins = false;
|
|
38
|
-
/**
|
|
39
|
-
* @ru Создаёт новый экземпляр ядра HTTP-клиента.
|
|
40
|
-
* @en Creates a new HTTP client core instance.
|
|
41
|
-
* @param config - Client configuration options.
|
|
42
|
-
* @param transport - Optional custom transport implementation.
|
|
43
|
-
*/
|
|
44
|
-
constructor(config = defaultConfig, transport) {
|
|
45
|
-
this.config = {
|
|
46
|
-
...defaultConfig,
|
|
47
|
-
...config,
|
|
48
|
-
network: {
|
|
49
|
-
...defaultConfig.network,
|
|
50
|
-
...config.network,
|
|
51
|
-
stealth: config.network?.stealth || defaultConfig.network?.stealth
|
|
52
|
-
? Object.assign({}, defaultConfig.network?.stealth, config.network?.stealth)
|
|
53
|
-
: undefined,
|
|
54
|
-
},
|
|
55
|
-
};
|
|
56
|
-
this.transportManager = new TransportManager(this.config, transport);
|
|
57
|
-
this.transportReady = this.transportManager.getSync()
|
|
58
|
-
? Promise.resolve(this.transportManager.getSync())
|
|
59
|
-
: this.transportManager.ensure();
|
|
60
|
-
this.defaultHeaders = normalizeHeaders({
|
|
61
|
-
Accept: "application/json, text/plain, */*",
|
|
62
|
-
"Accept-Encoding": "gzip, deflate, br",
|
|
63
|
-
"User-Agent": this.config.network?.userAgent ?? "Hyperttp/2.0",
|
|
64
|
-
...this.config.network?.headers,
|
|
65
|
-
});
|
|
66
|
-
this.pluginCtx = { config: this.config, core: this };
|
|
67
|
-
}
|
|
68
|
-
/**
|
|
69
|
-
* @ru Возвращает имя класса текущего активного транспорта.
|
|
70
|
-
* @en Returns the class name of the currently active transport.
|
|
71
|
-
* @returns Promise resolving to the transport class name.
|
|
72
|
-
*/
|
|
73
|
-
async getTransportName() {
|
|
74
|
-
const t = this.transportManager.transport ?? (await this.transportManager.get());
|
|
75
|
-
return t.constructor.name;
|
|
76
|
-
}
|
|
77
|
-
/**
|
|
78
|
-
* @ru Отправляет внутренний запрос через полный конвейер обработки:
|
|
79
|
-
* плагины запроса → транспорт → плагины данных ответа → маппинг → плагины ответа.
|
|
80
|
-
* @en Dispatches an internal request through the full processing pipeline:
|
|
81
|
-
* request plugins → transport → response data plugins → mapping → response plugins.
|
|
82
|
-
* @template T - Expected response body type.
|
|
83
|
-
* @param req - The normalized internal request object.
|
|
84
|
-
* @returns Promise resolving to the HTTP response.
|
|
85
|
-
*/
|
|
86
|
-
async dispatch(req) {
|
|
87
|
-
try {
|
|
88
|
-
if (this.hasRequestPlugins) {
|
|
89
|
-
const syncResult = executeRequestPipeline(this.pipelines.request, req, this.pluginCtx);
|
|
90
|
-
const shortCircuit = syncResult instanceof Promise ? await syncResult : syncResult;
|
|
91
|
-
if (shortCircuit != null) {
|
|
92
|
-
this.recycleRequest(req);
|
|
93
|
-
return shortCircuit;
|
|
94
|
-
}
|
|
95
|
-
}
|
|
96
|
-
const transport = this.transportManager.transport ??
|
|
97
|
-
this.transportManager.getSync() ??
|
|
98
|
-
(await this.transportReady);
|
|
99
|
-
const networkStart = performance.now();
|
|
100
|
-
let rawResponse = await transport.execute(req);
|
|
101
|
-
const networkMs = performance.now() - networkStart;
|
|
102
|
-
const meta = req.meta;
|
|
103
|
-
if (meta.timings) {
|
|
104
|
-
meta.timings.networkMs = networkMs;
|
|
105
|
-
}
|
|
106
|
-
if (this.hasResponseDataPlugins) {
|
|
107
|
-
const syncResult = executeResponseDataPipeline(this.pipelines.responseData, rawResponse, this.pluginCtx);
|
|
108
|
-
rawResponse = syncResult instanceof Promise ? await syncResult : syncResult;
|
|
109
|
-
}
|
|
110
|
-
const response = meta.responseType === "stream" ? mapStreamFast(rawResponse) : mapResponseFast(rawResponse);
|
|
111
|
-
if (this.hasResponsePlugins) {
|
|
112
|
-
const reqForPipeline = this.pipelines.responseSideEffects.length > 0
|
|
113
|
-
? {
|
|
114
|
-
...req,
|
|
115
|
-
meta: {
|
|
116
|
-
...meta,
|
|
117
|
-
timings: meta.timings ? { ...meta.timings } : undefined,
|
|
118
|
-
},
|
|
119
|
-
}
|
|
120
|
-
: req;
|
|
121
|
-
const syncResult = executeResponsePipeline(this.pipelines.responseMutators, this.pipelines.responseSideEffects, response, reqForPipeline, this.pluginCtx, this.config.logger);
|
|
122
|
-
if (syncResult instanceof Promise) {
|
|
123
|
-
await syncResult;
|
|
124
|
-
}
|
|
125
|
-
}
|
|
126
|
-
this.recycleRequest(req);
|
|
127
|
-
return response;
|
|
128
|
-
}
|
|
129
|
-
catch (error) {
|
|
130
|
-
return this.handleDispatchError(error, req);
|
|
131
|
-
}
|
|
132
|
-
}
|
|
133
|
-
/**
|
|
134
|
-
* @ru Регистрирует плагин в экземпляре клиента. Плагины выполняются в порядке приоритета.
|
|
135
|
-
* @en Registers a plugin into the client instance. Plugins are executed in priority order.
|
|
136
|
-
* @param plugin - The plugin instance to register.
|
|
137
|
-
* @returns The current instance for chaining.
|
|
138
|
-
*/
|
|
139
|
-
use(plugin) {
|
|
140
|
-
const isEnabled = plugin.enabled ? plugin.enabled(this.config) : true;
|
|
141
|
-
if (!isEnabled)
|
|
142
|
-
return this;
|
|
143
|
-
plugin.setup?.(this.pluginCtx);
|
|
144
|
-
const priority = plugin.priority ?? 0;
|
|
145
|
-
const hook = { name: plugin.name, priority };
|
|
146
|
-
if (plugin.onRequest) {
|
|
147
|
-
insertHookSorted(this.pipelines.request, {
|
|
148
|
-
...hook,
|
|
149
|
-
run: plugin.onRequest,
|
|
150
|
-
});
|
|
151
|
-
this.hasRequestPlugins = true;
|
|
152
|
-
}
|
|
153
|
-
if (plugin.onResponse) {
|
|
154
|
-
const target = plugin.mode === "background"
|
|
155
|
-
? this.pipelines.responseSideEffects
|
|
156
|
-
: this.pipelines.responseMutators;
|
|
157
|
-
insertHookSorted(target, { ...hook, run: plugin.onResponse });
|
|
158
|
-
this.hasResponsePlugins = true;
|
|
159
|
-
}
|
|
160
|
-
if (plugin.onResponseData) {
|
|
161
|
-
insertHookSorted(this.pipelines.responseData, {
|
|
162
|
-
...hook,
|
|
163
|
-
run: plugin.onResponseData,
|
|
164
|
-
});
|
|
165
|
-
this.hasResponseDataPlugins = true;
|
|
166
|
-
}
|
|
167
|
-
if (plugin.onError) {
|
|
168
|
-
insertHookSorted(this.pipelines.error, { ...hook, run: plugin.onError });
|
|
169
|
-
this.hasErrorPlugins = true;
|
|
170
|
-
}
|
|
171
|
-
return this;
|
|
172
|
-
}
|
|
173
|
-
/**
|
|
174
|
-
* @ru Выполняет GET-запрос.
|
|
175
|
-
* @en Performs a GET request.
|
|
176
|
-
* @template T - Expected response body type.
|
|
177
|
-
* @param req - Request URL or RequestInterface object.
|
|
178
|
-
* @param signal - Optional abort signal.
|
|
179
|
-
* @returns Promise resolving to the HTTP response.
|
|
180
|
-
*/
|
|
181
|
-
get(req, signal) {
|
|
182
|
-
return this.dispatch(this.acquireReq("GET", req, undefined, signal));
|
|
183
|
-
}
|
|
184
|
-
/**
|
|
185
|
-
* @ru Выполняет POST-запрос с телом.
|
|
186
|
-
* @en Performs a POST request with a body.
|
|
187
|
-
* @template T - Expected response body type.
|
|
188
|
-
* @param req - Request URL or RequestInterface object.
|
|
189
|
-
* @param body - Request body data.
|
|
190
|
-
* @param signal - Optional abort signal.
|
|
191
|
-
* @returns Promise resolving to the HTTP response.
|
|
192
|
-
*/
|
|
193
|
-
post(req, body, signal) {
|
|
194
|
-
return this.dispatch(this.acquireReq("POST", req, body, signal));
|
|
195
|
-
}
|
|
196
|
-
/**
|
|
197
|
-
* @ru Выполняет PUT-запрос с телом.
|
|
198
|
-
* @en Performs a PUT request with a body.
|
|
199
|
-
* @template T - Expected response body type.
|
|
200
|
-
* @param req - Request URL or RequestInterface object.
|
|
201
|
-
* @param body - Request body data.
|
|
202
|
-
* @param signal - Optional abort signal.
|
|
203
|
-
* @returns Promise resolving to the HTTP response.
|
|
204
|
-
*/
|
|
205
|
-
put(req, body, signal) {
|
|
206
|
-
return this.dispatch(this.acquireReq("PUT", req, body, signal));
|
|
207
|
-
}
|
|
208
|
-
/**
|
|
209
|
-
* @ru Выполняет PATCH-запрос с телом.
|
|
210
|
-
* @en Performs a PATCH request with a body.
|
|
211
|
-
* @template T - Expected response body type.
|
|
212
|
-
* @param req - Request URL or RequestInterface object.
|
|
213
|
-
* @param body - Request body data.
|
|
214
|
-
* @param signal - Optional abort signal.
|
|
215
|
-
* @returns Promise resolving to the HTTP response.
|
|
216
|
-
*/
|
|
217
|
-
patch(req, body, signal) {
|
|
218
|
-
return this.dispatch(this.acquireReq("PATCH", req, body, signal));
|
|
219
|
-
}
|
|
220
|
-
/**
|
|
221
|
-
* @ru Выполняет DELETE-запрос.
|
|
222
|
-
* @en Performs a DELETE request.
|
|
223
|
-
* @template T - Expected response body type.
|
|
224
|
-
* @param req - Request URL or RequestInterface object.
|
|
225
|
-
* @param signal - Optional abort signal.
|
|
226
|
-
* @returns Promise resolving to the HTTP response.
|
|
227
|
-
*/
|
|
228
|
-
delete(req, signal) {
|
|
229
|
-
return this.dispatch(this.acquireReq("DELETE", req, undefined, signal));
|
|
230
|
-
}
|
|
231
|
-
/**
|
|
232
|
-
* @ru Выполняет OPTIONS-запрос.
|
|
233
|
-
* @en Performs an OPTIONS request.
|
|
234
|
-
* @template T - Expected response body type.
|
|
235
|
-
* @param req - Request URL or RequestInterface object.
|
|
236
|
-
* @param body - Optional request body data.
|
|
237
|
-
* @param signal - Optional abort signal.
|
|
238
|
-
* @returns Promise resolving to the HTTP response.
|
|
239
|
-
*/
|
|
240
|
-
options(req, body, signal) {
|
|
241
|
-
return this.dispatch(this.acquireReq("OPTIONS", req, body, signal));
|
|
242
|
-
}
|
|
243
|
-
/**
|
|
244
|
-
* @ru Выполняет HEAD-запрос (без тела ответа).
|
|
245
|
-
* @en Performs a HEAD request (no response body).
|
|
246
|
-
* @param req - Request URL or RequestInterface object.
|
|
247
|
-
* @param signal - Optional abort signal.
|
|
248
|
-
* @returns Promise resolving to the HTTP response with null body.
|
|
249
|
-
*/
|
|
250
|
-
head(req, signal) {
|
|
251
|
-
return this.dispatch(this.acquireReq("HEAD", req, undefined, signal));
|
|
252
|
-
}
|
|
253
|
-
/**
|
|
254
|
-
* @ru Инициирует потоковый GET-запрос. Тело ответа возвращается как ReadableStream.
|
|
255
|
-
* @en Initiates a streaming GET request. Response body is returned as a ReadableStream.
|
|
256
|
-
* @param req - Request URL or RequestInterface object.
|
|
257
|
-
* @param signal - Optional abort signal.
|
|
258
|
-
* @returns Promise resolving to the stream response.
|
|
259
|
-
*/
|
|
260
|
-
stream(req, signal) {
|
|
261
|
-
return this.dispatch(this.acquireReq("GET", req, undefined, signal, "stream"));
|
|
262
|
-
}
|
|
263
|
-
/**
|
|
264
|
-
* @ru Инициирует потоковый POST-запрос с телом. Тело ответа возвращается как ReadableStream.
|
|
265
|
-
* @en Initiates a streaming POST request with a body. Response body is returned as a ReadableStream.
|
|
266
|
-
* @template T - Expected response body type.
|
|
267
|
-
* @param req - Request URL or RequestInterface object.
|
|
268
|
-
* @param body - Request body data.
|
|
269
|
-
* @param signal - Optional abort signal.
|
|
270
|
-
* @returns Promise resolving to the stream response.
|
|
271
|
-
*/
|
|
272
|
-
postStream(req, body, signal) {
|
|
273
|
-
return this.dispatch(this.acquireReq("POST", req, body, signal, "stream"));
|
|
274
|
-
}
|
|
275
|
-
/**
|
|
276
|
-
* @ru Создаёт новый экземпляр клиента, объединяя текущую конфигурацию с переданными опциями.
|
|
277
|
-
* @en Creates a new client instance by merging the current configuration with provided options.
|
|
278
|
-
* @param options - Partial configuration options to extend.
|
|
279
|
-
* @returns A new HyperCore instance.
|
|
280
|
-
*/
|
|
281
|
-
extend(options) {
|
|
282
|
-
return new HyperCore({
|
|
283
|
-
...this.config,
|
|
284
|
-
...options,
|
|
285
|
-
network: {
|
|
286
|
-
...this.config.network,
|
|
287
|
-
...options.network,
|
|
288
|
-
stealth: options.network?.stealth || this.config.network?.stealth
|
|
289
|
-
? { ...this.config.network?.stealth, ...options.network?.stealth }
|
|
290
|
-
: undefined,
|
|
291
|
-
},
|
|
292
|
-
}, this.transportManager.transport ?? undefined);
|
|
293
|
-
}
|
|
294
|
-
/**
|
|
295
|
-
* @ru Создаёт полностью новый экземпляр клиента на основе переданных опций.
|
|
296
|
-
* @en Creates a completely new client instance based on provided options.
|
|
297
|
-
* @param options - Partial configuration options for the new instance.
|
|
298
|
-
* @returns A new HyperCore instance.
|
|
299
|
-
*/
|
|
300
|
-
create(options) {
|
|
301
|
-
return this.extend(options);
|
|
302
|
-
}
|
|
303
|
-
/**
|
|
304
|
-
* @ru Завершает работу клиента и освобождает ресурсы (соединения, пулы).
|
|
305
|
-
* @en Shuts down the client and releases resources (connections, pools).
|
|
306
|
-
* @param graceful - If true, waits for active requests to complete before closing.
|
|
307
|
-
* @returns Promise that resolves when shutdown is complete.
|
|
308
|
-
*/
|
|
309
|
-
destroy(graceful = true) {
|
|
310
|
-
return this.transportManager.destroy(graceful);
|
|
311
|
-
}
|
|
312
|
-
/**
|
|
313
|
-
* @ru Выполняет GET-запрос и возвращает распарсенное JSON-тело ответа.
|
|
314
|
-
* @en Performs a GET request and returns the parsed JSON response body.
|
|
315
|
-
* @template T - Expected type of the parsed JSON.
|
|
316
|
-
* @param req - Request URL or RequestInterface object.
|
|
317
|
-
* @param signal - Optional abort signal.
|
|
318
|
-
* @returns Promise resolving to the parsed JSON data.
|
|
319
|
-
*/
|
|
320
|
-
json(req, signal) {
|
|
321
|
-
return this.shortcut(req, signal).then((res) => {
|
|
322
|
-
if (res.json)
|
|
323
|
-
return res.json();
|
|
324
|
-
throw new Error("json() not supported");
|
|
325
|
-
});
|
|
326
|
-
}
|
|
327
|
-
/**
|
|
328
|
-
* @ru Выполняет GET-запрос и возвращает тело ответа как текст.
|
|
329
|
-
* @en Performs a GET request and returns the response body as text.
|
|
330
|
-
* @param req - Request URL or RequestInterface object.
|
|
331
|
-
* @param signal - Optional abort signal.
|
|
332
|
-
* @returns Promise resolving to the response text.
|
|
333
|
-
*/
|
|
334
|
-
text(req, signal) {
|
|
335
|
-
return this.shortcut(req, signal).then((res) => {
|
|
336
|
-
if (res.text)
|
|
337
|
-
return res.text();
|
|
338
|
-
throw new Error("text() not supported");
|
|
339
|
-
});
|
|
340
|
-
}
|
|
341
|
-
/**
|
|
342
|
-
* @ru Выполняет GET-запрос и немедленно отбрасывает тело ответа для освобождения ресурсов.
|
|
343
|
-
* @en Performs a GET request and immediately discards the response body to free resources.
|
|
344
|
-
* @param req - Request URL or RequestInterface object.
|
|
345
|
-
* @param signal - Optional abort signal.
|
|
346
|
-
* @returns Promise that resolves when the stream is drained.
|
|
347
|
-
*/
|
|
348
|
-
dump(req, signal) {
|
|
349
|
-
return this.shortcut(req, signal).then((res) => {
|
|
350
|
-
if (res.dump)
|
|
351
|
-
return res.dump();
|
|
352
|
-
});
|
|
353
|
-
}
|
|
354
|
-
/**
|
|
355
|
-
* @ru Обрабатывает ошибку диспетчеризации через конвейер плагинов обработки ошибок.
|
|
356
|
-
* @en Handles dispatch errors through the error handling plugin pipeline.
|
|
357
|
-
* @template T - Expected response body type.
|
|
358
|
-
* @param error - The error that occurred.
|
|
359
|
-
* @param req - The original internal request.
|
|
360
|
-
* @returns Promise resolving to a recovered HTTP response, or throws if unrecoverable.
|
|
361
|
-
*/
|
|
362
|
-
async handleDispatchError(error, req) {
|
|
363
|
-
try {
|
|
364
|
-
if (this.hasErrorPlugins) {
|
|
365
|
-
const recovered = await executeErrorPipeline(this.pipelines.error, error, req, this.pluginCtx);
|
|
366
|
-
if (recovered != null) {
|
|
367
|
-
if (this.hasResponsePlugins) {
|
|
368
|
-
const meta = req.meta;
|
|
369
|
-
const reqForPipeline = this.pipelines.responseSideEffects.length > 0
|
|
370
|
-
? {
|
|
371
|
-
...req,
|
|
372
|
-
meta: {
|
|
373
|
-
...meta,
|
|
374
|
-
timings: meta?.timings ? { ...meta.timings } : undefined,
|
|
375
|
-
},
|
|
376
|
-
}
|
|
377
|
-
: req;
|
|
378
|
-
const syncResult = executeResponsePipeline(this.pipelines.responseMutators, this.pipelines.responseSideEffects, recovered, reqForPipeline, this.pluginCtx, this.config.logger);
|
|
379
|
-
if (syncResult instanceof Promise) {
|
|
380
|
-
await syncResult;
|
|
381
|
-
}
|
|
382
|
-
}
|
|
383
|
-
return recovered;
|
|
384
|
-
}
|
|
385
|
-
}
|
|
386
|
-
throw error;
|
|
387
|
-
}
|
|
388
|
-
finally {
|
|
389
|
-
this.recycleRequest(req);
|
|
390
|
-
}
|
|
391
|
-
}
|
|
392
|
-
/**
|
|
393
|
-
* @ru Создаёт или переиспользует объект InternalRequest из пула, заполняя его поля.
|
|
394
|
-
* @en Creates or reuses an InternalRequest object from the pool, populating its fields.
|
|
395
|
-
* @param method - HTTP method (GET, POST, etc.).
|
|
396
|
-
* @param req - Request URL or RequestInterface object.
|
|
397
|
-
* @param body - Optional request body data.
|
|
398
|
-
* @param signal - Optional abort signal.
|
|
399
|
-
* @param responseType - Optional response type hint ('stream').
|
|
400
|
-
* @returns The populated internal request object.
|
|
401
|
-
*/
|
|
402
|
-
acquireReq(method, req, body, signal, responseType) {
|
|
403
|
-
const pooled = requestPool.pop();
|
|
404
|
-
const internalReq = pooled ?? {
|
|
405
|
-
method: "GET",
|
|
406
|
-
url: "",
|
|
407
|
-
headers: this.defaultHeaders,
|
|
408
|
-
body: undefined,
|
|
409
|
-
signal: undefined,
|
|
410
|
-
meta: {
|
|
411
|
-
responseType: undefined,
|
|
412
|
-
timings: {
|
|
413
|
-
networkMs: undefined,
|
|
414
|
-
},
|
|
415
|
-
},
|
|
416
|
-
stealth: undefined,
|
|
417
|
-
};
|
|
418
|
-
const metaObj = internalReq.meta;
|
|
419
|
-
if (typeof req === "string") {
|
|
420
|
-
internalReq.method = method;
|
|
421
|
-
internalReq.url = this.resolveUrl(req);
|
|
422
|
-
internalReq.headers = this.hasRequestPlugins
|
|
423
|
-
? { ...this.defaultHeaders }
|
|
424
|
-
: this.defaultHeaders;
|
|
425
|
-
internalReq.body = body !== undefined ? normalizeBody(method, body) : undefined;
|
|
426
|
-
internalReq.signal = signal;
|
|
427
|
-
metaObj.responseType = responseType;
|
|
428
|
-
internalReq.stealth = this.config.network?.stealth;
|
|
429
|
-
return internalReq;
|
|
430
|
-
}
|
|
431
|
-
const rawUrl = normalizeUrl(req);
|
|
432
|
-
if (!rawUrl)
|
|
433
|
-
throw new Error(`[HyperCore] URL is undefined for ${method}`);
|
|
434
|
-
let finalUrl;
|
|
435
|
-
if (req.query) {
|
|
436
|
-
const cacheKey = rawUrl + "_base";
|
|
437
|
-
let baseUrl = urlCache[cacheKey];
|
|
438
|
-
if (!baseUrl) {
|
|
439
|
-
baseUrl = this.config.baseURL
|
|
440
|
-
? new URL(rawUrl, this.config.baseURL).href
|
|
441
|
-
: new URL(rawUrl).href;
|
|
442
|
-
this.ensureCacheSpace();
|
|
443
|
-
urlCache[cacheKey] = baseUrl;
|
|
444
|
-
urlCacheCount++;
|
|
445
|
-
}
|
|
446
|
-
const urlObj = new URL(baseUrl);
|
|
447
|
-
this.appendQueryParams(urlObj, req.query);
|
|
448
|
-
finalUrl = urlObj.href;
|
|
449
|
-
}
|
|
450
|
-
else {
|
|
451
|
-
let cachedUrl = urlCache[rawUrl];
|
|
452
|
-
if (!cachedUrl) {
|
|
453
|
-
cachedUrl = this.config.baseURL
|
|
454
|
-
? new URL(rawUrl, this.config.baseURL).href
|
|
455
|
-
: new URL(rawUrl).href;
|
|
456
|
-
if (urlCacheCount >= MAX_CACHE_SIZE) {
|
|
457
|
-
urlCache = Object.create(null);
|
|
458
|
-
urlCacheCount = 0;
|
|
459
|
-
}
|
|
460
|
-
urlCache[rawUrl] = cachedUrl;
|
|
461
|
-
urlCacheCount++;
|
|
462
|
-
}
|
|
463
|
-
finalUrl = cachedUrl;
|
|
464
|
-
}
|
|
465
|
-
internalReq.method = method;
|
|
466
|
-
internalReq.url = finalUrl;
|
|
467
|
-
internalReq.headers = req.headers
|
|
468
|
-
? mergeHeadersFast(this.defaultHeaders, req.headers)
|
|
469
|
-
: { ...this.defaultHeaders };
|
|
470
|
-
internalReq.body = normalizeBody(method, req.body ?? body);
|
|
471
|
-
internalReq.signal = req.signal ?? signal;
|
|
472
|
-
metaObj.responseType =
|
|
473
|
-
responseType ?? req.meta?.responseType;
|
|
474
|
-
if (req.stealth) {
|
|
475
|
-
internalReq.stealth = this.config.network?.stealth
|
|
476
|
-
? { ...this.config.network.stealth, ...req.stealth }
|
|
477
|
-
: req.stealth;
|
|
478
|
-
}
|
|
479
|
-
else {
|
|
480
|
-
internalReq.stealth = this.config.network?.stealth;
|
|
481
|
-
}
|
|
482
|
-
return internalReq;
|
|
483
|
-
}
|
|
484
|
-
ensureCacheSpace() {
|
|
485
|
-
if (urlCacheCount >= MAX_CACHE_SIZE) {
|
|
486
|
-
urlCache = Object.create(null);
|
|
487
|
-
urlCacheCount = 0;
|
|
488
|
-
}
|
|
489
|
-
}
|
|
490
|
-
/**
|
|
491
|
-
* @ru Возвращает объект запроса в пул для переиспользования, очищая ссылки для GC.
|
|
492
|
-
* @en Returns the request object to the pool for reuse, clearing references for GC.
|
|
493
|
-
* @param req - The internal request object to recycle.
|
|
494
|
-
*/
|
|
495
|
-
recycleRequest(req) {
|
|
496
|
-
if (requestPool.length < MAX_POOL_SIZE) {
|
|
497
|
-
req.method = "GET";
|
|
498
|
-
req.url = "";
|
|
499
|
-
req.headers = this.defaultHeaders;
|
|
500
|
-
req.body = undefined;
|
|
501
|
-
req.signal = undefined;
|
|
502
|
-
req.stealth = undefined;
|
|
503
|
-
const m = req.meta;
|
|
504
|
-
if (m) {
|
|
505
|
-
m.responseType = undefined;
|
|
506
|
-
if (m.timings) {
|
|
507
|
-
for (const key in m.timings) {
|
|
508
|
-
m.timings[key] = undefined;
|
|
509
|
-
}
|
|
510
|
-
}
|
|
511
|
-
}
|
|
512
|
-
requestPool.push(req);
|
|
513
|
-
}
|
|
514
|
-
}
|
|
515
|
-
/**
|
|
516
|
-
* @ru Разрешает и кэширует URL, нормализуя его через URL API при необходимости.
|
|
517
|
-
* @en Resolves and caches the URL, normalizing it via the URL API when necessary.
|
|
518
|
-
* @param url - The raw URL string.
|
|
519
|
-
* @returns The resolved and cached URL string.
|
|
520
|
-
*/
|
|
521
|
-
resolveUrl(url) {
|
|
522
|
-
if (!url)
|
|
523
|
-
throw new Error("[HyperCore] URL is undefined");
|
|
524
|
-
let finalUrl = urlCache[url];
|
|
525
|
-
if (finalUrl)
|
|
526
|
-
return finalUrl;
|
|
527
|
-
const isAbsolute = url.startsWith("http://") || url.startsWith("https://");
|
|
528
|
-
if (isAbsolute && !url.includes("?")) {
|
|
529
|
-
finalUrl = url;
|
|
530
|
-
}
|
|
531
|
-
else {
|
|
532
|
-
finalUrl = this.config.baseURL ? new URL(url, this.config.baseURL).href : new URL(url).href;
|
|
533
|
-
}
|
|
534
|
-
if (urlCacheCount >= MAX_CACHE_SIZE) {
|
|
535
|
-
urlCache = Object.create(null);
|
|
536
|
-
urlCacheCount = 0;
|
|
537
|
-
}
|
|
538
|
-
urlCache[url] = finalUrl;
|
|
539
|
-
urlCacheCount++;
|
|
540
|
-
return finalUrl;
|
|
541
|
-
}
|
|
542
|
-
/**
|
|
543
|
-
* @ru Добавляет query-параметры к объект URL, поддерживая массивы значений.
|
|
544
|
-
* @en Appends query parameters to the URL object, supporting arrays of values.
|
|
545
|
-
* @param url - The URL object to modify.
|
|
546
|
-
* @param query - Record of query parameter key-value pairs.
|
|
547
|
-
*/
|
|
548
|
-
appendQueryParams(url, query) {
|
|
549
|
-
for (const k in query) {
|
|
550
|
-
if (Object.prototype.hasOwnProperty.call(query, k)) {
|
|
551
|
-
const v = query[k];
|
|
552
|
-
if (v == null)
|
|
553
|
-
continue;
|
|
554
|
-
if (Array.isArray(v)) {
|
|
555
|
-
for (let j = 0; j < v.length; j++)
|
|
556
|
-
url.searchParams.append(k, String(v[j]));
|
|
557
|
-
}
|
|
558
|
-
else {
|
|
559
|
-
url.searchParams.set(k, String(v));
|
|
560
|
-
}
|
|
561
|
-
}
|
|
562
|
-
}
|
|
563
|
-
}
|
|
564
|
-
/**
|
|
565
|
-
* @ru Выполняет быстрый запрос с автоматическим определением HTTP-метода.
|
|
566
|
-
* @en Performs a shortcut request with automatic HTTP method detection.
|
|
567
|
-
* @param req - Request URL or RequestInterface object.
|
|
568
|
-
* @param signal - Optional abort signal.
|
|
569
|
-
* @returns Promise resolving to the HTTP response.
|
|
570
|
-
*/
|
|
571
|
-
shortcut(req, signal) {
|
|
572
|
-
const method = typeof req === "string" ? "GET" : (req.method ?? "GET");
|
|
573
|
-
return this.dispatch(this.acquireReq(method, req, undefined, signal));
|
|
574
|
-
}
|
|
575
|
-
}
|
|
576
|
-
//# sourceMappingURL=HyperCore.js.map
|
|
1
|
+
"use strict";import{defaultConfig as u}from"../defaultConfig.js";import{mapResponseFast as R,mapStreamFast as y}from"../utils/response.js";import{TransportManager as P}from"../transports/manager.js";import{createPipelines as E,executeErrorPipeline as x,executeRequestPipeline as k,executeResponsePipeline as d,executeResponseDataPipeline as q,insertHookSorted as c}from"../utils/pipeline.js";import{normalizeHeaders as M,normalizeBodyForTransport as T}from"../utils/normalize.js";import{calcDelay as f,shouldRetry as S,drainBody as b}from"../utils/retryUtils.js";import{TimeoutError as D}from"../utils/errors.js";import{RequestBuilder as C}from"./RequestBuilder.js";const m=p=>new Promise(t=>setTimeout(t,p)),H=64;class A{max;current=0;queue=[];constructor(t){this.max=t}acquire(){return this.current<this.max?(this.current++,Promise.resolve()):new Promise(t=>{this.queue.push(()=>{this.current++,t()})})}release(){const t=this.queue.shift();t?t():this.current--}}export class HyperCore{config;transportManager;transportReady;defaultHeaders;pluginCtx;pipelines=E();requestBuilder=new C;requestPool=[];semaphore=null;hasRequestPlugins=!1;hasResponseDataPlugins=!1;hasResponsePlugins=!1;hasErrorPlugins=!1;constructor(t=u,e){this.config={...u,...t,network:{...u.network,...t.network,stealth:t.network?.stealth||u.network?.stealth?Object.assign({},u.network?.stealth,t.network?.stealth):void 0}},this.transportManager=new P(this.config,e),this.transportReady=this.transportManager.getSync()?Promise.resolve(this.transportManager.getSync()):this.transportManager.ensure(),this.defaultHeaders=M({Accept:"application/json, text/plain, */*","Accept-Encoding":"gzip, deflate, br","User-Agent":this.config.network?.userAgent??"Hyperttp/2.0",...this.config.network?.headers});const s=this.config.network?.maxConcurrent;this.semaphore=s!=null&&s>0?new A(s):null,this.pluginCtx={config:this.config,core:this}}async getTransportName(){return(this.transportManager.transport??await this.transportManager.get()).constructor.name}async dispatch(t){const e=this.config.retry??{},s=e.maxRetries??0;for(let i=0;;i++)try{if(this.hasRequestPlugins){const o=k(this.pipelines.request,t,this.pluginCtx),h=o instanceof Promise?await o:o;if(h!=null)return this.recycleRequest(t),h}t.body!=null&&(t.body=T(t.body,t.headers));const n=this.transportManager.transport??this.transportManager.getSync()??await this.transportReady;this.semaphore&&await this.semaphore.acquire();let r;const g=performance.now();try{r=await n.execute(t)}finally{this.semaphore?.release()}const w=performance.now()-g,a=t.meta;if(a.timings&&(a.timings.networkMs=w),i<s&&S(r.status,e)){await b(r.body),await m(f(i,e));continue}if(this.hasResponseDataPlugins){const o=q(this.pipelines.responseData,r,this.pluginCtx);r=o instanceof Promise?await o:o}const l=a.responseType==="stream"?y(r):R(r);if(this.hasResponsePlugins){const o=this.pipelines.responseSideEffects.length>0?{...t,meta:{...a,timings:a.timings?{...a.timings}:void 0}}:t,h=d(this.pipelines.responseMutators,this.pipelines.responseSideEffects,l,o,this.pluginCtx,this.config.logger);h instanceof Promise&&await h}return this.recycleRequest(t),l}catch(n){if(n instanceof Error&&n.name==="AbortError"){const r=this.config.network?.timeout;return r!=null&&r>0?this.handleDispatchError(new D(t.url,r),t):this.handleDispatchError(n,t)}if(i<s&&!t.signal?.aborted){await m(f(i,e));continue}return this.handleDispatchError(n,t)}}use(t){if(!(t.enabled?t.enabled(this.config):!0))return this;t.setup?.(this.pluginCtx);const s=t.priority??0,i={name:t.name,priority:s};if(t.onRequest&&(c(this.pipelines.request,{...i,run:t.onRequest}),this.hasRequestPlugins=!0),t.onResponse){const n=t.mode==="background"?this.pipelines.responseSideEffects:this.pipelines.responseMutators;c(n,{...i,run:t.onResponse}),this.hasResponsePlugins=!0}return t.onResponseData&&(c(this.pipelines.responseData,{...i,run:t.onResponseData}),this.hasResponseDataPlugins=!0),t.onError&&(c(this.pipelines.error,{...i,run:t.onError}),this.hasErrorPlugins=!0),this}get(t,e){return this.dispatch(this.acquireReq("GET",t,void 0,e))}post(t,e,s){return this.dispatch(this.acquireReq("POST",t,e,s))}put(t,e,s){return this.dispatch(this.acquireReq("PUT",t,e,s))}patch(t,e,s){return this.dispatch(this.acquireReq("PATCH",t,e,s))}delete(t,e){return this.dispatch(this.acquireReq("DELETE",t,void 0,e))}options(t,e,s){return this.dispatch(this.acquireReq("OPTIONS",t,e,s))}head(t,e){return this.dispatch(this.acquireReq("HEAD",t,void 0,e))}stream(t,e){return this.dispatch(this.acquireReq("GET",t,void 0,e,"stream"))}postStream(t,e,s){return this.dispatch(this.acquireReq("POST",t,e,s,"stream"))}extend(t){return new HyperCore({...this.config,...t,network:{...this.config.network,...t.network,stealth:t.network?.stealth||this.config.network?.stealth?{...this.config.network?.stealth,...t.network?.stealth}:void 0}},this.transportManager.transport??void 0)}create(t){return this.extend(t)}destroy(t=!0){return this.transportManager.destroy(t)}json(t,e){return this.shortcut(t,e).then(s=>{if(s.json)return s.json();throw new Error("json() not supported")})}text(t,e){return this.shortcut(t,e).then(s=>{if(s.text)return s.text();throw new Error("text() not supported")})}dump(t,e){return this.shortcut(t,e).then(s=>{if(s.dump)return s.dump()})}async handleDispatchError(t,e){try{if(this.hasErrorPlugins){const s=await x(this.pipelines.error,t,e,this.pluginCtx);if(s!=null){if(this.hasResponsePlugins){const i=e.meta,n=this.pipelines.responseSideEffects.length>0?{...e,meta:{...i,timings:i?.timings?{...i.timings}:void 0}}:e,r=d(this.pipelines.responseMutators,this.pipelines.responseSideEffects,s,n,this.pluginCtx,this.config.logger);r instanceof Promise&&await r}return s}}throw t}finally{this.recycleRequest(e)}}acquireReq(t,e,s,i,n){const r=this.requestPool.pop();return this.requestBuilder.build(t,e,s,i,n,this.defaultHeaders,this.config,r)}recycleRequest(t){if(this.requestPool.length<H){t.method="GET",t.url="",t.headers=this.defaultHeaders,t.body=void 0,t.signal=void 0,t.stealth=void 0;const e=t.meta;if(e&&(e.responseType=void 0,e.timings))for(const s in e.timings)e.timings[s]=void 0;this.requestPool.push(t)}}shortcut(t,e){const s=typeof t=="string"?"GET":t.method??"GET";return this.dispatch(this.acquireReq(s,t,void 0,e))}}
|
|
2
|
+
//# sourceMappingURL=HyperCore.js.map
|