/** * Core type definitions for the HTTP client. * * @module */ import type { RetryOptions } from './retry.js'; /** * HTTP request method. */ export type HttpMethod = 'GET' | 'POST' | 'PUT' | 'PATCH' | 'DELETE' | 'HEAD' | 'OPTIONS'; /** Request metadata passed to a client auth-error listener when the server responds with 401. */ export interface HttpAuthErrorEvent { /** The HTTP method after request interception. */ readonly method: HttpMethod; /** The request's configured URL after interception, with credentials redacted. */ readonly url: string; /** * Whether the request supplied an Authorization or Cookie header, configured transport auth, * or explicitly opted into sending cookies. Browsers do not expose implicit cookies to the * client, so consumers also need the app's auth state to decide whether a visitor is signed out. */ readonly sentCredentials: boolean; } /** * HTTP request options (headers, query params, timeout, credentials, response type, abort signal). */ export interface RequestConfig { /** * Request headers. */ headers?: Record; /** * Query parameters. */ params?: Record; /** * Request timeout in milliseconds. */ timeout?: number; /** * Whether to include credentials (cookies). */ withCredentials?: boolean; /** * Send this request WITHOUT waiting for the session restore (the auth gate). * * For a custom HTTP restore, `setAuthGate({ client, restore })` provides a request function * that applies this option automatically. * * A request the gate's restore issues from a LATER continuation must set this. The gate * recognizes a request the settle function issues while it runs and never holds it — this * package's client awaits the gate before anything else, so a `restoreSession()` that calls * it directly does not deadlock. But a restore that awaits something else first * (`await storage.get()`), then calls the client, reaches `awaitAuthGate` after that window: * the gate then waits on itself, and every request on the page stalls until the gate times * out (3 s) — so pass `skipAuthGate: true` on that request. A provider that awaits the gate * inside a scheduled interceptor (the Axios bond) also reaches it after the window, so its * restore's request needs the opt-out. * * ```typescript * // the request the gate's restore makes, through the same client the gate holds back * await http.get(currentUserEndpoint, { skipAuthGate: true }) * ``` * * `@molecule/app-auth`'s own restore does not need it — it sends its request with * `fetch`, not through this client. An app with its own session store that registers a * gate with `setAuthGate` does not need it either when its restore calls the client * directly. */ skipAuthGate?: boolean; /** * Response type. */ responseType?: 'json' | 'text' | 'blob' | 'arraybuffer'; /** * Abort signal for cancellation. */ signal?: AbortSignal; /** * Keep the fetch client's configured timeout when a caller also supplies a signal. * Use this when the signal represents cancellation independent of the timeout, * such as a session change during a write. */ timeoutWithSignal?: boolean; /** * Keep the request running when the page navigates away or closes before it finishes — fetch's * own `keepalive`. The bundled clients already do this for a write (POST, PUT, PATCH, DELETE) to * the page's own origin with a body of at most 8 KB, so a favorite or a save followed at once by * a navigation still reaches the API; nothing needs to be set for that. Pass `true` for anything * else that must outlive the page (a cross-origin write, a beacon on `pagehide`) and `false` to * let a navigation cancel a write. The browser caps the bodies of in-flight keepalive requests * at 64 KB in total, so not for uploads. * * ```typescript * await http.post('https://events.example.com/v1/track', event, { keepalive: true }) * ``` */ keepalive?: boolean; /** * Request body data, as a field of THIS config object — the `request({ method, url, data })` * form. The verb methods take the body as their SECOND argument: `post(url, data, config)`, * `put(url, data, config)`, `patch(url, data, config)`. Never wrap it there as * `{ data: body }`: that object is the body, so the wire sends `{"data":body}` and the API * sees none of the fields at its top level. */ data?: unknown; /** * Custom request options (implementation-specific). */ options?: Record; /** * Retry policy for this request, or `false` to disable retries. * * The default policy retries only IDEMPOTENT requests (`GET`/`HEAD`/`PUT`/ * `DELETE`/`OPTIONS`, and `POST`/`PATCH` carrying an `Idempotency-Key`) on * `502`/`503`/`504` or a reset/refused connection, twice, with exponential * backoff and jitter, honoring `Retry-After`. See `@molecule/app-http`'s * `shouldRetryRequest`. */ retry?: RetryOptions | false; } /** * What the auth gate is told about the request it is about to hold: whether the request * opts out of the wait, and how to name it in the stalled-gate report. * * A request's own `RequestConfig` satisfies this — the providers pass it straight through * (`awaitAuthGate(requestConfig)`), so a provider never has to build one by hand. */ export interface AuthGateRequest { /** * Send this request without waiting for the gate at all — see * `RequestConfig.skipAuthGate`. */ skipAuthGate?: boolean; /** * The request's HTTP method, for the message logged when the gate never settles. */ method?: string; /** * The request's URL, for the message logged when the gate never settles. Any userinfo or * credential query/fragment values are redacted from that report; non-secret parts remain. */ url?: string; } /** * Full request configuration including method and URL. */ export interface FullRequestConfig extends RequestConfig { /** * HTTP method. */ method: HttpMethod; /** * Request URL (can be relative or absolute). */ url: string; /** * Request body data — a field of this config object, never a second argument here. */ data?: unknown; } /** * Parsed HTTP response with status code, headers, and typed body data. */ export interface HttpResponse { /** * Response data. */ data: T; /** * HTTP status code. */ status: number; /** * HTTP status text. */ statusText: string; /** * Response headers. */ headers: Record; /** * Original request config. */ config: FullRequestConfig; } /** * Materialize a failed response body before the synchronous HttpError capture. Unchanged bytes * are cloned directly, including a Blob's BOM and every typed-array kind. Changed textual bytes * retain the BOM and use a Uint8Array fallback if the original view's alignment no longer fits. * Successful responses never pass through this helper. * * @param body - A response body about to be retained on a failed request. * @returns A scrubbed body with unchanged binary content preserved byte-for-byte. */ export declare const snapshotHttpErrorBody: (body: T) => Promise; /** * Read and scrub a failed response once for a retained-error reconstruction. The detached capture * carries the original body kind, safe response metadata, and minimal request config, so callers * such as auth never need to read the source response or its body again. * * @param response - The failed HTTP response to capture. * @returns A detached, credential-scrubbed response preserving binary body bytes where safe. */ export declare const snapshotHttpErrorResponse: (response: T) => Promise; /** * HTTP error with response details. * * `instanceof HttpError` also recognizes compatible failures carrying the shared * `Symbol.for('@molecule/app-http/HttpError')` brand, including non-ok auth responses * and errors from duplicated package copies. Branded producers must provide this * class's instance fields. Subclasses retain ordinary prototype-based checks. * * Request metadata on `config` and `response.config` is limited to method, a * credential-redacted URL, and the two boolean notification-suppression controls * (`molSilentErrorNotification` and `molSilentRateLimitNotification`). Request bodies, * headers, params and all other provider options are omitted, as are credential-bearing * response headers, because errors are routinely serialized by logging transports. * * **`status` is an HTTP status when the server answered, and `0` when it did not.** * A `0` means NO response exists: the request was aborted (an `AbortController`, a * component's effect cleanup, a route change tearing the request down) or the * network failed before anything came back. It is not an HTTP status at all, so it * says nothing about the session — an app must never treat `status < 500` as * "signed out", because every aborted request on a route change would clear the * session. The correct check is {@link isAuthFailure} (`status === 401 || status === 403`); * `isNoResponse` (`status === 0`) identifies this case. * * @example * ```typescript * try { * await http.get('/projects') * } catch (err) { * if (isAuthFailure(err)) clearSession() // 401/403: the server rejected the credential * else if (isNoResponse(err)) return // aborted or offline — not a session decision * else showError(err) * } * ``` */ export declare class HttpError extends Error { status: number; response?: HttpResponse | undefined; config?: FullRequestConfig | undefined; errorKey?: string | undefined; aborted: boolean; /** * Recognizes the shared failed-request contract without widening subclass checks. * * @param value - Any value to test. * @returns True for a prototype instance, or a compatible branded value checked against the base class. */ static [Symbol.hasInstance](value: unknown): boolean; /** * Redacts URL userinfo and credential query/fragment values while preserving the path and * non-secret parameters. Shared by compatible HTTP and auth error/log views. */ static readonly redactUrlCredentials: (value: string) => string; /** * Builds a failed-request error. * * @param message - Human-readable message (already translated where a key exists); * credentials in any URL it contains are redacted. * @param status - HTTP status, or `0` when no response was received (aborted / network failure). * @param response - Parsed response when the server answered, otherwise undefined; * its request config and headers are sanitized for safe logging. * @param config - The request config that failed; only its method, redacted URL and * boolean notification-suppression controls are retained. * @param errorKey - Translation key for the failure (`http.error.aborted` for an * aborted request, `http.error.networkError` for a real network failure). * @param aborted - Whether the request was aborted before a response: an * `AbortController` signal (component cleanup, a cancelled request) or the * browser tearing the fetch down during a navigation. Distinguishes an abort * from a network outage on the same `status === 0`, without parsing the message. */ constructor(message: string, status: number, response?: HttpResponse | undefined, config?: FullRequestConfig | undefined, errorKey?: string | undefined, aborted?: boolean); } //# sourceMappingURL=types.d.ts.map