@hyperttp/core 1.5.5 → 1.5.6

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 (84) hide show
  1. package/README.md +177 -305
  2. package/{Core → dist/Core}/HyperCore.d.ts.map +1 -1
  3. package/dist/Core/HyperCore.js +2 -0
  4. package/dist/Core/HyperCore.js.map +7 -0
  5. package/dist/Core/RequestBuilder.d.ts +8 -0
  6. package/dist/Core/RequestBuilder.d.ts.map +1 -0
  7. package/dist/Core/RequestBuilder.js +2 -0
  8. package/dist/Core/RequestBuilder.js.map +7 -0
  9. package/dist/LICENSE +21 -0
  10. package/dist/README.md +291 -0
  11. package/dist/defaultConfig.js.map +7 -0
  12. package/dist/package.json +50 -0
  13. package/dist/transports/browser.js.map +7 -0
  14. package/{transports → dist/transports}/manager.d.ts.map +1 -1
  15. package/dist/transports/manager.js +7 -0
  16. package/dist/transports/manager.js.map +7 -0
  17. package/dist/transports/node.js.map +7 -0
  18. package/{utils → dist/utils}/errors.d.ts +10 -0
  19. package/{utils → dist/utils}/errors.d.ts.map +1 -1
  20. package/dist/utils/errors.js +2 -0
  21. package/dist/utils/errors.js.map +7 -0
  22. package/{utils → dist/utils}/merge.d.ts.map +1 -1
  23. package/dist/utils/merge.js +2 -0
  24. package/dist/utils/merge.js.map +7 -0
  25. package/dist/utils/normalize.d.ts.map +1 -0
  26. package/dist/utils/normalize.js +2 -0
  27. package/dist/utils/normalize.js.map +7 -0
  28. package/dist/utils/pipeline.js.map +7 -0
  29. package/{utils → dist/utils}/response.d.ts +0 -5
  30. package/{utils → dist/utils}/response.d.ts.map +1 -1
  31. package/dist/utils/response.js +2 -0
  32. package/dist/utils/response.js.map +7 -0
  33. package/{utils → dist/utils}/retryUtils.d.ts.map +1 -1
  34. package/dist/utils/retryUtils.js +2 -0
  35. package/dist/utils/retryUtils.js.map +7 -0
  36. package/package.json +38 -8
  37. package/Core/HyperCore.js +0 -2
  38. package/Core/HyperCore.js.map +0 -7
  39. package/Core/RequestBuilder.d.ts +0 -32
  40. package/Core/RequestBuilder.d.ts.map +0 -1
  41. package/Core/RequestBuilder.js +0 -2
  42. package/Core/RequestBuilder.js.map +0 -7
  43. package/defaultConfig.js.map +0 -7
  44. package/transports/browser.js.map +0 -7
  45. package/transports/manager.js +0 -7
  46. package/transports/manager.js.map +0 -7
  47. package/transports/node.js.map +0 -7
  48. package/utils/errors.js +0 -2
  49. package/utils/errors.js.map +0 -7
  50. package/utils/merge.js +0 -2
  51. package/utils/merge.js.map +0 -7
  52. package/utils/normalize.d.ts.map +0 -1
  53. package/utils/normalize.js +0 -2
  54. package/utils/normalize.js.map +0 -7
  55. package/utils/pipeline.js.map +0 -7
  56. package/utils/response.js +0 -2
  57. package/utils/response.js.map +0 -7
  58. package/utils/retryUtils.js +0 -2
  59. package/utils/retryUtils.js.map +0 -7
  60. /package/{Core → dist/Core}/HyperCore.d.ts +0 -0
  61. /package/{Core → dist/Core}/index.d.ts +0 -0
  62. /package/{Core → dist/Core}/index.d.ts.map +0 -0
  63. /package/{Core → dist/Core}/index.js +0 -0
  64. /package/{Core → dist/Core}/index.js.map +0 -0
  65. /package/{defaultConfig.d.ts → dist/defaultConfig.d.ts} +0 -0
  66. /package/{defaultConfig.d.ts.map → dist/defaultConfig.d.ts.map} +0 -0
  67. /package/{defaultConfig.js → dist/defaultConfig.js} +0 -0
  68. /package/{index.d.ts → dist/index.d.ts} +0 -0
  69. /package/{index.d.ts.map → dist/index.d.ts.map} +0 -0
  70. /package/{index.js → dist/index.js} +0 -0
  71. /package/{index.js.map → dist/index.js.map} +0 -0
  72. /package/{transports → dist/transports}/browser.d.ts +0 -0
  73. /package/{transports → dist/transports}/browser.d.ts.map +0 -0
  74. /package/{transports → dist/transports}/browser.js +0 -0
  75. /package/{transports → dist/transports}/manager.d.ts +0 -0
  76. /package/{transports → dist/transports}/node.d.ts +0 -0
  77. /package/{transports → dist/transports}/node.d.ts.map +0 -0
  78. /package/{transports → dist/transports}/node.js +0 -0
  79. /package/{utils → dist/utils}/merge.d.ts +0 -0
  80. /package/{utils → dist/utils}/normalize.d.ts +0 -0
  81. /package/{utils → dist/utils}/pipeline.d.ts +0 -0
  82. /package/{utils → dist/utils}/pipeline.d.ts.map +0 -0
  83. /package/{utils → dist/utils}/pipeline.js +0 -0
  84. /package/{utils → dist/utils}/retryUtils.d.ts +0 -0
