@indra211/exios 0.0.0-stage → 2.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 exios contributors
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,188 @@
1
- # Temporary Holding Version
1
+ # exios
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
+ An axios-compatible HTTP client with **exponential-backoff retry** and a **circuit breaker** built in. Like axios it uses **XHR in browsers** and **Node's `http`/`https` in Node**, with native `fetch` as a third adapter. Zero runtime dependencies, fully typed, ESM + CJS, runs in Node >= 20, modern browsers, Bun, Deno and edge runtimes.
4
+
5
+ Retry and the breaker are **on by default** for the default instance and for every `create()` instance, with safe defaults (idempotent methods only, `Retry-After` honoured, breaker outside the retry loop).
6
+
7
+ ## Install
8
+
9
+ ```sh
10
+ npm install @indra211/exios
11
+ ```
12
+
13
+ CommonJS works too: `require('@indra211/exios')` returns the default instance itself, so `const exios = require('@indra211/exios'); exios.get(...)` works, and named exports are available as properties (`require('@indra211/exios').create`, `.CircuitOpenError`, ...). `require('@indra211/exios').default` is the same instance.
14
+
15
+ ## Quick start
16
+
17
+ ```ts
18
+ import exios, { create, isExiosError, isCancel, CircuitOpenError } from "@indra211/exios";
19
+
20
+ const { data } = await exios.get<{ id: number }>(
21
+ "https://api.example.com/users/1",
22
+ {
23
+ params: { expand: "team" },
24
+ },
25
+ );
26
+
27
+ const api = exios.create({
28
+ baseURL: "https://api.example.com",
29
+ timeout: 5000,
30
+ retry: { retries: 2, baseDelayMs: 200 },
31
+ breaker: { failureThreshold: 5, resetTimeoutMs: 10_000 },
32
+ });
33
+
34
+ api.interceptors.request.use((config) => {
35
+ config.headers.authorization = "Bearer ...";
36
+ return config;
37
+ });
38
+
39
+ try {
40
+ const res = await api.post("/orders", { sku: "a1" });
41
+ console.log(res.status, res.meta.attempts);
42
+ } catch (err) {
43
+ if (err instanceof CircuitOpenError)
44
+ console.log("circuit open for", err.origin, "until", err.retryAt);
45
+ else if (isCancel(err)) console.log("canceled");
46
+ else if (isExiosError(err))
47
+ console.log(err.code, err.status, err.meta?.attempts);
48
+ }
49
+ ```
50
+
51
+ `api.defaults` is mutable, axios-style: `api.defaults.headers.common.Authorization = 'Bearer ...'` and per-method buckets such as `api.defaults.headers.post['Content-Type'] = '...'` work (every bucket always exists). Headers set by request interceptors are normalised before sending: keys are case-insensitive, the last write wins, and `null` removes a header.
52
+
53
+ The API surface matches axios: `exios(config)`, `exios(url, config)`, `exios.request`, `get/delete/head/options`, `post/put/patch`, `postForm/putForm/patchForm`, `create`, `defaults`, `interceptors`, `getUri`. Responses are `{ data, status, statusText, headers, config, request, meta }`.
54
+
55
+ ## Adapters
56
+
57
+ | Adapter | Used by default in | Notes |
58
+ |---|---|---|
59
+ | `xhr` | browsers and web workers | Real upload and download progress everywhere. Ignores `fetchOptions`; always follows redirects (`redirect` is ignored). `responseType: 'stream'` is served by `fetch` (XHR cannot stream); a `ReadableStream` request body is read into memory first. |
60
+ | `http` | Node and Bun (Node build) | Node `http`/`https`: `proxy`, `httpAgent`/`httpsAgent`, `maxRedirects`, `beforeRedirect`, `socketPath`, `decompress`, `insecureHTTPParser`, Node `Readable` streams, upload and download progress. |
61
+ | `fetch` | Deno, Cloudflare Workers, edge runtimes, service workers | `fetchOptions`, `redirect`, custom `fetch`. Upload progress streams the body where the runtime supports request streams (Node, Deno, Bun, workers); in browser pages it reports one final event. |
62
+
63
+ The default is `adapter: ['xhr', 'http', 'fetch']`: the first one available wins. Force one with `adapter: 'fetch'` (or pass your own `(config) => Promise<response>` function). Asking for an adapter the runtime does not have rejects with `ERR_NOT_SUPPORT`. `package.json` export conditions pick the build automatically: `node` gets the Node build (with `http`); `browser`, `deno`, `workerd` and `edge-light` get the browser build (no `node:*` imports).
64
+
65
+ Retry, the circuit breaker, interceptors, timeouts, cancellation and error codes behave the same on every adapter. `response.request` is the `XMLHttpRequest`, `ClientRequest` or `Request` that was sent; on the `http` adapter `response.request.responseURL` is the final URL after redirects.
66
+
67
+ With `responseType: 'stream'`, `timeout` covers only getting the response, not reading the stream; aborting `signal` (or a `cancelToken`) after the response resolved still stops the stream with a `CanceledError`. A stream body from an attempt that is retried is cancelled.
68
+
69
+ ### Node `http` options
70
+
71
+ ```ts
72
+ await exios.get(url, {
73
+ proxy: { protocol: "http", host: "127.0.0.1", port: 8080, auth: { username: "u", password: "p" } },
74
+ httpsAgent: new https.Agent({ keepAlive: true }),
75
+ maxRedirects: 5, // default 21; 0 returns the 3xx response
76
+ beforeRedirect: (options, { statusCode, headers }) => {},
77
+ decompress: true, // gzip, deflate, br (default true)
78
+ socketPath: "/var/run/docker.sock",
79
+ });
80
+ ```
81
+
82
+ - **Proxy:** `proxy` wins; `proxy: false` disables proxying; otherwise `HTTP_PROXY` / `HTTPS_PROXY` / `NO_PROXY` (and lowercase variants) are used, like axios. HTTPS targets go through a `CONNECT` tunnel, using the TLS options (`ca`, `rejectUnauthorized`, ...) of your `httpsAgent`. An `https:` proxy (`protocol: 'https'` or `HTTPS_PROXY=https://...`) is reached over TLS. Aborts and timeouts also tear down a `CONNECT` still in progress.
83
+ - **Redirects:** 303, and 301/302 after a POST, become GET without a body; 307/308 resend the method and body (a one-shot stream body cannot be resent, so the 307/308 is returned). A redirect to another host or port, or from `https:` to `http:`, drops `Authorization`, `Cookie` and `Proxy-Authorization`. A redirect that would have to resend a one-shot stream body is returned instead of followed. Too many redirects reject with `ERR_FR_TOO_MANY_REDIRECTS` (never retried).
84
+ - **Network errors** keep `code: 'ERR_NETWORK'` (retry and the breaker depend on it); the Node error is in `error.cause`, so `error.cause.code` is `ECONNREFUSED`, `ECONNRESET`, `ENOTFOUND`, ... (axios puts that in `error.code` instead).
85
+ - **Bodies:** `FormData`, `Blob`, `URLSearchParams`, strings and typed arrays are buffered (so they are resent on retries and redirects, with an exact `Content-Length`); web `ReadableStream` and Node `Readable` bodies (including `fs` streams and the `form-data` package, whose `getHeaders()` boundary is used) are streamed and never retried. If a body stream fails, the request rejects with `ERR_BAD_REQUEST` (the stream's error is in `cause`), and an aborted or timed-out request destroys the body stream.
86
+
87
+ ## Progress, XSRF, encodings and CancelToken
88
+
89
+ - **`onUploadProgress` / `onDownloadProgress`** on every adapter, axios event shape: `{ loaded, total, progress, bytes, rate, estimated, upload | download, event }`. With `decompress`, the download `total` is omitted (the `Content-Length` is the compressed size).
90
+ - **XSRF** (browsers): `xsrfCookieName` (default `'XSRF-TOKEN'`) is read from `document.cookie` and sent as `xsrfHeaderName` (default `'X-XSRF-TOKEN'`) when `withXSRFToken` is `true`, or when it is unset and the request is same-origin. `withXSRFToken: false` never sends it; a function decides per request. A header you set yourself is never overwritten.
91
+ - **`responseEncoding`** decodes text and JSON responses with any `TextDecoder` label (`'latin1'`, `'shift_jis'`, ...); default UTF-8. An unknown label rejects with `ERR_BAD_OPTION_VALUE` before any request is sent.
92
+ - **`CancelToken`** (deprecated in favour of `signal`, as in axios): `CancelToken.source()` → `{ token, cancel(message) }`, `new CancelToken(executor)`, `token.reason`, `token.throwIfRequested()`, `token.subscribe/unsubscribe`, `token.toAbortSignal()`. With both `signal` and `cancelToken`, whichever fires first cancels; cancelling also stops a retry backoff and is never counted by the breaker.
93
+
94
+ ## Breaking changes since 1.0.0
95
+
96
+ - In Node the default transport is now Node `http`/`https` (it was `fetch`), so `responseType: 'stream'` returns a Node `Readable` instead of a web `ReadableStream`. Use `adapter: 'fetch'` to get 1.0.0 behaviour back.
97
+ - `response.request` / `error.request` are the adapter's request object (typed `any`), not always a `Request`.
98
+ - `responseEncoding` is now honoured (it was ignored).
99
+
100
+ ## Migrating from axios
101
+
102
+ 1. Swap the import: `import axios from 'axios'` becomes `import exios from '@indra211/exios'`. Named helpers: `isExiosError` (was `isAxiosError`), `isCancel`, `ExiosError`, `CanceledError`, `toFormData`, `mergeConfig`.
103
+ 2. `CancelToken` works as in axios (and is deprecated there too); prefer `signal: controller.signal`.
104
+ 3. Error codes are the axios strings (`ERR_BAD_REQUEST`, `ERR_BAD_RESPONSE`, `ERR_NETWORK`, `ECONNABORTED`, `ETIMEDOUT`, `ERR_CANCELED`, `ERR_BAD_OPTION_VALUE`, `ERR_NOT_SUPPORT`, `ERR_FR_TOO_MANY_REDIRECTS`) plus the new `ERR_CIRCUIT_OPEN`.
105
+ 4. The number of attempts made is `response.meta.attempts` (and `error.meta.attempts`). A request rejected by an open circuit has `attempts: 0`.
106
+ 5. `response.headers` is a plain lowercase-keyed object; `response.request` is the adapter's request object (see Adapters).
107
+ 6. Node transport options (`proxy`, agents, `maxRedirects`, `socketPath`, `decompress`, ...) work on the `http` adapter. The `fetch` adapter adds `fetch` (custom implementation), `fetchOptions` (`cache`, `credentials`, `mode`, `redirect`, `referrer`, `referrerPolicy`, `integrity`, `keepalive`, `priority`) and `redirect`. `fetchOptions.credentials` is used as given; `withCredentials: true` forces `'include'`, and the default is `'same-origin'`.
108
+ 7. Any object body that is not `FormData`, `Blob`, `ArrayBuffer`/typed array, `ReadableStream` or `URLSearchParams` (including class instances and `Date`) is sent as JSON, like axios. Only plain objects and arrays are converted for `multipart/form-data` or `application/x-www-form-urlencoded`.
109
+ 8. If you used `axios-retry` or `opossum`, remove them: use the `retry` and `breaker` options below.
110
+
111
+ ## Retry
112
+
113
+ `retry` is `false` or an options object. Defaults:
114
+
115
+ | Option | Default | Meaning |
116
+ | --------------------- | ----------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
117
+ | `retries` | `3` | Retries after the first attempt (up to 4 attempts) |
118
+ | `methods` | `['get','head','options','put','delete']` | Methods that may be retried (also gates retries after network errors) |
119
+ | `statusCodes` | `[408, 429, 500, 502, 503, 504]` | Response statuses that trigger a retry |
120
+ | `retryOnNetworkError` | `true` | Retry `ERR_NETWORK` and timeouts |
121
+ | `baseDelayMs` | `300` | Delay before the first retry |
122
+ | `maxDelayMs` | `30000` | Cap on any delay (including `Retry-After`) |
123
+ | `factor` | `2` | Backoff multiplier: delay n = `min(maxDelayMs, baseDelayMs * factor^(n-1))` |
124
+ | `jitter` | `'full'` | `'full'` picks `random(0, delay)`; `'none'` uses the exact delay |
125
+ | `respectRetryAfter` | `true` | `Retry-After` (seconds or HTTP date) replaces the computed delay, capped at `maxDelayMs` |
126
+ | `maxElapsedMs` | none | Optional time budget for the retry sequence: no new attempt starts if its delay would exceed the budget (an attempt already in flight is not cut short; use `timeout` for that) |
127
+ | `shouldRetry` | none | `({ error?, response?, attempt, config }) => boolean \| Promise<boolean>` |
128
+ | `onRetry` | none | `({ error?, response?, attempt, delayMs }) => void`, called before each backoff sleep |
129
+
130
+ `timeout` applies per attempt. Aborting `signal` cancels the whole sequence immediately, including a pending backoff sleep.
131
+
132
+ A `shouldRetry` or `onRetry` hook that throws rejects the request with that error as-is (not wrapped in an `ExiosError`), and nothing is recorded on the breaker for that request.
133
+
134
+ All numeric options are validated when a request is made: `retries`, `baseDelayMs`, `maxDelayMs` and `maxElapsedMs` must be non-negative finite numbers and `factor` must be `>= 1`; anything else rejects with `ERR_BAD_OPTION_VALUE`. An option set to `undefined` counts as not set and keeps its default.
135
+
136
+ ## Circuit breaker
137
+
138
+ There is one breaker per origin (`protocol//host:port`) per instance, kept in memory. States: closed, then open after the failure threshold, then half-open after `resetTimeoutMs`; probe success closes it, probe failure re-opens it. Requests rejected while open fail immediately with `CircuitOpenError` (`code: 'ERR_CIRCUIT_OPEN'`, with `origin` and `retryAt`).
139
+
140
+ | Option | Default | Meaning |
141
+ | ---------------------- | -------------------------------- | ----------------------------------------------------------------------------------------- |
142
+ | `failureThreshold` | `5` | Consecutive failures that open the circuit |
143
+ | `windowMs` | none | If set, rolling-window mode: the failure _rate_ is used and `failureThreshold` is ignored |
144
+ | `minRequests` | `10` | Minimum samples in the window before the rate applies |
145
+ | `failureRateThreshold` | `0.5` | Failure rate that opens the circuit (window mode) |
146
+ | `resetTimeoutMs` | `30000` | Time open before moving to half-open |
147
+ | `halfOpenMaxRequests` | `1` | Concurrent probes allowed in half-open |
148
+ | `successThreshold` | `1` | Probe successes needed to close |
149
+ | `isFailure` | network error, timeout, 5xx, 429 | `({ error?, response? }) => boolean` (also settable per request) |
150
+ | `key` | origin of the final URL | `(config) => string` (also settable per request) |
151
+ | `onStateChange` | none | `(key, from, to) => void` |
152
+
153
+ Introspect with `api.breaker.state(origin)` and reset with `api.breaker.reset(origin?)`. 4xx responses other than 408/429 are not failures, and cancellations never count.
154
+
155
+ The open to half-open move is lazy: it happens when the next request arrives, so `breaker.state(origin)` keeps reporting `'open'` after `resetTimeoutMs` has passed until a request is made.
156
+
157
+ Breaker options are validated like retry options: `failureThreshold`, `resetTimeoutMs`, `minRequests` and `windowMs` must be `> 0`, `failureRateThreshold` must be in `(0, 1]`, and `halfOpenMaxRequests` and `successThreshold` must be `>= 1`. Invalid values reject with `ERR_BAD_OPTION_VALUE`; `undefined` keeps the default. Relative and protocol-relative URLs are keyed by their origin resolved against `location` in browsers.
158
+
159
+ ## Behavior rules
160
+
161
+ These are deliberate and tested.
162
+
163
+ 1. **Per-request `breaker` config.** Thresholds (`failureThreshold`, window settings, `resetTimeoutMs`, `halfOpenMaxRequests`, `successThreshold`, `onStateChange`) are per instance only. Per request you may set only `breaker: false` (skip the gate and report nothing), `breaker.key` and `breaker.isFailure`. A breaker reads the instance config when it is first created for a key; changing `defaults.breaker` later affects new keys only, and `api.breaker.reset()` discards existing breakers so they pick up the new config.
164
+ 2. **`create()` inherits resilience.** Instances from `create()` get retry and breaker enabled with the default settings. Pass `retry: false` / `breaker: false` to opt out.
165
+ 3. **`validateStatus` does not affect resilience.** Retry and breaker judge the raw attempt outcome (network error/timeout, or the HTTP status). A 503 accepted by a custom `validateStatus` is still retried and still counts as a breaker failure, unless `shouldRetry` / `isFailure` say otherwise. `validateStatus` only decides whether the final result resolves or rejects.
166
+ 4. **Half-open probes get no retries.** A request admitted as a half-open probe makes exactly one attempt; its outcome closes or re-opens the circuit immediately.
167
+ 5. **Node floor is 20.** `engines.node` is `>=20`. The full test suite needs Node 22+ (Vitest), so Node 20 is covered by a smoke test against the built package, not the full suite.
168
+ 6. **`shouldRetry` scope.** It replaces the `methods`, `statusCodes` and `retryOnNetworkError` checks, so an explicit hook can retry a POST. It can never override the never-retry list (canceled, circuit open, bad option, one-shot stream body); `retries` and `maxElapsedMs` still cap.
169
+ 7. **Rolling-window mode.** When `windowMs` is set, `failureThreshold` is ignored. Closing from half-open clears the window / consecutive counter.
170
+ 8. **Network errors and `methods`.** The `methods` filter gates every retry, including after network errors: a POST that failed at the network level may have reached the server, so it is not retried by default.
171
+
172
+ Also:
173
+
174
+ - **Breaker outside retry.** The breaker sees one outcome per logical request, not one per attempt. Between attempts it is re-checked; if other requests opened it, the loop stops with `CircuitOpenError`.
175
+ - **2xx responses are never retried**, even if `shouldRetry` returns true.
176
+ - **Throwing request interceptors.** A synchronous request interceptor that throws routes to the next interceptor's `onRejected` (this differs from axios).
177
+ - **Hung half-open probes.** A half-open probe that hangs longer than `resetTimeoutMs` counts as a failure.
178
+ - **Never retried:** cancellations, `ERR_CIRCUIT_OPEN`, `ERR_BAD_OPTION_VALUE`, `ERR_NOT_SUPPORT`, `ERR_FR_TOO_MANY_REDIRECTS`, and requests whose body is a one-shot stream (web `ReadableStream` or Node `Readable`).
179
+
180
+ ## Not supported
181
+
182
+ - `maxRate` (bandwidth limits), `lookup` / `family` DNS options, HTTP/2 on the `http` adapter.
183
+ - `redirect: 'manual' | 'error'` and `fetchOptions` on the `xhr` adapter (browsers' XHR always follows redirects); use `adapter: 'fetch'` when you need them.
184
+ - Distributed or persisted breaker state.
185
+
186
+ ## License
187
+
188
+ MIT