@indra211/exios 2.0.1 → 3.1.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/README.md +182 -0
- package/dist/index.cjs +640 -16
- package/dist/index.d.cts +19 -0
- package/dist/index.d.ts +216 -10
- package/dist/index.js +641 -16
- package/dist/index.node.cjs +640 -16
- package/dist/index.node.js +641 -16
- package/package.json +8 -3
package/README.md
CHANGED
|
@@ -97,6 +97,12 @@ await exios.get(url, {
|
|
|
97
97
|
- `response.request` / `error.request` are the adapter's request object (typed `any`), not always a `Request`.
|
|
98
98
|
- `responseEncoding` is now honoured (it was ignored).
|
|
99
99
|
|
|
100
|
+
## Breaking changes in 3.0.0
|
|
101
|
+
|
|
102
|
+
- `error.toJSON()` now redacts credentials, sensitive header values and the request body (see [Error diagnostics](#error-diagnostics)). The shape is unchanged; code that read a secret back out of serialized errors will now see `"[REDACTED]"`.
|
|
103
|
+
- `response.meta` and `error.meta` gain optional fields (`requestId`, `correlationId`, `durationMs`, …). Tests that compare `meta` with an exact `toEqual({ attempts: 1 })` need `toMatchObject`.
|
|
104
|
+
- Retry, breaker, error codes and error messages are unchanged.
|
|
105
|
+
|
|
100
106
|
## Migrating from axios
|
|
101
107
|
|
|
102
108
|
1. Swap the import: `import axios from 'axios'` becomes `import exios from '@indra211/exios'`. Named helpers: `isExiosError` (was `isAxiosError`), `isCancel`, `ExiosError`, `CanceledError`, `toFormData`, `mergeConfig`.
|
|
@@ -156,6 +162,166 @@ The open to half-open move is lazy: it happens when the next request arrives, so
|
|
|
156
162
|
|
|
157
163
|
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
164
|
|
|
165
|
+
## Observability and diagnostics
|
|
166
|
+
|
|
167
|
+
### Request and correlation IDs
|
|
168
|
+
|
|
169
|
+
Every logical request gets a `requestId`: a UUID from `crypto.randomUUID()` where that exists, otherwise a unique fallback. Retries share it. You can pass your own, and request interceptors can read or replace it. `correlationId` is yours to set, usually on an instance, to tie requests to a wider operation.
|
|
170
|
+
|
|
171
|
+
```js
|
|
172
|
+
const api = exios.create({
|
|
173
|
+
baseURL: "https://api.example.com",
|
|
174
|
+
correlationId: "checkout-7f3a",
|
|
175
|
+
correlationIdHeader: "x-correlation-id", // opt-in: off by default
|
|
176
|
+
});
|
|
177
|
+
const res = await api.get("/cart");
|
|
178
|
+
res.meta; // { attempts, requestId, correlationId, durationMs, responseTimeMs }
|
|
179
|
+
```
|
|
180
|
+
|
|
181
|
+
IDs are **not** sent to the server unless you set `correlationIdHeader`. An extra header can trigger a CORS preflight in browsers. The header carries `correlationId`, or `requestId` when there is none. A header you set yourself always wins.
|
|
182
|
+
|
|
183
|
+
`durationMs` covers the whole logical request: breaker gate, every attempt and the backoff sleeps. `responseTimeMs` covers the final attempt only. Neither includes request or response interceptors. For `responseType: 'stream'`, timing stops when the headers arrive.
|
|
184
|
+
|
|
185
|
+
### Error diagnostics
|
|
186
|
+
|
|
187
|
+
Error messages and codes are unchanged from axios. Errors that reach your code carry context in `error.meta`:
|
|
188
|
+
|
|
189
|
+
```js
|
|
190
|
+
try {
|
|
191
|
+
await api.get("/users/1");
|
|
192
|
+
} catch (err) {
|
|
193
|
+
err.code; // 'ERR_BAD_REQUEST', 'ERR_NETWORK', 'ECONNABORTED', 'ERR_CIRCUIT_OPEN', ...
|
|
194
|
+
err.meta; // { attempts, requestId, correlationId, method, url, durationMs }
|
|
195
|
+
err.cause; // the original error (e.g. the ECONNREFUSED system error) for network failures
|
|
196
|
+
}
|
|
197
|
+
```
|
|
198
|
+
|
|
199
|
+
`meta.url` is `baseURL + url` without the serialized `params`. A query string you wrote into `url` yourself is kept.
|
|
200
|
+
|
|
201
|
+
`error.toJSON()` (and so `JSON.stringify(error)`) is **log-safe**: the values of `Authorization`, `Proxy-Authorization`, `Cookie`, `Set-Cookie`, `X-Api-Key`, `X-Auth-Token`, `X-XSRF-Token` and `X-CSRF-Token`, `auth.password`, proxy credentials and the request body are replaced with `"[REDACTED]"`. The error object itself (`error.config`) is not modified.
|
|
202
|
+
|
|
203
|
+
### Lifecycle events
|
|
204
|
+
|
|
205
|
+
```ts
|
|
206
|
+
const off = api.on("retry", (e) => {
|
|
207
|
+
console.log(e.requestId, `attempt ${e.attempt} failed (${e.status ?? e.error?.code}), retrying in ${e.delayMs}ms`);
|
|
208
|
+
});
|
|
209
|
+
api.once("circuitOpen", (e) => alert(`${e.key} is down`));
|
|
210
|
+
off(); // unsubscribe one listener
|
|
211
|
+
api.off("retry"); // or remove every listener of an event
|
|
212
|
+
```
|
|
213
|
+
|
|
214
|
+
| Event | When | Payload (besides `requestId`, `correlationId`, `method`, `url`, `config`, `metadata`, `timestamp`) |
|
|
215
|
+
| ----------------- | ---------------------------------------------------------------------------- | -------------------------------------------------------------------------------------- |
|
|
216
|
+
| `request` | Once per logical request, after request interceptors, before the breaker | none |
|
|
217
|
+
| `retry` | Before each backoff sleep | `attempt` (the one that failed), `delayMs`, `error?`, `status?` |
|
|
218
|
+
| `timeout` | An attempt hit `timeout` (it may be retried), or `totalTimeout` ended the request | `kind` (`'attempt'` / `'total'`), `attempt`, `timeoutMs`, `error` |
|
|
219
|
+
| `response` | Final success, before response interceptors | `response`, `status`, `attempts`, `durationMs`, `responseTimeMs` |
|
|
220
|
+
| `error` | Final failure, cancellations excluded | `error`, `code?`, `status?`, `attempts`, `durationMs` |
|
|
221
|
+
| `canceled` | The request was canceled (`signal` or `CancelToken`) | `error`, `attempts`, `durationMs` |
|
|
222
|
+
| `circuitOpen` | A breaker opened | `key`, `from`, `to`, `timestamp` only |
|
|
223
|
+
| `circuitHalfOpen` | A breaker moved to half-open (lazily, when the next request arrives) | same |
|
|
224
|
+
| `circuitClose` | A breaker closed | same |
|
|
225
|
+
|
|
226
|
+
- Payloads are typed (`ExiosEventMap`) and are built only when the event has a listener, so unused events cost nothing.
|
|
227
|
+
- Listeners run synchronously. A listener that throws is reported with `console.error` and never affects the request or other listeners.
|
|
228
|
+
- Listeners belong to one instance. `create()` does not copy them, just as it does not copy interceptors.
|
|
229
|
+
- A request rejected by a request interceptor never dispatches, so it emits no events.
|
|
230
|
+
- `retry.onRetry` and `breaker.onStateChange` keep working as before, and run before the events.
|
|
231
|
+
- Events describe network requests: a cache hit or a deduplicated caller makes none, so it emits none.
|
|
232
|
+
|
|
233
|
+
## Request management
|
|
234
|
+
|
|
235
|
+
All of these are **off by default**. Turning them on never changes retry or breaker behaviour.
|
|
236
|
+
|
|
237
|
+
### Total timeout
|
|
238
|
+
|
|
239
|
+
`timeout` limits each attempt. `totalTimeout` limits the whole request: every attempt, retry and backoff sleep.
|
|
240
|
+
|
|
241
|
+
```js
|
|
242
|
+
api.get("/report", { timeout: 2000, totalTimeout: 10000 });
|
|
243
|
+
// at most 10 s in total, however many retries are left
|
|
244
|
+
```
|
|
245
|
+
|
|
246
|
+
When it fires, the request rejects with `code: 'ECONNABORTED'` (`'ETIMEDOUT'` with `transitional.clarifyTimeoutError`) and the message `total timeout of 10000ms exceeded`. The `timeout` event fires with `kind: 'total'`. Like a cancellation, it does **not** count as a circuit breaker failure. Your own `signal` / `CancelToken` still produce a `CanceledError`. For `responseType: 'stream'` the limit ends when the headers arrive.
|
|
247
|
+
|
|
248
|
+
### Request metadata
|
|
249
|
+
|
|
250
|
+
`metadata` is free-form data that travels with a request. It is readable in interceptors, adapters and every event (`event.metadata`), and it is never sent to the server. Instance and request metadata are merged.
|
|
251
|
+
|
|
252
|
+
```js
|
|
253
|
+
const api = exios.create({ metadata: { feature: "checkout" } });
|
|
254
|
+
api.on("error", (e) => report(e.metadata?.feature, e.code));
|
|
255
|
+
api.get("/cart", { metadata: { step: "load" } }); // metadata: { feature: "checkout", step: "load" }
|
|
256
|
+
```
|
|
257
|
+
|
|
258
|
+
### Request deduplication
|
|
259
|
+
|
|
260
|
+
With `dedupe: true`, identical requests made while one is already in flight share a single network request.
|
|
261
|
+
|
|
262
|
+
```js
|
|
263
|
+
const api = exios.create({ baseURL: "https://api.example.com", dedupe: true });
|
|
264
|
+
const [a, b] = await Promise.all([api.get("/me"), api.get("/me")]); // one network request
|
|
265
|
+
b.meta.deduped; // true
|
|
266
|
+
```
|
|
267
|
+
|
|
268
|
+
- **What counts as identical:** same method, URL, params, headers, `auth` and `responseType`. Requests with different `Authorization` headers are never shared.
|
|
269
|
+
- **Methods:** only `GET` and `HEAD` are deduplicated, unless you list others in `dedupe: { methods: [...] }`. Requests with a body, and `responseType: 'stream'`, are never shared.
|
|
270
|
+
- **Cancellation:** each caller keeps its own `signal` / `CancelToken`. A caller that aborts is rejected at once, and the others still get the response. The network request is aborted only when **every** caller has aborted.
|
|
271
|
+
- **Separate results:** every caller gets its own response object, with its own `requestId` and a cloned copy of `data`, and runs its own response interceptors. Errors are passed to every caller.
|
|
272
|
+
- **Custom key:** `dedupe: { key: (config) => string | undefined }`. Return `undefined` to skip deduplication for a request.
|
|
273
|
+
- **Events:** lifecycle events and request interceptors see the first caller's request. `onDownloadProgress` / `onUploadProgress` fire only for that caller.
|
|
274
|
+
|
|
275
|
+
### Response caching
|
|
276
|
+
|
|
277
|
+
```js
|
|
278
|
+
const api = exios.create({
|
|
279
|
+
baseURL: "https://api.example.com",
|
|
280
|
+
cache: { ttl: 30_000 }, // or cache: true (ttl 60 s)
|
|
281
|
+
});
|
|
282
|
+
await api.get("/products"); // network
|
|
283
|
+
const res = await api.get("/products"); // from memory
|
|
284
|
+
res.meta.cached; // true
|
|
285
|
+
```
|
|
286
|
+
|
|
287
|
+
| Option | Default | Meaning |
|
|
288
|
+
| --------------------- | ---------------------------- | ----------------------------------------------------------------------------------------- |
|
|
289
|
+
| `ttl` | `60000` | Time to live in ms |
|
|
290
|
+
| `methods` | `['get', 'head']` | Methods whose responses may be cached |
|
|
291
|
+
| `respectCacheControl` | `true` | Honour `no-store`, `no-cache` and `max-age` on requests and responses |
|
|
292
|
+
| `key` | method + URL + params + headers hash | `(config) => string \| undefined`; `undefined` skips the cache for that request |
|
|
293
|
+
| `provider` | built-in memory LRU (100 entries) | Any object with `get` / `set` / `delete` / `clear` (sync or async), plus optional `keys` |
|
|
294
|
+
|
|
295
|
+
- **What is stored:** only 2xx responses. Errors, request bodies, streams and data that `structuredClone` can't copy are never cached.
|
|
296
|
+
- **Isolated data:** every response read from the cache gets its own copy of `data`, so changing it can't affect the cache or other callers.
|
|
297
|
+
- **Credentials:** the key includes a hash of the request headers and `auth`, so requests made with different credentials never share an entry. Secrets never appear in the key text.
|
|
298
|
+
- **Cache-Control:** a response with `no-store` or `no-cache` is not stored, and `max-age` shortens the `ttl`. A request sent with `Cache-Control: no-cache` skips the read and refreshes the entry; `no-store` skips both the read and the write.
|
|
299
|
+
- **Per request:** `cache: false` bypasses the cache; `cache: { ttl: 5000 }` overrides the ttl.
|
|
300
|
+
- **Failures:** a cache provider that throws never fails the request. The error is reported with `console.error`, and the request goes to the network.
|
|
301
|
+
- **Instances:** each instance (including each `create()` child) has its own memory cache, unless you pass a `provider`.
|
|
302
|
+
|
|
303
|
+
Managing the cache:
|
|
304
|
+
|
|
305
|
+
```js
|
|
306
|
+
await api.cache.invalidate("/products"); // /products, /products?page=2, /products/42 (not /products-old)
|
|
307
|
+
await api.cache.invalidate(/\/users\//); // RegExp tested against keys
|
|
308
|
+
await api.cache.invalidate((key) => key.startsWith("GET")); // predicate; resolves with the number removed
|
|
309
|
+
await api.cache.delete(api.cache.key({ url: "/products" })); // one entry
|
|
310
|
+
await api.cache.clear();
|
|
311
|
+
```
|
|
312
|
+
|
|
313
|
+
A custom provider, for example backed by `localStorage` or Redis:
|
|
314
|
+
|
|
315
|
+
```js
|
|
316
|
+
import { MemoryCache } from "@indra211/exios";
|
|
317
|
+
|
|
318
|
+
const api = exios.create({ cache: { provider: new MemoryCache({ maxEntries: 500 }) } });
|
|
319
|
+
// or: { get(key), set(key, entry), delete(key), clear(), keys?() }; entries are plain objects
|
|
320
|
+
// { status, statusText, headers, data, storedAt, expiresAt }
|
|
321
|
+
```
|
|
322
|
+
|
|
323
|
+
`invalidate()` needs a provider with `keys()`; without one it rejects with `ERR_NOT_SUPPORT`.
|
|
324
|
+
|
|
159
325
|
## Behavior rules
|
|
160
326
|
|
|
161
327
|
These are deliberate and tested.
|
|
@@ -183,6 +349,22 @@ Also:
|
|
|
183
349
|
- `redirect: 'manual' | 'error'` and `fetchOptions` on the `xhr` adapter (browsers' XHR always follows redirects); use `adapter: 'fetch'` when you need them.
|
|
184
350
|
- Distributed or persisted breaker state.
|
|
185
351
|
|
|
352
|
+
## Development: browser tests
|
|
353
|
+
|
|
354
|
+
| Script | Browsers |
|
|
355
|
+
| --- | --- |
|
|
356
|
+
| `npm run test:browser` | Chromium, WebKit (Playwright engines, headless) |
|
|
357
|
+
| `npm run test:browser:all` | Chromium, Firefox, WebKit (used in CI) |
|
|
358
|
+
| `npm run test:browser:edge` | the real Microsoft Edge app installed on your machine |
|
|
359
|
+
| `npm run test:browser:safari` | the real Safari app: **experimental, not working yet** (see below) |
|
|
360
|
+
| `npm run test:browser:mac` | Chromium, WebKit, Firefox and real Edge |
|
|
361
|
+
|
|
362
|
+
Real Safari is driven by macOS's built-in `safaridriver`. It does not work yet: Safari opens, but the test page never connects back to Vitest. WebKit (Safari's engine) is covered by the other scripts. One-time setup if you want to work on it:
|
|
363
|
+
|
|
364
|
+
1. In Safari: Settings > Advanced > tick "Show features for web developers".
|
|
365
|
+
2. Settings > Developer > tick "Allow remote automation".
|
|
366
|
+
3. In a terminal: `safaridriver --enable` (asks for your password).
|
|
367
|
+
|
|
186
368
|
## Author
|
|
187
369
|
|
|
188
370
|
Questions, bugs or ideas: [work.indrasena@outlook.com](mailto:work.indrasena@outlook.com)
|