# StormFetch API Reference

This reference explains what each public function does, when to use it, its important inputs, and what it returns.

**Version:** `1.16.3` · **Developer:** Pradeep Kumar Sheoran (Stack Developer) · **Company:** BSG Technologies  
**Official support:** [+91-8595147850 (Also WhatsApp)](https://bsgtechnologies.com) · [Visit, learn, contribute, discuss, or accept a coffee invitation](https://bsgtechnologies.com)

[README](./README.md) · [Learn Here](./LEARN_HERE.md) · [Complete Functions List](./FUNCTIONS.md) · [Feature Inventory](./FEATURES.md) · [React Native](./REACT_NATIVE.md) · [Security](./SECURITY.md)

## How to Choose the Right Function

| Need | Use this |
| --- | --- |
| Simple REST read/write | `get`, `post`, `put`, `patch`, `delete` |
| Fetch-like one-method API | `fetch` |
| File upload | `createFormData`, `postMultipart`, `createReactNativeFile` |
| File download | `download`, `saveBlob`, native `fileSaver` |
| React UI state | `createStormFetchHooks` |
| Cache/preload/SSR hydration | `cacheManager`, `prefetch`, `dehydrateCache`, `hydrateCache` |
| Debugging API calls | `history`, `replay`, `toCurl`, `toHAR` |
| Route-based defaults | `policy` |
| Production outage protection | `circuitBreaker` |
| HTML/XML extraction | `getHtml`, `getXml`, `getDom`, `scrape`, DOM helpers |
| Streaming APIs | `streamText`, `streamJson`, `streamNdjson`, `sse` |
| Tests and demos | `createMockAdapter`, `createMockServer` |
| SDK-style services | `resource`, `contract`, `createTypedStormFetchClient` |
| Node HTTP/2 | `adapter: 'http2'` |
| Deno or Bun | automatic Fetch adapter |

## Function Responsibility Index

This index groups public functions by responsibility so users can choose the correct tool before reading the detailed signatures.

| Responsibility | Public API | Purpose |
| --- | --- | --- |
| Client setup | `createStormFetchClient`, `createFastApiClient`, `fastApi` | Create a reusable configured HTTP client |
| Mobile setup | `createReactNativeStormFetchClient` | Use Fetch safely in React Native/Expo with native storage and file saving hooks |
| Server setup | `createStormFetchServerClient` | Forward server request context during SSR or backend-to-backend calls |
| Typed API setup | `createTypedStormFetchClient`, `contract`, `generateStormFetchServicesFromOpenApi` | Turn known API contracts into typed service functions |
| Basic requests | `request`, `fetch`, `get`, `post`, `put`, `patch`, `delete`, `head`, `options` | Send HTTP calls with auth, retry, cache, interceptors, and adapters |
| Body helpers | `postJson`, `postForm`, `postMultipart`, `createFormData` | Send the correct content type without repeating headers |
| Upload/download | `createReactNativeFile`, `isReactNativeFile`, `download`, `saveBlob` | Move files across browser, Node, and mobile environments |
| React state | `createStormFetchHooks` | Create query, lazy query, mutation, and infinite query hooks from your client |
| Cache control | `cacheManager`, `clearCache`, `clearCacheAsync`, `invalidateTags` | Preload, hydrate, inspect, and invalidate cached data |
| Reliability | `policy`, retry options, queue options, `flushOfflineQueue` | Keep requests stable during network failure, high traffic, and offline states |
| Debugging | `history`, `clearHistory`, `replay`, `toCurl`, `toHAR`, `subscribe` | Inspect, reproduce, export, and observe requests with redaction |
| Content parsing | `getHtml`, `getXml`, `getDom`, `parseDom`, `scrape`, DOM helpers | Fetch and extract structured content from HTML/XML |
| Streaming | `streamText`, `streamJson`, `streamNdjson`, `sse` | Consume live or chunked responses |
| Testing | `createMockAdapter`, `createMockServer`, `createStormFetchError` | Build deterministic unit tests, demos, and error cases |
| Runtime checks | `isBrowser`, `isReactNative`, `isNodeLike`, `isDeno`, `isBun`, `getRuntimeInfo` | Detect runtime and explain adapter decisions |
| Security plugins | `hmacSigningPlugin`, `secureLoggerPlugin`, `securityRateLimitPlugin` | Sign requests, log safely, and flag repeated auth/security responses |

## Request Lifecycle

Every client call follows the same high-level lifecycle:

1. Build URL from `baseURL`, request `url`, `pathParams`, and `params`.
2. Apply route `policy`, auth, language, XSRF, plugins, and request interceptors.
3. Run security checks such as host policy, protocol policy, path traversal guard, payload limits, credential policy, and custom `guard`.
4. Dispatch through the selected adapter: Fetch, XHR, Node HTTP/1.1, Node HTTP/2, or mock/custom adapter.
5. Handle redirects, retries, cancellation, timeout, progress, response parsing, schema validation, cache updates, and events.
6. Return `FastApiResponse<TData, TBody>` or throw a normalized `FastApiError`.

## Client Creation

### `STORMFETCH_PACKAGE_INFO`

Frozen official package metadata. Use `version`, `developer`, `company`, `contact`, `website`, or `signature` in support/about screens without duplicating package identity strings.

### `fastApi`

Pre-created client with an empty `baseURL`, a 30-second timeout, JSON headers, and guarded browser token/language interceptors. It is useful for a quick start. Use a custom client in production when auth, base URL, and error behavior are app-specific.

### `createStormFetchClient(options?)`

Creates an independent `FastApiClient`. Use it for ReactJS, Node, SSR, or shared packages.

```ts
const api = createStormFetchClient({ baseURL, timeout, token, plugins });
```

### `createFastApiClient(options?)`

Alias of `createStormFetchClient`, retained for FastApi naming compatibility.

### `createTypedStormFetchClient<EndpointMap>(options?)`

Creates a client whose route strings infer response and body types from an endpoint map. Use it when the API contract is known at compile time.

### `createReactNativeStormFetchClient(options?)`

Creates a React Native/Expo client and defaults `adapter` to `fetch`. Use `token` for async secure storage, `isOnline` for native connectivity, `fileSaver` for downloads, and an optional custom cache adapter.

## Request Methods

All methods return `Promise<FastApiResponse<TData, TBody>>`. The response contains `data`, `status`, `statusText`, `headers`, resolved `config`, `requestId`, and `duration`.

### `client.request(config)`

Lowest-level request method. Use it when method, URL, or body are selected dynamically.

Required: `url`. Optional: `method`, `data`, `headers`, `params`, retry/cache options, cancellation signal, response type, and adapter options.

Use this when a wrapper has to decide the HTTP method at runtime, or when you are building your own service abstraction.

### `client.fetch(url, config?)`

Fetch-like universal method that still uses StormFetch auth, retry, cache, interceptors, and adapters. Set `config.method` for non-GET requests.

Use this when you want one familiar function instead of separate `get`, `post`, and `patch` calls.

### `client.get<TData>(url, config?)`

Sends GET. Use for lists, details, search, and cacheable reads. `data` in the returned response is `TData`.

Typical options: `params`, `cache`, `cacheTTL`, `cacheTags`, `dedupe`, `signal`.

### `client.post<TData, TBody>(url, data?, config?)`

Sends POST. Use for create operations, login, uploads, and server commands.

Typical options: `headers`, `retryUnsafe`, `invalidateTags`, `requestSchema`, `responseSchema`.

### `client.put<TData, TBody>(url, data?, config?)`

Sends PUT. Conventionally used to replace a complete resource.

Use this when the server expects the full object, not only changed fields.

### `client.patch<TData, TBody>(url, data?, config?)`

Sends PATCH. Conventionally used for partial resource updates.

Use this for edit forms where only changed fields are submitted.

### `client.delete<TData>(url, config?)`

Sends DELETE. Request options, including `pathParams`, belong in the second argument.

Use `invalidateTags` to clear related cached list/detail data after deletion.

### `client.head(url, config?)`, `client.options(url, config?)`, and `client.query(url, data?, config?)`

`head` reads headers and status without response data. `options` reads server capabilities such as allowed methods and CORS behavior. `query` sends the standards-track HTTP QUERY method with an optional request body.

### Uppercase aliases

`GET`, `POST`, `PUT`, `PATCH`, `DELETE`, `HEAD`, `OPTIONS`, and `QUERY` call the matching lowercase methods. Use them when you prefer HTTP-style service files.

### Conditional interceptors

`interceptors.request`, `interceptors.response`, and `interceptors.error` accept an optional second argument with `runWhen`, `once`, and `prepend`. `use()` still returns an eject function.

```ts
const eject = api.interceptors.request.use(addSignature, {
  runWhen: (value) => (value as { method?: string }).method === 'POST',
  once: false,
  prepend: true,
});
```

### `client.postJson(url, data?, config?)`

Posts JSON with an explicit `content-type: application/json` header.

Use this for strict APIs where the backend requires the JSON content type even when the body is empty.

### `client.postForm(url, data, config?)`

Posts `application/x-www-form-urlencoded` data using `URLSearchParams`. Useful for OAuth, login, and legacy APIs.

Object values are converted into URL search params. Arrays append repeated keys.

### `client.postMultipart(url, data, config?)`

Posts multipart data. Accepts an existing `FormData` or a plain object handled by `createFormData`.

Use this for file upload. Do not set multipart `Content-Type` manually; the runtime must add the boundary.

### `client.graphql(query, variables?, config?)`

Posts `{ query, variables }` to `config.url`, `graphqlEndpoint`, or `/graphql`.

Use `graphqlEndpoint` in client options when your GraphQL server is not `/graphql`.

### `client.batch(requests)`

Runs request configs concurrently and returns responses in the same order.

Use this for dashboards or app bootstrap screens that need several endpoints together.

### `client.poll(url, options)`

Starts repeated GET requests and returns a controller with `stop()` and `subscribe(listener)`.

Use `stopWhen` to end polling after a server job, payment, upload, or order reaches a final state.

### `client.resource(basePath)`

Returns REST CRUD helpers: `list`, `detail`, `create`, `replace`, `update`, and `remove`.

### `client.cacheManager`

Smart cache facade with `prefetch`, `invalidate`, `clear`, `keys`, `dehydrate`, `hydrate`, and `subscribe`. Use it for SSR hydration, app boot preloading, and cache inspection.

This is the easiest entry point when you want React Query-like cache behavior without installing another runtime library.

### `client.history()`, `client.replay(id)`, `client.toCurl(id)`, and `client.toHAR()`

Debug helpers inspired by DevTools. History stores recent requests, replay re-runs one request, `toCurl` exports a reproducible command, and `toHAR` creates a HAR-like log object.

Use these when a backend issue needs to be reproduced or shared with another developer.

Sensitive headers such as `Authorization`, `Cookie`, `Proxy-Authorization`, `Set-Cookie`, `X-API-Key`, and XSRF/CSRF headers are redacted from public history, curl export, and HAR export by default. Add custom names with `security.sensitiveHeaders`, or set `security.redactSensitiveHeaders: false` only in trusted local debugging sessions.

### `client.policy(match, config)`

Registers route-based defaults. `match` can be a string prefix, `/path/**`, RegExp, or predicate. Returns an unsubscribe function.

Use this when payments, admin APIs, uploads, or public APIs need different timeout/retry/security defaults.

### `client.streamText`, `client.streamJson`, `client.streamNdjson`, and `client.sse`

Streaming helpers for AI responses, log feeds, NDJSON APIs, and Server-Sent Events. These use the Fetch stream API where available.

Use these for live APIs where data arrives gradually rather than as one final JSON response.

### `client.contract(definition)`

Builds SDK-like functions from endpoint definitions:

```ts
const sdk = api.contract({
  listUsers: { method: 'GET', url: '/users' },
  createUser: { method: 'POST', url: '/users' },
});
```

### `createStormFetchServerClient(options)`

Creates an SSR/Node client with header and cookie forwarding. Pass `cookies` as a string or object.

### `client.download(url, fileName?, config?)`

Requests a Blob. In a browser it saves through `saveBlob`. In React Native, provide `fileSaver`. Set `autoSave: false` when only the response data is needed.

### `client.createFormData(data)`

Creates multipart `FormData`. Arrays append repeated fields; plain objects are JSON encoded; Blob values and React Native file descriptors are appended as files.

### `client.getHtml(url)`, `client.getXml(url)`, `client.getDom(url)`, and `client.scrape(url, schema)`

Fetches HTML/XML content as text, parses DOM documents, or extracts data with CSS selectors. Browser builds use native `DOMParser`; Node.js and React Native can provide `domParser` in client options.

### `client.clearCache(key?)`

With no key, clears this client's cache. With a key, clears matching in-memory entries or the exact persistent entry.

### `client.clearCacheAsync(key?)`

Async-safe cache clear. Use it when cache storage is promise-based, such as React Native AsyncStorage wrappers.

### `client.invalidateTags(tags)`

Removes cache records whose `cacheTags` overlap with the provided tags. Mutations can also pass `invalidateTags` to clear related reads after success.

### `client.subscribe(listener)`

Subscribes to request/cache events such as `request:start`, `request:success`, `request:error`, `cache:hit`, `cache:stale`, and `cache:invalidate`. Returns an unsubscribe function.

### `client.flushOfflineQueue()`

Starts requests waiting in the in-memory offline queue. Call after the app reports that connectivity returned. The queue is process-memory only and is not a durable background-sync store.

## React Hooks

### `createStormFetchHooks(React, client)`

Creates hooks without bundling React as a dependency. Pass `import * as React from 'react'` and the client the hooks should use. Works in React DOM and React Native.

Returns:

- `useStormQuery<TData>(url, config?, options?)`: returns `{ data, error, loading, refetch, reset }` and fetches on mount when enabled.
- `useLazyStormQuery<TData>(url, config?, options?)`: same state shape, but waits until `refetch()` is called.
- `useStormMutation<TData, TBody>(url, method?, options?)`: returns `{ data, error, loading, mutate, reset }`; supports `invalidateTags`, `onMutate`, `onSuccess`, `onError`, and `optimisticData`.
- `useStormInfiniteQuery<TData, TPageParam>(url, options)`: returns paginated state with `pages`, `pageParams`, `fetchNextPage`, `hasNextPage`, `refetch`, and `reset`.

Keep `config` stable with `useMemo` when it is created inside a component because it participates in hook dependencies.

## URL and Parameter Functions

### `buildQueryString(params?, options?)`

Converts an object into a URL query string including the leading `?`. Supports arrays, nested objects, dot notation, index control, and a custom serializer.

### `replacePathParams(url, pathParams?)`

Replaces `:name` placeholders with encoded values. Example: `/users/:id` plus `{ id: 10 }` becomes `/users/10`.

### `joinURL(baseURL, url)`

Safely combines base and relative URLs while avoiding duplicate boundary slashes. Absolute request URLs remain usable.

## Upload and Download Functions

### `createFormData(data)`

Standalone version of `client.createFormData`.

### `createReactNativeFile(uri, name, type)`

Creates a typed `{ uri, name, type }` object accepted by React Native's `FormData` implementation.

### `isReactNativeFile(value)`

Type guard that checks for string `uri`, `name`, and `type` fields.

### `saveBlob(blob, fileName?)`

Starts a browser download through an object URL and temporary anchor. It intentionally throws outside browsers; use an injected native `fileSaver` on mobile.

### DOM helpers

`parseDom`, `scrapeDocument`, `selectText`, `selectAttr`, `selectAll`, `extractMeta`, `extractLinks`, `extractImages`, and `extractJsonLd` are exported for custom parsing flows.

## Errors and Interceptors

### `createStormFetchError(input)`

Creates the normalized error object used by adapters. Useful for custom adapters and plugins.

### `createFastApiError(input)`

Alias of `createStormFetchError`.

### `createInterceptorManager<T>()`

Creates a manager with `use`, `eject`, `clear`, and `handlers`. `use(handler)` returns an unsubscribe function.

Client request interceptors may change resolved config; response interceptors may change responses; error interceptors handle or report failures.

## Plugins

### `authPlugin(getToken)`

Adds `Authorization: Bearer <token>` before requests. `getToken` may be async, which makes it suitable for native secure storage.

### `languagePlugin(getLanguage)`

Adds `Accept-Language` when the provider returns a value.

### `loggerPlugin(logger?)`

Logs responses and errors. Pass an object implementing `debug` and `error`, or omit it to use `console`.

## Security Options

`security` centralizes request safety policy for production clients:

```ts
const api = createStormFetchClient({
  baseURL: 'https://api.example.com',
  security: {
    allowedHosts: ['api.example.com', '*.trusted.example.com'],
    blockedHosts: ['169.254.169.254'],
    blockedCidrs: ['169.254.169.254/32', '127.0.0.0/8'],
    allowedMethods: ['GET', 'POST', 'PATCH'],
    allowAbsoluteUrls: false,
    allowPathTraversal: false,
    allowHttp: false,
    allowPrivateNetwork: false,
    blockCloudMetadata: true,
    validateDns: true,
    maxUrlLength: 4096,
    maxQueryDepth: 5,
    maxJsonDepth: 24,
    maxJsonKeys: 10000,
    maxResponseJsonDepth: 24,
    maxResponseJsonKeys: 10000,
    maxDecompressionRatio: 100,
    sensitiveHeaders: ['x-tenant-secret'],
    credentialPolicy: {
      authorization: ['api.example.com'],
      cookie: 'same-origin',
    },
    requireSameOriginXSRF: true,
  },
});
```

| Security option | What it does |
| --- | --- |
| `allowedHosts` | Allows only matching hosts. Matchers can be exact strings, `*.example.com`, RegExp, or a function |
| `blockedHosts` | Denies matching hosts even before custom guards/signing run |
| `allowedCidrs` / `blockedCidrs` | Allows or denies resolved IPv4 addresses by CIDR |
| `allowedMethods` | Restricts HTTP methods, or use `'*'` to allow all |
| `allowedProtocols` | Restricts protocols to `https:` and/or `http:` |
| `allowAbsoluteUrls` | Set false to prevent absolute request URLs from overriding `baseURL` |
| `allowPathTraversal` | Set false to reject `..` path traversal before URL normalization |
| `allowHttp` | Permits plain HTTP when explicitly true |
| `allowPrivateNetwork` | Permits `localhost`, loopback, link-local, and private IPv4 ranges when explicitly true |
| `blockCloudMetadata` | Blocks common cloud metadata hosts by default when security is enabled |
| `validateDns` / `resolveHost` | Re-checks resolved addresses to reduce DNS rebinding and CIDR bypass risk |
| `maxUrlLength` | Blocks unusually long URLs before dispatch |
| `maxQueryDepth` | Caps nested query serialization depth |
| `maxJsonDepth` / `maxJsonKeys` | Caps nested JSON request shapes before dispatch |
| `maxResponseJsonDepth` / `maxResponseJsonKeys` | Caps parsed response JSON shape after dispatch |
| `parseReviver` | Custom `JSON.parse` reviver for BigInt/date-safe parsing |
| `maxDecompressionRatio` | Blocks unexpectedly large decoded responses compared with declared size |
| `sensitiveHeaders` | Adds custom header names to the redaction list |
| `sensitiveDataPatterns` | Adds custom token/secret regexes for body, URL, and debug export redaction |
| `redactSensitiveHeaders` | Set false to disable redaction in trusted debugging only |
| `redactSensitiveData` | Set false to disable URL/body token-pattern redaction in trusted debugging only |
| `requireSameOriginXSRF` | Keeps browser XSRF cookie-to-header attachment same-origin by default |
| `credentialPolicy` | Per-header forwarding policy: `always`, `same-origin`, `same-host`, `never`, or host matchers |
| `guard` | Runs custom validation before dispatch |
| `signRequest` | Mutates or returns a signed config before dispatch |

StormFetch emits `security:block`, `security:redact`, and `security:credential-strip` events through `subscribe()` and `observability.onEvent`.

### Transport Hardening

Node transport supports safer advanced options:

| Option | Purpose |
| --- | --- |
| `trustProxyEnv` | Reads `HTTP_PROXY` / `HTTPS_PROXY` only when explicitly true |
| `socketPath` | Uses a Unix socket only when also present in `allowedSocketPaths` |
| `allowedSocketPaths` | Exact allowlist for privileged local sockets |
| `tls.ca`, `tls.cert`, `tls.key` | mTLS and custom CA inputs |
| `tls.servername` | Explicit TLS SNI/servername |
| `tls.rejectUnauthorized` | Certificate validation switch; keep true in production |
| `tls.certificatePins` | SHA-256 certificate pins, with `sha256/<base64>` supported |
| `formDataHeaderPolicy` | `content-only` by default; set `all` only for trusted Node FormData |

### Security Plugins

| Plugin | Purpose |
| --- | --- |
| `hmacSigningPlugin(options)` | Adds timestamp, nonce, and HMAC signature headers |
| `secureLoggerPlugin(options?)` | Logs request metadata without raw headers or body |
| `securityRateLimitPlugin(options?)` | Marks repeated 401/403/429 bursts with `STORMFETCH_SECURITY_RATE_LIMIT` |

## Proxy and Redirect Safety

Node requests support explicit proxy configuration, HTTPS proxy CONNECT tunneling, custom agents, and enterprise bypass rules:

```ts
const api = createStormFetchClient({
  proxy: {
    protocol: 'http',
    host: 'proxy.corp.local',
    port: 8080,
    noProxy: ['localhost', '.internal.example.com'],
  },
});
```

`proxy.noProxy` accepts a comma-separated string or array. StormFetch also reads `NO_PROXY` and `no_proxy`, normalizes hostnames, supports leading-dot suffix matches, exact host matches, host-with-port matches, and `*`.

Use `httpAgent` and `httpsAgent` to pass custom Node agents for keep-alive, corporate TLS, connection pooling, or test instrumentation.

For Node redirects, StormFetch removes `Authorization`, `Cookie`, and `Proxy-Authorization` when the redirect crosses origin. Use `beforeRedirect` to inspect, block, or re-sign a redirect:

```ts
await api.get('/file', {
  beforeRedirect: ({ from, to, requestOptions }) => {
    if (from.hostname !== to.hostname) return false;
    requestOptions.headers = {
      ...(requestOptions.headers as Record<string, string>),
      'X-Redirect-Checked': 'true',
    };
  },
});
```

## Cache, Dedupe, and Queue

### `new StormFetchCache(storage?)`

TTL cache with `get`, `getAsync`, `set`, `setAsync`, `clear`, `clearAsync`, and `invalidateTags`. Defaults to memory. Browser strings `localStorage` and `sessionStorage` are supported. Promise-based stores are also supported for React Native persistence.

### `FastApiCache`

Alias of `StormFetchCache`.

### `new RequestDedupe()`

Tracks in-flight promises by key. The client uses it to share simultaneous GET requests when `dedupe` is enabled.

### `new RequestQueue()`

Serializes/rate-spaces tasks. The client uses it when `rateLimit` is configured.

## Adapters

### `dispatchAdapter(config)`

Chooses the requested adapter or detects the runtime. React Native is checked before Node shims and always uses fetch in automatic mode. Deno and Bun also use the Fetch adapter in automatic mode. In browsers, `onUploadProgress` is routed through XHR because Fetch does not expose portable upload progress events.

### `fetchAdapter(config)`

Web Fetch API adapter used by modern browsers, React Native, and fetch-capable runtimes. Cancellation from an external `AbortController` is reported as `isAbortError`.

### `xhrAdapter(config)`

Browser XMLHttpRequest adapter. Automatic browser selection uses it when upload or download progress callbacks are supplied.

### `httpAdapter(config)`

Node HTTP/HTTPS adapter for HTTP/1.1 streams, `responseType: 'stream'`, native WHATWG `FormData` multipart uploads, automatic form serialization, gzip/deflate/br/zstd decompression, chunked buffered upload progress, HTTPS proxy CONNECT, custom agents, normalized `NO_PROXY` bypass, redirect method rules, body limits, and content limits.

Errors returned by adapters are normalized StormFetch errors with stable codes such as `ERR_CANCELED`, `ERR_TIMEOUT`, `ERR_NETWORK`, `ERR_BAD_RESPONSE`, `ERR_BAD_OPTION_VALUE`, `ERR_DECOMPRESSION`, `ERR_RESPONSE_TOO_LARGE`, and safe `toJSON()` output.

### `http2Adapter(config)`

Node HTTP/2 adapter using `node:http2`. Select it with `adapter: 'http2'`. It supports buffered bodies, cancellation, timeout, response parsing, and progress callbacks. Streaming request bodies are intentionally rejected until a fully tested flow-control implementation is added.

### `createMockAdapter(options?)`

Creates a custom adapter for tests, demos, and storybooks. Routes match by method and URL string, regular expression, or predicate. If no route matches, it throws unless a `passthrough` adapter is provided.

### `createMockServer(options?)`

Creates a scenario-aware mock server with `adapter`, `setScenario`, `addRoute`, `requests`, and `clearRequests`.

## Runtime Functions

### `isBrowser()`

Returns true when both `window` and `document` exist.

### `isReactNative()`

Detects classic and new-architecture React Native globals.

### `isNodeLike()`

Returns true for Node runtimes, excluding browsers and React Native environments that expose a process shim.

### `isDeno()` and `isBun()`

Return true for Deno and Bun runtimes. Automatic dispatch uses Fetch in both runtimes.

### `getRuntimeInfo()`

Returns the detected runtime plus Fetch, XHR, FormData, Blob, Node, Deno, and Bun capability flags. Use it in diagnostics and support reports.

## OpenAPI

### `generateStormFetchServicesFromOpenApi(document, options?)`

Generates TypeScript service source from an OpenAPI document. It returns source code as a string; your tooling decides where and how to review/write that code.

## Important Client Options

| Option | Purpose |
| --- | --- |
| `baseURL` | Prefix for relative request URLs |
| `headers` | Default headers merged into every request |
| `timeout` | Abort timeout in milliseconds |
| `token` | Sync/async bearer-token provider |
| `refreshToken` | Called once after an authenticated 401 before retry |
| `onUnauthorized` | Central 401 callback |
| `language` | `Accept-Language` provider |
| `plugins` | Client extension setup functions |
| `adapter` | `auto`, `fetch`, `xhr`, `http`, or `http2` |
| `domParser` | HTML/XML parser adapter for Node.js and React Native |
| `graphqlEndpoint` | Default URL for `client.graphql()` |
| `historyLimit` | Maximum request history entries kept in memory |
| `policies` | Initial route policies |
| `circuitBreaker` | Failure threshold, reset timeout, recovery threshold, and fallback |
| `retry`, `retryDelay`, `retryPolicy` | Retry count, backoff base, and policy |
| `cache`, `cacheTTL`, `cacheStorage` | GET cache controls |
| `cacheTags`, `invalidateTags`, `staleTime`, `staleWhileRevalidate` | Tagged cache invalidation and background refresh |
| `dedupe` | Share matching in-flight GET calls |
| `rateLimit` | Minimum queue spacing in milliseconds |
| `maxConcurrent`, `maxConcurrentPerHost`, `priority` | Request scheduling controls |
| `requestSchema`, `responseSchema` | Runtime validation using a function or parser-like object |
| `security` | Allowed hosts, HTTP blocking, request guard, and request signing |
| `observability` | Structured request/cache events |
| `isOnline` | Sync/async native network-state provider |
| `fileSaver` | Browser/native downloaded Blob handler |
| `normalizeError` | Converts API error payloads into the common shape |
| `onSuccess`, `onError` | UI-independent notification hooks |

## Important Per-Request Options

`params`, `pathParams`, `headers`, `data`, `signal`, `responseType`, `validateStatus`, `retry`, `cache`, `dedupe`, `silent`, `meta`, `transformRequest`, `transformResponse`, `onUploadProgress`, `onDownloadProgress`, `beforeRedirect`, XSRF options, proxy options, and body/content limits can be set per request. Per-request values override client defaults.

## Enterprise Function Selection (v1.14+)

| Need | Use | Import |
| --- | --- | --- |
| Persist queued mutations | `createJsonOfflineQueueStorage(storage)` | `stormfetch/core` |
| Inspect pending/dead requests | `client.offlineQueueSnapshot()` | client instance |
| Retry or discard a queue item | `retryOfflineRequest(id)`, `discardOfflineRequest(id)` | client instance |
| Native background promise | `nativeUpload`, `nativeDownload` | client instance |
| Pause/resume/cancel transfer | `startNativeUpload`, `startNativeDownload` | client instance |
| OpenTelemetry spans | `createOpenTelemetryObservability(options)` | `stormfetch/observability` |
| Runtime counters | `createStormFetchMetrics()` | `stormfetch/observability` |
| Headless request inspection | `createStormFetchDevTools(client)` | `stormfetch/devtools` |
| Mounted inspector UI | `mountStormFetchDevTools(client, element)` | `stormfetch/devtools` |
| Generate a typed service file | `stormfetch-generate` | package CLI |
| Send an HTTP QUERY request | `client.query()` / `client.QUERY()` | client instance |
| Match/run one interceptor first | `{ runWhen, once, prepend }` | interceptor options |
| Read official package signature | `STORMFETCH_PACKAGE_INFO` | `stormfetch` |
| Learn any public function | `LEARN_HERE.md` | npm package documentation |

### Offline client options

- `offlineStorage`: persistent `load`/`save` adapter; optional dead-letter methods are supported.
- `offlineMaxAttempts`: attempts before a record becomes a dead letter; default `5`.
- `offlineRetryDelay`: number or attempt-aware delay function.
- `offlineIdempotencyHeader`: defaults to `Idempotency-Key`; set `false` to disable.
- `resolveOfflineConflict`: handles HTTP `409` with `retry`, `discard`, or replacement config.
- `onOfflineDeadLetter`: reports permanently failed mutations.

### Native transfer adapter

Implement `upload()` and `download()` for promise usage. Implement optional `startUpload()` and `startDownload()` returning a `NativeTransferTask` to expose platform pause, resume, and cancel capabilities. StormFetch does not bundle or silently select a third-party native runtime.

### OpenTelemetry bridge

`createOpenTelemetryObservability` accepts any tracer matching the small `OpenTelemetryTracerLike` interface. This preserves zero runtime dependencies while working with an application-owned OpenTelemetry SDK. StormFetch sets method, URL, request ID, response status, duration, and error attributes.
