@hyperttp/core 1.5.6 → 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.
Files changed (112) hide show
  1. package/Core/HyperCore.d.ts +206 -0
  2. package/Core/HyperCore.d.ts.map +1 -0
  3. package/Core/HyperCore.js +2 -0
  4. package/Core/HyperCore.js.map +7 -0
  5. package/README.md +259 -187
  6. package/defaultConfig.d.ts +12 -0
  7. package/defaultConfig.d.ts.map +1 -0
  8. package/defaultConfig.js +2 -0
  9. package/defaultConfig.js.map +7 -0
  10. package/index.d.ts +6 -0
  11. package/index.d.ts.map +1 -0
  12. package/index.js +2 -0
  13. package/index.js.map +7 -0
  14. package/package.json +40 -64
  15. package/protocols/manager.d.ts +31 -0
  16. package/protocols/manager.d.ts.map +1 -0
  17. package/protocols/manager.js +2 -0
  18. package/protocols/manager.js.map +7 -0
  19. package/protocols/rest/index.d.ts +9 -0
  20. package/protocols/rest/index.d.ts.map +1 -0
  21. package/protocols/rest/index.js +2 -0
  22. package/protocols/rest/index.js.map +7 -0
  23. package/protocols/rest/receiver.d.ts +31 -0
  24. package/protocols/rest/receiver.d.ts.map +1 -0
  25. package/protocols/rest/receiver.js +2 -0
  26. package/protocols/rest/receiver.js.map +7 -0
  27. package/protocols/rest/sender.d.ts +19 -0
  28. package/protocols/rest/sender.d.ts.map +1 -0
  29. package/protocols/rest/sender.js +2 -0
  30. package/protocols/rest/sender.js.map +7 -0
  31. package/protocols/rest/type.d.ts +71 -0
  32. package/protocols/rest/type.d.ts.map +1 -0
  33. package/protocols/rest/type.js +2 -0
  34. package/protocols/rest/type.js.map +7 -0
  35. package/rest.d.ts +2 -0
  36. package/rest.d.ts.map +1 -0
  37. package/rest.js +2 -0
  38. package/rest.js.map +7 -0
  39. package/transports/fetch.d.ts +24 -0
  40. package/transports/fetch.d.ts.map +1 -0
  41. package/transports/fetch.js +2 -0
  42. package/transports/fetch.js.map +7 -0
  43. package/transports/manager.d.ts +26 -0
  44. package/transports/manager.d.ts.map +1 -0
  45. package/transports/manager.js +2 -0
  46. package/transports/manager.js.map +7 -0
  47. package/utils/abort.d.ts +23 -0
  48. package/utils/abort.d.ts.map +1 -0
  49. package/utils/abort.js +2 -0
  50. package/utils/abort.js.map +7 -0
  51. package/{dist/utils → utils}/errors.d.ts +3 -3
  52. package/utils/errors.d.ts.map +1 -0
  53. package/utils/errors.js +2 -0
  54. package/utils/errors.js.map +7 -0
  55. package/dist/Core/HyperCore.d.ts +0 -171
  56. package/dist/Core/HyperCore.d.ts.map +0 -1
  57. package/dist/Core/HyperCore.js +0 -2
  58. package/dist/Core/HyperCore.js.map +0 -7
  59. package/dist/Core/RequestBuilder.d.ts +0 -8
  60. package/dist/Core/RequestBuilder.d.ts.map +0 -1
  61. package/dist/Core/RequestBuilder.js +0 -2
  62. package/dist/Core/RequestBuilder.js.map +0 -7
  63. package/dist/LICENSE +0 -21
  64. package/dist/README.md +0 -291
  65. package/dist/defaultConfig.d.ts +0 -7
  66. package/dist/defaultConfig.d.ts.map +0 -1
  67. package/dist/defaultConfig.js +0 -2
  68. package/dist/defaultConfig.js.map +0 -7
  69. package/dist/index.d.ts +0 -3
  70. package/dist/index.d.ts.map +0 -1
  71. package/dist/index.js +0 -2
  72. package/dist/index.js.map +0 -7
  73. package/dist/package.json +0 -50
  74. package/dist/transports/browser.d.ts +0 -37
  75. package/dist/transports/browser.d.ts.map +0 -1
  76. package/dist/transports/browser.js +0 -2
  77. package/dist/transports/browser.js.map +0 -7
  78. package/dist/transports/manager.d.ts +0 -89
  79. package/dist/transports/manager.d.ts.map +0 -1
  80. package/dist/transports/manager.js +0 -7
  81. package/dist/transports/manager.js.map +0 -7
  82. package/dist/transports/node.d.ts +0 -33
  83. package/dist/transports/node.d.ts.map +0 -1
  84. package/dist/transports/node.js +0 -2
  85. package/dist/transports/node.js.map +0 -7
  86. package/dist/utils/errors.d.ts.map +0 -1
  87. package/dist/utils/errors.js +0 -2
  88. package/dist/utils/errors.js.map +0 -7
  89. package/dist/utils/normalize.d.ts +0 -35
  90. package/dist/utils/normalize.d.ts.map +0 -1
  91. package/dist/utils/normalize.js +0 -2
  92. package/dist/utils/normalize.js.map +0 -7
  93. package/dist/utils/pipeline.d.ts +0 -63
  94. package/dist/utils/pipeline.d.ts.map +0 -1
  95. package/dist/utils/pipeline.js +0 -2
  96. package/dist/utils/pipeline.js.map +0 -7
  97. package/dist/utils/response.d.ts +0 -108
  98. package/dist/utils/response.d.ts.map +0 -1
  99. package/dist/utils/response.js +0 -2
  100. package/dist/utils/response.js.map +0 -7
  101. package/dist/utils/retryUtils.d.ts +0 -17
  102. package/dist/utils/retryUtils.d.ts.map +0 -1
  103. package/dist/utils/retryUtils.js +0 -2
  104. package/dist/utils/retryUtils.js.map +0 -7
  105. /package/{dist/Core → Core}/index.d.ts +0 -0
  106. /package/{dist/Core → Core}/index.d.ts.map +0 -0
  107. /package/{dist/Core → Core}/index.js +0 -0
  108. /package/{dist/Core → Core}/index.js.map +0 -0
  109. /package/{dist/utils → utils}/merge.d.ts +0 -0
  110. /package/{dist/utils → utils}/merge.d.ts.map +0 -0
  111. /package/{dist/utils → utils}/merge.js +0 -0
  112. /package/{dist/utils → utils}/merge.js.map +0 -0
