hyperttp 0.4.0 → 0.4.2

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/README.md CHANGED
@@ -1,200 +1,186 @@
1
- # Hyperttp
1
+ # Hyperttp ⚡
2
2
 
3
- Advanced HTTP client for Node.js with caching, rate limiting, request queuing,
4
- automatic retries, cookie management, and automatic JSON/XML parsing.
3
+ [English](https://github.com/Dirold2/hyperttp) • [Русский](https://github.com/Dirold2/hyperttp/tree/main/lang/ru)
5
4
 
6
- ## Features
5
+ An advanced, high-performance HTTP client for Node.js and Bun featuring built-in caching, rate limiting,
6
+ request queuing, inflight request deduplication, performance metrics, and a fluent chainable API.
7
+ Built as a feature-rich, production-ready extension over the optimized `@hyperttp/core` engine.
7
8
 
8
- - Automatic request deduplication
9
- - LRU caching with TTL
10
- - Configurable rate limiting
11
- - Concurrent request management
12
- - Exponential backoff with jitter for retries
13
- - Cookie jar support
14
- - Automatic response parsing (JSON/XML/text/buffer)
15
- - Automatic handling of redirects
16
- - Fluent request builder API
9
+ ---
10
+
11
+ ## 🔥 Key Features
12
+
13
+ - **🔀 Concurrency Management:** Built-in queue plugin (`withQueue`) to strictly enforce concurrent request limits.
14
+ - **💾 Smart LRU Caching:** Dedicated caching layer (`withCache`) with TTL support to prevent redundant network drift.
15
+ - **🚦 Rate Limiting:** Built-in Token Bucket algorithm to protect against external API blocks and rate limits.
16
+ - **🛡️ Inflight Deduplication:** Prevents duplicate simultaneous requests to the same endpoint if the first is pending.
17
+ - **📈 Real-Time Metrics:** Out-of-the-box telemetry tracking latencies, RPS, cache hits, and overall client health.
18
+ - **🔌 Modular Architecture:** Clean pipeline approach allowing custom plugins, serialization layers, and interceptors.
19
+ - **💎 Fluent Request Builder API:** Clean, chainable API syntax to compose and configure requests with ease.
20
+
21
+ ---
17
22
 
18
- ## Installation
23
+ ## 🚀 Installation
19
24
 
20
25
  ```bash
21
26
  npm install hyperttp
27
+
22
28
  ```
23
29
 
24
30
  ---
25
31
 
26
- ## 🚀 Simple Usage
32
+ ## 📦 Quick Start
27
33
 
28
- Get started in seconds — just import and make requests:
34
+ Simply import `HyperClient` and start dispatched requests. Core features like caching, queue management,
35
+ and rate limiting are instantly preconfigured and active out of the box.
29
36
 
30
37
  ```typescript
31
- import HttpClientImproved from "hyperttp";
38
+ import { HyperClient } from "hyperttp";
32
39
 
33
- const client = new HttpClientImproved();
40
+ const client = new HyperClient();
34
41
 
35
- // Simple GET request
36
- const data = await client.get("https://api.example.com/data");
42
+ // Simple GET request (instantly resolves to the pre-parsed type-safe body)
43
+ const data = await client.get<MyDataType>("https://api.example.com/data");
37
44
 
38
- // POST request with JSON body
39
- const postData = await client.post("https://api.example.com/items", {
40
- name: "Item 1",
45
+ // POST request specifying expected response type alongside body payload
46
+ const newItem = await client.post("https://api.example.com/items", "json", {
47
+ name: "New Item Structure",
41
48
  });
42
49
  ```
43
50
 
44
- **That's it!** Caching, request queuing, and retries are enabled by default.
45
-
46
51
  ---
47
52
 
48
53
  ## ⚙️ Advanced Configuration
49
54
 
50
- Configure all components for your specific needs:
55
+ Fine-tune every infrastructure layer by supplying a configuration object directly to the `HyperClient` constructor:
51
56
 
52
57
  ```typescript
53
- import HttpClientImproved from "hyperttp";
58
+ import { HyperClient } from "hyperttp";
54
59
 
55
- const client = new HttpClientImproved({
56
- // 🌐 Network settings
60
+ const client = new HyperClient({
61
+ // 🌐 Core Network Level Settings (NetworkOptions)
57
62
  network: {
58
- timeout: 10000, // Request timeout (ms)
59
- maxConcurrent: 50, // Max concurrent requests
60
- maxRedirects: 5, // Max redirects to follow
61
- followRedirects: true, // Follow redirects automatically
62
- userAgent: "MyApp/1.0", // User-Agent header
63
- allowHttp2: true, // Enable HTTP/2
64
- pipelining: 10, // Request pipelining
65
- keepAliveTimeout: 30000, // Keep-alive timeout
66
- rejectUnauthorized: false, // Skip SSL certificate validation
63
+ timeout: 10000, // Request timeout in milliseconds
64
+ maxConcurrent: 50, // Maximum simultaneous active sockets (0 = unlimited)
65
+ pipelining: 1, // Pipelined requests per connection limit
66
+ keepAliveTimeout: 30000, // Keep-alive socket preservation time in ms
67
+ rejectUnauthorized: true, // Reject untrusted or self-signed SSL certificates
68
+ followRedirects: true, // Automatically follow HTTP redirects
69
+ maxRedirects: 5, // Maximum follow threshold for redirects
70
+ maxResponseBytes: 10 * 1024 * 1024, // Prevents OOM by capping response body size (10 MB)
71
+ userAgent: "HyperClient/2.0", // Global fallback User-Agent header
72
+ headers: {
73
+ // Default baseline headers appended to every request
74
+ "X-App-Client": "Backend",
75
+ },
76
+ validateStatus: (status) => status >= 200 && status < 300, // Status success validation rules
67
77
  },
68
78
 
69
- // 💾 Caching (LRU cache)
70
- cache: {
71
- enabled: true, // Enable caching
72
- ttl: 1000 * 60 * 5, // Cache TTL (5 minutes)
73
- maxSize: 500, // Max cache size (entries)
79
+ // 🔄 Automated Retry Logic (RetryOptions)
80
+ retry: {
81
+ maxRetries: 3, // Number of recovery attempts before failing
82
+ baseDelay: 1000, // Initial delay baseline between retries (ms)
83
+ maxDelay: 10000, // Maximum cap for retry delay intervals (ms)
84
+ retryStatusCodes: [408, 429, 502, 503, 504], // Target status codes that trigger a retry
85
+ jitter: true, // Randomized delay variations to avoid thundering herd crashes
74
86
  },
75
87
 
76
- // 🚦 Rate Limiting (Token Bucket)
77
- rateLimit: {
78
- enabled: true, // Enable rate limiting
79
- maxRequests: 100, // Max requests per window
80
- windowMs: 60000, // Time window (ms)
88
+ // 📈 Telemetry and Engine Logging
89
+ trackMetrics: true, // Enables global system performance collection
90
+ verbose: false, // Toggles internal micro-logs output
91
+ logger: (level, message, meta) => {
92
+ // Custom logging implementation sink
93
+ console.log(`[${level}] ${message}`, meta ?? "");
81
94
  },
82
95
 
83
- // 📊 Request Queue
84
- queue: {
85
- enabled: true, // Enable request queue
86
- },
96
+ // 🔌 Plugin Registration
97
+ plugins: [], // Inline custom plugin instances or absolute module paths
87
98
 
88
- // 🔄 Retry Logic
89
- retry: {
90
- maxRetries: 3, // Max retry attempts
91
- baseDelay: 1000, // Base delay between retries (ms)
92
- maxDelay: 10000, // Max delay (ms)
93
- jitter: true, // Add randomization to delays
94
- retryStatusCodes: [408, 429, 500, 502, 503, 504],
99
+ // 💾 Extended Plugin Configurations (Injected via HyperttpPluginsExtension)
100
+ cache: {
101
+ enabled: true,
102
+ ttl: 300000, // 5 minutes cache lifespan
103
+ maxSize: 500, // Max item limit for local LRU storage
95
104
  },
96
-
97
- // 📈 Metrics
98
- metrics: {
99
- enabled: true, // Enable metrics collection
100
- maxHistory: 1000, // Metrics history size
105
+ rateLimit: {
106
+ enabled: true,
107
+ maxRequests: 100,
108
+ windowMs: 60000,
109
+ },
110
+ inflight: {
111
+ enabled: true,
101
112
  },
102
-
103
- // 🔍 Logging
104
- verbose: true, // Enable verbose logging
105
- logger: (level, msg) => console.log(`[${level}] ${msg}`),
106
113
  });
107
114
  ```
108
115
 
109
- ### Using Advanced Features
116
+ ---
117
+
118
+ ## 🛠️ Advanced Features
119
+
120
+ ### Fluent Builder API
121
+
122
+ Invoke the `.request(url)` chain to programmatically craft highly specific request structures on the fly:
110
123
 
111
124
  ```typescript
112
- // Using Fluent RequestBuilder
113
125
  const result = await client
114
126
  .request("https://api.example.com/search")
115
- .query({ q: "hyperttp", limit: 10 })
127
+ .post() // Specify HTTP Method (Defaults to GET)
128
+ .query({ q: "hyperttp", p: 1 }) // Safely append and encode Query Parameters
116
129
  .headers({ Authorization: "Bearer TOKEN" })
117
- .json()
130
+ .jsonBody({ activeOnly: true }) // Automatically serializes and sets Content-Type header
131
+ .json() // Asserts expected response format (.text(), .buffer(), .stream())
132
+ .timeout(5000) // Instantiates a contextual, request-scoped AbortSignal timeout
118
133
  .send();
134
+ ```
119
135
 
120
- // Get client statistics
136
+ ### Statistics, Cache, and Metrics Engine
137
+
138
+ ```typescript
139
+ // Inspect pipeline internals (active connections, active queue payloads)
121
140
  const stats = client.getStats();
122
- console.log({
123
- cacheSize: stats.cacheSize, // Current cache size
124
- inflightRequests: stats.inflightRequests, // Active requests
125
- queuedRequests: stats.queuedRequests, // Requests waiting in queue
126
- activeRequests: stats.activeRequests, // Currently executing
127
- currentRateLimit: stats.currentRateLimit, // Used rate limit slots
128
- });
141
+ console.log(stats);
129
142
 
130
- // Work with metrics
131
- const metrics = client.getMetrics("https://api.example.com/data");
132
- console.log(metrics);
143
+ // Retrieve aggregated historical latency and performance metrics
144
+ const allMetrics = client.getAllMetrics();
145
+ console.log(allMetrics);
133
146
 
134
- // Clear cache
135
- client.clearCache();
147
+ // Flush the entire local response cache programmatically
148
+ await client.clearCache();
136
149
 
137
- // Clear metrics
138
- client.clearMetrics();
150
+ // Identify the execution context's current driving transport layout
151
+ const transportName = await client.getTransportName();
152
+ console.log(`Current Active Transport Driver: ${transportName}`);
139
153
 
140
- // Graceful shutdown
154
+ // Gracefully teardown the client instance, draining keep-alive pools and sockets
141
155
  await client.destroy();
142
156
  ```
143
157
 
144
- ---
145
-
146
- ## Fluent Builder API
158
+ ### Stream Handlers
147
159
 
148
160
  ```typescript
149
- client
150
- .request("https://api.example.com/data")
151
- .get() // default
152
- .headers({ "X-Test": "123" })
153
- .query({ page: 1 })
154
- .json() // or .text(), .xml()
155
- .send()
156
- .then(console.log);
161
+ // Returns an HttpResponse interface carrying a custom ReadableStream with clone() support
162
+ const streamResponse = await client.stream(
163
+ "https://stream.example.com/audio.mp3",
164
+ );
165
+ const reader = streamResponse.body.getReader();
157
166
  ```
158
167
 
159
168
  ---
160
169
 
161
- ## Architecture Components
162
-
163
- ### 💾 CacheManager
164
-
165
- LRU cache with TTL and metadata support (etag, lastModified):
166
-
167
- - Automatically caches GET/HEAD responses
168
- - Configurable size and TTL
169
- - Methods: `get()`, `set()`, `getWithMetadata()`, `setWithMetadata()`
170
-
171
- ### 📊 QueueManager
172
-
173
- Request queue management:
174
-
175
- - Concurrency control (maxConcurrent)
176
- - FIFO processing of pending requests
177
- - Methods: `enqueue()`, `activeCount`, `queuedCount`
178
-
179
- ### 🚦 RateLimiter
180
-
181
- Token bucket algorithm with wait queue:
182
-
183
- - Smooth rate limiting
184
- - FIFO waiting when limit exceeded
185
- - Methods: `wait()`, `tryConsume()`, `remainingRequests`
186
-
187
- ### 📈 MetricsManager
170
+ ## 🏗️ Architecture Pipeline
188
171
 
189
- Performance metrics collection and analysis:
172
+ `HyperClient` structures outbound and inbound requests across a sequential pipeline composed of granular plugins:
190
173
 
191
- - Request timing
192
- - Bytes sent/received
193
- - Cache hits/misses
194
- - Retry counts
174
+ 1. **withSerializer / withParser:** Manages automated runtime type transformations, payload normalization, and safe serialization.
175
+ 2. **withCache:** Intercepts identical outgoing target operations, returning data directly from the LRU cache when matching.
176
+ 3. **withInflight:** Identifies matching parallel operations and merges them into a single flight path, avoiding race conditions.
177
+ 4. **withRateLimit & withQueue:** Sorts requests into a coordinated FIFO pattern,
178
+ enforcing strict window boundaries and capacity bounds.
179
+ 5. **withInterceptors:** Exposes direct developer lifecycle hooks to capture requests and responses before execution steps.
180
+ 6. **withMetrics:** Records execution metrics across the entire lifecycle to offer real-time health telemetry.
195
181
 
196
182
  ---
197
183
 
198
- ## Documentation
184
+ ## 📄 License
199
185
 
200
- - [Русский](https://github.com/Dirold2/hyperttp/blob/main/lang/ru/README.md)
186
+ MIT
package/index.d.ts CHANGED
@@ -1,5 +1,5 @@
1
1
  export { HyperClient } from "./Hyperttp/index.js";
2
- export { Request, UrlExtractor } from "./Hyperttp/index.js";
2
+ export { Request, PreparedRequest, UrlExtractor } from "./Hyperttp/index.js";
3
3
  export type * from "./Types/index.js";
4
4
  export * from "@hyperttp/cache";
5
5
  export * from "@hyperttp/queue";
package/index.d.ts.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,WAAW,EAAE,MAAM,qBAAqB,CAAC;AAClD,OAAO,EAAE,OAAO,EAAE,YAAY,EAAE,MAAM,qBAAqB,CAAC;AAE5D,mBAAmB,kBAAkB,CAAC;AAEtC,cAAc,iBAAiB,CAAC;AAChC,cAAc,iBAAiB,CAAC;AAChC,cAAc,qBAAqB,CAAC;AACpC,cAAc,wBAAwB,CAAC;AACvC,cAAc,mBAAmB,CAAC;AAClC,cAAc,oBAAoB,CAAC;AACnC,cAAc,kBAAkB,CAAC;AACjC,cAAc,sBAAsB,CAAC"}
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,WAAW,EAAE,MAAM,qBAAqB,CAAC;AAClD,OAAO,EAAE,OAAO,EAAE,eAAe,EAAE,YAAY,EAAE,MAAM,qBAAqB,CAAC;AAE7E,mBAAmB,kBAAkB,CAAC;AAEtC,cAAc,iBAAiB,CAAC;AAChC,cAAc,iBAAiB,CAAC;AAChC,cAAc,qBAAqB,CAAC;AACpC,cAAc,wBAAwB,CAAC;AACvC,cAAc,mBAAmB,CAAC;AAClC,cAAc,oBAAoB,CAAC;AACnC,cAAc,kBAAkB,CAAC;AACjC,cAAc,sBAAsB,CAAC"}
package/index.js CHANGED
@@ -1,5 +1,5 @@
1
1
  export { HyperClient } from "./Hyperttp/index.js";
2
- export { Request, UrlExtractor } from "./Hyperttp/index.js";
2
+ export { Request, PreparedRequest, UrlExtractor } from "./Hyperttp/index.js";
3
3
  export * from "@hyperttp/cache";
4
4
  export * from "@hyperttp/queue";
5
5
  export * from "@hyperttp/ratelimit";
package/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,WAAW,EAAE,MAAM,qBAAqB,CAAC;AAClD,OAAO,EAAE,OAAO,EAAE,YAAY,EAAE,MAAM,qBAAqB,CAAC;AAI5D,cAAc,iBAAiB,CAAC;AAChC,cAAc,iBAAiB,CAAC;AAChC,cAAc,qBAAqB,CAAC;AACpC,cAAc,wBAAwB,CAAC;AACvC,cAAc,mBAAmB,CAAC;AAClC,cAAc,oBAAoB,CAAC;AACnC,cAAc,kBAAkB,CAAC;AACjC,cAAc,sBAAsB,CAAC"}
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,WAAW,EAAE,MAAM,qBAAqB,CAAC;AAClD,OAAO,EAAE,OAAO,EAAE,eAAe,EAAE,YAAY,EAAE,MAAM,qBAAqB,CAAC;AAI7E,cAAc,iBAAiB,CAAC;AAChC,cAAc,iBAAiB,CAAC;AAChC,cAAc,qBAAqB,CAAC;AACpC,cAAc,wBAAwB,CAAC;AACvC,cAAc,mBAAmB,CAAC;AAClC,cAAc,oBAAoB,CAAC;AACnC,cAAc,kBAAkB,CAAC;AACjC,cAAc,sBAAsB,CAAC"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "hyperttp",
3
- "version": "0.4.0",
3
+ "version": "0.4.2",
4
4
  "description": "A high-performance, universal HTTP client for Node.js with caching, retries, queueing, rate limiting, cookies and logging.",
5
5
  "type": "module",
6
6
  "main": "./index.js",
@@ -36,16 +36,16 @@
36
36
  "logger"
37
37
  ],
38
38
  "dependencies": {
39
- "@hyperttp/core": "^1.3.0",
40
- "@hyperttp/types": "^0.2.0",
41
39
  "@hyperttp/cache": "^1.1.6",
42
- "@hyperttp/parser": "^1.1.6",
43
- "@hyperttp/inflight": "^1.1.5",
40
+ "@hyperttp/core": "^1.3.3",
41
+ "@hyperttp/inflight": "^1.1.6",
44
42
  "@hyperttp/interceptors": "^1.1.5",
45
43
  "@hyperttp/metrics": "^1.1.5",
44
+ "@hyperttp/parser": "^1.1.8",
46
45
  "@hyperttp/queue": "^1.1.5",
46
+ "@hyperttp/ratelimit": "^1.1.5",
47
47
  "@hyperttp/serializer": "^1.1.5",
48
- "@hyperttp/ratelimit": "^1.1.5"
48
+ "@hyperttp/types": "^0.2.0"
49
49
  },
50
50
  "private": false
51
51
  }