@hyperttp/core 1.5.5 → 2.0.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/Core/HyperCore.d.ts +176 -141
- package/Core/HyperCore.d.ts.map +1 -1
- package/Core/HyperCore.js +1 -1
- package/Core/HyperCore.js.map +3 -3
- package/README.md +260 -316
- package/defaultConfig.d.ts +9 -4
- package/defaultConfig.d.ts.map +1 -1
- package/defaultConfig.js +1 -1
- package/defaultConfig.js.map +2 -2
- package/index.d.ts +3 -0
- package/index.d.ts.map +1 -1
- package/index.js +1 -1
- package/index.js.map +2 -2
- package/package.json +39 -33
- package/protocols/manager.d.ts +31 -0
- package/protocols/manager.d.ts.map +1 -0
- package/protocols/manager.js +2 -0
- package/protocols/manager.js.map +7 -0
- package/protocols/rest/index.d.ts +9 -0
- package/protocols/rest/index.d.ts.map +1 -0
- package/protocols/rest/index.js +2 -0
- package/protocols/rest/index.js.map +7 -0
- package/protocols/rest/receiver.d.ts +31 -0
- package/protocols/rest/receiver.d.ts.map +1 -0
- package/protocols/rest/receiver.js +2 -0
- package/protocols/rest/receiver.js.map +7 -0
- package/protocols/rest/sender.d.ts +19 -0
- package/protocols/rest/sender.d.ts.map +1 -0
- package/protocols/rest/sender.js +2 -0
- package/protocols/rest/sender.js.map +7 -0
- package/protocols/rest/type.d.ts +71 -0
- package/protocols/rest/type.d.ts.map +1 -0
- package/protocols/rest/type.js +2 -0
- package/protocols/rest/type.js.map +7 -0
- package/rest.d.ts +2 -0
- package/rest.d.ts.map +1 -0
- package/rest.js +2 -0
- package/rest.js.map +7 -0
- package/transports/fetch.d.ts +24 -0
- package/transports/fetch.d.ts.map +1 -0
- package/transports/fetch.js +2 -0
- package/transports/fetch.js.map +7 -0
- package/transports/manager.d.ts +17 -80
- package/transports/manager.d.ts.map +1 -1
- package/transports/manager.js +1 -6
- package/transports/manager.js.map +3 -3
- package/utils/abort.d.ts +23 -0
- package/utils/abort.d.ts.map +1 -0
- package/utils/abort.js +2 -0
- package/utils/abort.js.map +7 -0
- package/utils/errors.d.ts +12 -2
- package/utils/errors.d.ts.map +1 -1
- package/utils/errors.js +1 -1
- package/utils/errors.js.map +3 -3
- package/utils/merge.d.ts.map +1 -1
- package/utils/merge.js +1 -1
- package/utils/merge.js.map +2 -2
- package/Core/RequestBuilder.d.ts +0 -32
- package/Core/RequestBuilder.d.ts.map +0 -1
- package/Core/RequestBuilder.js +0 -2
- package/Core/RequestBuilder.js.map +0 -7
- package/transports/browser.d.ts +0 -37
- package/transports/browser.d.ts.map +0 -1
- package/transports/browser.js +0 -2
- package/transports/browser.js.map +0 -7
- package/transports/node.d.ts +0 -33
- package/transports/node.d.ts.map +0 -1
- package/transports/node.js +0 -2
- package/transports/node.js.map +0 -7
- package/utils/normalize.d.ts +0 -35
- package/utils/normalize.d.ts.map +0 -1
- package/utils/normalize.js +0 -2
- package/utils/normalize.js.map +0 -7
- package/utils/pipeline.d.ts +0 -63
- package/utils/pipeline.d.ts.map +0 -1
- package/utils/pipeline.js +0 -2
- package/utils/pipeline.js.map +0 -7
- package/utils/response.d.ts +0 -113
- package/utils/response.d.ts.map +0 -1
- package/utils/response.js +0 -2
- package/utils/response.js.map +0 -7
- package/utils/retryUtils.d.ts +0 -17
- package/utils/retryUtils.d.ts.map +0 -1
- package/utils/retryUtils.js +0 -2
- package/utils/retryUtils.js.map +0 -7
package/Core/HyperCore.d.ts
CHANGED
|
@@ -1,25 +1,46 @@
|
|
|
1
|
-
import type {
|
|
1
|
+
import type { HyperClientOptions, HyperPlugin, HyperProtocol, HyperProtocols, HyperReceiver, HyperSender, HyperServerListenOptions, HyperTransport, IHyperCore, SenderProtocol, SendRequest, TransportServer, UniversalResponse } from "@hyperttp/types";
|
|
2
|
+
export interface HyperCore extends HyperProtocols {
|
|
3
|
+
}
|
|
2
4
|
/**
|
|
3
|
-
* @ru
|
|
4
|
-
*
|
|
5
|
+
* @ru Универсальное ядро v2.0.0. Протокол-независимый диспетчер: регистрирует
|
|
6
|
+
* единые модули протоколов (Sender + Receiver), выполняет клиентский цикл
|
|
7
|
+
* prepare → send → parse и серверный цикл receive → handle → respond через
|
|
8
|
+
* физический транспорт, а также прогоняет хуки плагинов.
|
|
9
|
+
* @en Universal core v2.0.0. Protocol-agnostic dispatcher: registers unified
|
|
10
|
+
* protocol modules (Sender + Receiver), runs the client cycle prepare → send → parse
|
|
11
|
+
* and the server cycle receive → handle → respond through the physical transport,
|
|
12
|
+
* and executes plugin hooks.
|
|
5
13
|
*/
|
|
6
14
|
export declare class HyperCore implements IHyperCore {
|
|
7
|
-
config:
|
|
8
|
-
private readonly
|
|
9
|
-
private readonly transportReady;
|
|
10
|
-
private readonly defaultHeaders;
|
|
15
|
+
readonly config: HyperClientOptions;
|
|
16
|
+
private readonly registry;
|
|
11
17
|
private readonly pluginCtx;
|
|
12
|
-
private readonly
|
|
13
|
-
private readonly
|
|
14
|
-
private readonly
|
|
15
|
-
private
|
|
16
|
-
private
|
|
17
|
-
private
|
|
18
|
-
private
|
|
19
|
-
private
|
|
20
|
-
private
|
|
21
|
-
private
|
|
22
|
-
constructor(config?:
|
|
18
|
+
private readonly plugins;
|
|
19
|
+
private readonly servers;
|
|
20
|
+
private readonly protocolNamespaces;
|
|
21
|
+
private readonly generatedFlatMethods;
|
|
22
|
+
private readonly transportPromises;
|
|
23
|
+
private readonly transports;
|
|
24
|
+
private readonly retainedTransports;
|
|
25
|
+
private readonly fixedTransport;
|
|
26
|
+
private destroyPromise;
|
|
27
|
+
private isDestroyed;
|
|
28
|
+
constructor(config?: Partial<HyperClientOptions>, transport?: HyperTransport, sharedTransportPromises?: ReadonlyMap<SenderProtocol, Promise<HyperTransport>>);
|
|
29
|
+
/**
|
|
30
|
+
* @ru Получает зарегистрированный модуль протокола (Sender + Receiver).
|
|
31
|
+
* @en Gets a registered protocol module (Sender + Receiver).
|
|
32
|
+
*/
|
|
33
|
+
getProtocol<P extends SenderProtocol>(protocol: P): HyperProtocol<unknown, unknown, unknown, unknown, P> | undefined;
|
|
34
|
+
/**
|
|
35
|
+
* @ru Получает зарегистрированный сендер протокола.
|
|
36
|
+
* @en Gets a registered protocol sender.
|
|
37
|
+
*/
|
|
38
|
+
getSender<P extends SenderProtocol>(protocol: P): HyperSender<unknown, unknown, unknown, unknown, P> | undefined;
|
|
39
|
+
/**
|
|
40
|
+
* @ru Получает зарегистрированный ресивер протокола.
|
|
41
|
+
* @en Gets a registered protocol receiver.
|
|
42
|
+
*/
|
|
43
|
+
getReceiver<P extends SenderProtocol>(protocol: P): HyperReceiver<unknown, unknown, unknown, unknown, P> | undefined;
|
|
23
44
|
/**
|
|
24
45
|
* @ru Возвращает имя текущего транспорта.
|
|
25
46
|
* @en Returns the name of the current transport.
|
|
@@ -27,145 +48,159 @@ export declare class HyperCore implements IHyperCore {
|
|
|
27
48
|
*/
|
|
28
49
|
getTransportName(): Promise<string>;
|
|
29
50
|
/**
|
|
30
|
-
* @ru
|
|
31
|
-
*
|
|
32
|
-
* @
|
|
33
|
-
*
|
|
51
|
+
* @ru Возвращает имя сендера протокола (по умолчанию — "rest").
|
|
52
|
+
* Протокол резолвится лениво, если ещё не зарегистрирован.
|
|
53
|
+
* @en Returns the sender constructor name for a protocol (default "rest").
|
|
54
|
+
* The protocol is resolved lazily if not registered yet.
|
|
55
|
+
* @param protocol - The protocol to inspect.
|
|
56
|
+
* @returns Sender constructor name.
|
|
57
|
+
*/
|
|
58
|
+
getSenderName(protocol?: SenderProtocol): Promise<string>;
|
|
59
|
+
/**
|
|
60
|
+
* @ru Возвращает имя ресивера протокола (по умолчанию — "rest").
|
|
61
|
+
* Протокол резолвится лениво, если ещё не зарегистрирован.
|
|
62
|
+
* @en Returns the receiver constructor name for a protocol (default "rest").
|
|
63
|
+
* The protocol is resolved lazily if not registered yet.
|
|
64
|
+
* @param protocol - The protocol to inspect.
|
|
65
|
+
* @returns Receiver constructor name.
|
|
66
|
+
*/
|
|
67
|
+
getReceiverName(protocol?: SenderProtocol): Promise<string>;
|
|
68
|
+
/**
|
|
69
|
+
* @ru Возвращает имя модуля протокола (по умолчанию — "rest"): предпочитает
|
|
70
|
+
* `name`, затем `constructor.name`, затем идентификатор протокола.
|
|
71
|
+
* Протокол резолвится лениво, если ещё не зарегистрирован.
|
|
72
|
+
* @en Returns the protocol module name (default "rest"): prefers `name`, then
|
|
73
|
+
* `constructor.name`, then the protocol identifier.
|
|
74
|
+
* The protocol is resolved lazily if not registered yet.
|
|
75
|
+
* @param protocol - The protocol to inspect.
|
|
76
|
+
* @returns The protocol module display name.
|
|
77
|
+
*/
|
|
78
|
+
getProtocolName(protocol?: SenderProtocol): Promise<string>;
|
|
79
|
+
/**
|
|
80
|
+
* @ru Регистрирует единый модуль протокола и раскрывает методы его сендера
|
|
81
|
+
* на ядре (например, `core.rest` для REST).
|
|
82
|
+
* @en Registers a unified protocol module and exposes its sender methods on the
|
|
83
|
+
* core (e.g., `core.rest` for REST).
|
|
84
|
+
* @param protocol - The protocol module to register.
|
|
85
|
+
* @returns This instance for chaining.
|
|
86
|
+
*/
|
|
87
|
+
registerProtocol<P extends SenderProtocol>(protocol: HyperProtocol<unknown, unknown, unknown, unknown, P>): this;
|
|
88
|
+
/**
|
|
89
|
+
* @ru Регистрирует сендер протокола, оборачивая его в модуль протокола.
|
|
90
|
+
* Существующий ресивер того же протокола сохраняется.
|
|
91
|
+
* @en Registers a protocol sender, wrapping it into a protocol module.
|
|
92
|
+
* An existing receiver for the same protocol is preserved.
|
|
93
|
+
* @param sender - The protocol sender to register.
|
|
94
|
+
* @returns This instance for chaining.
|
|
34
95
|
*/
|
|
35
|
-
|
|
96
|
+
registerSender<P extends SenderProtocol>(sender: HyperSender<unknown, unknown, unknown, unknown, P>): this;
|
|
36
97
|
/**
|
|
37
|
-
* @ru Регистрирует
|
|
38
|
-
*
|
|
98
|
+
* @ru Регистрирует ресивер протокола, оборачивая его в модуль протокола.
|
|
99
|
+
* Существующий сендер того же протокола сохраняется.
|
|
100
|
+
* @en Registers a protocol receiver, wrapping it into a protocol module.
|
|
101
|
+
* An existing sender for the same protocol is preserved.
|
|
102
|
+
* @param receiver - The protocol receiver to register.
|
|
103
|
+
* @returns This instance for chaining.
|
|
104
|
+
*/
|
|
105
|
+
registerReceiver<P extends SenderProtocol>(receiver: HyperReceiver<unknown, unknown, unknown, unknown, P>): this;
|
|
106
|
+
/**
|
|
107
|
+
* @ru Создаёт ленивый namespace методов протокола: методы доступны ещё до
|
|
108
|
+
* регистрации протокола и резолвятся по требованию при первом вызове.
|
|
109
|
+
* @en Creates a lazy protocol methods namespace: methods are reachable before
|
|
110
|
+
* the protocol is registered and are resolved on first call.
|
|
111
|
+
* @param protocol - The protocol to expose lazily.
|
|
112
|
+
* @returns A Proxy that dispatches method calls to the resolved protocol sender.
|
|
113
|
+
*/
|
|
114
|
+
private createLazyNamespace;
|
|
115
|
+
/**
|
|
116
|
+
* @ru Разрешает протокол по требованию и вызывает метод `methods`-поверхности
|
|
117
|
+
* его сендера, биндя ядро первым аргументом.
|
|
118
|
+
* @en Resolves the protocol on demand and calls a method on its sender
|
|
119
|
+
* `methods` surface, binding the core as the first argument.
|
|
120
|
+
* @param protocol - The protocol identifier.
|
|
121
|
+
* @param name - The method name on the sender surface.
|
|
122
|
+
* @param args - Arguments forwarded after the core instance.
|
|
123
|
+
* @returns The result of the sender method call.
|
|
124
|
+
*/
|
|
125
|
+
private dispatchLazyMethod;
|
|
126
|
+
/**
|
|
127
|
+
* @ru Основной метод диспетчеризации: выбирает сендер по протоколу и выполняет
|
|
128
|
+
* трёхфазный цикл с поддержкой плагинов.
|
|
129
|
+
* @en Main dispatch method: resolves the sender by protocol and runs the three-phase
|
|
130
|
+
* cycle with plugin support.
|
|
131
|
+
* @param req - The universal request envelope.
|
|
132
|
+
* @returns A promise resolving to the normalized universal response.
|
|
133
|
+
*/
|
|
134
|
+
send<TInput = unknown, TOutput = unknown, P extends string = string>(req: SendRequest<TInput, P>): Promise<UniversalResponse<TOutput>>;
|
|
135
|
+
private resolveRequestSender;
|
|
136
|
+
private runResponseHooks;
|
|
137
|
+
private reportBackgroundPluginError;
|
|
138
|
+
/**
|
|
139
|
+
* @ru Атомарно получает транспорт для конкретного протокола и удерживает
|
|
140
|
+
* каждый физический экземпляр ровно один раз за время жизни ядра.
|
|
141
|
+
* @en Atomically acquires a transport for a protocol and retains each physical
|
|
142
|
+
* instance exactly once for the lifetime of this core.
|
|
143
|
+
*/
|
|
144
|
+
private acquireTransport;
|
|
145
|
+
private resolveAndRetainTransport;
|
|
146
|
+
private retainResolvedTransport;
|
|
147
|
+
/**
|
|
148
|
+
* @ru Выполняет ядро цикла запроса: prepare → send → parse через физический
|
|
149
|
+
* транспорт. Транспорт получается через `acquireTransport()`.
|
|
150
|
+
* @en Runs the core request cycle: prepare → send → parse through the physical
|
|
151
|
+
* transport. The transport is acquired via `acquireTransport()`.
|
|
152
|
+
* @param sender - The resolved protocol sender.
|
|
153
|
+
* @param req - The (possibly plugin-modified) universal request.
|
|
154
|
+
* @param ctx - The per-request execution context.
|
|
155
|
+
* @returns The normalized universal response.
|
|
156
|
+
*/
|
|
157
|
+
private runSender;
|
|
158
|
+
/**
|
|
159
|
+
* @ru Запускает сервер для указанного протокола: связывает транспорт, ресивер и
|
|
160
|
+
* application handler в цепочку receive → handle → respond.
|
|
161
|
+
* @en Starts a server for the given protocol, wiring transport, receiver, and
|
|
162
|
+
* application handler into the receive → handle → respond pipeline.
|
|
163
|
+
* @template P - The protocol identifier.
|
|
164
|
+
* @param options - The server listen options.
|
|
165
|
+
* @returns A promise resolving to the transport server handle.
|
|
166
|
+
*/
|
|
167
|
+
listen<P extends SenderProtocol = SenderProtocol>(options: HyperServerListenOptions<P>): Promise<TransportServer>;
|
|
168
|
+
/**
|
|
169
|
+
* @ru Регистрирует плагин. Пропускает отключённые плагины.
|
|
170
|
+
* @en Registers a plugin. Skips disabled plugins.
|
|
39
171
|
* @param plugin - The plugin instance to register.
|
|
40
172
|
* @returns This instance for chaining.
|
|
41
173
|
*/
|
|
42
174
|
use(plugin: HyperPlugin): this;
|
|
43
175
|
/**
|
|
44
|
-
* @ru
|
|
45
|
-
*
|
|
46
|
-
* @
|
|
47
|
-
*
|
|
48
|
-
* @returns Promise resolving to the HTTP response.
|
|
49
|
-
*/
|
|
50
|
-
get<T = unknown>(req: RequestInterface | string, signal?: AbortSignal): Promise<HttpResponse<T>>;
|
|
51
|
-
private fastGet;
|
|
52
|
-
/**
|
|
53
|
-
* @ru Выполняет POST-запрос.
|
|
54
|
-
* @en Performs a POST request.
|
|
55
|
-
* @param req - URL string or RequestInterface.
|
|
56
|
-
* @param body - Optional request body.
|
|
57
|
-
* @param signal - Optional abort signal.
|
|
58
|
-
* @returns Promise resolving to the HTTP response.
|
|
59
|
-
*/
|
|
60
|
-
post<T = unknown>(req: RequestInterface | string, body?: RequestBodyData, signal?: AbortSignal): Promise<HttpResponse<T>>;
|
|
61
|
-
/**
|
|
62
|
-
* @ru Выполняет PUT-запрос.
|
|
63
|
-
* @en Performs a PUT request.
|
|
64
|
-
* @param req - URL string or RequestInterface.
|
|
65
|
-
* @param body - Optional request body.
|
|
66
|
-
* @param signal - Optional abort signal.
|
|
67
|
-
* @returns Promise resolving to the HTTP response.
|
|
68
|
-
*/
|
|
69
|
-
put<T = unknown>(req: RequestInterface | string, body?: RequestBodyData, signal?: AbortSignal): Promise<HttpResponse<T>>;
|
|
70
|
-
/**
|
|
71
|
-
* @ru Выполняет PATCH-запрос.
|
|
72
|
-
* @en Performs a PATCH request.
|
|
73
|
-
* @param req - URL string or RequestInterface.
|
|
74
|
-
* @param body - Optional request body.
|
|
75
|
-
* @param signal - Optional abort signal.
|
|
76
|
-
* @returns Promise resolving to the HTTP response.
|
|
77
|
-
*/
|
|
78
|
-
patch<T = unknown>(req: RequestInterface | string, body?: RequestBodyData, signal?: AbortSignal): Promise<HttpResponse<T>>;
|
|
79
|
-
/**
|
|
80
|
-
* @ru Выполняет DELETE-запрос.
|
|
81
|
-
* @en Performs a DELETE request.
|
|
82
|
-
* @param req - URL string or RequestInterface.
|
|
83
|
-
* @param signal - Optional abort signal.
|
|
84
|
-
* @returns Promise resolving to the HTTP response.
|
|
85
|
-
*/
|
|
86
|
-
delete<T = unknown>(req: RequestInterface | string, signal?: AbortSignal): Promise<HttpResponse<T>>;
|
|
87
|
-
/**
|
|
88
|
-
* @ru Выполняет OPTIONS-запрос.
|
|
89
|
-
* @en Performs an OPTIONS request.
|
|
90
|
-
* @param req - URL string or RequestInterface.
|
|
91
|
-
* @param body - Optional request body.
|
|
92
|
-
* @param signal - Optional abort signal.
|
|
93
|
-
* @returns Promise resolving to the HTTP response.
|
|
94
|
-
*/
|
|
95
|
-
options<T = unknown>(req: RequestInterface | string, body?: RequestBodyData, signal?: AbortSignal): Promise<HttpResponse<T>>;
|
|
96
|
-
/**
|
|
97
|
-
* @ru Выполняет HEAD-запрос.
|
|
98
|
-
* @en Performs a HEAD request.
|
|
99
|
-
* @param req - URL string or RequestInterface.
|
|
100
|
-
* @param signal - Optional abort signal.
|
|
101
|
-
* @returns Promise resolving to the HTTP response with null body.
|
|
102
|
-
*/
|
|
103
|
-
head(req: RequestInterface | string, signal?: AbortSignal): Promise<HttpResponse<null>>;
|
|
104
|
-
/**
|
|
105
|
-
* @ru Выполняет GET-запрос и возвращает стриминг-ответ.
|
|
106
|
-
* @en Performs a GET request and returns a streaming response.
|
|
107
|
-
* @param req - URL string or RequestInterface.
|
|
108
|
-
* @param signal - Optional abort signal.
|
|
109
|
-
* @returns Promise resolving to a StreamResponse.
|
|
110
|
-
*/
|
|
111
|
-
stream(req: RequestInterface | string, signal?: AbortSignal): Promise<StreamResponse<unknown>>;
|
|
112
|
-
/**
|
|
113
|
-
* @ru Выполняет POST-запрос и возвращает стриминг-ответ.
|
|
114
|
-
* @en Performs a POST request and returns a streaming response.
|
|
115
|
-
* @param req - URL string or RequestInterface.
|
|
116
|
-
* @param body - Optional request body.
|
|
117
|
-
* @param signal - Optional abort signal.
|
|
118
|
-
* @returns Promise resolving to a StreamResponse.
|
|
119
|
-
*/
|
|
120
|
-
postStream<T = unknown>(req: RequestInterface | string, body?: RequestBodyData, signal?: AbortSignal): Promise<StreamResponse<T>>;
|
|
121
|
-
/**
|
|
122
|
-
* @ru Создаёт новый экземпляр HyperCore с расширенной/переопределённой конфигурацией.
|
|
123
|
-
* @en Creates a new HyperCore instance with extended/overridden configuration.
|
|
176
|
+
* @ru Создаёт новый экземпляр ядра с расширенной/переопределённой конфигурацией,
|
|
177
|
+
* переиспользуя текущий транспорт.
|
|
178
|
+
* @en Creates a new core instance with extended/overridden configuration,
|
|
179
|
+
* reusing the current transport.
|
|
124
180
|
* @param options - Partial configuration overrides.
|
|
125
|
-
* @returns A new
|
|
181
|
+
* @returns A new IHyperCore instance.
|
|
126
182
|
*/
|
|
127
|
-
extend(options: Partial<
|
|
183
|
+
extend(options: Partial<HyperClientOptions>): IHyperCore;
|
|
128
184
|
/**
|
|
129
|
-
* @ru
|
|
130
|
-
*
|
|
185
|
+
* @ru Создаёт полностью независимый экземпляр ядра на основе текущей
|
|
186
|
+
* конфигурации: не переиспользует текущий транспорт и по умолчанию не
|
|
187
|
+
* наследует `customTransport`.
|
|
188
|
+
* @en Creates a fully independent core instance based on the current config:
|
|
189
|
+
* it does not reuse the current transport and does not inherit
|
|
190
|
+
* `customTransport` by default.
|
|
131
191
|
* @param options - Partial configuration overrides.
|
|
132
|
-
* @returns A new
|
|
192
|
+
* @returns A new IHyperCore instance.
|
|
133
193
|
*/
|
|
134
|
-
create(options: Partial<
|
|
194
|
+
create(options: Partial<HyperClientOptions>): IHyperCore;
|
|
135
195
|
/**
|
|
136
|
-
* @ru Завершает работу
|
|
137
|
-
*
|
|
196
|
+
* @ru Завершает работу ядра и освобождает ресурсы: закрывает активные серверы,
|
|
197
|
+
* затем освобождает удержание транспорта.
|
|
198
|
+
* @en Shuts down the core and releases resources: closes active servers, then
|
|
199
|
+
* releases the transport hold.
|
|
138
200
|
* @param graceful - If true, waits for active requests to complete.
|
|
139
201
|
* @returns Promise that resolves when shutdown is complete.
|
|
140
202
|
*/
|
|
141
203
|
destroy(graceful?: boolean): Promise<void>;
|
|
142
|
-
|
|
143
|
-
* @ru Выполняет GET-запрос и возвращает тело ответа, разобранное как JSON.
|
|
144
|
-
* @en Performs a GET request and returns the response body parsed as JSON.
|
|
145
|
-
* @param req - URL string or RequestInterface.
|
|
146
|
-
* @param signal - Optional abort signal.
|
|
147
|
-
* @returns Promise resolving to the parsed JSON value.
|
|
148
|
-
*/
|
|
149
|
-
json<T = unknown>(req: RequestInterface | string, signal?: AbortSignal): Promise<T>;
|
|
150
|
-
/**
|
|
151
|
-
* @ru Выполняет GET-запрос и возвращает тело ответа как строку.
|
|
152
|
-
* @en Performs a GET request and returns the response body as text.
|
|
153
|
-
* @param req - URL string or RequestInterface.
|
|
154
|
-
* @param signal - Optional abort signal.
|
|
155
|
-
* @returns Promise resolving to the response text.
|
|
156
|
-
*/
|
|
157
|
-
text(req: RequestInterface | string, signal?: AbortSignal): Promise<string>;
|
|
158
|
-
/**
|
|
159
|
-
* @ru Выполняет GET-запрос и сбрасывает тело ответа (без сохранения).
|
|
160
|
-
* @en Performs a GET request and discards the response body.
|
|
161
|
-
* @param req - URL string or RequestInterface.
|
|
162
|
-
* @param signal - Optional abort signal.
|
|
163
|
-
* @returns Promise that resolves when the body is discarded.
|
|
164
|
-
*/
|
|
165
|
-
dump(req: RequestInterface | string, signal?: AbortSignal): Promise<void>;
|
|
166
|
-
private handleDispatchError;
|
|
167
|
-
private acquireReq;
|
|
168
|
-
private recycleRequest;
|
|
169
|
-
private shortcut;
|
|
204
|
+
private performDestroy;
|
|
170
205
|
}
|
|
171
206
|
//# sourceMappingURL=HyperCore.d.ts.map
|
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,
|
|
1
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;;;OAOG;IACH,OAAO,CAAC,mBAAmB;IAU3B;;;;;;;;;OASG;YACW,kBAAkB;IA0BhC;;;;;;;OAOG;IACU,IAAI,CAAC,MAAM,GAAG,OAAO,EAAE,OAAO,GAAG,OAAO,EAAE,CAAC,SAAS,MAAM,GAAG,MAAM,EAC9E,GAAG,EAAE,WAAW,CAAC,MAAM,EAAE,CAAC,CAAC,GAC1B,OAAO,CAAC,iBAAiB,CAAC,OAAO,CAAC,CAAC,CAgDrC;YAEa,oBAAoB;YAgBpB,gBAAgB;IA2B9B,OAAO,CAAC,2BAA2B;IAanC;;;;;OAKG;YACW,gBAAgB;YA0BhB,yBAAyB;IAkBvC,OAAO,CAAC,uBAAuB;IAa/B;;;;;;;;;OASG;YACW,SAAS;IAYvB;;;;;;;;OAQG;IACU,MAAM,CAAC,CAAC,SAAS,cAAc,GAAG,cAAc,EAC3D,OAAO,EAAE,wBAAwB,CAAC,CAAC,CAAC,GACnC,OAAO,CAAC,eAAe,CAAC,CAmD1B;IAED;;;;;OAKG;IACI,GAAG,CAAC,MAAM,EAAE,WAAW,GAAG,IAAI,CAUpC;IAED;;;;;;;OAOG;IACI,MAAM,CAAC,OAAO,EAAE,OAAO,CAAC,kBAAkB,CAAC,GAAG,UAAU,CAI9D;IAED;;;;;;;;;OASG;IACI,MAAM,CAAC,OAAO,EAAE,OAAO,CAAC,kBAAkB,CAAC,GAAG,UAAU,CAI9D;IAED;;;;;;;OAOG;IACI,OAAO,CAAC,QAAQ,UAAO,GAAG,OAAO,CAAC,IAAI,CAAC,CAK7C;YAEa,cAAc;CAiC7B"}
|
package/Core/HyperCore.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
"use strict";import{
|
|
1
|
+
"use strict";import{defaultCoreConfig as w}from"../defaultConfig.js";import{KNOWN_PROTOCOLS as m,resolveProtocol as d}from"../protocols/manager.js";import{evictCachedTransport as S,resolveTransport as x}from"../transports/manager.js";import{HyperClientError as l}from"../utils/errors.js";let f=0,P=Date.now().toString(36)+"-";const v=Object.freeze({START:0,PREPARE:1,CONTROL:2,FORMAT:3,NETWORK:4,DATA:5});function q(){return f=f+1>>>0,f===0&&(P=Date.now().toString(36)+"-"),P+(f>>>0).toString(36)}const g=new WeakMap;function T(c){g.set(c,(g.get(c)??0)+1)}function H(c){const e=(g.get(c)??1)-1;return e<=0?g.delete(c):g.set(c,e),e}class R{requestId=q();startTime=performance.now();signal;requestMeta;requestState;constructor(e){this.signal=e}get meta(){return this.requestMeta??={}}set meta(e){this.requestMeta=e}get state(){return this.requestState??={}}set state(e){this.requestState=e}}function N(c){return new R(c.signal)}function b(c){return new R(c.signal)}function y(c){return typeof c=="object"&&c!==null&&"data"in c&&"status"in c&&!("input"in c)}class E{protocols=new Map;register(e){this.protocols.set(e.protocol,e)}get(e){return this.protocols.get(e)}has(e){return this.protocols.has(e)}get size(){return this.protocols.size}}export class HyperCore{config;registry=new E;pluginCtx;plugins=[];servers=new Set;protocolNamespaces=new Set;generatedFlatMethods=new Set;transportPromises=new Map;transports=new Map;retainedTransports=new Set;fixedTransport;destroyPromise=null;isDestroyed=!1;constructor(e={},t,r){if(this.config={...w,...e,retry:{...w.retry,...e.retry}},this.fixedTransport=t??null,t&&(T(t),this.retainedTransports.add(t)),r)for(const[i,h]of r)this.transportPromises.set(i,h.then(C=>this.retainResolvedTransport(i,C)));this.pluginCtx={config:this.config,core:this};const s=this.config.protocols;if(s)for(let i=0;i<s.length;i++)this.registerProtocol(s[i]);const o=this.config.senders;if(o)for(let i=0;i<o.length;i++)this.registerSender(o[i]);const a=this.config.customSender;a&&this.registerSender(a);const n=this.config.receivers;if(n)for(let i=0;i<n.length;i++)this.registerReceiver(n[i]);const u=this.config.plugins;if(u)for(let i=0;i<u.length;i++){const h=u[i];if(typeof h=="string")throw new l(`[HyperCore] Plugin module "${h}" cannot be loaded by the synchronous constructor. Import it and pass the plugin instance instead.`);this.use(h)}const p=this;for(let i=0;i<m.length;i++){const h=m[i];!this.registry.has(h)&&p[h]===void 0&&(p[h]=this.createLazyNamespace(h),this.protocolNamespaces.add(h))}}getProtocol(e){return this.registry.get(e)}getSender(e){return this.registry.get(e)?.sender}getReceiver(e){return this.registry.get(e)?.receiver}async getTransportName(){return(await this.acquireTransport()).constructor.name}async getSenderName(e="rest"){let t=this.registry.get(e);t||(t=await d(e),this.registerProtocol(t));const r=t.sender;if(!r)throw new l(`[HyperCore] Protocol "${e}" has no sender (client role).`);return r.constructor.name}async getReceiverName(e="rest"){let t=this.registry.get(e);t||(t=await d(e),this.registerProtocol(t));const r=t.receiver;if(!r)throw new l(`[HyperCore] Protocol "${e}" has no receiver (server role).`);return r.constructor.name}async getProtocolName(e="rest"){let t=this.registry.get(e);if(t||(t=await d(e),this.registerProtocol(t)),t.name)return t.name;const r=t.constructor;return r&&r.name&&r.name!=="Object"?r.name:String(t.protocol)}registerProtocol(e){const t=String(e.protocol),r=this;if(t==="__proto__"||t==="prototype"||t==="constructor"||t in HyperCore.prototype||t in this&&!this.protocolNamespaces.has(t))throw new l(`[HyperCore] Protocol name "${t}" conflicts with the core API.`);this.registry.register(e);const o=e.sender?.methods;if(o&&typeof o=="object"){const a=Object.create(null);for(const n in o){const u=o[n];if(typeof u!="function")continue;const p=(...i)=>u.apply(o,[this,...i]);a[n]=p,this.generatedFlatMethods.has(n)?r[n]=p:!(n in HyperCore.prototype)&&!(n in this)&&(r[n]=p,this.generatedFlatMethods.add(n))}r[t]=a,this.protocolNamespaces.add(t)}return this}registerSender(e){const t=this.registry.get(e.protocol);return this.registerProtocol({protocol:e.protocol,sender:e,receiver:t?.receiver})}registerReceiver(e){const t=this.registry.get(e.protocol);return this.registerProtocol({protocol:e.protocol,sender:t?.sender,receiver:e})}createLazyNamespace(e){const t={get:(r,s)=>{if(!(typeof s!="string"||s==="then"))return(...o)=>this.dispatchLazyMethod(e,s,o)}};return new Proxy({},t)}async dispatchLazyMethod(e,t,r){let s=this.registry.get(e);s||(s=await d(e),this.registerProtocol(s));const o=s.sender;if(!o)throw new l(`[HyperCore] Protocol "${e}" has no sender (client role).`);const a=o.methods,n=a?.[t];if(typeof n!="function")throw new TypeError(`[HyperCore] Protocol "${e}" has no method "${t}".`);return n.apply(a,[this,...r])}async send(e){const t=N(e);let r=e;if(this.plugins.length===0){const s=this.registry.get(e.protocol)?.sender;if(s)return this.runSender(s,e,t)}try{let s;for(let o=0;o<this.plugins.length;o++){const a=this.plugins[o];if(typeof a.onRequest!="function")continue;const n=await a.onRequest(r,this.pluginCtx,t);if(n!=null){if(y(n)){s=n;break}r=n,t.signal=r.signal}}if(!s){const o=await this.resolveRequestSender(r.protocol);s=await this.runSender(o,r,t)}return await this.runResponseHooks(s,r,t)}catch(s){for(let o=0;o<this.plugins.length;o++){const a=this.plugins[o];if(typeof a.onError!="function")continue;const n=await a.onError(s,r,this.pluginCtx,t);if(n!=null&&y(n))return n}throw s}}async resolveRequestSender(e){let t=this.registry.get(e);t||(t=await d(e),this.registerProtocol(t));const r=t.sender;if(!r)throw new l(`[HyperCore] Protocol "${e}" has no sender (client role).`);return r}async runResponseHooks(e,t,r){let s=e;for(let o=0;o<this.plugins.length;o++){const a=this.plugins[o];if(typeof a.onResponse!="function")continue;if(a.mode==="background"){Promise.resolve().then(()=>a.onResponse(s,t,this.pluginCtx,r)).catch(u=>this.reportBackgroundPluginError(u));continue}const n=await a.onResponse(s,t,this.pluginCtx,r);n!=null&&y(n)&&(s=n)}return s}reportBackgroundPluginError(e){const t=this.config.onError;if(typeof t=="function")try{t(e);return}catch(r){console.error("[HyperCore] Background error handler failed:",r)}console.error("[HyperCore] Background plugin error:",e)}async acquireTransport(e="rest"){if(this.isDestroyed)throw new l("[HyperCore] Cannot acquire transport on a destroyed core instance.");const t=this.transports.get(e);if(t)return t;let r=this.transportPromises.get(e);r||(r=this.resolveAndRetainTransport(e),this.transportPromises.set(e,r));const s=await r;if(this.isDestroyed)throw new l("[HyperCore] Core instance was destroyed while resolving transport.");return s}async resolveAndRetainTransport(e){const t=this.fixedTransport??await x(e,{customTransport:this.config.customTransport});if(!(typeof t.supports=="function"?t.supports(e):t.protocols?.includes(e)??!0))throw new l(`[HyperCore] Transport "${t.constructor.name}" does not support protocol "${e}".`);return this.retainResolvedTransport(e,t)}retainResolvedTransport(e,t){return this.retainedTransports.has(t)||(T(t),this.retainedTransports.add(t)),this.transports.set(e,t),t}async runSender(e,t,r){const s=this.transports.get(t.protocol)??await this.acquireTransport(t.protocol),o=e.prepare(t,r),a=await e.send(o,s,r);return e.parse(a,r)}async listen(e){const t=await this.acquireTransport(e.protocol);if(typeof t.listen!="function")throw new l(`[HyperCore] Transport "${t.constructor.name}" does not support listen() (server role).`);let r=this.registry.get(e.protocol);r||(r=await d(e.protocol),this.registerProtocol(r));const s=r.receiver;if(!s)throw new l(`[HyperCore] Protocol "${e.protocol}" has no receiver (server role).`);const o=e.handler,a=async u=>{const p=b(u),i=await s.receive(u,p),h=o?await o(i,p):await s.handle(i,p);return s.respond(h,p)},n=await t.listen({host:e.host,port:e.port,signal:e.signal,onRequest:a});if(this.isDestroyed)throw await n.close(),new l("[HyperCore] Core instance was destroyed while starting the server.");return this.servers.add(n),n}use(e){return(e.enabled?e.enabled(this.config):!0)?(e.setup?.(this.pluginCtx),this.plugins.push(e),this.plugins.sort((r,s)=>(v[r.phase??""]??0)-(v[s.phase??""]??0)),this):this}extend(e){const t=e.customTransport??this.fixedTransport??void 0,r=e.customTransport?void 0:this.transportPromises;return new HyperCore({...this.config,...e},t,r)}create(e){const t={...this.config};return delete t.customTransport,new HyperCore({...t,...e})}destroy(e=!0){return this.destroyPromise||(this.destroyPromise=this.performDestroy(e)),this.destroyPromise}async performDestroy(e){this.isDestroyed=!0;for(const r of this.servers)try{await r.close()}catch{}this.servers.clear(),await Promise.allSettled(this.transportPromises.values()),this.transportPromises.clear(),this.transports.clear();const t=[...this.retainedTransports];this.retainedTransports.clear();for(const r of t)H(r)>0||(S(r),e&&typeof r.close=="function"?await r.close():typeof r.destroy=="function"?await r.destroy():typeof r.close=="function"&&await r.close())}}
|
|
2
2
|
//# sourceMappingURL=HyperCore.js.map
|