package/dist/README.md DELETED
@@ -1,291 +0,0 @@
1
- # @hyperttp/core ⚡
2
-
3
- > High-performance HTTP engine for Node.js and Bun.
4
-
5
- **English** | [Русский](https://github.com/IT-IF-OR/hyperttp-core/tree/main/lang/ru)
6
-
7
- [![npm version](https://img.shields.io/npm/v/@hyperttp/core)](https://www.npmjs.com/package/@hyperttp/core)
8
- [![npm downloads](https://img.shields.io/npm/dm/@hyperttp/core)](https://www.npmjs.com/package/@hyperttp/core)
9
- [![bundle size](https://img.shields.io/bundlephobia/minzip/@hyperttp/core)](https://bundlephobia.com/package/@hyperttp/core)
10
- [![license](https://img.shields.io/npm/l/@hyperttp/core)](./LICENSE)
11
- [![typescript](https://img.shields.io/badge/TypeScript-strict-blue)](https://www.typescriptlang.org/)
12
-
13
- ---
14
-
15
- ## What is @hyperttp/core?
16
-
17
- **@hyperttp/core** is a low-level, high-performance HTTP engine designed for building fast,
18
- extensible HTTP clients and SDKs.
19
-
20
- It provides:
21
-
22
- - ⚡ Optimized request execution pipeline
23
- - 🔀 Runtime-aware transport abstraction
24
- - 🔌 Plugin lifecycle hooks
25
- - 🛡️ Safe request/response handling
26
- - 📦 Zero runtime dependencies
27
-
28
- `@hyperttp/core` is the foundation that powers **hyperttp**,
29
- but it can also be used directly to build custom HTTP clients, SDKs, API wrappers and internal tooling.
30
-
31
- > 💡 Looking for a batteries-included client?
32
- >
33
- > Use **[`hyperttp`](https://www.npmjs.com/package/hyperttp)** — it ships with retries, caching,
34
- > parsing, rate limiting and other plugins already configured.
35
-
36
- ---
37
-
38
- ## Why @hyperttp/core?
39
-
40
- Unlike the native `fetch()`, HyperCore is designed as an extensible HTTP engine rather than just a request API.
41
-
42
- | Feature | fetch | @hyperttp/core |
43
- | ---------------------- | :---: | :------------: |
44
- | Transport abstraction | ❌ | ✅ |
45
- | Plugin pipeline | ❌ | ✅ |
46
- | Request/Response hooks | ❌ | ✅ |
47
- | Custom transports | ❌ | ✅ |
48
- | Built for SDKs | ⚠️ | ✅ |
49
- | Safe response cleanup | ❌ | ✅ |
50
- | Runtime auto-detection | ❌ | ✅ |
51
-
52
- ---
53
-
54
- ## Features
55
-
56
- - ⚡ Optimized hot paths with minimal allocations
57
- - 🚀 Fast manual query string serialization
58
- - 🔀 Automatic runtime transport selection
59
- - 🔌 Extensible plugin system
60
- - 🧠 Request/response lifecycle hooks
61
- - 🛡️ Protection against Prototype Pollution
62
- - 🛡️ CRLF header validation
63
- - 🛡️ Safe `ArrayBuffer` handling
64
- - 📦 Zero runtime dependencies
65
- - 🌊 Native stream support
66
- - 🧹 Automatic resource cleanup
67
- - 📈 Designed for high concurrency
68
-
69
- ---
70
-
71
- ## Architecture
72
-
73
- ```text
74
- hyperttp
75
- │
76
- ▼
77
- @hyperttp/core
78
- │
79
- ┌───────────────┴───────────────┐
80
- │ │
81
- ▼ ▼
82
- Transport Layer Plugin Pipeline
83
- │ │
84
- ├── BunTransport │
85
- ├── UndiciTransport ├── Retry
86
- ├── NodeTransport ├── Cache
87
- ├── BrowserTransport ├── Parser
88
- └── Custom Transport └── Пользовательские плагины
89
- ```
90
-
91
- ---
92
-
93
- ## Installation
94
-
95
- ```bash
96
- npm install @hyperttp/core
97
- ```
98
-
99
- Recommended transports:
100
-
101
- ```bash
102
- # Bun
103
- npm install @hyperttp/transport-bun
104
-
105
- # Node.js
106
- npm install @hyperttp/transport-undici
107
- ```
108
-
109
- ---
110
-
111
- ## Quick Start
112
-
113
- ```ts
114
- import { HyperCore } from "@hyperttp/core";
115
-
116
- const http = new HyperCore({
117
- network: {
118
- baseURL: "https://api.example.com",
119
- headers: {
120
- "X-App-Version": "1.0.0",
121
- },
122
- },
123
- });
124
-
125
- const response = await http.get("/users", {
126
- query: {
127
- page: 1,
128
- limit: 20,
129
- },
130
- });
131
-
132
- const users = await response.json();
133
-
134
- console.log(users);
135
- ```
136
-
137
- ---
138
-
139
- ## Error Handling
140
-
141
- ```ts
142
- import { HyperCore, HttpClientError, TimeoutError } from "@hyperttp/core";
143
-
144
- try {
145
- const res = await http.get("/users");
146
-
147
- console.log(await res.json());
148
- } catch (error) {
149
- if (TimeoutError.isTimeoutError(error)) {
150
- console.error("Request timed out.");
151
- }
152
-
153
- if (HttpClientError.isHttpClientError(error)) {
154
- console.error(error.statusCode, error.message);
155
- }
156
-
157
- throw error;
158
- }
159
- ```
160
-
161
- ---
162
-
163
- ## Streaming
164
-
165
- Read a streaming response:
166
-
167
- ```ts
168
- const response = await http.stream("https://stream.example.com/audio");
169
-
170
- const reader = response.body.getReader();
171
-
172
- while (true) {
173
- const { done, value } = await reader.read();
174
-
175
- if (done) break;
176
-
177
- console.log(value.length);
178
- }
179
- ```
180
-
181
- Discard a response body without buffering:
182
-
183
- ```ts
184
- await http.dump("https://api.example.com/ping");
185
- ```
186
-
187
- ---
188
-
189
- ## Plugins
190
-
191
- HyperCore exposes request lifecycle hooks that allow intercepting requests, responses and errors.
192
-
193
- ```ts
194
- http.use({
195
- name: "logger",
196
- priority: 10,
197
-
198
- onRequest(req) {
199
- req.meta.start = performance.now();
200
- },
201
-
202
- onResponse(res, req) {
203
- const elapsed = performance.now() - (req.meta.start as number);
204
-
205
- console.log(`${req.method} ${req.url} -> ${res.status} (${elapsed.toFixed(2)} ms)`);
206
- },
207
-
208
- onError(error, req) {
209
- console.error(`${req.url}: ${error.message}`);
210
- },
211
- });
212
- ```
213
-
214
- ---
215
-
216
- ## Transports
217
-
218
- HyperCore automatically detects the current runtime, or you can provide your own transport.
219
-
220
- | Transport | Runtime |
221
- | ---------------- | ------------- |
222
- | BunTransport | Bun |
223
- | UndiciTransport | Node.js |
224
- | NodeTransport | Bun / Node.js |
225
- | BrowserTransport | Browser |
226
- | Custom Transport | Any |
227
-
228
- Example:
229
-
230
- ```ts
231
- import { HyperCore } from "@hyperttp/core";
232
- import { UndiciTransport } from "@hyperttp/transport-undici";
233
-
234
- const http = new HyperCore({
235
- customTransport: new UndiciTransport(),
236
- });
237
- ```
238
-
239
- ---
240
-
241
- ## Performance
242
-
243
- HyperCore is optimized for sustained high concurrency.
244
-
245
- Recent stress testing:
246
-
247
- - **200,000 requests**
248
- - **1000 concurrent connections**
249
- - **120 seconds**
250
- - **0 request errors**
251
-
252
- Optimizations include:
253
-
254
- - minimal allocations
255
- - object reuse
256
- - optimized semaphore
257
- - manual query serialization
258
- - efficient header normalization
259
- - zero-dependency core
260
-
261
- ---
262
-
263
- ## Ecosystem
264
-
265
- | Package | Description |
266
- | ---------------------------- | ------------------------ |
267
- | `hyperttp` | Ready-to-use HTTP client |
268
- | `@hyperttp/core` | HTTP engine |
269
- | `@hyperttp/parser` | Response parsing |
270
- | `@hyperttp/cache` | Cache utilities |
271
- | `@hyperttp/transport-undici` | Undici transport |
272
- | `@hyperttp/transport-bun` | Bun transport |
273
-
274
- ---
275
-
276
- ## Development
277
-
278
- ```bash
279
- bun install
280
-
281
- bun run lint
282
- bun run typecheck
283
- bun run test
284
- bun run build
285
- ```
286
-
287
- ---
288
-
289
- ## License
290
-
291
- MIT
@@ -1,7 +0,0 @@
1
- import type { HttpClientOptions } from "@hyperttp/types";
2
- /**
3
- * @ru Конфигурация по умолчанию для HTTP-клиента Hyperttp.
4
- * @en Default configuration for the Hyperttp HTTP client.
5
- */
6
- export declare const defaultConfig: HttpClientOptions;
7
- //# sourceMappingURL=defaultConfig.d.ts.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"defaultConfig.d.ts","sourceRoot":"","sources":["../src/defaultConfig.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,iBAAiB,EAAE,MAAM,iBAAiB,CAAC;AAEzD;;;GAGG;AACH,eAAO,MAAM,aAAa,EAAE,iBAiB3B,CAAC"}
@@ -1,2 +0,0 @@
1
- "use strict";export const defaultConfig={network:{timeout:3e4,maxConcurrent:128,pipelining:0,keepAliveTimeout:5e3,followRedirects:!0,maxRedirects:5,rejectUnauthorized:!0},retry:{maxRetries:0,baseDelay:100,maxDelay:5e3,jitter:!0},verbose:!1};
2
- //# sourceMappingURL=defaultConfig.js.map
@@ -1,7 +0,0 @@
1
- {
2
- "version": 3,
3
- "sources": ["../src/defaultConfig.ts"],
4
- "sourcesContent": ["import type { HttpClientOptions } from \"@hyperttp/types\";\n\n/**\n * @ru Конфигурация по умолчанию для HTTP-клиента Hyperttp.\n * @en Default configuration for the Hyperttp HTTP client.\n */\nexport const defaultConfig: HttpClientOptions = {\n network: {\n timeout: 30000,\n maxConcurrent: 128,\n pipelining: 0,\n keepAliveTimeout: 5000,\n followRedirects: true,\n maxRedirects: 5,\n rejectUnauthorized: true,\n },\n retry: {\n maxRetries: 0,\n baseDelay: 100,\n maxDelay: 5000,\n jitter: true,\n },\n verbose: false,\n};\n"],
5
- "mappings": "aAMO,aAAM,cAAmC,CAC9C,QAAS,CACP,QAAS,IACT,cAAe,IACf,WAAY,EACZ,iBAAkB,IAClB,gBAAiB,GACjB,aAAc,EACd,mBAAoB,IAEtB,MAAO,CACL,WAAY,EACZ,UAAW,IACX,SAAU,IACV,OAAQ,IAEV,QAAS",
6
- "names": []
7
- }
package/dist/index.d.ts DELETED
@@ -1,3 +0,0 @@
1
- export { HyperCore } from "./Core/index.js";
2
- export { deepMerge } from "./utils/merge.js";
3
- //# sourceMappingURL=index.d.ts.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,SAAS,EAAE,MAAM,iBAAiB,CAAC;AAC5C,OAAO,EAAE,SAAS,EAAE,MAAM,kBAAkB,CAAC"}
package/dist/index.js DELETED
@@ -1,2 +0,0 @@
1
- "use strict";export{HyperCore}from"./Core/index.js";export{deepMerge}from"./utils/merge.js";
2
- //# sourceMappingURL=index.js.map
package/dist/index.js.map DELETED
@@ -1,7 +0,0 @@
1
- {
2
- "version": 3,
3
- "sources": ["../src/index.ts"],
4
- "sourcesContent": ["export { HyperCore } from \"./Core/index.js\";\nexport { deepMerge } from \"./utils/merge.js\";\n"],
5
- "mappings": "aAAA,OAAS,cAAiB,kBAC1B,OAAS,cAAiB",
6
- "names": []
7
- }
package/dist/package.json DELETED
@@ -1,50 +0,0 @@
1
- {
2
- "name": "@hyperttp/core",
3
- "version": "1.5.6",
4
- "description": "High-performance, extensible HTTP client for Node.js, Bun, Deno and Browser",
5
- "type": "module",
6
- "sideEffects": false,
7
- "main": "./index.js",
8
- "types": "./index.d.ts",
9
- "exports": {
10
- ".": {
11
- "types": "./index.d.ts",
12
- "import": "./index.js"
13
- }
14
- },
15
- "keywords": [
16
- "http",
17
- "client",
18
- "high-performance",
19
- "undici",
20
- "fetch",
21
- "bun",
22
- "deno",
23
- "isomorphic",
24
- "hyperttp"
25
- ],
26
- "author": "dirold2",
27
- "license": "MIT",
28
- "repository": {
29
- "type": "git",
30
- "url": "git+https://github.com/IT-IF-OR/hyperttp-core.git"
31
- },
32
- "peerDependencies": {
33
- "@hyperttp/types": "^0.2.5",
34
- "@hyperttp/transport-bun": "^0.2.4",
35
- "@hyperttp/transport-undici": "^0.2.5",
36
- "hcacher": "^0.1.0"
37
- },
38
- "peerDependenciesMeta": {
39
- "@hyperttp/types": {
40
- "optional": false
41
- },
42
- "@hyperttp/transport-bun": {
43
- "optional": true
44
- },
45
- "@hyperttp/transport-undici": {
46
- "optional": true
47
- }
48
- },
49
- "private": false
50
- }
@@ -1,37 +0,0 @@
1
- import type { HttpClientOptions, HyperTransport, TransportRequest, TransportResponse } from "@hyperttp/types";
2
- /**
3
- * @ru Конфигурация транспорта для браузера.
4
- * @en Browser transport configuration.
5
- */
6
- export interface BrowserTransportConfig extends HttpClientOptions {
7
- /**
8
- * @ru Базовый URL для относительных путей. По умолчанию — window.location.origin.
9
- * @en Base URL for relative paths. Defaults to window.location.origin.
10
- */
11
- baseUrl?: string;
12
- }
13
- /**
14
- * @ru Реализация транспорта для браузера с использованием глобального fetch API.
15
- * Оптимизирован для минимального размера и максимальной совместимости.
16
- * @en Browser transport implementation using the global fetch API.
17
- * Optimized for minimal size and maximum compatibility.
18
- */
19
- export declare class BrowserTransport implements HyperTransport {
20
- config: BrowserTransportConfig;
21
- private readonly isProduction;
22
- private readonly cleanBaseUrl;
23
- /**
24
- * @ru Создаёт экземпляр BrowserTransport.
25
- * @en Creates a BrowserTransport instance.
26
- * @param config - Transport configuration.
27
- */
28
- constructor(config: BrowserTransportConfig);
29
- /**
30
- * @ru Выполняет HTTP-запрос через глобальный fetch.
31
- * @en Executes an HTTP request via the global fetch.
32
- * @param req - The normalized transport request.
33
- * @returns Promise resolving to the transport response.
34
- */
35
- execute(req: TransportRequest): Promise<TransportResponse>;
36
- }
37
- //# sourceMappingURL=browser.d.ts.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"browser.d.ts","sourceRoot":"","sources":["../../src/transports/browser.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EACV,iBAAiB,EACjB,cAAc,EACd,gBAAgB,EAChB,iBAAiB,EAElB,MAAM,iBAAiB,CAAC;AAEzB;;;GAGG;AACH,MAAM,WAAW,sBAAuB,SAAQ,iBAAiB;IAC/D;;;OAGG;IACH,OAAO,CAAC,EAAE,MAAM,CAAC;CAClB;AAaD;;;;;GAKG;AACH,qBAAa,gBAAiB,YAAW,cAAc;IASlC,MAAM,EAAE,sBAAsB;IARjD,OAAO,CAAC,QAAQ,CAAC,YAAY,CAAU;IACvC,OAAO,CAAC,QAAQ,CAAC,YAAY,CAAS;IAEtC;;;;OAIG;IACH,YAAmB,MAAM,EAAE,sBAAsB,EAehD;IAED;;;;;OAKG;IACU,OAAO,CAAC,GAAG,EAAE,gBAAgB,GAAG,OAAO,CAAC,iBAAiB,CAAC,CA6DtE;CACF"}
@@ -1,2 +0,0 @@
1
- "use strict";export class BrowserTransport{config;isProduction;cleanBaseUrl;constructor(s){this.config=s;const o=typeof window<"u"&&["localhost","127.0.0.1","::1"].includes(window.location.hostname),c=typeof process<"u"&&process.env,a=typeof import.meta<"u";this.isProduction=!o&&(c&&!0||a&&import.meta.env?.PROD===!0);const r=s.baseUrl??(typeof window<"u"?window.location.origin:"");this.cleanBaseUrl=r.endsWith("/")?r.slice(0,-1):r}async execute(s){const o=s.url,a=o.startsWith("http://")||o.startsWith("https://")||o.startsWith("//")?o:o.charCodeAt(0)===47?this.cleanBaseUrl+o:this.cleanBaseUrl+"/"+o;if(this.isProduction&&a.includes("//localhost"))throw new Error("Localhost URL detected in production environment");const r=Object.create(null);if(s.headers)if(s.headers instanceof Headers)s.headers.forEach((t,e)=>{r[e.toLowerCase()]=t});else if(Array.isArray(s.headers))for(let t=0;t<s.headers.length;t++){const e=s.headers[t];e&&typeof e[0]=="string"&&(r[e[0].toLowerCase()]=String(e[1]))}else{const t=s.headers;for(const e in t){const i=t[e];i!=null&&(r[e.toLowerCase()]=Array.isArray(i)?i.join(", "):String(i))}}const n=await globalThis.fetch(a,{method:s.method,headers:r,body:s.body,signal:s.signal}),l=Object.create(null);return n.headers.forEach((t,e)=>{l[e]=t}),{status:n.status,url:n.url,body:n.body,headers:l,_raw:n}}}
2
- //# sourceMappingURL=browser.js.map
@@ -1,7 +0,0 @@
1
- {
2
- "version": 3,
3
- "sources": ["../../src/transports/browser.ts"],
4
- "sourcesContent": ["import type {\n HttpClientOptions,\n HyperTransport,\n TransportRequest,\n TransportResponse,\n TransportResponsePayload,\n} from \"@hyperttp/types\";\n\n/**\n * @ru Конфигурация транспорта для браузера.\n * @en Browser transport configuration.\n */\nexport interface BrowserTransportConfig extends HttpClientOptions {\n /**\n * @ru Базовый URL для относительных путей. По умолчанию — window.location.origin.\n * @en Base URL for relative paths. Defaults to window.location.origin.\n */\n baseUrl?: string;\n}\n\n/**\n * @ru Интерфейс для безопасного доступа к мета-окружению сборщиков (Vite, Webpack и др.).\n * @en Interface for safe access to bundler meta-environment (Vite, Webpack, etc.).\n */\ninterface ImportMetaEnv {\n env?: {\n PROD?: boolean;\n [key: string]: unknown;\n };\n}\n\n/**\n * @ru Реализация транспорта для браузера с использованием глобального fetch API.\n * Оптимизирован для минимального размера и максимальной совместимости.\n * @en Browser transport implementation using the global fetch API.\n * Optimized for minimal size and maximum compatibility.\n */\nexport class BrowserTransport implements HyperTransport {\n private readonly isProduction: boolean;\n private readonly cleanBaseUrl: string;\n\n /**\n * @ru Создаёт экземпляр BrowserTransport.\n * @en Creates a BrowserTransport instance.\n * @param config - Transport configuration.\n */\n constructor(public config: BrowserTransportConfig) {\n const isLocalhost =\n typeof window !== \"undefined\" &&\n [\"localhost\", \"127.0.0.1\", \"::1\"].includes(window.location.hostname);\n\n const hasProcess = typeof process !== \"undefined\" && process.env;\n const hasMeta = typeof import.meta !== \"undefined\";\n\n this.isProduction =\n !isLocalhost &&\n ((hasProcess && process.env.NODE_ENV === \"production\") ||\n (hasMeta && (import.meta as unknown as ImportMetaEnv).env?.PROD === true));\n\n const base = config.baseUrl ?? (typeof window !== \"undefined\" ? window.location.origin : \"\");\n this.cleanBaseUrl = base.endsWith(\"/\") ? base.slice(0, -1) : base;\n }\n\n /**\n * @ru Выполняет HTTP-запрос через глобальный fetch.\n * @en Executes an HTTP request via the global fetch.\n * @param req - The normalized transport request.\n * @returns Promise resolving to the transport response.\n */\n public async execute(req: TransportRequest): Promise<TransportResponse> {\n const urlStr = req.url;\n\n const isAbsolute =\n urlStr.startsWith(\"http://\") || urlStr.startsWith(\"https://\") || urlStr.startsWith(\"//\");\n\n const fullUrl = isAbsolute\n ? urlStr\n : urlStr.charCodeAt(0) === 47\n ? this.cleanBaseUrl + urlStr\n : this.cleanBaseUrl + \"/\" + urlStr;\n\n if (this.isProduction && fullUrl.includes(\"//localhost\")) {\n throw new Error(\"Localhost URL detected in production environment\");\n }\n\n const finalHeaders: Record<string, string> = Object.create(null);\n if (req.headers) {\n if (req.headers instanceof Headers) {\n req.headers.forEach((value, key) => {\n finalHeaders[key.toLowerCase()] = value;\n });\n } else if (Array.isArray(req.headers)) {\n for (let i = 0; i < req.headers.length; i++) {\n const pair = req.headers[i] as unknown as [string, string] | undefined;\n if (pair && typeof pair[0] === \"string\") {\n finalHeaders[pair[0].toLowerCase()] = String(pair[1]);\n }\n }\n } else {\n const src = req.headers as Record<string, unknown>;\n for (const key in src) {\n const value = src[key];\n if (value != null) {\n finalHeaders[key.toLowerCase()] = Array.isArray(value)\n ? value.join(\", \")\n : String(value);\n }\n }\n }\n }\n\n const res = await globalThis.fetch(fullUrl, {\n method: req.method,\n headers: finalHeaders as HeadersInit,\n body: req.body as BodyInit | null,\n signal: req.signal,\n });\n\n const resHeaders: Record<string, string> = Object.create(null);\n res.headers.forEach((value, key) => {\n resHeaders[key] = value;\n });\n\n return {\n status: res.status,\n url: res.url,\n body: res.body as unknown as TransportResponsePayload,\n headers: resHeaders,\n _raw: res,\n } as TransportResponse;\n }\n}\n"],
5
- "mappings": "aAqCM,aAAO,gBAAgB,CASR,OARF,a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AIH,CAAG,EACjBD,GAAS,OACXD,EAAaE,EAAI,YAAW,CAAE,EAAI,MAAM,QAAQD,CAAK,EACjDA,EAAM,KAAK,IAAI,EACf,OAAOA,CAAK,EAEpB,CACF,CAGF,MAAMK,EAAM,MAAM,WAAW,MAAMP,EAAS,CAC1C,OAAQF,EAAI,OACZ,QAASG,EACT,KAAMH,EAAI,KACV,OAAQA,EAAI,OACb,EAEKU,EAAqC,OAAO,OAAO,IAAI,EAC7D,OAAAD,EAAI,QAAQ,QAAQ,CAACL,EAAOC,IAAO,CACjCK,EAAWL,CAAG,EAAID,CACpB,CAAC,EAEM,CACL,OAAQK,EAAI,OACZ,IAAKA,EAAI,IACT,KAAMA,EAAI,KACV,QAASC,EACT,KAAMD,EAEV",
6
- "names": ["config", "isLocalhost", "hasProcess", "hasMeta", "base", "req", "urlStr", "fullUrl", "finalHeaders", "value", "key", "i", "pair", "src", "res", "resHeaders"]
7
- }
@@ -1,89 +0,0 @@
1
- import type { HttpClientOptions, HyperTransport } from "@hyperttp/types";
2
- /**
3
- * @ru Поддерживаемые среды выполнения для автоматического выбора транспорта.
4
- * @en Supported runtime environments for automatic transport selection.
5
- */
6
- export type Runtime = "bun" | "node" | "deno" | "browser";
7
- /**
8
- * @ru Определяет текущую среду выполнения при загрузке модуля.
9
- * Порядок проверки: Bun → Deno → Node.js → Browser.
10
- * @en Detects the current runtime at module load time.
11
- * Detection order: Bun → Deno → Node.js → Browser.
12
- */
13
- export declare const CURRENT_RUNTIME: Runtime;
14
- /**
15
- * @ru Разрешает и создаёт оптимальный транспорт для текущей среды.
16
- * Перебирает кандидатов по приоритету, кэширует первый успешный результат.
17
- * @en Resolves and creates the optimal transport for the current runtime.
18
- * Iterates candidates by priority, caches the first successful result.
19
- * @param config - Client configuration options.
20
- * @returns Promise resolving to the instantiated transport.
21
- * @throws Error if no compatible transport is found.
22
- */
23
- export declare function resolveTransport(config: HttpClientOptions): Promise<HyperTransport>;
24
- /**
25
- * @ru Менеджер транспорта с ленивой инициализацией и кэшированием.
26
- * Поддерживает синхронный доступ, отложенную инициализацию и корректное завершение.
27
- * @en Transport manager with lazy initialization and caching.
28
- * Supports synchronous access, deferred initialization, and graceful shutdown.
29
- */
30
- export declare class TransportManager {
31
- /**
32
- * @ru Текущий экземпляр транспорта (null до инициализации).
33
- * @en Current transport instance (null before initialization).
34
- */
35
- transport: HyperTransport | null;
36
- /**
37
- * @ru Промис отложенной инициализации транспорта.
38
- * @en Deferred transport initialization promise.
39
- */
40
- private promise;
41
- /**
42
- * @ru Конфигурация клиента для создания транспорта.
43
- * @en Client configuration for transport creation.
44
- */
45
- private config;
46
- /**
47
- * @ru Создаёт менеджер транспорта с опциональным пользовательским транспортом.
48
- * @en Creates a transport manager with an optional custom transport.
49
- * @param config - Client configuration options.
50
- * @param custom - Optional custom transport instance.
51
- */
52
- constructor(config: HttpClientOptions, custom?: HyperTransport);
53
- /**
54
- * @ru Синхронно возвращает текущий транспорт или null, если не инициализирован.
55
- * @en Synchronously returns the current transport or null if not initialized.
56
- * @returns The transport instance or null.
57
- */
58
- getSync(): HyperTransport | null;
59
- /**
60
- * @ru Гарантирует наличие транспорта, инициализируя его при необходимости.
61
- * Повторные вызовы возвращают один и тот же промис.
62
- * @en Ensures a transport exists, initializing it if necessary.
63
- * Repeated calls return the same promise.
64
- * @returns Promise resolving to the transport instance.
65
- */
66
- ensure(): Promise<HyperTransport>;
67
- /**
68
- * @ru Возвращает транспорт синхронно или промис, если требуется инициализация.
69
- * @en Returns the transport synchronously or a promise if initialization is needed.
70
- * @returns The transport instance or a promise resolving to it.
71
- */
72
- get(): HyperTransport | Promise<HyperTransport>;
73
- /**
74
- * @ru Обновляет конфигурацию транспорта, если он поддерживает setConfig.
75
- * @en Updates the transport configuration if it supports setConfig.
76
- * @param config - New client configuration options.
77
- */
78
- setConfig(config: HttpClientOptions): void;
79
- /**
80
- * @ru Завершает работу транспорта и освобождает ресурсы.
81
- * В graceful-режиме вызывает close(), иначе — destroy().
82
- * @en Shuts down the transport and releases resources.
83
- * In graceful mode calls close(), otherwise calls destroy().
84
- * @param graceful - If true, waits for active requests to complete.
85
- * @returns Promise that resolves when shutdown is complete.
86
- */
87
- destroy(graceful?: boolean): Promise<void>;
88
- }
89
- //# sourceMappingURL=manager.d.ts.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"manager.d.ts","sourceRoot":"","sources":["../../src/transports/manager.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,iBAAiB,EAAE,cAAc,EAAE,MAAM,iBAAiB,CAAC;AAEzE;;;GAGG;AACH,MAAM,MAAM,OAAO,GAAG,KAAK,GAAG,MAAM,GAAG,MAAM,GAAG,SAAS,CAAC;AAyB1D;;;;;GAKG;AACH,eAAO,MAAM,eAAe,EAAE,OAK1B,CAAC;AA4JL;;;;;;;;GAQG;AACH,wBAAsB,gBAAgB,CAAC,MAAM,EAAE,iBAAiB,GAAG,OAAO,CAAC,cAAc,CAAC,CA+BzF;AAED;;;;;GAKG;AACH,qBAAa,gBAAgB;IAC3B;;;OAGG;IACI,SAAS,EAAE,cAAc,GAAG,IAAI,CAAQ;IAE/C;;;OAGG;IACH,OAAO,CAAC,OAAO,CAAwC;IAEvD;;;OAGG;IACH,OAAO,CAAC,MAAM,CAAoB;IAElC;;;;;OAKG;IACH,YAAY,MAAM,EAAE,iBAAiB,EAAE,MAAM,CAAC,EAAE,cAAc,EAU7D;IAED;;;;OAIG;IACI,OAAO,IAAI,cAAc,GAAG,IAAI,CAEtC;IAED;;;;;;OAMG;IACI,MAAM,IAAI,OAAO,CAAC,cAAc,CAAC,CAUvC;IAED;;;;OAIG;IACI,GAAG,IAAI,cAAc,GAAG,OAAO,CAAC,cAAc,CAAC,CAErD;IAED;;;;OAIG;IACI,SAAS,CAAC,MAAM,EAAE,iBAAiB,GAAG,IAAI,CAOhD;IAED;;;;;;;OAOG;IACU,OAAO,CAAC,QAAQ,UAAO,GAAG,OAAO,CAAC,IAAI,CAAC,CAoBnD;CACF"}
@@ -1,7 +0,0 @@
1
- "use strict";export const CURRENT_RUNTIME=typeof Bun<"u"?"bun":typeof Deno<"u"?"deno":typeof process<"u"&&process.versions?.node?"node":"browser";const i=[{name:"Bun",runtime:["bun"],pkg:"@hyperttp/transport-bun",export:"BunTransport",priority:100},{name:"Deno",runtime:["deno"],pkg:"@hyperttp/transport-deno",export:"DenoTransport",priority:95},{name:"Undici",runtime:["node"],pkg:"@hyperttp/transport-undici",export:"UndiciTransport",priority:90},{name:"Browser",runtime:["browser"],pkg:"./browser.js",export:"BrowserTransport",priority:80},{name:"Node",runtime:["node","bun","deno"],pkg:"./node.js",export:"NodeTransport",priority:10}];i.forEach(Object.freeze),Object.freeze(i);const f=new Set(i.map(t=>t.pkg)),u=i.filter(t=>t.runtime.includes(CURRENT_RUNTIME)).sort((t,r)=>r.priority-t.priority);let s=null;function c(t){if(!t||typeof t!="object")return!1;const r=t,e=r.code;if(e==="ERR_MODULE_NOT_FOUND"||e==="MODULE_NOT_FOUND")return!0;const n=t instanceof Error?t.message:String(r.message??"");return n.includes("Cannot find module")||n.includes("Failed to resolve")||n.includes("Failed to load")}function d(t,r,e){const n=typeof process<"u"&&!1,o=typeof process<"u"&&process.env?.DEBUG==="1",l=t.includes(CURRENT_RUNTIME);if(o||n&&l){const p=`Failed to load preferred transport "${t}"`,a="Falling back to alternative transport...";e?.logger?(e.logger("warn",`[Hyperttp Debug] ${p}`,r),e.logger("warn",`[Hyperttp Debug] ${a}`)):(console.warn(`
2
- \u26A0\uFE0F [Hyperttp Debug] ${p}:`),console.error(r),console.warn(`${a}
3
- `))}}async function y(t,r,e){if(!f.has(t))throw new Error(`[Hyperttp Security] Blocked untrusted transport import attempt: ${t}`);try{const n=await import(t),o=n[r]??n.default;return typeof o=="function"?o:null}catch(n){if(c(n))return d(t,n,e),null;throw n}}export async function resolveTransport(t){if(t.customTransport)return t.customTransport;if(s)return new s(t);const r=[];for(let e=0;e<u.length;e++){const n=u[e];try{const o=await y(n.pkg,n.export,t);if(!o){r.push(`${n.pkg} (missing export or not installed)`);continue}return s=o,new o(t)}catch(o){if(c(o)){r.push(`${n.pkg} (not installed)`);continue}throw new Error(`[Hyperttp] Transport crash in ${n.pkg}: ${o?.message}`,{cause:o})}}throw new Error(`No compatible transport for runtime="${CURRENT_RUNTIME}".
4
- Failures:
5
- - ${r.join(`
6
- - `)}`)}export class TransportManager{transport=null;promise=null;config;constructor(r,e){this.config=r,e?this.transport=e:r.customTransport?this.transport=r.customTransport:s&&(this.transport=new s(r))}getSync(){return this.transport}ensure(){return this.transport!==null?this.promise||(this.promise=Promise.resolve(this.transport)):this.promise!==null?this.promise:this.promise=resolveTransport(this.config).then(r=>(this.transport=r,r))}get(){return this.transport??this.ensure()}setConfig(r){this.config=r;const e=this.transport;typeof e?.setConfig=="function"&&e.setConfig(r)}async destroy(r=!0){const e=this.transport;if(e)try{if(r&&typeof e.close=="function"){await e.close();return}typeof e.destroy=="function"&&await e.destroy()}finally{this.transport=null,this.promise=null}}}
7
- //# sourceMappingURL=manager.js.map
@@ -1,7 +0,0 @@
1
- {
2
- "version": 3,
3
- "sources": ["../../src/transports/manager.ts"],
4
- "sourcesContent": ["import type { HttpClientOptions, HyperTransport } from \"@hyperttp/types\";\n\n/**\n * @ru Поддерживаемые среды выполнения для автоматического выбора транспорта.\n * @en Supported runtime environments for automatic transport selection.\n */\nexport type Runtime = \"bun\" | \"node\" | \"deno\" | \"browser\";\n\n/**\n * @ru Конструктор транспорта, принимающий конфигурацию клиента.\n * @en Transport constructor accepting client configuration.\n */\ntype TransportCtor = new (config: HttpClientOptions) => HyperTransport;\n\n/**\n * @ru Описание транспорта: имя, поддерживаемые среды, пакет, экспорт и приоритет.\n * @en Transport descriptor: name, supported runtimes, package, export, and priority.\n */\ntype TransportDef = {\n /** @ru Имя транспорта для логирования. @en Transport name for logging. */\n readonly name: string;\n /** @ru Список сред, в которых транспорт может работать. @en List of runtimes where the transport can operate. */\n readonly runtime: readonly Runtime[];\n /** @ru Имя пакета npm или относительный путь для встроенных транспортов. @en npm package name or relative path for built-in transports. */\n readonly pkg: string;\n /** @ru Имя экспортируемого класса транспорта. @en Exported transport class name. */\n readonly export: string;\n /** @ru Приоритет выбора (выше значение = раньше попытка загрузки). @en Selection priority (higher value = earlier load attempt). */\n readonly priority: number;\n};\n\n/**\n * @ru Определяет текущую среду выполнения при загрузке модуля.\n * Порядок проверки: Bun → Deno → Node.js → Browser.\n * @en Detects the current runtime at module load time.\n * Detection order: Bun → Deno → Node.js → Browser.\n */\nexport const CURRENT_RUNTIME: Runtime = (() => {\n if (typeof Bun !== \"undefined\") return \"bun\";\n if (typeof Deno !== \"undefined\") return \"deno\";\n if (typeof process !== \"undefined\" && process.versions?.node) return \"node\";\n return \"browser\";\n})();\n\n/**\n * @ru Внутренний реестр всех доступных транспортов с приоритетами.\n * Заморожен для предотвращения модификаций в runtime.\n * @en Internal registry of all available transports with priorities.\n * Frozen to prevent runtime modifications.\n */\nconst INTERNAL_TRANSPORTS: readonly TransportDef[] = [\n {\n name: \"Bun\",\n runtime: [\"bun\"],\n pkg: \"@hyperttp/transport-bun\",\n export: \"BunTransport\",\n priority: 100,\n },\n {\n name: \"Deno\",\n runtime: [\"deno\"],\n pkg: \"@hyperttp/transport-deno\",\n export: \"DenoTransport\",\n priority: 95,\n },\n {\n name: \"Undici\",\n runtime: [\"node\"],\n pkg: \"@hyperttp/transport-undici\",\n export: \"UndiciTransport\",\n priority: 90,\n },\n {\n name: \"Browser\",\n runtime: [\"browser\"],\n pkg: \"./browser.js\",\n export: \"BrowserTransport\",\n priority: 80,\n },\n {\n name: \"Node\",\n runtime: [\"node\", \"bun\", \"deno\"],\n pkg: \"./node.js\",\n export: \"NodeTransport\",\n priority: 10,\n },\n];\n\nINTERNAL_TRANSPORTS.forEach(Object.freeze);\nObject.freeze(INTERNAL_TRANSPORTS);\n\n/**\n * @ru Белый список разрешённых пакетов для защиты от несанкционированного импорта.\n * @en Whitelist of allowed packages to protect against unauthorized imports.\n */\nconst ALLOWED_PACKAGES = new Set<string>(INTERNAL_TRANSPORTS.map((t) => t.pkg));\n\n/**\n * @ru Отфильтрованный и отсортированный список транспортов для текущей среды.\n * Вычисляется один раз при загрузке модуля.\n * @en Filtered and sorted list of transports for the current runtime.\n * Computed once at module load time.\n */\nconst CANDIDATES = INTERNAL_TRANSPORTS.filter((t) => t.runtime.includes(CURRENT_RUNTIME)).sort(\n (a, b) => b.priority - a.priority,\n);\n\n/**\n * @ru Кэш разрешённого конструктора транспорта для избежания повторного разрешения.\n * @en Cached resolved transport constructor to avoid repeated resolution.\n */\nlet RESOLVED_RUNTIME_CTOR: TransportCtor | null = null;\n\n/**\n * @ru Проверяет, является ли ошибкой отсутствия модуля.\n * Поддерживает коды ERR_MODULE_NOT_FOUND и MODULE_NOT_FOUND,\n * а также сообщения об ошибках (для совместимости с Bun и Deno).\n * @en Checks if the error is a module-not-found error.\n * Supports ERR_MODULE_NOT_FOUND and MODULE_NOT_FOUND codes,\n * as well as error messages (for Bun and Deno compatibility).\n * @param err - The error to check.\n * @returns True if the error indicates a missing module.\n */\nfunction isModuleNotFoundError(err: unknown): boolean {\n if (!err || typeof err !== \"object\") return false;\n\n const e = err as Record<string, unknown>;\n const code = e.code as string | undefined;\n if (code === \"ERR_MODULE_NOT_FOUND\" || code === \"MODULE_NOT_FOUND\") return true;\n\n const msg = err instanceof Error ? err.message : String(e.message ?? \"\");\n return (\n msg.includes(\"Cannot find module\") ||\n msg.includes(\"Failed to resolve\") ||\n msg.includes(\"Failed to load\")\n );\n}\n\n/**\n * @ru Логирует информацию о неудачной попытке загрузки транспорта.\n * Активируется в режиме DEBUG=1 или при ошибке нативного транспорта в dev-окружении.\n * @en Logs information about failed transport load attempts.\n * Activated in DEBUG=1 mode or when native transport fails in dev environment.\n * @param pkg - Package name that failed to load.\n * @param err - The error that occurred.\n * @param config - Optional client configuration for custom logger.\n */\nfunction logDebugFallback(pkg: string, err: unknown, config?: HttpClientOptions): void {\n const isDev = typeof process !== \"undefined\" && process.env?.NODE_ENV === \"development\";\n const isDebug = typeof process !== \"undefined\" && process.env?.DEBUG === \"1\";\n const isNativeTransport = pkg.includes(CURRENT_RUNTIME);\n\n if (isDebug || (isDev && isNativeTransport)) {\n const primaryMessage = `Failed to load preferred transport \"${pkg}\"`;\n const fallbackMessage = `Falling back to alternative transport...`;\n\n if (config?.logger) {\n config.logger(\"warn\", `[Hyperttp Debug] ${primaryMessage}`, err);\n config.logger(\"warn\", `[Hyperttp Debug] ${fallbackMessage}`);\n } else {\n console.warn(`\\n⚠️ [Hyperttp Debug] ${primaryMessage}:`);\n console.error(err);\n console.warn(`${fallbackMessage}\\n`);\n }\n }\n}\n\n/**\n * @ru Загружает конструктор транспорта из пакета или относительного пути.\n * @en Loads a transport constructor from a package or relative path.\n * @param pkg - Package name or relative path.\n * @param exportName - Name of the exported transport class.\n * @param config - Optional client configuration for debug logging.\n * @returns Transport constructor or null if not found.\n * @throws Error if the package is not in the whitelist.\n */\nasync function loadCtor(\n pkg: string,\n exportName: string,\n config?: HttpClientOptions,\n): Promise<TransportCtor | null> {\n if (!ALLOWED_PACKAGES.has(pkg)) {\n throw new Error(`[Hyperttp Security] Blocked untrusted transport import attempt: ${pkg}`);\n }\n\n try {\n const mod = (await import(pkg)) as Record<string, unknown>;\n const candidate = mod[exportName] ?? mod.default;\n return typeof candidate === \"function\" ? (candidate as TransportCtor) : null;\n } catch (err) {\n if (isModuleNotFoundError(err)) {\n logDebugFallback(pkg, err, config);\n return null;\n }\n throw err;\n }\n}\n\n/**\n * @ru Разрешает и создаёт оптимальный транспорт для текущей среды.\n * Перебирает кандидатов по приоритету, кэширует первый успешный результат.\n * @en Resolves and creates the optimal transport for the current runtime.\n * Iterates candidates by priority, caches the first successful result.\n * @param config - Client configuration options.\n * @returns Promise resolving to the instantiated transport.\n * @throws Error if no compatible transport is found.\n */\nexport async function resolveTransport(config: HttpClientOptions): Promise<HyperTransport> {\n if (config.customTransport) return config.customTransport;\n if (RESOLVED_RUNTIME_CTOR) return new RESOLVED_RUNTIME_CTOR(config);\n\n const failures: string[] = [];\n\n for (let i = 0; i < CANDIDATES.length; i++) {\n const t = CANDIDATES[i]!;\n try {\n const ctor = await loadCtor(t.pkg, t.export, config);\n if (!ctor) {\n failures.push(`${t.pkg} (missing export or not installed)`);\n continue;\n }\n\n RESOLVED_RUNTIME_CTOR = ctor;\n return new ctor(config);\n } catch (err) {\n if (isModuleNotFoundError(err)) {\n failures.push(`${t.pkg} (not installed)`);\n continue;\n }\n throw new Error(`[Hyperttp] Transport crash in ${t.pkg}: ${(err as Error)?.message}`, {\n cause: err,\n });\n }\n }\n\n throw new Error(\n `No compatible transport for runtime=\"${CURRENT_RUNTIME}\".\\nFailures:\\n- ${failures.join(\"\\n- \")}`,\n );\n}\n\n/**\n * @ru Менеджер транспорта с ленивой инициализацией и кэшированием.\n * Поддерживает синхронный доступ, отложенную инициализацию и корректное завершение.\n * @en Transport manager with lazy initialization and caching.\n * Supports synchronous access, deferred initialization, and graceful shutdown.\n */\nexport class TransportManager {\n /**\n * @ru Текущий экземпляр транспорта (null до инициализации).\n * @en Current transport instance (null before initialization).\n */\n public transport: HyperTransport | null = null;\n\n /**\n * @ru Промис отложенной инициализации транспорта.\n * @en Deferred transport initialization promise.\n */\n private promise: Promise<HyperTransport> | null = null;\n\n /**\n * @ru Конфигурация клиента для создания транспорта.\n * @en Client configuration for transport creation.\n */\n private config: HttpClientOptions;\n\n /**\n * @ru Создаёт менеджер транспорта с опциональным пользовательским транспортом.\n * @en Creates a transport manager with an optional custom transport.\n * @param config - Client configuration options.\n * @param custom - Optional custom transport instance.\n */\n constructor(config: HttpClientOptions, custom?: HyperTransport) {\n this.config = config;\n\n if (custom) {\n this.transport = custom;\n } else if (config.customTransport) {\n this.transport = config.customTransport;\n } else if (RESOLVED_RUNTIME_CTOR) {\n this.transport = new RESOLVED_RUNTIME_CTOR(config);\n }\n }\n\n /**\n * @ru Синхронно возвращает текущий транспорт или null, если не инициализирован.\n * @en Synchronously returns the current transport or null if not initialized.\n * @returns The transport instance or null.\n */\n public getSync(): HyperTransport | null {\n return this.transport;\n }\n\n /**\n * @ru Гарантирует наличие транспорта, инициализируя его при необходимости.\n * Повторные вызовы возвращают один и тот же промис.\n * @en Ensures a transport exists, initializing it if necessary.\n * Repeated calls return the same promise.\n * @returns Promise resolving to the transport instance.\n */\n public ensure(): Promise<HyperTransport> {\n if (this.transport !== null) {\n return this.promise || (this.promise = Promise.resolve(this.transport));\n }\n if (this.promise !== null) return this.promise;\n\n return (this.promise = resolveTransport(this.config).then((t) => {\n this.transport = t;\n return t;\n }));\n }\n\n /**\n * @ru Возвращает транспорт синхронно или промис, если требуется инициализация.\n * @en Returns the transport synchronously or a promise if initialization is needed.\n * @returns The transport instance or a promise resolving to it.\n */\n public get(): HyperTransport | Promise<HyperTransport> {\n return this.transport ?? this.ensure();\n }\n\n /**\n * @ru Обновляет конфигурацию транспорта, если он поддерживает setConfig.\n * @en Updates the transport configuration if it supports setConfig.\n * @param config - New client configuration options.\n */\n public setConfig(config: HttpClientOptions): void {\n this.config = config;\n\n const t = this.transport as { setConfig?: (cfg: HttpClientOptions) => void } | null;\n if (typeof t?.setConfig === \"function\") {\n t.setConfig(config);\n }\n }\n\n /**\n * @ru Завершает работу транспорта и освобождает ресурсы.\n * В graceful-режиме вызывает close(), иначе — destroy().\n * @en Shuts down the transport and releases resources.\n * In graceful mode calls close(), otherwise calls destroy().\n * @param graceful - If true, waits for active requests to complete.\n * @returns Promise that resolves when shutdown is complete.\n */\n public async destroy(graceful = true): Promise<void> {\n const t = this.transport as {\n close?: () => Promise<void> | void;\n destroy?: () => Promise<void> | void;\n } | null;\n\n if (!t) return;\n\n try {\n if (graceful && typeof t.close === \"function\") {\n await t.close();\n return;\n }\n if (typeof t.destroy === \"function\") {\n await t.destroy();\n }\n } finally {\n this.transport = null;\n this.promise = null;\n }\n }\n}\n"],
5
- "mappings": "aAqCO,aAAM,gBACP,OAAO,IAAQ,IAAoB,MACnC,OAAO,K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CTOR", "isModuleNotFoundError", "err", "e", "code", "msg", "logDebugFallback", "pkg", "config", "isDev", "isDebug", "isNativeTransport", "primaryMessage", "fallbackMessage", "loadCtor", "exportName", "mod", "candidate", "failures", "i", "t", "ctor", "custom", "graceful"]
7
- }
@@ -1,33 +0,0 @@
1
- import type { HttpClientOptions, HyperTransport, StealthOptions, TransportRequest, TransportResponse } from "@hyperttp/types";
2
- /**
3
- * @ru Конфигурация транспорта для Node.js с использованием нативных http/https модулей.
4
- * @en Node.js transport configuration using native http/https modules.
5
- */
6
- export interface NodeTransportConfig extends HttpClientOptions {
7
- /**
8
- * @ru Базовый URL для относительных путей.
9
- * @en Base URL for relative paths.
10
- */
11
- baseUrl?: string;
12
- /**
13
- * @ru Настройки stealth-маскировки на уровне транспорта.
14
- * @en Stealth masking settings at the transport level.
15
- */
16
- stealth?: StealthOptions;
17
- }
18
- /**
19
- * @ru Реализация транспорта для Node.js с использованием нативных http/https модулей.
20
- * Поддерживает stealth-маскировку, фрагментацию TLS Client Hello и автоматическую декомпрессию.
21
- */
22
- export declare class NodeTransport implements HyperTransport {
23
- config: NodeTransportConfig;
24
- private readonly isProduction;
25
- private readonly cleanBaseUrl;
26
- private readonly agentCache;
27
- private readonly trackedAgents;
28
- constructor(config: NodeTransportConfig);
29
- execute(req: TransportRequest): Promise<TransportResponse>;
30
- close(): Promise<void>;
31
- destroy(): Promise<void>;
32
- }
33
- //# sourceMappingURL=node.d.ts.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"node.d.ts","sourceRoot":"","sources":["../../src/transports/node.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAEV,iBAAiB,EACjB,cAAc,EACd,cAAc,EACd,gBAAgB,EAChB,iBAAiB,EAElB,MAAM,iBAAiB,CAAC;AASzB;;;GAGG;AACH,MAAM,WAAW,mBAAoB,SAAQ,iBAAiB;IAC5D;;;OAGG;IACH,OAAO,CAAC,EAAE,MAAM,CAAC;IACjB;;;OAGG;IACH,OAAO,CAAC,EAAE,cAAc,CAAC;CAC1B;AAqUD;;;GAGG;AACH,qBAAa,aAAc,YAAW,cAAc;IAC3C,MAAM,EAAE,mBAAmB,CAAC;IACnC,OAAO,CAAC,QAAQ,CAAC,YAAY,CAAU;IACvC,OAAO,CAAC,QAAQ,CAAC,YAAY,CAAS;IACtC,OAAO,CAAC,QAAQ,CAAC,UAAU,CAGxB;IACH,OAAO,CAAC,QAAQ,CAAC,aAAa,CAAuC;IAErE,YAAY,MAAM,EAAE,mBAAmB,EAMtC;IAEY,OAAO,CAAC,GAAG,EAAE,gBAAgB,GAAG,OAAO,CAAC,iBAAiB,CAAC,CA2HtE;IAEY,KAAK,IAAI,OAAO,CAAC,IAAI,CAAC,CAMlC;IAEY,OAAO,IAAI,OAAO,CAAC,IAAI,CAAC,CAMpC;CACF"}