vigor-fetch 4.0.11 → 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/README.md +408 -32
- package/dist/index.cjs +1071 -359
- package/dist/index.d.cts +3578 -1539
- package/dist/index.d.ts +3578 -1539
- package/dist/index.js +1051 -359
- package/package.json +4 -3
package/README.md
CHANGED
|
@@ -14,6 +14,7 @@ Vigor gives you an immutable, chainable API for building robust network logic: r
|
|
|
14
14
|
- 🔌 **Content-aware parsing** — auto-detects `Content-Type`, with a sniffing fallback and custom strategies
|
|
15
15
|
- ⚡ **Bounded concurrency runner** — run many tasks with a concurrency cap, batch-level hooks, and per-task hooks
|
|
16
16
|
- 🪝 **Two middleware modes** — `"fluent"` (return a value) or `"intercept"` (get an explicit control API)
|
|
17
|
+
- 🕒 **Execution timeline** — with `settings.debug`, `requestVerbose()` returns a typed record of every step a request went through: each attempt's response, every retry decision and why, which middleware ran or threw, and how it ended — nested engines included
|
|
17
18
|
- 🧬 **Type-level result override** — `.cast<T>()` on every module, when you know better than inference does
|
|
18
19
|
- 🧠 **TypeScript-first** — config shape is inferred and carried through the whole chain
|
|
19
20
|
|
|
@@ -81,6 +82,7 @@ const results = await vigor
|
|
|
81
82
|
() => fetch("/api/2")
|
|
82
83
|
)
|
|
83
84
|
.request();
|
|
85
|
+
// -> [{ success: true, data: Response, error: null }, { success: false, data: null, error: TypeError }]
|
|
84
86
|
```
|
|
85
87
|
|
|
86
88
|
---
|
|
@@ -94,13 +96,17 @@ vigor.parse(request|response?) // -> VigorParse, target pre-set if given
|
|
|
94
96
|
vigor.all(...tasks) // -> VigorAll, target pre-set if any tasks given
|
|
95
97
|
vigor.use(plugin, options?)
|
|
96
98
|
vigor.builders // direct access to each module's sub-builders
|
|
99
|
+
vigor.guards // each module's error type guard
|
|
97
100
|
```
|
|
98
101
|
|
|
99
102
|
Every module follows the same shape: an **immutable builder** with `.settings()`, `.middlewares()`, a terminal `.request()` / `.requestVerbose()` pair, and a `.cast<T>()` escape hatch for the result type.
|
|
100
103
|
|
|
101
104
|
- `.request()` returns the result directly and **throws** on final failure.
|
|
102
|
-
- `.requestVerbose()` never throws — it returns `{ success: true, data, error: null }` or `{ success: false, data: null, error }`.
|
|
105
|
+
- `.requestVerbose()` never throws — it returns `{ success: true, data, error: null, timeline }` or `{ success: false, data: null, error, timeline }`. `timeline` is recorded only with `settings.debug` on. See [Timeline](#timeline). `vigor.fetch`'s envelope also carries `status` and `response` — see [Status and response](#status-and-response).
|
|
103
106
|
- `.cast<T>()` overrides the inferred result type with `T`. It can be called before or after any other configuration method — whichever `.cast<T>()` call happens *last* in the chain wins, and it always takes priority over the naturally-inferred type.
|
|
107
|
+
- The result type includes what `settings.default` returns, since a fallback can become the result.
|
|
108
|
+
- `.request<R>()` / `.requestVerbose<R>()` take an optional type argument meaning "ignore the inference, it's `R`" — taken as-is, unchecked, for that call only. (`.cast<T>()` does the same on the builder, so it carries through `middlewares` too.)
|
|
109
|
+
- To name the inferred result type itself, use `VigorResultOf<typeof builder>` — `ReturnType<typeof builder.request>` can't see it, since `R` is a free override.
|
|
104
110
|
|
|
105
111
|
### `vigor.builders`
|
|
106
112
|
|
|
@@ -128,6 +134,17 @@ vigor.builders.all.middlewares() // -> VigorAllPolicyMiddlewares
|
|
|
128
134
|
|
|
129
135
|
This is equivalent to `new VigorFetchPolicySettings()` etc., just namespaced under `vigor` for discoverability.
|
|
130
136
|
|
|
137
|
+
### `vigor.guards`
|
|
138
|
+
|
|
139
|
+
Each module's error type guard, namespaced the same way (see [typed errors](#typed-errors)):
|
|
140
|
+
|
|
141
|
+
```ts
|
|
142
|
+
vigor.guards.retry(err) // same as isVigorRetryError(err)
|
|
143
|
+
vigor.guards.parse(err) // isVigorParseError
|
|
144
|
+
vigor.guards.fetch(err) // isVigorFetchError
|
|
145
|
+
vigor.guards.all(err) // isVigorAllError
|
|
146
|
+
```
|
|
147
|
+
|
|
131
148
|
---
|
|
132
149
|
|
|
133
150
|
## `vigor.fetch`
|
|
@@ -143,11 +160,13 @@ This is equivalent to `new VigorFetchPolicySettings()` etc., just namespaced und
|
|
|
143
160
|
| `hash(str)` | Sets the URL fragment, replacing any previous value |
|
|
144
161
|
| `headers(mode, obj)` | Sets headers. `mode`: `"overwrite"` (discard previous) or `"merge"` (`Object.assign`-style) |
|
|
145
162
|
| `body(mode, obj)` | Sets the body. `"overwrite"` replaces it entirely; `"merge"` shallow-merges when both old and new body are plain objects, otherwise replaces |
|
|
146
|
-
| `options(mode, obj)` | Sets extra native `RequestInit` fields other than `method`/`headers`/`body`/`signal` (e.g. `credentials`, `mode`, `cache`) |
|
|
163
|
+
| `options(mode, obj)` | Sets extra native `RequestInit` fields other than `method`/`headers`/`body`/`signal` (e.g. `credentials`, `mode`, `cache`). `"merge"` shallow-merges onto the previous options |
|
|
147
164
|
| `settings(fn \| config)` | Configures fetch-level settings (below) |
|
|
148
165
|
| `middlewares(fn \| config)` | Configures the fetch middleware pipeline (below) |
|
|
149
|
-
| `retry(fn \| config \| VigorRetry)` | Configures the **internal retry engine** used to send the request |
|
|
150
|
-
| `parse(fn \| config \| VigorParse)` | Configures the **internal parse engine** used to interpret the request or response |
|
|
166
|
+
| `retry(fn \| config \| VigorRetry)` | Configures the **internal retry engine** used to send the request. Replaces the previous engine config; a config object is applied on top of the retry defaults |
|
|
167
|
+
| `parse(fn \| config \| VigorParse)` | Configures the **internal parse engine** used to interpret the request or response. Replaces the previous engine config; a config object is applied on top of the parse defaults. Its result type (`.cast<T>()`, `raw`, middlewares, `default`) becomes the request's result type |
|
|
168
|
+
| `apiMap<M>()` | Attaches a type-level API map: the matched route's `response` becomes the result type (see [apiMap / route](#apimap--route)) |
|
|
169
|
+
| `route(key, params?)` | Sets method and path from an API map route, filling its `:name` segments |
|
|
151
170
|
| `cast<T>()` | Overrides the inferred result type with `T` |
|
|
152
171
|
| `request()` | Executes and returns the parsed result, throwing on failure |
|
|
153
172
|
| `requestVerbose()` | Executes and returns `{ success, data, error }` |
|
|
@@ -166,6 +185,100 @@ vigor.fetch("https://api.example.com/", "/api")
|
|
|
166
185
|
|
|
167
186
|
`origin()` only accepts one argument — pass origin + first path segments as separate calls, or fold extra segments into `path()`.
|
|
168
187
|
|
|
188
|
+
Path segments are percent-encoded, so values like `"a b"` or `"x?y"` can never leak into the query or fragment. A `/` inside a segment still separates path levels: `.path("v1/users", "a b")` → `/v1/users/a%20b`. Pass segments **unencoded** — an already-encoded `%20` would be encoded again.
|
|
189
|
+
|
|
190
|
+
`.` and `..` segments still work as relative steps, but by default (`settings.confinePath`) never out of the origin: with `vigor.fetch("https://api.example.com/api/v1")`, `.path("users", "..", "posts")` goes to `/api/v1/posts`, while `.path("users", "../../../internal")` — say, a user-supplied id — fails with `VigorFetchError("PATH_ESCAPED")` without sending anything. The origin's path is the boundary (`/api/v1` allows `/api/v1/...`, not `/api/v1x`). `.settings(s => s.confinePath(false))` turns the check off.
|
|
191
|
+
|
|
192
|
+
### apiMap / route
|
|
193
|
+
|
|
194
|
+
Describe your API once as a type, and every request built from it gets its route's response type — no `.cast<T>()` per call:
|
|
195
|
+
|
|
196
|
+
```ts
|
|
197
|
+
type Api = {
|
|
198
|
+
"GET /users": { response: User[] }
|
|
199
|
+
"POST /users": { response: User }
|
|
200
|
+
"GET /users/me": { response: Me }
|
|
201
|
+
"GET /users/:id": { response: User }
|
|
202
|
+
"DELETE /users/:id": { response: null }
|
|
203
|
+
}
|
|
204
|
+
|
|
205
|
+
const api = vigor.fetch("https://api.example.com").apiMap<Api>()
|
|
206
|
+
|
|
207
|
+
await api.path("users").request() // User[]
|
|
208
|
+
await api.path("users", id).request() // User
|
|
209
|
+
await api.path("users", "me").request() // Me
|
|
210
|
+
await api.path("users").body("overwrite", newUser).request() // User (POST: a body is set)
|
|
211
|
+
await api.path("users", id).method("DELETE").request() // null
|
|
212
|
+
await api.path("nope").request() // unknown (no route matched)
|
|
213
|
+
|
|
214
|
+
await api.route("GET /users/:id", { id: 1 }).request() // User — key autocompletes
|
|
215
|
+
```
|
|
216
|
+
|
|
217
|
+
- Keys are `"<METHOD> /<path>"`. A `:name` segment matches any one segment; a static segment needs that exact literal. When several routes match, the most specific wins segment by segment from the left (`/users/me` beats `/users/:id`), like a router.
|
|
218
|
+
- The request's method is the one set with `.method()`, or — as at runtime — `POST` with a body and `GET` without.
|
|
219
|
+
- Path arguments are matched the way the URL is built: `.path("users/1")` is two segments, `null`/`undefined` are dropped, numbers become their digits. A non-literal argument (`id: string`) only matches a `:name` segment.
|
|
220
|
+
- Routes are relative to the path set before `.apiMap()`, so a shared prefix goes first: `vigor.fetch(origin).path("v1").apiMap<Api>()`. The origin's own pathname isn't part of the match.
|
|
221
|
+
- No match falls back to the parse engine's type (`unknown` by default). `.cast<T>()` still wins over the map, and a `raw` parse still gives the `Response`.
|
|
222
|
+
- `route(key, params)` sets the method and appends the route's path with `:name` segments filled from `params` (encoded like any path segment). Unknown keys, missing or extra params, and a `GET`/`HEAD` route on a request that already has a body are type errors.
|
|
223
|
+
- It's purely a type: `apiMap()` changes nothing at runtime, and responses aren't validated.
|
|
224
|
+
|
|
225
|
+
#### Route descriptions
|
|
226
|
+
|
|
227
|
+
A route can describe more than its response. Every key is optional:
|
|
228
|
+
|
|
229
|
+
```ts
|
|
230
|
+
type Api = {
|
|
231
|
+
"GET /users/:id": {
|
|
232
|
+
params: { id: number } // .route()'s param types
|
|
233
|
+
responses: {
|
|
234
|
+
200: User
|
|
235
|
+
304: null
|
|
236
|
+
404: { error: "not_found" }
|
|
237
|
+
"4xx": ApiError // every other 4xx
|
|
238
|
+
"5xx": { message: string }
|
|
239
|
+
}
|
|
240
|
+
}
|
|
241
|
+
"POST /users": {
|
|
242
|
+
body: { name: string } // the body the request must carry
|
|
243
|
+
responses: { 201: User, 422: { fields: Record<string, string> } }
|
|
244
|
+
}
|
|
245
|
+
"GET /search": {
|
|
246
|
+
query: { q: string, page?: number } // what .query() must add up to
|
|
247
|
+
response: User[] // shorthand for responses: { "2xx": User[] }
|
|
248
|
+
}
|
|
249
|
+
}
|
|
250
|
+
```
|
|
251
|
+
|
|
252
|
+
- **`responses`** maps statuses to the parsed body: an exact status (`404`, or `"404"`) or a whole class (`"2xx"`–`"5xx"`) for its statuses not listed on their own. The **success** statuses — `2xx` and `304`, as at runtime — are what the request resolves to: `request()` gives their union (`User | null` above). The others type [`FETCH_FAILED`](#typed-errors)'s `data.parsed`.
|
|
253
|
+
- **`response`** is shorthand for `responses: { "2xx": ... }`. Undeclared success statuses aren't modeled, so a route that declares none falls back to the parse engine's type.
|
|
254
|
+
- **`params`** types `.route()`'s values: `api.route("GET /users/:id", { id: "1" })` is an error above.
|
|
255
|
+
- **`body`** and **`query`** are checked **when the request is sent**, so the order you build it in doesn't matter: `request()`/`requestVerbose()` don't compile when the body doesn't match (or is missing — unless the declared type allows `undefined`), or when the `.query()` objects, added together, miss a key, have an unknown one, or a value of the wrong type. A route without `body`/`query` accepts anything there. The compiler error names the route and the problem:
|
|
256
|
+
|
|
257
|
+
```
|
|
258
|
+
The 'this' context of type 'VigorFetch<...>' is not assignable to method's 'this' of type
|
|
259
|
+
'VigorApiRequestIssue<"GET /search", "unknown query key \"pgae\"", { q: string; page?: number }, { readonly q: "x"; readonly pgae: 1 }>'
|
|
260
|
+
```
|
|
261
|
+
|
|
262
|
+
The check is on `this`, so it's only computed where `request()`/`requestVerbose()` is called. One consequence: calling them on a `VigorFetch<T>` with a still-generic `T` (inside a generic helper) doesn't compile — take a concrete builder, or `VigorFetch<any>`.
|
|
263
|
+
|
|
264
|
+
#### Status and response
|
|
265
|
+
|
|
266
|
+
`vigor.fetch`'s `requestVerbose()` envelope carries the `status` and `response` the result was parsed from:
|
|
267
|
+
|
|
268
|
+
```ts
|
|
269
|
+
const res = await api.route("GET /users/:id", { id: 1 }).requestVerbose()
|
|
270
|
+
if (res.success) {
|
|
271
|
+
res.status // 200 | 304
|
|
272
|
+
res.response // Response
|
|
273
|
+
if (res.status === 200) res.data // User
|
|
274
|
+
else res.data // null
|
|
275
|
+
}
|
|
276
|
+
```
|
|
277
|
+
|
|
278
|
+
- With an API map, there's one success member per declared status, each with that status's data run through the middlewares — so narrowing `status` narrows `data`. Without one, `status` is a `number`.
|
|
279
|
+
- A result recovered from a failure — by `onError`'s `setResult` or `settings.default` — has no response: `status` and `response` are `null` (those members only exist when one of the two is set). On a failure they're `null` too; the failed response is on the error (`FETCH_FAILED`'s `data`).
|
|
280
|
+
- `.cast<T>()` and `requestVerbose<R>()` replace every success's `data`, but keep `status` — and the failure types.
|
|
281
|
+
|
|
169
282
|
### headers / body / options
|
|
170
283
|
|
|
171
284
|
```ts
|
|
@@ -175,13 +288,15 @@ vigor.fetch("/api")
|
|
|
175
288
|
.options("merge", { credentials: "include" })
|
|
176
289
|
```
|
|
177
290
|
|
|
178
|
-
Body is auto-normalized based on type (string, `Blob`, `ArrayBuffer`, `URLSearchParams`, `FormData`, or plain object → JSON), and a matching `Content-Type` header is set automatically unless you've already set one via `.headers()`.
|
|
291
|
+
Body is auto-normalized based on type (string, `Blob`, `ArrayBuffer`/typed array/`DataView`, `ReadableStream`, `URLSearchParams`, `FormData`, or plain object → JSON), and a matching `Content-Type` header is set automatically unless you've already set one via `.headers()` (header names are compared case-insensitively). `body("overwrite", null)` removes a previously set body. A body on a `GET`/`HEAD` request fails immediately with `VigorFetchError("BODY_NOT_ALLOWED")` instead of being sent — and when the method and body are set through the builder, it's already a type error (`.method("GET").body(...)` or `.body(...).method("GET")`).
|
|
292
|
+
|
|
293
|
+
> A `ReadableStream` body can only be sent once, so a request with a stream body is never retried (its first failure is final), and a restarted one will fail — use a replayable body type if you rely on retries.
|
|
179
294
|
|
|
180
295
|
### settings
|
|
181
296
|
|
|
182
297
|
```ts
|
|
183
298
|
.settings(s => s
|
|
184
|
-
.unretryStatus(400, 401, 403, 404,
|
|
299
|
+
.unretryStatus(400, 401, 403, 404, 409, 422)
|
|
185
300
|
.retryHeaders("retry-after", "x-ratelimit-reset")
|
|
186
301
|
.maxRestarts(3)
|
|
187
302
|
.default(ctx => ({ fallback: true }))
|
|
@@ -190,12 +305,41 @@ Body is auto-normalized based on type (string, `Blob`, `ArrayBuffer`, `URLSearch
|
|
|
190
305
|
|
|
191
306
|
| Method | Description | Default |
|
|
192
307
|
|---|---|---|
|
|
193
|
-
| `retryHeaders(...strs)` | Response headers checked for a `429` retry delay | `["retry-after", "ratelimit-reset", "x-ratelimit-reset", "x-retry-after", "x-amz-retry-after"
|
|
194
|
-
| `unretryStatus(...nums)` | HTTP status codes that are never retried, regardless of the retry engine's attempt budget | `
|
|
308
|
+
| `retryHeaders(...strs)` | Response headers checked for a `429`/`503` retry delay | `["retry-after", "ratelimit-reset", "x-ratelimit-reset", "x-retry-after", "x-amz-retry-after"]` |
|
|
309
|
+
| `unretryStatus(...nums)` | HTTP status codes that are never retried, regardless of the retry engine's attempt budget | every `4xx` except `408`, `421`, `423`, `425`, `429`, plus `501`, `505`, `506`, `508`, `510`, `511` (see below) |
|
|
310
|
+
| `maxRetryAfter(num)` | Upper bound (ms) on a server-suggested retry delay from `retryHeaders`; longer values are clamped | `300000` (5 min) |
|
|
311
|
+
| `redirect(bool)` | On a redirected response, navigates the page via `window.location.href` (see below) | `false` |
|
|
312
|
+
| `confinePath(bool)` | Keeps the request URL inside its origin — same domain, within the origin's path; a request that would leave it (e.g. a `".."` segment) fails with `PATH_ESCAPED` before it's sent | `true` |
|
|
195
313
|
| `maxRestarts(num)` | Max number of full pipeline restarts (see `onError` below) | `3` |
|
|
196
314
|
| `default(fn)` | Fallback value/factory used only if the request ultimately fails and no restart/override happened | throws |
|
|
315
|
+
| `debug(bool)` | Records `requestVerbose()`'s [timeline](#timeline) (the nested retry/parse engines' too) | `false` |
|
|
316
|
+
|
|
317
|
+
The default `unretryStatus` covers the statuses a retry of the same request can't change: `400`–`407`, `409`–`417`, `422`, `424`, `426`, `428`, `431`, `451`, `501`, `505`, `506`, `508`, `510`, `511`. These stay retryable: `408 Request Timeout`, `421 Misdirected Request`, `423 Locked`, `425 Too Early`, `429 Too Many Requests`, and transient `5xx` (`500`, `502`, `503`, `504`, `507`).
|
|
197
318
|
|
|
198
|
-
|
|
319
|
+
`retryHeaders` and `unretryStatus` **replace** the whole list (in both the builder and the config-object form), so you can also remove defaults — e.g. `.settings({ unretryStatus: [] })` makes every failure status retryable. To extend the defaults instead, spread `VigorFetchPolicySettingsBase.unretryStatus`.
|
|
320
|
+
|
|
321
|
+
On any non-`unretryStatus` failure response, the internal retry engine retries per its own `settings`/`algorithms` (defaults: 5 attempts, 20s timeout, exponential-ish backoff jitter — see `vigor.retry` below). On a `429` or `503`, Vigor reads `retryHeaders` off the response and uses the first usable value as the next delay automatically. Delta seconds (`Retry-After: 120`), Unix epoch seconds/milliseconds (`X-RateLimit-Reset: 1735689600`), and HTTP dates are all understood. The delay is clamped to `maxRetryAfter`.
|
|
322
|
+
|
|
323
|
+
The whole response body is read within the attempt, so the retry engine's per-attempt `timeout` also covers a body that stalls mid-transfer, and a body that fails to arrive is retried. (With the parse engine's `raw` setting, the body is left unread for you to stream.)
|
|
324
|
+
|
|
325
|
+
### redirect
|
|
326
|
+
|
|
327
|
+
With `settings.redirect(true)`, a redirected response navigates the browser to its target:
|
|
328
|
+
|
|
329
|
+
```ts
|
|
330
|
+
await vigor
|
|
331
|
+
.fetch("/api/session")
|
|
332
|
+
.settings({ redirect: true })
|
|
333
|
+
.request();
|
|
334
|
+
// 302 Location: /login (followed by fetch) -> window.location.href = "https://app.example.com/login"
|
|
335
|
+
```
|
|
336
|
+
|
|
337
|
+
- With the native default `redirect: "follow"`, the target is the final URL `fetch` landed on (`response.redirected`).
|
|
338
|
+
- With `.options("merge", { redirect: "manual" })` in a runtime where the `3xx` is readable, the target is its `Location` header, resolved against the responding URL.
|
|
339
|
+
- Navigation isn't instant, so the call still settles: it fails with `VigorFetchError("REDIRECTED")`, whose `data` holds `{ url, status, response }`. That attempt is never retried.
|
|
340
|
+
- **Without `window.location` (Node, workers, SSR) it does nothing and behaves exactly like `redirect(false)`.**
|
|
341
|
+
|
|
342
|
+
Independently of this setting, a `3xx` (or browser `opaqueredirect`) that reaches Vigor because you chose `redirect: "manual"` fails with `FETCH_FAILED` and is **not retried**, since a retry would get the same redirect. `304 Not Modified` is treated as a result, not a failure (it parses to `null`).
|
|
199
343
|
|
|
200
344
|
### interceptors (`middlewares`)
|
|
201
345
|
|
|
@@ -223,6 +367,10 @@ Every stage takes a mode as the first argument: `"fluent"` (return a plain value
|
|
|
223
367
|
|
|
224
368
|
Fluent-mode signatures: `before`/`after` take `(ctx) => void`, `onResult` takes `(res) => newRes`, `onError` takes `(err) => void`.
|
|
225
369
|
|
|
370
|
+
In `before`, `ctx.options` already holds the built request (`method`, `headers`, `body`, extra options), so a fluent middleware can also edit it directly — e.g. `ctx.options.headers["X-Trace"] = id`.
|
|
371
|
+
|
|
372
|
+
An intercept middleware that returns nothing keeps the current context (this applies to every module).
|
|
373
|
+
|
|
226
374
|
`onError` → `proceedRestart()` re-runs the **entire** fetch pipeline from scratch (up to `settings.maxRestarts` times) — this is separate from, and on top of, the internal retry engine's per-attempt retries.
|
|
227
375
|
|
|
228
376
|
### retry / parse (nested engines)
|
|
@@ -235,7 +383,7 @@ const data = await vigor
|
|
|
235
383
|
.request();
|
|
236
384
|
```
|
|
237
385
|
|
|
238
|
-
Both accept a config object, a builder callback, or an already-built `VigorRetry`/`VigorParse` instance. The target
|
|
386
|
+
Both accept a config object, a builder callback, or an already-built `VigorRetry`/`VigorParse` instance. The target you'd normally set with `.target()` is ignored here — fetch always supplies its own: the actual `fetch()` call for the retry engine, and the response for the parse engine (a `response.clone()` for the best-effort parse of a failed response's body, see `FETCH_FAILED`).
|
|
239
387
|
|
|
240
388
|
### cast
|
|
241
389
|
|
|
@@ -259,7 +407,7 @@ Without `.cast()`, the result type falls back to whatever your `parse()` config
|
|
|
259
407
|
| Method | Description |
|
|
260
408
|
|---|---|
|
|
261
409
|
| `target(fn)` | Sets the function to run: `(signal: AbortSignal) => any \| Promise<any>` |
|
|
262
|
-
| `abortSignals(...sigs)` | Attaches external `AbortSignal`s
|
|
410
|
+
| `abortSignals(...sigs)` | Attaches external `AbortSignal`s. Aborting cancels the current attempt (or the pending retry delay) and stops retrying |
|
|
263
411
|
| `settings(fn \| config)` | General retry settings (below) |
|
|
264
412
|
| `middlewares(fn \| config)` | Middleware pipeline (below) |
|
|
265
413
|
| `algorithms(fn)` | Selects and configures the delay algorithm (below) |
|
|
@@ -283,7 +431,8 @@ await vigor
|
|
|
283
431
|
| `default(fn)` | Fallback value/factory when the target ultimately fails | throws |
|
|
284
432
|
| `maxAttempts(num)` | Max attempts before giving up on this run | `5` |
|
|
285
433
|
| `maxRestarts(num)` | Max full pipeline restarts (see `onError`) | `3` |
|
|
286
|
-
| `timeout(ms)` | Timeout per individual attempt | `20000` |
|
|
434
|
+
| `timeout(ms)` | Timeout per individual attempt. `0` or `Infinity` disables it | `20000` |
|
|
435
|
+
| `debug(bool)` | Records `requestVerbose()`'s [timeline](#timeline) | `false` |
|
|
287
436
|
|
|
288
437
|
### algorithms
|
|
289
438
|
|
|
@@ -300,7 +449,7 @@ Delay algorithm is a **replace**, not merge — switching algorithms discards th
|
|
|
300
449
|
| `backoff(cfg?)` | `initial` (`0`), `multiplier` (`1.7`), `unit` (`1000`), `minDelay` (`500`), `maxDelay` (`10000`), `jitter` (`800`) |
|
|
301
450
|
| `custom(cfg?)` | `target: (attempt) => number` (required), `minDelay` (`500`), `maxDelay` (`10000`), `jitter` (`800`) |
|
|
302
451
|
|
|
303
|
-
Each computed delay is clamped to `[minDelay, maxDelay]`
|
|
452
|
+
Each computed delay is perturbed by `±jitter` ms. For `linear`/`backoff`/`custom`, the jitter fits inside `[minDelay, maxDelay]`: it's capped at half that range, and the delay is clamped to `[minDelay + jitter, maxDelay - jitter]` before jitter is applied, so the final delay never leaves `[minDelay, maxDelay]`. `constant` has no bounds; its interval is only raised to at least `jitter`, so the delay never goes negative.
|
|
304
453
|
|
|
305
454
|
```ts
|
|
306
455
|
.algorithms(a => a.custom({
|
|
@@ -327,7 +476,7 @@ Each computed delay is clamped to `[minDelay, maxDelay]` (except `constant`, whi
|
|
|
327
476
|
| Stage | Runs | Intercept API |
|
|
328
477
|
|---|---|---|
|
|
329
478
|
| `before` | Before each attempt | `throwError`, `abort`, `breakRetry` |
|
|
330
|
-
| `after` | After the target settles successfully | `
|
|
479
|
+
| `after` | After the target settles successfully | `throwError` |
|
|
331
480
|
| `onResult` | Right before returning the attempt's result | `setResult`, `throwError` |
|
|
332
481
|
| `retryIf` | After a failed attempt, decides whether to retry | `proceedRetry`, `cancelRetry` |
|
|
333
482
|
| `onRetry` | Right before the retry delay is awaited | `throwError`, `setDelay` |
|
|
@@ -361,10 +510,13 @@ There are two independent resilience layers here:
|
|
|
361
510
|
| `raw(bool)` | When `true`, skips parsing entirely and returns the raw `Request\|Response` object | `false` |
|
|
362
511
|
| `default(fn)` | Fallback value/factory when parsing ultimately fails | throws |
|
|
363
512
|
| `maxRestarts(num)` | Max full pipeline restarts | `3` |
|
|
513
|
+
| `debug(bool)` | Records `requestVerbose()`'s [timeline](#timeline) | `false` |
|
|
364
514
|
|
|
365
515
|
### strategies
|
|
366
516
|
|
|
367
|
-
Strategies form an ordered list that's tried in sequence until one succeeds
|
|
517
|
+
Strategies form an ordered list that's tried in sequence until one succeeds. If you never configure any, Vigor defaults to content-type detection.
|
|
518
|
+
|
|
519
|
+
The body is read **once**, into raw bytes, and every strategy parses those same bytes — nothing is cloned, and a failed strategy consumes nothing. Formats are decoded directly from the bytes (`JSON.parse`, `TextDecoder`, a hand-written `x-www-form-urlencoded` parser, ...); only `multipart/form-data` goes through the platform's `formData()`. The bytes are cached per `Request|Response` object, so a restart or a second parse of the same object reuses them.
|
|
368
520
|
|
|
369
521
|
```ts
|
|
370
522
|
.strategies(s => s.sniff())
|
|
@@ -372,15 +524,31 @@ Strategies form an ordered list that's tried in sequence until one succeeds (eac
|
|
|
372
524
|
|
|
373
525
|
| Method | Behavior |
|
|
374
526
|
|---|---|
|
|
375
|
-
| `contentType(replace?)` | Parses based on the request|response's `Content-Type` header (JSON / XML / form-urlencoded / octet-stream / image / audio / video / multipart / text) |
|
|
376
|
-
| `sniff(replace?)` | Tries
|
|
377
|
-
| `json(replace?)` | Always parses as JSON |
|
|
378
|
-
| `text(replace?)` | Always parses as text |
|
|
527
|
+
| `contentType(replace?)` | Parses based on the request|response's `Content-Type` header (JSON / XML / form-urlencoded / octet-stream / image / audio / video / multipart / text). An empty body (e.g. `204 No Content`) resolves to `null`; a body without `Content-Type` is read as text; a `Content-Type` it doesn't know (`application/pdf`, `application/zip`, `application/x-ndjson`, ...) becomes a `Blob` of that type, so a response that arrived fine never fails to parse just for its type |
|
|
528
|
+
| `sniff(replace?)` | Tries JSON, then form data (only for a form `Content-Type`), then text (only if the bytes are valid in the declared charset), then falls back to a `Blob` |
|
|
529
|
+
| `json(replace?)` | Always parses as JSON (always UTF-8, per the JSON spec) |
|
|
530
|
+
| `text(replace?)` | Always parses as text, in the `Content-Type`'s `charset` (UTF-8 when absent or unsupported) |
|
|
379
531
|
| `arrayBuffer(replace?)` | Always parses as `ArrayBuffer` |
|
|
380
532
|
| `blob(replace?)` | Always parses as `Blob` |
|
|
381
533
|
| `bytes(replace?)` | Always parses as `Uint8Array` |
|
|
382
|
-
| `formData(replace?)` | Always parses as `FormData` |
|
|
383
|
-
| `custom(func, replace?)` | Uses a custom `(
|
|
534
|
+
| `formData(replace?)` | Always parses as `FormData` (`x-www-form-urlencoded` or `multipart/form-data`; any other `Content-Type` fails) |
|
|
535
|
+
| `custom(func, replace?)` | Uses a custom `(body: VigorParseBody) => any \| Promise<any>` — see below |
|
|
536
|
+
|
|
537
|
+
A custom strategy receives the already-read body, not the `Request|Response`:
|
|
538
|
+
|
|
539
|
+
```ts
|
|
540
|
+
type VigorParseBody = {
|
|
541
|
+
bytes: Uint8Array // the raw body, empty when there is none
|
|
542
|
+
contentType: string | null // the Content-Type header
|
|
543
|
+
status: number | null // null when parsing a Request
|
|
544
|
+
headers: Headers
|
|
545
|
+
source: Request | Response // its body is already consumed
|
|
546
|
+
}
|
|
547
|
+
|
|
548
|
+
.strategies(s => s.custom(({ bytes }) => new TextDecoder().decode(bytes).split("\n")))
|
|
549
|
+
```
|
|
550
|
+
|
|
551
|
+
`readVigorParseBody(requestOrResponse)` is exported too, if you need the same read-once bytes outside a strategy.
|
|
384
552
|
|
|
385
553
|
By default each call **appends** to the chain (they concatenate, so you can layer fallbacks: e.g. `contentType()` then `sniff()` as a last resort). Pass `replace: true` as the trailing argument to replace the whole chain instead.
|
|
386
554
|
|
|
@@ -404,17 +572,20 @@ const data = await vigor
|
|
|
404
572
|
.request();
|
|
405
573
|
```
|
|
406
574
|
|
|
575
|
+
`proceedRestart()` re-parses the same cached bytes, so a restart never hits an already-consumed body.
|
|
576
|
+
|
|
407
577
|
---
|
|
408
578
|
|
|
409
579
|
## `vigor.all`
|
|
410
580
|
|
|
411
|
-
Runs a fixed list of
|
|
581
|
+
Runs a fixed list of tasks with bounded concurrency, `Promise.allSettled`-style — an individual task failing never makes the whole batch throw by itself.
|
|
412
582
|
|
|
413
583
|
### Methods
|
|
414
584
|
|
|
415
585
|
| Method | Description |
|
|
416
586
|
|---|---|
|
|
417
|
-
| `target(...funcs)` | Sets the task list — each is `() => unknown \| Promise<unknown>` |
|
|
587
|
+
| `target(...funcs)` | Sets the task list — each is `(signal: AbortSignal) => unknown \| Promise<unknown>` |
|
|
588
|
+
| `abortSignals(...signals)` | External signals that cancel the remaining tasks and fail the batch with the signal's reason |
|
|
418
589
|
| `settings(fn \| config)` | Concurrency settings (below) |
|
|
419
590
|
| `middlewares(fn \| config)` | Batch-level and per-task hooks (below) |
|
|
420
591
|
| `cast<T>()` | Overrides the inferred result type with `T` |
|
|
@@ -436,11 +607,38 @@ const results = await vigor
|
|
|
436
607
|
| Method | Description | Default |
|
|
437
608
|
|---|---|---|
|
|
438
609
|
| `concurrency(num)` | Max number of tasks running at once | `5` |
|
|
439
|
-
| `onlySuccess(bool)` | When `true`,
|
|
610
|
+
| `onlySuccess(bool)` | When `true`, the result is just the successful tasks' values (a failed task not recovered by `onErrorEach` is left out) instead of one outcome per task | `false` |
|
|
611
|
+
| `timeout(ms)` | Per-task timeout. A task exceeding it fails with `VigorAllError("TIMED_OUT")` (recoverable via `onErrorEach`). `0` or `Infinity` disables it | disabled |
|
|
612
|
+
| `failFast(bool)` | When `true`, the first task failure not recovered by `onErrorEach` aborts the remaining tasks and makes the batch fail with that error | `false` |
|
|
613
|
+
| `debug(bool)` | Records `requestVerbose()`'s [timeline](#timeline) | `false` |
|
|
440
614
|
|
|
441
|
-
|
|
615
|
+
Each task receives an `AbortSignal` that fires on its timeout, on an external `abortSignals` abort, or when `failFast` stops the batch. Pass it along (e.g. to `fetch`) so in-flight work actually stops — a task that ignores it keeps running in the background, but its result is discarded.
|
|
442
616
|
|
|
443
|
-
|
|
617
|
+
```ts
|
|
618
|
+
const results = await vigor
|
|
619
|
+
.all(
|
|
620
|
+
(signal) => fetch("/api/1", { signal }),
|
|
621
|
+
(signal) => fetch("/api/2", { signal })
|
|
622
|
+
)
|
|
623
|
+
.abortSignals(controller.signal)
|
|
624
|
+
.settings(s => s.timeout(5000).failFast(true))
|
|
625
|
+
.request();
|
|
626
|
+
```
|
|
627
|
+
|
|
628
|
+
> Unlike `vigor.retry`/`vigor.fetch`/`vigor.parse`, `vigor.all` has no `default`/fallback setting and no batch-level `onError`. By default the batch only fails on an **empty** task list (`EMPTY_TARGET`), an external abort, a `failFast` stop, an `onErrorEach` hook throwing, or a batch-level `before`/`after`/`onResult` middleware throwing. Per-task failures are otherwise handled by `onErrorEach` (below).
|
|
629
|
+
|
|
630
|
+
**Result shape:** with `onlySuccess` off (the default), the result has **one outcome per task**, in order, shaped like `requestVerbose()`'s envelope — `{ success: true, data, error: null }` when the task returned (or `onErrorEach` recovered it), `{ success: false, data: null, error }` when it failed. So a thrown error can never pass for a returned value (and a task that *returns* an `Error` is a success):
|
|
631
|
+
|
|
632
|
+
```ts
|
|
633
|
+
const [user, posts] = await vigor.all(() => getUser(), () => getPosts()).request();
|
|
634
|
+
if (user.success) user.data; // what getUser returned
|
|
635
|
+
else if (isVigorAllError(user.error, "TIMED_OUT")) user.error.data.index;
|
|
636
|
+
else user.error; // whatever getUser threw
|
|
637
|
+
```
|
|
638
|
+
|
|
639
|
+
With `onlySuccess(true)`, it's just the successful tasks' values.
|
|
640
|
+
|
|
641
|
+
**Result typing:** given literal task functions, the default result is a **tuple** with each task's own type — `.target(() => 1 as const, () => "a")` infers `[VigorAllSettled<1>, VigorAllSettled<"a">]`, and narrowing a slot by `success` narrows `data`. With `onlySuccess(true)` the length is only known at runtime, so it's an array of the tasks' result types (`(1 | "a")[]`); a non-literal `boolean` gives the union of both shapes. `.cast<T>()` overrides either case.
|
|
444
642
|
|
|
445
643
|
### hooks (`middlewares`)
|
|
446
644
|
|
|
@@ -453,7 +651,9 @@ const results = await vigor
|
|
|
453
651
|
| `onResult(type, fn)` | Batch | Once, right before returning the final result | `setResult`, `throwError` (intercept mode) |
|
|
454
652
|
| `beforeEach(fn)` | Per-task | Before each individual task is invoked | — |
|
|
455
653
|
| `afterEach(fn)` | Per-task | After a task settles successfully | — |
|
|
456
|
-
| `onErrorEach(fn)` | Per-task | When an individual task throws | `setResult` |
|
|
654
|
+
| `onErrorEach(fn)` | Per-task | When an individual task throws (including `TIMED_OUT`) | `setResult` |
|
|
655
|
+
|
|
656
|
+
Per-task hooks receive a context with `index` (the task's position in `target`), `result`, `error`, and `flags.overridden`.
|
|
457
657
|
|
|
458
658
|
```ts
|
|
459
659
|
.middlewares(m => m
|
|
@@ -473,6 +673,86 @@ Batch-level fluent signatures: `before`/`after` take `(ctx) => void`, `onResult`
|
|
|
473
673
|
|
|
474
674
|
---
|
|
475
675
|
|
|
676
|
+
## Timeline
|
|
677
|
+
|
|
678
|
+
Every `requestVerbose()` result carries a `timeline`: an ordered list of everything the call went through, on success and on failure alike. Recording is **off by default** — turn it on with the `debug` setting, `.settings(s => s.debug(true))` or `.settings({ debug: true })` (every module has it). Without it, `timeline` is an empty array and no context snapshots are taken, so it costs nothing. It's created fresh for each call and can't be passed in; a restart keeps appending to the same list.
|
|
679
|
+
|
|
680
|
+
```ts
|
|
681
|
+
const res = await vigor.fetch("https://api.example.com/users").settings(s => s.debug(true)).requestVerbose();
|
|
682
|
+
|
|
683
|
+
for (const item of res.timeline) {
|
|
684
|
+
console.log(item.now, item.action, item.content);
|
|
685
|
+
}
|
|
686
|
+
```
|
|
687
|
+
|
|
688
|
+
Each item is `{ action, content, now, ctx }`. `now` is a `Date.now()` timestamp (a number, not a `Date`). `ctx` is a snapshot of the context at that moment: a deep copy, so later changes don't reach it, without `timeline` itself (`vigor.all`'s per-task actions snapshot that task's context instead). `action` and `content` are typed together, so narrowing by `action` narrows `content`.
|
|
689
|
+
|
|
690
|
+
The same list is also `ctx.timeline`, so middlewares can read what has happened so far. The types are exported as `VigorRetryTimeline`, `VigorParseTimeline`, `VigorFetchTimeline` and `VigorAllTimeline`.
|
|
691
|
+
|
|
692
|
+
### Shared events
|
|
693
|
+
|
|
694
|
+
| Action | Content |
|
|
695
|
+
|---|---|
|
|
696
|
+
| `PROCESS_HANDLING` | `{ type, data }` — the run's lifecycle steps (below) |
|
|
697
|
+
| `MIDDLEWARE_LOOP_STARTED` | `{ stage, middlewares }` |
|
|
698
|
+
| `MIDDLEWARE_RAN` | `{ stage, index, middleware, internal, took, threw, error }` — one middleware ran; `error` is what it threw when `threw` is `true` |
|
|
699
|
+
| `MIDDLEWARE_LOOP_ENDED` | `{ stage, middlewares, took }` |
|
|
700
|
+
| `MIDDLEWARE_API_CALLED` | `{ stage, index, middleware, internal, method, args }` — an intercept API call, e.g. `setDelay` |
|
|
701
|
+
| `REQUEST_END` | `{ success, outcome, took, restarts, error }` — always the last entry (see below) |
|
|
702
|
+
|
|
703
|
+
A stage with no middlewares records nothing. `took` is in milliseconds. `index` is the middleware's position in its stage, and `internal` is `true` for one Vigor added itself — e.g. the `after`/`retryIf`/`onRetry` middlewares `vigor.fetch` puts on its retry engine to judge responses — so you can tell them from yours.
|
|
704
|
+
|
|
705
|
+
`REQUEST_END` says how the call ended: `outcome` is `"result"` (the pipeline produced it), `"overridden"` (`onError` called `setResult`), `"default"` (`settings.default` produced it), or `"failed"`. `took` spans the whole call, restarts included, and `restarts` counts them; `error` is what it failed with, `null` on success. Nested engines end their own timelines with one too.
|
|
706
|
+
|
|
707
|
+
### Per module
|
|
708
|
+
|
|
709
|
+
| Module | `PROCESS_HANDLING` types | Other actions |
|
|
710
|
+
|---|---|---|
|
|
711
|
+
| `vigor.retry` | `REQUEST_START`, `REQUEST_ERROR`, `REQUEST_RESTART`, `RETRY_START`, `RETRY_ERROR` | `ATTEMPT_INCREASED`, `TARGET_REQUEST_STARTED`, `TARGET_REQUEST_ENDED`, `RETRY_DECISION`, `RETRY_DELAY` |
|
|
712
|
+
| `vigor.parse` | `REQUEST_START`, `REQUEST_ERROR`, `REQUEST_RESTART` | `BODY_READ`, `STRATEGY_STARTED`, `STRATEGY_SUCCEEDED`, `STRATEGY_FAILED` |
|
|
713
|
+
| `vigor.fetch` | `REQUEST_START`, `REQUEST_ERROR`, `REQUEST_RESTART` | `BUILT_URL`, `SET_OPTIONS`, `ENGINE_CREATED`, `RETRY_STARTED`, `RESPONSE_RECEIVED`, `RETRY_ENDED`, `PARSE_STARTED`, `PARSE_ENDED` |
|
|
714
|
+
| `vigor.all` | `REQUEST_START`, `REQUEST_ERROR` | `TASK_STARTED`, `TASK_ENDED`, `TASK_ERROR` |
|
|
715
|
+
|
|
716
|
+
In `vigor.retry`, `RETRY_START`/`RETRY_ERROR` are per attempt. `RETRY_ERROR`'s data also says whether the attempt `timedOut` (hit `settings.timeout`) or was `aborted` (an external signal fired). After every failed attempt, `RETRY_DECISION` records `{ attempt, retry, reason }`:
|
|
717
|
+
|
|
718
|
+
| `reason` | `retry` | Meaning |
|
|
719
|
+
|---|---|---|
|
|
720
|
+
| `"retry"` | `true` | It will be retried (`RETRY_DELAY` follows) |
|
|
721
|
+
| `"cancelled"` | `false` | `retryIf` decided against it — `cancelRetry()` or a fluent `false`; the matching `MIDDLEWARE_API_CALLED` shows which middleware (e.g. fetch's internal one for an `unretryStatus`) |
|
|
722
|
+
| `"breakRetry"` | `false` | A middleware called `breakRetry()` |
|
|
723
|
+
| `"aborted"` | `false` | An external abort signal fired |
|
|
724
|
+
| `"exhausted"` | `false` | No attempts left |
|
|
725
|
+
|
|
726
|
+
The context's flags mirror this: `ctx.flags.brokeRetry` is set only by `breakRetry()`, `ctx.flags.aborted` by an external abort, and `ctx.flags.timedOut` while the current attempt has timed out.
|
|
727
|
+
|
|
728
|
+
In `vigor.all`, tasks run concurrently, so their entries interleave; each one carries its task's `index`.
|
|
729
|
+
|
|
730
|
+
### Nested engines in `vigor.fetch`
|
|
731
|
+
|
|
732
|
+
With `debug` on in the fetch's settings, its retry and parse engines record too. `RETRY_ENDED` and `PARSE_ENDED` hold the nested engine's **whole timeline**, alongside the engine, `took`, and its `response`/`result` (`VigorDefault` when it failed):
|
|
733
|
+
|
|
734
|
+
```ts
|
|
735
|
+
for (const item of res.timeline) {
|
|
736
|
+
if (item.action === "RETRY_ENDED") item.content.timeline; // VigorRetryTimeline
|
|
737
|
+
}
|
|
738
|
+
```
|
|
739
|
+
|
|
740
|
+
Every response an attempt gets is recorded as `RESPONSE_RECEIVED` — `{ attempt, status, statusText, ok, redirected, url }` — before it's judged, so a failing status still shows up there. `PARSE_STARTED`/`PARSE_ENDED` also carry a `source` — `"response"` for the result, or `"failedResponse"` for the best-effort parse of a failed response's body — and the `attempt` whose response they parsed. Those run inside the retry engine, so they appear between `RETRY_STARTED` and `RETRY_ENDED`, in order:
|
|
741
|
+
|
|
742
|
+
```text
|
|
743
|
+
RETRY_STARTED
|
|
744
|
+
RESPONSE_RECEIVED attempt=1 status=503
|
|
745
|
+
PARSE_STARTED failedResponse attempt=1
|
|
746
|
+
PARSE_ENDED failedResponse attempt=1
|
|
747
|
+
RESPONSE_RECEIVED attempt=2 status=200
|
|
748
|
+
RETRY_ENDED (the retry engine's own timeline inside)
|
|
749
|
+
PARSE_STARTED response attempt=2
|
|
750
|
+
PARSE_ENDED response attempt=2
|
|
751
|
+
REQUEST_END success outcome="result"
|
|
752
|
+
```
|
|
753
|
+
|
|
754
|
+
---
|
|
755
|
+
|
|
476
756
|
## Plugins
|
|
477
757
|
|
|
478
758
|
```ts
|
|
@@ -484,10 +764,12 @@ export type VigorPlugin<
|
|
|
484
764
|
func: (v: VigorInstance, options: O) => Ext
|
|
485
765
|
}
|
|
486
766
|
|
|
487
|
-
vigor.use(plugin, options?)
|
|
767
|
+
vigor.use(plugin, options?) // options: Partial<O>
|
|
488
768
|
```
|
|
489
769
|
|
|
490
|
-
`plugin.func` receives the current `vigor` instance (read-only — plugins never mutate it, e.g. they might read it to wrap an existing method) and returns `Ext`, a set of properties to merge in. `vigor.use()` shallow-clones
|
|
770
|
+
`plugin.func` receives the current `vigor` instance (read-only — plugins never mutate it, e.g. they might read it to wrap an existing method) and returns `Ext`, a set of properties to merge in. `vigor.use()` shallow-clones the instance it's called on (including its nested `builders` groups) and merges `Ext` on top, returning a **new** instance, typed `VigorInstance<Ext>`, while the original stays untouched. Calls chain: `vigor.use(a).use(b)` keeps both plugins' extensions, and `b` receives the instance that already includes `a`'s. A property in `Ext` replaces a same-named one (a built-in like `fetch`, or an earlier plugin's), in the type as well as at runtime.
|
|
771
|
+
|
|
772
|
+
`plugin.options` holds the plugin's defaults: `func` receives them with the `options` passed to `use()` shallow-merged on top, so `use(plugin)` alone works and `func` always gets a complete `O`.
|
|
491
773
|
|
|
492
774
|
```ts
|
|
493
775
|
const loggingPlugin: VigorPlugin<{ prefix?: string }> = {
|
|
@@ -518,6 +800,78 @@ try {
|
|
|
518
800
|
}
|
|
519
801
|
```
|
|
520
802
|
|
|
803
|
+
### typed errors
|
|
804
|
+
|
|
805
|
+
`requestVerbose()`'s `error` is typed per module, as **a union of that module's errors plus `{}`**:
|
|
806
|
+
|
|
807
|
+
| Module | `error` type |
|
|
808
|
+
|---|---|
|
|
809
|
+
| `vigor.retry` | `VigorRetryErrors \| {} \| null \| undefined` |
|
|
810
|
+
| `vigor.parse` | `VigorParseErrors \| {} \| null \| undefined` |
|
|
811
|
+
| `vigor.all` | `VigorAllErrors \| {} \| null \| undefined` |
|
|
812
|
+
| `vigor.fetch` | `VigorFetchErrors \| {} \| null \| undefined` (the nested engines' failures included, see below) |
|
|
813
|
+
|
|
814
|
+
`VigorRetryErrors` & co. are unions with **one member per error code**, so narrowing by `code` also narrows `data` to that code's payload. The `{} | null | undefined` tail is everything Vigor didn't create — an error your own target or middleware threw, an abort reason, a network `TypeError`, or even a bare `throw null`. It's there because those really do reach you: a `cancelRetry()`/`breakRetry()`/abort path returns your error as-is, rather than wrapping it.
|
|
815
|
+
|
|
816
|
+
Narrow with the exported guards — `isVigorRetryError`, `isVigorParseError`, `isVigorFetchError`, `isVigorAllError` (or `vigor.guards.*`):
|
|
817
|
+
|
|
818
|
+
```ts
|
|
819
|
+
const res = await vigor.retry(task).requestVerbose();
|
|
820
|
+
if (!res.success) {
|
|
821
|
+
if (isVigorRetryError(res.error)) {
|
|
822
|
+
res.error.code; // "VALUE_REQUIRED" | "RETRY_EXHAUSTED" | "RESTART_EXHAUSTED" | "TIMED_OUT"
|
|
823
|
+
if (res.error.code === "TIMED_OUT") res.error.data.limit; // number
|
|
824
|
+
if (res.error.code === "RETRY_EXHAUSTED") res.error.data.error; // the last underlying error
|
|
825
|
+
} else {
|
|
826
|
+
res.error; // whatever your task threw
|
|
827
|
+
}
|
|
828
|
+
}
|
|
829
|
+
```
|
|
830
|
+
|
|
831
|
+
Pass one or more codes to check the code too — the error is narrowed to just those codes, so `data` is that code's payload right away (works on a `catch` binding as well):
|
|
832
|
+
|
|
833
|
+
```ts
|
|
834
|
+
const res = await vigor.fetch("/api/users").requestVerbose();
|
|
835
|
+
if (!res.success) {
|
|
836
|
+
if (isVigorFetchError(res.error, "FETCH_FAILED")) {
|
|
837
|
+
res.error.data.status; // number
|
|
838
|
+
res.error.data.parsed; // the error body, best-effort parsed
|
|
839
|
+
} else if (isVigorFetchError(res.error, "RETRY_EXHAUSTED", "TIMED_OUT")) {
|
|
840
|
+
res.error.code; // "RETRY_EXHAUSTED" | "TIMED_OUT"
|
|
841
|
+
}
|
|
842
|
+
}
|
|
843
|
+
|
|
844
|
+
try { await vigor.fetch("/api/users").request() }
|
|
845
|
+
catch (e) { if (isVigorFetchError(e, "INVALID_PROTOCOL")) e.data.origin }
|
|
846
|
+
```
|
|
847
|
+
|
|
848
|
+
`error.context` is the run context at the time of the error, and its type depends on the code — some errors are raised where no run exists:
|
|
849
|
+
|
|
850
|
+
| Module | `context` may be `undefined` | `context` is always `undefined` |
|
|
851
|
+
|---|---|---|
|
|
852
|
+
| fetch | `VALUE_REQUIRED` (also raised by `.route()` while building) | — |
|
|
853
|
+
| retry | `VALUE_REQUIRED` (also raised by the `custom` algorithm) | — |
|
|
854
|
+
| parse | `PARSER_ALL_FAILED` (also raised by `VigorParseSniffStrategy`) | `INVALID_CONTENT_TYPE`, `PARSER_NOT_FOUND` (raised inside strategies; the built-in ones no longer raise `PARSER_NOT_FOUND`) |
|
|
855
|
+
| all | — | `TIMED_OUT` (per task — see `data.index`) |
|
|
856
|
+
|
|
857
|
+
Every other code always has one, so after `isVigorFetchError(e, "FETCH_FAILED")`, `e.context.href` needs no check.
|
|
858
|
+
|
|
859
|
+
On a `requestVerbose()` error, `context` is typed with **that request's own config** — the guards keep it rather than widening to a generic type:
|
|
860
|
+
|
|
861
|
+
```ts
|
|
862
|
+
const res = await vigor.fetch("https://api.example.com").path("users").requestVerbose();
|
|
863
|
+
if (!res.success && isVigorFetchError(res.error, "FETCH_FAILED")) {
|
|
864
|
+
res.error.context.policy.origin; // "https://api.example.com"
|
|
865
|
+
res.error.context.policy.path; // ["users"]
|
|
866
|
+
}
|
|
867
|
+
```
|
|
868
|
+
|
|
869
|
+
A thrown value (`catch (e)` around `request()`) carries no type, so there the guards give the generic `VigorFetchContextSchema<any>` — use `requestVerbose()` when you want the typed context. The context types (`VigorFetchContextSchema` & co.) are exported.
|
|
870
|
+
|
|
871
|
+
Prefer the guard over a bare `instanceof`: because of the `{}` member, `instanceof` widens `data` back to every code's payload, while the guard keeps `code` and `data` in sync. And since the tail has no `code`, reading `res.error.code` without narrowing is a compile error — that's the point.
|
|
872
|
+
|
|
873
|
+
All four modules are typed this way. `request()` throws instead of returning an envelope, so its thrown value stays `unknown` — narrow it with the same guards.
|
|
874
|
+
|
|
521
875
|
Or avoid try/catch entirely with `requestVerbose()`:
|
|
522
876
|
|
|
523
877
|
```ts
|
|
@@ -525,22 +879,44 @@ const res = await vigor.fetch("/api/users").requestVerbose();
|
|
|
525
879
|
if (!res.success) {
|
|
526
880
|
// res.error is typed, res.data is null
|
|
527
881
|
}
|
|
882
|
+
// res.timeline is there either way
|
|
528
883
|
```
|
|
529
884
|
|
|
530
885
|
| Module | Error codes |
|
|
531
886
|
|---|---|
|
|
532
|
-
| `VigorFetchError` | `VALUE_REQUIRED`, `INVALID_BODY`, `INVALID_PROTOCOL`, `FETCH_FAILED`, `RESTART_EXHAUSTED` |
|
|
887
|
+
| `VigorFetchError` | `VALUE_REQUIRED`, `INVALID_BODY`, `BODY_NOT_ALLOWED`, `INVALID_PROTOCOL`, `PATH_ESCAPED`, `FETCH_FAILED`, `RESTART_EXHAUSTED`, `REDIRECTED`, plus every `VigorRetryError` and `VigorParseError` code |
|
|
533
888
|
| `VigorRetryError` | `VALUE_REQUIRED`, `RETRY_EXHAUSTED`, `RESTART_EXHAUSTED`, `TIMED_OUT` |
|
|
534
889
|
| `VigorParseError` | `VALUE_REQUIRED`, `INVALID_CONTENT_TYPE`, `PARSER_NOT_FOUND`, `PARSER_ALL_FAILED`, `RESTART_EXHAUSTED` |
|
|
535
|
-
| `VigorAllError` | `EMPTY_TARGET` |
|
|
890
|
+
| `VigorAllError` | `EMPTY_TARGET`, `TIMED_OUT` |
|
|
891
|
+
|
|
892
|
+
`vigor.fetch` only ever fails with `VigorFetchError` (or something you threw): when its nested retry or parse engine fails, the error is re-raised as a `VigorFetchError` with the same `code` and `data`, the original kept as `cause`. So a request that ran out of attempts fails with `VigorFetchError("RETRY_EXHAUSTED")` — its `data.error` holding the last attempt's error, e.g. a `FETCH_FAILED` or a `TIMED_OUT` — and a body no strategy could parse with e.g. `VigorFetchError("PARSER_NOT_FOUND")`. `onError` and `settings.default` see the same error.
|
|
536
893
|
|
|
537
894
|
`FETCH_FAILED`'s `data` includes `parsed`: Vigor best-effort parses the failed response's body (using your configured parse strategies) before throwing, so you can inspect an API's error payload without re-fetching. If parsing that body also fails, `parsed` is simply `undefined`.
|
|
538
895
|
|
|
896
|
+
With an [API map](#route-descriptions) route that declares failure `responses`, `FETCH_FAILED`'s `data` has one member per status, so narrowing `data.status` narrows `data.parsed` — to the declared body `| undefined`, or `unknown` for a status the route doesn't cover. `RETRY_EXHAUSTED`/`RESTART_EXHAUSTED`'s `data.error` is typed as the same request's errors, so the last attempt's failure stays typed one level down:
|
|
897
|
+
|
|
898
|
+
```ts
|
|
899
|
+
const res = await api.route("POST /users").body("overwrite", { name: "a" }).requestVerbose()
|
|
900
|
+
if (!res.success) {
|
|
901
|
+
const err = isVigorFetchError(res.error, "RETRY_EXHAUSTED") ? res.error.data.error : res.error
|
|
902
|
+
if (isVigorFetchError(err, "FETCH_FAILED") && err.data.status === 422) {
|
|
903
|
+
err.data.parsed // { fields: Record<string, string> } | undefined
|
|
904
|
+
}
|
|
905
|
+
}
|
|
906
|
+
```
|
|
907
|
+
|
|
908
|
+
`.cast<T>()` only replaces the success type — the failure types stay. A `raw` parse makes `parsed` the `Response`, so it keeps the plain `{ status: number, ..., parsed: unknown }` shape.
|
|
909
|
+
|
|
910
|
+
`PARSER_ALL_FAILED` keeps why each strategy failed: `data.tried[i]` names a strategy and `data.errors[i]` is what it threw, the message lists them (`All parsers failed: strategy#0 (SyntaxError: ...)`), and `cause` is the last one — so a malformed JSON body still carries its `SyntaxError`, with or without `settings.debug`.
|
|
911
|
+
|
|
539
912
|
---
|
|
540
913
|
|
|
541
914
|
## TypeScript notes
|
|
542
915
|
|
|
543
916
|
- Every builder is **immutable** — `.settings(...)`, `.path(...)`, etc. all return a *new* instance with the change merged in; the original is untouched.
|
|
544
|
-
- Array-valued config (`path`, `query`, parse `strategies`, etc.) **concatenates** across calls by default; object-valued config deep-merges. A handful of methods (`hash`, `headers("overwrite", ...)`, `body("overwrite", ...)`, `options("overwrite", ...)`, `retry(...)`, `parse(...)`, `algorithms(...)`) force a full **replace** instead, since merging wouldn't make sense there.
|
|
917
|
+
- Array-valued config (`path`, `query`, parse `strategies`, etc.) **concatenates** across calls by default; object-valued config deep-merges. A handful of methods (`hash`, `headers("overwrite", ...)`, `body("overwrite", ...)`, `options("overwrite", ...)`, `retry(...)`, `parse(...)`, `algorithms(...)`, fetch's `retryHeaders`/`unretryStatus`) force a full **replace** instead, since merging wouldn't make sense there. The config's type follows the same rules, so it always matches what's stored at runtime.
|
|
918
|
+
- Config objects are checked for unknown keys at any depth: `.settings({ maxAttempts: 3, timeot: 5 })` is a type error.
|
|
919
|
+
- To store or pass around a configured builder, type it with `any`: `VigorRetry<any>`, `VigorFetch<any>`, etc. The bare `VigorRetry` is the unconfigured instance's type.
|
|
920
|
+
- To narrow `requestVerbose()`'s `error`, use the `isVigor*Error` guards (or `vigor.guards.*`): they narrow `code` and `data` together. The sentinels `VigorDefault`/`VigorEmpty` (and `isVigorDefault`/`isVigorEmpty`) are exported for checking an unset `ctx.result` in middlewares.
|
|
545
921
|
- Config shape is tracked through the whole chain via TypeScript generics, so `.settings()`/`.middlewares()` callbacks and `.request()`'s inferred return type stay accurate as you chain.
|
|
546
922
|
- `.cast<T>()` is available on every module (`fetch`, `retry`, `parse`, `all`) and always wins over the naturally-inferred type, regardless of where in the chain it's called.
|