@eserstack/httpclient 0.0.0-stage → 5.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE ADDED
@@ -0,0 +1,13 @@
1
+ Copyright 2023-present Eser Ozvataf and other contributors.
2
+
3
+ Licensed under the Apache License, Version 2.0 (the "License");
4
+ you may not use this file except in compliance with the License.
5
+ You may obtain a copy of the License at
6
+
7
+ http://www.apache.org/licenses/LICENSE-2.0
8
+
9
+ Unless required by applicable law or agreed to in writing, software
10
+ distributed under the License is distributed on an "AS IS" BASIS,
11
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ See the License for the specific language governing permissions and
13
+ limitations under the License.
package/README.md CHANGED
@@ -1,3 +1,304 @@
1
- # Temporary Holding Version
1
+ # 📨 [@eserstack/httpclient](./)
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ > **Note:** JSR is frozen at 4.5.x. From 5.0.0, `@eserstack/httpclient` is
4
+ > published on npm under the same name (`pnpm add @eserstack/httpclient`); the
5
+ > JSR versions stay available but get no updates.
6
+
7
+ `@eserstack/httpclient` is an HTTP client for services and CLIs that talk to
8
+ remote APIs. It wraps `fetch` with a base URL, a timeout on every request,
9
+ retries with exponential backoff, rate-limit headers, request and response
10
+ interceptors, and a typed error for each way a request can fail. Every method
11
+ comes in two styles: one that throws, and one that returns a `Result` for
12
+ `@eserstack/functions` pipelines.
13
+
14
+ Install it with `pnpm add @eserstack/httpclient`.
15
+
16
+ ## Quick Start
17
+
18
+ Create a client once and call it with paths relative to its base URL:
19
+
20
+ ```typescript
21
+ import * as httpclient from "@eserstack/httpclient";
22
+
23
+ type User = { id: number; name: string };
24
+
25
+ const client = httpclient.createHttpClient({
26
+ baseUrl: "https://api.example.com",
27
+ headers: { Authorization: "Bearer your_access_token" },
28
+ });
29
+
30
+ const response = await client.get<User>("/users/1");
31
+ console.log(response.status, response.data.name);
32
+ ```
33
+
34
+ `response.data` is the parsed body: JSON when the response is JSON (or its text
35
+ parses as JSON), the text otherwise, and `undefined` for 204, 304 and empty
36
+ responses. The response also carries `headers`, `retries`, the sent `request`,
37
+ the `raw` `Response` and, when the server sent rate-limit headers, `rateLimit`.
38
+
39
+ ## Requests
40
+
41
+ `get`, `post`, `put`, `patch` and `delete` take a path and options;
42
+ `request(method, path, options)` takes the method as well.
43
+
44
+ ```typescript
45
+ import * as httpclient from "@eserstack/httpclient";
46
+
47
+ const client = httpclient.createHttpClient({
48
+ baseUrl: "https://api.example.com",
49
+ });
50
+
51
+ const created = await client.post<{ id: number }>("/users", {
52
+ body: { name: "Ada" },
53
+ params: { notify: "true" },
54
+ timeout: 5_000,
55
+ });
56
+ ```
57
+
58
+ A plain object or array `body` is sent as JSON with
59
+ `Content-Type: application/json` unless you set that header yourself. Strings,
60
+ `FormData`, `Blob`, `URLSearchParams`, buffers and streams are sent as they are.
61
+
62
+ | Option | Description |
63
+ | --------- | ---------------------------------------------------- |
64
+ | `headers` | Headers for this request, merged over the client's |
65
+ | `body` | Request body (see above) |
66
+ | `params` | Query string parameters |
67
+ | `timeout` | Timeout in milliseconds for this request |
68
+ | `retry` | Retry policy for this request, or `false` to disable |
69
+ | `signal` | `AbortSignal` that cancels the request |
70
+
71
+ `client.withDefaults(overrides)` returns a new client with merged configuration
72
+ and leaves the original unchanged.
73
+
74
+ ## Timeouts and Retries
75
+
76
+ Every request has a timeout, 30 seconds unless `timeout` says otherwise. Failed
77
+ requests are retried with exponential backoff:
78
+
79
+ | `RetryConfig` field | Default | Description |
80
+ | ------------------- | -------------------------------- | -------------------------------------------- |
81
+ | `maxAttempts` | `3` | Attempts in total, including the first |
82
+ | `initialDelay` | `1000` | First backoff delay in milliseconds |
83
+ | `maxDelay` | `30000` | Upper bound for one delay in milliseconds |
84
+ | `factor` | `2` | Multiplier applied to the delay each attempt |
85
+ | `jitter` | `true` | Randomize delays to spread out retries |
86
+ | `retryableStatuses` | `[408, 429, 500, 502, 503, 504]` | Status codes that trigger a retry |
87
+ | `respectRetryAfter` | `true` | Wait for the `Retry-After` header on a 429 |
88
+
89
+ ```typescript
90
+ import * as httpclient from "@eserstack/httpclient";
91
+
92
+ const client = httpclient.createHttpClient({
93
+ baseUrl: "https://api.example.com",
94
+ timeout: 10_000,
95
+ retry: { maxAttempts: 5, initialDelay: 500 },
96
+ });
97
+
98
+ // Turn retries off for one call
99
+ const health = await client.get("/health", { retry: false });
100
+ ```
101
+
102
+ A request whose body is a `ReadableStream` is sent once and never retried,
103
+ because the first attempt consumes the stream.
104
+
105
+ The retry policy runs in Go, in the `@eserstack/ajan` library this package
106
+ depends on: the client asks it how many attempts a request gets and, after each
107
+ failed attempt, whether and how long to wait. That holds for both transports.
108
+ When the library cannot be loaded, every request throws an `HttpClientError`
109
+ before anything is sent, and its `cause` says why.
110
+
111
+ ## Errors
112
+
113
+ A failed request throws an `HttpClientError` subclass. Each one has
114
+ `statusCode`, `body` (the parsed error body), `retryAfter` (seconds), `request`
115
+ and `response` (or `null` when not known), and a `code`:
116
+
117
+ | Class | `code` | Raised when |
118
+ | -------------------- | ---------------- | ----------------------------------------- |
119
+ | `HttpResponseError` | `RESPONSE_ERROR` | The server answered with a non-2xx status |
120
+ | `HttpRateLimitError` | `RATE_LIMITED` | The server answered 429 Too Many Requests |
121
+ | `HttpTimeoutError` | `TIMEOUT` | The timeout elapsed |
122
+ | `HttpAbortError` | `ABORT_ERROR` | Your `signal` aborted the request |
123
+ | `HttpNetworkError` | `NETWORK_ERROR` | DNS or the connection failed, no response |
124
+
125
+ ```typescript
126
+ import * as httpclient from "@eserstack/httpclient";
127
+
128
+ const client = httpclient.createHttpClient({
129
+ baseUrl: "https://api.example.com",
130
+ });
131
+
132
+ try {
133
+ await client.get("/users/1");
134
+ } catch (error) {
135
+ if (error instanceof httpclient.HttpRateLimitError) {
136
+ console.log(`Rate limited, retry after ${error.retryAfter} seconds`);
137
+ } else if (error instanceof httpclient.HttpResponseError) {
138
+ console.log(`HTTP ${error.statusCode}`, error.body);
139
+ } else {
140
+ throw error;
141
+ }
142
+ }
143
+ ```
144
+
145
+ `classifyError(error, response?)` and `classifyHttpStatus(status)` map a native
146
+ error or a status code to these classes for code that calls `fetch` itself.
147
+
148
+ ## Result Style
149
+
150
+ Each method has a `Result` twin (`getResult`, `postResult`, `putResult`,
151
+ `patchResult`, `deleteResult`, `requestResult`) that never throws and returns
152
+ `Result<HttpResponse<T>, HttpClientError>`:
153
+
154
+ ```typescript
155
+ import * as httpclient from "@eserstack/httpclient";
156
+ import * as primitives from "@eserstack/primitives";
157
+
158
+ const client = httpclient.createHttpClient({
159
+ baseUrl: "https://api.example.com",
160
+ });
161
+
162
+ const result = await client.getResult<{ id: number }>("/users/1");
163
+
164
+ if (primitives.results.isOk(result)) {
165
+ console.log(result.value.data.id);
166
+ } else {
167
+ console.log(result.error.statusCode);
168
+ }
169
+ ```
170
+
171
+ ## Streaming
172
+
173
+ `requestStream(method, path, options)` and `postStream(path, options)` return
174
+ the body as a `ReadableStream` without reading it, for server-sent events and
175
+ NDJSON. Retries and the timeout apply to opening the connection only (on the
176
+ native transport the timeout covers the whole stream; see Native Client), and
177
+ response interceptors do not run. You own the stream and must read it to the end
178
+ or cancel it.
179
+
180
+ ```typescript
181
+ import * as httpclient from "@eserstack/httpclient";
182
+
183
+ const client = httpclient.createHttpClient({
184
+ baseUrl: "https://api.example.com",
185
+ });
186
+
187
+ const stream = await client.postStream("/completions", {
188
+ body: { prompt: "Hello", stream: true },
189
+ });
190
+
191
+ const decoder = new TextDecoder();
192
+ for await (const chunk of stream.body) {
193
+ console.log(decoder.decode(chunk, { stream: true }));
194
+ }
195
+ ```
196
+
197
+ `requestStreamResult` and `postStreamResult` are the `Result` forms.
198
+
199
+ ## Interceptors
200
+
201
+ Request interceptors receive the `Request` before it is sent; response
202
+ interceptors receive the `HttpResponse` after it is parsed. Each runs in order
203
+ and passes its output to the next.
204
+
205
+ ```typescript
206
+ import * as httpclient from "@eserstack/httpclient";
207
+
208
+ const client = httpclient.createHttpClient({
209
+ baseUrl: "https://api.example.com",
210
+ interceptors: {
211
+ request: [
212
+ {
213
+ name: "request-id",
214
+ intercept: (request) => {
215
+ const headers = new Headers(request.headers);
216
+ headers.set("X-Request-Id", crypto.randomUUID());
217
+ return new Request(request, { headers });
218
+ },
219
+ },
220
+ ],
221
+ },
222
+ });
223
+ ```
224
+
225
+ `InterceptorChain` is an ordered list you can add to and remove from by name,
226
+ and `applyRequestInterceptors` and `applyResponseInterceptors` run a list
227
+ outside the client.
228
+
229
+ ## Native Client
230
+
231
+ By default every request goes through `fetch`, or through `fetchFn` when you
232
+ pass one. Set `transport: "native"` to send the requests through the Go HTTP
233
+ client of `@eserstack/ajan` instead:
234
+
235
+ ```typescript
236
+ import * as httpclient from "@eserstack/httpclient";
237
+
238
+ const client = httpclient.createHttpClient({
239
+ baseUrl: "https://api.example.com",
240
+ transport: "native",
241
+ });
242
+
243
+ try {
244
+ const response = await client.get<{ id: number }>("/users/1");
245
+ console.log(response.data.id);
246
+ } finally {
247
+ client.close();
248
+ }
249
+ ```
250
+
251
+ Every method behaves the same on both transports: the request is built the same
252
+ way, interceptors run, the retry policy applies, and failures throw the same
253
+ errors. Only the exchange itself differs:
254
+
255
+ - With the native library, each call into the Go client runs in a worker
256
+ thread, so the JavaScript thread keeps running while it waits. The client's
257
+ `timeout` bounds the call and covers reading the response body too, so a
258
+ `requestStream` body is cut off once `timeout` has passed. A `signal` that
259
+ fires rejects the request at once; the Go request itself runs on in its
260
+ worker until it ends, and an abort while a streamed body is read closes the
261
+ stream. On the WASM fallback (no native library for the platform), the
262
+ requests wait on the runtime's `fetch`, and a `signal` stops one in flight;
263
+ see the `@eserstack/ajan` README, "Network on the WASM fallback".
264
+ - Request bodies must be text: a string, `URLSearchParams`, or an object sent as
265
+ JSON. A binary, `FormData`, `Blob` or stream body throws an `HttpClientError`;
266
+ send those with the default transport.
267
+ - The response body of a non-streaming request arrives as UTF-8 text of at most
268
+ 32 MiB, so a binary body is not kept byte for byte. `requestStream` passes the
269
+ bytes through unchanged.
270
+ - When the native library cannot be loaded, every request throws an
271
+ `HttpClientError` whose `cause` says why, as on the default transport (see
272
+ Timeouts and Retries).
273
+ - `transport: "native"` cannot be combined with `fetchFn`.
274
+
275
+ Call `client.close()` to release the Go client when you are done with a client.
276
+ The `@eserstack/httpclient/go-client` module calls the Go client directly; its
277
+ options use the Go bridge's field names, such as `timeoutMs`, `retryEnabled` and
278
+ `maxAttempts`.
279
+
280
+ For tests, pass `fetchFn` to replace `fetch`.
281
+
282
+ ## Upgrading from 4.x
283
+
284
+ These changes since 4.5.2 need a change in code, commands or files that use this
285
+ package. The [changelog](https://github.com/eser/stack/blob/main/CHANGELOG.md)
286
+ lists the changes in every package.
287
+
288
+ - `request()` and `requestStream()` use `fetch` like the other methods instead
289
+ of switching to the Go client when `@eserstack/ajan` loads. Pass
290
+ `transport: "native"` in `HttpClientConfig` to use the Go client; passing it
291
+ together with `fetchFn` throws `TypeError`.
292
+ - A request whose body is a `ReadableStream` is not retried. Buffer the body
293
+ yourself if you need retries.
294
+ - The retry policy runs in Go through `@eserstack/ajan`, on the default `fetch`
295
+ transport too, so a request throws an `HttpClientError` when that library
296
+ cannot be loaded (for example with `ESER_AJAN=disabled`).
297
+ - A `RetryConfig` field set to `undefined` or `null` takes its default, and a
298
+ value outside the `RetryConfig` types (such as `jitter: "yes"` or
299
+ `retry: true`) throws an `HttpClientError` instead of being coerced.
300
+
301
+ ## 🔗 Links
302
+
303
+ - [npm package](https://www.npmjs.com/package/@eserstack/httpclient)
304
+ - [eser/stack on GitHub](https://github.com/eser/stack)
@@ -0,0 +1,85 @@
1
+ /**
2
+ * HttpClient — resilient HTTP client with timeout, retry, rate-limit handling,
3
+ * and request/response interceptors.
4
+ *
5
+ * Provides two APIs:
6
+ * - Throw-style: `client.get<T>(url)` — throws HttpClientError on failure
7
+ * - Result-style: `client.getResult<T>(url)` — returns Result<HttpResponse<T>, HttpClientError>
8
+ * for @eserstack/functions do-notation compatibility
9
+ *
10
+ * @module
11
+ */
12
+ import * as results from "@eserstack/primitives/results";
13
+ import type * as types from "./types.ts";
14
+ import * as errors from "./errors.ts";
15
+ export declare const parseRetryAfter: (header: string | null) => number | null;
16
+ export declare const extractRateLimitInfo: (hdrs: Headers) => types.RateLimitInfo | undefined;
17
+ export declare class HttpClient {
18
+ #private;
19
+ private readonly config;
20
+ constructor(config?: types.HttpClientConfig);
21
+ /** Return a new client with merged configuration (immutable). */
22
+ withDefaults(overrides: Partial<types.HttpClientConfig>): HttpClient;
23
+ request<T>(method: types.HttpMethod, url: string, options?: types.RequestOptions): Promise<types.HttpResponse<T>>;
24
+ get<T>(url: string, options?: types.RequestOptions): Promise<types.HttpResponse<T>>;
25
+ post<T>(url: string, options?: types.RequestOptions): Promise<types.HttpResponse<T>>;
26
+ put<T>(url: string, options?: types.RequestOptions): Promise<types.HttpResponse<T>>;
27
+ patch<T>(url: string, options?: types.RequestOptions): Promise<types.HttpResponse<T>>;
28
+ delete<T>(url: string, options?: types.RequestOptions): Promise<types.HttpResponse<T>>;
29
+ /**
30
+ * Make a request and return the response body as a ReadableStream.
31
+ * Throws HttpClientError on non-2xx status (after retries).
32
+ *
33
+ * Key differences from `request<T>()`:
34
+ * - Body is NOT consumed or parsed — caller owns the stream lifecycle.
35
+ * - Retry applies to connection establishment only, not stream reading.
36
+ * - Timeout applies to the initial connection, not stream duration; on
37
+ * transport "native" the Go client's timeout covers the whole stream.
38
+ * - Response interceptors do NOT run (they require a parsed `data` field).
39
+ */
40
+ requestStream(method: types.HttpMethod, url: string, options?: types.RequestOptions): Promise<types.HttpStreamResponse>;
41
+ /**
42
+ * POST a request and return the response body as a ReadableStream.
43
+ * The only streaming convenience method provided — it is the only HTTP verb
44
+ * used for streaming in practice (SSE, NDJSON).
45
+ */
46
+ postStream(url: string, options?: types.RequestOptions): Promise<types.HttpStreamResponse>;
47
+ requestResult<T>(method: types.HttpMethod, url: string, options?: types.RequestOptions): Promise<results.Result<types.HttpResponse<T>, errors.HttpClientError>>;
48
+ getResult<T>(url: string, options?: types.RequestOptions): Promise<results.Result<types.HttpResponse<T>, errors.HttpClientError>>;
49
+ postResult<T>(url: string, options?: types.RequestOptions): Promise<results.Result<types.HttpResponse<T>, errors.HttpClientError>>;
50
+ putResult<T>(url: string, options?: types.RequestOptions): Promise<results.Result<types.HttpResponse<T>, errors.HttpClientError>>;
51
+ patchResult<T>(url: string, options?: types.RequestOptions): Promise<results.Result<types.HttpResponse<T>, errors.HttpClientError>>;
52
+ deleteResult<T>(url: string, options?: types.RequestOptions): Promise<results.Result<types.HttpResponse<T>, errors.HttpClientError>>;
53
+ requestStreamResult(method: types.HttpMethod, url: string, options?: types.RequestOptions): Promise<results.Result<types.HttpStreamResponse, errors.HttpClientError>>;
54
+ postStreamResult(url: string, options?: types.RequestOptions): Promise<results.Result<types.HttpStreamResponse, errors.HttpClientError>>;
55
+ /**
56
+ * Shared retry/timeout/error-handling core.
57
+ * Handles URL building, header merging, body serialization, retry loop,
58
+ * timeout via AbortSignal, rate-limit parsing, and error classification.
59
+ *
60
+ * The `onSuccess` callback is invoked once a 2xx response is received.
61
+ * It receives the raw Response, the sent Request, the retry count, and any
62
+ * extracted rate-limit info. Each public method variant supplies its own
63
+ * onSuccess: _execute parses JSON and runs response interceptors;
64
+ * _executeStream returns the body stream directly.
65
+ *
66
+ * This is the single source of truth for retry/timeout behavior — both
67
+ * _execute and _executeStream delegate entirely to this method, on the
68
+ * fetch and the native transport alike. The loop stays here because it runs
69
+ * the request interceptors before every attempt; the decisions come from
70
+ * the retry policy in Go (retry-policy.ts). `stream` tells the native
71
+ * transport to hand the body over unread.
72
+ */
73
+ private _executeFetch;
74
+ /** JSON-parsing variant — parses body, builds HttpResponse<T>, runs response interceptors. */
75
+ private _execute;
76
+ /**
77
+ * Streaming variant — returns body as ReadableStream without consuming it.
78
+ * Response interceptors do NOT run (they require a parsed `data` field).
79
+ * Timeout applies to connection establishment only, not stream reading.
80
+ */
81
+ private _executeStream;
82
+ /** Release the Go HTTP client handle that `transport: "native"` opened. */
83
+ close(): void;
84
+ }
85
+ export declare const createHttpClient: (config?: types.HttpClientConfig) => HttpClient;