# Plugins (https://effetch.pages.dev/docs/reference/plugins)

`@monarcode/effetch/plugins` exports the built-in plugins, their options and the types they return:

```ts
import {
  bearer,
  consoleLogger,
  logger,
  retry,
  timeout,
  TimeoutError,
} from "@monarcode/effetch/plugins";
```

## Bearer tokens

Guide: [Refresh a token](https://effetch.pages.dev/docs/plugins/token-refresh).

### bearer

Sends `Authorization: <scheme> <token>` with every request.

### BearerOptions

Options for [`bearer`](https://effetch.pages.dev/docs/reference/plugins#bearer).

| Prop       | Type                | Description                                                                  |
| ---------- | ------------------- | ---------------------------------------------------------------------------- |
| `token`    | `TokenSource<E, R>` | Where the token comes from, resolved for every request.                      |
| `scheme?`  | `string`            | The word before the token. Defaults to `"Bearer"`.                           |
| `refresh?` | `union`             | Where a new token comes from on a `401`. The request is then sent once more. |

### BearerPlugin

The plugin made by [`bearer`](https://effetch.pages.dev/docs/reference/plugins#bearer): it fails with `E` and needs `R`, the errors and services of the `token` and `refresh` Effects. Calls can only skip it (`plugins: { bearer: false }`).

### RefreshSource

Where [`bearer`](https://effetch.pages.dev/docs/reference/plugins#bearer) gets a new token when the server answers `401`:

- a function of the request that was refused, as it was sent, returning the new token or a promise of it;
- an Effect, whose error and services become the plugin's (and so the client's).

### TokenSource

Where [`bearer`](https://effetch.pages.dev/docs/reference/plugins#bearer) gets the token, for every request:

- a string, for a token that never changes;
- a function of the request, returning the token or a promise of it;
- an Effect, whose error and services become the plugin's (and so the client's).

### TokenValue

What a token source gives: the token, or `null`, `undefined` or `""` to send the request without an `Authorization` header.

## Retries

Guide: [Retry-After and a time limit](https://effetch.pages.dev/docs/plugins/retry-after).

### retry

Retries a call that failed with a `NetworkError` or got a retryable status, for the configured methods only (idempotent ones by default, so a `POST` is never sent twice).

### RetryBudgetOptions

Options for [`retry`](https://effetch.pages.dev/docs/reference/plugins#retry) with a time limit for the whole call: [`RetryOptions`](https://effetch.pages.dev/docs/reference/plugins#retryoptions), plus `budget`.

| Prop          | Type     | Description                                                               |
| ------------- | -------- | ------------------------------------------------------------------------- |
| `budget?`     | `union`  | How long the whole call may take, retries and waits included.             |
| `times?`      | `number` | How many times to retry after the first attempt. Defaults to `2`.         |
| `schedule?`   | `object` | The delays between attempts. Defaults to jittered exponential backoff.    |
| `methods?`    | `array`  | The methods that are retried. Defaults to the idempotent ones.            |
| `statuses?`   | `array`  | The statuses that are retried. Defaults to 408, 429, 500, 502–504.        |
| `retryAfter?` | `union`  | Wait as `Retry-After` asks, up to 1 minute or `max`. Defaults to `false`. |

### RetryBudgetPlugin

The plugin made by [`retry`](https://effetch.pages.dev/docs/reference/plugins#retry) with a `budget`. It fails with `TimeoutError` when the budget runs out during an attempt. Calls can override `times` and `budget`, or skip it.

### RetryOptions

Options for [`retry`](https://effetch.pages.dev/docs/reference/plugins#retry).

| Prop          | Type     | Description                                                               |
| ------------- | -------- | ------------------------------------------------------------------------- |
| `times?`      | `number` | How many times to retry after the first attempt. Defaults to `2`.         |
| `schedule?`   | `object` | The delays between attempts. Defaults to jittered exponential backoff.    |
| `methods?`    | `array`  | The methods that are retried. Defaults to the idempotent ones.            |
| `statuses?`   | `array`  | The statuses that are retried. Defaults to 408, 429, 500, 502–504.        |
| `retryAfter?` | `union`  | Wait as `Retry-After` asks, up to 1 minute or `max`. Defaults to `false`. |

### RetryPlugin

The plugin made by [`retry`](https://effetch.pages.dev/docs/reference/plugins#retry). It adds no errors; calls can override `times` or skip it.

## Time limits

Guide: [Choose a time limit](https://effetch.pages.dev/docs/plugins#choose-a-time-limit).

### timeout

Fails the call with a [`TimeoutError`](https://effetch.pages.dev/docs/reference/plugins#timeouterror), and aborts the request, when the response headers don't arrive within `duration`.

### TimeoutError

No response arrived within the [`timeout`](https://effetch.pages.dev/docs/reference/plugins#timeout) plugin's duration. The request was aborted.

- `url` is the request URL without its query string.
- `duration` is the limit that was exceeded, formatted (`"10s"`).

### TimeoutOptions

Options for [`timeout`](https://effetch.pages.dev/docs/reference/plugins#timeout), and what a call can override: `plugins: { timeout: { duration } }`.

| Prop       | Type    | Description                                |
| ---------- | ------- | ------------------------------------------ |
| `duration` | `Input` | How long to wait for the response headers. |

### TimeoutPlugin

The plugin made by [`timeout`](https://effetch.pages.dev/docs/reference/plugins#timeout): it adds [`TimeoutError`](https://effetch.pages.dev/docs/reference/plugins#timeouterror), and calls can override its `duration` or skip it.

## Logging

Guide: [Built-in plugins](https://effetch.pages.dev/docs/plugins#what-each-plugin-does).

### logger

Logs one entry per call with Effect's logger: the method, the URL, the status and how long the response took, e.g. `GET https://api.example.com/todos 200 (35ms)`, or `… failed (35ms)` with the failure's cause.

### LoggerOptions

Options for [`logger`](https://effetch.pages.dev/docs/reference/plugins#logger).

| Prop     | Type    | Description                                      |
| -------- | ------- | ------------------------------------------------ |
| `level?` | `union` | The level of every entry. Defaults to `"Debug"`. |

### LoggerPlugin

The plugin made by [`logger`](https://effetch.pages.dev/docs/reference/plugins#logger). Calls can only skip it (`plugins: { logger: false }`).

## Console logging

Guide: [Log to the console](https://effetch.pages.dev/docs/plugins/console-logging).

### consoleLogger

Prints each call to the console while you develop: one line per call, opening a group with its URL, headers, bodies and error.

### ConsoleLoggerCall

The call `ConsoleLoggerOptions.filter` decides on.

| Prop         | Type                     | Description                                                      |
| ------------ | ------------------------ | ---------------------------------------------------------------- |
| `route`      | `string`                 | The call's method and unfilled path, such as `"GET /users/:id"`. |
| `request`    | `object`                 | The request that was sent.                                       |
| `response`   | `union`                  | The response, or `undefined` when there was none.                |
| `exit`       | `Exit<unknown, unknown>` | The call's outcome.                                              |
| `durationMs` | `number`                 | How long the call took, in milliseconds.                         |

### ConsoleLoggerColor

How [`consoleLogger`](https://effetch.pages.dev/docs/reference/plugins#consolelogger) colors its output.

- `"auto"`: `"css"` where there's a `document` (browsers), else `false`.
- `"css"`: `%c` styles, for browser devtools and React Native DevTools.
- `"ansi"`: terminal escape codes, for Node, Bun and Deno.
- `false`: plain text.

### ConsoleLoggerDetail

How much [`consoleLogger`](https://effetch.pages.dev/docs/reference/plugins#consolelogger) prints for each call.

- `"summary"`: one line, such as `✗ POST /users/:id/roles  400 Bad Request  120 ms  → InvalidRole`.
- `"headers"`: that line opens a group holding the full URL, the request and response headers, and the error.
- `"full"`: the request and response bodies too.

### ConsoleLoggerOptions

Options for [`consoleLogger`](https://effetch.pages.dev/docs/reference/plugins#consolelogger). All are optional.

| Prop             | Type       | Description                                                                                                                        |
| ---------------- | ---------- | ---------------------------------------------------------------------------------------------------------------------------------- |
| `enabled?`       | `union`    | `false` makes the plugin do nothing. Defaults to `true`.                                                                           |
| `detail?`        | `union`    | How much to print for each call. Defaults to `"full"`.                                                                             |
| `only?`          | `union`    | Which calls to print. Defaults to `"all"`.                                                                                         |
| `collapsed?`     | `union`    | Whether groups start collapsed. Defaults to `true`, and to `false` in React Native, where Metro's terminal drops collapsed groups. |
| `slow?`          | `union`    | Flags calls that take at least this long. Defaults to `false`.                                                                     |
| `maxBodyLength?` | `number`   | Body text longer than this is cut. Defaults to `10_000`.                                                                           |
| `redact?`        | `union`    | Names to redact on top of the defaults, or `false` for none.                                                                       |
| `filter?`        | `function` | Prints only the calls it returns `true` for.                                                                                       |
| `color?`         | `union`    | How to color the output. Defaults to `"auto"`.                                                                                     |

### ConsoleLoggerPlugin

The plugin made by [`consoleLogger`](https://effetch.pages.dev/docs/reference/plugins#consolelogger). Calls can skip it (`plugins: { consoleLogger: false }`) or override its [`ConsoleLoggerSettings`](https://effetch.pages.dev/docs/reference/plugins#consoleloggersettings).

### ConsoleLoggerRedact

Names to redact on top of [`consoleLogger`](https://effetch.pages.dev/docs/reference/plugins#consolelogger)'s defaults. Strings match a name ignoring case, `-` and `_`, so `"accessToken"` also matches `access_token` and `Access-Token`. A `RegExp` is tested against the name as it is.

| Prop       | Type    | Description                                                                                    |
| ---------- | ------- | ---------------------------------------------------------------------------------------------- |
| `headers?` | `array` | Request and response header names.                                                             |
| `query?`   | `array` | Query parameter names.                                                                         |
| `body?`    | `array` | Keys in JSON bodies (at any depth), and field names in form bodies, of requests and responses. |

### ConsoleLoggerSettings

The options of [`consoleLogger`](https://effetch.pages.dev/docs/reference/plugins#consolelogger) that calls can override, with `plugins: { consoleLogger: { ... } }`. See [`ConsoleLoggerOptions`](https://effetch.pages.dev/docs/reference/plugins#consoleloggeroptions) for what each does.

| Prop            | Type                  | Description                                                                                                                    |
| --------------- | --------------------- | ------------------------------------------------------------------------------------------------------------------------------ |
| `detail`        | `ConsoleLoggerDetail` | How much to print for each call.                                                                                               |
| `only`          | `union`               | Which calls to print: `"all"`, or only the failed ones (`"errors"`).                                                           |
| `collapsed`     | `union`               | Whether each call's group starts collapsed. `false` by default in React Native, where Metro's terminal drops collapsed groups. |
| `slow`          | `union`               | Calls that take at least this long are flagged; `false` for none.                                                              |
| `maxBodyLength` | `number`              | Body text longer than this many characters is cut.                                                                             |