vigor-fetch 5.4.0 → 6.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 +172 -54
- package/dist/index.cjs +1 -1
- package/dist/index.d.cts +3018 -2488
- package/dist/index.d.ts +3018 -2488
- package/dist/index.js +1 -1
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -47,8 +47,8 @@ import vigor from "vigor-fetch";
|
|
|
47
47
|
|
|
48
48
|
const data = await vigor
|
|
49
49
|
.fetch("https://api.example.com")
|
|
50
|
-
.path("v1", "users")
|
|
51
|
-
.query({ page: 1, limit: 10 })
|
|
50
|
+
.path("append", "v1", "users")
|
|
51
|
+
.query("append", { page: 1, limit: 10 })
|
|
52
52
|
.request();
|
|
53
53
|
// -> GET https://api.example.com/v1/users?page=1&limit=10
|
|
54
54
|
```
|
|
@@ -95,6 +95,7 @@ vigor.retry(task?) // -> VigorRetry, target pre-set if given
|
|
|
95
95
|
vigor.parse(request|response?) // -> VigorParse, target pre-set if given
|
|
96
96
|
vigor.all(...tasks) // -> VigorAll, target pre-set if any tasks given
|
|
97
97
|
vigor.use(plugin, options?)
|
|
98
|
+
vigor.transform(key, arg?, fn) // a registered result transform, see Result transforms
|
|
98
99
|
vigor.builders // direct access to each module's sub-builders
|
|
99
100
|
vigor.guards // each module's error type guard
|
|
100
101
|
```
|
|
@@ -115,6 +116,7 @@ Every sub-builder used internally by `.settings()`/`.middlewares()`/etc. is also
|
|
|
115
116
|
```ts
|
|
116
117
|
vigor.builders.fetch.settings() // -> VigorFetchPolicySettings
|
|
117
118
|
vigor.builders.fetch.middlewares() // -> VigorFetchPolicyMiddlewares
|
|
119
|
+
vigor.builders.fetch.serializers() // -> VigorFetchPolicySerializers
|
|
118
120
|
|
|
119
121
|
vigor.builders.retry.settings() // -> VigorRetryPolicySettings
|
|
120
122
|
vigor.builders.retry.middlewares() // -> VigorRetryPolicyMiddlewares
|
|
@@ -166,39 +168,44 @@ Without a callback the guard only checks the error you pass, as before: it narro
|
|
|
166
168
|
|---|---|
|
|
167
169
|
| `method(str)` | Forces the HTTP method. Default: `POST` if a body is set, otherwise `GET` |
|
|
168
170
|
| `origin(str)` | Sets the base URL (absolute) or a path relative to the current page |
|
|
169
|
-
| `path(...
|
|
170
|
-
| `query(...objs)` |
|
|
171
|
-
| `hash(str)` | Sets the URL fragment,
|
|
172
|
-
| `headers(mode, obj)` | Sets headers. `mode`: `"
|
|
173
|
-
| `body(mode, obj)` | Sets the body. `"
|
|
171
|
+
| `path(mode, ...values)` | Sets path values. `mode`: `"append"` (after the ones set so far) or `"replace"` (discard them) |
|
|
172
|
+
| `query(mode, ...objs)` | Sets query-parameter objects. `mode`: `"append"` or `"replace"` |
|
|
173
|
+
| `hash(str)` | Sets the URL fragment (a single value, so it always replaces) |
|
|
174
|
+
| `headers(mode, obj)` | Sets headers. `mode`: `"replace"` (discard previous) or `"merge"` (`Object.assign`-style) |
|
|
175
|
+
| `body(mode, obj)` | Sets the body. `"replace"` replaces it entirely; `"merge"` shallow-merges when both old and new body are plain objects, otherwise replaces |
|
|
174
176
|
| `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 |
|
|
177
|
+
| `serializers(fn \| config)` | Sets the steps that turn the stored path/query/hash/headers/body into what is sent (see [Serializers](#serializers)) |
|
|
175
178
|
| `settings(fn \| config)` | Configures fetch-level settings (below) |
|
|
176
179
|
| `middlewares(fn \| config)` | Configures the fetch middleware pipeline (below) |
|
|
177
|
-
| `retry(fn \| config \| VigorRetry)` | Configures the **internal retry engine** used to send the request
|
|
178
|
-
| `parse(fn \| config \| VigorParse)` | Configures the **internal parse engine** used to interpret the request or response
|
|
179
|
-
| `apiMap<M>()` | Attaches a type-level API map: the matched route's `response` becomes the result type (see [apiMap / route](#apimap--route)) |
|
|
180
|
+
| `retry(fn \| config \| VigorRetry)` | Configures the **internal retry engine** used to send the request, starting from its current config (the retry defaults until set). A callback gets a `VigorRetry` holding that config and a config object is merged into it, so each call adds to the previous ones (`algorithms` still replaces the algorithm); a `VigorRetry` instance is a complete engine and replaces it |
|
|
181
|
+
| `parse(fn \| config \| VigorParse)` | Configures the **internal parse engine** used to interpret the request or response, merging the same way as `retry()`: a callback or config object adds to the current config, a `VigorParse` instance replaces it. Its result type (`.cast<T>()`, `raw`, middlewares, `default`) becomes the request's result type |
|
|
182
|
+
| `apiMap<M>(options?)` | Attaches a type-level API map: the matched route's `response` becomes the result type. `{ strict: true }` makes an unmatched request a compile error (see [apiMap / route](#apimap--route)) |
|
|
180
183
|
| `route(key, params?)` | Sets method and path from an API map route, filling its `:name` segments |
|
|
181
184
|
| `cast<T>()` | Overrides the inferred result type with `T` |
|
|
182
185
|
| `request()` | Executes and returns the parsed result, throwing on failure |
|
|
183
186
|
| `requestVerbose()` | Executes and returns `{ success, data, error }` |
|
|
184
187
|
|
|
185
|
-
> `path
|
|
188
|
+
> Every method that sets a list or an object takes its mode first — `"append"`/`"replace"` for lists (`path`, `query`), `"merge"`/`"replace"` for objects (`headers`, `body`, `options`) — so how a call combines with the previous ones is always written at the call. Single values (`origin`, `method`, `hash`) always replace.
|
|
186
189
|
|
|
187
190
|
### origin / path / query / hash
|
|
188
191
|
|
|
189
192
|
```ts
|
|
190
193
|
vigor.fetch("https://api.example.com/", "/api")
|
|
191
|
-
.path("v1", "users")
|
|
192
|
-
.query({ page: 1 })
|
|
194
|
+
.path("append", "v1", "users")
|
|
195
|
+
.query("append", { page: 1 })
|
|
193
196
|
.hash("section-2")
|
|
194
197
|
// -> https://api.example.com/api/v1/users?page=1#section-2
|
|
195
198
|
```
|
|
196
199
|
|
|
197
200
|
`origin()` only accepts one argument — pass origin + first path segments as separate calls, or fold extra segments into `path()`.
|
|
198
201
|
|
|
199
|
-
|
|
202
|
+
`.path()` and `.query()` store their values as given. Turning them into the URL is done by the `path`, `query` and `url` [serializers](#serializers), and with the default steps:
|
|
200
203
|
|
|
201
|
-
|
|
204
|
+
- Path values: `null`/`undefined` are dropped, a `Date` becomes its ISO string, a `/` inside a value separates path levels, and each segment is percent-encoded, so `"a b"` or `"x?y"` can never leak into the query or fragment: `.path("append", "v1/users", "a b")` → `/v1/users/a%20b`. Pass segments **unencoded** — an already-encoded `%20` would be encoded again. The origin's own path goes in front.
|
|
205
|
+
- Query values: the origin's own query goes first, `null`/`undefined` entries are dropped, an array repeats its key (`a=1&a=2`), and a `Date` becomes its ISO string.
|
|
206
|
+
- Without `.hash()`, the origin's fragment is kept.
|
|
207
|
+
|
|
208
|
+
`.` and `..` segments still work as relative steps, but by default (the `url` stage's `confine` step) never out of the origin: with `vigor.fetch("https://api.example.com/api/v1")`, `.path("append", "users", "..", "posts")` goes to `/api/v1/posts`, while `.path("append", "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`). Leaving `confine` out of the `url` stage turns the check off: `.serializers(s => s.url(u => u.hashFromOrigin()))`.
|
|
202
209
|
|
|
203
210
|
### apiMap / route
|
|
204
211
|
|
|
@@ -206,64 +213,78 @@ Describe your API once as a type, and every request built from it gets its route
|
|
|
206
213
|
|
|
207
214
|
```ts
|
|
208
215
|
type Api = {
|
|
209
|
-
"
|
|
210
|
-
|
|
211
|
-
|
|
212
|
-
|
|
213
|
-
"
|
|
216
|
+
"/users": {
|
|
217
|
+
GET: { response: User[] }
|
|
218
|
+
POST: { response: User }
|
|
219
|
+
}
|
|
220
|
+
"/users/me": {
|
|
221
|
+
GET: { response: Me }
|
|
222
|
+
}
|
|
223
|
+
"/users/:id": {
|
|
224
|
+
GET: { response: User }
|
|
225
|
+
DELETE: { response: null }
|
|
226
|
+
}
|
|
214
227
|
}
|
|
215
228
|
|
|
216
229
|
const api = vigor.fetch("https://api.example.com").apiMap<Api>()
|
|
217
230
|
|
|
218
|
-
await api.path("users").request() // User[]
|
|
219
|
-
await api.path("users", id).request() // User
|
|
220
|
-
await api.path("users", "me").request() // Me
|
|
221
|
-
await api.path("users").body("
|
|
222
|
-
await api.path("users", id).method("DELETE").request() // null
|
|
223
|
-
await api.path("nope").request() // unknown (no route matched)
|
|
231
|
+
await api.path("append", "users").request() // User[]
|
|
232
|
+
await api.path("append", "users", id).request() // User
|
|
233
|
+
await api.path("append", "users", "me").request() // Me
|
|
234
|
+
await api.path("append", "users").body("replace", newUser).request() // User (POST: a body is set)
|
|
235
|
+
await api.path("append", "users", id).method("DELETE").request() // null
|
|
236
|
+
await api.path("append", "nope").request() // unknown (no route matched)
|
|
224
237
|
|
|
225
238
|
await api.route("GET /users/:id", { id: 1 }).request() // User — key autocompletes
|
|
226
239
|
```
|
|
227
240
|
|
|
228
|
-
- Keys are `"
|
|
241
|
+
- Keys are paths, `"/<path>"`; each holds an operation per upper-case method (`GET`, `POST`, …). A `:name` segment matches any one segment; a static segment needs that exact literal. When several paths match, the most specific wins segment by segment from the left (`/users/me` beats `/users/:id`), like a router.
|
|
229
242
|
- The request's method is the one set with `.method()`, or — as at runtime — `POST` with a body and `GET` without.
|
|
230
|
-
- 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.
|
|
231
|
-
- 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.
|
|
243
|
+
- Path arguments are matched the way the URL is built: `.path("append", "users/1")` is two segments, `null`/`undefined` are dropped, numbers become their digits. A non-literal argument (`id: string`) only matches a `:name` segment.
|
|
244
|
+
- Routes are relative to the path set before `.apiMap()`, so a shared prefix goes first: `vigor.fetch(origin).path("append", "v1").apiMap<Api>()`. The origin's own pathname isn't part of the match.
|
|
245
|
+
- The map describes the raw response body, what the parse strategies produce. Everything that runs after that applies on top of it, as at runtime: the parse engine's middlewares, `default` and `onError`, then the fetch's `.cast<T>()`, middlewares, `default` and `onError`. A declared failure's `parsed` goes through the parse engine too.
|
|
232
246
|
- 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`.
|
|
233
|
-
-
|
|
247
|
+
- `.apiMap<Api>({ strict: true })` turns a missed match into a compile error on `request()`/`requestVerbose()` instead: the error lists the routes of the request's method and the path it got. A dynamic path (`.path("append", ...segments)` with `segments: string[]`) can't be matched, so it's an error too — use `.route()`, or `.cast<T>()`, which opts a request out of the check.
|
|
248
|
+
- `route(key, params)` takes `"<METHOD> /<path>"` keys built from the map, 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.
|
|
234
249
|
- It's purely a type: `apiMap()` changes nothing at runtime, and responses aren't validated.
|
|
235
250
|
|
|
236
251
|
#### Route descriptions
|
|
237
252
|
|
|
238
|
-
A
|
|
253
|
+
A path can hold `params`, shared by all its methods; an operation can hold `request`, `response` and `responses`. Every key is optional:
|
|
239
254
|
|
|
240
255
|
```ts
|
|
241
256
|
type Api = {
|
|
242
|
-
"
|
|
243
|
-
params:
|
|
244
|
-
|
|
245
|
-
|
|
246
|
-
|
|
247
|
-
|
|
248
|
-
|
|
249
|
-
|
|
257
|
+
"/users/:id": {
|
|
258
|
+
params: { id: number } // .route()'s param types
|
|
259
|
+
GET: {
|
|
260
|
+
responses: {
|
|
261
|
+
200: User
|
|
262
|
+
304: null
|
|
263
|
+
404: { error: "not_found" }
|
|
264
|
+
"4xx": ApiError // every other 4xx
|
|
265
|
+
"5xx": { message: string }
|
|
266
|
+
}
|
|
250
267
|
}
|
|
251
268
|
}
|
|
252
|
-
"
|
|
253
|
-
|
|
254
|
-
|
|
269
|
+
"/users": {
|
|
270
|
+
POST: {
|
|
271
|
+
request: { body: { name: string } } // the body the request must carry
|
|
272
|
+
responses: { 201: User, 422: { fields: Record<string, string> } }
|
|
273
|
+
}
|
|
255
274
|
}
|
|
256
|
-
"
|
|
257
|
-
|
|
258
|
-
|
|
275
|
+
"/search": {
|
|
276
|
+
GET: {
|
|
277
|
+
request: { query: { q: string, page?: number } } // what .query() must add up to
|
|
278
|
+
response: User[] // shorthand for responses: { "2xx": User[] }
|
|
279
|
+
}
|
|
259
280
|
}
|
|
260
281
|
}
|
|
261
282
|
```
|
|
262
283
|
|
|
263
284
|
- **`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`.
|
|
264
|
-
- **`response`** is shorthand for `responses: { "2xx": ... }`. Undeclared success statuses aren't modeled, so
|
|
285
|
+
- **`response`** is shorthand for `responses: { "2xx": ... }`. Undeclared success statuses aren't modeled, so an operation that declares none falls back to the parse engine's type.
|
|
265
286
|
- **`params`** types `.route()`'s values: `api.route("GET /users/:id", { id: "1" })` is an error above.
|
|
266
|
-
- **`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.
|
|
287
|
+
- **`request.body`** and **`request.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. An operation without `body`/`query` accepts anything there. The compiler error names the route and the problem:
|
|
267
288
|
|
|
268
289
|
```
|
|
269
290
|
The 'this' context of type 'VigorFetch<...>' is not assignable to method's 'this' of type
|
|
@@ -271,6 +292,32 @@ type Api = {
|
|
|
271
292
|
```
|
|
272
293
|
|
|
273
294
|
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>`.
|
|
295
|
+
- Keys other than these (an old-style `body` next to `response`, a lower-case `get`, `headers` in `request`) are type errors on `.apiMap<Api>()`.
|
|
296
|
+
|
|
297
|
+
#### Overloads
|
|
298
|
+
|
|
299
|
+
When one method answers differently depending on what's sent, give it a tuple of operations:
|
|
300
|
+
|
|
301
|
+
```ts
|
|
302
|
+
type Api = {
|
|
303
|
+
"/users/:id": {
|
|
304
|
+
params: { id: number }
|
|
305
|
+
GET: [
|
|
306
|
+
{ request: { query: { expand: true } }, response: UserWithPosts },
|
|
307
|
+
{ request: { query?: { expand?: false } }, response: User },
|
|
308
|
+
]
|
|
309
|
+
}
|
|
310
|
+
}
|
|
311
|
+
|
|
312
|
+
await api.route("GET /users/:id", { id }).query("append", { expand: true }).request() // UserWithPosts
|
|
313
|
+
await api.route("GET /users/:id", { id }).request() // User
|
|
314
|
+
await api.route("GET /users/:id", { id }).query("append", { expand: flag }).request() // UserWithPosts | User
|
|
315
|
+
```
|
|
316
|
+
|
|
317
|
+
- The request's `body` and `query`, as set when it's sent, pick the overload: the **first** one they surely match wins (order them from most to least specific).
|
|
318
|
+
- When none surely matches — a value only known as `boolean` or `"csv" | "json"` — it's the union of every overload the request may match. A value may match when its type overlaps the declared one; a missing required key or an unknown key rules an overload out.
|
|
319
|
+
- A request that may match none doesn't compile (`"the request matches none of the route's overloads"`, with every overload's `request` as `expected`).
|
|
320
|
+
- Failures (`FETCH_FAILED`'s `data.parsed`) follow the picked overload too. `params` stay the path's, shared by every overload.
|
|
274
321
|
|
|
275
322
|
#### Status and response
|
|
276
323
|
|
|
@@ -290,16 +337,44 @@ if (res.success) {
|
|
|
290
337
|
- 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`).
|
|
291
338
|
- `.cast<T>()` and `requestVerbose<R>()` replace every success's `data`, but keep `status` — and the failure types.
|
|
292
339
|
|
|
340
|
+
### Serializers
|
|
341
|
+
|
|
342
|
+
Everything between what you set on the builder and what `fetch` receives is a list of named steps. Nothing outside these steps touches the URL, headers or body.
|
|
343
|
+
|
|
344
|
+
| Stage | Turns | Default steps |
|
|
345
|
+
|---|---|---|
|
|
346
|
+
| `path` | `.path()` values → string segments | `dropNullish`, `stringify`, `split("/")`, `encode`, `prefixOrigin` |
|
|
347
|
+
| `query` | `.query()` entries → `[string, string]` entries | `fromOrigin`, `dropNullish`, `arrays("repeat")`, `stringify` |
|
|
348
|
+
| `url` | the assembled `URL` → the `URL` sent | `hashFromOrigin`, `confine` |
|
|
349
|
+
| `body` | `.body()` value → `BodyInit` and its content type (the first step that handles it wins) | `text`, `blob`, `binary`, `stream`, `urlencoded`, `formData`, `json` |
|
|
350
|
+
| `headers` | `.headers()` object → the headers sent | `caseInsensitive`, `contentType` |
|
|
351
|
+
|
|
352
|
+
The URL is the origin + `/` + the `path` segments joined by `/`, with the `query` entries appended and `.hash()` set; the `url` stage gets it after that.
|
|
353
|
+
|
|
354
|
+
```ts
|
|
355
|
+
vigor.fetch("https://api.example.com")
|
|
356
|
+
.serializers(s => s
|
|
357
|
+
.query(q => q.dropNullish().arrays("comma").stringify()) // ids=1,2,3
|
|
358
|
+
.headers(h => h.caseInsensitive().custom("trace", headers => ({ ...headers, "X-Trace": id }))))
|
|
359
|
+
```
|
|
360
|
+
|
|
361
|
+
- **A stage you set replaces that stage's whole list**, and its callback starts from an empty chain: the steps you write are exactly the ones that run. The example above drops `fromOrigin` from `query` and `contentType` from `headers`. Stages you don't set keep their defaults (`VigorFetchSerializersBase`).
|
|
362
|
+
- `custom(name, func)` adds your own step to any stage. Steps get the stage's value and `{ origin, context }` (`headers` steps also get the body's `contentType`); `url` steps may change the `URL` in place and return nothing.
|
|
363
|
+
- `path` and `query` must end in strings: a value left otherwise fails with `SERIALIZE_FAILED`. No `body` step handling the body fails with `INVALID_BODY`.
|
|
364
|
+
- The step factories are also exported on their own (`VigorPathSteps`, `VigorQuerySteps`, `VigorUrlSteps`, `VigorBodySteps`, `VigorHeadersSteps`), and the config-object form takes step lists: `.serializers({ url: [VigorUrlSteps.confine()] })`.
|
|
365
|
+
- With `settings.debug`, the timeline gets a `SERIALIZED` entry per stage with its step names and output.
|
|
366
|
+
- `apiMap` routes match the path as the default `path` steps produce it.
|
|
367
|
+
|
|
293
368
|
### headers / body / options
|
|
294
369
|
|
|
295
370
|
```ts
|
|
296
371
|
vigor.fetch("/api")
|
|
297
372
|
.headers("merge", { Authorization: "Bearer token" })
|
|
298
|
-
.body("
|
|
373
|
+
.body("replace", { username: "john" })
|
|
299
374
|
.options("merge", { credentials: "include" })
|
|
300
375
|
```
|
|
301
376
|
|
|
302
|
-
|
|
377
|
+
The body is turned into a `BodyInit` by the `body` [serializer](#serializers): with the default steps, a string, `Blob`, `ArrayBuffer`/typed array/`DataView`, `ReadableStream`, `URLSearchParams` and `FormData` are sent as they are, and any other object as JSON. The `headers` serializer then adds the matching `Content-Type` unless `.headers()` set one, and keeps one key per header name regardless of case. `body("replace", 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")`).
|
|
303
378
|
|
|
304
379
|
> 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.
|
|
305
380
|
|
|
@@ -320,8 +395,8 @@ Body is auto-normalized based on type (string, `Blob`, `ArrayBuffer`/typed array
|
|
|
320
395
|
| `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) |
|
|
321
396
|
| `maxRetryAfter(num)` | Upper bound (ms) on a server-suggested retry delay from `retryHeaders`; longer values are clamped | `300000` (5 min) |
|
|
322
397
|
| `redirect(bool)` | On a redirected response, navigates the page via `window.location.href` (see below) | `false` |
|
|
323
|
-
| `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` |
|
|
324
398
|
| `maxRestarts(num)` | Max number of full pipeline restarts (see `onError` below) | `3` |
|
|
399
|
+
| `fetcher(fn)` | The function that sends each attempt, in place of the global `fetch` (see [Custom fetch](#custom-fetch)) | global `fetch` |
|
|
325
400
|
| `default(fn)` | Fallback value/factory used only if the request ultimately fails and no restart/override happened | throws |
|
|
326
401
|
| `debug(bool)` | Records `requestVerbose()`'s [timeline](#timeline) (the nested retry/parse engines' too) | `false` |
|
|
327
402
|
|
|
@@ -333,6 +408,24 @@ On any non-`unretryStatus` failure response, the internal retry engine retries p
|
|
|
333
408
|
|
|
334
409
|
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.)
|
|
335
410
|
|
|
411
|
+
### Custom fetch
|
|
412
|
+
|
|
413
|
+
By default every attempt goes through the global `fetch`, looked up when the request is sent. `settings.fetcher` swaps in any function with the native signature, `(input: string, init: RequestInit) => Promise<Response>` (exported as `VigorFetcher`):
|
|
414
|
+
|
|
415
|
+
```ts
|
|
416
|
+
import { fetch as undiciFetch, ProxyAgent } from "undici"
|
|
417
|
+
|
|
418
|
+
const proxied = vigor
|
|
419
|
+
.fetch("https://api.example.com")
|
|
420
|
+
.settings(s => s.fetcher((input, init) => undiciFetch(input, { ...init, dispatcher: new ProxyAgent(proxyUrl) })))
|
|
421
|
+
```
|
|
422
|
+
|
|
423
|
+
- It receives the fully built URL and the `RequestInit` after the `before` middlewares ran, with the attempt's `signal` (timeout and external aborts) — honor it, or a timed-out attempt keeps running in the background.
|
|
424
|
+
- Everything around it stays the same: retries, `Retry-After`, parsing and middlewares all work on the `Response` it returns, and what it throws is retried like a network error.
|
|
425
|
+
- It's only type-checked: the signature is enforced at compile time, and the `Response` isn't checked at runtime.
|
|
426
|
+
- It's called as a plain function (`this` is `undefined`), so passing `window.fetch` directly is fine.
|
|
427
|
+
- Builders are immutable, so set it once on a base builder and reuse it: `const api = vigor.fetch(origin).settings({ fetcher })`.
|
|
428
|
+
|
|
336
429
|
### redirect
|
|
337
430
|
|
|
338
431
|
With `settings.redirect(true)`, a redirected response navigates the browser to its target:
|
|
@@ -389,6 +482,31 @@ In `before`, `ctx.options` already holds the built request (`method`, `headers`,
|
|
|
389
482
|
|
|
390
483
|
An intercept middleware that returns nothing keeps the current context (this applies to every module).
|
|
391
484
|
|
|
485
|
+
#### Result transforms
|
|
486
|
+
|
|
487
|
+
A plain callback is typed where it's written: on a shared base, before `.apiMap()` or the path, a fluent `onResult`'s parameter is `unknown`, and its return type is fixed from that. To keep the type of what a middleware does and apply it once the input is known, register the transform's type and tag the function with `vigor.transform()`:
|
|
488
|
+
|
|
489
|
+
```ts
|
|
490
|
+
declare module "vigor-fetch" {
|
|
491
|
+
interface VigorTransforms<In, Arg> { // write the type parameters exactly like this
|
|
492
|
+
unwrap: In extends { data: infer D } ? D : never
|
|
493
|
+
pick: Arg extends keyof In ? In[Arg] : never
|
|
494
|
+
}
|
|
495
|
+
}
|
|
496
|
+
|
|
497
|
+
const unwrap = vigor.transform("unwrap", r => r.data)
|
|
498
|
+
const pick = <const K extends string>(key: K) => vigor.transform("pick", key, r => r[key])
|
|
499
|
+
|
|
500
|
+
const base = vigor.fetch(origin).middlewares(m => m.onResult("fluent", unwrap))
|
|
501
|
+
const me = await base.apiMap<Api>().path("append", "me").request() // the route's `data`
|
|
502
|
+
```
|
|
503
|
+
|
|
504
|
+
- `In` is the result the middleware actually gets, at that point of the pipeline: the API map's data (per status, so narrowing `status` still narrows `data`), a `.cast<T>()`, the target's return type, or `unknown` where nothing is known — the entry decides what that gives.
|
|
505
|
+
- `Arg` is the argument the transform was created with (`vigor.transform(key, arg, fn)`), `undefined` without one.
|
|
506
|
+
- Use it as a fluent `onResult` middleware, on any engine — including a fetch's parse engine, where the map's data (and a failed response's declared body) goes through it too.
|
|
507
|
+
- Nothing checks that the function returns its entry's type; keep the two side by side. The function runs as it is: `vigor.transform()` returns it unchanged.
|
|
508
|
+
- The registry is global to the program. A library registering entries should prefix their names (`"mylib:unwrap"`) so they don't collide with its users'.
|
|
509
|
+
|
|
392
510
|
`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.
|
|
393
511
|
|
|
394
512
|
### retry / parse (nested engines)
|
|
@@ -877,7 +995,7 @@ Every other code always has one, so after `isVigorFetchError(e, "FETCH_FAILED")`
|
|
|
877
995
|
On a `requestVerbose()` error, `context` is typed with **that request's own config** — the guards keep it rather than widening to a generic type:
|
|
878
996
|
|
|
879
997
|
```ts
|
|
880
|
-
const res = await vigor.fetch("https://api.example.com").path("users").requestVerbose();
|
|
998
|
+
const res = await vigor.fetch("https://api.example.com").path("append", "users").requestVerbose();
|
|
881
999
|
if (!res.success && isVigorFetchError(res.error, "FETCH_FAILED")) {
|
|
882
1000
|
res.error.context.policy.origin; // "https://api.example.com"
|
|
883
1001
|
res.error.context.policy.path; // ["users"]
|
|
@@ -914,7 +1032,7 @@ if (!res.success) {
|
|
|
914
1032
|
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:
|
|
915
1033
|
|
|
916
1034
|
```ts
|
|
917
|
-
const res = await api.route("POST /users").body("
|
|
1035
|
+
const res = await api.route("POST /users").body("replace", { name: "a" }).requestVerbose()
|
|
918
1036
|
if (!res.success) {
|
|
919
1037
|
isVigorFetchError(res.error, "FETCH_FAILED", err => { // unwraps RETRY_EXHAUSTED if needed
|
|
920
1038
|
if (err.data.status === 422) {
|
|
@@ -932,8 +1050,8 @@ if (!res.success) {
|
|
|
932
1050
|
|
|
933
1051
|
## TypeScript notes
|
|
934
1052
|
|
|
935
|
-
- Every builder is **immutable** — `.settings(...)`, `.path(...)`, etc. all return a *new* instance with the change merged in; the original is untouched.
|
|
936
|
-
-
|
|
1053
|
+
- Every builder is **immutable** — `.settings(...)`, `.path("append", ...)`, etc. all return a *new* instance with the change merged in; the original is untouched.
|
|
1054
|
+
- Fetch's request parts take an explicit mode (`path`/`query`: `"append"`/`"replace"`, `headers`/`body`/`options`: `"merge"`/`"replace"`). Elsewhere, array-valued config (parse `strategies`, etc.) **concatenates** across calls by default and object-valued config deep-merges. A handful of methods (`hash`, `serializers(...)` per stage, `retry(VigorRetry)`/`parse(VigorParse)` with an instance, `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.
|
|
937
1055
|
- Config objects are checked for unknown keys at any depth: `.settings({ maxAttempts: 3, timeot: 5 })` is a type error.
|
|
938
1056
|
- 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.
|
|
939
1057
|
- 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.
|