/** * Client HTTP interface for molecule.dev. * * Provides a unified HTTP client API that works across different * HTTP libraries (fetch, axios, ky, etc.). * * **The body is the SECOND argument: `post(url, data, config?)` — likewise `put` and `patch`, * and the response is `HttpResponse` (read `.data` for the body).** `data` IS the request * body; a plain object is serialized as the JSON body. Passing `{ data: body }` there is NOT a * config object — it makes the wire body `{"data":{…}}`, so the API sees an object whose only * key is `data`, finds none of the fields it validates, and answers * `422 {"errors":{"username":["can't be blank"],…}}`. Write `post('/users', { user })`, never * `post('/users', { data: { user } })`. The config object (headers, params, timeout, * `skipAuthGate`) is the THIRD argument. Only `request({ method, url, data, … })` takes `data` * inside an options object, because there that object IS the config. * * **List responses:** `unwrapList(response)` accepts a bare array, a `data` envelope, * or a named list such as `{ articles: T[], articlesCount: number }` or * `{ items: T[], count: number }`, in both raw-body and `HttpResponse` forms. It selects * the single collection array only when every sibling is list metadata (pagination, * `meta`, `links`, or a numeric `Count` / `_count`). Metadata keys * are not collection names. Resource objects with fields such as `id` or `subtotal`, * multiple collection arrays, and unsupported or empty mock responses return `[]`. * For a resource containing an array, read its field explicitly; the generic casts * the rows without validating the server's schema. * * **Single responses preserve API-specific field names.** `unwrapSingle(response)` peels * transport and `data` envelopes. It does not select a named resource such as `{ record: T }`. * For that body, read `unwrapSingle<{ record: RecordType }>(response)?.record`, or * `response.data.record` with a typed client call. For a bare resource body, keep the resource * directly. The generic is a type assertion, not runtime validation of the server's schema. * * @example * ```tsx * // In a React component, get the configured client from context and call it. * // The hook is exported by the framework binding (@molecule/app-react), not * // this core package. Use the configured client for the visitor's session. * import { useHttpClient } from '@molecule/app-react' * * function Plants() { * const http = useHttpClient() * const load = async () => { * const res = await http.get('/plants') // the bonded client's baseURL ('/api') is prepended * setPlants(res.data) * } * // Body-carrying verbs take the body as the SECOND argument: * // http.post('/plants', plant) — wire body is `plant` * // http.post('/plants', { data: plant }) — WRONG: wire body is `{"data": plant}` * // http.put(url, body), http.patch(url, body) and http.delete(url) are also available. * } * ``` * * @remarks * Make ALL API calls through this client (via the framework hook `useHttpClient()` in * React / the Vue composable) — it carries the configured `baseURL`, auth headers, and * interceptors. Do NOT call `fetch()` / `axios` directly in components — that bypasses auth * + base-URL config and breaks when the transport is swapped. * * Two mistakes that break in preview/production (seen in real imported apps): * - **Pass RELATIVE paths; never a hardcoded host.** Use `'/plants'` (the BONDED client's * `baseURL` — `'/api'` in a scaffold — is prepended), NOT `'/api/plants'`, and NEVER an * absolute dev URL like `'http://localhost:4000/api/…'`. A hardcoded `localhost`/host works on * the author's machine, then fails cross-origin (CORS) in the preview and points at the wrong * server in production. The base URL is configured ONCE (via `setClient`), not per call. * - **`getClient()` itself knows no baseURL.** Its same-origin fallback while nothing is * bonded has `baseURL: ''`, so `getClient().get('/items')` requests the PAGE origin — in * dev the Vite server answers its own `index.html` with a 200, and the HTML arrives as * `data`, and the API then validates none of the fields it was sent. A scaffold bonds * `'/api'`. A handle captured before setup follows the client bonded later, including * extracted methods. An explicitly constructed client stays independent and must pass `{ baseURL }`. * - **The client is PUBLIC — never put a secret in it.** Anything the browser sends (an API * key, a service-role / `sk_…` key, a signing secret) is visible to every user. Secrets * stay in YOUR API; the browser calls your API and the API uses the secret server-side. * Only a publishable/public key may ever be client-side. * * Auth (the bearer token / session cookie) is attached by the bonded client's * interceptors and token source. Keep persistence in `@molecule/app-auth`'s * `AuthClientConfig.storage`; use the bonded client instead of reading storage * or hand-attaching headers in each component. * An API that wants another scheme than `Bearer` (`Authorization: Token `) passes * `authScheme: 'Token'` to the client's CONSTRUCTOR — `setClient(createFetchClient({ baseURL, * authScheme: 'Token' }))`, or the bonded provider's constructor * (`createAxiosClient({ … })` from `@molecule/app-http-axios`). It is NOT a property of * `getClient()`'s result: that is a built client, and `client.authScheme = 'Token'` is a type * error (TS2339) that changes no header. Do not hand-write a fetch wrapper for the scheme either. * * Header names are case-insensitive: request headers replace defaults with the same name. * `createFetchClient` applies a nonempty static or resolved auth token AFTER request * interceptors, replacing any default, request or interceptor `Authorization` header in any * spelling. Clear the token (and any token resolver) or use a separate client to send another * credential. The Axios bond retains Axios's precedence: explicit default/request headers and * request interceptors can override the client's token. * `client.onAuthError(handler)` calls `handler({ method, url, sentCredentials })` on 401. * The event describes the rejected request after interception and token injection. Its URL * is credential-redacted, and explicit cookie inclusion counts as credentialed. * * **A different account does not require a hand-written transport.** For demo data, * an operator action, or another tenant's token, construct a separate package client in * the composition root and pass it to the helper as `HttpClient`. Leave it unbonded: * `setAuthTokenSource` affects the bonded client, not an independent instance. Set the * independent client's own token with `setAuthToken(accountToken)` (or a live * `setAuthTokenResolver`). Do not call `setClient`, change the visitor's auth client, * or override the visitor's resolver to act as another account. Each independent client * needs its own `baseURL` and `authScheme`. This is package reuse, not another fetch wrapper. * The global session-restore gate still applies. Use the request's `skipAuthGate: true` * only when that request is independent of the visitor's restore. * * ```typescript * // In the composition root. Pass this client to the account-specific helper. * import { createFetchClient } from '@molecule/app-http' * * const scoped = createFetchClient({ baseURL: '/api', authScheme: 'Token' }) * scoped.setAuthToken(accountToken) * const response = await scoped.post('/stock', { name: 'Paper' }) * // response.data is the parsed body. The visitor's client and session are unchanged. * ``` * * A request made while the session is still being restored WAITS for that restore, so a page * that fetches viewer-dependent data on mount (account settings, a dashboard, or a * saved-item state) cannot go out unauthenticated and answer for an anonymous viewer. The auth * bond registers that wait with `setAuthGate`; apps that bond auth through * `@molecule/app-bonds-default-react` get it without doing anything. An app with its own session * module can start its restore and register the wait together with * `setAuthGate({ client, restore })`. * Use the provided `request` inside that callback. It uses the configured transport and * bypasses the gate, including after awaits and with intercepting HTTP providers. * Waiting for the restore does NOT attach the token: a client created beside the auth bond needs * `createDefaultHttpClientWithAuthBearer({ baseURL, getToken: () => authClient.getAccessToken(), * authScheme })` from `@molecule/app-bonds-default-react` (or an auth client built with * `createDefaultAuthClientWithHttpSync`, which registers the auth client's token source with * `setAuthTokenSource`: the client reads it on each request, so a session adopted mid-page by * `setSession()` or an OAuth callback's `setAccessToken()` is sent instead of the previous * account's token — `setAuthTokenSource` says which request first carries it on a transport * without `setAuthTokenResolver`), because `setAuthGate` alone sends no `Authorization` header. * * **The gate never holds its own restore's request.** A request the settle function issues * while it runs (its call reaches this client before the function awaits anything) is part of * the restore it is waiting for, so it goes out immediately — `setAuthGate(() => * restoreSession())` does not deadlock even when `restoreSession` uses this client. A restore * that awaits something else first and only then calls the client reaches it after that * window, and that request must opt out of the gate: `http.get(currentUserEndpoint, { * skipAuthGate: true })`. Without the opt-out the gate waits on itself, the restore never * settles, and every request the gate holds stalls until it times out (3 s). * `@molecule/app-auth`'s own restore does not need it (it calls `fetch`, not this client). * * **A failed request's `status` is `0` when NO response arrived — never read it as * "signed out".** An aborted request (an `AbortController` signal, a component's * effect cleanup, a route change tearing the fetch down) and a network outage both * throw an `HttpError` with `status === 0`; the aborted ones also carry * `aborted: true` and the `http.error.aborted` key, the rest `http.error.networkError`. * Neither says anything about the session. To decide whether a session ended, use * `isAuthFailure(err)` (401/403 only); `isNoResponse(err)` identifies the no-response * case so a caller can stay silent instead of reporting an outage. **Do not write * `err instanceof HttpError && err.status < 500` as a sign-out check** — it clears * the session on every aborted navigation request. * * Every non-ok response rejected by `@molecule/app-auth` also satisfies * `err instanceof HttpError` and `isHttpError(err)`: its `status` and `response.data` * are the same HTTP status and parsed body exposed as `AuthError.status` and * `AuthError.body`, while it remains an `I18nError`. Both checks accept the shared * brand across duplicated package copies. Subclass checks keep their ordinary * prototype semantics; a branded base error is not an instance of every subclass. * * **Show a failed request as `serverErrorMessage(err) ?? t(fallbackKey, …)`, never * `err.message`.** An `HttpError`'s message is the transport's status line (`Request * failed with status code 403`), written for logs; molecule API routes answer a refused * request with a translated `{ error }` body (a wrong password, an invalid code), which * `serverErrorMessage` returns. * * @module */ export * from './auth-gate.js'; export * from './client.js'; export * from './errors.js'; export * from './interceptors.js'; export * from './keepalive.js'; export * from './provider.js'; export * from './retry.js'; export * from './types.js'; export * from './unwrap.js'; export * from './utilities.js'; //# sourceMappingURL=index.d.ts.map