package/README.md CHANGED
@@ -1,6 +1,8 @@
1
1
  # @hyperttp/core ⚡
2
2
 
3
- > English | [Русский](https://github.com/IT-IF-OR/hyperttp-core/tree/main/lang/ru)
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)
4
6
 
5
7
  [![npm version](https://img.shields.io/npm/v/@hyperttp/core)](https://www.npmjs.com/package/@hyperttp/core)
6
8
  [![npm downloads](https://img.shields.io/npm/dm/@hyperttp/core)](https://www.npmjs.com/package/@hyperttp/core)
@@ -10,410 +12,280 @@
10
12
 
11
13
  ---
12
14
 
13
- ## 🌐 Language
14
-
15
- - 🇺🇸 English
16
- - 🇷🇺 [Русский](https://github.com/IT-IF-OR/hyperttp-core/tree/main/lang/ru)
17
-
18
- ---
15
+ ## What is @hyperttp/core?
19
16
 
20
- ## 🔗 Quick Links
17
+ **@hyperttp/core** is a low-level, high-performance HTTP engine designed for building fast,
18
+ extensible HTTP clients and SDKs.
21
19
 
22
- - 🏢 **Organization:** [github.com/IT-IF-OR](https://github.com/IT-IF-OR)
23
- - 👤 **Author:** [github.com/dirold2](https://github.com/dirold2)
24
- - 📦 **npm:** [npmjs.com/org/hyperttp](https://www.npmjs.com/org/hyperttp)
25
- - 🚀 **High-level client:** [`hyperttp`](https://www.npmjs.com/package/hyperttp) (all plugins pre-wired)
20
+ It provides:
26
21
 
27
- ---
22
+ - ⚡ Optimized request execution pipeline
23
+ - 🔀 Runtime-aware transport abstraction
24
+ - 🔌 Plugin lifecycle hooks
25
+ - 🛡️ Safe request/response handling
26
+ - 📦 Zero runtime dependencies
28
27
 
29
- **@hyperttp/core** is the low-level, high-performance engine of the Hyperttp ecosystem.
30
- It provides a thin, optimized HTTP core with an intelligent transport layer and an advanced
31
- pipeline-based plugin architecture — the foundation upon which the feature-rich [`hyperttp`](https://www.npmjs.com/package/hyperttp) client is built.
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.
32
30
 
33
- > 💡 **Looking for a batteries-included client?** Install [`hyperttp`](https://www.npmjs.com/package/hyperttp) instead — it wraps `@hyperttp/core` with caching, rate limiting, queueing, parsing, and more.
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.
34
35
 
35
36
  ---
36
37
 
37
- ## 🔥 Key Features
38
+ ## Why @hyperttp/core?
38
39
 
39
- - **⚡ Zero-Overhead Hot Paths:** Fast header merging, response mapping, and object creation loops optimized for high-throughput environments. Object pooling for `InternalRequest` eliminates allocations in the hot path.
40
- - **📍 LRU URL Caching:** Built-in string URL parsing cache (up to 512 entries) with automatic eviction to bypass repetitive `new URL()` overhead.
41
- - **🔀 Intelligent Isomorphism:** Automatically switches between optimal underlying transports (Native Bun, Undici, or Node.js native `fetch`) while maintaining a unified, clean API.
42
- - **🔌 Multi-Stage Hooks & Pipelines:** Granular control over the request lifecycle with sorted hook priorities and short-circuit capabilities.
43
- - **🗜️ Transparent Decompression:** Automatic out-of-the-box handling of `gzip`, `deflate`, and `br` (Brotli) content-encodings for both standard `Uint8Array` buffers and `ReadableStream` data.
44
- - **💎 Prototype Preservation:** Safe internal mapping that respects and carries forward custom prototypes passed via request configurations.
45
- - **🛡️ Security Hardening:** Response body size limiting (`maxResponseBytes`), CRLF injection prevention in headers, SSL certificate validation enforcement, and concurrent request throttling (`maxConcurrent`).
46
- - **📦 Tiny Footprint:** ~30.7 KB raw / ~9.6 KB gzip after minification — no unnecessary dependencies.
47
- - **🦀 Rust-Powered Toolchain:** Built and linted with OXC (`oxlint` + `oxfmt`) for blazing-fast development cycles.
40
+ Unlike the native `fetch()`, HyperCore is designed as an extensible HTTP engine rather than just a request API.
48
41
 
49
- ---
50
-
51
- ## 📦 Ecosystem Packages
52
-
53
- | Package | Description | Repository |
54
- | ---------------------------------------------------------------------------------------- | -------------------------------------------- | --------------------------------------------------------------- |
55
- | **`@hyperttp/core`** (you are here) | Low-level core with transport pipeline | [GitHub](https://github.com/IT-IF-OR/hyperttp-core) |
56
- | [`@hyperttp/types`](https://www.npmjs.com/package/@hyperttp/types) | Shared TypeScript type definitions | [GitHub](https://github.com/dirold2/hyperttp-types) |
57
- | [`@hyperttp/transport-bun`](https://www.npmjs.com/package/@hyperttp/transport-bun) | Native Bun transport | [GitHub](https://github.com/IT-IF-OR/hyperttp-transport-bun) |
58
- | [`@hyperttp/transport-undici`](https://www.npmjs.com/package/@hyperttp/transport-undici) | Undici transport for Node.js | [GitHub](https://github.com/IT-IF-OR/hyperttp-transport-undici) |
59
- | [`hyperttp`](https://www.npmjs.com/package/hyperttp) | High-level client with all plugins pre-wired | [GitHub](https://github.com/dirold2/hyperttp) |
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 | ❌ | ✅ |
60
51
 
61
52
  ---
62
53
 
63
- ## 🏗️ Architecture & Lifecycle
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
64
68
 
65
- `HyperCore` shifts heavy lifting into structured execution pipelines:
69
+ ---
66
70
 
67
- ```
68
- ┌─────────────────────────────────────────────────────────────────┐
69
- │ HyperCore │
70
- │ │
71
- │ 1. Request Pipeline (onRequest) ─── short-circuit capable │
72
- │ │ │
73
- │ 2. Transport Execution (HyperTransport) │
74
- │ ├─ BunTransport (native Bun fetch) │
75
- │ ├─ UndiciTransport (Node.js) │
76
- │ └─ NodeTransport (global fetch) │
77
- │ │ │
78
- │ 3. Response Data Pipeline (onResponseData) │
79
- │ │ │
80
- │ 4. Internal Processing (decompression, mapping) │
81
- │ │ │
82
- │ 5. Response Pipeline (onResponse) │
83
- │ ├─ Mutators (sync/async modification) │
84
- │ └─ Side Effects (background, non-blocking) │
85
- │ │ │
86
- │ 6. Error Pipeline (onError) ─── recovery capable │
87
- └─────────────────────────────────────────────────────────────────┘
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 └── Пользовательские плагины
88
89
  ```
89
90
 
90
91
  ---
91
92
 
92
- ## 🚀 Quick Start
93
-
94
- ### Installation
93
+ ## Installation
95
94
 
96
95
  ```bash
97
96
  npm install @hyperttp/core
97
+ ```
98
+
99
+ Recommended transports:
100
+
101
+ ```bash
102
+ # Bun
103
+ npm install @hyperttp/transport-bun
98
104
 
99
- # Optional: install a specific transport
100
- npm install @hyperttp/transport-bun # for Bun
101
- npm install @hyperttp/transport-undici # for Node.js
105
+ # Node.js
106
+ npm install @hyperttp/transport-undici
102
107
  ```
103
108
 
104
- ### Basic Usage
109
+ ---
105
110
 
106
- `HyperCore` returns `HttpResponse<T>` objects with full control over the response body:
111
+ ## Quick Start
107
112
 
108
- ```typescript
113
+ ```ts
109
114
  import { HyperCore } from "@hyperttp/core";
110
115
 
111
116
  const http = new HyperCore({
112
117
  network: {
113
- userAgent: "MyApp/2.0",
114
- headers: { "X-Custom-Global": "Hyperttp" },
118
+ baseURL: "https://api.example.com",
119
+ headers: {
120
+ "X-App-Version": "1.0.0",
121
+ },
115
122
  },
116
123
  });
117
124
 
118
- // Returns HttpResponse<T> with full control
119
- const response = await http.get("https://api.example.com/data");
120
- console.log(response.status);
121
- console.log(response.headers);
122
-
123
- // Built-in parsing methods
124
- const json = await response.json<User>();
125
- const text = await response.text();
126
- const buffer = await response.arrayBuffer();
127
-
128
- // Shortcut methods
129
- const userJson = await http.json<{ name: string }>("/users/123");
130
- const logsText = await http.text("/logs/latest");
131
-
132
- // Safely consume/drain a response without allocations
133
- await http.dump("/analytics/ping");
134
- ```
135
-
136
- ### Streaming
125
+ const response = await http.get("/users", {
126
+ query: {
127
+ page: 1,
128
+ limit: 20,
129
+ },
130
+ });
137
131
 
138
- ```typescript
139
- // GET Streams
140
- const streamResponse = await http.stream("https://stream.example.com/audio");
141
- const reader = streamResponse.body.getReader();
132
+ const users = await response.json();
142
133
 
143
- // POST Streams (e.g., LLM Completions / Audio Pipes)
144
- const chatStream = await http.postStream("/v1/chat/completions", {
145
- model: "gpt-4",
146
- stream: true,
147
- });
134
+ console.log(users);
148
135
  ```
149
136
 
150
137
  ---
151
138
 
152
- ## 🔌 Plugin System
139
+ ## Error Handling
153
140
 
154
- Extend `HyperCore` with custom hooks that integrate into the pipeline:
141
+ ```ts
142
+ import { HyperCore, HttpClientError, TimeoutError } from "@hyperttp/core";
155
143
 
156
- ```typescript
157
- import { HyperCore } from "@hyperttp/core";
158
-
159
- const http = new HyperCore();
160
-
161
- http.use({
162
- name: "performance-logger",
163
- priority: 100, // Sorted execution priority (higher runs first)
164
- mode: "background", // Forces onResponse to run as a non-blocking side-effect
165
-
166
- setup: (ctx) => {
167
- // Fired immediately on registration
168
- ctx.config.logger?.info?.("Plugin active");
169
- },
144
+ try {
145
+ const res = await http.get("/users");
170
146
 
171
- onRequest: async (req, ctx) => {
172
- req.meta.startTime = performance.now();
173
- },
147
+ console.log(await res.json());
148
+ } catch (error) {
149
+ if (TimeoutError.isTimeoutError(error)) {
150
+ console.error("Request timed out.");
151
+ }
174
152
 
175
- onResponse: async (res, req, ctx) => {
176
- const duration = performance.now() - (req.meta.startTime as number);
177
- console.log(`[${req.method}] ${req.url} -> ${res.status} (${duration.toFixed(2)}ms)`);
178
- },
153
+ if (HttpClientError.isHttpClientError(error)) {
154
+ console.error(error.statusCode, error.message);
155
+ }
179
156
 
180
- onError: async (error, req, ctx) => {
181
- console.error(`Request failed to ${req.url}: ${error.message}`);
182
- // Return a response object here to bypass/recover from the failure
183
- },
184
- });
157
+ throw error;
158
+ }
185
159
  ```
186
160
 
187
- ### Plugin Phases
188
-
189
- | Phase | Hook | Description |
190
- | ----------- | ---------------- | ------------------------------------------------------- |
191
- | **REQUEST** | `onRequest` | Intercepts before execution. Supports short-circuiting. |
192
- | **DATA** | `onResponseData` | Transforms raw transport responses before mapping. |
193
- | **FORMAT** | `onResponse` | Modifies client-facing responses. |
194
- | **ERROR** | `onError` | Catches and recovers from errors. |
195
-
196
- > 💡 **Need caching, rate limiting, queueing, parsing, and more?** Use the [`hyperttp`](https://www.npmjs.com/package/hyperttp) meta-package — it comes with 8 pre-wired plugins.
197
-
198
161
  ---
199
162
 
200
- ## 🌍 Transports
163
+ ## Streaming
201
164
 
202
- Hyperttp automatically selects the optimal transport for your runtime:
165
+ Read a streaming response:
203
166
 
204
- | Transport | Runtime | Installation |
205
- | ------------------- | ----------------- | ---------------------------------------- |
206
- | **BunTransport** | Bun | `npm install @hyperttp/transport-bun` |
207
- | **UndiciTransport** | Node.js | `npm install @hyperttp/transport-undici` |
208
- | **NodeTransport** | Node.js / Browser | Built-in (uses global `fetch`) |
167
+ ```ts
168
+ const response = await http.stream("https://stream.example.com/audio");
209
169
 
210
- ### Custom Transport
170
+ const reader = response.body.getReader();
211
171
 
212
- Implement your own transport:
172
+ while (true) {
173
+ const { done, value } = await reader.read();
213
174
 
214
- ```typescript
215
- import type { HyperTransport, TransportRequest, TransportResponse } from "@hyperttp/types";
175
+ if (done) break;
216
176
 
217
- class MyCustomTransport implements HyperTransport {
218
- async execute(req: TransportRequest): Promise<TransportResponse> {
219
- const response = await fetch(req.url, {
220
- method: req.method,
221
- headers: req.headers,
222
- body: req.body,
223
- signal: req.signal,
224
- });
225
-
226
- return {
227
- status: response.status,
228
- headers: Object.fromEntries(response.headers),
229
- body: response.body,
230
- url: response.url,
231
- };
232
- }
233
-
234
- async close(): Promise<void> {
235
- // Cleanup resources
236
- }
177
+ console.log(value.length);
237
178
  }
179
+ ```
180
+
181
+ Discard a response body without buffering:
238
182
 
239
- const http = new HyperCore({}, new MyCustomTransport());
183
+ ```ts
184
+ await http.dump("https://api.example.com/ping");
240
185
  ```
241
186
 
242
187
  ---
243
188
 
244
- ## 🛡️ Security
189
+ ## Plugins
245
190
 
246
- @hyperttp/core includes several hardening mechanisms built into the core pipeline:
191
+ HyperCore exposes request lifecycle hooks that allow intercepting requests, responses and errors.
247
192
 
248
- | Protection | Mechanism | Default |
249
- |---|---|---|
250
- | **SSL Validation** | `rejectUnauthorized` enforced via `https.Agent` in NodeTransport | `true` |
251
- | **Response Size Limit** | `maxResponseBytes` — streaming transform aborts oversized responses | unlimited (0) |
252
- | **CRLF Injection** | `\r\n` stripped from all header values in `appendHeader()` | always on |
253
- | **Concurrency Throttle** | `maxConcurrent` — semaphore gates transport execution | unlimited (0) |
254
- | **Transport Whitelist** | only explicitly registered packages can be loaded dynamically | strict |
255
- | **Prototype Pollution** | all internal maps use `Object.create(null)` | always on |
193
+ ```ts
194
+ http.use({
195
+ name: "logger",
196
+ priority: 10,
256
197
 
257
- Configurable via `HyperCore` constructor:
198
+ onRequest(req) {
199
+ req.meta.start = performance.now();
200
+ },
258
201
 
259
- ```typescript
260
- const http = new HyperCore({
261
- network: {
262
- maxResponseBytes: 10 * 1024 * 1024, // 10 MB limit
263
- maxConcurrent: 50, // max 50 in-flight requests
264
- rejectUnauthorized: true,
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}`);
265
210
  },
266
211
  });
267
212
  ```
268
213
 
269
214
  ---
270
215
 
271
- ## 🔄 Extending Configuration
216
+ ## Transports
272
217
 
273
- Create derived clients with merged configuration via `.extend()`:
218
+ HyperCore automatically detects the current runtime, or you can provide your own transport.
274
219
 
275
- ```typescript
276
- // Inherit global pools and layers while changing specific presets
277
- const authenticatedClient = http.extend({
278
- network: { headers: { Authorization: "Bearer token_abc" } },
279
- });
280
- ```
220
+ | Transport | Runtime |
221
+ | ---------------- | ------------- |
222
+ | BunTransport | Bun |
223
+ | UndiciTransport | Node.js |
224
+ | NodeTransport | Bun / Node.js |
225
+ | BrowserTransport | Browser |
226
+ | Custom Transport | Any |
281
227
 
282
- ### Graceful Resource Destruction
228
+ Example:
283
229
 
284
- Always clean up underlying transport configurations, socket pools, and keep-alive timers in microservice tear-downs:
230
+ ```ts
231
+ import { HyperCore } from "@hyperttp/core";
232
+ import { UndiciTransport } from "@hyperttp/transport-undici";
285
233
 
286
- ```typescript
287
- // Performs a graceful or rapid shutdown sequence across transport selectors
288
- await http.destroy(true);
234
+ const http = new HyperCore({
235
+ customTransport: new UndiciTransport(),
236
+ });
289
237
  ```
290
238
 
291
239
  ---
292
240
 
293
- ## 📊 Benchmarks
241
+ ## Performance
294
242
 
295
- ### Test Configuration
243
+ HyperCore is optimized for sustained high concurrency.
296
244
 
297
- ```txt
298
- Requests 20000
299
- Concurrency 200
300
- Duration 20000
301
- Timeout 60000 ms
302
- ```
245
+ Recent stress testing:
303
246
 
304
- To run your own suite:
247
+ - **200,000 requests**
248
+ - **1000 concurrent connections**
249
+ - **120 seconds**
250
+ - **0 request errors**
305
251
 
306
- ```bash
307
- bun run bench.ts && npx tsx bench.ts
308
- ```
252
+ Optimizations include:
309
253
 
310
- ## 🟦 Bun 1.3.14 — BunTransport
254
+ - minimal allocations
255
+ - object reuse
256
+ - optimized semaphore
257
+ - manual query serialization
258
+ - efficient header normalization
259
+ - zero-dependency core
311
260
 
312
- ```bash
313
- npm install @hyperttp/transport-bun
314
- ```
315
-
316
- | Rank | Client | RPS | Avg | p50 | p90 | p99 | Errors |
317
- | ---- | ------------------ | ---------- | ------------ | ------------ | ------------ | ------------ | ------ |
318
- | 🥇 1 | bun-fetch | 24.34K | 8.18 ms | 8.50 ms | 10.62 ms | 14.10 ms | 0 |
319
- | 🥈 2 | node-fetch | 21.58K | 9.23 ms | 9.39 ms | 12.86 ms | 14.72 ms | 0 |
320
- | 🥉 3 | undici | 20.28K | 9.83 ms | 10.12 ms | 13.80 ms | 15.35 ms | 0 |
321
- | 4 | **@hyperttp/core** | **17.39K** | **11.46 ms** | **12.94 ms** | **15.53 ms** | **16.66 ms** | 0 |
322
- | 5 | ky | 12.80K | 15.58 ms | 13.95 ms | 20.62 ms | 22.77 ms | 0 |
323
- | 6 | request | 8.31K | 24.00 ms | 23.43 ms | 29.54 ms | 32.82 ms | 0 |
324
- | 7 | superagent | 7.96K | 25.09 ms | 24.95 ms | 26.85 ms | 28.46 ms | 0 |
325
- | 8 | axios | 6.19K | 32.21 ms | 31.93 ms | 34.15 ms | 39.09 ms | 0 |
326
- | 9 | got | 5.13K | 38.94 ms | 30.99 ms | 58.61 ms | 63.14 ms | 0 |
327
-
328
- ## 🟦 Bun 1.3.14 — NodeTransport
329
-
330
- | Rank | Client | RPS | Avg | p50 | p90 | p99 | Errors |
331
- | ---- | ------------------ | ---------- | ------------ | ------------ | ------------ | ------------ | ------ |
332
- | 🥇 1 | bun-fetch | 23.94K | 8.32 ms | 8.63 ms | 10.64 ms | 13.77 ms | 0 |
333
- | 🥈 2 | node-fetch | 21.71K | 9.18 ms | 9.35 ms | 12.58 ms | 14.40 ms | 0 |
334
- | 🥉 3 | undici | 20.22K | 9.86 ms | 10.15 ms | 13.65 ms | 15.41 ms | 0 |
335
- | 4 | **@hyperttp/core** | **17.80K** | **11.20 ms** | **12.38 ms** | **15.20 ms** | **17.29 ms** | 0 |
336
- | 5 | ky | 12.78K | 15.63 ms | 13.92 ms | 20.59 ms | 23.70 ms | 0 |
337
- | 6 | request | 8.20K | 24.31 ms | 23.62 ms | 29.13 ms | 34.53 ms | 0 |
338
- | 7 | superagent | 8.06K | 24.79 ms | 24.79 ms | 27.26 ms | 29.52 ms | 0 |
339
- | 8 | axios | 6.28K | 31.72 ms | 31.81 ms | 33.53 ms | 35.65 ms | 0 |
340
- | 9 | got | 5.17K | 38.56 ms | 30.85 ms | 58.12 ms | 61.60 ms | 0 |
341
-
342
- ## 🟦 Node.js v24.14.1 — UndiciTransport
261
+ ---
343
262
 
344
- ```bash
345
- npm install @hyperttp/transport-undici
346
- ```
263
+ ## Ecosystem
347
264
 
348
- | Rank | Client | RPS | Avg | p50 | p90 | p99 | Errors |
349
- | ---- | ------------------ | ---------- | ------------ | ------------ | ------------ | ------------ | ------ |
350
- | 🥇 1 | undici | 13.84K | 14.41 ms | 13.54 ms | 15.39 ms | 26.23 ms | 0 |
351
- | 🥈 2 | **@hyperttp/core** | **11.95K** | **16.68 ms** | **14.90 ms** | **17.04 ms** | **26.58 ms** | 0 |
352
- | 3 | bun-fetch | 7.89K | 25.26 ms | 23.04 ms | 33.86 ms | 39.14 ms | 0 |
353
- | 4 | request | 6.99K | 28.58 ms | 27.19 ms | 34.91 ms | 39.22 ms | 0 |
354
- | 5 | ky | 5.97K | 33.42 ms | 30.05 ms | 41.58 ms | 64.01 ms | 0 |
355
- | 6 | axios | 4.71K | 42.39 ms | 40.65 ms | 48.48 ms | 56.20 ms | 0 |
356
- | 7 | node-fetch | 4.43K | 45.03 ms | 42.18 ms | 53.61 ms | 65.02 ms | 0 |
357
- | 8 | got | 4.20K | 47.51 ms | 45.20 ms | 55.32 ms | 67.58 ms | 0 |
358
- | 9 | superagent | 3.18K | 62.66 ms | 61.13 ms | 70.10 ms | 75.46 ms | 0 |
359
-
360
- ## 🟦 Node.js v24.14.1 — NodeTransport
361
-
362
- | Rank | Client | RPS | Avg | p50 | p90 | p99 | Errors |
363
- | ---- | ------------------ | --------- | ------------ | ------------ | ------------ | ------------ | ------ |
364
- | 🥇 1 | undici | 15.45K | 12.91 ms | 12.68 ms | 13.69 ms | 16.96 ms | 0 |
365
- | 🥈 2 | bun-fetch | 8.31K | 24.00 ms | 22.34 ms | 30.38 ms | 36.20 ms | 0 |
366
- | 🥉 3 | request | 7.34K | 27.14 ms | 26.27 ms | 30.96 ms | 34.91 ms | 0 |
367
- | 4 | **@hyperttp/core** | **7.23K** | **27.58 ms** | **25.68 ms** | **33.76 ms** | **42.75 ms** | 0 |
368
- | 5 | ky | 6.41K | 31.14 ms | 28.43 ms | 37.55 ms | 61.30 ms | 0 |
369
- | 6 | axios | 4.87K | 40.96 ms | 39.70 ms | 45.47 ms | 56.43 ms | 0 |
370
- | 7 | node-fetch | 4.62K | 43.15 ms | 41.12 ms | 49.25 ms | 64.28 ms | 0 |
371
- | 8 | got | 4.58K | 43.63 ms | 41.57 ms | 48.48 ms | 65.02 ms | 0 |
372
- | 9 | superagent | 3.32K | 60.11 ms | 59.08 ms | 66.02 ms | 71.26 ms | 0 |
373
-
374
- ### 📈 Performance Analysis
375
-
376
- **Key Insights:**
377
-
378
- - **Bun + BunTransport**: @hyperttp/core achieves **17.39K RPS** — only 14% slower than native `bun-fetch` (24.34K)
379
- - **Node.js + UndiciTransport**: @hyperttp/core reaches **11.95K RPS** with p99 latency of **26.58ms** — virtually identical to native undici (26.23ms)
380
- - **Zero Error Rate**: 0% errors across all scenarios in all benchmarks
381
- - **Memory Efficiency**: @hyperttp/core uses ~148-184MB in Bun, less than axios (201MB) and got (165-170MB)
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 |
382
273
 
383
274
  ---
384
275
 
385
- ## 🛠️ Development
386
-
387
- This project uses the OXC toolchain for lightning-fast development:
276
+ ## Development
388
277
 
389
278
  ```bash
390
- # Install dependencies
391
279
  bun install
392
280
 
393
- # Type checking
394
- bun run typecheck
395
-
396
- # Linting (oxlint — ~8ms)
397
281
  bun run lint
398
-
399
- # Formatting (oxfmt — ~25ms)
400
- bun run format
401
-
402
- # Build
403
- bun run build
404
-
405
- # Run tests
282
+ bun run typecheck
406
283
  bun run test
284
+ bun run build
407
285
  ```
408
286
 
409
287
  ---
410
288
 
411
- ## 📄 License
289
+ ## License
412
290
 
413
291
  MIT
414
-
415
- ---
416
-
417
- <p align="center">
418
- <a href="https://github.com/dirold2">dirold2</a>
419
- </p>
@@ -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,EAIhB,MAAM,iBAAiB,CAAC;AAuHzB;;;GAGG;AACH,qBAAa,SAAU,YAAW,UAAU;IACnC,MAAM,EAAE,iBAAiB,CAAC;IACjC,OAAO,CAAC,QAAQ,CAAC,gBAAgB,CAAmB;IACpD,O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AG,OAAO,CAAC,MAAM,CAAC,CAMjF;IAED;;;;;;OAMG;IACI,IAAI,CAAC,GAAG,EAAE,gBAAgB,GAAG,MAAM,EAAE,MAAM,CAAC,EAAE,WAAW,GAAG,OAAO,CAAC,IAAI,CAAC,CAM/E;YAEa,mBAAmB;IAmCjC,OAAO,CAAC,UAAU;IAoBlB,OAAO,CAAC,cAAc;IA0BtB,OAAO,CAAC,QAAQ;CAOjB"}
@@ -0,0 +1,2 @@
1
+ "use strict";import{defaultConfig as h}from"../defaultConfig.js";import{mapResponseFast as g,mapStreamFast as x,recycleResponse as p}from"../utils/response.js";import{TransportManager as E}from"../transports/manager.js";import{createPipelines as k,executeErrorPipeline as q,executeRequestPipeline as M,executeResponsePipeline as y,executeResponseDataPipeline as T,insertHookSorted as u}from"../utils/pipeline.js";import{normalizeHeaders as b,normalizeBodyForTransport as S}from"../utils/normalize.js";import{calcDelay as R,shouldRetry as D,drainBody as C}from"../utils/retryUtils.js";import{TimeoutError as O}from"../utils/errors.js";import{RequestBuilder as A}from"./RequestBuilder.js";const w=l=>new Promise(t=>setTimeout(t,l)),H=64;class z{current=0;max;queue;capacity;head=0;tail=0;size=0;constructor(t,e=1024){this.max=t,this.capacity=e;const s=[];s.length=e,this.queue=s}tryAcquire(){return this.current<this.max?(this.current++,!0):!1}acquire(){return this.current<this.max?(this.current++,Promise.resolve()):new Promise(t=>{this.size===this.capacity&&this.grow(),this.queue[this.tail]=t,this.tail=(this.tail+1)%this.capacity,this.size++})}release(){if(this.size>0){const t=this.queue[this.head];this.queue[this.head]=void 0,this.head=(this.head+1)%this.capacity,this.size--,t()}else this.current--}grow(){const t=this.capacity,e=t*2,s=[];s.length=e;for(let i=0;i<this.size;i++)s[i]=this.queue[(this.head+i)%t];this.queue=s,this.capacity=e,this.head=0,this.tail=this.size}}export class HyperCore{config;transportManager;transportReady;defaultHeaders;pluginCtx;pipelines=k();requestBuilder=new A;requestPool=[];semaphore=null;hasRequestPlugins=!1;hasResponseDataPlugins=!1;hasResponsePlugins=!1;hasErrorPlugins=!1;_cachedMaxRetries;_cachedRetryOpts;constructor(t=h,e){this.config={...h,...t,network:{...h.network,...t.network,stealth:t.network?.stealth||h.network?.stealth?Object.assign({},h.network?.stealth,t.network?.stealth):void 0}},this.transportManager=new E(this.config,e),this.transportReady=this.transportManager.getSync()?Promise.resolve(this.transportManager.getSync()):this.transportManager.ensure(),this.defaultHeaders=b({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 z(s):null,this._cachedRetryOpts=this.config.retry??{},this._cachedMaxRetries=this._cachedRetryOpts.maxRetries??0,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._cachedRetryOpts,s=this._cachedMaxRetries;for(let i=0;;i++)try{if(this.hasRequestPlugins){const n=M(this.pipelines.request,t,this.pluginCtx),m=n instanceof Promise?await n:n;if(m!=null)return this.recycleRequest(t),m}t.body!=null&&(t.body=S(t.body,t.headers));const r=this.transportManager.transport??this.transportManager.getSync()??await this.transportReady;let a=!1;if(this.semaphore&&(a=this.semaphore.tryAcquire(),a||await this.semaphore.acquire(),a=!0),t.signal?.aborted)throw t.signal.reason??new DOMException("Aborted","AbortError");let o;const c=t.meta,d=!!c.timings,P=d?performance.now():0;try{o=await r.execute(t)}finally{a&&this.semaphore?.release()}if(d&&(c.timings.networkMs=performance.now()-P),i<s&&D(o.status,e)){await C(o.body),await w(R(i,e));continue}if(this.hasResponseDataPlugins){const n=T(this.pipelines.responseData,o,this.pluginCtx);o=n instanceof Promise?await n:n}const f=c.responseType==="stream"?x(o):g(o);if(this.hasResponsePlugins){const n=y(this.pipelines.responseMutators,this.pipelines.responseSideEffects,f,t,this.pluginCtx,this.config.logger);n instanceof Promise&&await n}return this.recycleRequest(t),f}catch(r){if(r instanceof Error&&(r.name==="AbortError"||r.name==="TimeoutError")){if(t.signal&&t.signal.isTimeout){const a=this.config.network?.timeout??0;return this.handleDispatchError(new O(t.url,a),t)}return this.handleDispatchError(r,t)}if(i<s&&!t.signal?.aborted){await w(R(i,e));continue}return this.handleDispatchError(r,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,run:null};if(t.onRequest&&(u(this.pipelines.request,{name:i.name,priority:i.priority,run:t.onRequest}),this.hasRequestPlugins=!0),t.onResponse){const r=t.mode==="background"?this.pipelines.responseSideEffects:this.pipelines.responseMutators;u(r,{name:i.name,priority:i.priority,run:t.onResponse}),this.hasResponsePlugins=!0}return t.onResponseData&&(u(this.pipelines.responseData,{name:i.name,priority:i.priority,run:t.onResponseData}),this.hasResponseDataPlugins=!0),t.onError&&(u(this.pipelines.error,{name:i.name,priority:i.priority,run:t.onError}),this.hasErrorPlugins=!0),this}get(t,e){return typeof t=="string"&&t!==""&&!e&&!this.hasRequestPlugins&&!this.hasResponsePlugins&&!this.hasResponseDataPlugins&&!this.hasErrorPlugins&&this._cachedMaxRetries===0?this.fastGet(t):this.dispatch(this.acquireReq("GET",t,void 0,e))}async fastGet(t){const e=this.requestBuilder.resolveUrl(t,this.config.baseURL);let s=!1;this.semaphore&&(s=this.semaphore.tryAcquire(),s||(await this.semaphore.acquire(),s=!0));const i=this.transportManager.transport??this.transportManager.getSync()??await this.transportReady;try{if(typeof i.fastRequest=="function")return await i.fastRequest(e,"GET",this.defaultHeaders);const r=await i.execute({method:"GET",url:e,headers:this.defaultHeaders,body:void 0,signal:void 0,stealth:this.config.network?.stealth});return g(r)}finally{s&&this.semaphore?.release()}}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))}postStream(t,e,s){return this.dispatch(this.acquireReq("POST",t,e,s))}extend(t){const e={...this.config};for(const s in t)Object.prototype.hasOwnProperty.call(t,s)&&(s==="network"&&t.network?e.network={...this.config.network,...t.network,stealth:t.network.stealth||this.config.network?.stealth?{...this.config.network?.stealth,...t.network.stealth}:void 0}:e[s]=t[s]);return new HyperCore(e,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=>{const i=s.json?s.json():Promise.reject(new Error("json() not supported"));return p(s),i})}text(t,e){return this.shortcut(t,e).then(s=>{const i=s.text?s.text():Promise.reject(new Error("text() not supported"));return p(s),i})}dump(t,e){return this.shortcut(t,e).then(s=>{const i=s.dump?s.dump():Promise.resolve();return p(s),i})}async handleDispatchError(t,e){try{if(this.hasErrorPlugins){const s=await q(this.pipelines.error,t,e,this.pluginCtx);if(s!=null){if(this.hasResponsePlugins){const i=y(this.pipelines.responseMutators,this.pipelines.responseSideEffects,s,e,this.pluginCtx,this.config.logger);i instanceof Promise&&await i}return s}}throw t}finally{this.recycleRequest(e)}}acquireReq(t,e,s,i,r){const a=this.requestPool.pop();return this.requestBuilder.build(t,e,s,i,r,this.defaultHeaders,this.config,a)}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;e&&(e.responseType=void 0,typeof e.cleanupSignal=="function"&&(e.cleanupSignal(),e.cleanupSignal=void 0),e.timings&&(e.timings.networkMs=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