--- url: https://haihv.github.io/valifetch/guide/getting-started.md description: >- Install valifetch and make your first type-safe, Valibot-validated request with native fetch in Node.js, Deno, Bun or the browser. --- # Getting started valifetch is a type-safe HTTP client built on native `fetch` with [Valibot](https://valibot.dev) schema validation. It is like [ky](https://github.com/sindresorhus/ky), but with built-in request and response validation. ::: tip Try it live [Open the demo in StackBlitz](https://stackblitz.com/github/haihv/valifetch/tree/main/examples/demo?file=src%2Fmain.ts) to run valifetch in your browser, no install needed. It shows response validation, request-body validation and typed errors against a real API. ::: ## Installation ::: code-group ```bash [npm] npm install valifetch valibot ``` ```bash [Deno (JSR)] deno add jsr:@haihv/valifetch ``` ```bash [Bun / other (JSR)] bunx jsr add @haihv/valifetch ``` ::: In Deno you can also import directly: ```ts import valifetch from 'jsr:@haihv/valifetch'; import { bearerAuth } from 'jsr:@haihv/valifetch/auth'; import { createMock } from 'jsr:@haihv/valifetch/mock'; ``` The JSR package publishes the main entry plus the `auth` and `mock` subpaths. `valifetch/error` and `valifetch/types` are npm-only; on JSR, import `ValifetchError` and the core types from the main entry, `JwtRefreshOptions` from the `auth` subpath, and `MockCall`, `MockHandler` and `ValifetchMock` from the `mock` subpath. See [Subpath imports](https://haihv.github.io/valifetch/guide/subpath-imports.md). ## Requirements * Node.js >= 22.0.0 (uses native `fetch`) * valibot >= 1.0.0 (a peer dependency) * TypeScript `moduleResolution: "node16"` (or `"bundler"` / `"nodenext"`). This is required to resolve subpath imports like `valifetch/types`, `valifetch/error`, `valifetch/auth` and `valifetch/mock`. ## Your first request ```ts import valifetch from 'valifetch'; import * as v from 'valibot'; const UserSchema = v.object({ id: v.number(), name: v.string(), email: v.pipe(v.string(), v.email()), }); const user = await valifetch.get('https://api.example.com/users/1', { responseSchema: UserSchema, }); // user is fully typed: { id: number; name: string; email: string } ``` There is no `.json()` call. JSON responses are parsed automatically, then validated against `responseSchema` when one is given. Three ways to get a result type: ```ts // 1. From a schema: validated at runtime, type inferred const a = await valifetch.get('https://api.example.com/users/1', { responseSchema: UserSchema, }); // 2. From a generic: no runtime validation type User = { id: number; name: string }; const b = await valifetch.get('https://api.example.com/users/1'); // 3. Nothing: the result is unknown const c = await valifetch.get('https://api.example.com/data'); ``` ## HTTP methods ```ts valifetch.get(url, options); valifetch.post(url, options); valifetch.put(url, options); valifetch.patch(url, options); valifetch.delete(url, options); valifetch.head(url, options); valifetch.options(url, options); ``` ::: warning Bodyless methods `head()` always resolves `void` and does not accept `responseSchema` or `responseType`. `get()` and `head()` do not accept `json`, `form` or `body`. `delete()` and `options()` use the same bodyless option type as `get()`, so they reject those options too; send bodies with `post`, `put` or `patch`. ::: ## Configure once, reuse everywhere Most apps create an instance with shared defaults: ```ts const api = valifetch.create({ prefixUrl: 'https://api.example.com', timeout: 10_000, headers: { Accept: 'application/json' }, }); const user = await api.get('/users/1', { responseSchema: UserSchema }); ``` Continue with [Instances](https://haihv.github.io/valifetch/guide/instances.md), or jump to [Requests](https://haihv.github.io/valifetch/guide/requests.md) and [Validation](https://haihv.github.io/valifetch/guide/validation.md). ## Where to go next * [Requests](https://haihv.github.io/valifetch/guide/requests.md): bodies, path params, search params, timeouts, cancellation and deduplication. * [Errors](https://haihv.github.io/valifetch/guide/errors.md): the error codes you can catch. * [Recipes](https://haihv.github.io/valifetch/recipes/auth.md): authentication, SSE streaming, mocking, pagination. * [API reference](https://haihv.github.io/valifetch/api.md): every exported symbol, generated from the source. --- --- url: https://haihv.github.io/valifetch/guide/instances.md description: >- Create configured valifetch instances with create() and extend(): shared prefixUrl, headers, hooks and retry, with lightweight prototype-based inheritance. --- # Instances The default export, `valifetch`, is itself an instance. You create configured instances with `create()` and derive new ones with `extend()`. ```ts // Create a new instance valifetch.create(options); // Extend an instance instance.extend(options); instance.extend((parentOptions) => newOptions); // Wrap an instance for callable syntax instance.callable(); // Run requests in parallel (typed tuple results; cancellable) instance.all([req1, req2]); instance.allSettled([req1, req2]); ``` ## create ```ts const api = valifetch.create({ prefixUrl: 'https://api.example.com', timeout: 10_000, headers: { Authorization: 'Bearer token123', }, retry: { limit: 3, statusCodes: [408, 429, 500, 502, 503, 504], }, }); // Now use without prefixUrl const user = await api.get('/users/1', { responseSchema: UserSchema }); ``` Instance options (`ValifetchInstanceOptions`) are the base options minus the request-only ones. `json`, `form`, `body`, `signal` and `window` are request-only and cannot be set on `create()` or `extend()`. `priority` works on both and is forwarded to `fetch` unchanged. `responseType` is per-call only; see [API design decisions](https://haihv.github.io/valifetch/guide/api-design-decisions.md). ## extend `extend()` creates a child instance that inherits the parent's options. ```ts const adminApi = api.extend({ headers: { 'X-Admin': 'true' }, }); // Or with a function that receives the parent options const authApi = api.extend((options) => ({ ...options, headers: { ...options.headers, Authorization: `Bearer ${getToken()}`, }, })); ``` ### Option merging Options from the child are merged over the parent's: plain options set by the child win, while `headers` (merged per header name, case-insensitively, child wins) and `searchParams` combine with the parent's instead of replacing them. `debug` is inherited too, and a child can override it by passing its own value. `retry` is a plain option, so a child's (or a per-request) `retry` object **replaces** the parent's entirely rather than merging field by field; unset fields take the built-in defaults. See [Retry](https://haihv.github.io/valifetch/guide/retry.md#defaults). ### Hooks are concatenated Hooks from the parent and the child are **concatenated**, with the parent's hooks running first. A child never replaces a parent hook; it adds to the chain. ```ts const base = valifetch.create({ hooks: { beforeRequest: [logRequest] }, }); const child = base.extend({ hooks: { beforeRequest: [addTraceId] }, }); // child runs: logRequest, then addTraceId ``` Merged options are computed lazily on first use and cached, so deeply nested instances stay cheap. ## Callable syntax For ky-style calls, wrap an instance with `callable()`: ```ts import valifetch from 'valifetch'; const api = valifetch.create({ prefixUrl: 'https://api.example.com' }).callable(); // Call directly: defaults to GET const users = await api('/users'); // Specify the method in options const newUser = await api('/users', { method: 'POST', json: { name: 'John' }, }); // Or use method shortcuts const user = await api.get('/users/1'); const created = await api.post('/users', { json: { name: 'Jane' } }); // create() and extend() on a callable instance return callable instances const adminApi = api.extend({ headers: { 'X-Admin': 'true' } }); await adminApi('/admin/stats'); ``` Calling the instance directly with `{ method, responseType, ... }` typechecks like the corresponding verb method would. For example, `api(url, { method: 'GET', responseType: 'blob' })` is typed as `Promise`. `callable().head()` does not accept `responseType` or `responseSchema`, matching `ValifetchInstance.head()`. ## Lightweight by design Instances share a prototype that holds the HTTP methods. Each instance carries at most three small own properties (its options, plus a parent link and a lazily cached merge for an `extend()` child), so creating many of them (for example one per tenant) is cheap. ## Parallel helpers `all()` and `allSettled()` live on every instance. See [Parallel requests](https://haihv.github.io/valifetch/recipes/parallel-requests.md). --- --- url: https://haihv.github.io/valifetch/guide/requests.md description: >- Every valifetch request option: HTTP methods, json, form and raw bodies, path params, search params, headers, timeout, signals and download progress. --- # Requests ## Options at a glance ```ts type Options = { // Schema validation responseSchema?: Schema; // Validate response JSON bodySchema?: Schema; // Validate request body paramsSchema?: Schema; // Validate path parameters searchSchema?: Schema; // Validate search/query parameters // Request data (request-only: not accepted on create()/extend()) json?: object; form?: FormData | URLSearchParams | Record; body?: RawBody; params?: object; // Path parameters for :param replacement searchParams?: string | URLSearchParams | Record | Array<[string, string | number | boolean]>; method?: 'GET' | 'POST' | 'PUT' | 'PATCH' | 'DELETE' | 'HEAD' | 'OPTIONS'; priority?: 'high' | 'low' | 'auto'; // Forwarded to fetch // Response format (per-call only) responseType?: 'json' | 'text' | 'blob' | 'arrayBuffer' | 'formData' | 'stream' | 'raw' | 'sse'; // Configuration prefixUrl?: string; // Paths must stay under it; no `?` or `#` in the prefix timeout?: number; // ms retry?: RetryOptions | number | false; validateResponse?: boolean; // default: true validateRequest?: boolean; // default: true throwHttpErrors?: boolean; // default: true dedupe?: boolean; // default: false onDownloadProgress?: (event: DownloadProgressEvent) => void; debug?: true | ((event: DebugEvent) => void); sseMaxEventSize?: number; // Largest single SSE event buffered, in UTF-16 code units (default: 16 MiB) // Hooks hooks?: Hooks; // Standard fetch options headers?: HeadersInit; signal?: AbortSignal; // request-only credentials?: RequestCredentials; // ... other RequestInit options }; ``` Every symbol is documented in the [API reference](https://haihv.github.io/valifetch/api/index/type-aliases/ValifetchOptions.md). ## Request bodies ### JSON `json` is auto-stringified and sets `Content-Type: application/json`. When you pass `bodySchema`, the value is validated first and `json` is typed from the schema's input. ```ts const CreateUserSchema = v.object({ name: v.pipe(v.string(), v.minLength(1)), email: v.pipe(v.string(), v.email()), }); const newUser = await valifetch.post('https://api.example.com/users', { json: { name: 'John', email: 'john@example.com' }, bodySchema: CreateUserSchema, responseSchema: UserSchema, }); ``` ### Form `form` accepts `FormData`, `URLSearchParams` or a plain string record. ```ts // Multipart: Content-Type is set automatically with the correct boundary const formData = new FormData(); formData.append('file', file); formData.append('name', 'avatar'); await api.post('/upload', { form: formData }); // URL-encoded: sets Content-Type: application/x-www-form-urlencoded await api.post('/login', { form: { username: 'alice', password: 'secret' }, }); await api.post('/login', { form: new URLSearchParams({ username: 'alice', password: 'secret' }), }); ``` ### Raw body When a request body is neither JSON nor a form (a pre-serialised payload, a binary blob, a streamed upload) use the `body` escape hatch. It is sent exactly as given. `RawBody` is `string | Blob | ArrayBuffer | ArrayBufferView | ReadableStream`. ```ts // Pre-serialised payload: set the Content-Type yourself await api.post('/events', { body: '{"type":"ping"}', headers: { 'content-type': 'application/json' }, }); // Binary upload await api.put('/blobs/abc', { body: new Blob([bytes]), headers: { 'content-type': 'application/octet-stream' }, }); // Streamed upload: `duplex: 'half'` is added automatically await api.put('/blobs/abc', { body: fileStream, headers: { 'content-type': 'application/octet-stream' }, }); ``` Rules for raw bodies: * **No validation.** `bodySchema` applies to `json` only. * **No `Content-Type` inference.** valifetch never sets one for a raw body. The platform `Request` constructor still applies its own spec default for `string` and `Blob` bodies. * **Mutually exclusive** with `json` and `form`. * **Request-only**, and rejected on the bodyless methods (`get`, `head`, `delete`, `options`). * **`duplex: 'half'`** is added automatically for `ReadableStream` bodies, which the runtime requires. * **Streaming needs runtime support.** `ReadableStream` request bodies work on Node 22+, Deno and Chromium-based browsers (over HTTP/2 or newer); Firefox does not support them, and other engines vary. Where the runtime cannot stream (detected by the engine stringifying the stream into a `text/plain` body), valifetch throws a `TypeError` before calling `fetch` (instead of the browser silently sending `[object ReadableStream]`). Pass a `Blob`, `ArrayBuffer` or string there. * **Retries re-send the body.** The request is cloned before each attempt, so `Blob`, `ArrayBuffer` and string bodies re-send identically. A `ReadableStream` body is teed on clone, which buffers the stream in memory. Pass `retry: false` for large streamed uploads if that matters. ::: warning One body per request `json`, `form` and `body` are mutually exclusive. Setting more than one on a request throws a `TypeError`. Setting none is fine. ::: ## Path parameters Use `:name` segments in the URL and pass `params`. The names are type-checked; see [TypeScript](https://haihv.github.io/valifetch/guide/typescript.md). ```ts const user = await valifetch.get('https://api.example.com/users/:id', { params: { id: 123 }, paramsSchema: v.object({ id: v.pipe(v.number(), v.integer(), v.minValue(1)), }), responseSchema: UserSchema, }); ``` Param values are percent-encoded with `encodeURIComponent`, so `/`, `?`, `#` and `\` in a value can never add path segments, a query string or a fragment. The values `.` and `..` cannot be encoded safely (the URL parser resolves dot segments, even percent-encoded ones), so they throw a `TypeError` before any request is sent. Params are looked up as own properties only, so `:constructor` or `:toString` without a matching param throws as missing rather than resolving from `Object.prototype`. A missing (or `null` / `undefined`) param throws an `Error` naming it. ## Search parameters ```ts const users = await valifetch.get('https://api.example.com/users', { searchParams: { page: 1, limit: 10, q: 'john' }, searchSchema: v.object({ page: v.optional(v.pipe(v.number(), v.integer())), limit: v.optional(v.pipe(v.number(), v.integer(), v.maxValue(100))), q: v.optional(v.string()), }), responseSchema: v.array(UserSchema), }); ``` Instance-level `searchParams` are defaults that are merged with, and overridden per key by, the per-request value. They are appended to any query string already in the request path: `api.get('/a?x=1')` against an instance created with `{ searchParams: { x: 'i' } }` produces `?x=1&x=i`, not a replacement. A per-request key set explicitly to `undefined` or `null` removes the instance default for that key entirely. ## prefixUrl `prefixUrl` is joined to the request path with trailing and leading slashes normalised, so `prefixUrl: 'https://api.example.com/v1/'` plus `'/users'` gives `https://api.example.com/v1/users`. With `prefixUrl` set, the request path is always joined *under* the prefix: the final URL keeps the prefix origin, and its path stays under the prefix path. ```ts const api = valifetch.create({ prefixUrl: 'https://api.example.com/v1' }); await api.get('https://evil.com'); // -> https://api.example.com/v1/https://evil.com await api.get('/../admin'); // throws TypeError: resolves outside the prefix path await api.get('/%2e%2e/admin'); // throws TypeError too valifetch.create({ prefixUrl: 'https://api.example.com/v1?key=1' }).get('/users'); // throws TypeError: prefixUrl must not contain a query string or fragment ``` * Absolute or protocol-relative inputs (`https://evil.com`, `//evil.com`, `\\evil.com`) become path segments under the prefix rather than switching host. * A path that climbs above the prefix with `..` (including `%2e%2e`) throws a `TypeError` before any request is sent. * A `prefixUrl` containing a query string or fragment (`?` or `#`) throws a `TypeError`, because the path would otherwise be swallowed into the query. Put default query values in `searchParams` instead. * Without `prefixUrl`, the input must be a full URL and is used as-is. Validate user-controlled full URLs yourself; see [Security](https://haihv.github.io/valifetch/guide/security.md). ## Timeout By default requests never time out. `timeout` is in milliseconds; pass `0` to disable it explicitly. ```ts // Instance-level timeout (applies to every request) const api = valifetch.create({ timeout: 10_000 }); // Per-request timeout overrides the instance default for this call only const user = await api.get('https://api.example.com/users/1', { timeout: 2_000, responseSchema: UserSchema, }); ``` When the timeout elapses, the call rejects with `TIMEOUT_ERROR`. ## Cancellation Every request returns a `CancellablePromise` with a `.cancel()` method. You can also pass your own `AbortSignal`; both work together. ```ts const req = valifetch.get('https://api.example.com/slow'); req.cancel(); // rejects with ValifetchError { code: 'ABORT_ERROR' } const controller = new AbortController(); const req2 = valifetch.get('https://api.example.com/slow', { signal: controller.signal, }); controller.abort(); // same effect as req2.cancel() ``` ## Deduplication With `dedupe: true`, concurrent requests with the same method and fully-resolved URL share a single in-flight promise. The key is `method` plus the fully-resolved URL (`prefixUrl`, path params and merged `searchParams`, computed from the raw pre-validation values). The cache is scoped per instance, including instances created via `create()` with no arguments. ```ts const api = valifetch.create({ prefixUrl: 'https://api.example.com', dedupe: true, }); // One HTTP request, two callers const [a, b] = await Promise.all([api.get('/users/1'), api.get('/users/1')]); // Different resolved URLs: two separate requests await Promise.all([ api.get('/users', { searchParams: { page: 1 } }), api.get('/users', { searchParams: { page: 2 } }), ]); ``` ::: warning The key deliberately excludes headers, the request body and schemas. Two calls that differ only by header or body are collapsed into one in-flight request. Do not enable `dedupe` for such calls, and avoid it on non-idempotent methods (POST, PATCH, DELETE). Calling `.cancel()` on a deduped call aborts the single shared request for **every** caller waiting on it. ::: ## Priority `priority: 'high' | 'low' | 'auto'` is forwarded to `fetch` unchanged. It works on both instance and per-request options. ## Disabling validation ```ts // For a single request const data = await api.get('/data', { validateResponse: false }); // For every request on an instance const unsafeApi = valifetch.create({ validateResponse: false, validateRequest: false, }); ``` `validateRequest` covers `bodySchema`, `paramsSchema` and `searchSchema`; `validateResponse` covers `responseSchema`. ## Non-2xx responses By default a non-2xx status rejects with an `HTTP_ERROR`. Set `throwHttpErrors: false` to skip the status check; the response then goes through the normal parsing (and `responseSchema` validation, if set) like a successful one. See [Errors](https://haihv.github.io/valifetch/guide/errors.md). --- --- url: https://haihv.github.io/valifetch/guide/validation.md description: >- Validate response bodies, JSON request bodies, path params and search params with Valibot schemas, with full TypeScript type inference. --- # Validation valifetch validates four things with [Valibot](https://valibot.dev) schemas: | Option | Validates | `ValidationTarget` | |---|---|---| | `responseSchema` | The parsed response body | `'response'` | | `bodySchema` | The `json` request body | `'body'` | | `paramsSchema` | Path parameters (`params`) | `'params'` | | `searchSchema` | Search parameters (`searchParams`) | `'search'` | A failed schema rejects with a `ValifetchError` whose `code` is `VALIDATION_ERROR`. ## Response validation ```ts const user = await valifetch.get('https://api.example.com/users/1', { responseSchema: UserSchema, }); ``` The return type is `InferOutput`. Valibot transformations in the schema apply, so a schema that parses ISO strings into `Date` objects yields `Date` objects in the result. ## Request validation ```ts const newUser = await valifetch.post('https://api.example.com/users', { json: { name: 'John', email: 'john@example.com' }, bodySchema: CreateUserSchema, responseSchema: UserSchema, }); ``` When `bodySchema` is set, `json` is typed as the schema's **input** type. ::: tip `bodySchema` applies to `json` only. A raw `body` or a `form` body is never validated against it. ::: ## Path parameter inference The `:name` segments of a string-literal URL are extracted at the type level. With no `paramsSchema`, `params` must contain exactly those keys with `string | number` values: ```ts await valifetch.get('/users/:id/posts/:postId', { params: { id: 1, postId: 2 }, // both keys are required }); ``` With a `paramsSchema`, `params` is typed from the schema's input instead, and the schema runs before the URL is built: ```ts await valifetch.get('https://api.example.com/users/:id', { params: { id: 123 }, paramsSchema: v.object({ id: v.pipe(v.number(), v.integer(), v.minValue(1)), }), responseSchema: UserSchema, }); ``` The helper types `ExtractPathParams`, `PathParamsRecord` and `HasPathParams` are exported from `valifetch` and `valifetch/types`. Values are percent-encoded, and `.` / `..` throw a `TypeError`; see [Requests](https://haihv.github.io/valifetch/guide/requests.md#path-parameters). Encoding stops a param from changing the URL structure, but not an empty string or an unexpected ID, so validate untrusted params with `paramsSchema` (for example `v.pipe(v.string(), v.minLength(1))`). ## Search parameter validation ```ts const users = await valifetch.get('https://api.example.com/users', { searchParams: { page: 1, limit: 10, q: 'john' }, searchSchema: v.object({ page: v.optional(v.pipe(v.number(), v.integer())), limit: v.optional(v.pipe(v.number(), v.integer(), v.maxValue(100))), q: v.optional(v.string()), }), responseSchema: v.array(UserSchema), }); ``` ## Reading validation failures ```ts import { ValifetchError } from 'valifetch'; try { await api.get('/users/1', { responseSchema: UserSchema }); } catch (error) { if (error instanceof ValifetchError && error.isValidationError) { console.log(error.target); // 'response' | 'body' | 'params' | 'search' console.log(error.issues); // Valibot issues console.log(error.validation?.input); // the value that failed } } ``` `error.validation` is `{ target, issues, input }`. `error.request` and `error.response` are only set when `target === 'response'`. For `body`, `params` and `search` the `Request` does not exist yet, so `error.request` is `undefined`. ## Turning validation off `validateResponse: false` skips `responseSchema`; `validateRequest: false` skips `bodySchema`, `paramsSchema` and `searchSchema`. Both default to `true` and can be set per request or on an instance. See [Requests](https://haihv.github.io/valifetch/guide/requests.md#disabling-validation). ## Without a schema You can still get a result type without runtime validation by passing a generic: ```ts type User = { id: number; name: string }; const user = await valifetch.get('/users/1'); ``` This is a type assertion only. Prefer a schema for data you do not control. --- --- url: https://haihv.github.io/valifetch/guide/responses.md description: >- Choose how valifetch reads a response with responseType: JSON, text, Blob, ArrayBuffer, FormData, a stream, the raw Response, or server-sent events. --- # Responses `responseType` controls how the response body is read and what the call resolves to. It is set per request (see [API design decisions](https://haihv.github.io/valifetch/guide/api-design-decisions.md)). | `responseType` | Resolves to | |---|---| | `'json'` (default) | Parsed JSON, validated against `responseSchema` when given | | `'text'` | `string` | | `'blob'` | `Blob` | | `'arrayBuffer'` | `ArrayBuffer` | | `'formData'` | `FormData` | | `'stream'` | `ReadableStream` (`response.body`) | | `'raw'` | The raw `Response` object | | `'sse'` | `AsyncIterable` | ```ts // JSON (default) const data = await valifetch.get('https://api.example.com/data'); // Text const html = await valifetch.get('https://example.com', { responseType: 'text', }); // Blob const image = await valifetch.get('https://example.com/image.png', { responseType: 'blob', }); // Streaming: returns response.body as a ReadableStream const stream = await valifetch.get('https://example.com/large-file', { responseType: 'stream', }); // Raw Response object const response = await valifetch.get('https://example.com', { responseType: 'raw', }); ``` Parsing failures for `json`, `text`, `blob`, `arrayBuffer` and `formData` reject with a `PARSE_ERROR`. For `'sse'`, a pending (unterminated) event larger than `sseMaxEventSize` makes the iterator throw a `PARSE_ERROR` (see below). ## Server-sent events With `responseType: 'sse'` the call resolves to an async iterable of `MessageEvent`s. valifetch parses the SSE frame protocol internally. ```ts const events = await valifetch.get('https://api.example.com/stream', { responseType: 'sse', }); for await (const event of events) { console.log(event.type, event.data); // event.type defaults to 'message' } ``` Per the frame protocol, `event:` sets the event type, `data:` lines are joined into `event.data`, `id:` sets `lastEventId`, lines starting with `:` are comments and are ignored, and `retry:` is parsed but not yielded. It is a reconnect hint that does not apply to a one-shot fetch. `\n`, `\r` and `\r\n` line endings are all handled, including a `\r\n` pair split across two chunks. A line ending in `\r` is processed as soon as its chunk arrives, so a CR-only server's events are never held back waiting for the next chunk. Leaving the loop early (`break`, `return` or a throw) cancels the response body, which releases the connection. ### Event size limit The parser buffers at most `sseMaxEventSize` UTF-16 code units (default 16 MiB, 16,777,216) for a single not-yet-terminated event. The default is generous because real streams (for example AI responses carrying a base64 image) can put megabytes in one event. The cap is checked after each chunk against the pending (unterminated) event only: an event whose terminating blank line arrives in the same chunk is delivered whatever its size. A pending event larger than the cap cancels the stream and the iterator throws a `ValifetchError` with code `PARSE_ERROR`, so a server that never sends a blank line cannot exhaust memory. ```ts // Instance-wide cap const api = valifetch.create({ sseMaxEventSize: 1024 * 1024 }); // Per call (the per-call value wins); Infinity disables the cap const events = await api.get('/stream', { responseType: 'sse', sseMaxEventSize: Infinity, }); ``` A non-number, `NaN` or negative value falls back to the default. The option is ignored for every other `responseType`. See [SSE and AI streaming](https://haihv.github.io/valifetch/recipes/sse-streaming.md) for a complete example. ## Download progress `onDownloadProgress` is fired for each received chunk with a `DownloadProgressEvent`: ```ts type DownloadProgressEvent = { loaded: number; // bytes received so far total: number | undefined; // total bytes (undefined without a Content-Length header) percent: number | undefined; // 0-100 (undefined if total is unknown) }; ``` ```ts const data = await valifetch.get('https://api.example.com/large-file.json', { onDownloadProgress: ({ loaded, total, percent }) => { if (percent !== undefined) { console.log(`Downloaded ${percent.toFixed(1)}% (${loaded}/${total} bytes)`); } else { console.log(`Downloaded ${loaded} bytes`); } }, }); ``` ::: warning `onDownloadProgress` is not called when `responseType` is `'stream'`, `'raw'` or `'sse'`, because in those modes the caller takes direct ownership of the response body. ::: An instance-level `onDownloadProgress` (set on `create()` or inherited via `extend()`) works the same as the per-request option. There is no upload progress callback; see [File upload](https://haihv.github.io/valifetch/recipes/file-upload.md) for why. ## After parsing The [`afterParseResponse` hook](https://haihv.github.io/valifetch/guide/hooks.md#afterparseresponse) can transform the parsed value. It does not run for `'stream'`, `'raw'` or `'sse'`, and therefore never for `head()`. --- --- url: https://haihv.github.io/valifetch/guide/errors.md description: >- Handle valifetch failures with ValifetchError: typed codes for HTTP, validation, parse, timeout, abort and network errors, plus the parsed response body. --- # Errors Every failure that valifetch itself detects is thrown as a `ValifetchError`, an `Error` subclass with a typed `code`. See the generated [`ValifetchError` reference](https://haihv.github.io/valifetch/api/index/classes/ValifetchError.md). ```ts import { ValifetchError } from 'valifetch'; try { const user = await api.get('/users/1', { responseSchema: UserSchema }); } catch (error) { if (error instanceof ValifetchError) { switch (error.code) { case 'VALIDATION_ERROR': console.log('Validation failed:', error.validation?.issues); console.log('Target:', error.validation?.target); // 'response' | 'body' | 'params' | 'search' break; case 'HTTP_ERROR': console.log('HTTP error:', error.response?.status); console.log('Error body:', error.responseBody); // parsed JSON or plain text from the server break; case 'TIMEOUT_ERROR': console.log('Request timed out'); break; case 'NETWORK_ERROR': console.log('Network error:', error.message); break; case 'ABORT_ERROR': console.log('Request was cancelled'); break; case 'PARSE_ERROR': console.log('Failed to parse response:', error.message); break; } } } ``` ## Error codes | `ErrorCode` | Thrown when | Fields populated | |---|---|---| | `HTTP_ERROR` | Response status is non-2xx and `throwHttpErrors` is `true` | `request`, `response`, `responseBody` (parsed JSON, or text if not JSON) | | `PARSE_ERROR` | Reading or parsing the response body fails (`json`, `text`, `blob`, `arrayBuffer` or `formData`), or an SSE event exceeds `sseMaxEventSize` (thrown by the iterator) | `request`, `response`, `cause` (raw thrown value); `responseBody` = the unparseable raw text, JSON reads only | | `VALIDATION_ERROR` | A Valibot schema fails (`bodySchema`, `paramsSchema`, `searchSchema` or `responseSchema`) | `validation: { target, issues, input }`; `request`/`response` are only set when `target === 'response'` | | `TIMEOUT_ERROR` | The configured `timeout` elapses before a response | `request`, `cause` | | `ABORT_ERROR` | `.cancel()` or a caller `AbortSignal` aborts the request | `request`, `cause` | | `NETWORK_ERROR` | `fetch` itself throws (offline, DNS failure, etc.) | `request`, `cause` | For `body`, `params` and `search` validation failures the `Request` does not exist yet, so `error.request` is `undefined`. ## Convenience members * `error.status` and `error.statusText`, read from `error.response`. * `error.issues`, which is `error.validation?.issues ?? []`. * `error.target`, which is `error.validation?.target`. * Booleans: `isHttpError`, `isValidationError`, `isTimeoutError`, `isNetworkError`, `isAbortError`, `isParseError`. `cause` is typed `unknown`, matching the standard `Error.cause`, so non-`Error` throws pass through unwrapped. ## HTTP error bodies On a non-2xx response, valifetch reads the body and attaches it to `error.responseBody`: parsed JSON when the body is JSON, plain text otherwise. This is the right place to read server-side error details such as a `{ "code": "...", "message": "..." }` envelope. ```ts try { await api.post('/users', { json: payload }); } catch (error) { if (error instanceof ValifetchError && error.status === 422) { const details = v.parse(ApiErrorSchema, error.responseBody); // ... } } ``` ## beforeError The `beforeError` [hook](https://haihv.github.io/valifetch/guide/hooks.md#beforeerror) runs just before any `ValifetchError` is thrown, for every code. Use it to add context, normalise messages or report to an error tracker. ```ts const api = valifetch.create({ hooks: { beforeError: [ (error) => { error.message = `[api] ${error.message}`; return error; }, ], }, }); ``` ## Errors that are not ValifetchErrors A hook or a `shouldRetry` predicate that throws propagates its own error as-is, without wrapping, and aborts the request. Invalid input is rejected before any request is made, with a plain `TypeError` (or `Error`) rather than a `ValifetchError`, so `beforeError` does not see it: * More than one of `json`, `form` and `body` on a request (`TypeError`). * A path that resolves outside `prefixUrl`, for example `/../admin` (`TypeError`). * A `prefixUrl` containing a query string or fragment (`TypeError`). * A path param whose value is `.` or `..` (`TypeError`), or a missing / `null` / `undefined` path param (`Error`). * A `ReadableStream` `body` on a runtime that cannot stream request bodies, such as Firefox (`TypeError`). * A header name or value containing CR, LF or NUL (`TypeError`, from the platform `Headers` class). ## Standalone import If you only need the class, for example for `instanceof` checks in a module that never creates requests, import it from the lightweight subpath: ```ts import { ValifetchError } from 'valifetch/error'; ``` --- --- url: https://haihv.github.io/valifetch/guide/retry.md description: >- Configure valifetch retries: exponential backoff with jitter, status codes, methods, Retry-After handling, maxRetryAfter and a custom shouldRetry predicate. --- # Retry valifetch retries failed requests with exponential backoff and jitter. Retry applies to both HTTP error responses (matching `statusCodes`) and network-level errors (for example `TypeError: Failed to fetch`). ## Configuration ```ts const api = valifetch.create({ retry: { limit: 3, // Max retry attempts methods: ['GET', 'PUT'], // Methods to retry (also guards network-error retries) statusCodes: [408, 429, 500, 502, 503, 504], // Status codes to retry delay: (attempt) => Math.min(1000 * 2 ** attempt, 30000), // Backoff in ms maxRetryAfter: 120_000, // Wait for a server Retry-After of up to 2 minutes (default 60 s) // Custom predicate: overrides the statusCodes/methods verdict shouldRetry: async ({ reason, response }) => { // Network failures: retry POSTs too (this API is idempotent by request id) if (reason === 'network') return true; // Retry a 409 only when the server says the version was stale if (response.status === 409) { const body = await response.clone().json(); return body.code === 'STALE_VERSION'; } return undefined; // defer to statusCodes + methods }, }, }); // Or just set the limit const api2 = valifetch.create({ retry: 5 }); // Disable retry const api3 = valifetch.create({ retry: false }); ``` ## Defaults | Option | Default | |---|---| | `limit` | `2` | | `methods` | `['GET', 'PUT', 'HEAD', 'DELETE', 'OPTIONS']` | | `statusCodes` | `[408, 413, 429, 500, 502, 503, 504]` | | `delay(attempt)` | `0.3 * 2 ** attempt` seconds plus up to 20% random jitter, capped at 30 s (about 0.3 s, 0.6 s, 1.2 s, ...) | | `maxRetryAfter` | `60_000` (ms) | Non-idempotent methods such as `POST` and `PATCH` are not retried by default, to prevent duplicate submissions. The same `methods` guard applies to network-error retries. ::: warning Overriding `retry` replaces the whole object A per-request or child-instance (`extend()`) `retry` value **replaces** the instance `retry` object entirely. Its fields are not merged with the parent's, and any field you leave out takes the built-in default. Restate `maxRetryAfter` (or any other field you customised) when you override `retry`. ```ts const api = valifetch.create({ retry: { limit: 5, maxRetryAfter: 120_000 } }); // limit is 1 and maxRetryAfter is back to the 60 s default for this call await api.get('/users', { retry: { limit: 1 } }); ``` ::: ## Retry-After When a retryable response includes a `Retry-After` header (for example on a 429), valifetch waits the server-prescribed delay instead of the exponential backoff formula. Parsing is strict. The value is delay-seconds only when it is all digits after trimming (`Retry-After: 120`); otherwise it must be an HTTP-date (`Retry-After: Wed, 21 Oct 2015 07:28:00 GMT`; a past date means retry now). Anything else (`1.5`, `1e9`, `0x10`, `-1`, `5abc`) is ignored and the normal `delay` backoff applies. ### maxRetryAfter If the requested delay is longer than `retry.maxRetryAfter` (default `60_000` ms), valifetch does **not** retry. Retrying early would hammer a server that asked for a pause, and waiting would stall the client. The response is handled as if retries were exhausted: it throws an `HTTP_ERROR` through `beforeError`, or is returned as-is with `throwHttpErrors: false`. * The check runs after `shouldRetry` decides to retry and before `beforeRetry`, so no `beforeRetry` hook or `retry` debug event fires. * `maxRetryAfter: Infinity` waits for any value. A non-number, `NaN` or negative value falls back to the default. * Every retry sleep is clamped to the range 0 to 2^31 − 1 ms (the `setTimeout` limit, past which the timer would overflow and fire immediately), and a `NaN` delay becomes 0. ## shouldRetry `shouldRetry(context)` is a custom predicate consulted for every failed response and every network error. The context is: ```ts type RetryContext = { request: Request; retryCount: number; // 1-based: 1 = the first retry } & ( | { reason: 'status'; response: Response; error?: undefined } | { reason: 'network'; error: Error; response?: undefined } ); ``` Return `true` to retry even when `statusCodes` and `methods` would not, `false` to never retry this failure, or `undefined` to defer to the built-in status-code and method check. * It may be async. The response is passed unconsumed, so `response.clone().json()` is safe. * It is always bounded by `limit`. * It is never consulted for a successful (`response.ok`) response. * It runs **before** the `beforeRetry` hooks; returning `false` skips them entirely. * A predicate that throws aborts the request with that error. ## beforeRetry The [`beforeRetry` hook](https://haihv.github.io/valifetch/guide/hooks.md#beforeretry) runs before each retry is scheduled. It only runs for failures that are retryable under your config. Return the [`stop` sentinel](#the-stop-sentinel) to give up, a new `Request` to replace the request for the remaining attempts, or nothing to proceed with the normal backoff. ## The stop sentinel `stop` is exported from `valifetch` as `Symbol.for('valifetch.stop')`. Returning it from a `beforeRetry` hook aborts retrying and treats the original failure as final. Hooks run in order, and returning `stop` short-circuits the remaining ones. ```ts import valifetch, { stop } from 'valifetch'; const api = valifetch.create({ hooks: { beforeRetry: [ ({ response, retryCount }) => { // Give up early on a second 429 instead of waiting out the backoff if (retryCount > 1 && response?.status === 429) return stop; }, ], }, }); ``` ## Counter semantics The counters use different bases on purpose: | Value | Base | Meaning | |---|---|---| | `RetryOptions.delay(attempt)` | 0-based | `delay(0)` computes the first retry's delay | | `BeforeRetryState.retryCount` | 1-based | The retry about to be performed | | `RetryContext.retryCount` | 1-based | The retry about to be performed | | `DebugEvent` retry `attempt` | 1-based | The retry about to be performed | ## Retrying uploads Retries re-send the request body: the request is cloned before each attempt. A `ReadableStream` body is teed on clone, which buffers it in memory, so pass `retry: false` for large streamed uploads. See [Requests](https://haihv.github.io/valifetch/guide/requests.md#raw-body). --- --- url: https://haihv.github.io/valifetch/guide/hooks.md description: >- Intercept the valifetch request lifecycle with beforeRequest, afterResponse, afterParseResponse, beforeRetry and beforeError hooks. --- # Hooks Hooks are interceptors you register under the `hooks` option, as arrays of functions. There are five: | Hook | Signature | |---|---| | `beforeRequest` | `(request, options)` | | `afterResponse` | `(request, options, response)` | | `afterParseResponse` | `(data, response, request)` | | `beforeRetry` | `(state)` | | `beforeError` | `(error)` | Signatures are positional and deliberately aligned with ky 1.x's positional form (ky 2 moved to state objects) rather than a single unified state object. See [API design decisions](https://haihv.github.io/valifetch/guide/api-design-decisions.md). A hook that throws propagates that error as-is and aborts the request; it is never wrapped. On `extend()`, parent and child hooks are concatenated with the parent's first. See [Instances](https://haihv.github.io/valifetch/guide/instances.md#hooks-are-concatenated). ```ts import valifetch, { stop } from 'valifetch'; const api = valifetch.create({ prefixUrl: 'https://api.example.com', hooks: { beforeRequest: [ (request, options) => { console.log('Request:', request.method, request.url); // Optionally return a modified Request, or a Response to bypass fetch. // A Response returned here still flows through afterResponse (e.g. valifetch/mock). }, ], afterResponse: [ async (request, options, response) => { if (response.status === 401) { // Returning a new Response short-circuits the remaining afterResponse // hooks and replaces the original response for parsing/validation. const newToken = await refreshToken(); return fetch(request, { headers: { ...Object.fromEntries(request.headers), Authorization: `Bearer ${newToken}`, }, }); } return response; }, ], afterParseResponse: [ // Transform parsed data: unwrap a nested response (data) => data.data, // Add metadata from response headers (data, response) => ({ ...data, _meta: { totalCount: response.headers.get('X-Total-Count') }, }), ], beforeRetry: [ ({ request, response, retryCount }) => { // Give up early on a second 429 instead of waiting out the backoff if (retryCount > 1 && response?.status === 429) return stop; // Tag retried attempts so the server can detect duplicates return new Request(request, { headers: { ...Object.fromEntries(request.headers), 'x-retry-attempt': String(retryCount), }, }); }, ], beforeError: [ (error) => { error.message = `[api] ${error.message}`; return error; }, ], }, }); ``` ## beforeRequest `(request, options) => Request | Response | void`. Runs before each fetch. Return a modified `Request` to replace it, or a `Response` to bypass `fetch` entirely; a returned `Response` still flows through `afterResponse`. This is how [`valifetch/mock`](https://haihv.github.io/valifetch/recipes/testing.md) and the [auth helpers](https://haihv.github.io/valifetch/recipes/auth.md) work. The `beforeRequest` hooks run once per request, while `beforeRetry` hooks run inside the retry loop. ## afterResponse `(request, options, response) => Response | void`. Runs on the response before status checking and parsing. Returning a new `Response` short-circuits the remaining `afterResponse` hooks and replaces the original for parsing and validation. This is the place for a 401 refresh-and-replay; see [Authentication](https://haihv.github.io/valifetch/recipes/auth.md#refresh-on-401-with-afterresponse). ## afterParseResponse `(data, response, request) => data`. Runs after the body is parsed (and validated). Hooks chain: the output of one is the input of the next. It does **not** run for `responseType: 'stream' | 'raw' | 'sse'` (there is no parsed value to transform), and therefore never runs for `head()` either. ## beforeRetry `(state) => Request | typeof stop | void`. `state` is a `BeforeRetryState`: the [`RetryContext`](https://haihv.github.io/valifetch/guide/retry.md#shouldretry) plus `options`. Runs before each retry is scheduled, and only for failures that are retryable under your `retry` config (status codes, methods and limit, or a `shouldRetry` verdict). Return `stop` to abort retrying and treat the original failure as final; return a new `Request` to replace the request for all remaining attempts; return nothing to proceed with the normal backoff. Hooks run in order; returning `stop` short-circuits the rest. It does not run when a `Retry-After` header asks for longer than `retry.maxRetryAfter`, because that response is not retried; see [Retry](https://haihv.github.io/valifetch/guide/retry.md#maxretryafter). ## beforeError `(error) => ValifetchError`. Runs just before any `ValifetchError` is thrown: `HTTP_ERROR`, `VALIDATION_ERROR`, `PARSE_ERROR`, `TIMEOUT_ERROR`, `ABORT_ERROR` and `NETWORK_ERROR`. Each hook receives the error and must return it, either the same mutated instance or a replacement. Hooks chain: the output of one becomes the input of the next. `beforeError` only ever sees `ValifetchError`s. ## Execution order ``` valifetch.get(url, opts) -> buildRequest URL construction, path params, body/schema validation -> beforeRequest (hooks; may short-circuit with a Response) -> fetch + retry loop timeout, beforeRetry hooks inside the loop -> afterResponse -> status check throws HTTP_ERROR on 4xx/5xx with parsed responseBody -> parse + validate JSON parse and optional schema validation -> afterParseResponse -> beforeError (only when something threw) ``` --- --- url: https://haihv.github.io/valifetch/guide/debug.md description: >- Turn on valifetch debug mode for structured request lifecycle logging, with sensitive headers and query parameters redacted automatically. --- # Debug mode Enable structured lifecycle logging for development by passing `debug: true` (emits via `console.debug`) or a custom function. ```ts // Emit all events to console.debug const api = valifetch.create({ debug: true }); // Custom handler with full type safety on the event import type { DebugEvent } from 'valifetch/types'; const api2 = valifetch.create({ debug: (event: DebugEvent) => { if (event.type === 'request') { console.log('->', event.request.method, event.request.url); } else if (event.type === 'response') { console.log('<-', event.response.status, `(attempt ${event.attempt})`); } else if (event.type === 'retry') { console.log( `retry attempt ${event.attempt}, delay ${event.delay}ms, reason: ${event.reason}` ); } else if (event.type === 'cancel') { console.log('cancelled:', event.request.url); } }, }); ``` ## What `debug: true` logs `debug: true` logs a plain, redacted summary per event, not the raw `Request` and `Response` objects: ```ts console.debug('[valifetch]', { type: 'response', method: 'GET', url: 'https://api.example.com/users?access_token=[REDACTED]', headers: { authorization: '[REDACTED]', accept: 'application/json' }, attempt: 1, // response and retry events status: 200, // response events responseHeaders: { 'content-type': 'application/json' }, // response events // retry events carry `attempt`, `delay` and `reason` instead }); ``` The value of a header, or of a URL query parameter, is replaced with `'[REDACTED]'` when its name contains (case-insensitive) `auth`, `cookie`, `token`, `secret`, `key`, `session`, `pass`, `credential`, `sig`, `jwt`, `dpop`, `csrf`, `xsrf`, `otp`, `bearer` or `code`. That covers `Authorization`, `Cookie`, `Set-Cookie`, `X-Api-Key`, `?access_token=`, presigned-URL `X-Amz-Signature` and OAuth `?code=`. The match is deliberately broad, so some harmless names are redacted too. Only the logged summary is redacted; the request itself is unchanged. The URL path is logged as-is, so keep secrets out of paths. ::: warning Custom functions see everything A custom `debug` function receives the live `Request` and `Response` with headers unredacted. Redacting secrets before you log them is up to you. ::: ## Event types `DebugEvent` is a discriminated union. The `type` field narrows the payload. | `type` | Extra fields | |---|---| | `'request'` | `request: Request` | | `'response'` | `request`, `response: Response`, `attempt: number` | | `'retry'` | `request`, `attempt`, `delay: number`, `reason: 'status' \| 'network'` | | `'cancel'` | `request` | `debug` is inherited by child instances created with `extend()`. A child can override it by passing its own `debug` value. The `attempt` on a retry event is 1-based; see [Retry](https://haihv.github.io/valifetch/guide/retry.md#counter-semantics). --- --- url: https://haihv.github.io/valifetch/guide/typescript.md description: >- How valifetch infers TypeScript types from Valibot schemas, typed path params, and the public types exported from valifetch/types. --- # TypeScript valifetch infers types from your Valibot schemas. ```ts import * as v from 'valibot'; import valifetch from 'valifetch'; const UserSchema = v.object({ id: v.number(), name: v.string(), }); // Response type is inferred as { id: number; name: string } const user = await valifetch.get('/users/1', { responseSchema: UserSchema, }); // Or use a generic type without a schema (no runtime validation) type User = { id: number; name: string }; const user2 = await valifetch.get('/users/1'); // Path params are type-checked await valifetch.get('/users/:id/posts/:postId', { params: { id: 1, postId: 2 }, // TypeScript knows these are required }); ``` ## What gets inferred * **Response:** with `responseSchema`, the result is `InferOutput` of the schema; otherwise the generic `TData` (default `unknown`). * **Request body:** with `bodySchema`, `json` is typed as the schema's `InferInput`. * **Path params:** extracted from the URL string literal. With `paramsSchema`, typed from the schema's input. * **Return type by `responseType`:** `'blob'` gives `Blob`, `'text'` gives `string`, `'sse'` gives `AsyncIterable`, and so on. This also holds for callable calls like `api(url, { method: 'GET', responseType: 'blob' })`. ## Importing types All public types are available from the zero-runtime `valifetch/types` entry point: ```ts import type { ValifetchOptions, ValifetchInstance, RetryOptions, BeforeRequestHook, DebugEvent, } from 'valifetch/types'; ``` The root entry exports the core types you need day to day; `valifetch/types` is the superset, including `JwtRefreshOptions`, `MockCall`, `MockHandler` and `ValifetchMock`. See [Subpath imports](https://haihv.github.io/valifetch/guide/subpath-imports.md). ## Reference The [API reference](https://haihv.github.io/valifetch/api.md) lists every exported type with its documentation. --- --- url: https://haihv.github.io/valifetch/guide/subpath-imports.md description: >- Import only what you need from valifetch, valifetch/auth, valifetch/mock, valifetch/error and valifetch/types for minimal, tree-shaken bundles. --- # Subpath imports and tree-shaking valifetch is fully tree-shakeable. For minimal bundle size, import just what you need. ```ts // Main import: the core runtime import valifetch, { ValifetchError } from 'valifetch'; // Just the error class import { ValifetchError } from 'valifetch/error'; // Just the auth helpers (zero runtime cost if unused) import { bearerAuth, basicAuth, jwtRefresh } from 'valifetch/auth'; // Testing utilities (import in test files only) import { createMock } from 'valifetch/mock'; // Just types (no runtime code) import type { ValifetchOptions, RawBody, RetryOptions, RetryContext, BeforeRequestHook, BeforeRetryHook, BeforeRetryState, BeforeErrorHook, AfterResponseHook, AfterParseResponseHook, CallableInstance, } from 'valifetch/types'; ``` The package uses code splitting internally, so code shared between entry points is only loaded once. The package has `"sideEffects": false`. ## Entry points | Entry | Kind | Contents | |---|---|---| | `valifetch` | runtime | Core client, `ValifetchError`, `stop`, and the core types | | `valifetch/error` | runtime | `ValifetchError` and its option types | | `valifetch/types` | types only | Every public type | | `valifetch/auth` | runtime | `bearerAuth`, `basicAuth`, `jwtRefresh`, `JwtRefreshOptions` | | `valifetch/mock` | runtime | `createMock()` and the mock types | **Entry-point rule:** `valifetch` (`.`) exports the core runtime plus the core types you need day to day. `valifetch/types` is the superset: every public type, including the less common ones like `JwtRefreshOptions`, `MockCall`, `MockHandler` and `ValifetchMock`. `./error`, `./auth` and `./mock` are runtime subpaths. ::: info JSR On JSR, `.`, `./auth` and `./mock` are published: ```ts import valifetch, { ValifetchError } from 'jsr:@haihv/valifetch'; import { bearerAuth } from 'jsr:@haihv/valifetch/auth'; import { createMock } from 'jsr:@haihv/valifetch/mock'; ``` `./error` and `./types` are npm-only, because they only re-export symbols already exported from `.`, `./auth` or `./mock`, and re-exporting the same symbol from several JSR entry points duplicates it and lowers the documentation score. On JSR, import `ValifetchError` and the core types from `jsr:@haihv/valifetch`, `JwtRefreshOptions` from `jsr:@haihv/valifetch/auth`, and `MockCall`, `MockHandler` and `ValifetchMock` from `jsr:@haihv/valifetch/mock`. ::: ## Module resolution Subpath imports need TypeScript `moduleResolution` set to `"node16"`, `"nodenext"` or `"bundler"`. ## Dual format Every entry ships as both ESM and CommonJS, with matching type declarations. --- --- url: https://haihv.github.io/valifetch/guide/api-design-decisions.md description: >- Why valifetch names and shapes its API the way it does: searchParams vs params, json/form/body, per-call responseType and positional hooks. --- # API design decisions A few naming and ergonomics choices are intentional and locked for stability. They are documented here so the asymmetries do not read as accidental. * **`searchParams` vs `params`.** Query values use `searchParams` (plus `searchSchema`); path values use `params` (plus `paramsSchema`). The `searchParams` key deliberately mirrors the web platform's `URL.searchParams` / `URLSearchParams` and the equivalent option in ky, so the value key (`searchParams`) and its schema (`searchSchema`) use slightly different stems. Platform alignment is preferred over internal symmetry. * **`json` / `form` / `body`.** Structured bodies go through `json` (validated against `bodySchema`) or `form`; `body` is the raw escape hatch (string, `Blob`, `ArrayBuffer`, typed array, `ReadableStream`) sent as-is with no validation or `Content-Type` inference. Exactly one may be set per request; none is accepted at instance level. * **`responseType` is per-call only.** `responseType` lives on the per-request options, not on `create()` / `extend()` instance options. It changes the **return type** of a call (`'blob'` gives `Blob`, `'sse'` gives `AsyncIterable`, and so on), which cannot be expressed at instance-creation time without losing type safety. Set it on each call instead. * **`ValifetchError.cause` is `unknown`.** Matching the standard `Error.cause`, the `cause` option accepts any thrown value, not just an `Error`, so non-`Error` throws pass through without wrapping. * **Hook signatures stay positional, following ky 1.x.** (ky 2 moved to state-object arguments; valifetch deliberately does not.) `beforeRequest(request, options)`, `afterResponse(request, options, response)`, `afterParseResponse(data, response, request)`, `beforeRetry(state)` and `beforeError(error)` are not being unified into a single state-object signature. Matching ky's conventions is deliberate, and a hook that throws propagates that error as-is (never wrapped) to abort the request. `beforeError` only ever sees `ValifetchError`s. * **Entry-point rule.** `valifetch` (`.`) is the core runtime plus core types; `valifetch/types` is the superset of every public type; `./error`, `./auth` and `./mock` are runtime subpaths. JSR publishes `.`, `./auth` and `./mock` (disjoint symbol sets); `./error` and `./types` are npm-only because they only re-export symbols already in `.`, `./auth` or `./mock`. * **`options(url, requestOptions)`.** The HTTP-verb method is deliberately named `options` (matching the OPTIONS HTTP verb); its parameter is internally named `requestOptions` to avoid colliding with the method name. * **Retry counters use different bases on purpose.** `RetryOptions.delay(attempt)` is 0-based (`delay(0)` computes the first retry's delay). `BeforeRetryState.retryCount` and the `attempt` field on a `DebugEvent` of type `'retry'` are both 1-based: they describe "the retry about to be performed", which reads more naturally in hook and log code than a 0-based count would. See also [Versioning and stability](https://haihv.github.io/valifetch/guide/versioning.md). --- --- url: https://haihv.github.io/valifetch/guide/performance.md description: >- valifetch benchmark results against ky, ofetch and axios on Node.js 24, and the cost of schema validation. --- # Performance Benchmarked with Vitest's [benchmark API](https://vitest.dev/guide/benchmarking) on Node.js 24, with `fetch` mocked to eliminate network variance. Run `npm run bench` in the repository to reproduce on your machine. ::: tip Why is ofetch faster on the baseline? ofetch is a minimal wrapper with no built-in retry, hook system or schema validation. valifetch bundles all of that, so the gap reflects features, not inefficiency. Schema validation itself adds roughly 10-15% overhead over valifetch's own baseline. ::: ## GET + JSON parse (no schema) | Library | ops/sec | vs valifetch | |---|---|---| | ofetch | 192,529 | 1.86× faster | | **valifetch** | **103,649** | baseline | | up-fetch | 54,582 | 1.90× slower | | ky | 49,388 | 2.10× slower | | axios (fetch adapter) | 26,933 | 3.85× slower | ## GET + JSON parse + schema validation Only valifetch and up-fetch support schema validation natively. ky, ofetch and axios would require a manual parse step on top of their baseline cost. | Library | ops/sec | vs valifetch | |---|---|---| | **valifetch + valibot** | **90,743** | baseline | | up-fetch + valibot | 46,978 | 1.93× slower | ## POST with JSON body | Library | ops/sec | vs valifetch | |---|---|---| | ofetch | 139,527 | 1.89× faster | | **valifetch** | **73,777** | baseline | | up-fetch | 41,702 | 1.77× slower | | ky | 22,881 | 3.22× slower | | axios (fetch adapter) | 22,318 | 3.31× slower | ## 4xx error path | Library | ops/sec | vs valifetch | |---|---|---| | ofetch | 55,654 | 1.55× faster | | up-fetch | 49,698 | 1.39× faster | | **valifetch** | **35,792** | baseline | | ky | 27,038 | 1.32× slower | | axios (fetch adapter) | 11,666 | 3.07× slower | axios constructs a full `AxiosError` with a deep copy of the request config on every error, which explains the roughly 3× gap. Coming from another client? See the migration guides for [ky](https://haihv.github.io/valifetch/migration/from-ky.md) and [axios](https://haihv.github.io/valifetch/migration/from-axios.md). --- --- url: https://haihv.github.io/valifetch/guide/versioning.md description: >- valifetch follows semantic versioning from 1.0.0: what counts as a breaking change, which defaults are covered, and how deprecations work. --- # Versioning and stability From 1.0.0, valifetch follows [Semantic Versioning](https://semver.org). The public API is everything documented on this site (the guides, recipes and API reference) and in the repository README, in the JSDoc of the exports of `valifetch`, `valifetch/error`, `valifetch/types`, `valifetch/auth` and `valifetch/mock`, and in `llms.txt` / `AGENTS.md`. Anything else is internal. ## Major (breaking) changes * Removing or renaming any export of the five subpaths (`.`, `./error`, `./types`, `./auth`, `./mock`), or removing a subpath. * Changing a hook signature (the positional arguments of `beforeRequest`, `afterResponse`, `afterParseResponse`, `beforeRetry`, `beforeError`) or hook ordering semantics (parent hooks run before child hooks; hooks run in array order). * Renaming an option, or changing an option's type so that previously valid input is rejected at compile time or at runtime. * Changing a documented default: retry limit `2`, retry statuses `[408, 413, 429, 500–504]`, retry-eligible methods, `retry.maxRetryAfter` `60000` ms, `sseMaxEventSize` 16 MiB (16,777,216 UTF-16 code units), `throwHttpErrors: true`, no timeout unless `timeout` is set, and so on. * Removing or renaming a `ValifetchError` code, or changing which code a given failure produces (for example a failure that surfaced as `NETWORK_ERROR` now surfacing as `ABORT_ERROR`). * Changing the return type of an HTTP method, or the shape of a `ValifetchError` field. * Raising the minimum Node.js major (currently `>=22`). Dropping a Node.js version is a breaking change even when that version is end-of-life, so it only ships in a major release. This keeps `engines` a promise users can rely on within a major line. * Narrowing the `valibot` peer range (currently `>=1.0.0`), for example by dropping support for a valibot major. ## Minor (non-breaking) changes * New options, new exports, new hook types, new methods and new subpaths. * Widening accepted input (an option that accepts more types than before). * Adding a new `ValifetchError` code. A new code is observable by an exhaustive `switch` over `ErrorCode`, so code-based handling should keep a `default` branch. The addition is accepted in a minor release and announced in the changelog. A new code is never used for a failure that already produces an existing code; that would be a breaking change (see above). * Making types stricter so that they catch real runtime errors (for example a type that previously accepted an input that always threw at runtime). Stricter types that reject input which worked at runtime are major. * Raising the minimum supported TypeScript version. valifetch supports TypeScript versions released within the last two years; the floor moves only in a minor release and is announced in the changelog. ## Patch changes * Bug fixes, performance improvements and documentation updates. * Fixing behaviour that contradicted the documentation is a patch, even if some users depended on the buggy behaviour. The documentation (this site, the README, JSDoc and `llms.txt`) is the specification. ## Internal and undocumented Anything undocumented (for example the `opts`, `parent` and `merged` properties an instance carries), or whose name starts with `_`, is internal and not covered by semver. The same applies to the `dist/` file layout, chunk names, and the exact wording of error messages (match on `error.code`, not `error.message`). ## Deprecation process A feature is deprecated with a `@deprecated` JSDoc tag (naming the replacement) and a CHANGELOG note, in a minor release. It is removed no earlier than the next major release, and at least one minor release after the deprecation. ## See also * Release notes for every version are in the [changelog](https://github.com/haihv/valifetch/blob/main/CHANGELOG.md). * The deliberate API shape decisions that are locked for stability are summarised in [API design decisions](https://haihv.github.io/valifetch/guide/api-design-decisions.md). --- --- url: https://haihv.github.io/valifetch/guide/security.md description: >- valifetch security policy: supported versions, private vulnerability reporting and the threat model behind its hardening. --- # Security The security policy is in the repository: * [SECURITY.md](https://github.com/haihv/valifetch/blob/main/SECURITY.md): supported versions, how to report a vulnerability privately, and the full threat model. Please do not report vulnerabilities in public issues. Use GitHub's [private vulnerability reporting](https://github.com/haihv/valifetch/security/advisories/new) instead. ## What valifetch guarantees A summary; SECURITY.md has the exact rules. * **Prefix containment.** With `prefixUrl` set, the final URL keeps the prefix origin and its path stays under the prefix path. Absolute inputs such as `https://evil.com` or `//evil.com` become path segments under the prefix, and a path that climbs above it with `..` (including `%2e%2e`) throws a `TypeError`. A `prefixUrl` containing `?` or `#` also throws a `TypeError`. See [Requests](https://haihv.github.io/valifetch/guide/requests.md#prefixurl). * **Path-param encoding.** `params` values are percent-encoded, so they cannot add path segments, a query string or a fragment. The values `.` and `..` throw a `TypeError`, and params are read as own properties only. See [Requests](https://haihv.github.io/valifetch/guide/requests.md#path-parameters). * **No header injection.** Header names and values containing CR, LF or NUL are rejected by the platform `Headers` class with a `TypeError` before the request is sent. * **Prototype-pollution-safe merging.** `create()` / `extend()` assign user-supplied keys as own data properties, so a JSON-derived `__proto__` key cannot change a prototype. * **No secrets in built-in logs.** [`debug: true`](https://haihv.github.io/valifetch/guide/debug.md) logs a summary with sensitive header and query-parameter values replaced by `[REDACTED]`. * **Bounded parsing of untrusted responses.** The SSE parser caps the pending (unterminated) event at [`sseMaxEventSize`](https://haihv.github.io/valifetch/guide/responses.md#server-sent-events) (default 16 MiB). `Retry-After` is parsed strictly, and a delay longer than [`retry.maxRetryAfter`](https://haihv.github.io/valifetch/guide/retry.md#retry-after) (default 60 s) is not retried rather than waited for. Retries are always bounded by `retry.limit`. ## What is your responsibility * **User-controlled full URLs (SSRF).** Without `prefixUrl`, valifetch requests whatever URL it is given. Validate any user-supplied URL against an allow-list of schemes and hosts. * **Where credentials go.** Auth hooks attach credentials to every request of their instance, including full URLs on other hosts. Keep credentialed instances behind a `prefixUrl`. * **Custom `debug` functions** receive the live, unredacted `Request` and `Response`. * **Response size.** JSON, text, blob and error bodies are read fully into memory, as with plain `fetch`. Use a `timeout`, or `responseType: 'stream'` with your own byte limit, for untrusted responses. * **[`dedupe`](https://haihv.github.io/valifetch/guide/requests.md#deduplication)** keys on method and URL only. Do not use it for calls that differ by headers (for example per-user tokens) or body. --- --- url: https://haihv.github.io/valifetch/recipes/auth.md description: >- Add bearer token, HTTP basic or JWT refresh authentication to valifetch with the bearerAuth, basicAuth and jwtRefresh hooks from valifetch/auth. --- # Authentication The `valifetch/auth` subpath ships three `beforeRequest` hook factories for the most common auth patterns. They are zero-cost if unused (tree-shaken out entirely) and each returns a plain `BeforeRequestHook`, so they compose freely with any other hooks. ```ts import valifetch from 'valifetch'; import { bearerAuth, basicAuth, jwtRefresh } from 'valifetch/auth'; ``` On Deno or other JSR consumers, import from `jsr:@haihv/valifetch/auth`. ## bearerAuth Reads the token on every request, so a rotated token is picked up automatically. If the getter returns `null` or `undefined`, no header is set. ```ts const api = valifetch.create({ prefixUrl: 'https://api.example.com', hooks: { beforeRequest: [bearerAuth(() => localStorage.getItem('token'))] }, }); ``` ## basicAuth HTTP Basic auth. The credentials are UTF-8 encoded once, at creation time. ```ts const adminApi = valifetch.create({ prefixUrl: 'https://api.example.com', hooks: { beforeRequest: [basicAuth('admin', 's3cr3t')] }, }); ``` Read secrets from your environment or a secret store; do not hardcode them. ## jwtRefresh Proactive refresh. Before each request it reads the current token; if there is none or it is expired, it calls `refresh()`, then sets the `Authorization` header. Concurrent requests share a single in-flight refresh, so only one refresh call is made. ```ts const authApi = valifetch.create({ prefixUrl: 'https://api.example.com', hooks: { beforeRequest: [ jwtRefresh({ getToken: () => store.accessToken, isExpired: (token) => isJwtExpired(token), refresh: () => authApi.post('/auth/refresh').then((r) => r.token), onRefreshed: (token) => store.setToken(token), }), ], }, }); ``` The options (`JwtRefreshOptions`) are: | Option | Type | Purpose | |---|---|---| | `getToken` | `() => string \| null \| undefined` | Returns the current access token | | `isExpired` | `(token: string) => boolean` | Whether the token needs refreshing | | `refresh` | `() => Promise` | Obtains a new token | | `onRefreshed` | `(token: string) => void \| Promise` (optional) | Persist the new token | ::: warning Avoid a refresh loop In the example above, the refresh call goes through `authApi` itself, so the `/auth/refresh` request would also trigger `jwtRefresh`. Make sure `getToken` / `isExpired` do not report the refresh endpoint as needing a token, or call refresh through a separate instance that does not have the hook. ::: ## Refresh on 401 with afterResponse When you cannot know expiry up front, react to the 401 instead: an `afterResponse` hook can fetch a new token and replay the request. Returning a `Response` replaces the original for parsing and validation, and short-circuits the remaining `afterResponse` hooks. ```ts import valifetch from 'valifetch'; import { bearerAuth } from 'valifetch/auth'; let accessToken = loadToken(); const api = valifetch.create({ prefixUrl: 'https://api.example.com', hooks: { beforeRequest: [bearerAuth(() => accessToken)], afterResponse: [ async (request, _options, response) => { if (response.status !== 401) return response; accessToken = await refreshAccessToken(); // Replay the original request with the new token const headers = new Headers(request.headers); headers.set('Authorization', `Bearer ${accessToken}`); return fetch(request, { headers }); }, ], }, }); ``` The replayed response flows through the rest of the pipeline: the status check, parsing, schema validation, and `afterParseResponse`. To avoid several concurrent 401s each starting a refresh, share the refresh promise: ```ts let refreshing: Promise | null = null; function refreshOnce(): Promise { refreshing ??= refreshAccessToken().finally(() => { refreshing = null; }); return refreshing; } ``` ::: tip `request` in the hook may already have been sent, so a body that is a `ReadableStream` cannot be replayed. For JSON bodies, `fetch(request, ...)` on the hook's request works because valifetch clones requests before sending. ::: --- --- url: https://haihv.github.io/valifetch/recipes/sse-streaming.md description: >- Consume server-sent events and AI token streams, such as OpenAI-style chat completions, with valifetch responseType sse as an async iterable. --- # SSE and AI streaming `responseType: 'sse'` resolves to an `AsyncIterable`. valifetch parses the server-sent events frame protocol for you, so there is no manual chunk decoding. ## Basic consumption ```ts const events = await valifetch.get('https://api.example.com/stream', { responseType: 'sse', }); for await (const event of events) { console.log(event.type, event.data); // event.type defaults to 'message' } ``` Each `MessageEvent` has `type` (from `event:`, default `'message'`), `data` (multiple `data:` lines joined), and `lastEventId` (from `id:`). Comment lines and `retry:` hints are consumed but not yielded. ## Consuming an OpenAI-style event stream Chat completion APIs stream JSON chunks as SSE `data:` frames and end with a literal `[DONE]` sentinel. Validate each chunk with Valibot: ```ts import valifetch from 'valifetch'; import * as v from 'valibot'; const ChunkSchema = v.object({ choices: v.array( v.object({ delta: v.object({ content: v.optional(v.string()) }), }) ), }); const api = valifetch.create({ prefixUrl: 'https://api.openai.com/v1', headers: { Authorization: `Bearer ${process.env.OPENAI_API_KEY}` }, }); async function streamCompletion(prompt: string): Promise { const events = await api.post('/chat/completions', { json: { model: 'gpt-4o-mini', stream: true, messages: [{ role: 'user', content: prompt }], }, responseType: 'sse', }); let text = ''; for await (const event of events) { if (event.data === '[DONE]') break; const chunk = v.parse(ChunkSchema, JSON.parse(event.data)); const piece = chunk.choices[0]?.delta.content ?? ''; text += piece; process.stdout.write(piece); } return text; } ``` The model name and chunk shape belong to the provider's API; adjust them to the service you call. The pattern is the same for any provider that streams JSON over SSE. The `break` on `[DONE]` is safe: leaving the `for await` loop early (`break`, `return` or a throw) cancels the response body, so the connection is released even if the server keeps the stream open. ## Cancelling a stream Pass an `AbortSignal` to stop a stream from the outside, or call `.cancel()` on the request promise before it resolves. ```ts const controller = new AbortController(); const events = await api.post('/chat/completions', { json: { model: 'gpt-4o-mini', stream: true, messages }, responseType: 'sse', signal: controller.signal, }); setTimeout(() => controller.abort(), 5_000); try { for await (const event of events) { // ... } } catch (error) { // Aborting mid-stream ends the iteration with an error; handle it here } ``` ## Things to know * `timeout` is cleared as soon as the response headers arrive, so it does not cut off a long-lived stream. Use a signal to stop one. * A single event is capped at `sseMaxEventSize` UTF-16 code units (default 16 MiB). A larger one cancels the stream and throws a `PARSE_ERROR`. Raise it (or pass `Infinity`) for providers that send very large events; see [Responses](https://haihv.github.io/valifetch/guide/responses.md#event-size-limit). * `onDownloadProgress` and `afterParseResponse` do not run for `'sse'`. The caller owns the body. * Retries apply to establishing the connection (a failed status or network error), not to an interrupted stream. Resuming from `lastEventId` is up to you. --- --- url: https://haihv.github.io/valifetch/recipes/testing.md description: >- Mock valifetch requests in Vitest or Jest with createMock() from valifetch/mock: fixture responses, call inspection, no global fetch patching. --- # Mocking in tests The `valifetch/mock` subpath provides `createMock()`, a lightweight mock that intercepts requests through the `beforeRequest` hook. It does not patch `globalThis.fetch`, and it works in Vitest and Jest. Import it in test files only. On Deno or other JSR consumers, import from `jsr:@haihv/valifetch/mock`. ```ts import { createMock } from 'valifetch/mock'; import valifetch from 'valifetch'; const mock = createMock(); // Register fixture responses mock.get('/users').reply(200, [{ id: 1, name: 'Alice' }]); mock.post('/users').reply(201, { id: 2, name: 'Bob' }); // Attach to an instance const api = valifetch.extend({ hooks: mock.hooks }); // Make requests normally: matched routes never reach the network const users = await api.get('https://api.example.com/users'); ``` Because the mock is a hook, a mocked `Response` still flows through the real pipeline: status checking, parsing, schema validation and `afterResponse` hooks all run, so your tests exercise your schemas too. ## Handlers `get`, `post`, `put`, `patch`, `delete`, `head` and `options` register a handler for that method; `when(method, pattern)` takes `'*'` for any method. Each returns a `MockHandler` with `reply` and `replyOnce`. ```ts mock.get('/users/:id').reply(200, { id: 1 }); // :param wildcard mock.get('/files/*').reply(200, { file: true }); // * wildcard mock.get(/\/posts\/\d+$/).reply(200, { post: true }); // RegExp, tested against the full URL mock.when('*', '/ping').reply(200, { ok: true }); // any method ``` `reply(status, body?, headers?)` registers a permanent fixture. Bodies are always `JSON.stringify`-serialised. Omit the body for a bodyless response such as a 204. Status codes that must not carry a body per the HTTP spec (101, 204, 205, 304) always produce a bodyless response regardless of the `body` argument. ## Response queuing with replyOnce `replyOnce` registers a response that is consumed on its first match. Combine it with `reply` to script a sequence across consecutive calls: ```ts mock .get('/flaky') .replyOnce(503, { error: 'Service Unavailable' }) // first call -> 503 .reply(200, { data: 'ok' }); // subsequent calls -> 200 ``` ::: warning Mocks bypass the retry loop The mock answers from a `beforeRequest` hook, which runs once per call before the fetch-and-retry loop. A mocked 503 is therefore **not** retried by the `retry` option; each call to `api.get()` consumes one queued response. Test your own retry-at-the-call-site logic with `replyOnce`, and test valifetch's retry behaviour against a real server or a stubbed `fetch`. ::: ## Asserting on calls ```ts const call = mock.lastCall(); console.log(call?.method); // 'GET' console.log(call?.url); // 'https://api.example.com/users' console.log(call?.headers); // { 'content-type': 'application/json', ... } console.log(call?.body); // parsed request body (JSON object, string, or null) console.log(call?.searchParams); // URLSearchParams mock.calls(); // all recorded calls in order mock.lastCall(); // last recorded call, or undefined ``` Each `MockCall` has `method`, `url`, `headers`, `body` and `searchParams`. ## Resetting between tests ```ts import { afterEach } from 'vitest'; afterEach(() => { mock.reset(); // clears handlers and recorded calls }); ``` ## A complete test ```ts import { beforeEach, expect, it } from 'vitest'; import valifetch from 'valifetch'; import { createMock } from 'valifetch/mock'; import * as v from 'valibot'; const UserSchema = v.object({ id: v.number(), name: v.string() }); const mock = createMock(); const api = valifetch.extend({ hooks: mock.hooks }); beforeEach(() => mock.reset()); it('creates a user', async () => { mock.post('/users').reply(201, { id: 2, name: 'Bob' }); const user = await api.post('https://api.example.com/users', { json: { name: 'Bob' }, responseSchema: UserSchema, }); expect(user).toEqual({ id: 2, name: 'Bob' }); expect(mock.lastCall()?.body).toEqual({ name: 'Bob' }); }); it('rejects a response that does not match the schema', async () => { mock.get('/users/1').reply(200, { id: 'nope' }); await expect( api.get('https://api.example.com/users/1', { responseSchema: UserSchema }) ).rejects.toMatchObject({ code: 'VALIDATION_ERROR' }); }); ``` See the [`valifetch/mock` API reference](https://haihv.github.io/valifetch/api/mock.md) for the full type definitions. --- --- url: https://haihv.github.io/valifetch/recipes/pagination.md description: >- Paginate APIs with valifetch: cursor-based and Link-header pagination with async generators, every page validated by a Valibot schema. --- # Pagination Two common shapes: a cursor in the response body, and a `Link` header. Both are plain loops, and both keep every page validated. ## Cursor pagination Describe one page with a schema, then loop until the server stops returning a cursor. An async generator lets callers stop early. ```ts import valifetch from 'valifetch'; import * as v from 'valibot'; const api = valifetch.create({ prefixUrl: 'https://api.example.com' }); const ItemSchema = v.object({ id: v.number(), name: v.string() }); const PageSchema = v.object({ items: v.array(ItemSchema), nextCursor: v.nullable(v.string()), }); type Item = v.InferOutput; async function* listItems(pageSize = 50): AsyncGenerator { let cursor: string | null = null; do { const page = await api.get('/items', { searchParams: { limit: pageSize, cursor }, responseSchema: PageSchema, }); yield* page.items; cursor = page.nextCursor; } while (cursor !== null); } for await (const item of listItems()) { console.log(item.name); } ``` `searchParams` entries set to `null` or `undefined` are omitted, so the first request goes out without a `cursor`. To collect everything: ```ts const all: Item[] = []; for await (const item of listItems()) all.push(item); ``` ## Link-header pagination APIs such as GitHub's put the next URL in a `Link` header. Use `responseType: 'raw'` to get the `Response`, read the header, then validate the body yourself: ```ts import valifetch from 'valifetch'; import * as v from 'valibot'; const RepoSchema = v.object({ id: v.number(), full_name: v.string() }); const ReposSchema = v.array(RepoSchema); type Repo = v.InferOutput; function nextUrl(response: Response): string | undefined { const link = response.headers.get('link'); const match = link?.match(/<([^>]+)>;\s*rel="next"/); return match?.[1]; } async function* listRepos(org: string): AsyncGenerator { let url: string | undefined = `https://api.github.com/orgs/${org}/repos?per_page=100`; while (url) { const response = await valifetch.get(url, { responseType: 'raw' }); yield* v.parse(ReposSchema, await response.json()); url = nextUrl(response); } } ``` The `next` URL is absolute and already carries its query string, so pass it straight to `valifetch.get` without a `prefixUrl`. If you use an instance with a `prefixUrl`, strip the origin and the prefix path first: valifetch joins the input under the prefix, so a full URL would become a path segment, and a path that leaves the prefix path throws a `TypeError`. ::: warning Trust the next URL only from the API you called A `Link` header is server-controlled. If your requests carry credentials, check that the next URL stays on the expected origin before following it. ::: ## Tips * Combine pagination with [`retry`](https://haihv.github.io/valifetch/guide/retry.md): a transient 503 on page 7 is retried without restarting the loop. * Pass the same `signal` to every page request so a single `AbortController` stops the whole iteration. * Use a `searchSchema` when the pagination parameters themselves come from user input. --- --- url: https://haihv.github.io/valifetch/recipes/parallel-requests.md description: >- Run valifetch requests in parallel with all() and allSettled(): tuple-typed results and cancellation of the whole batch. --- # Parallel requests Every instance has `all()` and `allSettled()`. They are sugar over `Promise.all` and `Promise.allSettled` with two additions: element types are preserved as a tuple, and the result is cancellable. ## all `all()` runs requests in parallel and resolves to a tuple of their results. It rejects as soon as any request rejects. ```ts const [user, posts] = await api.all([ api.get('/users/1', { responseSchema: UserSchema }), api.get('/posts', { responseSchema: PostsSchema }), ]); // user: User, posts: Post[] ``` ::: warning A rejection does **not** cancel the remaining in-flight requests. If you need that, call `.cancel()` on the batch or use an `AbortController`. ::: ## allSettled `allSettled()` waits for every request to settle and never rejects. Each result is a standard `PromiseSettledResult`: `{ status: 'fulfilled', value }` or `{ status: 'rejected', reason }`, where `reason` is typically a `ValifetchError`. ```ts import { ValifetchError } from 'valifetch'; const results = await api.allSettled([api.get('/a'), api.get('/b')]); for (const result of results) { if (result.status === 'fulfilled') { console.log(result.value); } else if (result.reason instanceof ValifetchError) { console.error(result.reason.code, result.reason.status); } } ``` ## Cancelling a batch Both return a `CancellablePromise`. Calling `.cancel()` aborts every input that exposes a `.cancel()` method (other valifetch requests) and silently ignores plain promises. ```ts const batch = api.all([api.get('/a'), api.get('/b')]); batch.cancel(); // aborts both in-flight requests ``` ## Sharing one signal For a fail-fast batch that stops the siblings on the first error, share an `AbortController`: ```ts const controller = new AbortController(); try { const [a, b] = await api.all([ api.get('/a', { signal: controller.signal }), api.get('/b', { signal: controller.signal }), ]); } catch (error) { controller.abort(); // stop whatever is still running throw error; } ``` ## Limiting concurrency `all()` starts everything at once. For long lists, process them in chunks: ```ts async function inChunks( items: T[], size: number, run: (item: T) => Promise ): Promise { const results: R[] = []; for (let i = 0; i < items.length; i += size) { const chunk = items.slice(i, i + size); results.push(...(await Promise.all(chunk.map(run)))); } return results; } const users = await inChunks(ids, 10, (id) => api.get('/users/:id', { params: { id }, responseSchema: UserSchema }) ); ``` --- --- url: https://haihv.github.io/valifetch/recipes/file-upload.md description: >- Upload files with valifetch: multipart FormData, raw Blob, ArrayBuffer and ReadableStream bodies, and why fetch has no upload progress. --- # File upload ## Multipart upload Pass a `FormData` as `form`. The `Content-Type` is set automatically with the correct multipart boundary; do not set it yourself. ```ts const formData = new FormData(); formData.append('file', file); formData.append('name', 'avatar'); const result = await api.post('/upload', { form: formData, timeout: 60_000, // generous timeout for a large file responseSchema: UploadResultSchema, }); ``` `form` also accepts `URLSearchParams` or a plain string record, which are sent as `application/x-www-form-urlencoded`. ## Raw bytes and streams For a binary payload that is not a form, use the raw `body` option and set the `Content-Type` yourself: ```ts await api.put('/blobs/abc', { body: new Blob([bytes]), headers: { 'content-type': 'application/octet-stream' }, }); // A ReadableStream body: `duplex: 'half'` is added automatically await api.put('/blobs/abc', { body: fileStream, headers: { 'content-type': 'application/octet-stream' }, }); ``` Streaming request bodies need runtime support: Node 22+, Deno and Chromium-based browsers (over HTTP/2 or newer) stream them; other engines vary. Firefox does not support them, and there valifetch throws a `TypeError` before calling `fetch` rather than letting the browser silently send `[object ReadableStream]`. Pass a `Blob`, `ArrayBuffer` or string on such runtimes. Retries re-send the body. A `ReadableStream` is teed on clone, which buffers it in memory, so pass `retry: false` for large streamed uploads. PUT is retried by default and POST is not; see [Retry](https://haihv.github.io/valifetch/guide/retry.md). ## Progress valifetch supports **download** progress only (`onDownloadProgress`, see [Responses](https://haihv.github.io/valifetch/guide/responses.md#download-progress)). It has no upload progress option. The reason is the platform: native `fetch`, which valifetch is built on, does not expose upload progress events. The only way to observe upload progress is an `XMLHttpRequest`, which valifetch deliberately does not use, since the library is built on `fetch` end to end. If you need an upload progress bar: * Use `XMLHttpRequest` (or a library that wraps it) for that specific upload and keep valifetch for everything else. * Or, where your runtime supports streaming request bodies, count the bytes of a `ReadableStream` body as it is consumed: ```ts function withProgress( stream: ReadableStream, onProgress: (sentBytes: number) => void ): ReadableStream { let sent = 0; return stream.pipeThrough( new TransformStream({ transform(chunk, controller) { sent += chunk.byteLength; onProgress(sent); controller.enqueue(chunk); }, }) ); } await api.put('/blobs/abc', { body: withProgress(fileStream, (n) => console.log(`${n} bytes handed to fetch`)), headers: { 'content-type': 'application/octet-stream' }, retry: false, }); ``` ::: warning Caveats of the streaming approach The count is bytes handed to `fetch`, not bytes acknowledged by the server. Streaming request bodies are not supported by every browser or protocol version (Firefox has no support, where valifetch throws a `TypeError`; Chromium requires HTTP/2 or newer), and you lose the `Content-Length` header, which some servers require. Test it against your target runtimes and servers. ::: --- --- url: https://haihv.github.io/valifetch/migration/from-ky.md description: >- Migrate from ky to valifetch: option and hook mapping for ky 1.x and 2.x, parsed-data return values and Valibot validation. --- # Migrating from ky valifetch is deliberately close to [ky](https://github.com/sindresorhus/ky): both wrap native `fetch`, both have instances, retries and hooks. The biggest differences are that valifetch **returns parsed data** instead of a response promise with `.json()`, and that it **validates** with Valibot. ::: info Versions Option names below are shown for ky 1.x and ky 2.x where they differ. ky 2 renamed `prefixUrl` to `prefix` and moved its hooks to state-object arguments; valifetch's hooks use the positional signatures ky 1 had. ::: ## The shape of a call ::: code-group ```ts [ky] import ky from 'ky'; const user = await ky.get('https://api.example.com/users/1').json(); ``` ```ts [valifetch] import valifetch from 'valifetch'; const user = await valifetch.get('https://api.example.com/users/1', { responseSchema: UserSchema, // validated and typed }); // or, without validation: const user2 = await valifetch.get('https://api.example.com/users/1'); ``` ::: | ky | valifetch | |---|---| | `.json()` | Default; the call resolves to the parsed JSON | | `.text()` | `responseType: 'text'` | | `.blob()` | `responseType: 'blob'` | | `.arrayBuffer()` | `responseType: 'arrayBuffer'` | | `.formData()` | `responseType: 'formData'` | | The `Response` itself (`await ky(...)`) | `responseType: 'raw'` | | `response.body` | `responseType: 'stream'` | | `ky.create()` / `ky.extend()` | `valifetch.create()` / `instance.extend()` | | `ky(url, options)` | `instance.callable()` then `api(url, options)` | ## Options | ky | valifetch | Notes | |---|---|---| | `prefixUrl` (ky 1) / `prefix` (ky 2) | `prefixUrl` | Paths always stay under it: absolute inputs become path segments, a `..` escape throws a `TypeError`, and a prefix with `?` or `#` throws | | `searchParams` | `searchParams` | Same name. Instance values merge with per-request values; `undefined` / `null` removes a key | | `json` | `json` | Optionally validated by `bodySchema` | | `body` (string, `Blob`, stream, `FormData`, ...) | `body` for raw payloads, `form` for `FormData` / `URLSearchParams` | `json`, `form` and `body` are mutually exclusive | | `headers` | `headers` | | | `timeout` | `timeout` | `0` disables it (ky uses `false`) | | `retry: number` / `retry: { limit, methods, statusCodes }` | `retry: number` / `retry: { limit, methods, statusCodes }` | Same names | | `retry.delay(attemptCount)` | `retry.delay(attempt)` | 0-based; returns milliseconds | | `retry.shouldRetry` | `retry.shouldRetry` | See [Retry](https://haihv.github.io/valifetch/guide/retry.md#shouldretry) for the context shape | | `retry.maxRetryAfter` | `retry.maxRetryAfter` | Behaviour differs: ky clamps the wait to `maxRetryAfter` and still retries; valifetch skips the retry and surfaces the response (an `HTTP_ERROR`, or the response with `throwHttpErrors: false`). valifetch defaults to `60_000` ms. See [Retry](https://haihv.github.io/valifetch/guide/retry.md#maxretryafter) | | `retry.backoffLimit`, `retry.jitter`, `retry.retryOnTimeout`, `retry.afterStatusCodes` | none | valifetch caps the default backoff at 30 s, adds 20% jitter, and honours `Retry-After` | | `throwHttpErrors: boolean` | `throwHttpErrors: boolean` | valifetch does not accept a function | | `hooks` | `hooks` | See below | | `onDownloadProgress` | `onDownloadProgress` | Event is `{ loaded, total, percent }` | | `onUploadProgress` (ky 2) | none | See [File upload](https://haihv.github.io/valifetch/recipes/file-upload.md) | | `signal` | `signal`, plus `.cancel()` on the returned promise | | | `totalTimeout`, `maxResponseSize`, `parseJson`, `stringifyJson`, `fetch`, `context` | none | | | (none) | `responseSchema`, `bodySchema`, `paramsSchema`, `searchSchema` | Validation | | (none) | `params` with `:name` path segments | | | (none) | `dedupe`, `debug`, `priority`, `sseMaxEventSize` | | ## Hooks The five hook names match ky's, with the addition of `afterParseResponse`. valifetch hooks are plain arrays and use positional arguments. | ky 1 hook | ky 2 hook argument | valifetch | |---|---|---| | `beforeRequest(request, options)` | `({ request, options, retryCount })` | `beforeRequest(request, options)` | | `afterResponse(request, options, response)` | `({ request, options, response, retryCount })` | `afterResponse(request, options, response)` | | `beforeRetry({ request, options, error, retryCount })` | same state object | `beforeRetry(state)` where `state` is a `RetryContext` plus `options` | | `beforeError(error)` | `({ error, ... })` | `beforeError(error)`, receives `ValifetchError` only | | (none) | (none) | `afterParseResponse(data, response, request)` | | `init` hooks | `init` hooks | none | Differences that matter: * **Short-circuiting `beforeRetry`.** Return the exported `stop` sentinel to give up retrying. Returning a `Request` replaces the request for the remaining attempts. * **`beforeRequest` runs once per call.** `beforeRetry` runs inside the retry loop. * **Returning a `Response` from `beforeRequest`** bypasses `fetch` (valifetch's `valifetch/mock` is built on this) and still flows through `afterResponse`. * **Hooks concatenate on `extend()`**, parent first. * **Hook errors propagate unwrapped.** ## Errors | ky | valifetch | |---|---| | `HTTPError` (`error.response`) | `ValifetchError` with `code: 'HTTP_ERROR'`; `error.response`, `error.status`, and the already-parsed `error.responseBody` | | `TimeoutError` | `code: 'TIMEOUT_ERROR'` | | network `TypeError` | `code: 'NETWORK_ERROR'` | | `AbortError` | `code: 'ABORT_ERROR'` | | a JSON parse failure | `code: 'PARSE_ERROR'` | | (none) | `code: 'VALIDATION_ERROR'` with `error.validation = { target, issues, input }` | ```ts // ky try { await ky.post(url, { json }).json(); } catch (error) { if (error instanceof HTTPError) { const body = await error.response.json(); } } // valifetch: the body is already parsed try { await valifetch.post(url, { json }); } catch (error) { if (error instanceof ValifetchError && error.isHttpError) { const body = error.responseBody; } } ``` ## A worked example ::: code-group ```ts [ky] const api = ky.create({ prefixUrl: 'https://api.example.com', timeout: 10_000, retry: { limit: 3 }, hooks: { beforeRequest: [ (request) => request.headers.set('Authorization', `Bearer ${token()}`), ], }, }); const users = (await api .get('users', { searchParams: { page: 1 } }) .json()) as User[]; ``` ```ts [valifetch] import valifetch from 'valifetch'; import { bearerAuth } from 'valifetch/auth'; import * as v from 'valibot'; const api = valifetch.create({ prefixUrl: 'https://api.example.com', timeout: 10_000, retry: { limit: 3 }, hooks: { beforeRequest: [bearerAuth(token)] }, }); const users = await api.get('/users', { searchParams: { page: 1 }, responseSchema: v.array(UserSchema), }); ``` ::: Note the leading `/` is fine in valifetch: `prefixUrl` and the path are joined with the slashes normalised. --- --- url: https://haihv.github.io/valifetch/migration/from-axios.md description: >- Migrate from axios to valifetch: native fetch instead of XHR, parsed bodies instead of response wrappers, interceptors to hooks, and validation. --- # Migrating from axios axios and valifetch differ at the root: valifetch is built on native `fetch`, resolves to the **parsed body** rather than a response wrapper, and validates with Valibot. ## The shape of a call ::: code-group ```ts [axios] import axios from 'axios'; const { data } = await axios.get('https://api.example.com/users/1'); ``` ```ts [valifetch] import valifetch from 'valifetch'; const user = await valifetch.get('https://api.example.com/users/1', { responseSchema: UserSchema, // validated and typed }); ``` ::: There is no `{ data, status, headers }` wrapper. When you need the status or headers, use `responseType: 'raw'` to get the `Response`, or read them in an `afterResponse` hook. ## Config options | axios | valifetch | Notes | |---|---|---| | `baseURL` | `prefixUrl` | An absolute request URL does not override it: the path is always joined under the prefix, and a `..` escape throws a `TypeError`. Use a separate instance (or the default `valifetch`) for full URLs | | `url` + `method` | the method function (`get`, `post`, ...) or `api(url, { method })` on a `callable()` instance | | | `params` | `searchParams` | | | `data` (object) | `json` | Optionally validated by `bodySchema` | | `data` (`FormData`, `URLSearchParams`) | `form` | | | `data` (string, `Blob`, `ArrayBuffer`, stream) | `body` | Raw; set `Content-Type` yourself | | `headers` | `headers` | | | `timeout` | `timeout` | Milliseconds; `0` disables | | `withCredentials: true` | `credentials: 'include'` | Standard fetch option | | `auth: { username, password }` | `basicAuth(user, pass)` from `valifetch/auth` | | | `responseType: 'json'` | default | | | `responseType: 'text'` | `responseType: 'text'` | | | `responseType: 'blob'` | `responseType: 'blob'` | | | `responseType: 'arraybuffer'` | `responseType: 'arrayBuffer'` | Different casing | | `responseType: 'stream'` | `responseType: 'stream'` | Returns a web `ReadableStream` | | `validateStatus` | `throwHttpErrors: boolean` | A boolean only; no custom predicate | | `signal` | `signal`, or `.cancel()` on the returned promise | | | `cancelToken` | `.cancel()` / `signal` | | | `onDownloadProgress` | `onDownloadProgress` | Event is `{ loaded, total, percent }` | | `onUploadProgress` | none | See [File upload](https://haihv.github.io/valifetch/recipes/file-upload.md) | | `transformRequest` | `beforeRequest` hook | | | `transformResponse` | `afterParseResponse` hook | | | `interceptors.request` | `hooks.beforeRequest` | | | `interceptors.response` | `hooks.afterResponse` / `hooks.afterParseResponse` | | | `axios.create(config)` | `valifetch.create(options)` | | | `instance.defaults` mutation | `instance.extend(options)` | Instances are immutable; extend to derive | | `axios.all([...])` | `api.all([...])` | Typed tuple, cancellable | | (none) | `responseSchema`, `bodySchema`, `paramsSchema`, `searchSchema` | Validation | | (none) | `params` with `:name` path segments | | | (none) | `retry`, `dedupe`, `debug`, `priority`, `sseMaxEventSize` | | | `paramsSerializer`, `proxy`, `httpAgent` / `httpsAgent`, `maxRedirects`, `maxContentLength`, `decompress` | none | Node-specific transport options are not exposed; valifetch uses the global `fetch` | ## Interceptors become hooks ::: code-group ```ts [axios] axios.interceptors.request.use((config) => { config.headers.Authorization = `Bearer ${getToken()}`; return config; }); axios.interceptors.response.use( (response) => response, async (error) => { if (error.response?.status === 401) { await refresh(); return axios.request(error.config); } throw error; } ); ``` ```ts [valifetch] import valifetch from 'valifetch'; import { bearerAuth } from 'valifetch/auth'; const api = valifetch.create({ hooks: { beforeRequest: [bearerAuth(getToken)], afterResponse: [ async (request, _options, response) => { if (response.status !== 401) return response; await refresh(); const headers = new Headers(request.headers); headers.set('Authorization', `Bearer ${getToken()}`); return fetch(request, { headers }); }, ], }, }); ``` ::: Differences worth knowing: * Hooks are **arrays** under `hooks`, not registered with `.use()`, and there is no eject. Build a new instance with `extend()` instead. * Hooks from a parent and a child instance **concatenate**, parent first. * In axios, the response error handler only sees failures. In valifetch, `afterResponse` sees **every** response, including 4xx and 5xx, *before* the status check. That is why the 401 replay above works without a `try/catch`. * See [Authentication](https://haihv.github.io/valifetch/recipes/auth.md) for `jwtRefresh`, which refreshes proactively. ## Errors axios throws `AxiosError` for HTTP failures. valifetch throws a single `ValifetchError` with a `code`: | axios | valifetch | |---|---| | `axios.isAxiosError(e)` | `e instanceof ValifetchError` | | `error.response?.status` | `error.status` | | `error.response?.data` | `error.responseBody` (parsed JSON, or text) | | `error.response` | `error.response` | | `error.code === 'ECONNABORTED'` (timeout) | `error.code === 'TIMEOUT_ERROR'` or `error.isTimeoutError` | | `axios.isCancel(e)` | `error.code === 'ABORT_ERROR'` or `error.isAbortError` | | no response (network failure) | `error.code === 'NETWORK_ERROR'` | | (none) | `error.code === 'VALIDATION_ERROR'`, with `error.target` and `error.issues` | | (none) | `error.code === 'PARSE_ERROR'` | ```ts try { await api.get('/users/1', { responseSchema: UserSchema }); } catch (error) { if (error instanceof ValifetchError) { switch (error.code) { case 'HTTP_ERROR': console.log(error.status, error.responseBody); break; case 'VALIDATION_ERROR': console.log(error.target, error.issues); break; } } } ``` See [Errors](https://haihv.github.io/valifetch/guide/errors.md) for the full table. ## Retry axios has no built-in retry; it is usually added with a plugin. valifetch retries by default: 2 retries on idempotent methods for `[408, 413, 429, 500, 502, 503, 504]` and on network errors, with exponential backoff and `Retry-After` support (a `Retry-After` longer than `retry.maxRetryAfter`, default 60 s, is not retried). Set `retry: false` to turn it off. See [Retry](https://haihv.github.io/valifetch/guide/retry.md). ## Cancellation ```ts // axios const controller = new AbortController(); axios.get(url, { signal: controller.signal }); controller.abort(); // valifetch: same signal, or cancel the promise directly const req = valifetch.get(url); req.cancel(); ``` --- --- url: https://haihv.github.io/valifetch/api.md --- # API Reference ## Modules * [valifetch](index/index.md) * [valifetch/error](error/index.md) * [valifetch/types](types/index.md) * [valifetch/auth](auth/index.md) * [valifetch/mock](mock/index.md) --- --- url: https://haihv.github.io/valifetch/api/index/classes/ValifetchError.md --- # Class: ValifetchError Defined in: [src/errors/ValifetchError.ts:49](https://github.com/haihv/valifetch/blob/285835d38a6676b98d2ee1a93e23166c6c834cb2/src/errors/ValifetchError.ts#L49) Custom error class for valifetch errors Provides structured error information for better error handling ## Extends * `Error` ## Constructors ### Constructor > **new ValifetchError**(`options`): `ValifetchError` Defined in: [src/errors/ValifetchError.ts:70](https://github.com/haihv/valifetch/blob/285835d38a6676b98d2ee1a93e23166c6c834cb2/src/errors/ValifetchError.ts#L70) Constructs a `ValifetchError`. #### Parameters ##### options [`ValifetchErrorOptions`](../type-aliases/ValifetchErrorOptions.md) Error details: message, code, and optional request/response/validation/cause/responseBody context. #### Returns `ValifetchError` #### Overrides `Error.constructor` ## Properties ### cause? > `optional` **cause?**: `unknown` Defined in: node_modules/typescript/lib/lib.es2022.error.d.ts:24 #### Inherited from `Error.cause` *** ### code > `readonly` **code**: [`ErrorCode`](../type-aliases/ErrorCode.md) Defined in: [src/errors/ValifetchError.ts:51](https://github.com/haihv/valifetch/blob/285835d38a6676b98d2ee1a93e23166c6c834cb2/src/errors/ValifetchError.ts#L51) Error code for discriminated error handling *** ### message > **message**: `string` Defined in: node_modules/typescript/lib/lib.es5.d.ts:1075 #### Inherited from `Error.message` *** ### name > **name**: `string` Defined in: node_modules/typescript/lib/lib.es5.d.ts:1074 #### Inherited from `Error.name` *** ### request? > `readonly` `optional` **request?**: `Request` Defined in: [src/errors/ValifetchError.ts:53](https://github.com/haihv/valifetch/blob/285835d38a6676b98d2ee1a93e23166c6c834cb2/src/errors/ValifetchError.ts#L53) Original request that caused the error *** ### response? > `readonly` `optional` **response?**: `Response` Defined in: [src/errors/ValifetchError.ts:55](https://github.com/haihv/valifetch/blob/285835d38a6676b98d2ee1a93e23166c6c834cb2/src/errors/ValifetchError.ts#L55) Response received (if any) *** ### responseBody? > `readonly` `optional` **responseBody?**: `unknown` Defined in: [src/errors/ValifetchError.ts:64](https://github.com/haihv/valifetch/blob/285835d38a6676b98d2ee1a93e23166c6c834cb2/src/errors/ValifetchError.ts#L64) Parsed response body on `HTTP_ERROR` (JSON-parsed object/array, or plain text when the body is not valid JSON) and raw text on `PARSE_ERROR` (the response body that failed to parse as JSON). `undefined` when the body could not be read at all. *** ### stack? > `optional` **stack?**: `string` Defined in: node_modules/typescript/lib/lib.es5.d.ts:1076 #### Inherited from `Error.stack` *** ### validation? > `readonly` `optional` **validation?**: [`ValidationErrorInfo`](../type-aliases/ValidationErrorInfo.md) Defined in: [src/errors/ValifetchError.ts:57](https://github.com/haihv/valifetch/blob/285835d38a6676b98d2ee1a93e23166c6c834cb2/src/errors/ValifetchError.ts#L57) Validation error details (if validation failed) ## Accessors ### isAbortError #### Get Signature > **get** **isAbortError**(): `boolean` Defined in: [src/errors/ValifetchError.ts:107](https://github.com/haihv/valifetch/blob/285835d38a6676b98d2ee1a93e23166c6c834cb2/src/errors/ValifetchError.ts#L107) Check if this is an abort/cancel error ##### Returns `boolean` *** ### isHttpError #### Get Signature > **get** **isHttpError**(): `boolean` Defined in: [src/errors/ValifetchError.ts:92](https://github.com/haihv/valifetch/blob/285835d38a6676b98d2ee1a93e23166c6c834cb2/src/errors/ValifetchError.ts#L92) Check if this is an HTTP error (non-2xx status) ##### Returns `boolean` *** ### isNetworkError #### Get Signature > **get** **isNetworkError**(): `boolean` Defined in: [src/errors/ValifetchError.ts:102](https://github.com/haihv/valifetch/blob/285835d38a6676b98d2ee1a93e23166c6c834cb2/src/errors/ValifetchError.ts#L102) Check if this is a network error ##### Returns `boolean` *** ### isParseError #### Get Signature > **get** **isParseError**(): `boolean` Defined in: [src/errors/ValifetchError.ts:112](https://github.com/haihv/valifetch/blob/285835d38a6676b98d2ee1a93e23166c6c834cb2/src/errors/ValifetchError.ts#L112) Check if this is a parse error (e.g., invalid JSON) ##### Returns `boolean` *** ### issues #### Get Signature > **get** **issues**(): `BaseIssue`<`unknown`>\[] Defined in: [src/errors/ValifetchError.ts:117](https://github.com/haihv/valifetch/blob/285835d38a6676b98d2ee1a93e23166c6c834cb2/src/errors/ValifetchError.ts#L117) Get flattened validation issues (convenience) ##### Returns `BaseIssue`<`unknown`>\[] *** ### isTimeoutError #### Get Signature > **get** **isTimeoutError**(): `boolean` Defined in: [src/errors/ValifetchError.ts:97](https://github.com/haihv/valifetch/blob/285835d38a6676b98d2ee1a93e23166c6c834cb2/src/errors/ValifetchError.ts#L97) Check if this is a timeout error ##### Returns `boolean` *** ### isValidationError #### Get Signature > **get** **isValidationError**(): `boolean` Defined in: [src/errors/ValifetchError.ts:87](https://github.com/haihv/valifetch/blob/285835d38a6676b98d2ee1a93e23166c6c834cb2/src/errors/ValifetchError.ts#L87) Check if this is a validation error ##### Returns `boolean` *** ### status #### Get Signature > **get** **status**(): `number` | `undefined` Defined in: [src/errors/ValifetchError.ts:127](https://github.com/haihv/valifetch/blob/285835d38a6676b98d2ee1a93e23166c6c834cb2/src/errors/ValifetchError.ts#L127) HTTP status code (if available) ##### Returns `number` | `undefined` *** ### statusText #### Get Signature > **get** **statusText**(): `string` | `undefined` Defined in: [src/errors/ValifetchError.ts:132](https://github.com/haihv/valifetch/blob/285835d38a6676b98d2ee1a93e23166c6c834cb2/src/errors/ValifetchError.ts#L132) HTTP status text (if available) ##### Returns `string` | `undefined` *** ### target #### Get Signature > **get** **target**(): [`ValidationTarget`](../type-aliases/ValidationTarget.md) | `undefined` Defined in: [src/errors/ValifetchError.ts:122](https://github.com/haihv/valifetch/blob/285835d38a6676b98d2ee1a93e23166c6c834cb2/src/errors/ValifetchError.ts#L122) Which part of the request/response failed validation (convenience) ##### Returns [`ValidationTarget`](../type-aliases/ValidationTarget.md) | `undefined` --- --- url: >- https://haihv.github.io/valifetch/api/index/type-aliases/AfterParseResponseHook.md --- # Type Alias: AfterParseResponseHook\ > **AfterParseResponseHook**<`T`> = (`data`, `response`, `request`) => `T` | `Promise`<`T`> Defined in: [src/types/hooks.ts:28](https://github.com/haihv/valifetch/blob/285835d38a6676b98d2ee1a93e23166c6c834cb2/src/types/hooks.ts#L28) Hook called after response is parsed Can transform the parsed data ## Type Parameters ### T `T` = `unknown` ## Parameters ### data `T` ### response `Response` ### request `Request` ## Returns `T` | `Promise`<`T`> --- --- url: https://haihv.github.io/valifetch/api/index/type-aliases/AfterResponseHook.md --- # Type Alias: AfterResponseHook > **AfterResponseHook** = (`request`, `options`, `response`) => `Response` | `void` | `Promise`<`Response` | `void`> Defined in: [src/types/hooks.ts:18](https://github.com/haihv/valifetch/blob/285835d38a6676b98d2ee1a93e23166c6c834cb2/src/types/hooks.ts#L18) Hook called after each response (before parsing) Can modify response or return a new one ## Parameters ### request `Request` ### options [`NormalizedOptions`](NormalizedOptions.md) ### response `Response` ## Returns `Response` | `void` | `Promise`<`Response` | `void`> --- --- url: https://haihv.github.io/valifetch/api/index/type-aliases/BeforeErrorHook.md --- # Type Alias: BeforeErrorHook > **BeforeErrorHook** = (`error`) => [`ValifetchError`](../classes/ValifetchError.md) | `Promise`<[`ValifetchError`](../classes/ValifetchError.md)> Defined in: [src/types/hooks.ts:61](https://github.com/haihv/valifetch/blob/285835d38a6676b98d2ee1a93e23166c6c834cb2/src/types/hooks.ts#L61) Hook called just before a `ValifetchError` is thrown to the caller. Must return the error to throw — the same instance (optionally mutated) or a replacement `ValifetchError`. ## Parameters ### error [`ValifetchError`](../classes/ValifetchError.md) ## Returns [`ValifetchError`](../classes/ValifetchError.md) | `Promise`<[`ValifetchError`](../classes/ValifetchError.md)> --- --- url: https://haihv.github.io/valifetch/api/index/type-aliases/BeforeRequestHook.md --- # Type Alias: BeforeRequestHook > **BeforeRequestHook** = (`request`, `options`) => `Request` | `Response` | `void` | `Promise`<`Request` | `Response` | `void`> Defined in: [src/types/hooks.ts:9](https://github.com/haihv/valifetch/blob/285835d38a6676b98d2ee1a93e23166c6c834cb2/src/types/hooks.ts#L9) Hook called before each request Can modify request or return early Response to bypass fetch ## Parameters ### request `Request` ### options [`NormalizedOptions`](NormalizedOptions.md) ## Returns `Request` | `Response` | `void` | `Promise`<`Request` | `Response` | `void`> --- --- url: https://haihv.github.io/valifetch/api/index/type-aliases/BeforeRetryHook.md --- # Type Alias: BeforeRetryHook > **BeforeRetryHook** = (`state`) => `Request` | *typeof* [`stop`](../variables/stop.md) | `void` | `Promise`<`Request` | *typeof* [`stop`](../variables/stop.md) | `void`> Defined in: [src/types/hooks.ts:52](https://github.com/haihv/valifetch/blob/285835d38a6676b98d2ee1a93e23166c6c834cb2/src/types/hooks.ts#L52) Hook called before each retry is scheduled. Return `stop` to abort retrying (the original failure is then handled as if retries were exhausted), a `Request` to replace the request for subsequent attempts, or nothing to leave the request unchanged. ## Parameters ### state [`BeforeRetryState`](BeforeRetryState.md) ## Returns `Request` | *typeof* [`stop`](../variables/stop.md) | `void` | `Promise`<`Request` | *typeof* [`stop`](../variables/stop.md) | `void`> --- --- url: https://haihv.github.io/valifetch/api/index/type-aliases/BeforeRetryState.md --- # Type Alias: BeforeRetryState > **BeforeRetryState** = [`RetryContext`](RetryContext.md) & `object` Defined in: [src/types/hooks.ts:41](https://github.com/haihv/valifetch/blob/285835d38a6676b98d2ee1a93e23166c6c834cb2/src/types/hooks.ts#L41) State passed to `beforeRetry` hooks. Extends [RetryContext](RetryContext.md) with the normalized request options. Exactly one of `response` / `error` is set, discriminated by `reason`. Return a new `Request` from the hook to replace `request` for the remaining attempts. ## Type Declaration ### options > **options**: [`NormalizedOptions`](NormalizedOptions.md) Normalized request options --- --- url: https://haihv.github.io/valifetch/api/index/type-aliases/CallableInstance.md --- # Type Alias: CallableInstance() > **CallableInstance** = [`CancellablePromise`](CancellablePromise.md)<`ResolveResponseType`<`TData`, `TResponseSchema`>> Defined in: [src/types/instance.ts:96](https://github.com/haihv/valifetch/blob/285835d38a6676b98d2ee1a93e23166c6c834cb2/src/types/instance.ts#L96) Callable instance type for ky-style syntax > **CallableInstance**<`TData`, `TPath`, `TResponseSchema`, `TBodySchema`, `TParamsSchema`, `TSearchSchema`>(`url`, `options?`): [`CancellablePromise`](CancellablePromise.md)<`ResolveResponseType`<`TData`, `TResponseSchema`>> Perform a request, defaulting to `GET`. Pass `method` to choose another verb and `responseType` to change how the body is parsed. ## Type Parameters ### TData `TData` = `unknown` ### TPath `TPath` *extends* `string` = `string` ### TResponseSchema `TResponseSchema` *extends* `GenericSchema` | `undefined` = `undefined` ### TBodySchema `TBodySchema` *extends* `GenericSchema` | `undefined` = `undefined` ### TParamsSchema `TParamsSchema` *extends* `GenericSchema` | `undefined` = `undefined` ### TSearchSchema `TSearchSchema` *extends* `GenericSchema` | `undefined` = `undefined` ## Parameters ### url `TPath` ### options? `Omit`<`RequestInit`, `"body"` | `"method"` | `"window"`> & `object` & `object` & `object` & `object` ## Returns [`CancellablePromise`](CancellablePromise.md)<`ResolveResponseType`<`TData`, `TResponseSchema`>> ## Methods ### all() > **all**<`T`>(`requests`): [`CancellablePromise`](CancellablePromise.md)<{ -readonly \[P in string | number | symbol]: Awaited\ }> Defined in: [src/types/instance.ts:240](https://github.com/haihv/valifetch/blob/285835d38a6676b98d2ee1a93e23166c6c834cb2/src/types/instance.ts#L240) Run multiple requests in parallel and resolve to a tuple of their results, preserving each element's type (sugar over `Promise.all`). Rejects as soon as any input rejects. The returned promise is cancellable: `.cancel()` aborts every input that exposes a `.cancel()` method (e.g. other valifetch requests); inputs without one are ignored. A rejection does not cancel the remaining requests. #### Type Parameters ##### T `T` *extends* \[] | readonly `unknown`\[] #### Parameters ##### requests `T` #### Returns [`CancellablePromise`](CancellablePromise.md)<{ -readonly \[P in string | number | symbol]: Awaited\ }> #### Example ```ts const [user, posts] = await api.all([ api.get('/users/1', { responseSchema: UserSchema }), api.get('/posts', { responseSchema: PostsSchema }), ]); ``` *** ### allSettled() > **allSettled**<`T`>(`requests`): [`CancellablePromise`](CancellablePromise.md)<{ -readonly \[P in string | number | symbol]: PromiseSettledResult\> }> Defined in: [src/types/instance.ts:263](https://github.com/haihv/valifetch/blob/285835d38a6676b98d2ee1a93e23166c6c834cb2/src/types/instance.ts#L263) Run multiple requests in parallel and resolve once all have settled, never rejecting (sugar over `Promise.allSettled`). Each result is a standard `PromiseSettledResult`: `{ status: 'fulfilled', value }` or `{ status: 'rejected', reason }` (the `reason` is typically a `ValifetchError`). The returned promise is cancellable: `.cancel()` aborts every input that exposes a `.cancel()` method; inputs without one are ignored. A rejection does not cancel the remaining requests. #### Type Parameters ##### T `T` *extends* \[] | readonly `unknown`\[] #### Parameters ##### requests `T` #### Returns [`CancellablePromise`](CancellablePromise.md)<{ -readonly \[P in string | number | symbol]: PromiseSettledResult\> }> #### Example ```ts const results = await api.allSettled([api.get('/a'), api.get('/b')]); for (const r of results) { if (r.status === 'fulfilled') console.log(r.value); else console.error(r.reason); } ``` *** ### create() > **create**(`options?`): `CallableInstance` Defined in: [src/types/instance.ts:270](https://github.com/haihv/valifetch/blob/285835d38a6676b98d2ee1a93e23166c6c834cb2/src/types/instance.ts#L270) Create new instance with defaults #### Parameters ##### options? [`ValifetchInstanceOptions`](ValifetchInstanceOptions.md) #### Returns `CallableInstance` *** ### delete() > **delete**<`TData`, `TPath`, `TResponseSchema`, `TParamsSchema`, `TSearchSchema`>(`url`, `options?`): [`CancellablePromise`](CancellablePromise.md)<`ResolveResponseType`<`TData`, `TResponseSchema`>> Defined in: [src/types/instance.ts:187](https://github.com/haihv/valifetch/blob/285835d38a6676b98d2ee1a93e23166c6c834cb2/src/types/instance.ts#L187) DELETE request #### Type Parameters ##### TData `TData` = `unknown` ##### TPath `TPath` *extends* `string` = `string` ##### TResponseSchema `TResponseSchema` *extends* `GenericSchema` | `undefined` = `undefined` ##### TParamsSchema `TParamsSchema` *extends* `GenericSchema` | `undefined` = `undefined` ##### TSearchSchema `TSearchSchema` *extends* `GenericSchema` | `undefined` = `undefined` #### Parameters ##### url `TPath` ##### options? [`GetOptions`](GetOptions.md)<`TPath`, `TResponseSchema`, `TParamsSchema`, `TSearchSchema`> #### Returns [`CancellablePromise`](CancellablePromise.md)<`ResolveResponseType`<`TData`, `TResponseSchema`>> *** ### extend() > **extend**(`options`): `CallableInstance` Defined in: [src/types/instance.ts:272](https://github.com/haihv/valifetch/blob/285835d38a6676b98d2ee1a93e23166c6c834cb2/src/types/instance.ts#L272) Extend current instance with additional options #### Parameters ##### options [`ValifetchInstanceOptions`](ValifetchInstanceOptions.md) | ((`parent`) => [`ValifetchInstanceOptions`](ValifetchInstanceOptions.md)) #### Returns `CallableInstance` *** ### get() > **get**<`TData`, `TPath`, `TResponseSchema`, `TParamsSchema`, `TSearchSchema`>(`url`, `options?`): [`CancellablePromise`](CancellablePromise.md)<`ResolveResponseType`<`TData`, `TResponseSchema`>> Defined in: [src/types/instance.ts:122](https://github.com/haihv/valifetch/blob/285835d38a6676b98d2ee1a93e23166c6c834cb2/src/types/instance.ts#L122) GET request #### Type Parameters ##### TData `TData` = `unknown` ##### TPath `TPath` *extends* `string` = `string` ##### TResponseSchema `TResponseSchema` *extends* `GenericSchema` | `undefined` = `undefined` ##### TParamsSchema `TParamsSchema` *extends* `GenericSchema` | `undefined` = `undefined` ##### TSearchSchema `TSearchSchema` *extends* `GenericSchema` | `undefined` = `undefined` #### Parameters ##### url `TPath` ##### options? [`GetOptions`](GetOptions.md)<`TPath`, `TResponseSchema`, `TParamsSchema`, `TSearchSchema`> #### Returns [`CancellablePromise`](CancellablePromise.md)<`ResolveResponseType`<`TData`, `TResponseSchema`>> *** ### head() > **head**<`TPath`, `TParamsSchema`, `TSearchSchema`>(`url`, `options?`): [`CancellablePromise`](CancellablePromise.md)<`void`> Defined in: [src/types/instance.ts:201](https://github.com/haihv/valifetch/blob/285835d38a6676b98d2ee1a93e23166c6c834cb2/src/types/instance.ts#L201) HEAD request — always resolves to `void`; the response body is never read, so `responseType` and `responseSchema` are not accepted. #### Type Parameters ##### TPath `TPath` *extends* `string` = `string` ##### TParamsSchema `TParamsSchema` *extends* `GenericSchema` | `undefined` = `undefined` ##### TSearchSchema `TSearchSchema` *extends* `GenericSchema` | `undefined` = `undefined` #### Parameters ##### url `TPath` ##### options? `Omit`<[`GetOptions`](GetOptions.md)<`TPath`, `undefined`, `TParamsSchema`, `TSearchSchema`>, `"responseSchema"` | `"responseType"`> #### Returns [`CancellablePromise`](CancellablePromise.md)<`void`> *** ### options() > **options**<`TData`, `TPath`, `TResponseSchema`, `TParamsSchema`, `TSearchSchema`>(`url`, `options?`): [`CancellablePromise`](CancellablePromise.md)<`ResolveResponseType`<`TData`, `TResponseSchema`>> Defined in: [src/types/instance.ts:213](https://github.com/haihv/valifetch/blob/285835d38a6676b98d2ee1a93e23166c6c834cb2/src/types/instance.ts#L213) OPTIONS request #### Type Parameters ##### TData `TData` = `unknown` ##### TPath `TPath` *extends* `string` = `string` ##### TResponseSchema `TResponseSchema` *extends* `GenericSchema` | `undefined` = `undefined` ##### TParamsSchema `TParamsSchema` *extends* `GenericSchema` | `undefined` = `undefined` ##### TSearchSchema `TSearchSchema` *extends* `GenericSchema` | `undefined` = `undefined` #### Parameters ##### url `TPath` ##### options? [`GetOptions`](GetOptions.md)<`TPath`, `TResponseSchema`, `TParamsSchema`, `TSearchSchema`> #### Returns [`CancellablePromise`](CancellablePromise.md)<`ResolveResponseType`<`TData`, `TResponseSchema`>> *** ### patch() > **patch**<`TData`, `TPath`, `TResponseSchema`, `TBodySchema`, `TParamsSchema`, `TSearchSchema`>(`url`, `options?`): [`CancellablePromise`](CancellablePromise.md)<`ResolveResponseType`<`TData`, `TResponseSchema`>> Defined in: [src/types/instance.ts:169](https://github.com/haihv/valifetch/blob/285835d38a6676b98d2ee1a93e23166c6c834cb2/src/types/instance.ts#L169) PATCH request #### Type Parameters ##### TData `TData` = `unknown` ##### TPath `TPath` *extends* `string` = `string` ##### TResponseSchema `TResponseSchema` *extends* `GenericSchema` | `undefined` = `undefined` ##### TBodySchema `TBodySchema` *extends* `GenericSchema` | `undefined` = `undefined` ##### TParamsSchema `TParamsSchema` *extends* `GenericSchema` | `undefined` = `undefined` ##### TSearchSchema `TSearchSchema` *extends* `GenericSchema` | `undefined` = `undefined` #### Parameters ##### url `TPath` ##### options? [`PostOptions`](PostOptions.md)<`TPath`, `TResponseSchema`, `TBodySchema`, `TParamsSchema`, `TSearchSchema`> #### Returns [`CancellablePromise`](CancellablePromise.md)<`ResolveResponseType`<`TData`, `TResponseSchema`>> *** ### post() > **post**<`TData`, `TPath`, `TResponseSchema`, `TBodySchema`, `TParamsSchema`, `TSearchSchema`>(`url`, `options?`): [`CancellablePromise`](CancellablePromise.md)<`ResolveResponseType`<`TData`, `TResponseSchema`>> Defined in: [src/types/instance.ts:133](https://github.com/haihv/valifetch/blob/285835d38a6676b98d2ee1a93e23166c6c834cb2/src/types/instance.ts#L133) POST request #### Type Parameters ##### TData `TData` = `unknown` ##### TPath `TPath` *extends* `string` = `string` ##### TResponseSchema `TResponseSchema` *extends* `GenericSchema` | `undefined` = `undefined` ##### TBodySchema `TBodySchema` *extends* `GenericSchema` | `undefined` = `undefined` ##### TParamsSchema `TParamsSchema` *extends* `GenericSchema` | `undefined` = `undefined` ##### TSearchSchema `TSearchSchema` *extends* `GenericSchema` | `undefined` = `undefined` #### Parameters ##### url `TPath` ##### options? [`PostOptions`](PostOptions.md)<`TPath`, `TResponseSchema`, `TBodySchema`, `TParamsSchema`, `TSearchSchema`> #### Returns [`CancellablePromise`](CancellablePromise.md)<`ResolveResponseType`<`TData`, `TResponseSchema`>> *** ### put() > **put**<`TData`, `TPath`, `TResponseSchema`, `TBodySchema`, `TParamsSchema`, `TSearchSchema`>(`url`, `options?`): [`CancellablePromise`](CancellablePromise.md)<`ResolveResponseType`<`TData`, `TResponseSchema`>> Defined in: [src/types/instance.ts:151](https://github.com/haihv/valifetch/blob/285835d38a6676b98d2ee1a93e23166c6c834cb2/src/types/instance.ts#L151) PUT request #### Type Parameters ##### TData `TData` = `unknown` ##### TPath `TPath` *extends* `string` = `string` ##### TResponseSchema `TResponseSchema` *extends* `GenericSchema` | `undefined` = `undefined` ##### TBodySchema `TBodySchema` *extends* `GenericSchema` | `undefined` = `undefined` ##### TParamsSchema `TParamsSchema` *extends* `GenericSchema` | `undefined` = `undefined` ##### TSearchSchema `TSearchSchema` *extends* `GenericSchema` | `undefined` = `undefined` #### Parameters ##### url `TPath` ##### options? [`PostOptions`](PostOptions.md)<`TPath`, `TResponseSchema`, `TBodySchema`, `TParamsSchema`, `TSearchSchema`> #### Returns [`CancellablePromise`](CancellablePromise.md)<`ResolveResponseType`<`TData`, `TResponseSchema`>> --- --- url: https://haihv.github.io/valifetch/api/index/type-aliases/CancellablePromise.md --- # Type Alias: CancellablePromise\ > **CancellablePromise**<`T`> = `Promise`<`T`> & `object` Defined in: [src/types/instance.ts:24](https://github.com/haihv/valifetch/blob/285835d38a6676b98d2ee1a93e23166c6c834cb2/src/types/instance.ts#L24) A `Promise` with an attached `.cancel()` method that aborts the in-flight request. Cancelling rejects the promise with a `ValifetchError` whose `code` is `'ABORT_ERROR'`. ## Type Parameters ### T `T` ## Type Declaration ### cancel() > **cancel**(): `void` Aborts the in-flight request. The promise rejects with a `ValifetchError` whose `code` is `'ABORT_ERROR'`. #### Returns `void` ## Example ```ts const req = api.get('/slow-endpoint'); req.cancel(); // aborts immediately try { await req; } catch (err) { // err.code === 'ABORT_ERROR' } ``` --- --- url: https://haihv.github.io/valifetch/api/index/type-aliases/DebugEvent.md --- # Type Alias: DebugEvent > **DebugEvent** = { `request`: `Request`; `type`: `"request"`; } | { `attempt`: `number`; `request`: `Request`; `response`: `Response`; `type`: `"response"`; } | { `attempt`: `number`; `delay`: `number`; `reason`: `"status"` | `"network"`; `request`: `Request`; `type`: `"retry"`; } | { `request`: `Request`; `type`: `"cancel"`; } Defined in: [src/types/options.ts:137](https://github.com/haihv/valifetch/blob/285835d38a6676b98d2ee1a93e23166c6c834cb2/src/types/options.ts#L137) A structured event emitted during the request lifecycle when `debug` is enabled. Each variant carries the data relevant to that stage of the pipeline. ## Union Members ### Type Literal { `request`: `Request`; `type`: `"request"`; } #### request > **request**: `Request` The outgoing request #### type > **type**: `"request"` Fired before each request attempt, including retries and hook-intercepted requests *** ### Type Literal { `attempt`: `number`; `request`: `Request`; `response`: `Response`; `type`: `"response"`; } #### attempt > **attempt**: `number` Which attempt number this response came from (1-based) #### request > **request**: `Request` The originating request #### response > **response**: `Response` The raw response received #### type > **type**: `"response"` Fired after `fetch()` resolves with a response *** ### Type Literal { `attempt`: `number`; `delay`: `number`; `reason`: `"status"` | `"network"`; `request`: `Request`; `type`: `"retry"`; } #### attempt > **attempt**: `number` 1-based number of the retry about to be performed (`1` = first retry, i.e. second attempt) #### delay > **delay**: `number` Delay in milliseconds before the next attempt #### reason > **reason**: `"status"` | `"network"` Why the retry was triggered #### request > **request**: `Request` The originating request #### type > **type**: `"retry"` Fired when a retry is about to be scheduled *** ### Type Literal { `request`: `Request`; `type`: `"cancel"`; } #### request > **request**: `Request` The request that was cancelled #### type > **type**: `"cancel"` Fired when the request is cancelled via `.cancel()` or an AbortController --- --- url: https://haihv.github.io/valifetch/api/index/type-aliases/DebugOption.md --- # Type Alias: DebugOption > **DebugOption** = `true` | ((`event`) => `void`) Defined in: [src/types/options.ts:186](https://github.com/haihv/valifetch/blob/285835d38a6676b98d2ee1a93e23166c6c834cb2/src/types/options.ts#L186) Controls structured debug logging of request lifecycle events. * `true` — logs a plain summary of each event via `console.debug('[valifetch]', summary)`: `type`, `method`, `url`, request `headers`, plus `attempt`/`status`/`responseHeaders` (response) or `attempt`/`delay`/`reason` (retry). Values of headers, and of URL query parameters, whose name matches `auth`, `cookie`, `token`, `secret`, `key`, `session`, `pass`, `credential`, `sig`, `jwt`, `dpop`, `csrf`, `xsrf`, `otp`, `bearer` or `code` (case-insensitive substring) are replaced with `'[REDACTED]'`. Matching is deliberately broad, so some harmless names are redacted too. The URL path and fragment are logged as-is. * function — receives each `DebugEvent` directly, with the live `Request`/`Response` (headers unredacted); redacting secrets is then the function's responsibility --- --- url: >- https://haihv.github.io/valifetch/api/index/type-aliases/DownloadProgressEvent.md --- # Type Alias: DownloadProgressEvent > **DownloadProgressEvent** = `object` Defined in: [src/types/options.ts:191](https://github.com/haihv/valifetch/blob/285835d38a6676b98d2ee1a93e23166c6c834cb2/src/types/options.ts#L191) Progress event fired during response body download ## Properties ### loaded > **loaded**: `number` Defined in: [src/types/options.ts:193](https://github.com/haihv/valifetch/blob/285835d38a6676b98d2ee1a93e23166c6c834cb2/src/types/options.ts#L193) Bytes received so far *** ### percent > **percent**: `number` | `undefined` Defined in: [src/types/options.ts:197](https://github.com/haihv/valifetch/blob/285835d38a6676b98d2ee1a93e23166c6c834cb2/src/types/options.ts#L197) Download percentage 0–100 (undefined when total is unknown) *** ### total > **total**: `number` | `undefined` Defined in: [src/types/options.ts:195](https://github.com/haihv/valifetch/blob/285835d38a6676b98d2ee1a93e23166c6c834cb2/src/types/options.ts#L195) Total bytes expected (undefined when no Content-Length header is present) --- --- url: https://haihv.github.io/valifetch/api/index/type-aliases/ErrorCode.md --- # Type Alias: ErrorCode > **ErrorCode** = `"NETWORK_ERROR"` | `"TIMEOUT_ERROR"` | `"VALIDATION_ERROR"` | `"HTTP_ERROR"` | `"ABORT_ERROR"` | `"PARSE_ERROR"` Defined in: [src/types/options.ts:120](https://github.com/haihv/valifetch/blob/285835d38a6676b98d2ee1a93e23166c6c834cb2/src/types/options.ts#L120) Error codes for ValifetchError --- --- url: https://haihv.github.io/valifetch/api/index/type-aliases/ExtractPathParams.md --- # Type Alias: ExtractPathParams\ > **ExtractPathParams**<`Path`> = `Path` *extends* `` `:${infer Param}/${infer Rest}` `` ? `Param` | `ExtractPathParams`<`Rest`> : `Path` *extends* `` `:${infer Param}` `` ? `Param` : `Path` *extends* `` `${string}/:${infer Rest}` `` ? `ExtractPathParams`<`` `:${Rest}` ``> : `never` Defined in: [src/types/params.ts:5](https://github.com/haihv/valifetch/blob/285835d38a6676b98d2ee1a93e23166c6c834cb2/src/types/params.ts#L5) Extracts parameter names from a URL path pattern e.g., "/users/:id/posts/:postId" -> "id" | "postId" ## Type Parameters ### Path `Path` *extends* `string` --- --- url: https://haihv.github.io/valifetch/api/index/type-aliases/GetOptions.md --- # Type Alias: GetOptions\ > **GetOptions**<`TPath`, `TResponseSchema`, `TParamsSchema`, `TSearchSchema`> = `Omit`<[`ValifetchOptions`](ValifetchOptions.md)<`TPath`, `TResponseSchema`, `undefined`, `TParamsSchema`, `TSearchSchema`>, `"json"` | `"bodySchema"` | `"form"` | `"body"`> & `object` Defined in: [src/types/instance.ts:48](https://github.com/haihv/valifetch/blob/285835d38a6676b98d2ee1a93e23166c6c834cb2/src/types/instance.ts#L48) Options for GET-like methods (no body) ## Type Parameters ### TPath `TPath` *extends* `string` = `string` ### TResponseSchema `TResponseSchema` *extends* `GenericSchema` | `undefined` = `undefined` ### TParamsSchema `TParamsSchema` *extends* `GenericSchema` | `undefined` = `undefined` ### TSearchSchema `TSearchSchema` *extends* `GenericSchema` | `undefined` = `undefined` ## Type Declaration ### responseType? > `optional` **responseType?**: [`ResponseType`](ResponseType.md) Response format - defaults to 'json' --- --- url: https://haihv.github.io/valifetch/api/index/type-aliases/HasPathParams.md --- # Type Alias: HasPathParams\ > **HasPathParams**<`Path`> = [`ExtractPathParams`](ExtractPathParams.md)<`Path`> *extends* `never` ? `false` : `true` Defined in: [src/types/params.ts:26](https://github.com/haihv/valifetch/blob/285835d38a6676b98d2ee1a93e23166c6c834cb2/src/types/params.ts#L26) Checks if a path has any parameters ## Type Parameters ### Path `Path` *extends* `string` --- --- url: https://haihv.github.io/valifetch/api/index/type-aliases/Hooks.md --- # Type Alias: Hooks > **Hooks** = `object` Defined in: [src/types/hooks.ts:68](https://github.com/haihv/valifetch/blob/285835d38a6676b98d2ee1a93e23166c6c834cb2/src/types/hooks.ts#L68) All available hooks ## Properties ### afterParseResponse? > `optional` **afterParseResponse?**: [`AfterParseResponseHook`](AfterParseResponseHook.md)\[] Defined in: [src/types/hooks.ts:74](https://github.com/haihv/valifetch/blob/285835d38a6676b98d2ee1a93e23166c6c834cb2/src/types/hooks.ts#L74) Hooks called after the response body has been parsed *** ### afterResponse? > `optional` **afterResponse?**: [`AfterResponseHook`](AfterResponseHook.md)\[] Defined in: [src/types/hooks.ts:72](https://github.com/haihv/valifetch/blob/285835d38a6676b98d2ee1a93e23166c6c834cb2/src/types/hooks.ts#L72) Hooks called after each response is received, before parsing *** ### beforeError? > `optional` **beforeError?**: [`BeforeErrorHook`](BeforeErrorHook.md)\[] Defined in: [src/types/hooks.ts:78](https://github.com/haihv/valifetch/blob/285835d38a6676b98d2ee1a93e23166c6c834cb2/src/types/hooks.ts#L78) Hooks called before a ValifetchError is thrown to the caller *** ### beforeRequest? > `optional` **beforeRequest?**: [`BeforeRequestHook`](BeforeRequestHook.md)\[] Defined in: [src/types/hooks.ts:70](https://github.com/haihv/valifetch/blob/285835d38a6676b98d2ee1a93e23166c6c834cb2/src/types/hooks.ts#L70) Hooks called before each request is sent *** ### beforeRetry? > `optional` **beforeRetry?**: [`BeforeRetryHook`](BeforeRetryHook.md)\[] Defined in: [src/types/hooks.ts:76](https://github.com/haihv/valifetch/blob/285835d38a6676b98d2ee1a93e23166c6c834cb2/src/types/hooks.ts#L76) Hooks called before each retry attempt is scheduled --- --- url: https://haihv.github.io/valifetch/api/index/type-aliases/HttpMethod.md --- # Type Alias: HttpMethod > **HttpMethod** = `"GET"` | `"POST"` | `"PUT"` | `"PATCH"` | `"DELETE"` | `"HEAD"` | `"OPTIONS"` Defined in: [src/types/options.ts:9](https://github.com/haihv/valifetch/blob/285835d38a6676b98d2ee1a93e23166c6c834cb2/src/types/options.ts#L9) HTTP methods supported by valifetch --- --- url: https://haihv.github.io/valifetch/api/index/type-aliases/InferResponseType.md --- # Type Alias: InferResponseType\ > **InferResponseType**<`TSchema`> = `TSchema` *extends* `GenericSchema` ? `InferOutput`<`TSchema`> : `unknown` Defined in: [src/types/options.ts:379](https://github.com/haihv/valifetch/blob/285835d38a6676b98d2ee1a93e23166c6c834cb2/src/types/options.ts#L379) Infer response type from schema or fallback to unknown ## Type Parameters ### TSchema `TSchema` --- --- url: https://haihv.github.io/valifetch/api/index/type-aliases/NormalizedOptions.md --- # Type Alias: NormalizedOptions > **NormalizedOptions** = `Omit`<[`ValifetchBaseOptions`](ValifetchBaseOptions.md), `"signal"`> & `object` Defined in: [src/types/options.ts:287](https://github.com/haihv/valifetch/blob/285835d38a6676b98d2ee1a93e23166c6c834cb2/src/types/options.ts#L287) Fully resolved request options as seen by hooks, after instance and per-request options have been merged and defaults applied. `retry` is carried through unnormalized (still `RetryOptions | number | false | undefined`); the retry loop normalizes it internally. ## Type Declaration ### body? > `optional` **body?**: [`RawBody`](RawBody.md) The raw body of the request, when provided ### bodySchema? > `optional` **bodySchema?**: `GenericSchema` Schema used to validate the request body, when provided ### form? > `optional` **form?**: `FormData` | `URLSearchParams` | `Record`<`string`, `string`> The form body of the request, when provided ### headers > **headers**: `Headers` Resolved headers object, instance headers overridden by request headers ### hooks > **hooks**: [`Hooks`](Hooks.md) Concatenated instance and request hooks (instance hooks run first) ### json? > `optional` **json?**: `unknown` The JSON body of the request, when provided ### method > **method**: [`HttpMethod`](HttpMethod.md) HTTP method for the request ### params? > `optional` **params?**: `Record`<`string`, `string` | `number`> Path parameter values interpolated into the URL ### paramsSchema? > `optional` **paramsSchema?**: `GenericSchema` Schema used to validate path params, when provided ### responseSchema? > `optional` **responseSchema?**: `GenericSchema` Schema used to validate the response body, when provided ### responseType? > `optional` **responseType?**: [`ResponseType`](ResponseType.md) Requested response format (per-call only; `undefined` means `'json'`) ### searchSchema? > `optional` **searchSchema?**: `GenericSchema` Schema used to validate search params, when provided ### signal > **signal**: `AbortSignal` The composed abort signal actually passed to `fetch` — the caller's signal combined with the controller behind `.cancel()`, not the caller's raw signal. ### throwHttpErrors > **throwHttpErrors**: `boolean` Resolved flag controlling whether non-2xx statuses throw ### validateRequest > **validateRequest**: `boolean` Resolved request validation flag ### validateResponse > **validateResponse**: `boolean` Resolved response validation flag --- --- url: https://haihv.github.io/valifetch/api/index/type-aliases/PathParamsRecord.md --- # Type Alias: PathParamsRecord\ > **PathParamsRecord**<`Path`> = [`ExtractPathParams`](ExtractPathParams.md)<`Path`> *extends* `never` ? `Record`<`string`, `never`> : `Record`<[`ExtractPathParams`](ExtractPathParams.md)<`Path`>, `string` | `number`> Defined in: [src/types/params.ts:18](https://github.com/haihv/valifetch/blob/285835d38a6676b98d2ee1a93e23166c6c834cb2/src/types/params.ts#L18) Creates a record type from extracted path params All params are string | number for flexibility ## Type Parameters ### Path `Path` *extends* `string` --- --- url: https://haihv.github.io/valifetch/api/index/type-aliases/PostOptions.md --- # Type Alias: PostOptions\ > **PostOptions**<`TPath`, `TResponseSchema`, `TBodySchema`, `TParamsSchema`, `TSearchSchema`> = [`ValifetchOptions`](ValifetchOptions.md)<`TPath`, `TResponseSchema`, `TBodySchema`, `TParamsSchema`, `TSearchSchema`> & `object` Defined in: [src/types/instance.ts:70](https://github.com/haihv/valifetch/blob/285835d38a6676b98d2ee1a93e23166c6c834cb2/src/types/instance.ts#L70) Options for POST-like methods (with body) ## Type Parameters ### TPath `TPath` *extends* `string` = `string` ### TResponseSchema `TResponseSchema` *extends* `GenericSchema` | `undefined` = `undefined` ### TBodySchema `TBodySchema` *extends* `GenericSchema` | `undefined` = `undefined` ### TParamsSchema `TParamsSchema` *extends* `GenericSchema` | `undefined` = `undefined` ### TSearchSchema `TSearchSchema` *extends* `GenericSchema` | `undefined` = `undefined` ## Type Declaration ### responseType? > `optional` **responseType?**: [`ResponseType`](ResponseType.md) Response format - defaults to 'json' --- --- url: https://haihv.github.io/valifetch/api/index/type-aliases/RawBody.md --- # Type Alias: RawBody > **RawBody** = `string` | `Blob` | `ArrayBuffer` | `ArrayBufferView` | `ReadableStream`<`Uint8Array`> Defined in: [src/types/options.ts:22](https://github.com/haihv/valifetch/blob/285835d38a6676b98d2ee1a93e23166c6c834cb2/src/types/options.ts#L22) Raw request body accepted by the `body` option. Sent as-is: no validation and no `Content-Type` inference. --- --- url: https://haihv.github.io/valifetch/api/index/type-aliases/ResponseType.md --- # Type Alias: ResponseType > **ResponseType** = `"json"` | `"text"` | `"blob"` | `"arrayBuffer"` | `"formData"` | `"stream"` | `"raw"` | `"sse"` Defined in: [src/types/instance.ts:35](https://github.com/haihv/valifetch/blob/285835d38a6676b98d2ee1a93e23166c6c834cb2/src/types/instance.ts#L35) Response format options --- --- url: https://haihv.github.io/valifetch/api/index/type-aliases/RetryContext.md --- # Type Alias: RetryContext > **RetryContext** = `object` & ({ `error?`: `undefined`; `reason`: `"status"`; `response`: `Response`; } | { `error`: `Error`; `reason`: `"network"`; `response?`: `undefined`; }) Defined in: [src/types/options.ts:42](https://github.com/haihv/valifetch/blob/285835d38a6676b98d2ee1a93e23166c6c834cb2/src/types/options.ts#L42) Context passed to `RetryOptions.shouldRetry` — the failure that may be retried. Exactly one of `response` / `error` is set, discriminated by `reason`. ## Type Declaration ### request > **request**: `Request` The request that failed (the template that will be re-sent) ### retryCount > **retryCount**: `number` 1-based number of the retry being considered (`1` = first retry) --- --- url: https://haihv.github.io/valifetch/api/index/type-aliases/RetryOptions.md --- # Type Alias: RetryOptions > **RetryOptions** = `object` Defined in: [src/types/options.ts:71](https://github.com/haihv/valifetch/blob/285835d38a6676b98d2ee1a93e23166c6c834cb2/src/types/options.ts#L71) Retry configuration. A per-request or child-instance `retry` value replaces the instance `retry` object entirely (fields, including `maxRetryAfter`, are not merged with the parent's); unset fields take the built-in defaults. ## Properties ### delay? > `optional` **delay?**: (`attemptCount`) => `number` Defined in: [src/types/options.ts:84](https://github.com/haihv/valifetch/blob/285835d38a6676b98d2ee1a93e23166c6c834cb2/src/types/options.ts#L84) Custom delay function returning the milliseconds to wait before the next attempt. `attemptCount` is 0-based, so `delay(0)` precedes the first retry. #### Parameters ##### attemptCount `number` #### Returns `number` #### Default ```ts (attemptCount) => 0.3 * 2 ** attemptCount seconds, plus up to 20% jitter, capped at 30 s ``` *** ### limit? > `optional` **limit?**: `number` Defined in: [src/types/options.ts:73](https://github.com/haihv/valifetch/blob/285835d38a6676b98d2ee1a93e23166c6c834cb2/src/types/options.ts#L73) Max retry attempts (default: 2) *** ### maxRetryAfter? > `optional` **maxRetryAfter?**: `number` Defined in: [src/types/options.ts:103](https://github.com/haihv/valifetch/blob/285835d38a6676b98d2ee1a93e23166c6c834cb2/src/types/options.ts#L103) Longest server-sent `Retry-After` delay, in milliseconds, the client is willing to wait. When a retryable response asks for longer (integer seconds or HTTP-date), the request is NOT retried: the response is handled as if retries were exhausted (an `HTTP_ERROR` through `beforeError`, or returned as-is with `throwHttpErrors: false`). The check runs after `shouldRetry` says "retry" and before `beforeRetry`, so no `beforeRetry` hook or `retry` debug event fires for it. `Infinity` honours any value (the wait itself is still clamped to the ~24.8-day `setTimeout` limit); a non-number, `NaN` or negative value falls back to the default. A malformed `Retry-After` (not all-digit seconds, not an HTTP-date) is ignored in favour of `delay`. A per-request or child-instance `retry` value replaces the instance `retry` object entirely (fields are not merged), so restate `maxRetryAfter` there if you changed it. #### Default ```ts 60000 ``` *** ### methods? > `optional` **methods?**: [`HttpMethod`](HttpMethod.md)\[] Defined in: [src/types/options.ts:75](https://github.com/haihv/valifetch/blob/285835d38a6676b98d2ee1a93e23166c6c834cb2/src/types/options.ts#L75) Methods to retry (default: GET, PUT, HEAD, DELETE, OPTIONS) *** ### shouldRetry? > `optional` **shouldRetry?**: (`context`) => `boolean` | `undefined` | `Promise`<`boolean` | `undefined`> Defined in: [src/types/options.ts:112](https://github.com/haihv/valifetch/blob/285835d38a6676b98d2ee1a93e23166c6c834cb2/src/types/options.ts#L112) Custom retry predicate. Return `true` to retry even when `statusCodes`/`methods` would not, `false` to never retry this failure, or `undefined` to defer to the built-in status-code + method check. Always bounded by `limit`. Runs before `beforeRetry` hooks and only for failed responses (`response.ok === false`) or network errors. May be async (e.g. inspect `response.clone().json()`). A throwing predicate aborts the request with that error. #### Parameters ##### context [`RetryContext`](RetryContext.md) #### Returns `boolean` | `undefined` | `Promise`<`boolean` | `undefined`> *** ### statusCodes? > `optional` **statusCodes?**: `number`\[] Defined in: [src/types/options.ts:77](https://github.com/haihv/valifetch/blob/285835d38a6676b98d2ee1a93e23166c6c834cb2/src/types/options.ts#L77) Status codes to retry (default: 408, 413, 429, 500, 502, 503, 504) --- --- url: https://haihv.github.io/valifetch/api/index/type-aliases/SearchParamsInit.md --- # Type Alias: SearchParamsInit > **SearchParamsInit** = `string` | `URLSearchParams` | `Record`<`string`, `string` | `number` | `boolean` | `undefined` | `null`> | \[`string`, `string` | `number` | `boolean` | `undefined` | `null`]\[] Defined in: [src/types/options.ts:32](https://github.com/haihv/valifetch/blob/285835d38a6676b98d2ee1a93e23166c6c834cb2/src/types/options.ts#L32) Search params can be various formats --- --- url: >- https://haihv.github.io/valifetch/api/index/type-aliases/ValidationErrorInfo.md --- # Type Alias: ValidationErrorInfo > **ValidationErrorInfo** = `object` Defined in: [src/errors/ValifetchError.ts:7](https://github.com/haihv/valifetch/blob/285835d38a6676b98d2ee1a93e23166c6c834cb2/src/errors/ValifetchError.ts#L7) Validation error details ## Properties ### input > **input**: `unknown` Defined in: [src/errors/ValifetchError.ts:13](https://github.com/haihv/valifetch/blob/285835d38a6676b98d2ee1a93e23166c6c834cb2/src/errors/ValifetchError.ts#L13) The invalid data that was validated *** ### issues > **issues**: `BaseIssue`<`unknown`>\[] Defined in: [src/errors/ValifetchError.ts:11](https://github.com/haihv/valifetch/blob/285835d38a6676b98d2ee1a93e23166c6c834cb2/src/errors/ValifetchError.ts#L11) Valibot issues array *** ### target > **target**: [`ValidationTarget`](ValidationTarget.md) Defined in: [src/errors/ValifetchError.ts:9](https://github.com/haihv/valifetch/blob/285835d38a6676b98d2ee1a93e23166c6c834cb2/src/errors/ValifetchError.ts#L9) Which validation failed --- --- url: https://haihv.github.io/valifetch/api/index/type-aliases/ValidationTarget.md --- # Type Alias: ValidationTarget > **ValidationTarget** = `"response"` | `"body"` | `"params"` | `"search"` Defined in: [src/types/options.ts:131](https://github.com/haihv/valifetch/blob/285835d38a6676b98d2ee1a93e23166c6c834cb2/src/types/options.ts#L131) Validation target types --- --- url: >- https://haihv.github.io/valifetch/api/index/type-aliases/ValifetchBaseOptions.md --- # Type Alias: ValifetchBaseOptions > **ValifetchBaseOptions** = `Omit`<`RequestInit`, `"body"` | `"method"` | `"window"`> & `object` Defined in: [src/types/options.ts:203](https://github.com/haihv/valifetch/blob/285835d38a6676b98d2ee1a93e23166c6c834cb2/src/types/options.ts#L203) Base options without schemas (for internal use) ## Type Declaration ### debug? > `optional` **debug?**: [`DebugOption`](DebugOption.md) Enable structured debug logging of request lifecycle events. Pass `true` to emit via `console.debug`, or a function to handle events directly. ### dedupe? > `optional` **dedupe?**: `boolean` Deduplicate concurrent identical requests. The dedupe key is `method` plus the fully-resolved URL — `prefixUrl` + path params + merged search params, computed from the raw pre-validation values — scoped per instance (including instances created via `create()` with no arguments, each of which gets its own cache). The key deliberately excludes headers, the request body, and schemas, so two calls that differ only by header or body are treated as identical and collapsed into one in-flight request — avoid enabling `dedupe` for such calls, and avoid it on non-idempotent methods (POST, PATCH, DELETE) where collapsing distinct requests would be incorrect. Calling `.cancel()` on a deduplicated promise aborts the shared request for every caller awaiting it. #### Default ```ts false ``` ### hooks? > `optional` **hooks?**: [`Hooks`](Hooks.md) Hooks for request lifecycle ### onDownloadProgress? > `optional` **onDownloadProgress?**: (`event`) => `void` Callback fired as response body bytes are received. Not called when `responseType` is `'stream'`, `'raw'` or `'sse'` — the caller owns the stream in those modes. #### Parameters ##### event [`DownloadProgressEvent`](DownloadProgressEvent.md) #### Returns `void` ### prefixUrl? > `optional` **prefixUrl?**: `string` Base URL prefix for all requests. Resolved request paths must stay under it (a `..` escape throws a `TypeError`). Must not contain a query string or fragment (`?`/`#` throws a `TypeError`); use `searchParams` for defaults. ### retry? > `optional` **retry?**: [`RetryOptions`](RetryOptions.md) | `number` | `false` Retry configuration or limit number ### searchParams? > `optional` **searchParams?**: [`SearchParamsInit`](SearchParamsInit.md) Search/query parameters. Instance-level values act as defaults: per-request params are merged on top, and a key present in both is taken from the request (all instance-level entries for that key are dropped). A request key explicitly set to `undefined`/`null` removes the instance default for that key entirely, rather than leaving it in place. ### sseMaxEventSize? > `optional` **sseMaxEventSize?**: `number` Largest single Server-Sent Event the `responseType: 'sse'` parser buffers, in UTF-16 code units (one per ASCII character). A pending event that grows past it cancels the stream and throws a `PARSE_ERROR`, bounding memory against a server that never sends an event boundary. `Infinity` disables the cap; a non-number, `NaN` or negative value falls back to the default. Allowed at instance level (merged by `create`/`extend`) and per call; the per-call value wins. Ignored for every other `responseType`. #### Default ```ts 16777216 (16 MiB) ``` ### throwHttpErrors? > `optional` **throwHttpErrors?**: `boolean` Throw on non-2xx status codes (default: true) ### timeout? > `optional` **timeout?**: `number` Request timeout in milliseconds. #### Default undefined — requests never time out; `0` also disables the timeout ### validateRequest? > `optional` **validateRequest?**: `boolean` Enable/disable request body/params/search validation (default: true) ### validateResponse? > `optional` **validateResponse?**: `boolean` Enable/disable response schema validation (default: true) --- --- url: >- https://haihv.github.io/valifetch/api/index/type-aliases/ValifetchErrorOptions.md --- # Type Alias: ValifetchErrorOptions > **ValifetchErrorOptions** = `object` Defined in: [src/errors/ValifetchError.ts:19](https://github.com/haihv/valifetch/blob/285835d38a6676b98d2ee1a93e23166c6c834cb2/src/errors/ValifetchError.ts#L19) Options for creating a ValifetchError ## Properties ### cause? > `optional` **cause?**: `unknown` Defined in: [src/errors/ValifetchError.ts:35](https://github.com/haihv/valifetch/blob/285835d38a6676b98d2ee1a93e23166c6c834cb2/src/errors/ValifetchError.ts#L35) Original error cause. Typed as `unknown` to match the standard `Error.cause`, so any thrown value (not just an `Error`) can be passed through without wrapping. *** ### code > **code**: [`ErrorCode`](ErrorCode.md) Defined in: [src/errors/ValifetchError.ts:23](https://github.com/haihv/valifetch/blob/285835d38a6676b98d2ee1a93e23166c6c834cb2/src/errors/ValifetchError.ts#L23) Error code for pattern matching *** ### message > **message**: `string` Defined in: [src/errors/ValifetchError.ts:21](https://github.com/haihv/valifetch/blob/285835d38a6676b98d2ee1a93e23166c6c834cb2/src/errors/ValifetchError.ts#L21) Error message *** ### request? > `optional` **request?**: `Request` Defined in: [src/errors/ValifetchError.ts:25](https://github.com/haihv/valifetch/blob/285835d38a6676b98d2ee1a93e23166c6c834cb2/src/errors/ValifetchError.ts#L25) HTTP request that caused the error *** ### response? > `optional` **response?**: `Response` Defined in: [src/errors/ValifetchError.ts:27](https://github.com/haihv/valifetch/blob/285835d38a6676b98d2ee1a93e23166c6c834cb2/src/errors/ValifetchError.ts#L27) HTTP response (if received) *** ### responseBody? > `optional` **responseBody?**: `unknown` Defined in: [src/errors/ValifetchError.ts:42](https://github.com/haihv/valifetch/blob/285835d38a6676b98d2ee1a93e23166c6c834cb2/src/errors/ValifetchError.ts#L42) Parsed response body on `HTTP_ERROR` (JSON-parsed object/array, or plain text when the body is not valid JSON) and raw text on `PARSE_ERROR` (the response body that failed to parse as JSON). `undefined` when the body could not be read at all. *** ### validation? > `optional` **validation?**: [`ValidationErrorInfo`](ValidationErrorInfo.md) Defined in: [src/errors/ValifetchError.ts:29](https://github.com/haihv/valifetch/blob/285835d38a6676b98d2ee1a93e23166c6c834cb2/src/errors/ValifetchError.ts#L29) Validation error details (if validation failed) --- --- url: https://haihv.github.io/valifetch/api/index/type-aliases/ValifetchInstance.md --- # Type Alias: ValifetchInstance > **ValifetchInstance** = `object` Defined in: [src/types/instance.ts:282](https://github.com/haihv/valifetch/blob/285835d38a6676b98d2ee1a93e23166c6c834cb2/src/types/instance.ts#L282) The main valifetch instance type ## Methods ### all() > **all**<`T`>(`requests`): [`CancellablePromise`](CancellablePromise.md)<{ -readonly \[P in string | number | symbol]: Awaited\ }> Defined in: [src/types/instance.ts:427](https://github.com/haihv/valifetch/blob/285835d38a6676b98d2ee1a93e23166c6c834cb2/src/types/instance.ts#L427) Run multiple requests in parallel and resolve to a tuple of their results, preserving each element's type (sugar over `Promise.all`). Rejects as soon as any input rejects. The returned promise is cancellable: `.cancel()` aborts every input that exposes a `.cancel()` method (e.g. other valifetch requests); inputs without one are ignored. A rejection does not cancel the remaining requests. #### Type Parameters ##### T `T` *extends* \[] | readonly `unknown`\[] #### Parameters ##### requests `T` #### Returns [`CancellablePromise`](CancellablePromise.md)<{ -readonly \[P in string | number | symbol]: Awaited\ }> #### Example ```ts const [user, posts] = await api.all([ api.get('/users/1', { responseSchema: UserSchema }), api.get('/posts', { responseSchema: PostsSchema }), ]); ``` *** ### allSettled() > **allSettled**<`T`>(`requests`): [`CancellablePromise`](CancellablePromise.md)<{ -readonly \[P in string | number | symbol]: PromiseSettledResult\> }> Defined in: [src/types/instance.ts:450](https://github.com/haihv/valifetch/blob/285835d38a6676b98d2ee1a93e23166c6c834cb2/src/types/instance.ts#L450) Run multiple requests in parallel and resolve once all have settled, never rejecting (sugar over `Promise.allSettled`). Each result is a standard `PromiseSettledResult`: `{ status: 'fulfilled', value }` or `{ status: 'rejected', reason }` (the `reason` is typically a `ValifetchError`). The returned promise is cancellable: `.cancel()` aborts every input that exposes a `.cancel()` method; inputs without one are ignored. A rejection does not cancel the remaining requests. #### Type Parameters ##### T `T` *extends* \[] | readonly `unknown`\[] #### Parameters ##### requests `T` #### Returns [`CancellablePromise`](CancellablePromise.md)<{ -readonly \[P in string | number | symbol]: PromiseSettledResult\> }> #### Example ```ts const results = await api.allSettled([api.get('/a'), api.get('/b')]); for (const r of results) { if (r.status === 'fulfilled') console.log(r.value); else console.error(r.reason); } ``` *** ### callable() > **callable**(): [`CallableInstance`](CallableInstance.md) Defined in: [src/types/instance.ts:467](https://github.com/haihv/valifetch/blob/285835d38a6676b98d2ee1a93e23166c6c834cb2/src/types/instance.ts#L467) Wrap instance for callable ky-style syntax #### Returns [`CallableInstance`](CallableInstance.md) *** ### create() > **create**(`options?`): `ValifetchInstance` Defined in: [src/types/instance.ts:457](https://github.com/haihv/valifetch/blob/285835d38a6676b98d2ee1a93e23166c6c834cb2/src/types/instance.ts#L457) Create new instance with defaults #### Parameters ##### options? [`ValifetchInstanceOptions`](ValifetchInstanceOptions.md) #### Returns `ValifetchInstance` *** ### delete() > **delete**<`TData`, `TPath`, `TResponseSchema`, `TParamsSchema`, `TSearchSchema`>(`url`, `options?`): [`CancellablePromise`](CancellablePromise.md)<`ResolveResponseType`<`TData`, `TResponseSchema`>> Defined in: [src/types/instance.ts:368](https://github.com/haihv/valifetch/blob/285835d38a6676b98d2ee1a93e23166c6c834cb2/src/types/instance.ts#L368) DELETE request - returns parsed JSON by default #### Type Parameters ##### TData `TData` = `unknown` Generic type for response (used when no schema provided) ##### TPath `TPath` *extends* `string` = `string` ##### TResponseSchema `TResponseSchema` *extends* `GenericSchema` | `undefined` = `undefined` ##### TParamsSchema `TParamsSchema` *extends* `GenericSchema` | `undefined` = `undefined` ##### TSearchSchema `TSearchSchema` *extends* `GenericSchema` | `undefined` = `undefined` #### Parameters ##### url `TPath` ##### options? [`GetOptions`](GetOptions.md)<`TPath`, `TResponseSchema`, `TParamsSchema`, `TSearchSchema`> #### Returns [`CancellablePromise`](CancellablePromise.md)<`ResolveResponseType`<`TData`, `TResponseSchema`>> *** ### extend() > **extend**(`options`): `ValifetchInstance` Defined in: [src/types/instance.ts:460](https://github.com/haihv/valifetch/blob/285835d38a6676b98d2ee1a93e23166c6c834cb2/src/types/instance.ts#L460) Extend current instance with additional options #### Parameters ##### options [`ValifetchInstanceOptions`](ValifetchInstanceOptions.md) | ((`parent`) => [`ValifetchInstanceOptions`](ValifetchInstanceOptions.md)) #### Returns `ValifetchInstance` *** ### get() > **get**<`TData`, `TPath`, `TResponseSchema`, `TParamsSchema`, `TSearchSchema`>(`url`, `options?`): [`CancellablePromise`](CancellablePromise.md)<`ResolveResponseType`<`TData`, `TResponseSchema`>> Defined in: [src/types/instance.ts:287](https://github.com/haihv/valifetch/blob/285835d38a6676b98d2ee1a93e23166c6c834cb2/src/types/instance.ts#L287) GET request - returns parsed JSON by default #### Type Parameters ##### TData `TData` = `unknown` Generic type for response (used when no schema provided) ##### TPath `TPath` *extends* `string` = `string` ##### TResponseSchema `TResponseSchema` *extends* `GenericSchema` | `undefined` = `undefined` ##### TParamsSchema `TParamsSchema` *extends* `GenericSchema` | `undefined` = `undefined` ##### TSearchSchema `TSearchSchema` *extends* `GenericSchema` | `undefined` = `undefined` #### Parameters ##### url `TPath` ##### options? [`GetOptions`](GetOptions.md)<`TPath`, `TResponseSchema`, `TParamsSchema`, `TSearchSchema`> #### Returns [`CancellablePromise`](CancellablePromise.md)<`ResolveResponseType`<`TData`, `TResponseSchema`>> *** ### head() > **head**<`TPath`, `TParamsSchema`, `TSearchSchema`>(`url`, `options?`): [`CancellablePromise`](CancellablePromise.md)<`void`> Defined in: [src/types/instance.ts:383](https://github.com/haihv/valifetch/blob/285835d38a6676b98d2ee1a93e23166c6c834cb2/src/types/instance.ts#L383) HEAD request — always resolves to `void`; the response body is never read, so `responseType` and `responseSchema` are not accepted. #### Type Parameters ##### TPath `TPath` *extends* `string` = `string` ##### TParamsSchema `TParamsSchema` *extends* `GenericSchema` | `undefined` = `undefined` ##### TSearchSchema `TSearchSchema` *extends* `GenericSchema` | `undefined` = `undefined` #### Parameters ##### url `TPath` ##### options? `Omit`<[`GetOptions`](GetOptions.md)<`TPath`, `undefined`, `TParamsSchema`, `TSearchSchema`>, `"responseSchema"` | `"responseType"`> #### Returns [`CancellablePromise`](CancellablePromise.md)<`void`> *** ### options() > **options**<`TData`, `TPath`, `TResponseSchema`, `TParamsSchema`, `TSearchSchema`>(`url`, `options?`): [`CancellablePromise`](CancellablePromise.md)<`ResolveResponseType`<`TData`, `TResponseSchema`>> Defined in: [src/types/instance.ts:399](https://github.com/haihv/valifetch/blob/285835d38a6676b98d2ee1a93e23166c6c834cb2/src/types/instance.ts#L399) OPTIONS request - returns parsed JSON by default #### Type Parameters ##### TData `TData` = `unknown` Generic type for response (used when no schema provided) ##### TPath `TPath` *extends* `string` = `string` ##### TResponseSchema `TResponseSchema` *extends* `GenericSchema` | `undefined` = `undefined` ##### TParamsSchema `TParamsSchema` *extends* `GenericSchema` | `undefined` = `undefined` ##### TSearchSchema `TSearchSchema` *extends* `GenericSchema` | `undefined` = `undefined` #### Parameters ##### url `TPath` ##### options? [`GetOptions`](GetOptions.md)<`TPath`, `TResponseSchema`, `TParamsSchema`, `TSearchSchema`> #### Returns [`CancellablePromise`](CancellablePromise.md)<`ResolveResponseType`<`TData`, `TResponseSchema`>> *** ### patch() > **patch**<`TData`, `TPath`, `TResponseSchema`, `TBodySchema`, `TParamsSchema`, `TSearchSchema`>(`url`, `options?`): [`CancellablePromise`](CancellablePromise.md)<`ResolveResponseType`<`TData`, `TResponseSchema`>> Defined in: [src/types/instance.ts:346](https://github.com/haihv/valifetch/blob/285835d38a6676b98d2ee1a93e23166c6c834cb2/src/types/instance.ts#L346) PATCH request - returns parsed JSON by default #### Type Parameters ##### TData `TData` = `unknown` Generic type for response (used when no schema provided) ##### TPath `TPath` *extends* `string` = `string` ##### TResponseSchema `TResponseSchema` *extends* `GenericSchema` | `undefined` = `undefined` ##### TBodySchema `TBodySchema` *extends* `GenericSchema` | `undefined` = `undefined` ##### TParamsSchema `TParamsSchema` *extends* `GenericSchema` | `undefined` = `undefined` ##### TSearchSchema `TSearchSchema` *extends* `GenericSchema` | `undefined` = `undefined` #### Parameters ##### url `TPath` ##### options? [`PostOptions`](PostOptions.md)<`TPath`, `TResponseSchema`, `TBodySchema`, `TParamsSchema`, `TSearchSchema`> #### Returns [`CancellablePromise`](CancellablePromise.md)<`ResolveResponseType`<`TData`, `TResponseSchema`>> *** ### post() > **post**<`TData`, `TPath`, `TResponseSchema`, `TBodySchema`, `TParamsSchema`, `TSearchSchema`>(`url`, `options?`): [`CancellablePromise`](CancellablePromise.md)<`ResolveResponseType`<`TData`, `TResponseSchema`>> Defined in: [src/types/instance.ts:302](https://github.com/haihv/valifetch/blob/285835d38a6676b98d2ee1a93e23166c6c834cb2/src/types/instance.ts#L302) POST request - returns parsed JSON by default #### Type Parameters ##### TData `TData` = `unknown` Generic type for response (used when no schema provided) ##### TPath `TPath` *extends* `string` = `string` ##### TResponseSchema `TResponseSchema` *extends* `GenericSchema` | `undefined` = `undefined` ##### TBodySchema `TBodySchema` *extends* `GenericSchema` | `undefined` = `undefined` ##### TParamsSchema `TParamsSchema` *extends* `GenericSchema` | `undefined` = `undefined` ##### TSearchSchema `TSearchSchema` *extends* `GenericSchema` | `undefined` = `undefined` #### Parameters ##### url `TPath` ##### options? [`PostOptions`](PostOptions.md)<`TPath`, `TResponseSchema`, `TBodySchema`, `TParamsSchema`, `TSearchSchema`> #### Returns [`CancellablePromise`](CancellablePromise.md)<`ResolveResponseType`<`TData`, `TResponseSchema`>> *** ### put() > **put**<`TData`, `TPath`, `TResponseSchema`, `TBodySchema`, `TParamsSchema`, `TSearchSchema`>(`url`, `options?`): [`CancellablePromise`](CancellablePromise.md)<`ResolveResponseType`<`TData`, `TResponseSchema`>> Defined in: [src/types/instance.ts:324](https://github.com/haihv/valifetch/blob/285835d38a6676b98d2ee1a93e23166c6c834cb2/src/types/instance.ts#L324) PUT request - returns parsed JSON by default #### Type Parameters ##### TData `TData` = `unknown` Generic type for response (used when no schema provided) ##### TPath `TPath` *extends* `string` = `string` ##### TResponseSchema `TResponseSchema` *extends* `GenericSchema` | `undefined` = `undefined` ##### TBodySchema `TBodySchema` *extends* `GenericSchema` | `undefined` = `undefined` ##### TParamsSchema `TParamsSchema` *extends* `GenericSchema` | `undefined` = `undefined` ##### TSearchSchema `TSearchSchema` *extends* `GenericSchema` | `undefined` = `undefined` #### Parameters ##### url `TPath` ##### options? [`PostOptions`](PostOptions.md)<`TPath`, `TResponseSchema`, `TBodySchema`, `TParamsSchema`, `TSearchSchema`> #### Returns [`CancellablePromise`](CancellablePromise.md)<`ResolveResponseType`<`TData`, `TResponseSchema`>> --- --- url: >- https://haihv.github.io/valifetch/api/index/type-aliases/ValifetchInstanceOptions.md --- # Type Alias: ValifetchInstanceOptions > **ValifetchInstanceOptions** = `Omit`<[`ValifetchBaseOptions`](ValifetchBaseOptions.md), `"signal"`> & `object` Defined in: [src/types/options.ts:371](https://github.com/haihv/valifetch/blob/285835d38a6676b98d2ee1a93e23166c6c834cb2/src/types/options.ts#L371) Instance options for create/extend ## Type Declaration ### headers? > `optional` **headers?**: `HeadersInit` Default headers for all requests --- --- url: https://haihv.github.io/valifetch/api/index/type-aliases/ValifetchOptions.md --- # Type Alias: ValifetchOptions\ > **ValifetchOptions**<`TPath`, `TResponseSchema`, `TBodySchema`, `TParamsSchema`, `TSearchSchema`> = [`ValifetchBaseOptions`](ValifetchBaseOptions.md) & `object` Defined in: [src/types/options.ts:328](https://github.com/haihv/valifetch/blob/285835d38a6676b98d2ee1a93e23166c6c834cb2/src/types/options.ts#L328) Schema-aware options with full type inference ## Type Parameters ### TPath `TPath` *extends* `string` = `string` ### TResponseSchema `TResponseSchema` *extends* `GenericSchema` | `undefined` = `undefined` ### TBodySchema `TBodySchema` *extends* `GenericSchema` | `undefined` = `undefined` ### TParamsSchema `TParamsSchema` *extends* `GenericSchema` | `undefined` = `undefined` ### TSearchSchema `TSearchSchema` *extends* `GenericSchema` | `undefined` = `undefined` ## Type Declaration ### body? > `optional` **body?**: [`RawBody`](RawBody.md) Raw body sent exactly as given (string, `Blob`, `ArrayBuffer`, typed array, or `ReadableStream`). Set `Content-Type` yourself — valifetch never infers one (the `Request` constructor's own default still applies to `string` and `Blob` bodies). Mutually exclusive with `json` and `form`, and accepted per request only (never at instance level). `ReadableStream` bodies get `duplex: 'half'` automatically. ### bodySchema? > `optional` **bodySchema?**: `TBodySchema` Schema to validate request body ### form? > `optional` **form?**: `FormData` | `URLSearchParams` | `Record`<`string`, `string`> Form body — `FormData` sends `multipart/form-data`; `URLSearchParams` or a plain object sends `application/x-www-form-urlencoded`. Mutually exclusive with `json`, and accepted per request only (never at instance level). ### json? > `optional` **json?**: `TBodySchema` *extends* `GenericSchema` ? `InferInput`<`TBodySchema`> : `unknown` JSON body - validated against bodySchema if provided ### params? > `optional` **params?**: `TParamsSchema` *extends* `GenericSchema` ? `InferInput`<`TParamsSchema`> : [`ExtractPathParams`](ExtractPathParams.md)<`TPath`> *extends* `never` ? `undefined` : [`PathParamsRecord`](PathParamsRecord.md)<`TPath`> URL path parameters ### paramsSchema? > `optional` **paramsSchema?**: `TParamsSchema` Schema to validate URL path params ### responseSchema? > `optional` **responseSchema?**: `TResponseSchema` Schema to validate response body ### searchSchema? > `optional` **searchSchema?**: `TSearchSchema` Schema to validate search/query params --- --- url: https://haihv.github.io/valifetch/api/index/variables/default.md --- # Variable: default > `const` **default**: [`ValifetchInstance`](../type-aliases/ValifetchInstance.md) = `valifetch` Defined in: [src/core/valifetch.ts:921](https://github.com/haihv/valifetch/blob/285835d38a6676b98d2ee1a93e23166c6c834cb2/src/core/valifetch.ts#L921) Default export alias — enables `import valifetch from 'valifetch'` syntax. --- --- url: https://haihv.github.io/valifetch/api/index/variables/stop.md --- # Variable: stop > `const` **stop**: unique `symbol` Defined in: [src/core/stop.ts:8](https://github.com/haihv/valifetch/blob/285835d38a6676b98d2ee1a93e23166c6c834cb2/src/core/stop.ts#L8) Sentinel returned from a `beforeRetry` hook to abort the retry loop. Registered globally via `Symbol.for` so the CJS and ESM builds share a single identity — a plain `Symbol()` would produce two distinct values and `return stop` would be silently ignored for consumers that mix module formats. --- --- url: https://haihv.github.io/valifetch/api/index/variables/valifetch.md --- # Variable: valifetch > `const` **valifetch**: [`ValifetchInstance`](../type-aliases/ValifetchInstance.md) Defined in: [src/core/valifetch.ts:918](https://github.com/haihv/valifetch/blob/285835d38a6676b98d2ee1a93e23166c6c834cb2/src/core/valifetch.ts#L918) The default valifetch instance. Use `.get()`, `.post()`, etc. directly, or call `.create()` / `.extend()` to make a configured instance. ## Example ```ts const data = await valifetch.get('https://api.example.com/users/1'); ``` --- --- url: https://haihv.github.io/valifetch/api/error.md --- # valifetch/error Standalone error export — import `ValifetchError` and related types without pulling in the full valifetch client. ## Example ```ts import { ValifetchError } from 'valifetch/error'; ``` ## References ### ErrorCode Re-exports [ErrorCode](../index/type-aliases/ErrorCode.md) *** ### ValidationErrorInfo Re-exports [ValidationErrorInfo](../index/type-aliases/ValidationErrorInfo.md) *** ### ValidationTarget Re-exports [ValidationTarget](../index/type-aliases/ValidationTarget.md) *** ### ValifetchError Re-exports [ValifetchError](../index/classes/ValifetchError.md) *** ### ValifetchErrorOptions Re-exports [ValifetchErrorOptions](../index/type-aliases/ValifetchErrorOptions.md) --- --- url: https://haihv.github.io/valifetch/api/types.md --- # valifetch/types Standalone types export — import valifetch TypeScript types without pulling in any runtime code. ## Example ```ts import type { ValifetchInstance, ValifetchOptions } from 'valifetch/types'; ``` ## Type Aliases * [MockCall](type-aliases/MockCall.md) * [MockHandler](type-aliases/MockHandler.md) * [ValifetchMock](type-aliases/ValifetchMock.md) ## References ### AfterParseResponseHook Re-exports [AfterParseResponseHook](../index/type-aliases/AfterParseResponseHook.md) *** ### AfterResponseHook Re-exports [AfterResponseHook](../index/type-aliases/AfterResponseHook.md) *** ### BeforeErrorHook Re-exports [BeforeErrorHook](../index/type-aliases/BeforeErrorHook.md) *** ### BeforeRequestHook Re-exports [BeforeRequestHook](../index/type-aliases/BeforeRequestHook.md) *** ### BeforeRetryHook Re-exports [BeforeRetryHook](../index/type-aliases/BeforeRetryHook.md) *** ### BeforeRetryState Re-exports [BeforeRetryState](../index/type-aliases/BeforeRetryState.md) *** ### CallableInstance Re-exports [CallableInstance](../index/type-aliases/CallableInstance.md) *** ### CancellablePromise Re-exports [CancellablePromise](../index/type-aliases/CancellablePromise.md) *** ### DebugEvent Re-exports [DebugEvent](../index/type-aliases/DebugEvent.md) *** ### DebugOption Re-exports [DebugOption](../index/type-aliases/DebugOption.md) *** ### DownloadProgressEvent Re-exports [DownloadProgressEvent](../index/type-aliases/DownloadProgressEvent.md) *** ### ErrorCode Re-exports [ErrorCode](../index/type-aliases/ErrorCode.md) *** ### ExtractPathParams Re-exports [ExtractPathParams](../index/type-aliases/ExtractPathParams.md) *** ### GetOptions Re-exports [GetOptions](../index/type-aliases/GetOptions.md) *** ### HasPathParams Re-exports [HasPathParams](../index/type-aliases/HasPathParams.md) *** ### Hooks Re-exports [Hooks](../index/type-aliases/Hooks.md) *** ### HttpMethod Re-exports [HttpMethod](../index/type-aliases/HttpMethod.md) *** ### InferResponseType Re-exports [InferResponseType](../index/type-aliases/InferResponseType.md) *** ### JwtRefreshOptions Re-exports [JwtRefreshOptions](../auth/type-aliases/JwtRefreshOptions.md) *** ### NormalizedOptions Re-exports [NormalizedOptions](../index/type-aliases/NormalizedOptions.md) *** ### PathParamsRecord Re-exports [PathParamsRecord](../index/type-aliases/PathParamsRecord.md) *** ### PostOptions Re-exports [PostOptions](../index/type-aliases/PostOptions.md) *** ### RawBody Re-exports [RawBody](../index/type-aliases/RawBody.md) *** ### ResponseType Re-exports [ResponseType](../index/type-aliases/ResponseType.md) *** ### RetryContext Re-exports [RetryContext](../index/type-aliases/RetryContext.md) *** ### RetryOptions Re-exports [RetryOptions](../index/type-aliases/RetryOptions.md) *** ### SearchParamsInit Re-exports [SearchParamsInit](../index/type-aliases/SearchParamsInit.md) *** ### ValidationErrorInfo Re-exports [ValidationErrorInfo](../index/type-aliases/ValidationErrorInfo.md) *** ### ValidationTarget Re-exports [ValidationTarget](../index/type-aliases/ValidationTarget.md) *** ### ValifetchBaseOptions Re-exports [ValifetchBaseOptions](../index/type-aliases/ValifetchBaseOptions.md) *** ### ValifetchErrorOptions Re-exports [ValifetchErrorOptions](../index/type-aliases/ValifetchErrorOptions.md) *** ### ValifetchInstance Re-exports [ValifetchInstance](../index/type-aliases/ValifetchInstance.md) *** ### ValifetchInstanceOptions Re-exports [ValifetchInstanceOptions](../index/type-aliases/ValifetchInstanceOptions.md) *** ### ValifetchOptions Re-exports [ValifetchOptions](../index/type-aliases/ValifetchOptions.md) --- --- url: https://haihv.github.io/valifetch/api/types/type-aliases/MockCall.md --- # Type Alias: MockCall > **MockCall** = `object` Defined in: [src/mock/types.ts:7](https://github.com/haihv/valifetch/blob/285835d38a6676b98d2ee1a93e23166c6c834cb2/src/mock/types.ts#L7) A recorded request intercepted by the mock. Inspect these via `mock.calls()` and `mock.lastCall()` to assert on what was sent. ## Properties ### body > **body**: `unknown` Defined in: [src/mock/types.ts:20](https://github.com/haihv/valifetch/blob/285835d38a6676b98d2ee1a93e23166c6c834cb2/src/mock/types.ts#L20) Parsed request body. JSON-parsed object/array when `Content-Type` is `application/json`, decoded text for every other body (including raw `body` payloads), `null` when the request has no body. *** ### headers > **headers**: `Record`<`string`, `string`> Defined in: [src/mock/types.ts:13](https://github.com/haihv/valifetch/blob/285835d38a6676b98d2ee1a93e23166c6c834cb2/src/mock/types.ts#L13) Request headers as a plain string-to-string object *** ### method > **method**: [`HttpMethod`](../../index/type-aliases/HttpMethod.md) Defined in: [src/mock/types.ts:9](https://github.com/haihv/valifetch/blob/285835d38a6676b98d2ee1a93e23166c6c834cb2/src/mock/types.ts#L9) HTTP method of the intercepted request *** ### searchParams > **searchParams**: `URLSearchParams` Defined in: [src/mock/types.ts:22](https://github.com/haihv/valifetch/blob/285835d38a6676b98d2ee1a93e23166c6c834cb2/src/mock/types.ts#L22) URL search/query parameters *** ### url > **url**: `string` Defined in: [src/mock/types.ts:11](https://github.com/haihv/valifetch/blob/285835d38a6676b98d2ee1a93e23166c6c834cb2/src/mock/types.ts#L11) Full URL of the intercepted request --- --- url: https://haihv.github.io/valifetch/api/types/type-aliases/MockHandler.md --- # Type Alias: MockHandler > **MockHandler** = `object` Defined in: [src/mock/types.ts:29](https://github.com/haihv/valifetch/blob/285835d38a6676b98d2ee1a93e23166c6c834cb2/src/mock/types.ts#L29) Builder returned by `mock.when()` and the HTTP method shorthands. Call `reply` or `replyOnce` (chainable) to register fixture responses. ## Methods ### reply() > **reply**(`status`, `body?`, `headers?`): `MockHandler` Defined in: [src/mock/types.ts:42](https://github.com/haihv/valifetch/blob/285835d38a6676b98d2ee1a93e23166c6c834cb2/src/mock/types.ts#L42) Register a fixture response for all matching requests. If multiple `reply`/`replyOnce` calls are made on the same handler, responses are consumed in order (queue). This response stays at the end of the queue and is reused once all preceding `replyOnce` responses are consumed. #### Parameters ##### status `number` HTTP status code ##### body? `unknown` Response body — always serialised via `JSON.stringify` (objects, arrays, strings, `null`). Pass `null` to produce a JSON `null` response. Omit entirely only for genuinely bodyless statuses (e.g. 204 No Content) — omitting on a 200/201 response will cause valifetch's JSON parser to throw. ##### headers? `HeadersInit` Additional response headers #### Returns `MockHandler` The same `MockHandler`, for chaining additional `reply`/`replyOnce` calls. *** ### replyOnce() > **replyOnce**(`status`, `body?`, `headers?`): `MockHandler` Defined in: [src/mock/types.ts:55](https://github.com/haihv/valifetch/blob/285835d38a6676b98d2ee1a93e23166c6c834cb2/src/mock/types.ts#L55) Register a fixture response that is consumed on the first matching request only. Subsequent requests fall through to the next registered response (or the real `fetch` if none remain). Mock replies are produced by a `beforeRequest` hook outside the retry loop, so the `retry` option does not retry a mocked response; each call consumes one queued reply. #### Parameters ##### status `number` HTTP status code ##### body? `unknown` Response body — always serialised via `JSON.stringify` (objects, arrays, strings, `null`). Pass `null` to produce a JSON `null` response. Omit entirely only for genuinely bodyless statuses (e.g. 204 No Content) — omitting on a 200/201 response will cause valifetch's JSON parser to throw. ##### headers? `HeadersInit` Additional response headers #### Returns `MockHandler` The same `MockHandler`, for chaining additional `reply`/`replyOnce` calls. --- --- url: https://haihv.github.io/valifetch/api/types/type-aliases/ValifetchMock.md --- # Type Alias: ValifetchMock > **ValifetchMock** = `object` Defined in: [src/mock/types.ts:65](https://github.com/haihv/valifetch/blob/285835d38a6676b98d2ee1a93e23166c6c834cb2/src/mock/types.ts#L65) A valifetch mock instance created by `createMock()`. Attach it to a valifetch instance via `extend({ hooks: mock.hooks })`. Requests that match a registered pattern are intercepted and never reach the network. Unmatched requests fall through to the real `fetch`. ## Properties ### hooks > **hooks**: `Required`<`Pick`<[`Hooks`](../../index/type-aliases/Hooks.md), `"beforeRequest"`>> Defined in: [src/mock/types.ts:101](https://github.com/haihv/valifetch/blob/285835d38a6676b98d2ee1a93e23166c6c834cb2/src/mock/types.ts#L101) Hooks to attach to a valifetch instance. #### Example ```ts const api = valifetch.extend({ hooks: mock.hooks }); ``` ## Methods ### calls() > **calls**(): [`MockCall`](MockCall.md)\[] Defined in: [src/mock/types.ts:86](https://github.com/haihv/valifetch/blob/285835d38a6676b98d2ee1a93e23166c6c834cb2/src/mock/types.ts#L86) Returns all recorded calls in the order they were intercepted #### Returns [`MockCall`](MockCall.md)\[] *** ### delete() > **delete**(`pattern`): [`MockHandler`](MockHandler.md) Defined in: [src/mock/types.ts:75](https://github.com/haihv/valifetch/blob/285835d38a6676b98d2ee1a93e23166c6c834cb2/src/mock/types.ts#L75) Register a mock handler for DELETE requests matching `pattern` #### Parameters ##### pattern `string` | `RegExp` #### Returns [`MockHandler`](MockHandler.md) *** ### get() > **get**(`pattern`): [`MockHandler`](MockHandler.md) Defined in: [src/mock/types.ts:67](https://github.com/haihv/valifetch/blob/285835d38a6676b98d2ee1a93e23166c6c834cb2/src/mock/types.ts#L67) Register a mock handler for GET requests matching `pattern` #### Parameters ##### pattern `string` | `RegExp` #### Returns [`MockHandler`](MockHandler.md) *** ### head() > **head**(`pattern`): [`MockHandler`](MockHandler.md) Defined in: [src/mock/types.ts:77](https://github.com/haihv/valifetch/blob/285835d38a6676b98d2ee1a93e23166c6c834cb2/src/mock/types.ts#L77) Register a mock handler for HEAD requests matching `pattern` #### Parameters ##### pattern `string` | `RegExp` #### Returns [`MockHandler`](MockHandler.md) *** ### lastCall() > **lastCall**(): [`MockCall`](MockCall.md) | `undefined` Defined in: [src/mock/types.ts:90](https://github.com/haihv/valifetch/blob/285835d38a6676b98d2ee1a93e23166c6c834cb2/src/mock/types.ts#L90) Returns the last recorded call, or `undefined` if no requests have been intercepted yet. #### Returns [`MockCall`](MockCall.md) | `undefined` *** ### options() > **options**(`pattern`): [`MockHandler`](MockHandler.md) Defined in: [src/mock/types.ts:79](https://github.com/haihv/valifetch/blob/285835d38a6676b98d2ee1a93e23166c6c834cb2/src/mock/types.ts#L79) Register a mock handler for OPTIONS requests matching `pattern` #### Parameters ##### pattern `string` | `RegExp` #### Returns [`MockHandler`](MockHandler.md) *** ### patch() > **patch**(`pattern`): [`MockHandler`](MockHandler.md) Defined in: [src/mock/types.ts:73](https://github.com/haihv/valifetch/blob/285835d38a6676b98d2ee1a93e23166c6c834cb2/src/mock/types.ts#L73) Register a mock handler for PATCH requests matching `pattern` #### Parameters ##### pattern `string` | `RegExp` #### Returns [`MockHandler`](MockHandler.md) *** ### post() > **post**(`pattern`): [`MockHandler`](MockHandler.md) Defined in: [src/mock/types.ts:69](https://github.com/haihv/valifetch/blob/285835d38a6676b98d2ee1a93e23166c6c834cb2/src/mock/types.ts#L69) Register a mock handler for POST requests matching `pattern` #### Parameters ##### pattern `string` | `RegExp` #### Returns [`MockHandler`](MockHandler.md) *** ### put() > **put**(`pattern`): [`MockHandler`](MockHandler.md) Defined in: [src/mock/types.ts:71](https://github.com/haihv/valifetch/blob/285835d38a6676b98d2ee1a93e23166c6c834cb2/src/mock/types.ts#L71) Register a mock handler for PUT requests matching `pattern` #### Parameters ##### pattern `string` | `RegExp` #### Returns [`MockHandler`](MockHandler.md) *** ### reset() > **reset**(): `void` Defined in: [src/mock/types.ts:92](https://github.com/haihv/valifetch/blob/285835d38a6676b98d2ee1a93e23166c6c834cb2/src/mock/types.ts#L92) Clear all registered handlers and recorded calls #### Returns `void` *** ### when() > **when**(`method`, `pattern`): [`MockHandler`](MockHandler.md) Defined in: [src/mock/types.ts:84](https://github.com/haihv/valifetch/blob/285835d38a6676b98d2ee1a93e23166c6c834cb2/src/mock/types.ts#L84) Register a mock handler for the given method and pattern. Pass `'*'` as `method` to match any HTTP method. #### Parameters ##### method [`HttpMethod`](../../index/type-aliases/HttpMethod.md) | `"*"` ##### pattern `string` | `RegExp` #### Returns [`MockHandler`](MockHandler.md) --- --- url: https://haihv.github.io/valifetch/api/auth.md --- # valifetch/auth Built-in `beforeRequest` hook factories for common authentication patterns. Import from the `valifetch/auth` subpath so the auth code is tree-shaken out of bundles that don't use it. ## Example ```ts import valifetch from 'valifetch'; import { bearerAuth, basicAuth, jwtRefresh } from 'valifetch/auth'; const api = valifetch.create({ hooks: { beforeRequest: [bearerAuth(() => localStorage.getItem('token'))], }, }); ``` ## Type Aliases * [JwtRefreshOptions](type-aliases/JwtRefreshOptions.md) ## Functions * [basicAuth](functions/basicAuth.md) * [bearerAuth](functions/bearerAuth.md) * [jwtRefresh](functions/jwtRefresh.md) --- --- url: https://haihv.github.io/valifetch/api/auth/type-aliases/JwtRefreshOptions.md --- # Type Alias: JwtRefreshOptions > **JwtRefreshOptions** = `object` Defined in: [src/auth.ts:27](https://github.com/haihv/valifetch/blob/285835d38a6676b98d2ee1a93e23166c6c834cb2/src/auth.ts#L27) Options for the [jwtRefresh](../functions/jwtRefresh.md) hook factory. ## Properties ### getToken > **getToken**: () => `string` | `null` | `undefined` Defined in: [src/auth.ts:29](https://github.com/haihv/valifetch/blob/285835d38a6676b98d2ee1a93e23166c6c834cb2/src/auth.ts#L29) Returns the current access token, or `null`/`undefined` if not yet set. #### Returns `string` | `null` | `undefined` *** ### isExpired > **isExpired**: (`token`) => `boolean` Defined in: [src/auth.ts:34](https://github.com/haihv/valifetch/blob/285835d38a6676b98d2ee1a93e23166c6c834cb2/src/auth.ts#L34) Returns `true` when the token must be refreshed before the next request. Called only when `getToken()` returns a non-null value. #### Parameters ##### token `string` #### Returns `boolean` *** ### onRefreshed? > `optional` **onRefreshed?**: (`token`) => `void` | `Promise`<`void`> Defined in: [src/auth.ts:46](https://github.com/haihv/valifetch/blob/285835d38a6676b98d2ee1a93e23166c6c834cb2/src/auth.ts#L46) Persists the new token after a successful refresh (e.g. update a store). Optional; may be synchronous or return a `Promise` — when it returns a promise, the hook awaits it before attaching the refreshed token. #### Parameters ##### token `string` #### Returns `void` | `Promise`<`void`> *** ### refresh > **refresh**: () => `Promise`<`string`> Defined in: [src/auth.ts:40](https://github.com/haihv/valifetch/blob/285835d38a6676b98d2ee1a93e23166c6c834cb2/src/auth.ts#L40) Fetches a fresh access token from the auth server. Called at most once per concurrent refresh window — all queued requests share the same in-flight refresh promise. #### Returns `Promise`<`string`> --- --- url: https://haihv.github.io/valifetch/api/auth/functions/basicAuth.md --- # Function: basicAuth() > **basicAuth**(`user`, `pass`): [`BeforeRequestHook`](../../index/type-aliases/BeforeRequestHook.md) Defined in: [src/auth.ts:113](https://github.com/haihv/valifetch/blob/285835d38a6676b98d2ee1a93e23166c6c834cb2/src/auth.ts#L113) Returns a `beforeRequest` hook that adds an `Authorization: Basic ` header before every request. Credentials are encoded once at creation time. The `user:pass` string is UTF-8 encoded before base64 (not `btoa` directly, which only supports Latin-1), so non-ASCII usernames/passwords are safe. ## Parameters ### user `string` The username (must not contain a colon). ### pass `string` The password. ## Returns [`BeforeRequestHook`](../../index/type-aliases/BeforeRequestHook.md) A `beforeRequest` hook that sets the `Authorization` header. ## Example ```ts import valifetch from 'valifetch'; import { basicAuth } from 'valifetch/auth'; const api = valifetch.create({ hooks: { beforeRequest: [basicAuth('admin', 's3cr3t')] }, }); ``` --- --- url: https://haihv.github.io/valifetch/api/auth/functions/bearerAuth.md --- # Function: bearerAuth() > **bearerAuth**(`getToken`): [`BeforeRequestHook`](../../index/type-aliases/BeforeRequestHook.md) Defined in: [src/auth.ts:69](https://github.com/haihv/valifetch/blob/285835d38a6676b98d2ee1a93e23166c6c834cb2/src/auth.ts#L69) Returns a `beforeRequest` hook that adds an `Authorization: Bearer ` header before every request. If `getToken()` returns `null` or `undefined` the header is left unset, allowing unauthenticated requests to pass through. ## Parameters ### getToken () => `string` | `null` | `undefined` Synchronous getter for the current access token. ## Returns [`BeforeRequestHook`](../../index/type-aliases/BeforeRequestHook.md) A `beforeRequest` hook that sets the `Authorization` header. ## Example ```ts import valifetch from 'valifetch'; import { bearerAuth } from 'valifetch/auth'; const api = valifetch.create({ hooks: { beforeRequest: [bearerAuth(() => localStorage.getItem('token'))] }, }); ``` --- --- url: https://haihv.github.io/valifetch/api/auth/functions/jwtRefresh.md --- # Function: jwtRefresh() > **jwtRefresh**(`opts`): [`BeforeRequestHook`](../../index/type-aliases/BeforeRequestHook.md) Defined in: [src/auth.ts:150](https://github.com/haihv/valifetch/blob/285835d38a6676b98d2ee1a93e23166c6c834cb2/src/auth.ts#L150) Returns a `beforeRequest` hook that proactively refreshes a JWT access token when it is expired before attaching it as `Authorization: Bearer `. Concurrent requests that arrive while a refresh is already in flight are queued — only **one** refresh call is made, and all waiting requests receive the same new token once it resolves. ## Parameters ### opts [`JwtRefreshOptions`](../type-aliases/JwtRefreshOptions.md) Configuration for token retrieval, expiry check, and refresh. ## Returns [`BeforeRequestHook`](../../index/type-aliases/BeforeRequestHook.md) A `beforeRequest` hook that refreshes and attaches the token as needed. ## Example ```ts import valifetch from 'valifetch'; import { jwtRefresh } from 'valifetch/auth'; const api = valifetch.create({ hooks: { beforeRequest: [ jwtRefresh({ getToken: () => store.accessToken, isExpired: (token) => isJwtExpired(token), refresh: () => authApi.post('/refresh').then((r) => r.token), onRefreshed: (token) => store.setToken(token), }), ], }, }); ``` --- --- url: https://haihv.github.io/valifetch/api/mock.md --- # valifetch/mock Standalone mock export — testing utilities for intercepting requests without patching `globalThis.fetch`. ## Example ```ts import { createMock } from 'valifetch/mock'; ``` ## Functions * [createMock](functions/createMock.md) ## References ### MockCall Re-exports [MockCall](../types/type-aliases/MockCall.md) *** ### MockHandler Re-exports [MockHandler](../types/type-aliases/MockHandler.md) *** ### ValifetchMock Re-exports [ValifetchMock](../types/type-aliases/ValifetchMock.md) --- --- url: https://haihv.github.io/valifetch/api/mock/functions/createMock.md --- # Function: createMock() > **createMock**(): [`ValifetchMock`](../../types/type-aliases/ValifetchMock.md) Defined in: [src/mock/index.ts:120](https://github.com/haihv/valifetch/blob/285835d38a6676b98d2ee1a93e23166c6c834cb2/src/mock/index.ts#L120) Creates a valifetch mock for use in tests. Register fixture responses by URL pattern and HTTP method, then attach the mock to a valifetch instance via `extend({ hooks: mock.hooks })`. Matched requests are intercepted before reaching the network; unmatched requests fall through to the real `fetch`. ## Returns [`ValifetchMock`](../../types/type-aliases/ValifetchMock.md) A `ValifetchMock` with route registration, call inspection, and hooks. ## Example ```ts import { createMock } from 'valifetch/mock'; import valifetch from 'valifetch'; const mock = createMock(); mock.get('/users').reply(200, [{ id: 1, name: 'Alice' }]); mock.post('/users').reply(201, { id: 2, name: 'Bob' }); const api = valifetch.extend({ hooks: mock.hooks }); const users = await api.get('https://api.example.com/users'); // assert(users[0].name === 'Alice') const call = mock.lastCall(); // assert(call?.method === 'GET') mock.reset(); // clear between tests ``` --- --- url: https://haihv.github.io/valifetch/api/index.md --- # valifetch Valifetch — a type-safe HTTP client built on native `fetch` with [Valibot](https://valibot.dev) schema validation. ## Example ```ts import valifetch from 'valifetch'; import * as v from 'valibot'; const UserSchema = v.object({ id: v.number(), name: v.string() }); const user = await valifetch.get('/users/1', { responseSchema: UserSchema }); ``` All public types, including the `valifetch/auth` and `valifetch/mock` option types, are also available from the zero-runtime `valifetch/types` entry point. ## Classes * [ValifetchError](classes/ValifetchError.md) ## Type Aliases * [AfterParseResponseHook](type-aliases/AfterParseResponseHook.md) * [AfterResponseHook](type-aliases/AfterResponseHook.md) * [BeforeErrorHook](type-aliases/BeforeErrorHook.md) * [BeforeRequestHook](type-aliases/BeforeRequestHook.md) * [BeforeRetryHook](type-aliases/BeforeRetryHook.md) * [BeforeRetryState](type-aliases/BeforeRetryState.md) * [CallableInstance](type-aliases/CallableInstance.md) * [CancellablePromise](type-aliases/CancellablePromise.md) * [DebugEvent](type-aliases/DebugEvent.md) * [DebugOption](type-aliases/DebugOption.md) * [DownloadProgressEvent](type-aliases/DownloadProgressEvent.md) * [ErrorCode](type-aliases/ErrorCode.md) * [ExtractPathParams](type-aliases/ExtractPathParams.md) * [GetOptions](type-aliases/GetOptions.md) * [HasPathParams](type-aliases/HasPathParams.md) * [Hooks](type-aliases/Hooks.md) * [HttpMethod](type-aliases/HttpMethod.md) * [InferResponseType](type-aliases/InferResponseType.md) * [NormalizedOptions](type-aliases/NormalizedOptions.md) * [PathParamsRecord](type-aliases/PathParamsRecord.md) * [PostOptions](type-aliases/PostOptions.md) * [RawBody](type-aliases/RawBody.md) * [ResponseType](type-aliases/ResponseType.md) * [RetryContext](type-aliases/RetryContext.md) * [RetryOptions](type-aliases/RetryOptions.md) * [SearchParamsInit](type-aliases/SearchParamsInit.md) * [ValidationErrorInfo](type-aliases/ValidationErrorInfo.md) * [ValidationTarget](type-aliases/ValidationTarget.md) * [ValifetchBaseOptions](type-aliases/ValifetchBaseOptions.md) * [ValifetchErrorOptions](type-aliases/ValifetchErrorOptions.md) * [ValifetchInstance](type-aliases/ValifetchInstance.md) * [ValifetchInstanceOptions](type-aliases/ValifetchInstanceOptions.md) * [ValifetchOptions](type-aliases/ValifetchOptions.md) ## Variables * [default](variables/default.md) * [stop](variables/stop.md) * [valifetch](variables/valifetch.md)