diff --git a/.gitignore b/.gitignore index d8e0dd3..ef0e28e 100644 --- a/.gitignore +++ b/.gitignore @@ -14,3 +14,6 @@ coverage routeTree.gen.ts .tanstack site/.impeccable + +# Cloudflare's local Pages server +.wrangler diff --git a/AGENTS.md b/AGENTS.md index 5a203ec..7de0dc1 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -77,6 +77,18 @@ to static files. It's a package in the pnpm workspace and isn't published. `/llms.txt` and `/llms-full.txt` list the current line's pages. Link between pages with root-relative paths, which the Markdown turns into full URLs. +- Each docs page, and the landing page, has a link-preview image, drawn + with Takumi by `site/src/lib/og-image.tsx` and served at `/og/docs/.png` + and `/og/home.png`. `vite.config.ts` lists them for the prerender, which + saves responses as text, so it asks for each image as base64 and writes + the bytes back. In dev, open an image's URL to see it. +- Pages prerender to flat files (`docs/calls/body.html`), which Cloudflare + Pages serves at the URL every link uses, `/docs/calls/body`. A page's + head comes from `pageHead` in `site/src/lib/shared.ts`: its canonical URL, + link preview, Markdown alternate and structured data. `robots.txt` and + `sitemap.xml` are routes too, and the sitemap lists the landing page and + the current line's pages. `npx wrangler pages dev site/dist/client` + serves a build the way Cloudflare does, redirects and headers included. - The live docs deploy from the `site` branch, which the Release workflow moves to each released commit; `main` and pull requests deploy as previews. Don't push `site` yourself. diff --git a/CHANGELOG.md b/CHANGELOG.md index 2f8ef5e..e5d9256 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -30,6 +30,18 @@ All notable changes to `@monarcode/effetch`, newest first. entries name, such as "Upgrading from 0.1.0-rc.3" and "Uploading files", are now [Upgrade from 0.1.0-rc.3](https://effetch.pages.dev/docs/upgrading) and [Upload files](https://effetch.pages.dev/docs/calls/uploads). +- Error messages for an endpoint passed to the wrong place no longer name + the client `client` (as in `client.bind`). They say "bind" or "your + client's endpoint or bind method", so they read the same whatever you + name your client. + +### Fixed + +- The documented TypeScript requirement is 5.7 or newer, not 5.4. Effetch's + declarations use typed arrays with a type argument, such as + `Uint8Array`, which TypeScript 5.6 and older reject. With + `skipLibCheck: true`, an older TypeScript compiles a project that uses + Effetch, but some of its types become `any`. ## 0.1.0-rc.4 diff --git a/README.md b/README.md index ed59de6..13bfd95 100644 --- a/README.md +++ b/README.md @@ -50,10 +50,10 @@ export const getTodo = (id: number) => // NetworkError | DecodeError | HttpError.With, Api> ``` -> **Release candidate.** Effetch is close to its first stable release -> (`0.1.0-rc.N`). The API is settled: release candidates add small, opt-in -> features and fixes, and the [changelog](./CHANGELOG.md) lists anything -> that needs a change in your code. +> **Release candidate.** Effetch is in release candidates (`0.1.0-rc.N`) +> on the way to `0.1.0`. A release candidate can still change the API, and +> when one does, the [changelog](./CHANGELOG.md) says what to change in your +> code. ## Documentation @@ -77,8 +77,10 @@ You'll need: - `effect` 4.x, which is a peer dependency; - an ESM project, since the package is ESM only; -- TypeScript 5.4 or newer. With `skipLibCheck: false`, Effect's own - declarations need TypeScript 5.7 or newer. +- TypeScript 5.7 or newer. + +[Compatibility](https://effetch.pages.dev/docs/reference/compatibility) +lists the runtimes Effetch is built for, and which of them CI tests. ## Quick start @@ -139,10 +141,10 @@ Calling an API from a web page on another origin? Read responses. - [Errors](https://effetch.pages.dev/docs/errors): what a call can fail with, and how to catch and type each error. -- [Plugins](https://effetch.pages.dev/docs/plugins): auth, retries, timeouts and logging, and - writing your own. - [Endpoints](https://effetch.pages.dev/docs/endpoints): save routes with their schemas and share them as a service. +- [Plugins](https://effetch.pages.dev/docs/plugins): auth, retries, timeouts and logging, and + writing your own. - [Streaming responses](https://effetch.pages.dev/docs/streaming) and [Pagination](https://effetch.pages.dev/docs/pagination). - [Structure an app](https://effetch.pages.dev/docs/structuring-an-app). diff --git a/examples/README.md b/examples/README.md index c1665f3..2327ecd 100644 --- a/examples/README.md +++ b/examples/README.md @@ -1,7 +1,8 @@ # Examples Complete programs using Effetch. They're typechecked with the package -(`pnpm run typecheck`), so they always match the current API. +(`pnpm run typecheck`), so they match the API on the branch you're reading, +which on `main` can be ahead of the latest release. | Example | What it shows | | -------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------ | diff --git a/examples/backends.ts b/examples/backends.ts index 3e65776..1217c37 100644 --- a/examples/backends.ts +++ b/examples/backends.ts @@ -35,9 +35,9 @@ const session: { accessToken: string | undefined } = { // Plugins are plain values, so both clients can share one token source. const auth = bearer({ token: () => session.accessToken }); -// `ctx.route` is a method and path, with no host: both backends could have a -// `GET /health`. A plugin shared across backends takes the backend's name, -// and each client gets its own instance. +// `ctx.route` is a method and path, without the base URL: both backends +// could have a `GET /health`. A plugin shared across backends takes the +// backend's name, and each client gets its own instance. const reportErrors = (backend: string) => Fetch.plugin({ name: "reportErrors", diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index 03c02ee..c85db7c 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -76,13 +76,13 @@ importers: version: 15.6.0(@types/mdast@4.0.4)(@types/mdx@2.0.14)(@types/react@19.3.0)(fumadocs-core@16.19.0(@mdx-js/mdx@3.1.1)(@tanstack/react-router@1.170.46(@types/react@19.3.0)(react-dom@19.3.1(react@19.3.1))(react@19.3.1))(@types/estree-jsx@1.0.5)(@types/hast@3.0.4)(@types/mdast@4.0.4)(@types/react@19.3.0)(lucide-react@1.72.0(@types/react@19.3.0)(react@19.3.1))(react-dom@19.3.1(react@19.3.1))(react@19.3.1)(zod@4.6.7))(react@19.3.1)(rolldown@1.2.19)(vite@8.3.7(@types/node@26.6.5)(esbuild@0.28.2)(jiti@2.7.0)(yaml@2.9.1)) fumadocs-twoslash: specifier: 4.0.4 - version: 4.0.4(@fumadocs/base-ui@16.19.0(@types/mdx@2.0.14)(@types/react@19.3.0)(fumadocs-core@16.19.0(@mdx-js/mdx@3.1.1)(@tanstack/react-router@1.170.46(@types/react@19.3.0)(react-dom@19.3.1(react@19.3.1))(react@19.3.1))(@types/estree-jsx@1.0.5)(@types/hast@3.0.4)(@types/mdast@4.0.4)(@types/react@19.3.0)(lucide-react@1.72.0(@types/react@19.3.0)(react@19.3.1))(react-dom@19.3.1(react@19.3.1))(react@19.3.1)(zod@4.6.7))(react-dom@19.3.1(react@19.3.1))(react@19.3.1)(tailwindcss@4.3.5))(@types/react@19.3.0)(fumadocs-core@16.19.0(@mdx-js/mdx@3.1.1)(@tanstack/react-router@1.170.46(@types/react@19.3.0)(react-dom@19.3.1(react@19.3.1))(react@19.3.1))(@types/estree-jsx@1.0.5)(@types/hast@3.0.4)(@types/mdast@4.0.4)(@types/react@19.3.0)(lucide-react@1.72.0(@types/react@19.3.0)(react@19.3.1))(react-dom@19.3.1(react@19.3.1))(react@19.3.1)(zod@4.6.7))(react-dom@19.3.1(react@19.3.1))(react@19.3.1)(shiki@4.6.0) + version: 4.0.4(@fumadocs/base-ui@16.19.0(@types/mdx@2.0.14)(@types/react@19.3.0)(fumadocs-core@16.19.0(@mdx-js/mdx@3.1.1)(@tanstack/react-router@1.170.46(@types/react@19.3.0)(react-dom@19.3.1(react@19.3.1))(react@19.3.1))(@types/estree-jsx@1.0.5)(@types/hast@3.0.4)(@types/mdast@4.0.4)(@types/react@19.3.0)(lucide-react@1.72.0(@types/react@19.3.0)(react@19.3.1))(react-dom@19.3.1(react@19.3.1))(react@19.3.1)(zod@4.6.7))(react-dom@19.3.1(react@19.3.1))(react@19.3.1)(tailwindcss@4.3.5)(takumi-js@2.22.1(csstype@3.2.4)(react@19.3.1)))(@types/react@19.3.0)(fumadocs-core@16.19.0(@mdx-js/mdx@3.1.1)(@tanstack/react-router@1.170.46(@types/react@19.3.0)(react-dom@19.3.1(react@19.3.1))(react@19.3.1))(@types/estree-jsx@1.0.5)(@types/hast@3.0.4)(@types/mdast@4.0.4)(@types/react@19.3.0)(lucide-react@1.72.0(@types/react@19.3.0)(react@19.3.1))(react-dom@19.3.1(react@19.3.1))(react@19.3.1)(zod@4.6.7))(react-dom@19.3.1(react@19.3.1))(react@19.3.1)(shiki@4.6.0) fumadocs-typescript: specifier: 5.6.0 - version: 5.6.0(@fumadocs/base-ui@16.19.0(@types/mdx@2.0.14)(@types/react@19.3.0)(fumadocs-core@16.19.0(@mdx-js/mdx@3.1.1)(@tanstack/react-router@1.170.46(@types/react@19.3.0)(react-dom@19.3.1(react@19.3.1))(react@19.3.1))(@types/estree-jsx@1.0.5)(@types/hast@3.0.4)(@types/mdast@4.0.4)(@types/react@19.3.0)(lucide-react@1.72.0(@types/react@19.3.0)(react@19.3.1))(react-dom@19.3.1(react@19.3.1))(react@19.3.1)(zod@4.6.7))(react-dom@19.3.1(react@19.3.1))(react@19.3.1)(tailwindcss@4.3.5))(@types/estree@1.0.9)(@types/hast@3.0.4)(@types/mdast@4.0.4)(@types/react@19.3.0)(fumadocs-core@16.19.0(@mdx-js/mdx@3.1.1)(@tanstack/react-router@1.170.46(@types/react@19.3.0)(react-dom@19.3.1(react@19.3.1))(react@19.3.1))(@types/estree-jsx@1.0.5)(@types/hast@3.0.4)(@types/mdast@4.0.4)(@types/react@19.3.0)(lucide-react@1.72.0(@types/react@19.3.0)(react@19.3.1))(react-dom@19.3.1(react@19.3.1))(react@19.3.1)(zod@4.6.7))(react-dom@19.3.1(react@19.3.1))(react@19.3.1) + version: 5.6.0(@fumadocs/base-ui@16.19.0(@types/mdx@2.0.14)(@types/react@19.3.0)(fumadocs-core@16.19.0(@mdx-js/mdx@3.1.1)(@tanstack/react-router@1.170.46(@types/react@19.3.0)(react-dom@19.3.1(react@19.3.1))(react@19.3.1))(@types/estree-jsx@1.0.5)(@types/hast@3.0.4)(@types/mdast@4.0.4)(@types/react@19.3.0)(lucide-react@1.72.0(@types/react@19.3.0)(react@19.3.1))(react-dom@19.3.1(react@19.3.1))(react@19.3.1)(zod@4.6.7))(react-dom@19.3.1(react@19.3.1))(react@19.3.1)(tailwindcss@4.3.5)(takumi-js@2.22.1(csstype@3.2.4)(react@19.3.1)))(@types/estree@1.0.9)(@types/hast@3.0.4)(@types/mdast@4.0.4)(@types/react@19.3.0)(fumadocs-core@16.19.0(@mdx-js/mdx@3.1.1)(@tanstack/react-router@1.170.46(@types/react@19.3.0)(react-dom@19.3.1(react@19.3.1))(react@19.3.1))(@types/estree-jsx@1.0.5)(@types/hast@3.0.4)(@types/mdast@4.0.4)(@types/react@19.3.0)(lucide-react@1.72.0(@types/react@19.3.0)(react@19.3.1))(react-dom@19.3.1(react@19.3.1))(react@19.3.1)(zod@4.6.7))(react-dom@19.3.1(react@19.3.1))(react@19.3.1) fumadocs-ui: specifier: npm:@fumadocs/base-ui@16.19.0 - version: '@fumadocs/base-ui@16.19.0(@types/mdx@2.0.14)(@types/react@19.3.0)(fumadocs-core@16.19.0(@mdx-js/mdx@3.1.1)(@tanstack/react-router@1.170.46(@types/react@19.3.0)(react-dom@19.3.1(react@19.3.1))(react@19.3.1))(@types/estree-jsx@1.0.5)(@types/hast@3.0.4)(@types/mdast@4.0.4)(@types/react@19.3.0)(lucide-react@1.72.0(@types/react@19.3.0)(react@19.3.1))(react-dom@19.3.1(react@19.3.1))(react@19.3.1)(zod@4.6.7))(react-dom@19.3.1(react@19.3.1))(react@19.3.1)(tailwindcss@4.3.5)' + version: '@fumadocs/base-ui@16.19.0(@types/mdx@2.0.14)(@types/react@19.3.0)(fumadocs-core@16.19.0(@mdx-js/mdx@3.1.1)(@tanstack/react-router@1.170.46(@types/react@19.3.0)(react-dom@19.3.1(react@19.3.1))(react@19.3.1))(@types/estree-jsx@1.0.5)(@types/hast@3.0.4)(@types/mdast@4.0.4)(@types/react@19.3.0)(lucide-react@1.72.0(@types/react@19.3.0)(react@19.3.1))(react-dom@19.3.1(react@19.3.1))(react@19.3.1)(zod@4.6.7))(react-dom@19.3.1(react@19.3.1))(react@19.3.1)(tailwindcss@4.3.5)(takumi-js@2.22.1(csstype@3.2.4)(react@19.3.1))' lucide-react: specifier: 1.72.0 version: 1.72.0(@types/react@19.3.0)(react@19.3.1) @@ -92,6 +92,9 @@ importers: react-dom: specifier: 19.3.1 version: 19.3.1(react@19.3.1) + takumi-js: + specifier: 2.22.1 + version: 2.22.1(csstype@3.2.4)(react@19.3.1) devDependencies: '@tailwindcss/vite': specifier: 4.3.5 @@ -1074,6 +1077,84 @@ packages: peerDependencies: vite: ^5.2.0 || ^6 || ^7 || ^8 + '@takumi-rs/core-darwin-arm64@2.22.1': + resolution: {integrity: sha512-cFVSNjAMbgOv0AC+acAt6E/VPaZowfzQjDG06s9GBaBx4riZs2onoDpYP4OrJ2qpaTBAsI8wQVfLVWjYhU/Bzg==} + engines: {node: '>=18'} + cpu: [arm64] + os: [darwin] + + '@takumi-rs/core-darwin-x64@2.22.1': + resolution: {integrity: sha512-4hhz+gy7hSKQpntHHv7LOijJQuAHKPsInOtnu05BtKivCEi2LOwt99oMW3j9c6gkocbGaFEdIxGDSGAAnC5Fwg==} + engines: {node: '>=18'} + cpu: [x64] + os: [darwin] + + '@takumi-rs/core-linux-arm64-gnu@2.22.1': + resolution: {integrity: sha512-+YqJihKLMboNTse/ooADkwtL6spHi6JlI7Ql8tgxAAJJQ6arUSYh5z7e5oUKQbaVBFQTipRMFIhkneEcHkcPoA==} + engines: {node: '>=18'} + cpu: [arm64] + os: [linux] + + '@takumi-rs/core-linux-arm64-musl@2.22.1': + resolution: {integrity: sha512-2OGab+DWKrkfEyQm+VCZXkEnCnJVF58a6bP00vzVkQuxiBG+RNrHfRx798RSo5uihT3/OmuLvOv2dAOtbHh0cQ==} + engines: {node: '>=18'} + cpu: [arm64] + os: [linux] + + '@takumi-rs/core-linux-x64-gnu@2.22.1': + resolution: {integrity: sha512-UCYXrbE1oFn2HvOYqGMTAzhcFlWdvH7q3viMdbmTlAzxb5Z+rsN9vGauL6MV01YLtWa/+erPYjbIxv44NkJgPQ==} + engines: {node: '>=18'} + cpu: [x64] + os: [linux] + + '@takumi-rs/core-linux-x64-musl@2.22.1': + resolution: {integrity: sha512-Cel/JcQKM8RgjPUlCwc7idzse902wCLi0DleOPdlIynNvofvC7nRXjxPUh7kuDppXPoFxa/UFlDfUMCKhdztwQ==} + engines: {node: '>=18'} + cpu: [x64] + os: [linux] + + '@takumi-rs/core-win32-arm64-msvc@2.22.1': + resolution: {integrity: sha512-XFyL6ZtlkIj/cKctEKS5uve020zNKNdLPfwqo/mHTbZbRIyOIrSO42E+YoIIiuAPay7fIiswIW9gOuF5Gquf5g==} + engines: {node: '>=18'} + cpu: [arm64] + os: [win32] + + '@takumi-rs/core-win32-x64-msvc@2.22.1': + resolution: {integrity: sha512-cFFeThvOh4ZoP9TDvmlzSbHr7//YDZWh6tJDZljctCc+fiJpJJyerUNH7+0QEFWHfrOEAByOllcNVfzkyddcVQ==} + engines: {node: '>=18'} + cpu: [x64] + os: [win32] + + '@takumi-rs/core@2.22.1': + resolution: {integrity: sha512-/NT+uGosCmoTWzkZtZYQR5a+zUlLJtLDB56ogssPzJpEfvPW+giIeqT+cCJY1qKf5IG2+l9wJKEavQNIVZRsmQ==} + engines: {node: '>=18'} + peerDependencies: + csstype: '*' + peerDependenciesMeta: + csstype: + optional: true + + '@takumi-rs/helpers@2.22.1': + resolution: {integrity: sha512-VYJj5sKV3DSDV9Rasl0Jwh3hN+S3j0aSlCabvf3xxIatXHokSM1q4/A9/xTZZ9+s6LDyp0D1Sdn17H8v2syS+g==} + engines: {node: '>=18'} + peerDependencies: + preact: ^10.0.0 || ^11.0.0 + react: ^18.0.0 || ^19.0.0 + peerDependenciesMeta: + preact: + optional: true + react: + optional: true + + '@takumi-rs/wasm@2.22.1': + resolution: {integrity: sha512-d8mr3rpgZ48eTx0kesx8BKVXvDoxtu4Hl3t+2w71tM8mikR/IXPDatTs/t2nOxFWRWCvQaOKwkGfIAqDmi7yVw==} + engines: {node: '>=20.19'} + peerDependencies: + csstype: '*' + peerDependenciesMeta: + csstype: + optional: true + '@tanstack/history@1.162.5': resolution: {integrity: sha512-w1+YvwmTkwt5n8yUqEH3IWZ9DsmorCZW/EQ3KYHnqEgIkOZpH54NvW6/Epq3Dzb8H0ifIeYX8PExvrNLIH5FIA==} engines: {node: '>=20.19'} @@ -2766,6 +2847,10 @@ packages: tailwindcss@4.3.5: resolution: {integrity: sha512-FcQk9BuffmEHJP2G0XmB2SplU1aLTI7j07Kunk+U74Ny+XiWOtzXz9aujFZ/avntw1e2cOv/3PkgzflQ7gX2vQ==} + takumi-js@2.22.1: + resolution: {integrity: sha512-kxageAHzLTmNkXSMDt1o5R9sneATS/kFSgW/gisYtlR0c1T1vabzWVfY4vRj19wHAdLKE897YA1B20hBPpvA0Q==} + engines: {node: '>=20.19'} + tapable@2.3.4: resolution: {integrity: sha512-NHFiWnAbMJxNNpBwiO7jJVGDuqMxT9/oV8v57RR+fgBQShkJil5inGD8/xWy0hjLyHQyX1tu27QANhlz3KBqCg==} engines: {node: '>=6'} @@ -3426,7 +3511,7 @@ snapshots: optionalDependencies: '@types/react': 19.3.0 - '@fumadocs/base-ui@16.19.0(@types/mdx@2.0.14)(@types/react@19.3.0)(fumadocs-core@16.19.0(@mdx-js/mdx@3.1.1)(@tanstack/react-router@1.170.46(@types/react@19.3.0)(react-dom@19.3.1(react@19.3.1))(react@19.3.1))(@types/estree-jsx@1.0.5)(@types/hast@3.0.4)(@types/mdast@4.0.4)(@types/react@19.3.0)(lucide-react@1.72.0(@types/react@19.3.0)(react@19.3.1))(react-dom@19.3.1(react@19.3.1))(react@19.3.1)(zod@4.6.7))(react-dom@19.3.1(react@19.3.1))(react@19.3.1)(tailwindcss@4.3.5)': + '@fumadocs/base-ui@16.19.0(@types/mdx@2.0.14)(@types/react@19.3.0)(fumadocs-core@16.19.0(@mdx-js/mdx@3.1.1)(@tanstack/react-router@1.170.46(@types/react@19.3.0)(react-dom@19.3.1(react@19.3.1))(react@19.3.1))(@types/estree-jsx@1.0.5)(@types/hast@3.0.4)(@types/mdast@4.0.4)(@types/react@19.3.0)(lucide-react@1.72.0(@types/react@19.3.0)(react@19.3.1))(react-dom@19.3.1(react@19.3.1))(react@19.3.1)(zod@4.6.7))(react-dom@19.3.1(react@19.3.1))(react@19.3.1)(tailwindcss@4.3.5)(takumi-js@2.22.1(csstype@3.2.4)(react@19.3.1))': dependencies: '@base-ui/react': 1.9.0(@types/react@19.3.0)(react-dom@19.3.1(react@19.3.1))(react@19.3.1) '@fuma-translate/react': 1.0.2(@types/react@19.3.0)(react-dom@19.3.1(react@19.3.1))(react@19.3.1) @@ -3445,6 +3530,7 @@ snapshots: optionalDependencies: '@types/mdx': 2.0.14 '@types/react': 19.3.0 + takumi-js: 2.22.1(csstype@3.2.4)(react@19.3.1) transitivePeerDependencies: - '@date-fns/tz' - date-fns @@ -3871,6 +3957,60 @@ snapshots: tailwindcss: 4.3.5 vite: 8.3.7(@types/node@26.6.5)(esbuild@0.28.2)(jiti@2.7.0)(yaml@2.9.1) + '@takumi-rs/core-darwin-arm64@2.22.1': + optional: true + + '@takumi-rs/core-darwin-x64@2.22.1': + optional: true + + '@takumi-rs/core-linux-arm64-gnu@2.22.1': + optional: true + + '@takumi-rs/core-linux-arm64-musl@2.22.1': + optional: true + + '@takumi-rs/core-linux-x64-gnu@2.22.1': + optional: true + + '@takumi-rs/core-linux-x64-musl@2.22.1': + optional: true + + '@takumi-rs/core-win32-arm64-msvc@2.22.1': + optional: true + + '@takumi-rs/core-win32-x64-msvc@2.22.1': + optional: true + + '@takumi-rs/core@2.22.1(csstype@3.2.4)(react@19.3.1)': + dependencies: + '@takumi-rs/helpers': 2.22.1(react@19.3.1) + optionalDependencies: + '@takumi-rs/core-darwin-arm64': 2.22.1 + '@takumi-rs/core-darwin-x64': 2.22.1 + '@takumi-rs/core-linux-arm64-gnu': 2.22.1 + '@takumi-rs/core-linux-arm64-musl': 2.22.1 + '@takumi-rs/core-linux-x64-gnu': 2.22.1 + '@takumi-rs/core-linux-x64-musl': 2.22.1 + '@takumi-rs/core-win32-arm64-msvc': 2.22.1 + '@takumi-rs/core-win32-x64-msvc': 2.22.1 + csstype: 3.2.4 + transitivePeerDependencies: + - preact + - react + + '@takumi-rs/helpers@2.22.1(react@19.3.1)': + optionalDependencies: + react: 19.3.1 + + '@takumi-rs/wasm@2.22.1(csstype@3.2.4)(react@19.3.1)': + dependencies: + '@takumi-rs/helpers': 2.22.1(react@19.3.1) + optionalDependencies: + csstype: 3.2.4 + transitivePeerDependencies: + - preact + - react + '@tanstack/history@1.162.5': {} '@tanstack/react-router@1.170.46(@types/react@19.3.0)(react-dom@19.3.1(react@19.3.1))(react@19.3.1)': @@ -4666,13 +4806,13 @@ snapshots: transitivePeerDependencies: - supports-color - fumadocs-twoslash@4.0.4(@fumadocs/base-ui@16.19.0(@types/mdx@2.0.14)(@types/react@19.3.0)(fumadocs-core@16.19.0(@mdx-js/mdx@3.1.1)(@tanstack/react-router@1.170.46(@types/react@19.3.0)(react-dom@19.3.1(react@19.3.1))(react@19.3.1))(@types/estree-jsx@1.0.5)(@types/hast@3.0.4)(@types/mdast@4.0.4)(@types/react@19.3.0)(lucide-react@1.72.0(@types/react@19.3.0)(react@19.3.1))(react-dom@19.3.1(react@19.3.1))(react@19.3.1)(zod@4.6.7))(react-dom@19.3.1(react@19.3.1))(react@19.3.1)(tailwindcss@4.3.5))(@types/react@19.3.0)(fumadocs-core@16.19.0(@mdx-js/mdx@3.1.1)(@tanstack/react-router@1.170.46(@types/react@19.3.0)(react-dom@19.3.1(react@19.3.1))(react@19.3.1))(@types/estree-jsx@1.0.5)(@types/hast@3.0.4)(@types/mdast@4.0.4)(@types/react@19.3.0)(lucide-react@1.72.0(@types/react@19.3.0)(react@19.3.1))(react-dom@19.3.1(react@19.3.1))(react@19.3.1)(zod@4.6.7))(react-dom@19.3.1(react@19.3.1))(react@19.3.1)(shiki@4.6.0): + fumadocs-twoslash@4.0.4(@fumadocs/base-ui@16.19.0(@types/mdx@2.0.14)(@types/react@19.3.0)(fumadocs-core@16.19.0(@mdx-js/mdx@3.1.1)(@tanstack/react-router@1.170.46(@types/react@19.3.0)(react-dom@19.3.1(react@19.3.1))(react@19.3.1))(@types/estree-jsx@1.0.5)(@types/hast@3.0.4)(@types/mdast@4.0.4)(@types/react@19.3.0)(lucide-react@1.72.0(@types/react@19.3.0)(react@19.3.1))(react-dom@19.3.1(react@19.3.1))(react@19.3.1)(zod@4.6.7))(react-dom@19.3.1(react@19.3.1))(react@19.3.1)(tailwindcss@4.3.5)(takumi-js@2.22.1(csstype@3.2.4)(react@19.3.1)))(@types/react@19.3.0)(fumadocs-core@16.19.0(@mdx-js/mdx@3.1.1)(@tanstack/react-router@1.170.46(@types/react@19.3.0)(react-dom@19.3.1(react@19.3.1))(react@19.3.1))(@types/estree-jsx@1.0.5)(@types/hast@3.0.4)(@types/mdast@4.0.4)(@types/react@19.3.0)(lucide-react@1.72.0(@types/react@19.3.0)(react@19.3.1))(react-dom@19.3.1(react@19.3.1))(react@19.3.1)(zod@4.6.7))(react-dom@19.3.1(react@19.3.1))(react@19.3.1)(shiki@4.6.0): dependencies: '@base-ui/react': 1.9.0(@types/react@19.3.0)(react-dom@19.3.1(react@19.3.1))(react@19.3.1) '@types/hast': 3.0.5 cn: 0.5.2 fumadocs-core: 16.19.0(@mdx-js/mdx@3.1.1)(@tanstack/react-router@1.170.46(@types/react@19.3.0)(react-dom@19.3.1(react@19.3.1))(react@19.3.1))(@types/estree-jsx@1.0.5)(@types/hast@3.0.4)(@types/mdast@4.0.4)(@types/react@19.3.0)(lucide-react@1.72.0(@types/react@19.3.0)(react@19.3.1))(react-dom@19.3.1(react@19.3.1))(react@19.3.1)(zod@4.6.7) - fumadocs-ui: '@fumadocs/base-ui@16.19.0(@types/mdx@2.0.14)(@types/react@19.3.0)(fumadocs-core@16.19.0(@mdx-js/mdx@3.1.1)(@tanstack/react-router@1.170.46(@types/react@19.3.0)(react-dom@19.3.1(react@19.3.1))(react@19.3.1))(@types/estree-jsx@1.0.5)(@types/hast@3.0.4)(@types/mdast@4.0.4)(@types/react@19.3.0)(lucide-react@1.72.0(@types/react@19.3.0)(react@19.3.1))(react-dom@19.3.1(react@19.3.1))(react@19.3.1)(zod@4.6.7))(react-dom@19.3.1(react@19.3.1))(react@19.3.1)(tailwindcss@4.3.5)' + fumadocs-ui: '@fumadocs/base-ui@16.19.0(@types/mdx@2.0.14)(@types/react@19.3.0)(fumadocs-core@16.19.0(@mdx-js/mdx@3.1.1)(@tanstack/react-router@1.170.46(@types/react@19.3.0)(react-dom@19.3.1(react@19.3.1))(react@19.3.1))(@types/estree-jsx@1.0.5)(@types/hast@3.0.4)(@types/mdast@4.0.4)(@types/react@19.3.0)(lucide-react@1.72.0(@types/react@19.3.0)(react@19.3.1))(react-dom@19.3.1(react@19.3.1))(react@19.3.1)(zod@4.6.7))(react-dom@19.3.1(react@19.3.1))(react@19.3.1)(tailwindcss@4.3.5)(takumi-js@2.22.1(csstype@3.2.4)(react@19.3.1))' mdast-util-from-markdown: 2.1.0 mdast-util-to-hast: 13.2.2 react: 19.3.1 @@ -4686,7 +4826,7 @@ snapshots: - date-fns - supports-color - fumadocs-typescript@5.6.0(@fumadocs/base-ui@16.19.0(@types/mdx@2.0.14)(@types/react@19.3.0)(fumadocs-core@16.19.0(@mdx-js/mdx@3.1.1)(@tanstack/react-router@1.170.46(@types/react@19.3.0)(react-dom@19.3.1(react@19.3.1))(react@19.3.1))(@types/estree-jsx@1.0.5)(@types/hast@3.0.4)(@types/mdast@4.0.4)(@types/react@19.3.0)(lucide-react@1.72.0(@types/react@19.3.0)(react@19.3.1))(react-dom@19.3.1(react@19.3.1))(react@19.3.1)(zod@4.6.7))(react-dom@19.3.1(react@19.3.1))(react@19.3.1)(tailwindcss@4.3.5))(@types/estree@1.0.9)(@types/hast@3.0.4)(@types/mdast@4.0.4)(@types/react@19.3.0)(fumadocs-core@16.19.0(@mdx-js/mdx@3.1.1)(@tanstack/react-router@1.170.46(@types/react@19.3.0)(react-dom@19.3.1(react@19.3.1))(react@19.3.1))(@types/estree-jsx@1.0.5)(@types/hast@3.0.4)(@types/mdast@4.0.4)(@types/react@19.3.0)(lucide-react@1.72.0(@types/react@19.3.0)(react@19.3.1))(react-dom@19.3.1(react@19.3.1))(react@19.3.1)(zod@4.6.7))(react-dom@19.3.1(react@19.3.1))(react@19.3.1): + fumadocs-typescript@5.6.0(@fumadocs/base-ui@16.19.0(@types/mdx@2.0.14)(@types/react@19.3.0)(fumadocs-core@16.19.0(@mdx-js/mdx@3.1.1)(@tanstack/react-router@1.170.46(@types/react@19.3.0)(react-dom@19.3.1(react@19.3.1))(react@19.3.1))(@types/estree-jsx@1.0.5)(@types/hast@3.0.4)(@types/mdast@4.0.4)(@types/react@19.3.0)(lucide-react@1.72.0(@types/react@19.3.0)(react@19.3.1))(react-dom@19.3.1(react@19.3.1))(react@19.3.1)(zod@4.6.7))(react-dom@19.3.1(react@19.3.1))(react@19.3.1)(tailwindcss@4.3.5)(takumi-js@2.22.1(csstype@3.2.4)(react@19.3.1)))(@types/estree@1.0.9)(@types/hast@3.0.4)(@types/mdast@4.0.4)(@types/react@19.3.0)(fumadocs-core@16.19.0(@mdx-js/mdx@3.1.1)(@tanstack/react-router@1.170.46(@types/react@19.3.0)(react-dom@19.3.1(react@19.3.1))(react@19.3.1))(@types/estree-jsx@1.0.5)(@types/hast@3.0.4)(@types/mdast@4.0.4)(@types/react@19.3.0)(lucide-react@1.72.0(@types/react@19.3.0)(react@19.3.1))(react-dom@19.3.1(react@19.3.1))(react@19.3.1)(zod@4.6.7))(react-dom@19.3.1(react@19.3.1))(react@19.3.1): dependencies: estree-util-value-to-estree: 3.5.0 fumadocs-core: 16.19.0(@mdx-js/mdx@3.1.1)(@tanstack/react-router@1.170.46(@types/react@19.3.0)(react-dom@19.3.1(react@19.3.1))(react@19.3.1))(@types/estree-jsx@1.0.5)(@types/hast@3.0.4)(@types/mdast@4.0.4)(@types/react@19.3.0)(lucide-react@1.72.0(@types/react@19.3.0)(react@19.3.1))(react-dom@19.3.1(react@19.3.1))(react@19.3.1)(zod@4.6.7) @@ -4703,7 +4843,7 @@ snapshots: '@types/hast': 3.0.4 '@types/mdast': 4.0.4 '@types/react': 19.3.0 - fumadocs-ui: '@fumadocs/base-ui@16.19.0(@types/mdx@2.0.14)(@types/react@19.3.0)(fumadocs-core@16.19.0(@mdx-js/mdx@3.1.1)(@tanstack/react-router@1.170.46(@types/react@19.3.0)(react-dom@19.3.1(react@19.3.1))(react@19.3.1))(@types/estree-jsx@1.0.5)(@types/hast@3.0.4)(@types/mdast@4.0.4)(@types/react@19.3.0)(lucide-react@1.72.0(@types/react@19.3.0)(react@19.3.1))(react-dom@19.3.1(react@19.3.1))(react@19.3.1)(zod@4.6.7))(react-dom@19.3.1(react@19.3.1))(react@19.3.1)(tailwindcss@4.3.5)' + fumadocs-ui: '@fumadocs/base-ui@16.19.0(@types/mdx@2.0.14)(@types/react@19.3.0)(fumadocs-core@16.19.0(@mdx-js/mdx@3.1.1)(@tanstack/react-router@1.170.46(@types/react@19.3.0)(react-dom@19.3.1(react@19.3.1))(react@19.3.1))(@types/estree-jsx@1.0.5)(@types/hast@3.0.4)(@types/mdast@4.0.4)(@types/react@19.3.0)(lucide-react@1.72.0(@types/react@19.3.0)(react@19.3.1))(react-dom@19.3.1(react@19.3.1))(react@19.3.1)(zod@4.6.7))(react-dom@19.3.1(react@19.3.1))(react@19.3.1)(tailwindcss@4.3.5)(takumi-js@2.22.1(csstype@3.2.4)(react@19.3.1))' transitivePeerDependencies: - supports-color @@ -5798,6 +5938,16 @@ snapshots: tailwindcss@4.3.5: {} + takumi-js@2.22.1(csstype@3.2.4)(react@19.3.1): + dependencies: + '@takumi-rs/core': 2.22.1(csstype@3.2.4)(react@19.3.1) + '@takumi-rs/helpers': 2.22.1(react@19.3.1) + '@takumi-rs/wasm': 2.22.1(csstype@3.2.4)(react@19.3.1) + transitivePeerDependencies: + - csstype + - preact + - react + tapable@2.3.4: {} thenify-all@1.6.0: diff --git a/scripts/reference-docs.mjs b/scripts/reference-docs.mjs index ca36b68..d368058 100644 --- a/scripts/reference-docs.mjs +++ b/scripts/reference-docs.mjs @@ -1,7 +1,8 @@ #!/usr/bin/env node // Writes the docs site's API reference from the JSDoc: a page per namespace -// or entry point, listing every export with the first paragraph of its docs, -// grouped by the guide that covers it. +// or entry point, listing every export with the first paragraph of its docs +// (plus, for a value, the paragraphs that say what it needs and how it +// fails), grouped by the guide that covers it. // // pnpm run docs:reference // @@ -31,22 +32,21 @@ const PAGES = [ slug: "fetch", title: "Fetch", description: - "Every member of the Fetch namespace: clients, calls, errors, plugins, endpoints, streams and pages.", + "Every member of the Fetch namespace: clients, calls, responses, uploads, errors, plugins, endpoints, streaming and pagination.", + related: "every member of the `Fetch` namespace.", module: "src/Fetch.ts", qualifier: "Fetch", importLine: 'import { Fetch } from "@monarcode/effetch";', - intro: "`@monarcode/effetch` exports one name, the `Fetch` namespace. Its members, grouped by the guide that covers them:", + intro: "`@monarcode/effetch` exports one name, the `Fetch` namespace. Import it as follows:", + first: ["Service", "make"], groups: [ ["Clients", ["Declare a client", "/docs/clients"]], - ["Calls", ["Methods", "/docs/calls"]], + ["Calls", ["Make a call", "/docs/calls"]], ["Responses", ["Read the response", "/docs/calls/responses"]], ["Uploads", ["Upload files", "/docs/calls/uploads"]], ["Errors", ["Call errors", "/docs/errors"]], ["Plugins", ["Write a plugin", "/docs/plugins/writing"]], - [ - "Endpoints and services", - ["Endpoints or methods", "/docs/endpoints"], - ], + ["Endpoint definitions", ["Endpoints or methods", "/docs/endpoints"]], ["Streaming", ["Streaming responses", "/docs/streaming"]], ["Pagination", ["Pagination", "/docs/pagination"]], ], @@ -60,14 +60,14 @@ const PAGES = [ "src/Errors.ts": "Errors", "src/Status.ts": "Errors", "src/Plugin.ts": "Plugins", - "src/Endpoint.ts": "Endpoints and services", - "src/Endpoints.ts": "Endpoints and services", + "src/Endpoint.ts": "Endpoint definitions", + "src/Endpoints.ts": "Endpoint definitions", "src/Streams.ts": "Streaming", "src/Paginate.ts": "Pagination", }, names: { CallError: "Errors", - QuerySchema: "Endpoints and services", + QuerySchema: "Endpoint definitions", ResponseMode: "Responses", StatusError: "Errors", StatusErrorMap: "Errors", @@ -81,8 +81,9 @@ const PAGES = [ title: "Plugins", description: "Every export of @monarcode/effetch/plugins: the built-in plugins and their options.", + related: "the built-in plugins and their options.", module: "src/plugins/index.ts", - intro: "`@monarcode/effetch/plugins` exports the built-in plugins, their options and the types they return:", + intro: "`@monarcode/effetch/plugins` exports the built-in plugins, their options, the types they return and `TimeoutError`. Import what you use:", groups: [ ["Bearer tokens", ["Refresh a token", "/docs/plugins/token-refresh"]], [ @@ -91,12 +92,9 @@ const PAGES = [ ], [ "Time limits", - ["Choose a time limit", "/docs/plugins#choose-a-time-limit"], - ], - [ - "Logging", - ["Built-in plugins", "/docs/plugins#what-each-plugin-does"], + ["Retry-After and a time limit", "/docs/plugins/retry-after"], ], + ["Logging", ["Built-in plugins", "/docs/plugins#logger"]], [ "Console logging", ["Log to the console", "/docs/plugins/console-logging"], @@ -116,10 +114,11 @@ const PAGES = [ title: "FetchTest", description: "Every member of the FetchTest namespace: the fake backend for tests and the requests it records.", + related: "the fake backend for tests.", module: "src/test/FetchTest.ts", qualifier: "FetchTest", importLine: 'import { FetchTest } from "@monarcode/effetch/test";', - intro: "`@monarcode/effetch/test` exports one name, the `FetchTest` namespace. Its members:", + intro: "`@monarcode/effetch/test` exports one name, the `FetchTest` namespace. Import it as follows:", groups: [ ["Fake backend", ["Test with a fake backend", "/docs/testing"]], [ @@ -130,8 +129,6 @@ const PAGES = [ files: { "src/test/FetchTest.ts": "Fake backend" }, names: { Recorder: "Recorded requests", - RequestBody: "Recorded requests", - RequestQuery: "Recorded requests", requests: "Recorded requests", SentRequest: "Recorded requests", }, @@ -304,12 +301,25 @@ ${page.intro} \`\`\`ts ${importLine} \`\`\` + +Its exports follow, grouped by the guide that covers them. Each one has the +first paragraph of its docs, and what it needs and how it fails; your +editor shows the rest, with an example, when you hover the name. `; for (const [title, [guide, guideUrl]] of page.groups) { body += `\n## ${title} [#${slug(title)}]\n\nGuide: [${guide}](${guideUrl}).\n`; + const first = (entry) => { + const index = (page.first ?? []).indexOf(entry.short); + return index === -1 ? Infinity : index; + }; const entries = page.top .filter((entry) => entry.group === title) - .sort((a, b) => Number(b.value) - Number(a.value) || byName(a, b)); + .sort( + (a, b) => + first(a) - first(b) || + Number(b.value) - Number(a.value) || + byName(a, b), + ); for (const entry of entries.flatMap((entry) => [ entry, ...entry.members, @@ -323,12 +333,24 @@ ${importLine} } } } + body += "\n## Related pages\n\n"; + body += + "- [Entry points](/docs/reference): what each entry point exports.\n"; + for (const other of PAGES) + if (other.slug !== page.slug) + body += `- [${other.title}](/docs/reference/${other.slug}): ${other.related}\n`; + body += + "- [Compatibility](/docs/reference/compatibility): the Effect, runtime and TypeScript versions Effetch supports.\n"; return body; } +/** A paragraph that says what a value needs, or how it fails or dies. */ +const BEHAVIOR = /\b(?:fails|dies|throws|is a defect|needs|requires)\b/i; + /** * An entry's first paragraph, and the list after it, such as a type's - * values or a function's behavior. An entry with a type table keeps the list + * values or a function's behavior, plus, for a value, each later paragraph + * that says what it needs or how it fails. An entry with a type table keeps the list * only when the paragraph leads into it ("…, and"), since the table lists the * properties. A link to an export on the reference becomes a link to its * entry; others become code. @@ -349,11 +371,27 @@ function summaryOf(entry, page, checker, targets) { text += link(part, page, checker, targets); } else text += part.text; } - const blocks = text.trim().split(/\n\s*\n/); + const blocks = text + .replace(/```[\s\S]*?```/g, "") + .trim() + .split(/\n\s*\n/); const kept = [blocks[0] ?? ""]; const unfinished = !/[.!?]\s*$/.test(blocks[0] ?? ""); - if ((unfinished || !entry.table) && /^\s*- /.test(blocks[1] ?? "")) + let next = 1; + if ((unfinished || !entry.table) && /^\s*- /.test(blocks[1] ?? "")) { kept.push(blocks[1]); + next = 2; + } + // A value also keeps what it needs and how it goes wrong, so the page + // says when a call fails or dies without opening the declaration. + if (entry.value) + for (let i = next; i < blocks.length; i++) { + const block = blocks[i]; + if (/^\s*- /.test(block) || !BEHAVIOR.test(block)) continue; + kept.push(block); + if (/:\s*$/.test(block) && /^\s*- /.test(blocks[i + 1] ?? "")) + kept.push(blocks[++i]); + } return kept.map(toMarkdown).join("\n\n"); } diff --git a/site/content/docs/(latest)/calls/body.mdx b/site/content/docs/(latest)/calls/body.mdx index 28a4714..a91d800 100644 --- a/site/content/docs/(latest)/calls/body.mdx +++ b/site/content/docs/(latest)/calls/body.mdx @@ -3,13 +3,15 @@ title: Send a body description: Send JSON, form data, text or bytes, encoded with a schema or as is. --- -Send a request body with `post`, `put`, `patch` or `del`. Effetch sends the -`body` according to its type, and an `input` schema types and encodes it. +When a call creates or changes something, it sends a body: a todo as JSON, +a form, a file. You pass the value as `body`, and Effetch picks how to +send it from its type. Add an `input` schema, and the body is typed and +encoded by it too. This page shows both, and the `content-type` each kind +of body is sent with. -## Send JSON or a form +## Send JSON -The following calls send a body encoded with an `input` schema, a plain JSON -body, and a `FormData` you build yourself: +Pass a plain object as `body`, and Effetch sends it as JSON: ```ts import * as Schema from "effect/Schema"; @@ -22,6 +24,37 @@ const Todo = Schema.Struct({ id: Schema.Finite, title: Schema.String, done: Schema.Boolean, +}); + +export const complete = api.patch("/todos/:id", { + params: { id: 1 }, + body: { done: true }, + output: Todo, +}); +``` + +The request goes out with `content-type: application/json`. + +`post`, `put`, `patch` and `del` take a body. `get`, `head` and `options` +don't, and TypeScript rejects one there. With `api.request`, any method +takes one, but a body on a `GET` or `HEAD` request makes the call die (see +[When the methods aren't enough](/docs/calls/http-client)). + +## Encode the body with a schema + +Add an `input` schema, and `body` is typed by it and encoded with it before +it's sent as JSON: + +```ts +import * as Schema from "effect/Schema"; + +import type { Fetch } from "@monarcode/effetch"; + +declare const api: Fetch.Client; + +const Todo = Schema.Struct({ + id: Schema.Finite, + title: Schema.String, due: Schema.Date, }); const NewTodo = Schema.Struct({ title: Schema.String, due: Schema.Date }); @@ -31,12 +64,29 @@ export const create = api.post("/todos", { body: { title: "Write docs", due: new Date() }, output: Todo, }); +``` -export const complete = api.patch("/todos/:id", { - params: { id: 1 }, - body: { done: true }, - output: Todo, -}); +In `create`, `due` is a `Date` in your code and an ISO string on the wire. + +A body that doesn't match `input`, or that can't be serialized as JSON, +makes the call die: it fails as a defect (an Effect that dies, which you +don't catch in normal code), with a message that starts with +`Invalid request body:`. A body the call can't send is a bug in the calling +code, not something to handle at runtime. See +[Logging and defects](/docs/errors/logging-and-defects). + +To send a typed body as a form instead, such as a file upload, see +[Upload files](/docs/calls/uploads). + +## Send a form, text or bytes + +Without `input`, Effetch sends the body according to its type. A +`FormData` you build yourself is sent as a form: + +```ts +import type { Fetch } from "@monarcode/effetch"; + +declare const api: Fetch.Client; export const upload = (file: Blob) => { const form = new FormData(); @@ -45,22 +95,47 @@ export const upload = (file: Blob) => { }; ``` -## How a body is sent +The following table shows how each type of body is sent, checked in this +order: -A `body` is sent according to its type: +| Body | Sent as | `content-type` | +| ------------------------------------------------- | --------------------- | -------------------------------------------------------- | +| An Effect `HttpBody` | As it is | The body's own | +| A string | As it is | `text/plain` | +| An `ArrayBuffer`, typed array or `DataView` | Its bytes | `application/octet-stream` | +| A `Blob` or `File` | As it is | The blob's `type`, or none when its `type` is empty | +| `FormData` | As it is | `multipart/form-data`, with a boundary the platform adds | +| `URLSearchParams` | As a URL-encoded form | `application/x-www-form-urlencoded` | +| Anything else, such as an object, array or number | JSON | `application/json` | -- an `HttpBody`, a string, an `ArrayBuffer` or typed array, a `Blob` or - `File`, `FormData` and `URLSearchParams` are sent as they are; -- anything else is sent as JSON. +A string is sent as `text/plain`, even when it holds JSON. So +`body: JSON.stringify(todo)` arrives as text, and a server that only reads +JSON may reject it. Pass the object itself, and Effetch serializes it. -## Encode the body with a schema +## Set the content type -Add an `input` schema, and `body` is typed by it and encoded with it before -it's sent as JSON. In `create`, `due` is a `Date` in your code and an ISO -string on the wire. +A `content-type` header on the call wins over the body's. Use it to send a +string you serialized yourself as JSON, or a body in a format of your own: -To send a typed body as a form instead, such as a file upload, see -[Upload files](/docs/calls/uploads). +```ts +import type { Fetch } from "@monarcode/effetch"; + +declare const api: Fetch.Client; + +declare const todoJson: string; + +export const save = api.put("/todos/1", { + body: todoJson, + headers: { "content-type": "application/json" }, +}); +``` + +A `FormData` body is the exception. Its `content-type` has to carry the +boundary the platform picks, so Effetch removes any `content-type` set by +the call, the endpoint or the client, and lets the platform set it. + +A `content-type` in the client's headers is dropped for every body (see +[Client configuration](/docs/clients/configuration#headers)). ## What's next diff --git a/site/content/docs/(latest)/calls/http-client.mdx b/site/content/docs/(latest)/calls/http-client.mdx index 6cc1b0a..eb5f67b 100644 --- a/site/content/docs/(latest)/calls/http-client.mdx +++ b/site/content/docs/(latest)/calls/http-client.mdx @@ -3,14 +3,17 @@ title: When the methods aren't enough description: Choose the method at runtime, read a stream, or use the HttpClient underneath a client. --- -When the methods aren't enough, pick a method at runtime with `api.request`, -read a stream with `api.sse` or `api.ndjson`, or use the `HttpClient` -underneath the client. +The client's methods cover most calls, but a few needs fall outside them: +an HTTP method you only know at runtime, a response that arrives a piece at +a time, or a request that Effetch doesn't model at all. This page shows the +way out for each one: `api.request`, `api.sse` and `api.ndjson`, and the +`HttpClient` underneath the client. ## Choose the method at runtime When the method is only known at runtime, use `api.request`. It takes the -method as its first argument, before the path and the options: +method as its first argument, then the path and the same options as the +other methods: ```ts import type * as HttpMethod from "effect/http/HttpMethod"; @@ -23,16 +26,60 @@ export const send = (method: HttpMethod.HttpMethod, path: string) => api.request(method, path); ``` +`api.request` also sends the methods that have no shorthand, such as +`TRACE` or `QUERY`. The other methods are shorthand for it. + +`api.request` types `body` the same way for every method, a literal +`"GET"` included, so TypeScript doesn't stop a body on a `GET`. When the +call runs, a body on a `GET` or `HEAD` request makes it die, since those +requests can't carry one. + ## Read a stream of events or lines -When the response is a stream of events or lines, use `api.sse` or -`api.ndjson`. See [Streaming responses](/docs/streaming). +When the response is a stream of Server-Sent Events or newline-delimited +JSON, use `api.sse` or `api.ndjson`. Each gives you an Effect `Stream` of +decoded items. See [Streaming responses](/docs/streaming). ## Use the underlying HttpClient -When you need something the methods don't do, use `api.httpClient`. It's the -configured `HttpClient` underneath, with the base URL, the default headers and -the plugins, but no status check and no decoding. +When you need something the methods don't do, such as reading a response +your own way, use `api.httpClient`. It's the configured Effect `HttpClient` +underneath the client, and it takes Effect's own requests: + +```ts +import * as Effect from "effect/Effect"; +import * as HttpClientRequest from "effect/http/HttpClientRequest"; + +import type { Fetch } from "@monarcode/effetch"; + +declare const api: Fetch.Client; + +// Reads the export as text, whatever its status. +export const download = Effect.flatMap( + api.httpClient.execute(HttpClientRequest.get("/export.csv")), + (response) => response.text, +); +``` + +`api.httpClient` adds the base URL and the client's default headers to each +request, and runs every plugin with its default options. Transport failures +fail with `NetworkError`, next to the plugins' own errors. + +It leaves out the rest of what a call does: + +- **No status check.** A `404` succeeds with its response, so check + `response.status` yourself. +- **No decoding.** There's no `output`, no `Accept` header picked for you, + and no `DecodeError`. +- **No error schemas.** The client's `defaultError` and `statusErrors` + don't apply. +- **No `onError` or `onExit` hooks.** A plugin that works from those, such + as `consoleLogger`, which logs from `onExit`, isn't run for these requests. +- **No per-call plugin options.** You can't turn a plugin off, or change its + options, for one request. + +For a streamed body, use `api.sse` or `api.ndjson` rather than +`api.httpClient`. ## What's next diff --git a/site/content/docs/(latest)/calls/index.mdx b/site/content/docs/(latest)/calls/index.mdx index bd2baac..b93b13b 100644 --- a/site/content/docs/(latest)/calls/index.mdx +++ b/site/content/docs/(latest)/calls/index.mdx @@ -1,23 +1,121 @@ --- -title: Methods -description: Call a route with get, head, options, post, put, patch or del. +title: Make a call +description: Pick a method, fill in the path's parameters and build the query string. --- -With a client in hand, every call is one method: you pass the path and an -object of options, and get an Effect back. +With a client in hand, every request is a single method call. You pass a +path and an object of options, and you get back an Effect that sends the +request when it runs. This page covers what every call has in common: the +method, the path and its parameters, and the query string. ## Pick a method -A client has a method for each HTTP method: +The client has a method for each common HTTP method, named in lowercase: - `get`, `head` and `options` send no body. -- `post`, `put`, `patch` and `del` can send one. It's `del` because `delete` - is a reserved word. +- `post`, `put`, `patch` and `del` can send one. It's `del`, not `delete`, + because `delete` is a reserved word in JavaScript. + +Each one takes the path first, then the options: + +```ts +import * as Schema from "effect/Schema"; + +import type { Fetch } from "@monarcode/effetch"; + +declare const api: Fetch.Client; + +const Todo = Schema.Struct({ id: Schema.Finite, title: Schema.String }); + +export const todo = api.get("/todos/1", { output: Todo }); + +export const renamed = api.patch("/todos/1", { + body: { title: "Write the docs" }, + output: Todo, +}); +``` + +Three other methods cover the rest: + +- `api.request` takes the HTTP method as its first argument. Use it when + the method is only known at runtime, or for one with no shorthand, such + as `TRACE` or `QUERY` (see + [When the methods aren't enough](/docs/calls/http-client)). +- `api.sse` and `api.ndjson` read a response that arrives a piece at a time + (see [Streaming responses](/docs/streaming)). + +## Fill in path parameters + +To put a value in the path, write that segment as a name that starts with +`:`, and pass the value in `params`: + +```ts +import * as Schema from "effect/Schema"; + +import type { Fetch } from "@monarcode/effetch"; + +declare const api: Fetch.Client; + +const Todo = Schema.Struct({ id: Schema.Finite, title: Schema.String }); + +// GET /todos/42 +export const one = api.get("/todos/:id", { params: { id: 42 }, output: Todo }); +``` + +TypeScript reads the parameter names from the path, so it asks for exactly +`params: { id }`, with no names missing and none extra. A path without +parameters doesn't take `params` at all. + +A value can be a string or a number. Effetch converts it with `String()` and +encodes it with `encodeURIComponent`, so `"a/b"` stays one segment (`a%2Fb`) +and can't add a level to the path. + +A parameter is always a whole segment, from the `:` to the next `/`. In +`/files/:name.json`, the parameter is called `name.json`, not `name`. To send +a file name with its extension, make the whole segment the parameter, as in +`/files/:file`, and pass `"report.json"`. + +## Build a query string + +Pass the query as a plain object, and Effetch builds the string for you: + +```ts +import * as Schema from "effect/Schema"; + +import type { Fetch } from "@monarcode/effetch"; + +declare const api: Fetch.Client; + +const Todo = Schema.Struct({ id: Schema.Finite, title: Schema.String }); + +// GET /todos?page=1&tags=work&tags=home +export const some = api.get("/todos", { + query: { page: 1, tags: ["work", "home"], search: undefined }, + output: Schema.Array(Todo), +}); +``` + +The rules are made so that you can pass optional filters as they are: + +- An array repeats the key, as in `tags=work&tags=home`. +- `null` and `undefined` values are left out, so `search` sends nothing. +- Numbers, booleans and bigints are converted with `String()`. + +With Effect 4.1 or later, a value can also be `Redacted`, such as +`Redacted.make(apiKey)`. It's sent as its value, and Effect keeps it out of +its own logs and traces. + +The `query` object isn't checked against anything, so a typo in a key +compiles. To type a query, or to send values that need encoding, such as +dates, give an endpoint a query schema. See +[Typed query parameters](/docs/endpoints/typed-query). ## What's next -- [Path and query parameters](/docs/calls/parameters): fill in the path and - build a query. -- [Send a body](/docs/calls/body): send JSON, forms, text or bytes. -- [Read the response](/docs/calls/responses): decode what comes back. +- [Send a body](/docs/calls/body): send JSON, a form, text or bytes. +- [Upload files](/docs/calls/uploads): send files in a typed multipart form. +- [Read the response](/docs/calls/responses): decode what comes back with a + schema. - [Call options](/docs/calls/options): look up every option a call takes. +- [When the methods aren't enough](/docs/calls/http-client): pick the method + at runtime, or use the client's `HttpClient` directly. diff --git a/site/content/docs/(latest)/calls/meta.json b/site/content/docs/(latest)/calls/meta.json index 455ffe2..54c6934 100644 --- a/site/content/docs/(latest)/calls/meta.json +++ b/site/content/docs/(latest)/calls/meta.json @@ -1,12 +1,4 @@ { "title": "Calls", - "pages": [ - "index", - "parameters", - "body", - "uploads", - "responses", - "options", - "http-client" - ] + "pages": ["index", "body", "uploads", "responses", "options", "http-client"] } diff --git a/site/content/docs/(latest)/calls/options.mdx b/site/content/docs/(latest)/calls/options.mdx index 85f697b..6003909 100644 --- a/site/content/docs/(latest)/calls/options.mdx +++ b/site/content/docs/(latest)/calls/options.mdx @@ -1,25 +1,42 @@ --- title: Call options -description: Look up an option a call accepts. +description: Look up an option a call accepts, its default, and the page that explains it. --- -Every method takes the path and an object of options. This page lists every -option a call accepts. +Every method takes a path and an object of options, such as +`api.get("/todos/:id", { params: { id: 1 }, output: Todo })`. Use this page +to look an option up. Each row links to the page that explains it in full. ## Options -The following options control how a call builds its request and reads its -response: - -| Option | What it does | -| -------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -| `params` | Values for the path's `:params`. Required, with exactly those names, when the path has any; not allowed otherwise. Values are URI-encoded. | -| `query` | An object of query parameters. Arrays repeat the key, and `null` and `undefined` are dropped. | -| `headers` | Headers for this call. They win over the client's, and over the body's `content-type`. | -| `body` | Sent by its type: `HttpBody`, string, `ArrayBuffer` and typed arrays, `Blob`/`File`, `FormData` and `URLSearchParams` as they are, anything else as JSON. | -| `input` | A schema `body` is encoded with. `body` is then typed by it. Sent as JSON, or as `multipart/form-data` when wrapped in `Fetch.multipart` (see [Upload files](/docs/calls/uploads)). | -| `output` | A schema the 2xx body is decoded with: read as JSON, or as text with `Fetch.text()` and bytes with `Fetch.bytes()`. The call then sends a matching `Accept` header (unless you set `accept`). Without it, the call succeeds with the raw `HttpClientResponse`. See [Read the response](/docs/calls/responses). | -| `responseMode` | `"decoded-and-response"` makes the call succeed with `[value, response]`, to read the status and headers too. Defaults to `"decoded"`, the value alone. | -| `error` | A schema for the body of error responses, replacing the client's `defaultError`. | -| `statusErrors` | Your own errors for error responses, by status. See [Errors by status](/docs/errors/status-errors). | -| `plugins` | Plugin overrides for this call (see [Change plugins for one call](/docs/plugins/per-call)). | +The following table lists every option a call accepts, with what a call +without it does: + +| Option | What it does | Default | +| -------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------- | +| `params` | Fills in the path's `:name` segments. Required when the path has any, and not allowed otherwise. See [Fill in path parameters](/docs/calls#fill-in-path-parameters). | None. | +| `query` | Builds the query string from an object. See [Build a query string](/docs/calls#build-a-query-string). | None. | +| `headers` | Headers for this call. They win over the client's, and over the body's `content-type`, except on a `FormData` body. See [Set the content type](/docs/calls/body#set-the-content-type). | The client's headers. | +| `body` | The request body, sent by its type. Only on `post`, `put`, `patch`, `del` and `request`, and on `sse` and `ndjson`. See [Send a body](/docs/calls/body). | None: no body. | +| `input` | A schema that types `body` and encodes it. A body that doesn't match makes the call die. See [Encode the body with a schema](/docs/calls/body#encode-the-body-with-a-schema), and [Upload files](/docs/calls/uploads) for `Fetch.multipart`. | None: `body` is sent by its type. | +| `output` | A schema the 2xx body is decoded with. See [Read the response](/docs/calls/responses). | None: the call succeeds with the `HttpClientResponse`. | +| `responseMode` | `"decoded-and-response"` makes the call succeed with `[value, response]`. See [Read the body and the response](/docs/calls/responses#read-the-body-and-the-response). | `"decoded"`: the value alone. | +| `error` | A schema for the body of error responses, decoded onto `HttpError.body`. See [Catch errors](/docs/errors/catching#read-the-error-body). | The client's `defaultError`, else `Schema.Unknown`: the parsed JSON. | +| `statusErrors` | Your own errors for error responses, by status. Tried before the client's. See [Errors by status](/docs/errors/status-errors). | None: only the client's apply. | +| `plugins` | Turns a plugin off, or changes its options, for this call. See [Change plugins for one call](/docs/plugins/per-call). | None: each plugin runs with its defaults. | + +These are the options of the client's methods. An endpoint's call takes a +subset of them, since its definition holds the rest (see +[Call an endpoint](/docs/endpoints/calling)). + +`api.request` takes the same options, after the HTTP method. A `GET` or +`HEAD` request with a `body` makes the call die (see +[When the methods aren't enough](/docs/calls/http-client)). + +## What's next + +- [Make a call](/docs/calls): pick a method, and fill in the path and the + query. +- [Send a body](/docs/calls/body): send JSON, a form, text or bytes. +- [Read the response](/docs/calls/responses): decode what comes back with a + schema. diff --git a/site/content/docs/(latest)/calls/parameters.mdx b/site/content/docs/(latest)/calls/parameters.mdx deleted file mode 100644 index 72eed97..0000000 --- a/site/content/docs/(latest)/calls/parameters.mdx +++ /dev/null @@ -1,56 +0,0 @@ ---- -title: Path and query parameters -description: Fill in a path's parameters and build a query. ---- - -Fill in a path's `:name` parameters from `params`, and build the query string -from a plain `query` object. - -## Fill in path parameters and a query - -The following calls fill in an `:id` parameter, and send a query with a -number, a repeated key and a dropped value: - -```ts -import * as Schema from "effect/Schema"; - -import type { Fetch } from "@monarcode/effetch"; - -declare const api: Fetch.Client; - -const Todo = Schema.Struct({ id: Schema.Finite, title: Schema.String }); - -// GET /todos/1 -export const one = api.get("/todos/:id", { params: { id: 1 }, output: Todo }); - -// GET /todos?page=1&tags=work&tags=home -export const some = api.get("/todos", { - query: { page: 1, tags: ["work", "home"], search: undefined }, - output: Schema.Array(Todo), -}); -``` - -## Path parameters - -Every `:name` in a path is a parameter, filled in from `params`. When a path -has parameters, `params` is required, with exactly those names, and when it -has none, `params` isn't allowed. Effetch URI-encodes the values for you. - -## Query parameters - -`query` is a plain object. Arrays repeat the key, and `null` and `undefined` -are dropped, so you can pass optional filters as they are. - -With Effect 4.1 or later, a value can also be `Redacted`, such as -`Redacted.make(apiKey)`: it's sent as its value, and Effect keeps it out of -its own logs and traces. - -To type an endpoint's query and send values such as dates, give the endpoint -a schema for it. See [Typed query parameters](/docs/endpoints/typed-query). - -## What's next - -- [Send a body](/docs/calls/body): send data with `post`, `put` and `patch`. -- [Read the response](/docs/calls/responses): decode the body with a schema. -- [Typed query parameters](/docs/endpoints/typed-query): type a query with a - schema. diff --git a/site/content/docs/(latest)/calls/responses.mdx b/site/content/docs/(latest)/calls/responses.mdx index f865c96..0615a46 100644 --- a/site/content/docs/(latest)/calls/responses.mdx +++ b/site/content/docs/(latest)/calls/responses.mdx @@ -3,19 +3,14 @@ title: Read the response description: Decode the body with a schema, or read text, bytes or the whole response. --- -Decode a response body with a schema, read it as text or bytes, or read the -status and headers next to the decoded body. +Most calls come back with a JSON body that you want as a typed value. Give +the call an `output` schema, and Effetch decodes the body with it, so the +call succeeds with the value your code expects. This page shows how, and +how to read a body that isn't JSON, or the status and headers next to it. ## Decode the body with a schema -Give a call an `output` schema, and the response body is decoded with it. The -call succeeds with the decoded value, or fails with `DecodeError` if the body -doesn't match. It also sends `Accept: application/json`, unless you set an -`accept` header yourself. - -Without `output`, the call succeeds with the raw `HttpClientResponse`. That's -handy when you only care that the call worked, or want to read the body -yourself: +Pass the schema as `output`: ```ts import * as Schema from "effect/Schema"; @@ -24,16 +19,21 @@ import type { Fetch } from "@monarcode/effetch"; declare const api: Fetch.Client; -// No output: succeeds with the HttpClientResponse. -export const remove = api.del("/todos/:id", { params: { id: 1 } }); +const Todo = Schema.Struct({ id: Schema.Finite, title: Schema.String }); -// Nothing to decode: an empty body (204, HEAD) decodes as JSON null. -export const archive = api.post("/todos/:id/archive", { - params: { id: 1 }, - output: Schema.Void, -}); +// Succeeds with { id: number, title: string } +export const todo = api.get("/todos/:id", { params: { id: 1 }, output: Todo }); ``` +The call succeeds with the decoded value, or fails with `DecodeError` if +the body doesn't match. It also sends `Accept: application/json`, unless an +`accept` header is set on the call, the endpoint or the client. + +Only a 2xx response is decoded. Any other status, 3xx included, fails with +`HttpError` before `output` runs (see [Call errors](/docs/errors)). `fetch` +follows redirects itself, so a 3xx only arrives with `redirect: "manual"` +or from a conditional request, such as `304 Not Modified`. + Use `Schema.Finite` rather than `Schema.Number` for numbers. Responses are decoded with Effect's JSON codec, where `Schema.Number` also decodes the @@ -41,20 +41,59 @@ export const archive = api.post("/todos/:id/archive", { to strings. `Schema.Finite` accepts every JSON number and rejects the rest. +## Handle an empty body + +Some responses have no body, such as a `204 No Content` or any `HEAD` +response. An empty body decodes as JSON `null`, so give such a call +`output: Schema.Void`: + +```ts +import * as Schema from "effect/Schema"; + +import type { Fetch } from "@monarcode/effetch"; + +declare const api: Fetch.Client; + +export const archive = api.post("/todos/:id/archive", { + params: { id: 1 }, + output: Schema.Void, +}); +``` + +`Schema.Undefined` and `Schema.NullOr(…)` accept an empty body too. A JSON +`null` body and an empty one decode the same way, so a schema can't tell +them apart. + +## Skip decoding + +Without `output`, the call succeeds with the raw `HttpClientResponse`. +That's handy when you only care that the call worked, or want to read the +body yourself: + +```ts +import type { Fetch } from "@monarcode/effetch"; + +declare const api: Fetch.Client; + +// Succeeds with the HttpClientResponse. +export const remove = api.del("/todos/:id", { params: { id: 1 } }); +``` + +The status is still checked: a response outside 2xx fails with `HttpError` +whether or not the call has an `output`. + ## Read text or bytes -`output` reads the body as JSON. For other bodies, wrap the schema: +`output` reads the body as JSON. For other bodies, wrap the schema in one of +these: - `Fetch.text()` reads the body as a string, as it was sent. -- `Fetch.text(schema)` reads a single value, such as a count or a status: it +- `Fetch.text(schema)` reads a single value, such as a count or a status. It trims the text, then decodes it with a schema whose encoded side is a string, such as `Schema.NumberFromString`. - `Fetch.bytes()` reads the body as a `Uint8Array`, a copy of the body, for images, PDFs and other binary bodies. -The call sends a matching `Accept` header: `text/*, */*;q=0.1` for text, and -`*/*` for bytes, unless you set one. - The following program reads a CSV export as text, a count as a number, and a PDF as bytes: @@ -80,16 +119,25 @@ export const program = Effect.gen(function* () { }); ``` -They work wherever `output` does, endpoints included. +They work wherever `output` does, endpoints included. The one exception is +`Fetch.bytes()`, which a stream (`api.sse`, `api.ndjson` or a stream +endpoint) can't take. + +The following rules apply to `Fetch.text` and `Fetch.bytes`: -- An empty body is `""` for `Fetch.text()` and a `Uint8Array` of length 0 for - `Fetch.bytes()`. For `Fetch.text(schema)`, it fails with `DecodeError`, as - for JSON. +- The call sends a matching `Accept` header: `text/*, */*;q=0.1` for text, + and `*/*` for bytes, unless an `accept` header is set on the call, the + endpoint or the client. +- An empty body is `""` for `Fetch.text()`, and a `Uint8Array` of length 0 + for `Fetch.bytes()`. +- For `Fetch.text(schema)`, an empty body fails with `DecodeError` before it + reaches the schema, so `Schema.NumberFromString` never reads it as `0`. - A body that can't be read, or doesn't match the schema, fails with `DecodeError`. - Error responses are still read as JSON for `error` and `statusErrors`. -- Pass the schema they return to `output` as it is. A schema built around it, - such as with `Schema.NullOr`, is read as JSON again. +- Pass the schema they return to `output` as it is, or with more checks or + annotations. A schema built around it, such as with `Schema.NullOr`, is + read as JSON again. ## Read the body and the response @@ -117,11 +165,14 @@ export const page = Effect.gen(function* () { }); ``` +The following rules apply to `responseMode`: + +- The default, `"decoded"`, gives the decoded body alone. - It's allowed on calls, on endpoint definitions, and on each call of an endpoint, where the call's own mode wins. - Without `output`, both items are the response. -- The body has already been read: use the decoded value. -- The default, `"decoded"`, gives the decoded body alone. +- The body has already been read, so use the decoded value rather than + reading the response's body again. ## What's next diff --git a/site/content/docs/(latest)/calls/uploads.mdx b/site/content/docs/(latest)/calls/uploads.mdx index 59b790b..2dd4e64 100644 --- a/site/content/docs/(latest)/calls/uploads.mdx +++ b/site/content/docs/(latest)/calls/uploads.mdx @@ -3,58 +3,84 @@ title: Upload files description: Upload files with a typed multipart body. --- -Upload files with a body that's typed and checked by a schema, as for JSON, -then sent as `multipart/form-data`. +Most APIs take a file upload as a `multipart/form-data` body: the file in +one part, and the other fields in parts beside it. Effetch builds that form +from a schema, so an upload's body is typed and checked the way a JSON body +is. This page shows how to send one, how each platform passes its files, +and how the schema's fields become form parts. ## Send a multipart body To upload files, wrap the `input` schema in `Fetch.multipart`, and use -`Fetch.UploadFile` for a file field: +`Fetch.UploadFile` for each file field: ```ts -import * as Effect from "effect/Effect"; import * as Schema from "effect/Schema"; import { Fetch } from "@monarcode/effetch"; +declare const api: Fetch.Client; + const Document = Schema.Struct({ id: Schema.String }); +const NewDocument = Fetch.multipart( + Schema.Struct({ + file: Fetch.UploadFile, + kind: Schema.Literals(["PASSPORT", "DRIVERS_LICENSE"]), + pages: Schema.optional(Schema.Finite), + }), +); + +// In a browser, `file` comes from an . +export const upload = (file: File) => + api.post("/documents", { + input: NewDocument, + body: { file, kind: "PASSPORT" }, + output: Document, + }); +``` + +`Fetch.multipart` marks the schema, so the body is encoded with it and then +sent as a form rather than as JSON. TypeScript checks `body` against the +schema, as it does for any `input`. + +The same schema works in an endpoint definition (see +[Endpoints or methods](/docs/endpoints)), so the upload's route and schemas live in one +place: + +```ts +import * as Schema from "effect/Schema"; + +import { Fetch } from "@monarcode/effetch"; + +declare const api: Fetch.Client; + export const uploadDocument = Fetch.endpoint("POST /documents", { input: Fetch.multipart( Schema.Struct({ file: Fetch.UploadFile, kind: Schema.Literals(["PASSPORT", "DRIVERS_LICENSE"]), - pages: Schema.optional(Schema.Finite), }), ), - output: Document, + output: Schema.Struct({ id: Schema.String }), }); -class Api extends Fetch.Service()("Api", { - baseUrl: "https://api.example.com", -}) {} +const send = api.bind(uploadDocument); -class DocumentApi extends Fetch.Endpoints()("DocumentApi", Api, { - upload: uploadDocument, -}) {} - -// In a browser, `file` comes from an . export const upload = (file: File) => - Effect.gen(function* () { - const documents = yield* DocumentApi; - return yield* documents.upload({ body: { file, kind: "PASSPORT" } }); - }); + send({ body: { file, kind: "PASSPORT" } }); ``` ## Files on each platform -`Fetch.UploadFile` takes the files each platform can send: +A file field takes the kind of file each platform can send. That differs +between platforms, so `Fetch.UploadFile` accepts each of them: -- in browsers, Node, Bun and Deno, a `Blob` or `File`; -- in React Native, the `{ uri, name, type }` object its pickers give, typed - `Fetch.NativeFile`. `uri` and `name` are required: a server only treats a - part as a file when it has a file name. `type` is optional, and a file - without one is sent as `application/octet-stream`. +- **In browsers, Node.js, Bun and Deno:** a `Blob` or `File`. +- **In React Native:** the `{ uri, name, type }` object its pickers give, + typed `Fetch.NativeFile`. `uri` and `name` are required, because a server + only treats a part as a file when it has a file name. `type` is optional, + and a file without one is sent as `application/octet-stream`. Use `Fetch.UploadFile` rather than `Schema.File`. `Schema.File` only takes a `File`, not the `{ uri, name, type }` objects React Native's pickers give, @@ -62,8 +88,9 @@ and `FetchTest` can't read it back from a form. ## Send a file from React Native -In React Native, send a `NativeFile`, not a `Blob`: React Native's `fetch` -reads a form's files from disk by `uri`, and can't send a `Blob` in a form. +In React Native, send a `NativeFile`, not a `Blob`. React Native's `fetch` +reads a form's files from disk by their `uri`, and can't send a `Blob` in a +form. The following example builds a `NativeFile` from an image picker's asset: @@ -86,13 +113,15 @@ export const photo: Fetch.NativeFile = { ## How fields become form parts -Effetch turns the schema's fields into form parts as follows: +A form holds only strings and files, so Effetch encodes the body with the +schema, then turns each field into form parts as follows: -- strings as they are; numbers, booleans and bigints as strings; a `Date` as - its ISO string; -- a file as a file part; -- a list as one part per item, under the same name; -- `null` and `undefined` left out. +- A string is sent as it is. +- A number, boolean or bigint is sent as a string, and a `Date` as its ISO + string. +- A file becomes a file part. +- A list becomes one part per item, all under the field's name. +- `null` and `undefined` are left out. A form can't hold a nested object or a list of lists, so TypeScript rejects most schemas that have one, and a value that has one makes the call die. To @@ -101,8 +130,8 @@ send one, encode it to a string in the schema, such as ## Check a file's size -To check a file's size, add a check to `Fetch.UploadFile`. A `NativeFile` has -no size until it's read, so the check only looks at a `Blob`: +To check a file's size, add a check to `Fetch.UploadFile`. A `NativeFile` +has no size until it's read, so the check only looks at a `Blob`: ```ts import * as Schema from "effect/Schema"; @@ -119,37 +148,55 @@ export const SmallFile = Fetch.UploadFile.check( ## Headers, errors and where it works -The following details cover the request's headers, how a bad body fails, and -where multipart bodies work. +Most uploads need nothing more than the sections on this page. The +following details cover the request's `content-type`, how a bad body fails, where multipart +bodies work, and how `FetchTest` reads a form back. - + + +- Effetch sets no `content-type` on a form, so the platform adds + `multipart/form-data` with its boundary. A `content-type` from the call, + the endpoint or the client is removed, as for any `FormData` body (see + [Set the content type](/docs/calls/body#set-the-content-type)). +- That happens before your plugins run. A plugin's `onRequest` that sets a + `content-type` replaces the boundary, so leave it out for forms. + + + -- The request sets no `Content-Type`, so the platform adds the multipart - boundary. A `content-type` header from the call, the endpoint or the client - is removed, for any `FormData` body. -- The request sets no `Content-Type` before your plugins run. A plugin's - `onRequest` that sets one replaces the boundary, so leave it out for forms. - A body that doesn't match the schema, or a value a form can't hold, makes - the call die with an `Invalid request body:` defect, as for JSON (see - [Logging and defects](/docs/errors/logging-and-defects)). So does a - `{ uri, name, type }` file outside React Native, where `FormData` would send - `"[object Object]"`, or in a field that isn't a `Fetch.UploadFile`. -- `Fetch.UploadFile` in an `input` schema without `Fetch.multipart` makes the - call die too: a file has no JSON form. -- It works wherever `input` does: on methods such as `api.post`, on endpoints, - and in `api.sse` and `api.ndjson`. + the call die with an `Invalid request body:` defect, the same as a JSON + body that doesn't match its `input` (see + [Logging and defects](/docs/errors/logging-and-defects)). +- So does a `{ uri, name, type }` file outside React Native, where + `FormData` would send `"[object Object]"`, or one in a field that isn't a + `Fetch.UploadFile`. +- `Fetch.UploadFile` in an `input` schema without `Fetch.multipart` makes + the call die too, since a file has no JSON form. +- A field's encoded value must be a string, number, boolean, bigint, + `Date`, file, `null` or `undefined`, or a list of them. A schema such as + `Schema.DateTimeUtc` or `Schema.URL`, which encodes to an object, needs a + string form first, such as `Schema.DateTimeUtcFromString`. + + + + +- It works wherever `input` does: on methods such as `api.post`, on + endpoints, and in `api.sse` and `api.ndjson`. - `Fetch.multipart` returns the schema, marked. Add checks or annotations to it as you like. A schema built around it, such as with `Schema.NullOr`, is sent as JSON again. -- A field's encoded value must be a string, number, boolean, bigint, `Date`, - file, `null` or `undefined`, or a list of them. A schema such as - `Schema.DateTimeUtc` or `Schema.URL`, which encodes to an object, needs a - string form first, such as `Schema.DateTimeUtcFromString`. +- A `FormData` you build yourself still works as a `body` without `input` + (see [Send a body](/docs/calls/body#send-a-form-text-or-bytes)). + + + + - [`FetchTest`](/docs/testing) reads the form back into the body a handler - gets, decoded with the schema, with files as `File`s. In Node, test with a - `Blob` or `File`, since a `{ uri, name, type }` file only works in React - Native. + gets, decoded with the schema, with files as `File`s. In Node.js, test + with a `Blob` or `File`, since a `{ uri, name, type }` file only works in + React Native. - A form loses some of what the schema encodes, so `FetchTest` reads it back as best it can: - A `null` or `undefined` field and an empty list are left out. Such a @@ -160,7 +207,6 @@ where multipart bodies work. `"null"` comes back as `null`, and in `Schema.Union([Schema.String, Schema.Finite])` the string `"12"` comes back as the number `12`. -- A `FormData` you build yourself still works as a `body` without `input`. diff --git a/site/content/docs/(latest)/clients/configuration.mdx b/site/content/docs/(latest)/clients/configuration.mdx index 3c8ed7a..6e3b92d 100644 --- a/site/content/docs/(latest)/clients/configuration.mdx +++ b/site/content/docs/(latest)/clients/configuration.mdx @@ -1,15 +1,17 @@ --- title: Client configuration -description: Look up an option a client accepts. +description: Look up an option a client accepts, its default, and what it changes for each call. --- -This page lists the options you can pass when you declare a client. The -config of `Fetch.Service` takes the same options as `Fetch.make` (see -[Fetch.Service or Fetch.make](/docs/clients/service-or-make)). +A client's config holds what every call to one backend has in common. You +pass it to `Fetch.Service`, or to `Fetch.make`, which takes the same options +(see [Fetch.Service or Fetch.make](/docs/clients/service-or-make)). This +page lists each option with its default, then the rules that come with +each one. ## Example -Here's a client with all of the options: +Here's a client that uses every option: ```ts import * as Config from "effect/Config"; @@ -43,12 +45,93 @@ export class Api extends Fetch.Service()("Api", { ## Options -Every option is optional: +Every option is optional. The following table lists what each one is for, +and what a client without it does: -| Option | What it's for | -| -------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -| `baseUrl` | Where the API lives. It's put in front of every path that isn't a full `http(s)://` URL. Pass a string, or an Effect that's run once when the client is built, such as a `Config`. It can't contain a query string or a fragment. | -| `headers` | Headers sent with every request. A call's header with the same name wins. `content-type` and `content-length` are ignored here, since they come from each body. | -| `defaultError` | A schema for the body of the API's error responses (see [Typed error bodies](/docs/errors/error-bodies)). | -| `statusErrors` | Your own errors for error responses, by status, for every call (see [Errors by status](/docs/errors/status-errors)). | -| `plugins` | Behavior every call goes through, outermost first (see [Built-in plugins](/docs/plugins)). | +| Option | What it's for | Default | +| -------------- | -------------------------------------------------------------------------------------------------- | ------------------------------------------------------ | +| `baseUrl` | Where the API lives. A string, or an Effect such as a `Config`. See [The base URL](#the-base-url). | None: each path is sent as you wrote it. | +| `headers` | Headers sent with every request. See [Headers](#headers). | None. | +| `defaultError` | A schema for the body of the API's error responses, decoded onto `HttpError.body`. | `Schema.Unknown`: `HttpError.body` is the parsed JSON. | +| `statusErrors` | Your own errors for error responses, by status, for every call. | None: an error status fails with `HttpError`. | +| `plugins` | Behavior every call goes through, such as auth, retries and logging. | `[]`: no plugins. | + +## The base URL + +Effetch puts the `baseUrl` in front of every path that isn't a full +`http://` or `https://` URL. It joins the two with exactly one `/`, so a +base path is kept: with `https://api.example.com/v1`, both `"/todos"` and +`"todos"` go to `https://api.example.com/v1/todos`. + +A `baseUrl` can be a string, or an Effect that's run one time, when the +client is built. A `Config` such as `Config.String("API_URL")` works, and +its failure is the error of `Api.layer`. + +The `baseUrl` can't contain a query string or a fragment. Pass query +parameters with each call's `query` option instead (see +[Build a query string](/docs/calls#build-a-query-string)). + +Without a `baseUrl`, a browser resolves a relative path against the page's +URL. Other runtimes have no page to resolve it against, so there a call +with a relative path dies. + +## Headers + +The client's headers are sent with every request, and a header with the +same name on a call, or on an endpoint, wins over the client's. + +You can't set `content-type` or `content-length` here, and Effetch drops +them if you do. Each body sets its own, and a client-wide value would be +wrong for most of them (see [Send a body](/docs/calls/body)). + +An `accept` header here replaces the one Effetch picks for a call's +`output`, such as `application/json` (see +[Read the response](/docs/calls/responses)). Set one only when every call +expects the same type. + +## Error schemas + +`defaultError` decodes the body of every error response onto +`HttpError.body`. A call's or an endpoint's `error` option replaces it for +that call (see [Catch errors](/docs/errors/catching#read-the-error-body)). + +`statusErrors` apply to every call. An endpoint and a call can have their +own as well. For a given status, the call's map, or on an endpoint call +the endpoint's, is tried before the client's (see +[Errors by status](/docs/errors/status-errors)). + +## Plugins + +Plugins run outermost first: `plugins[0]` wraps all the others (see +[How plugins nest](/docs/plugins#how-plugins-nest)). Two rules keep the +list working: + +- **Each plugin's name must be unique.** Calls turn a plugin off or change + its options by its name, so two plugins with one name make building the + client die. +- **Pass the list inline,** in the config. Annotating it as `Plugin.Any[]` + erases the plugins' types, and with them the errors and per-call options + they add. + +## When a config is wrong + +Some mistakes in a config are bugs in your code, not failures to handle at +runtime, so they're defects: the Effect dies, and you don't catch it in +normal code (see [Logging and defects](/docs/errors/logging-and-defects)). + +Building the client dies when `Api.layer` is built or `Fetch.make` runs, +not when the class is declared, if: + +- the `baseUrl` contains a `?` or a `#`; +- two plugins have the same name. + +A call dies when it runs if its path is relative, the client has no +`baseUrl`, and the program isn't running in a browser. + +## What's next + +- [Provide the client](/docs/clients/providing): give `Api.layer` what it + needs, and run your program. +- [Derive a client](/docs/clients/derived): make a second client from this + config. +- [Built-in plugins](/docs/plugins): pick the plugins to add. diff --git a/site/content/docs/(latest)/clients/derived.mdx b/site/content/docs/(latest)/clients/derived.mdx index ca5ebfa..c6ad533 100644 --- a/site/content/docs/(latest)/clients/derived.mdx +++ b/site/content/docs/(latest)/clients/derived.mdx @@ -3,15 +3,16 @@ title: Derive a client description: Make a client from another, with a different base URL or one more header. --- -This page shows how to make a second client from a first one, for the same -client with a different base URL, such as a second API version, or with one -more header. +Sometimes you need a second client that's almost the same as the first: +the same API under another version, or the same backend with one more +header. Rather than repeat the config, you spread the first client's config +into the second and change what differs. This page shows how, and what +happens to each option you change. ## Spread the first client's config -Spread the first class's `config` into a second class. The second class -keeps the plugins, `defaultError` and `statusErrors`, so its client has the -same type: +Spread the first class's `config` into a second class, then set the options +that differ: ```ts import * as Schema from "effect/Schema"; @@ -31,11 +32,65 @@ export class ApiV2 extends Fetch.Service()("ApiV2", { }) {} ``` -## Keep the first client's headers +`ApiV2` keeps the plugins, the `defaultError` and the `statusErrors` of +`Api`, so its client has the same type. A function that takes +`Effect.Success` takes an `ApiV2` client too. -When you set `headers`, `Api.config.headers` is replaced, not merged. To -keep the first client's headers, spread them too, as in -`headers: { ...Api.config.headers, "x-client": "web" }`. +Give the second class its own id, as `"ApiV2"` here. With the same id, the +two classes would be the same service. + +## Change an option + +Any option you set replaces the first client's. It isn't merged with it. + +To add a header and keep the first client's, spread `Api.config.headers` +before your own: + +```ts +import { Fetch } from "@monarcode/effetch"; + +export class Api extends Fetch.Service()("Api", { + baseUrl: "https://api.example.com", + headers: { "x-app": "todos" }, +}) {} + +export class WebApi extends Fetch.Service()("WebApi", { + ...Api.config, + headers: { ...Api.config.headers, "x-client": "web" }, +}) {} +``` + +A header you list after the spread wins over one of the same name from +`Api.config.headers`, whatever its case. + +To add a plugin, list the plugins again. Keep the ones both clients share +in constants, so both lists hold the same plugins: + +```ts +import { Fetch } from "@monarcode/effetch"; +import { logger, retry } from "@monarcode/effetch/plugins"; + +const retrying = retry(); + +export class Api extends Fetch.Service()("Api", { + baseUrl: "https://api.example.com", + plugins: [retrying], +}) {} + +export class LoggedApi extends Fetch.Service()("LoggedApi", { + ...Api.config, + plugins: [retrying, logger()], +}) {} +``` + +A client with different plugins has a different type, since plugins add +errors and per-call options. The same goes for a different `defaultError` +or `statusErrors`. Type the second client as +`Effect.Success`. + +You could also write `[...(Api.config.plugins ?? []), logger()]`, but +`Api.config.plugins` can be `undefined` in its type, so the list's type +becomes a choice between two lists rather than the one you meant. ## What's next diff --git a/site/content/docs/(latest)/clients/index.mdx b/site/content/docs/(latest)/clients/index.mdx index 93f6ee3..e91dd41 100644 --- a/site/content/docs/(latest)/clients/index.mdx +++ b/site/content/docs/(latest)/clients/index.mdx @@ -3,17 +3,17 @@ title: Declare a client description: Declare a client as an Effect service with Fetch.Service. --- -This page shows how to declare a client with `Fetch.Service` and use it -anywhere in your app. - -A client holds everything a backend's calls have in common: where the -backend lives, the headers every request needs, the shape of its errors and -the plugins every call goes through. You declare it once and share it with -the rest of your app. +Every call to one backend shares a few things: where the backend lives, the +headers each request needs, the shape of its errors and the plugins each +call goes through. A client holds them, so you declare them once and every +call picks them up. This page shows how to declare a client with +`Fetch.Service`, and how to use it anywhere in your app. ## Declare the client -`Fetch.Service` declares a client as an Effect service, in one class: +`Fetch.Service` declares a client as an Effect service (a value your +program asks for by its type, and that a layer provides when it runs). It +takes an id and a config, and gives you one class: ```ts import * as Effect from "effect/Effect"; @@ -34,40 +34,90 @@ export const program = Effect.gen(function* () { }); ``` +The config takes more than a `baseUrl`: default headers, error schemas and +plugins. [Client configuration](/docs/clients/configuration) lists them all. + ## What the class gives you The class gives you three things: -- **`Api` is the service.** `yield* Api` gives the client, typed from the - config. -- **`Api.layer` builds the client.** It needs an `HttpClient`, plus - whatever the `baseUrl` Effect and the plugins need. Every layer that - depends on it in one layer graph gets the same client. -- **`Api.config` is the config you passed**, frozen. You can read it when - the module loads, before any layer is built, for example to get the - `defaultError` and `statusErrors` schemas. +- **`Api` is the service.** `yield* Api` gives you the client, typed from + the config. +- **`Api.layer` builds the client.** It needs an `HttpClient`, the Effect + service that sends the requests, plus whatever the `baseUrl` Effect and + the plugins need. [Provide the client](/docs/clients/providing) shows how + to give it those. +- **`Api.config` is a frozen copy of the config you passed.** You can read + it when the module loads, before any layer is built, for example to reuse + the `defaultError` and `statusErrors` schemas. Its `headers` are an Effect + `Headers` value, with the names in lowercase. + +`Api.layer` is a single value, and Effect shares a layer by value. Wherever +it appears in one layer graph, it's built once, and every layer that +depends on it gets the same client. Each `Effect.provide` builds it again, +though, so provide it once, where the program runs. + +To check whether a value is a class made by `Fetch.Service`, use +`Fetch.isService(value)`. It returns `true` for such a class, or one that +extends it, and `false` for anything else, including a key you wrote with +`Context.Service`. ## Type the client -Your client's type is `Effect.Success`. It includes your -plugins and your `defaultError`. Use it wherever you need to type a client, -such as a function parameter. +To type a client, for example as a function parameter, use +`Effect.Success`. That's the type `yield* Api` gives you, with +the plugins, the `defaultError` and the `statusErrors` from your config: + +```ts +import * as Effect from "effect/Effect"; +import * as Schema from "effect/Schema"; + +import { Fetch } from "@monarcode/effetch"; +import { retry } from "@monarcode/effetch/plugins"; -`Fetch.Client` is the type of a client without plugins, and yours won't fit -it. +const Todo = Schema.Struct({ id: Schema.Finite, title: Schema.String }); + +export class Api extends Fetch.Service()("Api", { + baseUrl: "https://api.example.com", + defaultError: Schema.Struct({ code: Schema.String }), + plugins: [retry()], +}) {} + +export const listTodos = (api: Effect.Success) => + api.get("/todos", { output: Schema.Array(Todo) }); +``` + +`Fetch.Client` is a shorter name for one case: a client with no plugins, no +`defaultError` and no `statusErrors`. The `Api` in the first example has +only a `baseUrl`, so its client is a `Fetch.Client`, and the samples in +these docs use `declare const api: Fetch.Client` for that reason. Adding any +of the three changes the client's type, because plugins add errors and +per-call options, `defaultError` types the error body, and `statusErrors` +add errors of your own. A client with any of them no longer fits +`Fetch.Client`, so use `Effect.Success`. ## Call from anywhere -Calls need nothing from the environment. The client holds on to the -`HttpClient`, the base URL and any services its plugins need. Its calls -only need the services of their own schemas, if any, so they run anywhere: -in a service, in a query function, or with `Effect.runPromise`. +A call doesn't need anything else from you to run. The client already holds +the `HttpClient`, the base URL and the services its plugins need, so you can +run a call from a service, a React Query function or a plain +`Effect.runPromise`. + +The one exception is schemas. A schema can need a service of its own to +decode or encode, and a call needs the services of every schema it uses: + +- the call's own `input`, `output`, `error` and `statusErrors`, or the + endpoint's, its `query` schema included; +- the client's `defaultError` and `statusErrors`. + +Most schemas need no services, so most calls need nothing at all. ## Give each client its own id -Two classes with the same id are the same service, so give each client its -own id. `Fetch.isService(value)` tells a class made by `Fetch.Service` -apart from any other value. +The id you pass, `"Api"` in the first example, is the service's identity when the program +runs, as with `Context.Service`. Two classes with the same id are the same +service, and a layer built for one serves the other. So give each client +its own id. ## What's next @@ -75,5 +125,6 @@ apart from any other value. the config takes. - [Provide the client](/docs/clients/providing): give `Api.layer` the `HttpClient` it needs, and run your program. +- [Make a call](/docs/calls): call the API with the client's methods. - [Fetch.Service or Fetch.make](/docs/clients/service-or-make): find out when to build a client without the class. diff --git a/site/content/docs/(latest)/clients/providing.mdx b/site/content/docs/(latest)/clients/providing.mdx index 45395c1..52b6913 100644 --- a/site/content/docs/(latest)/clients/providing.mdx +++ b/site/content/docs/(latest)/clients/providing.mdx @@ -1,15 +1,18 @@ --- title: Provide the client -description: Give a program the HttpClient that the client's layer needs. +description: Give a program the HttpClient that the client's layer needs, then run it. --- -This page shows how to give `Api.layer` the `HttpClient` it needs, so you -can run a program that uses your client. +`Api.layer` builds your client, but it doesn't bring the `HttpClient` that +sends the requests. You provide one where you run your program, and that +separation is what lets a test swap in a fake one. This page shows how to +provide it, how to set fetch options such as cookies, and how to build the +`HttpClient` into the layer when you'd rather not provide it. ## Provide an HttpClient where you run the program -`Api.layer` needs an `HttpClient`. Provide one where you run your program, -usually next to the other layers of your app: +Provide `FetchHttpClient.layer`, Effect's `HttpClient` built on `fetch`, to +`Api.layer`, then provide the result to your program and run it: ```ts import * as Effect from "effect/Effect"; @@ -29,11 +32,30 @@ export const program = Effect.gen(function* () { return yield* api.get("/health"); }); -export const runnable = program.pipe(Effect.provide(ApiLive)); +await Effect.runPromise(program.pipe(Effect.provide(ApiLive))); ``` -Keeping the `HttpClient` out of `Api.layer` is what lets tests swap in a -fake one. +`ApiLive` usually sits next to the other layers of your app. Provide it +one time, where the program runs: each `Effect.provide` builds the client +again, so providing it inside each function that calls the API builds a +separate client for every one of them. + +Effect's `HttpClient` adds tracing headers (`traceparent` and `b3`) to +every request. In a browser, a call to a cross-origin API that doesn't +allow them fails the CORS preflight. See [Platform notes](/docs/platforms#browsers) to turn +them off. + +## Set fetch options for every request + +`FetchHttpClient.RequestInit` sets the `fetch` options every request starts +from, such as `credentials`, `cache` or `redirect`. Provide it next to +`FetchHttpClient.layer`, and every call the client makes uses it, since the +client keeps the services it was built with. Each request's method, headers +and body still come from the call. + +The most common use is a browser app that calls an API on another origin +and needs its cookies sent. [Send cookies](/docs/platforms#send-cookies) +shows that setup, with what the API's CORS response has to allow. ## Build the HttpClient into the layer @@ -55,8 +77,9 @@ export class Api extends Fetch.Service()("Api", { } ``` -An override can need less than the original layer, but not more, and can't -add an error. +The override can need less than the original layer, but not more, and it +can't add an error. To add requirements, build a separate layer from +`Api.layer` instead. The override builds the real `HttpClient` into `Api.layer`, so a test can no @@ -67,8 +90,8 @@ add an error. ## What's next +- [Make a call](/docs/calls): call the API with the client's methods. - [Test with a fake backend](/docs/testing): provide a fake `HttpClient` instead of the real one. - [Derive a client](/docs/clients/derived): make a second client from the first one's config. -- [Methods](/docs/calls): make calls with the client. diff --git a/site/content/docs/(latest)/clients/service-or-make.mdx b/site/content/docs/(latest)/clients/service-or-make.mdx index c9d1ba0..8233924 100644 --- a/site/content/docs/(latest)/clients/service-or-make.mdx +++ b/site/content/docs/(latest)/clients/service-or-make.mdx @@ -3,19 +3,38 @@ title: Fetch.Service or Fetch.make description: Choose between declaring a client as a service and building one with Fetch.make. --- -This page explains how `Fetch.Service` and `Fetch.make` relate, and helps -you choose between them. +Most apps declare each client with `Fetch.Service`, and never need anything +else. Underneath it is `Fetch.make`, a function that builds a client +directly. It's the better fit for a script, for a config that only an +Effect can produce, or for a client made while the program runs. This page +shows how the two relate, what you give up with `Fetch.make`, and when to +use each. ## How they relate -`Fetch.make` is the function underneath `Fetch.Service`: it takes the same -config and returns an Effect that builds the client. Both give you the same -client, with the same calls and the same types. +`Fetch.make` takes the same config as `Fetch.Service` and returns an Effect +that builds the client. `Fetch.Service` calls `Fetch.make` in its layer, and +adds the pieces an app needs around it: a service key, a layer and the +config to read back. Both give you the same client, with the same calls and +the same types. + +## What you give up with Fetch.make + +With `Fetch.make`, you write by hand what the class gives you: + +- **No service key.** To share the client as a service, you declare one + with `Context.Service`, as in + [Fetch.make with a config from an Effect](#fetchmake-with-a-config-from-an-effect). +- **No layer.** You build one with `Layer.effect`. +- **No `Api.config`.** There's no frozen config to spread into a derived + client (see [Derive a client](/docs/clients/derived)). +- **No `Fetch.isService`.** It returns `false` for a key you wrote with + `Context.Service`. ## Which one to use -Use the class by default, and reach for `Fetch.make` when the class doesn't -fit: +Use the class by default, and use `Fetch.make` when the class doesn't fit. +The following table matches common situations to each: | Situation | Use | | ---------------------------------------------------------------------------------- | --------------- | @@ -26,9 +45,14 @@ fit: | A config that comes from an Effect, such as headers read from a service | `Fetch.make` | | A client made inside your own service's layer, or one per tenant at runtime | `Fetch.make` | +`Fetch.Endpoints` takes the client's service key, so it works with any key, +including one you wrote by hand. `Fetch.Service` is the shorter way there, +since the class is already that key. + ## Fetch.make in a script -In a script, use `Fetch.make` inline: +In a script, call `Fetch.make` inline and provide an `HttpClient` where you +run it: ```ts import * as Effect from "effect/Effect"; @@ -46,8 +70,9 @@ await Effect.runPromise(program.pipe(Effect.provide(FetchHttpClient.layer))); ## Fetch.make with a config from an Effect -When the config itself comes from an Effect, call `Fetch.make` inside that -Effect and declare the service by hand: +When the config itself comes from an Effect, such as a header read from +another service, call `Fetch.make` inside that Effect, then declare the +service and its layer by hand: ```ts import * as Context from "effect/Context"; @@ -75,8 +100,13 @@ export class Api extends Context.Service>()( export const ApiLive = Layer.effect(Api)(makeApi); ``` -## Related pages +`ApiLive` needs a `Tenant` and an `HttpClient`, and `Api` works as a client +key for `Fetch.Endpoints`. + +## What's next - [Declare a client](/docs/clients): declare a client with `Fetch.Service`. -- [Client configuration](/docs/clients/configuration): the options both - take. +- [Client configuration](/docs/clients/configuration): look up the options + both take. +- [Share endpoints as a service](/docs/endpoints/services): bind endpoints + to a client's service key with `Fetch.Endpoints`. diff --git a/site/content/docs/(latest)/coming-from-axios-or-ky.mdx b/site/content/docs/(latest)/coming-from-axios-or-ky.mdx index ff9d37a..4728d91 100644 --- a/site/content/docs/(latest)/coming-from-axios-or-ky.mdx +++ b/site/content/docs/(latest)/coming-from-axios-or-ky.mdx @@ -1,27 +1,84 @@ --- title: Coming from axios or ky -description: Map what you know from axios or ky to Effetch. +description: Map what you know from axios or ky to Effetch, and see what has no counterpart. --- -If you've used axios or ky, most of what you know has a counterpart in -Effetch. The following table maps what you know from axios and ky to Effetch: - -| axios or ky | Effetch | -| ------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -| `axios.create`, `ky.create` | [`Fetch.Service`](/docs/clients), or [`Fetch.make`](/docs/clients/service-or-make) in a script | -| `ky.extend`, a client per API version | A second `Fetch.Service` from `{ ...Api.config, baseUrl }` (see [Derive a client](/docs/clients/derived)) | -| `baseURL`, `prefixUrl` | `baseUrl`, a string or an Effect such as a `Config` | -| `params`, `searchParams` | `query`, a plain object, or typed by an endpoint's [`query` schema](/docs/endpoints/typed-query) | -| Interceptors, `hooks.beforeRequest` and `hooks.afterResponse` | A [plugin](/docs/plugins/writing)'s `onRequest` and `onResponse` | -| `hooks.beforeError` | `Effect.mapError` on the call. A plugin's `onError` sees errors but can't change them | -| `retry`, `timeout` | The [`retry` and `timeout` plugins](/docs/plugins), which a call can turn off or adjust | -| ky's `totalTimeout` | `retry({ budget })`, or `Effect.timeout` around a call | -| `AbortController`, `signal` | Interruption: `Fiber.interrupt`, `Effect.race`, `Effect.timeout`. An interrupted call aborts its request | -| `validateStatus`, `throwHttpErrors: false` | `Effect.catchTag("HttpError", …)`, [`statusErrors`](/docs/errors/status-errors), or [`Fetch.catchStatus`](/docs/errors/catching#catch-a-status) and `Fetch.optional` | -| `error.response.data`, ky's `HTTPError` body | `HttpError.body`, decoded with `defaultError` or the call's `error` schema | -| `ky.get(url).json()`, `axios.get(url)` | `api.get(path, { output: Schema })`: the body is checked, not cast | -| `responseType: "text"` or `"arraybuffer"` | `output: Fetch.text()` or `Fetch.bytes()` (see [Read text or bytes](/docs/calls/responses#read-text-or-bytes)) | -| Reading the status and headers with the data | `responseMode: "decoded-and-response"` (see [Read the body and the response](/docs/calls/responses#read-the-body-and-the-response)) | -| `responseType: "stream"`, `onDownloadProgress` for events | [`api.sse` and `api.ndjson`](/docs/streaming) | -| A `FormData` body built by hand | `input: Fetch.multipart(schema)`, a typed body sent as a form (see [Upload files](/docs/calls/uploads)) | -| The `fetch` option or an `adapter` in tests | [`FetchTest`](/docs/testing), or any `HttpClient` layer | +If you've used axios or ky, you already know most of what Effetch does. The +names are different, and a few things move: a hook becomes a plugin, a cast +becomes a schema, and an abort signal becomes interruption. This page maps +each option and habit to its counterpart in Effetch, and lists what has +none. + +## Clients and requests + +The following table maps how you create a client and build a request: + +| axios or ky | Effetch | +| ----------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------- | +| `axios.create`, `ky.create` | [`Fetch.Service`](/docs/clients), or [`Fetch.make`](/docs/clients/service-or-make) in a script | +| `ky.extend`, a client per API version | A second `Fetch.Service` from `{ ...Api.config, baseUrl }` (see [Derive a client](/docs/clients/derived)) | +| axios's `baseURL`; ky's `baseUrl` or `prefix` (`prefixUrl` before ky 2) | `baseUrl`, a string or an Effect such as a `Config`. It's joined to the path as a string, as ky's `prefix` is | +| `headers` | `headers`, on the client or on one call | +| `params`, `searchParams` | `query`, a plain object, or typed by an endpoint's [`query` schema](/docs/endpoints/typed-query) | +| axios's `data`, ky's `json` | `body`, which an `input` schema can type and check (see [Send a body](/docs/calls/body)) | +| A `FormData` body built by hand | `input: Fetch.multipart(schema)`, a typed body sent as a form (see [Upload files](/docs/calls/uploads)) | +| axios's `withCredentials`, ky's `credentials` | `credentials: "include"` in `FetchHttpClient.RequestInit` (see [Send cookies](/docs/platforms#send-cookies)) | + +## Responses + +The following table maps how you read what comes back: + +| axios or ky | Effetch | +| --------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| `ky.get(url).json()`, `axios.get(url)` | `api.get(path, { output: Schema })`. The body is checked against the schema, not cast | +| `responseType: "text"` or `"arraybuffer"` | `output: Fetch.text()` or `Fetch.bytes()` (see [Read text or bytes](/docs/calls/responses#read-text-or-bytes)) | +| Reading the status and headers with the data | `responseMode: "decoded-and-response"` (see [Read the body and the response](/docs/calls/responses#read-the-body-and-the-response)) | +| `responseType: "stream"`, `onDownloadProgress` for events | [`api.sse` and `api.ndjson`](/docs/streaming), which give the events or lines as a `Stream` | +| `responseType: "stream"` for raw bytes | A call without `output`. It succeeds with the `HttpClientResponse`, whose `stream` reads the body as it arrives (see [Skip decoding](/docs/calls/responses#skip-decoding)) | + +## Errors + +The following table maps how you handle a failed call: + +| axios or ky | Effetch | +| -------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| `validateStatus`, `throwHttpErrors: false` | `Effect.catchTag("HttpError", …)`, [`statusErrors`](/docs/errors/status-errors), or [`Fetch.catchStatus`](/docs/errors/catching#catch-a-status) and `Fetch.optional` | +| `error.response.data`, ky's `HTTPError` body | `HttpError.body`, decoded with `defaultError` or the call's `error` schema (see [Read the error body](/docs/errors/catching#read-the-error-body)) | +| `hooks.beforeError` | `Effect.mapError` on the call. A plugin's `onError` receives errors, but can't change them | + +## Hooks, retries, cancellation and tests + +The following table maps what runs around every request: + +| axios or ky | Effetch | +| ----------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| Interceptors, `hooks.beforeRequest` and `hooks.afterResponse` | A [plugin](/docs/plugins/writing)'s `onRequest` and `onResponse` | +| An interceptor that adds a token | The `bearer` plugin, which can also refresh the token (see [Refresh a token](/docs/plugins/token-refresh)) | +| `retry`, `timeout` | The [`retry` and `timeout` plugins](/docs/plugins), which a call can turn off or adjust | +| ky's `totalTimeout` | `retry({ budget })`, or `Effect.timeout` around a call | +| `AbortController`, `signal` | Interruption, with `Fiber.interrupt`, `Effect.race` or `Effect.timeout`. An interrupted call aborts its request | +| `transformRequest`, `transformResponse`, ky's `parseJson` and `stringifyJson` | An `input` or `output` schema, which encodes or decodes the body, such as a date string into a `Date`. For anything else, a plugin's `onRequest` or `onResponse` can return a changed request or response | + +In tests, where you'd pass ky a `fetch` option or give axios an `adapter`, +provide [`FetchTest`](/docs/testing) or any other `HttpClient` layer +instead. + +## What has no counterpart + +Some features of axios and ky have no counterpart in Effetch: + +- **Upload and download progress.** Effetch has no `onUploadProgress` or + `onDownloadProgress`, and Effect's `HttpClient` doesn't report progress + either. +- **`paramsSerializer`.** The query format is fixed: an array repeats its + key, as in `tags=a&tags=b`. For another format, build the value yourself, + such as `tags: tags.join(",")`. + +## What's next + +- [Getting started](/docs/getting-started): write and run a first program + with Effetch. +- [Write a plugin](/docs/plugins/writing): move an interceptor or a hook + into a plugin. +- [Catch errors](/docs/errors/catching): handle a failed call the Effect + way, by the error's tag. diff --git a/site/content/docs/(latest)/endpoints/calling.mdx b/site/content/docs/(latest)/endpoints/calling.mdx index d563d2a..eb03f2d 100644 --- a/site/content/docs/(latest)/endpoints/calling.mdx +++ b/site/content/docs/(latest)/endpoints/calling.mdx @@ -3,18 +3,22 @@ title: Call an endpoint description: Pass what changes on each call, and bind endpoints to a client with bind, bindAll or api.endpoint. --- -This page shows you what to pass when you call an endpoint, and how to bind -endpoints to a client yourself when `Fetch.Endpoints` doesn't fit. +A bound endpoint is a function: you call it with what changes from one call +to the next, and it returns the same Effect a method would. This page shows +what each call takes, and how to bind endpoints to a client yourself when +`Fetch.Endpoints` doesn't fit. ## Pass what changes on each call -What's fixed goes in the definition, and what changes goes in each call: +What's fixed goes in the definition, and what changes goes in each call. +The two sides split as follows: -| Defined once, on the endpoint | Passed with each call | -| --------------------------------------------------- | ------------------------- | -| `output`, `error`, `input`, `query`, `statusErrors` | `params`, `query`, `body` | -| `headers`, `responseMode`, `stream` | `headers`, `responseMode` | -| `plugins` (when binding) | `plugins` | +| Defined once, on the endpoint | Passed with each call | +| --------------------------------------------------------- | --------------------------------------------------------- | +| `output`, `error`, `input`, `statusErrors` and `stream` | `params` and `body` | +| `query`, a schema | `query`, the values | +| `headers` and `responseMode` | `headers`, and `responseMode` except on a stream endpoint | +| `plugins`, when binding or in `api.endpoint`'s definition | `plugins` | A call follows these rules: @@ -22,7 +26,7 @@ A call follows these rules: `api.get("/users/:id", { output: User, params: { id } })` does, and returns the same Effect. - `params` are required when the route's path has any, as with the methods. - An endpoint that needs nothing more is called with no arguments: + An endpoint that needs nothing more is called with no arguments, as in `users.list()`. - With an `input` schema, `body` is required and typed by it. - `GET`, `HEAD`, `OPTIONS` and `TRACE` endpoints take no `body` and no @@ -31,18 +35,24 @@ A call follows these rules: schema has required fields. See [Typed query parameters](/docs/endpoints/typed-query). +When the call and the endpoint both give headers, plugin overrides or a +`responseMode`, the call's win. The full rules are in +[How defaults combine](/docs/endpoints/defining#how-defaults-combine). + ## Bind endpoints with bind and bindAll `Fetch.Endpoints` is built on two client methods, which you can also use -directly, such as inside your own service's layer: +yourself, such as inside your own service's layer: - **`api.bind(definition, options?)`** binds one definition. `options` are the binding's `headers` and `plugins` overrides. -- **`api.bindAll(record)`** binds a record of definitions, each under its own - name. An entry can also be a `[definition, options]` pair, with the options - `api.bind` takes. Each endpoint has the type `api.bind` gives it. +- **`api.bindAll(record)`** binds a record of definitions, each under its + own name. An entry can also be a `[definition, options]` pair, with the + options `api.bind` takes. Each endpoint has the type `api.bind` gives it. -The following example binds the same two endpoints both ways: +The following example binds the same two endpoints both ways. Logging in +turns off the `bearer` plugin, which would otherwise add a token (see +[Built-in plugins](/docs/plugins)): ```ts import * as Effect from "effect/Effect"; @@ -52,10 +62,17 @@ import { Fetch } from "@monarcode/effetch"; import { bearer } from "@monarcode/effetch/plugins"; const User = Schema.Struct({ id: Schema.Finite, name: Schema.String }); +const Credentials = Schema.Struct({ + user: Schema.String, + password: Schema.String, +}); const Session = Schema.Struct({ token: Schema.String }); const getUser = Fetch.endpoint("GET /users/:id", { output: User }); -const login = Fetch.endpoint("POST /auth/login", { output: Session }); +const login = Fetch.endpoint("POST /auth/login", { + input: Credentials, + output: Session, +}); class Api extends Fetch.Service()("Api", { baseUrl: "https://api.example.com", @@ -79,11 +96,16 @@ export const sameEndpoints = Effect.gen(function* () { }); ``` +Both methods check what you pass when they run, and throw on a mistake that +got past the types. `api.bind` throws when it's given an endpoint that's +already bound, and `api.bindAll` throws on an entry that isn't a definition +or a `[definition, options]` pair. + ## Define and bind in one step -**`api.endpoint(route, definition)`** defines and binds in one step, where -you already have the client. Its definition can take `plugins` directly, -since it knows the client's plugins: +`api.endpoint(route, definition)` defines and binds in one step, where you +already have the client. Its definition can take `plugins` directly, since +the client is right there to check them against: ```ts import * as Effect from "effect/Effect"; @@ -92,6 +114,10 @@ import * as Schema from "effect/Schema"; import { Fetch } from "@monarcode/effetch"; import { bearer } from "@monarcode/effetch/plugins"; +const Credentials = Schema.Struct({ + user: Schema.String, + password: Schema.String, +}); const Session = Schema.Struct({ token: Schema.String }); class Api extends Fetch.Service()("Api", { @@ -103,6 +129,7 @@ export const endpoints = Effect.gen(function* () { const api = yield* Api; return { login: api.endpoint("POST /auth/login", { + input: Credentials, output: Session, plugins: { bearer: false }, }), @@ -112,9 +139,12 @@ export const endpoints = Effect.gen(function* () { ## Choose between Fetch.endpoint and api.endpoint -`api.bind(Fetch.endpoint(route, definition))` is the endpoint -`api.endpoint(route, definition)` makes, with the same type and the same -calls. Prefer `Fetch.endpoint` when: +The two give the same endpoint. `api.bind(Fetch.endpoint(route, definition))` +has the same type and makes the same calls as +`api.endpoint(route, definition)`, as long as the definition has no +`plugins`. With `Fetch.endpoint`, those go in `api.bind`'s options instead. + +Prefer `Fetch.endpoint` when: - endpoints should be listed next to their schemas, in a file with no client (see @@ -124,6 +154,9 @@ calls. Prefer `Fetch.endpoint` when: without a client, as `FetchTest` does (see [Test with a fake backend](/docs/testing)). +Otherwise, `api.endpoint` does the same in one step, where you have the +client. + ## What's next - [Typed query parameters](/docs/endpoints/typed-query): give an endpoint a diff --git a/site/content/docs/(latest)/endpoints/defining.mdx b/site/content/docs/(latest)/endpoints/defining.mdx index 6ee450a..1119c5b 100644 --- a/site/content/docs/(latest)/endpoints/defining.mdx +++ b/site/content/docs/(latest)/endpoints/defining.mdx @@ -1,17 +1,18 @@ --- title: Define endpoints -description: Save a route with its schemas, defaults and overrides. +description: Save a route with its schemas and defaults, and see how they combine with the client's and the call's. --- -This page shows you how to define an endpoint with `Fetch.endpoint`, how -its defaults combine with the client's and the call's, and which properties -you can read from it. +You define an endpoint once, and every call to it uses what you saved. This +page shows how to write a definition with `Fetch.endpoint`, what it can +hold, how its defaults combine with the client's and the call's, and what +you can read back from it. ## Define an endpoint -`Fetch.endpoint` takes a route, the method and the path in one string, and -what every call to it shares. It needs no client, so you can define endpoints -next to their schemas: +`Fetch.endpoint` takes a route, which is the method and the path in one +string, and what every call to it shares. It needs no client, so you can +define endpoints next to their schemas: ```ts import * as Schema from "effect/Schema"; @@ -32,47 +33,106 @@ export const createUser = Fetch.endpoint("POST /users", { getUser.route; // "GET /users/:id" getUser.output; // User +getUser.error; // undefined, so the client's defaultError applies ``` -A definition is plain data: it holds the route, the schemas and the defaults, -but it can't make a call until it's bound to a client. To bind it, see -[Share endpoints as a service](/docs/endpoints/services). +A definition is plain data. It holds the route, the schemas and the +defaults, but it can't make a call until you bind it to a client. To bind +it, see [Share endpoints as a service](/docs/endpoints/services). + +## What a definition holds + +Everything in a definition is optional. It takes the following options: + +| Option | What it does | +| -------------- | ----------------------------------------------------------------------------------------------------------------------- | +| `output` | Decodes a 2xx body. Without it, a call succeeds with the raw `HttpClientResponse`. | +| `error` | Decodes an error body into `HttpError.body`, in place of the client's `defaultError`. | +| `statusErrors` | Turns error responses into your own errors, by status. See [Errors by status](/docs/errors/status-errors). | +| `input` | Encodes `body`, and makes `body` required on every call. `GET`, `HEAD`, `OPTIONS` and `TRACE` endpoints can't take one. | +| `headers` | Headers sent with every call. | +| `responseMode` | What every call succeeds with. See [Read the response](/docs/calls/responses). | +| `query` | A schema that types and encodes each call's query. See [Typed query parameters](/docs/endpoints/typed-query). | +| `stream` | `"sse"` or `"ndjson"`, so every call returns a `Stream`. See [Streaming responses](/docs/streaming). | + +A `Fetch.endpoint` definition takes no `plugins`, because plugin overrides +are checked against a client's plugins, and a definition has no client yet. +You give them when you bind it, or in the definition of `api.endpoint`, +which defines and binds in one step (see +[Call an endpoint](/docs/endpoints/calling)). ## Write the route -The route is an uppercase method, one space, then a path that starts with `/` -or a full `http(s)://` URL. TypeScript checks it as you type: `"GTE /users"` -and `"get /users"` don't compile, and your editor suggests the methods. -`Fetch.endpoint` also throws on a malformed route, so a bad one fails as soon -as its module is imported. +The route is an uppercase method, one space, then a path that starts with +`/` or a full `http://` or `https://` URL. TypeScript checks it as you type: +`"GTE /users"` and `"get /users"` don't compile, and your editor suggests +the methods. -## Set defaults and overrides +`Fetch.endpoint` also checks the definition when it runs, and throws on +what can't work. A bad definition then fails as soon as its module is +imported, not on its first call. It throws on: -An endpoint's headers, plugin overrides and schemas combine with the -client's and the call's as follows: +- a malformed route, which TypeScript only lets through after a cast; +- a `query` schema with a field that can't be encoded to a string, such as + `Schema.instanceOf(Uint8Array)`; +- a `stream` that isn't `"sse"` or `"ndjson"`, or that comes with a + `responseMode` or a `Fetch.bytes()` output. -- **Headers.** A call's headers win over the endpoint's, which win over the - client's. A bound endpoint's headers are the binding's over the - definition's. Unlike the client's, an endpoint's headers can set - `content-type`. -- **Plugins.** A call's plugin override wins over the endpoint's (given when - binding, or to `api.endpoint`), and when both give options, they're - merged. An endpoint bound with `retry: false` can still be retried in one - call with `plugins: { retry: { times: 2 } }`. -- **Schemas** belong to the endpoint, and can't be changed per call. +## How defaults combine -## Read an endpoint's properties +An endpoint holds defaults, the client holds others, and each call can add +its own. They combine as follows: -Each endpoint also has `route`, `method` and `path` properties, for log labels -or cache keys. Plugins see the same route, as `ctx.route` (see -[Write a plugin](/docs/plugins/writing)). +- **Headers.** A call's headers win over the endpoint's, which win over the + client's. A bound endpoint's headers are the ones given when binding, over + the definition's. Unlike the client's, an endpoint's headers can set + `content-type`, such as `application/merge-patch+json` for a `PATCH`, + since one endpoint sends the same kind of body on every call. +- **Plugin overrides.** An override turns a plugin off for the endpoint, or + changes its options, as in `{ bearer: false }` for a login that sends no + token (see [Built-in plugins](/docs/plugins)). The endpoint's overrides + come from binding, or from `api.endpoint`'s definition. A call's override + for the same plugin wins, and when both give options, they're merged. So + an endpoint bound with `retry: false` can still be retried in one call + with `plugins: { retry: { times: 2 } }`. +- **Schemas.** `output`, `input` and `query` belong to the endpoint, and a + call can't change them. +- **Error body.** The endpoint's `error` schema replaces the client's + `defaultError`. Without one, the endpoint uses the `defaultError` of the + client it's bound to. +- **Errors by status.** The endpoint's `statusErrors` are tried first, then + the client's. A call to an endpoint can't add a map of its own. +- **Response mode.** A call's `responseMode` wins over the endpoint's. + A stream endpoint's calls can't take one. -Its `output`, `error` and `input` properties are its schemas, for things like -decoding cached data or building test fixtures: +## Read an endpoint's properties -- `output` and `input` are `undefined` when the endpoint has none. -- `error` is the schema error bodies are decoded with: the endpoint's, else - the client's `defaultError`, else `Schema.Unknown`. +An endpoint carries what it was defined with, so other code can read it. +`route`, `method` and `path` are there for log labels and cache keys, and +plugins get the same route, as `ctx.route` (see +[Write a plugin](/docs/plugins/writing)). The schemas are there for things +such as decoding cached data or building test fixtures. + +A definition from `Fetch.endpoint` and a bound endpoint have mostly the same +properties. A few differ, because only a bound endpoint has a client to +fall back on: + +| Property | On a definition | On a bound endpoint | +| -------------- | ---------------------------------------------- | ----------------------------------------------------------------------------------------------- | +| `route` | The route, such as `"GET /users/:id"` | The same | +| `method` | The method, such as `"GET"` | The same | +| `path` | The path, such as `"/users/:id"` | The same | +| `output` | The schema, or `undefined` without one | The same | +| `input` | The schema, or `undefined` without one | The same | +| `error` | The schema, or `undefined` without one | The endpoint's schema, else the client's `defaultError`, else `Schema.Unknown` | +| `statusErrors` | The map as given, or `undefined` without one | For each status, a list of the endpoint's schemas, then the client's. `{}` when neither has any | +| `headers` | The headers, or `undefined` without any | Not there | +| `responseMode` | The mode, or `undefined` without one | The same | +| `query` | The schema, or `undefined` without one | The same | +| `stream` | `"sse"`, `"ndjson"`, or `undefined` | The same | +| `url(options)` | The URL a call would go to, without a base URL | The same, starting with the client's `baseUrl` | + +For `url`, see [Build an endpoint's URL](/docs/endpoints/urls). ## What's next diff --git a/site/content/docs/(latest)/endpoints/index.mdx b/site/content/docs/(latest)/endpoints/index.mdx index b60499f..8f32de8 100644 --- a/site/content/docs/(latest)/endpoints/index.mdx +++ b/site/content/docs/(latest)/endpoints/index.mdx @@ -3,49 +3,102 @@ title: Endpoints or methods description: Learn what endpoints add over methods, and when to use each. --- -This page explains what an endpoint is, what it adds over the methods, and -how to choose between them for each call. +When the same call shows up in a few places, its path and schemas start to +repeat, and a typo in one copy still compiles. An endpoint saves the call +once, so every place that uses it stays in step. This page shows what that +buys you, and when a plain method is still the better choice. -The methods spell out a call's path and schemas where the call is made. -That's fine for a call made once. Once a call is made from several places, -you start repeating its path, its schemas and its rules, and a mistake in one -copy still compiles. An endpoint saves them once, and gives you a function to -call. +## What an endpoint is -## What endpoints add +An endpoint is a call you've saved under a name. Here's the same request as +a method call and as an endpoint: + +```ts +import * as Effect from "effect/Effect"; +import * as Schema from "effect/Schema"; + +import { Fetch } from "@monarcode/effetch"; + +const User = Schema.Struct({ id: Schema.Finite, name: Schema.String }); + +class Api extends Fetch.Service()("Api", { + baseUrl: "https://api.example.com", +}) {} + +// Saved once, with its route and schema, and bound to the client +const getUser = Fetch.endpoint("GET /users/:id", { output: User }); + +class Users extends Fetch.Endpoints()("Users", Api, { + get: getUser, +}) {} + +export const program = Effect.gen(function* () { + const api = yield* Api; + const users = yield* Users; + + // A method call spells out the path and the schema + const ada = yield* api.get("/users/:id", { + params: { id: 1 }, + output: User, + }); -An HTTP call mixes two kinds of information: + // An endpoint call passes only what changes + const grace = yield* users.get({ params: { id: 2 } }); -| Fixed by the API | Different on every call | -| ---------------------------------------------------- | ----------------------------------- | -| the route; the response, error and body schemas | path params, query values, the body | -| rules for that route, such as "login sends no token" | a one-off header or plugin override | + return [ada, grace]; +}); +``` -With the methods, you write both at every call site. Three calls to -`GET /users/:id` repeat the path and the `User` schema three times, and a -mistake in one of them, such as the wrong schema or a forgotten -`bearer: false`, still compiles. An endpoint takes the first column once, when -it's defined, and only the second column when it's called. That gives you: +Both calls send `GET /users/:id`, and decode the response with `User`. The +difference is in what you write at the call site. + +There are two ways to define an endpoint: + +- **`Fetch.endpoint(route, definition)`** gives a definition: plain data, + with no client. You can export it from a file next to its schemas, then + bind it to a client with `api.bind`, or share a group of them as a + service with `Fetch.Endpoints`. +- **`api.endpoint(route, definition)`** defines and binds in one step, on a + client you already have. + +Both give the same kind of bound endpoint, which is the function you call. +[Call an endpoint](/docs/endpoints/calling) compares them. + +## What endpoints add + +An HTTP call mixes two kinds of information. Some of it is fixed by the +API: the route, the schemas for the response, the error body and the +request body, and rules for that route, such as "logging in sends no +token". The rest changes on every call: the path's parameters, the query +values, the body, and the odd one-off header. + +With methods, you write both kinds at every call site. Three calls to +`GET /users/:id` repeat the path and the `User` schema three times. A +mistake in one of them, such as the wrong schema, or a forgotten +`bearer: false` (which turns off the `bearer` auth plugin for that call), +still compiles. An endpoint takes the fixed part once, when it's defined, +and only the changing part when it's called. That gives you: - **One place per route.** A path or a schema changes in one line, and the service that holds your endpoints lists the API you use. -- **Stricter types than a method can have.** A method only learns its HTTP - method and its `input` at the call, so it has to accept both ways. An - endpoint knows them up front: `body` is required when there's an `input` - (it's optional with `api.post`), a `GET` endpoint rejects a `body` at - compile time (`api.request("GET", …)` only dies at runtime), and the route - is checked as you type. +- **Stricter types than a method can have.** A method gets its HTTP method + and its `input` schema only at the call, so its types have to allow every + case. An endpoint has both from its definition. `body` is required when + there's an `input` (it's optional with `api.post`). A `GET` endpoint + rejects a `body` at compile time, while `api.request("GET", …)` only dies + at runtime. The route is checked as you type. - **Defaults that can't be forgotten.** An endpoint's headers and plugin overrides apply to every call. -- **A name instead of a URL.** Call sites read `users.get(…)`, and `route`, - `method` and `path` are there for query keys and log labels. +- **A name instead of a URL.** Call sites read `users.get(…)`, and the + endpoint's `route`, `method` and `path` are there for query keys and log + labels. -Endpoints add no new behavior: a call goes through the same plugins, +Endpoints add no new behavior. A call goes through the same plugins, decoding and errors as the method it stands for, so everything in -[Declare a client](/docs/clients), [Methods](/docs/calls), +[Declare a client](/docs/clients), [Make a call](/docs/calls), [Call errors](/docs/errors) and [Built-in plugins](/docs/plugins) applies to -both. An endpoint is a saved -call, not a contract shared with a server. For that, use Effect's `HttpApi`. +both. An endpoint is a saved call, not a contract shared with a server. For +that, use Effect's `HttpApi`. ## When to use an endpoint @@ -60,24 +113,31 @@ Use an endpoint when a call: ## When to use a method Use a method for one-off calls, and for calls whose method or path is only -known at runtime. Mixing them is normal: keep the client next to its -endpoints, for the calls that aren't worth one. +known at runtime. Mixing the two is normal. Keep the client available next +to its endpoints, for the calls that aren't worth one. ## Patterns to avoid -Avoid the following: +The following patterns compile, but cost you what endpoints are for: - **`api.endpoint(…)(…)` at a call site.** That's a method call written - twice: use the method. + twice. Use the method. - **Making or binding endpoints in code that runs on every request.** Do it - once, when the layer that holds them is built, as `Fetch.Endpoints` does. -- **Passing a bound endpoint's plugin overrides at every call.** A definition - can't hold them, since it doesn't know the client's plugins: give them once, - when binding, as in `api.bind(login, { plugins: { bearer: false } })`. -- **Spreading several groups of endpoints into one object.** When two use the - same name, the later one silently wins. Nest them instead: + once, when the layer that holds them is built, as `Fetch.Endpoints` + does. +- **Passing an endpoint's plugin overrides at every call.** Give them once + instead. A `Fetch.endpoint` definition can't hold them, since + overrides are checked against a client's plugins, so give them when + binding, as in `api.bind(login, { plugins: { bearer: false } })`. An + `api.endpoint` definition can hold them directly. +- **Spreading several groups of endpoints into one object.** When two use + the same name, the later one silently wins. Nest them instead, as in `{ users, todos }`, or give each group its own `Fetch.Endpoints` class. +How an endpoint's headers, overrides and schemas combine with the client's +and the call's is in +[Define endpoints](/docs/endpoints/defining#how-defaults-combine). + ## What's next - [Define endpoints](/docs/endpoints/defining): save a route with its diff --git a/site/content/docs/(latest)/endpoints/services.mdx b/site/content/docs/(latest)/endpoints/services.mdx index 729355d..a28606d 100644 --- a/site/content/docs/(latest)/endpoints/services.mdx +++ b/site/content/docs/(latest)/endpoints/services.mdx @@ -3,15 +3,17 @@ title: Share endpoints as a service description: Bind a record of endpoint definitions to a client once, and share them as an Effect service. --- -This page shows you how to bind your endpoint definitions to a client with -`Fetch.Endpoints`, so code anywhere in your app can call them through one -service. +Your definitions can't make calls until they're bound to a client, and you +want that done once, not in every function that calls them. `Fetch.Endpoints` +binds a record of definitions when its layer is built, and shares the result +as an Effect service, so any code in your app can `yield*` it. This page +shows how to declare one, and what the class gives you. ## Declare the service -`Fetch.Endpoints` binds a record of definitions to a client and shares them as -a service, the way `Fetch.Service` does for the client. It takes the -service's id, the client's service and the record: +`Fetch.Endpoints` does for endpoints what `Fetch.Service` does for the +client. It takes the service's id, the client's service and the record of +definitions: ```ts import * as Effect from "effect/Effect"; @@ -33,7 +35,10 @@ const Credentials = Schema.Struct({ const Session = Schema.Struct({ token: Schema.String }); const getUser = Fetch.endpoint("GET /users/:id", { output: User }); -const listUsers = Fetch.endpoint("GET /users", { output: Schema.Array(User) }); +const listUsers = Fetch.endpoint("GET /users", { + query: Schema.Struct({ page: Schema.optional(Schema.Finite) }), + output: Schema.Array(User), +}); const createUser = Fetch.endpoint("POST /users", { input: NewUser, output: User, @@ -70,6 +75,15 @@ export const AppLayer = UserApi.layer.pipe( ); ``` +Most entries are a definition. An entry can also be a +`[definition, options]` pair, with the options `api.bind` takes: `headers`, +and `plugins` overrides, which are checked against the client's plugins. +Here, `login` turns off the `bearer` plugin, so logging in sends no token +(see [Built-in plugins](/docs/plugins)). + +`Layer.provideMerge` keeps `Api` in the layer's output, so code can still +`yield* Api` for one-off calls. + ## What the class gives you Like `Fetch.Service`, the class gives you three things: @@ -77,25 +91,28 @@ Like `Fetch.Service`, the class gives you three things: - **`UserApi` is the service.** `yield* UserApi` gives the endpoints, each typed with the client's plugins, `defaultError` and `statusErrors`. - **`UserApi.layer` binds them** to the client once, when it's built. It - needs the client's service, here `Api`. The client can also be a service - you wrote by hand. + needs the client's service, here `Api`, and never fails. The client can + also be a service you wrote by hand. - **`UserApi.definitions` is the record you passed**, frozen. You can read - it when the module loads. + it when the module loads, without building anything. -`Layer.provideMerge` keeps `Api` in the layer's output, so code can still -`yield* Api` for one-off calls. +Two things to keep in mind when you declare one: -## Give options that depend on the client +- **Give each class its own id.** The id, `"UserApi"` here, is the + service's identity at run time, as with any Effect service. Two classes + with the same id are the same service. +- **Each entry is checked when the class is declared.** An entry that isn't + a definition or a `[definition, options]` pair throws then, so the mistake + shows up when the module is imported. -A definition doesn't know its client, so the following options depend on -the binding: +## How bound endpoints get the client's defaults -- **Plugin overrides are given when binding,** as in the `login` pair in the - example, where they're checked against the client's plugins. A definition - takes no `plugins`. -- **A definition without an `error` schema** uses the `defaultError` of the - client it's bound to. -- **Headers can be given in both.** The binding's win over the definition's. +Each endpoint is bound to the client, so it picks up what the client +holds. A definition without an `error` schema decodes error bodies with the +client's `defaultError`, and the client's `statusErrors` are tried after +the endpoint's. Headers can come from the definition and from the pair, +and the pair's win. The rules for headers, plugin overrides and schemas are +in [How defaults combine](/docs/endpoints/defining#how-defaults-combine). ## What's next diff --git a/site/content/docs/(latest)/endpoints/typed-query.mdx b/site/content/docs/(latest)/endpoints/typed-query.mdx index 72a9158..557f3fb 100644 --- a/site/content/docs/(latest)/endpoints/typed-query.mdx +++ b/site/content/docs/(latest)/endpoints/typed-query.mdx @@ -3,14 +3,17 @@ title: Typed query parameters description: Give an endpoint a schema that types each call's query and encodes it before it's sent. --- -This page shows you how to give an endpoint a `query` schema, how each field -is encoded into the URL, and what happens when a query doesn't match. +A plain `query` object isn't checked, so a misspelled filter compiles, and +a value such as a `Date` has to be converted by hand. Give the +endpoint a `query` schema instead, and each call's query is typed by the +schema and encoded with it before it's sent. This page shows how to add +one, how each field is encoded, and what happens when a query doesn't +match. ## Add a query schema -Give an endpoint a `query` schema, usually a `Schema.Struct`, and each call's -`query` is typed by it and encoded with it before it's sent. A `Schema.Class` -works too, called with an instance: +The following endpoint types its filters, sends a `Date` as an ISO string, +and renames `pageSize` to `page_size` in the URL: ```ts import * as Effect from "effect/Effect"; @@ -45,36 +48,54 @@ export const program = Effect.gen(function* () { }); ``` -The schema is the endpoint's `query` property. `client.bind`, -`client.bindAll` and `Fetch.Endpoints` keep it, and `api.endpoint` takes one -too. +A query schema is usually a `Schema.Struct`, as here. A `Schema.Class` +works too, and then each call's `query` is an instance of the class. + +Every field in `TodoFilters` is optional, so `query` is optional too, and +`list()` sends `GET /todos`. When the schema has a required field, every +call has to pass `query`, and TypeScript says so. + +The schema is the endpoint's `query` property. `api.bind`, `api.bindAll` +and `Fetch.Endpoints` keep it, and `api.endpoint` takes one too. ## How each field is encoded -The schema encodes the query as follows: +The schema encodes each field to a string, as Effect's +`Schema.toCodecStringTree` does: -- Each field is encoded to a string: a `Date` to its ISO string, a boolean to - `"true"` or `"false"`, a number to its digits. An array repeats the key. +- A `Date` becomes its ISO string, and a boolean `"true"` or `"false"`. A + number is written as `String()` writes it, such as `20` or `0.5`. +- An array repeats the key, as in `tag=work&tag=home`. - Rename keys with `Schema.encodeKeys`, as in the example. -- A field you leave out isn't sent, but a `null` is sent as the string - `"null"`, so prefer optional fields to nullable ones. -- A `Schema.Redacted` field is sent as its value and, with Effect 4.1 or - later, stays redacted in Effect's logs and traces. +- A field you leave out isn't sent. A `null` is sent as the string `"null"`, + unlike in a plain query, where it's left out. So prefer optional fields + to nullable ones. +- A `Schema.Redacted` field is sent as its value. With Effect 4.1 or later, + it stays redacted in Effect's logs and traces. + +A schema whose encoding needs a service adds that service to the call's +requirements, the way an `input` schema's does. Provide it where you run +the call. Such an endpoint's `url` can't be called, since `url` encodes +synchronously (see [Build an endpoint's URL](/docs/endpoints/urls)). ## Queries that don't match -A query or a schema that can't be encoded fails early: +A schema or a query that can't be encoded fails early, at one of two +points: -- A query that doesn't match the schema, or a field that encodes to an - object, is a bug, not an error to handle: the call dies before anything is - sent. See [Logging and defects](/docs/errors/logging-and-defects). -- A schema with a field that has no string encoding, such as - `Schema.instanceOf(Uint8Array)`, throws when the endpoint is defined. +- **When the endpoint is defined.** A schema with a field that has no + string encoding, such as `Schema.instanceOf(Uint8Array)`, throws there, + so the mistake shows up when the module is imported. +- **When the call runs.** A query that doesn't match the schema, or a field + that encodes to an object, is a bug, not an error to handle. The call + dies before anything is sent, with an `Error` whose message starts with + `Invalid query:`. See + [Logging and defects](/docs/errors/logging-and-defects). ## What's next - [Build an endpoint's URL](/docs/endpoints/urls): get the URL, query included, without sending a request. - [Call an endpoint](/docs/endpoints/calling): see everything a call takes. -- [Path and query parameters](/docs/calls/parameters): send a query from a - method call. +- [Make a call](/docs/calls#build-a-query-string): send a plain query from + a method call. diff --git a/site/content/docs/(latest)/endpoints/urls.mdx b/site/content/docs/(latest)/endpoints/urls.mdx index 2243725..28abd26 100644 --- a/site/content/docs/(latest)/endpoints/urls.mdx +++ b/site/content/docs/(latest)/endpoints/urls.mdx @@ -3,13 +3,15 @@ title: Build an endpoint's URL description: Get the URL a call to an endpoint would go to, without sending a request. --- -This page shows you how to get the URL an endpoint call would go to, as a -string, for a link, an `` source, or a cache key. +Sometimes you need the URL of a call rather than its response: for a link, +an `` source, a download or a cache key. Writing it by hand repeats the +path, and can drift from what the call sends. This page shows how to get +the URL from the endpoint itself, built the same way the call builds it. ## Get the URL -`endpoint.url(options)` returns the URL a call with the same `params` and -`query` would go to. It works on a definition and on a bound endpoint: +`endpoint.url(options)` returns the URL that a call with the same `params` +and `query` would go to. It works on a definition and on a bound endpoint: ```ts import * as Effect from "effect/Effect"; @@ -41,23 +43,40 @@ export const link = Effect.gen(function* () { }); ``` +`url` takes `params` and `query` as a call does, and TypeScript checks them +the same way. When neither is required, you can call it with no arguments. + ## What the URL contains -The URL contains the following: +Where the URL starts depends on what you call `url` on: + +- **On a bound endpoint,** the URL starts with the client's `baseUrl`. When + the client has no `baseUrl`, it's relative, as in `/files/report.pdf`. +- **On a definition from `Fetch.endpoint`,** which has no client, it's the + path alone, unless the route is a full URL. That makes it a stable cache + key for one backend, whichever client calls it. +- **For a route written as a full URL,** such as + `"GET https://cdn.example.com/files/:name"`, it's that URL in both cases. -- On a bound endpoint, the URL starts with the client's `baseUrl`. -- On a definition from `Fetch.endpoint`, which has no client, it's the path - alone, unless the route is a full URL. That makes it a stable cache key - for one backend, whichever client calls it. -- The URL is built before plugins run, so anything a plugin adds, such as a - token in the query, isn't in it. +The URL is built before plugins run, so anything a plugin adds, such as a +token in the query, isn't in it. ## When url throws -`url` throws when a path parameter is missing or the query doesn't match the -schema, as a call would die. It encodes the query synchronously, so on an -endpoint whose query schema needs services to encode, calling it doesn't -compile. +`url` runs synchronously and returns a string, so where a call would die, +`url` throws instead. It throws when: + +- a path parameter is missing; +- the query doesn't match the endpoint's `query` schema, or a field encodes + to an object; +- the URL can't be built from the base URL and the path. + +An endpoint whose query schema needs a service to encode can't be encoded +synchronously, so calling its `url` doesn't compile. + +`url` builds the URL with Effect's URL helpers, as each call does, and they +use the platform's `URL`. On React Native without Expo, that needs a +polyfill (see [Platform notes](/docs/platforms#react-native)). ## What's next diff --git a/site/content/docs/(latest)/errors/catching.mdx b/site/content/docs/(latest)/errors/catching.mdx index 471b175..c3bb3df 100644 --- a/site/content/docs/(latest)/errors/catching.mdx +++ b/site/content/docs/(latest)/errors/catching.mdx @@ -1,10 +1,14 @@ --- title: Catch errors -description: Handle an error by its tag, or one status. +description: Handle an error by its tag or its status, and read the API's error body. --- -This page shows how to handle a call's errors: by their tag, or by the -response's status. For the errors themselves, see +When a call fails, you usually want to do something specific: show "You're +offline" for a network error, treat a 404 as "nothing there", or show the +message the API sent back. Effetch's errors are tagged, so you can pick out +each one by name and leave the rest for code further up. This page shows how +to catch errors by tag, read the body the API sent with an error, and handle +one status at a time. For the errors themselves, see [Call errors](/docs/errors). ## Catch errors by tag @@ -37,18 +41,94 @@ export const todo = (id: number) => Each handler gets the error with its fields. You don't have to handle them all: the ones you leave out stay in the type, for code further up to handle. -For a single error, `Effect.catchTag` does the same. +To catch a single error, use `Effect.catchTag`. -`Fetch.FetchError` is the union of the three errors, and `Fetch.isFetchError` -tells them apart from other values. +For your own helpers, `Fetch.FetchError` is the union of the three errors, +and `Fetch.isFetchError` tells them apart from other values. -## Catch a status +## Read the error body + +APIs usually explain an error in its body, such as +`{ "code": "not_found" }`. Give Effetch a schema for that body, and +`HttpError.body` is decoded and typed. You can set the schema in two places: -To handle one or more statuses, use `Fetch.catchStatus`. For the common "a -404 means there's nothing there", `Fetch.optional` succeeds with -`Option.none()` on a 404 and `Option.some(value)` otherwise. +- `defaultError`, on the client, applies to every call. +- `error`, on a call or an [endpoint](/docs/endpoints), replaces it for that + call. -The following example uses both: +The following client sets `defaultError`, and one call replaces it with a +schema of its own: + +```ts +import * as Effect from "effect/Effect"; +import * as Schema from "effect/Schema"; + +import { Fetch } from "@monarcode/effetch"; + +const Todo = Schema.Struct({ id: Schema.Finite, title: Schema.String }); + +// Most errors: { "code": "not_found" } +const ApiError = Schema.Struct({ code: Schema.String }); +// Errors from POST /todos: { "code": "invalid", "fields": ["title"] } +const ValidationError = Schema.Struct({ + code: Schema.String, + fields: Schema.Array(Schema.String), +}); + +class Api extends Fetch.Service()("Api", { + baseUrl: "https://api.example.com", + defaultError: ApiError, +}) {} + +export const program = Effect.gen(function* () { + const api = yield* Api; + + // error.body is { code } | undefined, from defaultError + const todo = yield* api + .get("/todos/1", { output: Todo }) + .pipe( + Effect.catchTag("HttpError", (error) => + Effect.succeed(`Failed: ${error.body?.code ?? error.status}`), + ), + ); + + // error.body is { code, fields } | undefined, from error + const created = yield* api + .post("/todos", { + body: { title: "" }, + output: Todo, + error: ValidationError, + }) + .pipe( + Effect.catchTag("HttpError", (error) => + Effect.succeed(`Check ${error.body?.fields.join(", ") ?? "the form"}`), + ), + ); + + return { todo, created }; +}); +``` + +`body` is typed as your schema or `undefined`, because the server doesn't +always send what the schema expects: + +- With a schema, `body` is the decoded body, or `undefined` when it doesn't + match. +- Without one, `body` is the parsed JSON, typed `unknown`. +- With or without one, `body` is `undefined` when the response body is empty + or isn't JSON. + +Reading the body never fails the call: you always get the `HttpError`. The +raw body is always on `text`, or `""` if it couldn't be read. + +For your own function signatures, `Fetch.HttpError.With` is the type of an +`HttpError` whose `body` is `B | undefined`. + +## Catch a status + +That covers errors by tag. Often, though, you care about one status rather +than every `HttpError`. For that, use `Fetch.catchStatus`, or `Fetch.optional` +for the common "a 404 means there's nothing there": ```ts import * as Effect from "effect/Effect"; @@ -74,25 +154,35 @@ export const me = api ); ``` -Keep the following in mind when you catch a status: +`Fetch.optional` succeeds with `Option.some(value)` when the call succeeds, +and with `Option.none()` on a 404. Every other error, other statuses +included, passes through. + +`Fetch.catchStatus` takes one status or a list. Keep the following in mind +when you use it: - The handler gets the `HttpError`, with `status` narrowed to the statuses you gave, and what it returns joins the call's type. - `HttpError` stays in the error type, since other statuses still fail with it. -- Both work on endpoint calls too, and `catchStatus` also takes the effect - first: `Fetch.catchStatus(effect, 404, handler)`. -- A status that [`statusErrors`](/docs/errors/status-errors) maps fails with - your error, not an `HttpError`, so `catchStatus` and `optional` never see - it. Catch your error by its tag instead. -- The handler's `error.body` is `unknown`. For the typed body of an `error` - schema, use `Effect.catchTag("HttpError", …)`. +- The handler's `error.body` is `unknown`. For the body typed by an `error` + schema, use `Effect.catchTag("HttpError", …)` and check `error.status` + yourself. +- Both work on endpoint calls too, and on any Effect whose errors include + `HttpError`. `catchStatus` also takes the effect first: + `Fetch.catchStatus(effect, 404, handler)`. + +A status that [`statusErrors`](/docs/errors/status-errors) maps fails with +your error, not an `HttpError`, so `catchStatus` and `optional` don't get it. +Catch your error by its tag instead. That only holds when the body decodes +with your schema, though: a mapped status whose body is empty or doesn't +match still fails with an `HttpError`, which `catchStatus` does catch. ## What's next -- [Typed error bodies](/docs/errors/error-bodies): type `error.body` with a - schema. - [Errors by status](/docs/errors/status-errors): fail with your own error for a status, and catch it by its tag. -- [Test errors and statuses](/docs/testing/errors): check your handlers against a fake - backend. +- [Client configuration](/docs/clients/configuration): set `defaultError` + with the client's other options. +- [Test errors and statuses](/docs/testing/errors): check your handlers + against a fake backend. diff --git a/site/content/docs/(latest)/errors/error-bodies.mdx b/site/content/docs/(latest)/errors/error-bodies.mdx deleted file mode 100644 index 7a18c95..0000000 --- a/site/content/docs/(latest)/errors/error-bodies.mdx +++ /dev/null @@ -1,33 +0,0 @@ ---- -title: Typed error bodies -description: Decode the API's error body with a schema. ---- - -APIs usually explain an error in its body, such as -`{ "code": "not_found" }`. This page shows how to give Effetch a schema for -that body, so that `HttpError.body` is decoded and typed. - -## Give a schema for the error body - -You can set the schema in two places: - -- `defaultError`, on the client, applies to every call; -- `error`, on a call or an [endpoint](/docs/endpoints), replaces it. - -## Read the body - -`body` is the decoded body, or `undefined` if it didn't match the schema. -Without a schema, it's the parsed JSON. Reading it never fails the call, and -the raw body is always on `text`. - -`Fetch.HttpError.With` is the type of an `HttpError` whose `body` is `B`, -for your own function signatures. - -## What's next - -- [Catch errors](/docs/errors/catching): read the typed body in an - `HttpError` handler. -- [Errors by status](/docs/errors/status-errors): turn a status and its body - into your own error. -- [Client configuration](/docs/clients/configuration): set `defaultError` with the - client's other options. diff --git a/site/content/docs/(latest)/errors/index.mdx b/site/content/docs/(latest)/errors/index.mdx index 4956e3b..f6dd985 100644 --- a/site/content/docs/(latest)/errors/index.mdx +++ b/site/content/docs/(latest)/errors/index.mdx @@ -3,37 +3,98 @@ title: Call errors description: Learn what a call can fail with and how each error is typed. --- -Every call's type lists the ways it can fail, so TypeScript knows which -errors you've handled and which are left. This page describes those errors. -The other pages in this section show how to catch them and how to turn the -API's error responses into errors of your own. +A request can go wrong in more ways than one. The network can drop, the +server can answer with a 404, or the body can come back in a shape you +didn't expect. With Effetch, each of these is a separate tagged error, and +every call's type lists the ones it can fail with. TypeScript then tracks +which errors you've handled and which are left. -## What can go wrong +This page describes those errors and how they fit together. The rest of the +section shows how to catch them, read the API's error body, and turn error +statuses into errors of your own. -A call can fail in three ways, each with its own tagged error. Plugins can add -their own, such as `timeout`'s `TimeoutError`, and -[`statusErrors`](/docs/errors/status-errors) can turn an `HttpError` into one -of your own. +## How a call fails -The following table lists each error, when it happens and the fields it -carries: +A call fails with one of three errors, each with its own `_tag`: -| Error | When | Fields | -| ----------------------- | ---------------------------------------------------------------------------------- | ---------------------------------------------------- | -| `NetworkError` | No response: offline, DNS failure, connection refused, CORS rejection. | `method`, `url`, `cause` | -| `HttpError` | A response outside 200–299 (3xx included). | `method`, `url`, `status`, `headers`, `text`, `body` | -| `DecodeError` | A 2xx body that isn't JSON or doesn't match `output`. Only on calls with `output`. | `method`, `url`, `status`, `issue`, `message` | -| `TimeoutError` (plugin) | The `timeout` plugin's limit passed before the response arrived. | `method`, `url`, `duration` | +- **`NetworkError`:** the request got no response at all. +- **`HttpError`:** the server answered, but with a status outside 200–299. +- **`DecodeError`:** the server answered with a 2xx, but its body couldn't + be read or decoded. -## Error pages +Here's how they show up in a call's type: -The rest of this section covers each part of handling errors: +```ts +import * as Schema from "effect/Schema"; -- [Catch errors](/docs/errors/catching): handle an error by its tag, or one - status. -- [Typed error bodies](/docs/errors/error-bodies): decode the API's error - body with a schema. +import type { Fetch } from "@monarcode/effetch"; + +declare const api: Fetch.Client; + +const Todo = Schema.Struct({ id: Schema.Finite, title: Schema.String }); + +// Fails with NetworkError, HttpError or DecodeError +export const todo = api.get("/todos/:id", { + params: { id: 1 }, + output: Todo, +}); +``` + +Two things can add to that list: + +- **Plugins.** A plugin can fail a call with an error of its own, such as + the `timeout` plugin's `TimeoutError`, and that error joins the call's + type. +- **Your own errors.** With [`statusErrors`](/docs/errors/status-errors), + an error status becomes an error you define, such as a 404 that fails with + `TodoNotFound`. + +## The errors and their fields + +Every error carries the request's `method` and `url`, so a log line says +which call failed. The following table lists when each error happens and +the fields it carries: + +| Error | When | Fields | +| ----------------------- | ---------------------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------- | +| `NetworkError` | No response: offline, DNS failure, connection refused, CORS rejection. | `method`, `url`, `cause` | +| `HttpError` | A response outside 200–299, 3xx included. | `method`, `url`, `status`, `headers`, `text`, `body` | +| `DecodeError` | A 2xx body that couldn't be read, isn't JSON or doesn't match `output`, on a call with `output`. Or a stream that fails while it's read. | `method`, `url`, `status`, `issue`, `message` | +| `TimeoutError` (plugin) | The `timeout` plugin's limit passed before the response arrived, or the `retry` plugin's `budget` ran out during an attempt. | `method`, `url`, `duration` | + +A stream (`api.sse`, `api.ndjson` or a stream endpoint) fails with +`DecodeError` with or without `output`: when a value doesn't decode, when +the body breaks off, or when an SSE response's `Content-Type` isn't +`text/event-stream`. For how a stream reads its body, see +[Streaming responses](/docs/streaming). + +A few of these fields are worth knowing before you handle them: + +- `url` is the request URL without its query string, so a token in the + query doesn't end up in your logs. +- `HttpError.text` is the raw body, and `body` is that body decoded. See + [Read the error body](/docs/errors/catching#read-the-error-body). +- `DecodeError.message` is a readable summary of what went wrong, and + `issue` holds the schema issue, the JSON `SyntaxError` or the read error + behind it. + +## Errors and defects + +The errors in the table are things your app can recover from: show a +message, retry, or fall back to a cached value. A mistake in your own code, +such as a missing path parameter, is different. It makes the Effect die as +a defect (a failure that isn't in the error type, which you don't catch in +normal code), so the bug surfaces instead of passing as an `HttpError`. +[Logging and defects](/docs/errors/logging-and-defects) lists those +mistakes. + +## What's next + +- [Catch errors](/docs/errors/catching): handle an error by its tag or its + status, and read the API's error body. - [Errors by status](/docs/errors/status-errors): turn an error status into your own domain error. -- [Logging and defects](/docs/errors/logging-and-defects): what errors keep - out of logs, and which mistakes are defects rather than errors. +- [Logging and defects](/docs/errors/logging-and-defects): see what stays + out of logged errors, and which mistakes are defects. +- [Test errors and statuses](/docs/testing/errors): make a fake backend + fail, to test your handlers. diff --git a/site/content/docs/(latest)/errors/logging-and-defects.mdx b/site/content/docs/(latest)/errors/logging-and-defects.mdx index 772e0f1..f7ab993 100644 --- a/site/content/docs/(latest)/errors/logging-and-defects.mdx +++ b/site/content/docs/(latest)/errors/logging-and-defects.mdx @@ -1,33 +1,104 @@ --- title: Logging and defects -description: Learn which errors are safe to log, and why bugs are defects rather than errors. +description: Learn what stays out of a logged error, and why bugs are defects rather than errors. --- -This page explains what Effetch keeps out of its errors so you can log them, -and which mistakes make a call die as a defect instead of failing with a -typed error. +When a call fails in production, its error usually ends up in a log or an +error reporter. Before you send it there, check what the error carries: +Effetch keeps some secrets out for you, but not all of them. Some mistakes +don't produce an error at all: they're bugs in your code, and the Effect +dies instead. This page covers both. -## Errors that are safe to log +## What a logged error keeps out -Errors are made to be logged and reported: +Effetch's errors are made to be logged and reported. Two things are kept out +of them: -- `url` never includes the query string, so tokens in queries stay out of - logs. -- `HttpError.headers` are Effect `Headers`: `authorization`, `set-cookie` and - other sensitive headers print as ``. +- **The query string.** `url` is the request URL without its query string + or fragment, so a token in `?api_key=…` stays out of logs. +- **Sensitive headers.** `HttpError.headers` are Effect `Headers`, which + print sensitive values as `` when the error is logged or turned + into JSON. + +By default, Effect redacts these headers: + +- `authorization` +- `cookie` +- `set-cookie` +- `x-api-key` + +To change the list, provide `Headers.CurrentRedactedNames` with your own +names or regular expressions. Your list replaces the defaults, so include +them again if you still want them redacted: + +```ts +import * as Effect from "effect/Effect"; +import * as Headers from "effect/http/Headers"; + +declare const program: Effect.Effect; + +export const main = program.pipe( + Effect.provideService(Headers.CurrentRedactedNames, [ + "authorization", + "cookie", + "set-cookie", + "x-api-key", + /^x-session-/, + ]), +); +``` + +Effect reads the list when the error is printed. A log written with +`Effect.logError` inside the provided Effect uses your list. An error +printed outside any Effect, such as with `console.log` after +`Effect.runPromise`, uses the defaults. +Redaction only changes how headers print: `error.headers["set-cookie"]` in +your code still gives you the value. + +### What isn't scrubbed + +Effetch doesn't scrub anything else, so check these before you log an error +somewhere that others can read: + +- **`HttpError.text` and `body`** hold the response body in full. If the API + echoes a password or a token in an error, it's in there. +- **`NetworkError.cause`** is the platform's error, as it is. +- **`DecodeError.issue`** is the schema issue, the JSON `SyntaxError` or the + read error, as it is. + +To keep bodies and queries out of the logs the client writes for you, see +[Console logging](/docs/plugins/console-logging). ## Bugs as defects -Some mistakes are bugs in the calling code, not failures to recover from at -runtime. Those make the Effect die, as a defect, rather than fail with a typed -error: +That covers errors you'll log. Some mistakes, though, are bugs in the calling +code, not failures to recover from at runtime. Those make the Effect die, as +a defect, rather than fail with a typed error. A defect isn't in the error +type, so `catchTag` doesn't catch it, and it surfaces as a bug instead of +passing as an `HttpError`. + +A call dies when it has one of these mistakes: - a missing path parameter; - a body that can't be encoded; - a query that doesn't match an endpoint's `query` schema; - a body on a `GET` or `HEAD` request; -- a `baseUrl` with a query string; -- two plugins with the same name; -- a relative URL without a `baseUrl`, outside browsers. +- a relative URL without a `baseUrl`, outside browsers; +- on a stream call, a `responseMode`, or an `output` made by `Fetch.bytes()`. + A stream endpoint with the same mistake throws earlier, when it's + defined. + +Two mistakes in the client's configuration make building the client die, +before any call runs. That happens in `Fetch.make`, or when the client's +layer is built: + +- a `baseUrl` with a query string or a fragment; +- two plugins with the same name. + +## What's next -For the errors a call can fail with, see [Call errors](/docs/errors). +- [Call errors](/docs/errors): see each error a call can fail with, and its + fields. +- [Console logging](/docs/plugins/console-logging): log each call, with + bodies and queries redacted. +- [Catch errors](/docs/errors/catching): handle the errors you've logged. diff --git a/site/content/docs/(latest)/errors/meta.json b/site/content/docs/(latest)/errors/meta.json index 2b5d495..a71bf05 100644 --- a/site/content/docs/(latest)/errors/meta.json +++ b/site/content/docs/(latest)/errors/meta.json @@ -1,10 +1,4 @@ { "title": "Errors", - "pages": [ - "index", - "catching", - "error-bodies", - "status-errors", - "logging-and-defects" - ] + "pages": ["index", "catching", "status-errors", "logging-and-defects"] } diff --git a/site/content/docs/(latest)/errors/status-errors.mdx b/site/content/docs/(latest)/errors/status-errors.mdx index 49ee839..73dc988 100644 --- a/site/content/docs/(latest)/errors/status-errors.mdx +++ b/site/content/docs/(latest)/errors/status-errors.mdx @@ -3,26 +3,21 @@ title: Errors by status description: Turn an error status into your own domain error. --- -Often a status, or a status with a given body, means a specific error in -your app: a 404 from `GET /todos/:id` is "todo not found", a 400 with -`"code": "INVALID_ROLE"` is "invalid role", a 401 from anywhere is "session -expired". `statusErrors` maps statuses to your own error schemas, and the -call fails with your error instead of an `HttpError`. This page shows how to -set up those maps and how Effetch picks the error for a response. - -## Choose where a map applies - -You can give a map in three places, and they add up: - -- on the client, for every call, such as a `401` from anywhere; -- on an [endpoint](/docs/endpoints), for every call to it, which is where most - of them live; -- on a single call. +An error status often means something specific in your app. A 404 from +`GET /todos/:id` means "todo not found", a 400 with +`"code": "INVALID_ROLE"` means "invalid role", and a 401 with a message +from any endpoint means "session expired". Catching each of these as an +`HttpError` and checking its status at every call gets repetitive. +`statusErrors` maps statuses to error schemas of your own, so the call fails +with your error instead of an `HttpError`, and the error's tag says what +went wrong. This page shows how to set up those maps, and how Effetch picks +the error for a response. ## Map statuses to your errors -The following program gives a map in all three places, then catches the -errors by their tags: +A map's keys are statuses, and each value is an error schema, or a list of +them to try in order. The following program gives a map on the client, on +an endpoint and on one call, then catches the errors by their tags: ```ts import * as Effect from "effect/Effect"; @@ -93,18 +88,33 @@ export const program = Effect.gen(function* () { Before the `catchTags`, the role call fails with `InvalidRole | RoleTaken | SessionExpired | HttpError.With<{ readonly code: string }> | NetworkError | DecodeError`. -`HttpError` stays: a response can always fail to match. +`HttpError` stays in the type, because a response can always fail to match +your schemas. + +## Choose where a map applies + +As the program shows, you can give a map in three places, and they add up: + +- **On the client,** for every call, such as a 401 from anywhere. +- **On an [endpoint](/docs/endpoints),** for every call to it. Most maps live + here, next to the route they describe. +- **On a single client call,** such as `api.get` or `api.post`. + +An endpoint call takes no map of its own. It uses the endpoint's map and the +client's, so to add a status for one endpoint, put it on the endpoint's +definition. ## How a response is resolved -Effetch resolves a non-2xx response in the following order: +When a response comes back with a non-2xx status, Effetch picks the error in +the following order: 1. If the body is empty or isn't JSON, it's an `HttpError`. -2. Otherwise the schemas listed for its status are tried in order: the - call's, then the endpoint's, then the client's. The first one that - decodes the body is the error. -3. If none does, it's the `HttpError` you'd get without `statusErrors`, its - `body` decoded with `error` or `defaultError`. +2. Otherwise, the schemas listed for its status are tried in order: the + call's or the endpoint's, then the client's. The first one that decodes + the body is the error. +3. If none does, it's the `HttpError` you'd get without `statusErrors`, with + its `body` decoded by `error` or `defaultError`. With the maps from the program in [Map statuses to your errors](#map-statuses-to-your-errors), responses fail @@ -116,9 +126,16 @@ as follows: | 400 `{ "code": "ROLE_TAKEN", "message": "…" }` | `RoleTaken` | | 400 `{ "code": "MISSING_FIELD" }` | `HttpError` with `body.code` | | 400 with an empty or non-JSON body | `HttpError` | -| 401 from any endpoint | `SessionExpired` | +| 401 `{ "message": "…" }` from any endpoint | `SessionExpired` | +| 401 with an empty body | `HttpError` | | 500 | `HttpError` | +The empty 401 is the case to watch for. Some servers send a 401 or a 404 +with no body at all, and `statusErrors` can't map a body that isn't there. +For a status whose body may be empty, catch the `HttpError` with +[`Fetch.catchStatus`](/docs/errors/catching#catch-a-status), alongside your +error's tag. + @@ -129,25 +146,36 @@ as follows: `Schema.encodeKeys`: `InvalidRole.pipe(Schema.encodeKeys({ code: "error_code" }))`. - **Lists, not unions.** A `Schema.Union` is decoded as it is, without a - `_tag`: list its members instead. -- **2xx entries never apply**, since a 2xx is decoded with `output`. -- Plugins see the response before any of this, so `retry` still retries by - status. `onError` receives your error, and `api.httpClient` stays raw. -- Maps are copied when they're given, so changing one afterwards changes + `_tag`, so list its members instead. +- **2xx entries never apply,** since a 2xx is decoded with `output`. +- **Plugins get the response first.** They run before any of this, so + `retry` still retries by status. `onError` receives your error, and + `api.httpClient` stays raw. +- **Maps are copied when they're given,** so changing one afterwards changes nothing. `api.statusErrors` and a `Fetch.endpoint` definition's - `statusErrors` are those copies, frozen; an endpoint's `statusErrors` - joins its own with the client's, each status listing its schemas in the - order they're tried. -- `Fetch.StatusError` is the union of the errors in a map `M`, and - `Fetch.StatusErrorSchema` the union of its schemas, for your own + `statusErrors` are those copies, frozen. An endpoint made with + `api.endpoint` or `api.bind` has `statusErrors` that join its own with the + client's, each status listing its schemas in the order they're tried. +- **Types.** `Fetch.StatusError` is the union of the errors in a map `M`, + and `Fetch.StatusErrorSchema` the union of its schemas, for your own function signatures. -- A client's type includes its map: `Fetch.Client`. A client - with a map can't be passed where a plain `Fetch.Client` is expected, - since that would hide its errors. +- **A client's type includes its map:** `Fetch.Client`. A client + with a map can't be passed where a plain `Fetch.Client` is expected, since + that would hide its errors. +## Test a map + +To check that a status turns into your error, make a fake backend answer +with it. `FetchTest.fail(getTodo, 401, new SessionExpired({ message: "…" }))` +sends the error as JSON, and the client decodes it back into +`SessionExpired`. When the endpoint has no `error` or `statusErrors` schema +of its own, this works with a map that's only on the client, so you don't +need to repeat it on the endpoint. See +[Test errors and statuses](/docs/testing/errors). + ## See it in a full program [`examples/status-errors.ts`](https://github.com/monarcode/effetch/blob/main/examples/status-errors.ts) @@ -161,5 +189,5 @@ uses it across modules. you didn't map. - [Define endpoints](/docs/endpoints/defining): put each endpoint's `statusErrors` on its definition. -- [Test errors and statuses](/docs/testing/errors): make a fake backend answer with an - error status. +- [Test errors and statuses](/docs/testing/errors): make a fake backend + answer with an error status. diff --git a/site/content/docs/(latest)/examples.mdx b/site/content/docs/(latest)/examples.mdx index 07f35cc..ba6ba23 100644 --- a/site/content/docs/(latest)/examples.mdx +++ b/site/content/docs/(latest)/examples.mdx @@ -3,10 +3,15 @@ title: Examples description: Find a complete program that uses Effetch, typechecked with the package. --- -The repository's -[`examples/`](https://github.com/monarcode/effetch/tree/main/examples) folder -has complete programs, typechecked with the package so they always match the -current API. Use them to see a whole feature in context. +The guides show one feature at a time. When you want to see several of them +working together in a whole program, look in the repository's +[`examples/`](https://github.com/monarcode/effetch/tree/main/examples) +folder. + +The examples are typechecked with the package on the `main` branch, which +can be ahead of the latest release. To read them as they were at your +version, switch GitHub's branch menu to that release's tag, such as +`v0.1.0-rc.4`. The folder has these programs: @@ -34,4 +39,11 @@ The folder has these programs: The examples' [README](https://github.com/monarcode/effetch/blob/main/examples/README.md) -walks through each one. +walks through each one, and explains how `app/` is laid out. + +## What's next + +- [Structure an app](/docs/structuring-an-app): see the layout that `app/` + follows, and when to use it. +- [Test with a fake backend](/docs/testing): write tests like the ones in + `testing.ts`. diff --git a/site/content/docs/(latest)/getting-started.mdx b/site/content/docs/(latest)/getting-started.mdx index e198a13..e95dc8c 100644 --- a/site/content/docs/(latest)/getting-started.mdx +++ b/site/content/docs/(latest)/getting-started.mdx @@ -1,22 +1,30 @@ --- title: Getting started -description: Declare a client, make a typed call and run it, from an empty file to a working program. +description: Write a program that makes a typed call, run it and see what each part does. --- -In this tutorial, you write a complete program that fetches a todo from an -API, typed and checked by a schema. Along the way, you meet the four ideas -the rest of Effetch builds on. +The quickest way to see how Effetch works is to run a small program. In this +tutorial, you write one that fetches a todo from a public API, checks it +against a schema and prints its title. Then you go through it part by part, +so you know what each line does before you write your own calls. ## Before you begin -Install Effetch and Effect, and check that your project meets the -requirements. For the commands, see [Installation](/docs/installation). +To follow this tutorial, you need the following: -## Write your first client +- Effetch and Effect, installed in an ESM project, as + [Installation](/docs/installation) shows; +- Node.js 24, to run the program as it is, since it runs TypeScript files + without a build step. On another runtime, the run step names a command + that works there. -The following program fetches a todo from -[JSONPlaceholder](https://jsonplaceholder.typicode.com), a free fake API. -It's complete, so you can run it as it is: +## Write and run the program + +The program calls [JSONPlaceholder](https://jsonplaceholder.typicode.com), a +free fake API, so it needs no account or key. + +1. In your project, create a file named `main.ts`, with the following + program: ```ts import * as Effect from "effect/Effect"; @@ -54,71 +62,113 @@ const ApiLive = Api.layer.pipe(Layer.provide(FetchHttpClient.layer)); await Effect.runPromise(program.pipe(Effect.provide(ApiLive))); ``` +2. Run the program with the following command: + + ```bash + node main.ts + ``` + + On another version of Node.js, run `npx tsx main.ts` instead. With Bun, + run `bun main.ts`. + +3. Check the output. The program prints the title of todo 1: + + ```text + delectus aut autem + ``` + +If you see that line, the call worked: Effetch sent the request, checked +the response against `Todo` and gave you a typed value. + ## What each part does The numbered comments in the program mark its four parts: -1. **`Todo` describes the response.** Effetch decodes the body with it, so - `todo` is typed, and checked when it arrives. If the API sends something - else, the call fails with a `DecodeError` instead of handing you bad data. +1. **`Todo` describes the response.** It's a schema (a description of a + value's shape, from Effect's `Schema` module), and Effetch decodes the + body with it. That's why `todo` is typed, and why it's checked when it + arrives. If the API sends something else, the call fails with a + `DecodeError`, rather than handing you bad data. 2. **`Api` is your client.** `Fetch.Service` declares it as an Effect - service, with everything its calls have in common: here the base URL, - later the headers, error schemas and plugins. + service: a value your program asks for by name, and gets from a layer + when it runs. The client holds what all its calls have in common. Here + that's the base URL. Later, it can also hold headers, error schemas and + plugins. 3. **`api.get` makes the call.** `yield* Api` gives you the client, and the - `:id` in the path is filled in from `params`. -4. **`Api.layer` builds the client.** It needs an `HttpClient` to send the - requests. `FetchHttpClient.layer` uses the global `fetch`. Node's works - too, and in tests you'd use a fake one (see + `:id` in the path is filled in from `params`. The call is an Effect, so + nothing is sent until the program runs. +4. **`Api.layer` builds the client.** A layer is a recipe for building a + service, and this one needs an `HttpClient` to send the requests. + `FetchHttpClient.layer` sends them with the global `fetch`. Any other + `HttpClient` layer works too, such as a fake backend in tests (see [Test with a fake backend](/docs/testing)). - Calling an API from a web page on another origin? Read the browser notes in - [Platform notes](/docs/platforms) first. + If your program runs in a web page and calls an API on another origin, read + [Browsers](/docs/platforms#browsers) first. Effect adds tracing headers to + each request, and the browser blocks the call when the API doesn't allow them. ## How the pieces fit -Everything in Effetch builds on four ideas, from the bottom up: +Effetch has four building blocks. The program used the first three, and the +fourth is plugins. From the bottom up: -- **An `HttpClient`** sends requests. It's Effect's, and you choose it when - you run your program: the global `fetch`, Node's, or a fake in tests. -- **A client** is one backend: its base URL, default headers, error schemas - and plugins. You declare it once, with `Fetch.Service`. +- **An `HttpClient`** sends the requests. It comes from Effect, and you pick + it when you run your program: the global `fetch`, another `HttpClient` + layer, or a fake one in tests. +- **A client** stands for one backend, with its base URL, default headers, + error schemas and plugins. You declare it once, with `Fetch.Service`. - **A call** is one request: a method such as `api.get`, or an [endpoint](/docs/endpoints) you saved. It returns an Effect, typed by your schemas, that fails with typed errors. -- **Plugins** wrap every call a client makes, for auth, retries, timeouts - and logging. - -The sidebar follows the same order: -[clients](/docs/clients), [calls](/docs/calls) and -[errors](/docs/errors), then [plugins](/docs/plugins), including -[your own](/docs/plugins/writing), and [endpoints](/docs/endpoints). After -those come [streams](/docs/streaming), [pagination](/docs/pagination), -[how to structure an app](/docs/structuring-an-app) and -[testing](/docs/testing). +- **Plugins** wrap every call a client makes, to add auth, retries, + timeouts or logging. + +The guides in the sidebar follow the same order. They start with +[Clients](/docs/clients), [Calls](/docs/calls) and [Errors](/docs/errors). +Then come [Endpoints](/docs/endpoints), for calls you save once and reuse, +and [Plugins](/docs/plugins), including [your own](/docs/plugins/writing). +After those, the sidebar goes further, with +[Streaming responses](/docs/streaming), [Pagination](/docs/pagination), +[Testing](/docs/testing), [Structure an app](/docs/structuring-an-app) and +[Platform notes](/docs/platforms). ## The examples in these docs -To stay short, many examples start from `declare const api: Fetch.Client`: a -client without plugins, like the one `yield* Api` gives you when `Api` has -none. In your app, get the client with `yield* Api`. To type a client in a -function signature, use `Effect.Success`, which includes your -plugins and error schemas. +Most examples in these docs leave out the setup you wrote in this tutorial, +to stay short. They start from a client that's already there: + +```ts +import type { Fetch } from "@monarcode/effetch"; + +declare const api: Fetch.Client; + +export const todos = api.get("/todos"); +``` + +`Fetch.Client` is the type of a client with no plugins, `defaultError` or +`statusErrors`, like the `Api` in this tutorial. In your app, get the client +with `yield* Api`, as the program does. To type a client in a function +signature, use `Effect.Success`, which includes your plugins and +error schemas. -Some examples also bind an endpoint inline, with `api.bind`, to stay short. -In your app, bind endpoints once, with `Fetch.Endpoints` (see +Some examples also bind an endpoint inline, with `api.bind`, for the same +reason. In your app, bind endpoints once, with `Fetch.Endpoints` (see [Share endpoints as a service](/docs/endpoints/services)). -Every TypeScript example in these docs is compiled with the package, so -they all match the API. +Every TypeScript example in these docs is compiled against the package when +the site is built, so each one matches the version the docs describe. ## What's next -- [Declare a client](/docs/clients): see what the client class gives you +- [Declare a client](/docs/clients): see what the client class gives you, and how to type it. - [Client configuration](/docs/clients/configuration): add headers, error schemas and plugins to your client. -- [Methods](/docs/calls): make calls with each HTTP method. -- [Call errors](/docs/errors): see what can go wrong in a call and how to +- [Make a call](/docs/calls): pick a method, fill in path parameters and + build a query string. +- [Call errors](/docs/errors): see what can go wrong in a call, and how to catch it. +- [Examples](/docs/examples): read complete programs that use Effetch, from + one file to a whole app. diff --git a/site/content/docs/(latest)/index.mdx b/site/content/docs/(latest)/index.mdx index 454d58d..a89b9c3 100644 --- a/site/content/docs/(latest)/index.mdx +++ b/site/content/docs/(latest)/index.mdx @@ -3,20 +3,20 @@ title: Introduction description: Typed HTTP calls for Effect, without the boilerplate. --- -Effetch is a thin layer over Effect v4's `HttpClient` for calling REST and -JSON APIs. You give it a path and a schema. It fills in the path, builds the -query, sends the request, checks the status and decodes the response. What -you get back is an Effect that's typed end to end, errors included, so -TypeScript tells you what a call returns and every way it can fail. +Calling a REST API with Effect's `HttpClient` means writing the same steps +for every request: build the URL, send it, check the status, decode the +body. Effetch does those steps for you. You give it a path and a schema, and +you get back an Effect that's typed end to end, so a call's type says what +it returns and every way it can fail. -This page explains why Effetch exists, what it does and where it fits. To -start using it, see [Installation](/docs/installation). +This page shows why Effetch exists and where it fits next to Effect's own +tools. To start using it, see [Installation](/docs/installation). - Effetch is close to its first stable release (`0.1.0-rc.N`). The API is - settled: release candidates add small, opt-in features and fixes, and the - [changelog](https://github.com/monarcode/effetch/blob/main/CHANGELOG.md) lists - anything that needs a change in your code. + Effetch is in release candidates (`0.1.0-rc.N`) on the way to `0.1.0`. A + release candidate can still change the API. When one does, the + [changelog](https://github.com/monarcode/effetch/blob/main/CHANGELOG.md) says + what to change in your code. ## Why Effetch @@ -24,15 +24,16 @@ start using it, see [Installation](/docs/installation). Effect gives you two ways to call an HTTP API, and they sit at opposite ends: -- **`HttpClient` is low level.** For every request you build the URL, check +- **`HttpClient` is low level.** For each request, you build the URL, check the status and decode the body yourself. - **`HttpApi` is contract first.** You describe the whole API up front and - share it with the server, which is ideal when you own both sides. + share that description with the server. That's a good fit when you own + both sides. -Most apps sit in between. They call a backend they don't control, such as -their company's REST API or a third-party service, one call at a time. -Effetch is made for that. It gives each call the types and error handling of -a contract, without you having to write one. +Most apps sit somewhere in between. They call a backend they don't control, +such as their company's REST API or a third-party service, one call at a +time. Effetch is made for that case. Each call gets the types and error +handling a contract would give it, without you writing the contract. ## At a glance @@ -67,41 +68,44 @@ export const getTodo = (id: number) => api.get("/todos/:id", { params: { id }, output: Todo }); ``` -Both send the same request and decode the same response. The Effetch version -also: +Both call the same URL and decode the response with the same schema. The +Effetch version is one line, and it also: -- checks at compile time that every call passes an `id`; -- fails with `NetworkError`, `HttpError` or `DecodeError` rather than +- checks at compile time that the call passes an `id`; +- fails with `NetworkError`, `HttpError` or `DecodeError`, rather than `HttpClientError | SchemaError`, so you can handle each case on its own; - decodes the API's error body onto `HttpError`, with a schema you give it; -- runs the client's plugins, such as auth, retries, timeouts and logging, on - every call. +- sends `accept: application/json`, since it expects JSON back; +- runs the client's plugins, such as auth, retries, timeouts and logging. ## What you get -- **Paths that check themselves.** Write `"/users/:id"` and TypeScript asks - for `params: { id }`. No more, no less. +- **Paths that check themselves.** Write `"/users/:id"`, and TypeScript asks + for `params: { id }`, nothing more and nothing less. - **Queries from plain objects.** `{ page: 2, tags: ["a", "b"] }` becomes `?page=2&tags=a&tags=b`, and `undefined` values are left out. -- **Responses you can trust.** Decode the response with a `Schema`, and the - API's error body with another. The schemas' types become the call's types. -- **Errors you can catch by name.** Three tagged errors, `NetworkError`, - `HttpError` and `DecodeError`, plus any your plugins add, all in the type. - Turn statuses into your own errors, such as a `404` into `TodoNotFound`, - with `statusErrors`. +- **Responses you can trust.** One schema decodes the response, and another + decodes the API's error body. Their types become the call's types. +- **Errors you can catch by name.** A call fails with one of three tagged + errors, `NetworkError`, `HttpError` or `DecodeError`, plus any your + plugins add, and all of them are in its type. With `statusErrors`, you can + also turn statuses into errors of your own, such as a 404 into + `TodoNotFound` (see [Errors by status](/docs/errors/status-errors)). - **Plugins for the repetitive parts.** Auth with token refresh, retries, - timeouts and logging are built in, and your own take a few lines. Any call - can turn a plugin off or adjust it, and TypeScript checks the names and - options. -- **Endpoints.** Save a route like `"GET /users/:id"` with its schemas once, - then call it like a function wherever you need it. Share a module's - endpoints as a service with `Fetch.Endpoints`. + timeouts and logging are built in, and a plugin of your own takes a few + lines. Any call can turn a plugin off or adjust it, and TypeScript checks + the names and the options. +- **Endpoints.** Save a route such as `"GET /users/:id"` with its schemas + once, then call it like a function wherever you need it. Share a + module's endpoints as a service with `Fetch.Endpoints`. - **Streams and pages.** Read Server-Sent Events and newline-delimited JSON as an Effect `Stream`, and page through a list with `Fetch.paginate`. -- **Tests without a network.** `FetchTest` makes a typed fake backend from - your endpoints, so tests run the real client with its plugins. -- **Runs anywhere.** There are no platform-specific imports or builds: it - targets browsers, React Native, Node 20+, Bun and Deno. +- **Tests without a network.** `FetchTest` turns your endpoints into a typed + fake backend, so your tests run the real client, plugins included. +- **No platform-specific code.** Effetch has no Node.js imports and no + separate builds. It's built for browsers, React Native, Node.js, Bun and + Deno. [Compatibility](/docs/reference/compatibility) lists which of them + CI tests. ## Where it fits @@ -109,15 +113,19 @@ also: share code with. - Use Effect's **`HttpApi`** when you own both the server and the client, and want them to share one contract. -- Use **`HttpClient`** directly for what Effetch doesn't cover, such as - WebSockets or uploads with progress. Every Effetch client gives you its - own when you need it. +- Use **`HttpClient`** directly for a request Effetch doesn't model. Every + Effetch client gives you its own `HttpClient`, with the base URL and + plugins already applied. -If you know axios or ky, see -[Coming from axios or ky](/docs/coming-from-axios-or-ky) -for how what you know maps to Effetch. +Neither Effetch nor `HttpClient` covers WebSockets, which Effect's `Socket` +module handles, or reports upload progress. + +If you've used axios or ky, see +[Coming from axios or ky](/docs/coming-from-axios-or-ky) to see how what +you're used to maps to Effetch. ## What's next -- [Install Effetch](/docs/installation). -- Make your first typed call in [Getting started](/docs/getting-started). +- [Installation](/docs/installation): add Effetch and Effect to your project. +- [Getting started](/docs/getting-started): write a first program that makes + a typed call, from an empty file to a working run. diff --git a/site/content/docs/(latest)/installation.mdx b/site/content/docs/(latest)/installation.mdx index 0289278..490a20c 100644 --- a/site/content/docs/(latest)/installation.mdx +++ b/site/content/docs/(latest)/installation.mdx @@ -3,37 +3,45 @@ title: Installation description: Add Effetch to a project and import its entry points. --- -This page shows how to install Effetch and import it. After it, you can make -your first call. +Effetch is one package, and the only other package it needs is Effect. This +page shows how to add both to your project and how to import Effetch, so +you're ready to write your first call. ## Before you begin You need: -- `effect` 4.x, which is a peer dependency; -- an ESM project, since the package is ESM only; -- TypeScript 5.4 or later. With `skipLibCheck: false`, Effect's own - declarations need TypeScript 5.7 or later. +- an ESM project, such as one with `"type": "module"` in its + `package.json`, since the package is ESM only; +- TypeScript 5.7 or later; +- a supported runtime. [Compatibility](/docs/reference/compatibility) lists + them, and which of them CI tests. + +`effect` 4.x is a peer dependency: you install it next to Effetch, in the +next step. ## Install the package -To install Effetch and Effect, run the following command: +To install Effetch and Effect, run the command for your package manager: -```bash -pnpm add @monarcode/effetch effect -``` +- npm: `npm install @monarcode/effetch effect` +- pnpm: `pnpm add @monarcode/effetch effect` +- Yarn: `yarn add @monarcode/effetch effect` +- Bun: `bun add @monarcode/effetch effect` -In an Expo project, run the following commands instead: +In an Expo project, add `effect` with Expo's installer: ```bash npx expo install effect -pnpm add @monarcode/effetch ``` +Then add Effetch with your package manager, as in +`npm install @monarcode/effetch`. + ## Import Effetch -Everything in the main entry is under one export, `Fetch`. Plugins and the -test backend have their own entries: +Everything in the main entry is under one export, `Fetch`. The plugins and +the test backend each have an entry of their own: ```ts import { Fetch } from "@monarcode/effetch"; @@ -45,19 +53,21 @@ export const getTodo = Fetch.endpoint("GET /todos/:id"); export const Backend = FetchTest.layer([]); ``` -Your editor offers to add the `Fetch` import as you type it. For types -alone, use `import type { Fetch } from "@monarcode/effetch"`. +Your editor offers to add the `Fetch` import as you type the name. When you +need only its types, write `import type { Fetch } from "@monarcode/effetch"`. -The package also has `@monarcode/effetch/Fetch` and -`@monarcode/effetch/test/FetchTest`: the same exports, without the -namespace, as `effect/Effect` is to `import { Effect } from "effect"`. -TypeScript uses them to name Effetch's types in the `.d.ts` files it emits -for your code. In your own code, import from the main entry. +The package has two more entries, `@monarcode/effetch/Fetch` and +`@monarcode/effetch/test/FetchTest`. They hold the same exports without the +namespace, the way `effect/Effect` relates to `import { Effect } from +"effect"`. TypeScript uses them to name Effetch's types in the `.d.ts` files +it emits for your code. In your own code, import from the main entry. -If you're upgrading a project from 0.1.0-rc.3, see -[Upgrade from 0.1.0-rc.3](/docs/upgrading) -to move its imports to `Fetch`. +If your project was written for 0.1.0-rc.3 or earlier, its imports need to +move to `Fetch`. See [Upgrade from 0.1.0-rc.3](/docs/upgrading). ## What's next -- Make your first call: see [Getting started](/docs/getting-started). +- [Getting started](/docs/getting-started): write a first program that makes + a typed call, and run it. +- [Coming from axios or ky](/docs/coming-from-axios-or-ky): see how what + you know from those libraries maps to Effetch. diff --git a/site/content/docs/(latest)/meta.json b/site/content/docs/(latest)/meta.json index 888951a..1a6791c 100644 --- a/site/content/docs/(latest)/meta.json +++ b/site/content/docs/(latest)/meta.json @@ -5,19 +5,22 @@ "index", "installation", "getting-started", - "upgrading", + "coming-from-axios-or-ky", + "---Guides---", "clients", "calls", "errors", - "plugins", "endpoints", + "plugins", + "---Going further---", "streaming", "pagination", - "structuring-an-app", "testing", + "structuring-an-app", "platforms", - "coming-from-axios-or-ky", + "---Resources---", + "reference", "examples", - "reference" + "upgrading" ] } diff --git a/site/content/docs/(latest)/pagination.mdx b/site/content/docs/(latest)/pagination.mdx index d541616..6b790a7 100644 --- a/site/content/docs/(latest)/pagination.mdx +++ b/site/content/docs/(latest)/pagination.mdx @@ -4,9 +4,11 @@ description: Page through a list with Fetch.paginate, with the cursor in the bod --- Lists are often split into pages: you ask for the first, and the response -says how to get the next. `Fetch.paginate` follows those pages for you, as a -`Stream` of pages. This page shows how to page through a list, with the next -page's state in the body or in a header. +says how to get the next. Writing that loop by hand for every list means +tracking the state, stopping at the end, and not fetching pages nobody +reads. `Fetch.paginate` follows the pages for you, as a `Stream` of pages. +This page shows how to page through a list, with the next page's state in +the body or in a header. ## Page through a list @@ -41,20 +43,24 @@ export const allTodos = Effect.gen(function* () { return yield* Fetch.paginate(todos.list, { start: 1, request: (page) => ({ query: { page } }), - next: (page, number) => - page.length === 0 ? Option.none() : Option.some(number + 1), + next: (items, page) => + items.length === 0 ? Option.none() : Option.some(page + 1), }).pipe(Stream.flattenIterable, Stream.runCollect); }); ``` `Fetch.paginate` takes three options: -- `start` is the state of the first page, such as a page number or a +- **`start`** is the state of the first page, such as a page number or a cursor. -- `request(state)` gives the page's call options: `params`, `query`, `body` - and `headers`, typed by the endpoint. -- `next(page, state, response)` gives the next page's state, or - `Option.none()` after the last page. +- **`request(state)`** gives the options for that page's call: `params`, + `query`, `body` and `headers`, typed by the endpoint. Plugin overrides + aren't among them, so give those when you bind the endpoint. The + endpoint's `responseMode` always decides what each page is. +- **`next(page, state, response)`** gives the next page's state, or + `Option.none()` after the last page. `response` is the page's + `HttpClientResponse` when the endpoint's `responseMode` is + `"decoded-and-response"`, and `undefined` otherwise. Each page is one value of the stream, so a page that's a list stays a list. `Stream.flattenIterable` gives its items one by one. @@ -65,15 +71,17 @@ The stream is lazy: it sends a page's call only when the page is needed, so `Stream.take(1)` sends one. A call that fails fails the stream with the call's error. -`Fetch.paginate` takes a bound endpoint, from `Fetch.Endpoints`, -`client.bind`, `client.bindAll` or `client.endpoint`. A definition made by -`Fetch.endpoint` needs binding first, and a stream endpoint can't be paged. +`Fetch.paginate` takes a bound endpoint, from `Fetch.Endpoints`, `api.bind`, +`api.bindAll` or `api.endpoint`. It throws when you pass it a definition +made by `Fetch.endpoint`, which needs binding first, or a stream endpoint, +which can't be paged. ## Read the cursor from a header -When the next page's cursor is in a header, such as a `Link` header, define -the endpoint with `responseMode: "decoded-and-response"`. `next` then gets -each page's response: +Some APIs put the next page's cursor in a header, such as a `Link` header, +rather than in the body. For those, define the endpoint with +`responseMode: "decoded-and-response"`, and `next` gets each page's +response: ```ts import * as Option from "effect/Option"; @@ -103,6 +111,9 @@ export const allItems = Fetch.paginate(api.bind(listItems), { }); ``` +Each page is still the decoded body, here the array of items. Only `next` +gets the response. + ## What's next - [Call an endpoint](/docs/endpoints/calling): bind an endpoint so diff --git a/site/content/docs/(latest)/platforms.mdx b/site/content/docs/(latest)/platforms.mdx index 5a662de..cf63a4d 100644 --- a/site/content/docs/(latest)/platforms.mdx +++ b/site/content/docs/(latest)/platforms.mdx @@ -3,19 +3,25 @@ title: Platform notes description: Set up Effetch for browsers and React Native. --- -This page covers what to know, and what to set up, when you run Effetch in a -browser or in React Native. - -Effetch has no platform-specific imports or builds, and runs wherever Effect's -`HttpClient` does: browsers, React Native, Node 20 or newer, Bun and Deno. -Two platforms need a little setup. +Effetch runs the same code on every platform, with no platform-specific +imports or builds. Requests go through Effect's `HttpClient`, so what a +platform needs mostly comes from there. Two platforms need some setup: +browsers, for calls to other origins, and React Native. This page covers +both. For the full list of runtimes, and which of them CI tests, see +[Compatibility](/docs/reference/compatibility). ## Browsers +In a browser, a relative path in a client without a `baseUrl` is resolved +against the page's URL. Calls to another origin need the setup in this +section. + +### Turn off tracing headers + Effect's `HttpClient` adds `traceparent` and `b3` tracing headers to every -request. Cross-origin calls to APIs that don't allow those headers then fail -the CORS preflight. Turn propagation off in the layer that makes the client, -and it applies to all its calls: +request. A cross-origin call to an API that doesn't allow those headers then +fails the browser's CORS preflight. To stop sending them, turn propagation +off in the layer that builds the client: ```ts import * as FetchHttpClient from "effect/http/FetchHttpClient"; @@ -34,30 +40,103 @@ export const ApiLive = Api.layer.pipe( ); ``` -In a browser, a relative path without a `baseUrl` is resolved against the -page's URL. +The client keeps what its layer was given, so the setting applies to all of +its calls. + +### Send cookies + +By default, `fetch` sends cookies only to the page's own origin. To send +them to an API on another origin, set `credentials: "include"` in +`FetchHttpClient.RequestInit`, the default options for every `fetch` the +client makes: + +```ts +import * as FetchHttpClient from "effect/http/FetchHttpClient"; +import * as Layer from "effect/Layer"; + +import { Fetch } from "@monarcode/effetch"; + +export class Api extends Fetch.Service()("Api", { + baseUrl: "https://api.example.com", +}) {} + +export const ApiLive = Api.layer.pipe( + Layer.provide( + Layer.succeed(FetchHttpClient.RequestInit)({ credentials: "include" }), + ), + Layer.provide(FetchHttpClient.layer), +); +``` + +The API has to allow it too: its CORS response needs +`Access-Control-Allow-Credentials: true`, and an +`Access-Control-Allow-Origin` that names your page's origin rather than `*`. + +`RequestInit` can set other `fetch` options the same way, such as `cache` +or `redirect`. The call still sets the method, the body and the abort +signal, and its headers win over any in `RequestInit`. A `RequestInit` +provided around one call replaces the client's for that call. ## React Native -React Native differs from the other platforms in these ways: - -- Effetch doesn't use `URL` itself. Effect's `HttpClient` does, including - `searchParams`. Expo provides a standard `URL`. In a React Native app - without Expo, install a polyfill such as `react-native-url-polyfill`. -- Effetch and Effect use package `exports` (`effect/http/HttpClient`, - `@monarcode/effetch/plugins`). Metro resolves them by default from React - Native 0.79 (Expo SDK 53). On older versions, set - `resolver.unstable_enablePackageExports = true` in `metro.config.js`. -- `FetchHttpClient.layer` uses the global `fetch`. -- React Native's `fetch` doesn't stream response bodies, so `api.sse`, - `api.ndjson` and stream endpoints fail with a `DecodeError` there. In - Expo, provide the `fetch` from `expo/fetch`, which streams, as - `FetchHttpClient.Fetch`: - `Layer.succeed(FetchHttpClient.Fetch)(expoFetch as typeof globalThis.fetch)`. -- To upload a file a picker gave you, send its `{ uri, name, type }` in a - `Fetch.UploadFile` field (see [Upload files](/docs/calls/uploads)). - React Native's `FormData` reads the file from disk by `uri`, and can't send - a `Blob`. -- Metro's terminal drops `console.groupCollapsed` and everything inside it, - so `consoleLogger` doesn't collapse its groups in React Native (see the - details in [Log to the console](/docs/plugins/console-logging)). +React Native differs from the other platforms in the following ways: + +- **`URL`.** Effetch joins URLs as strings and never calls `new URL()` + itself. Effect's `HttpClient` does use `URL`, `searchParams` included, + when it sends each request. An endpoint's `url` helper uses it too. + Expo provides a standard `URL`. In a React + Native app without Expo, install a polyfill such as + `react-native-url-polyfill`. +- **Package `exports`.** Effetch and Effect use package `exports`, as in + `effect/http/HttpClient` and `@monarcode/effetch/plugins`. Metro resolves + them by default from React Native 0.79 (Expo SDK 53). On older versions, + set `resolver.unstable_enablePackageExports = true` in `metro.config.js`. +- **Streams.** `FetchHttpClient.layer` sends requests with the global + `fetch`, and React Native's `fetch` doesn't stream response bodies. So + `api.sse`, `api.ndjson` and stream endpoints fail with a `DecodeError` + there. A stream also needs `TextDecoder`, and fails with a `DecodeError` + on a runtime without it. In Expo, use the `fetch` from `expo/fetch`, which + streams (see the sample after this list). +- **File uploads.** To upload a file a picker gave you, send its + `{ uri, name, type }` in a `Fetch.UploadFile` field (see + [Upload files](/docs/calls/uploads)). React Native's `FormData` reads the + file from disk by its `uri`, and can't send a `Blob`. +- **Console logging.** Metro's terminal drops `console.groupCollapsed` and + everything inside it, so `consoleLogger` doesn't collapse its groups in + React Native (see [Log to the console](/docs/plugins/console-logging)). + +To stream in Expo, provide the `fetch` from `expo/fetch` as +`FetchHttpClient.Fetch`, in the layer that builds the client: + +```ts +import * as FetchHttpClient from "effect/http/FetchHttpClient"; +import * as Layer from "effect/Layer"; + +import { Fetch } from "@monarcode/effetch"; + +// In your app: import { fetch as expoFetch } from "expo/fetch"; +declare const expoFetch: unknown; + +export class Api extends Fetch.Service()("Api", { + baseUrl: "https://api.example.com", +}) {} + +export const ApiLive = Api.layer.pipe( + Layer.provide( + Layer.succeed(FetchHttpClient.Fetch)(expoFetch as typeof globalThis.fetch), + ), + Layer.provide(FetchHttpClient.layer), +); +``` + +The cast gives `expo/fetch`'s function the type of the global `fetch`, +which `FetchHttpClient.Fetch` expects. + +## What's next + +- [Compatibility](/docs/reference/compatibility): check the Effect, + runtime and TypeScript versions Effetch supports. +- [Upload files](/docs/calls/uploads): send a file from a picker in a typed + multipart form. +- [Streaming responses](/docs/streaming): read Server-Sent Events and + newline-delimited JSON as a `Stream`. diff --git a/site/content/docs/(latest)/plugins/console-logging.mdx b/site/content/docs/(latest)/plugins/console-logging.mdx index 0b162aa..591cc57 100644 --- a/site/content/docs/(latest)/plugins/console-logging.mdx +++ b/site/content/docs/(latest)/plugins/console-logging.mdx @@ -3,10 +3,12 @@ title: Log to the console description: Print every call's route, status, headers, bodies and error to the console during development. --- -`logger` writes one structured entry per call for production logs, and leaves -headers, query strings and bodies out. `consoleLogger` is for development: it -prints everything about a call to the console, as a group devtools can -expand. This page shows how to add it, what it prints, and how to tune it. +While you develop, a failed call is easier to fix when you can see what was +sent and what came back. `logger` writes one structured entry per call for +production logs, and leaves headers, query strings and bodies out. +`consoleLogger` is for development: it prints everything about a call to the +console, as a group that devtools can expand. This page shows how to add it, +how to read what it prints, and how to tune it. ## Add the console logger @@ -33,45 +35,71 @@ export class Api extends Fetch.Service()("Api", { ## Read the output -Each call prints a line, which opens a group with the details: +Each call prints a summary line. With `detail: "full"`, the default, that +line opens a group with the call's URL, headers, bodies and error. Here's +what Node prints for six calls, with `slow: "1 second"`. The first five ran +with `detail: "summary"`, so only the last one opens a group. The fourth was +interrupted by `Effect.timeout`, and the fifth died because its `bearer` +token function threw: ```text -▸ GET /todos/:id 200 OK 35 ms 1.2 kB -▸ ✗ GET /todos 3.0 s → NetworkError: Failed to fetch -▸ ⚠ GET /reports/:id 200 OK 2.4 s (slow) -▾ ✗ POST /users/:id/roles 400 Bad Request 120 ms → InvalidRole: No such role - POST https://api.example.com/users/7/roles - request headers { accept: "application/json", authorization: "" } - request body { role: "owner" } - response headers { "content-type": "application/json" } - response body { code: "INVALID_ROLE", message: "No such role" } - error InvalidRole { code: "INVALID_ROLE", message: "No such role" } +GET /todos/:id 200 OK 18 ms 24 B +✗ GET /todos 2 ms → NetworkError: fetch failed +⚠ GET /reports/:id 200 OK 1.2 s 8 B (slow) +⊘ GET /slow/:id 1.0 s interrupted (slow) +✗ GET /broken 0 ms → defect: Error: No token store +✗ POST /users/:id/roles 400 Bad Request 2 ms 48 B → InvalidRole: No such role + POST https://api.example.com/users/7/roles + request headers { + 'content-type': 'application/json', + 'content-length': '16', + accept: 'application/json', + authorization: '', + b3: '…', + traceparent: '…' + } + request body { role: 'owner' } + response headers { 'content-length': '48', 'content-type': 'application/json' } + response body { code: 'INVALID_ROLE', message: 'No such role' } + error { _tag: 'InvalidRole', message: 'No such role', code: 'INVALID_ROLE' } ``` -It prints each call once it's over, with the error it ended with, after +The summary line starts with a mark for how the call ended: + +- no mark: it succeeded in time; +- `✗`: it failed, and the line ends with the error. A call that died shows + `→ defect:` and the defect; +- `⚠`: it succeeded, but took at least as long as `slow`, and the line ends + with `(slow)`; +- `⊘`: it was interrupted, such as by `Effect.timeout`. + +It prints each call after it's over, with the error it ended with, after [`statusErrors`](/docs/errors/status-errors) and decoding. Values are printed -as objects, so devtools can expand them. +as objects, so devtools can expand them. In browser devtools, the group +starts collapsed under its summary line. Node, as the output shows, prints +it expanded. The `b3` and `traceparent` headers are the tracing headers +that Effect's `HttpClient` adds, with their IDs cut here. ## Options `consoleLogger` takes the following options: -| Option | Default | What it does | -| --------------- | -------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------- | -| `enabled` | `true` | `false` prints nothing, and keeps the plugin's type, so it can stay in the list in production. | -| `detail` | `"full"` | `"summary"` prints the line alone; `"headers"` adds the URL, headers and error; `"full"` adds the bodies. | -| `only` | `"all"` | `"errors"` prints failed calls only. | -| `collapsed` | `true` | Whether groups start collapsed. `false` by default in React Native, where Metro's terminal drops collapsed groups. Node, Bun and Deno print them expanded. | -| `slow` | `false` | A duration, such as `"1 second"`: slower calls are flagged. | -| `maxBodyLength` | `10_000` | Body text longer than this is cut. JSON within it is printed as an object. | -| `redact` | | `{ headers, query, body }`: more names to redact, as strings (ignoring case, `-` and `_`) or regular expressions. `false` redacts nothing. | -| `filter` | | `(call) => boolean`: prints only the calls it accepts. `call` has the `route`, the `request`, the `response`, the `exit` and the `durationMs`. | -| `color` | `"auto"` | `"css"` (browser devtools), `"ansi"` (terminals), or `false`. `"auto"` uses `"css"` where there's a `document`, else plain text. | +| Option | Default | What it does | +| --------------- | ------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------- | +| `enabled` | `true` | `false` prints nothing, and keeps the plugin's type, so it can stay in the list in production. | +| `detail` | `"full"` | `"summary"` prints the line alone. `"headers"` adds the URL, headers and error. `"full"` adds the bodies. | +| `only` | `"all"` | `"errors"` prints failed calls only. An interrupted call isn't a failed one. | +| `collapsed` | `true`, `false` in React Native | Whether groups start collapsed. Metro's terminal drops collapsed groups, so React Native defaults to `false`. | +| `slow` | `false` | A duration, such as `"1 second"`. Calls that take at least this long are flagged. | +| `maxBodyLength` | `10_000` | Body text longer than this many characters is cut. A JSON body within it is printed as an object. | +| `redact` | Built-in names (see Details) | `{ headers, query, body }`: more names to redact, as strings (ignoring case, `-` and `_`) or regular expressions. `false` redacts nothing. | +| `filter` | None: every call is printed | `(call) => boolean`: prints only the calls it accepts. `call` has the `route`, the `request`, the `response`, the `exit` and the `durationMs`. | +| `color` | `"auto"` | `"css"` (browser devtools and React Native DevTools), `"ansi"` (terminals), or `false`. `"auto"` uses `"css"` where there's a `document`, else plain text. | ## Change the output for one call -Calls can change `detail`, `only`, `collapsed`, `slow` and `maxBodyLength`, or -skip it with `false`: +A call can change `detail`, `only`, `collapsed`, `slow` and `maxBodyLength`, +or skip the plugin with `false`: ```ts import * as Effect from "effect/Effect"; @@ -118,43 +146,65 @@ It replaces these with ``, matching names ignoring case, `-` and as `Redacted`, and credentials in the URL (`https://user:password@…`). They're exact names rather than patterns, so fields such as `total_tokens` -stay visible. Plain-text bodies are printed as they are. A call's error is -printed as a copy of its fields, redacted like a body, without an -`HttpError`'s `text` or a `DecodeError`'s `issue`, which the response body -line shows. Defects are printed as they are. +stay visible. Plain-text bodies are printed as they are. + +A call's error is printed as a copy of its fields, with its `_tag` and +`message`, redacted like a body, since errors can carry body data. The copy +leaves out an `HttpError`'s `text` and a `DecodeError`'s `issue`, which the +response body line shows. Defects are printed as they are, with their stack. + + + + +- It reads a response body only with `detail: "full"`, and only when it's + text: JSON, `text/*` other than event streams, XML or a form. A body over + 1 MB, or over 4 × `maxBodyLength` if that's larger, is shown by its type + and size instead. +- Effect caches the body, so reading it here doesn't change what the call + decodes. +- A call without `output` returns the response itself, so `consoleLogger` + doesn't read its body, which stays yours to stream. It doesn't read an + interrupted call's body either. +- For `api.sse`, `api.ndjson` and stream endpoints, the entry is printed + when the response headers arrive, without the body. An error while the + stream reads, such as a `DecodeError`, isn't printed. +- A `HEAD` request and a `204`, `205` or `304` response have no body to + print. - - -- It only reads a response body that's text: JSON, `text/*` other than event - streams, XML or a form, up to 1 MB. Effetch has read it already to check - the status or decode it, and Effect caches it. A call without `output` - returns the response itself, so its body isn't read, and stays yours to - stream. Neither is an interrupted call's. -- It writes through Effect's `Console`, so you can provide another one, with - `console.log` and groups only. React Native turns `console.error` into an - error screen. + + +- It writes through Effect's `Console`, so you can provide your own. It calls + only `console.log` and the group methods, never `console.error`, which + React Native turns into an error screen. - In React Native, groups start expanded: Metro's terminal silently drops `console.groupCollapsed` and everything logged inside it. React Native is detected by `navigator.product`, which it sets to `"ReactNative"`. -- It runs when the call is over, so where it sits in the plugin list doesn't - matter: a retried call is one entry, and its duration covers every - attempt. The size comes from `content-length`, or from the body when it's - read. -- When a plugin fails on a response, such as an auth plugin on a 401, that +- Node, Bun and Deno print collapsed groups expanded. + + + + +- It runs from an `onExit` hook after the call is over, so where it sits in + the plugin list doesn't matter. A retried call is one entry, and its + duration covers every attempt, until the status is checked and the body + decoded. `logger`'s duration stops earlier, at the response headers. +- The size comes from `content-length`, or from the body when it's read. +- When a plugin fails on a response, such as an auth plugin on a `401`, that response is shown with the plugin's error. -- `slow` that isn't a duration throws when the plugin is made. - The request shown is the one that was sent, after plugins such as `bearer` changed it. When no response came back, it's the one the call built, before plugins ran. +- A `slow` that isn't a duration throws when the plugin is made. A call's own + `slow` that isn't a duration flags nothing. ## What's next -- [Built-in plugins](/docs/plugins): compare `consoleLogger` with `logger` - for production logs. +- [Built-in plugins](/docs/plugins#logger): compare `consoleLogger` with + `logger` for production logs. - [Change plugins for one call](/docs/plugins/per-call): skip or adjust any plugin on a single call. - [Write a plugin](/docs/plugins/writing): build your own logging or metrics diff --git a/site/content/docs/(latest)/plugins/index.mdx b/site/content/docs/(latest)/plugins/index.mdx index 1c1f5e2..6052aa1 100644 --- a/site/content/docs/(latest)/plugins/index.mdx +++ b/site/content/docs/(latest)/plugins/index.mdx @@ -1,13 +1,15 @@ --- title: Built-in plugins -description: Add a bearer token, retries, a timeout and logging to every call a client makes. +description: Add a bearer token, retries, a timeout and logging to every call a client makes, and see the order they run in. --- Most APIs need the same things on every call: a token, retries when the -network drops, a time limit, a log line. Plugins add that behavior to every -call a client makes. You list them in the client's config, and any call can -turn one off or adjust it. This page shows the plugins that ship with Effetch -and what each one does. +network drops, a time limit, a log line. Writing them into each call +repeats them, and the one call that forgets is the one that breaks. Plugins +add that behavior to every call a client makes. You list them in the +client's config, and any call can turn one off or adjust it. This page shows +the plugins that ship with Effetch, what each one does, and the order they +run in. ## Add plugins to a client @@ -15,8 +17,6 @@ The built-in plugins come from `@monarcode/effetch/plugins`. List them in the client's `plugins` option: ```ts -import * as Effect from "effect/Effect"; - import { Fetch } from "@monarcode/effetch"; import { bearer, logger, retry, timeout } from "@monarcode/effetch/plugins"; @@ -31,53 +31,215 @@ export class Api extends Fetch.Service()("Api", { bearer({ token: () => readToken() }), ], }) {} - -export const withEffectToken = bearer({ token: Effect.succeed("token") }); ``` -The order in this example is the one to use. To learn why, see -[Plugin order](/docs/plugins/order). +The order in this example is the one to use: `logger` covers the whole +call, and each retry gets its own time limit and asks for the token again. To +learn why, see [How plugins nest](#how-plugins-nest). ## What each plugin does The following table lists each built-in plugin, what it does, and what a call can pass for it in its `plugins` option: -| Plugin | What it does | Per call | -| ------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | ---------------------------------------------------- | -| `bearer({ token, scheme?, refresh? })` | Sends `Authorization: Bearer `. The token is a string, a function of the request (sync or async), or an Effect, read for every request. `null`, `undefined` and `""` send no header, and an existing `Authorization` header is kept. With `refresh`, a `401` gets a new token and the request is sent again, once. See [Refresh a token](/docs/plugins/token-refresh). | `false` | -| `logger({ level? })` | Logs one entry per call at Debug (or Info): `GET 200 (35ms)`, or `failed` with the cause, with the call's [route](/docs/plugins/writing#read-the-route) as an annotation. Never logs headers or query strings. | `false` | -| `consoleLogger(options?)` | Prints each call to the console while you develop: a line with the route, status, duration and outcome, opening a group with the full URL, headers, bodies and error. Sensitive headers, query parameters and body keys are redacted. See [Log to the console](/docs/plugins/console-logging). | `false`, its settings | -| `retry({ times?, schedule?, methods?, statuses?, retryAfter?, budget? })` | Retries network errors and 408, 429, 500, 502, 503 and 504, 2 times by default, with jittered exponential backoff from 200ms. Only idempotent methods (`GET`, `HEAD`, `OPTIONS`, `PUT`, `DELETE`) by default, so a `POST` is never sent twice. When retries run out, the last response is returned. `retryAfter` waits as `Retry-After` asks, and `budget` limits the whole call. See [Retry-After and a time limit](/docs/plugins/retry-after). | `false`, `{ times }`, and `{ budget }` with a budget | -| `timeout({ duration })` | Fails with `TimeoutError` and aborts the request when the response headers don't arrive in time. Downloading the body isn't covered. | `false`, `{ duration }` | +| Plugin | What it does | Per call | +| --------------- | ----------------------------------------------------- | ------------------------------------------------------------------ | +| `bearer` | Sends a token in the `Authorization` header. | `false` | +| `logger` | Logs one entry per call with Effect's logger. | `false` | +| `consoleLogger` | Prints each call to the console while you develop. | `false`, or `detail`, `only`, `collapsed`, `slow`, `maxBodyLength` | +| `retry` | Retries network errors and statuses such as `503`. | `false`, `{ times }`, and `{ budget }` when it has a budget | +| `timeout` | Fails the call when the response headers arrive late. | `false`, `{ duration }` | + +The sections that follow describe each one. + +### bearer + +`bearer({ token, scheme?, refresh? })` sends `Authorization: ` +with every request. `scheme` is the word before the token, and defaults to +`"Bearer"`. + +The token can be a string, a function of the request that returns it (sync +or async), or an Effect. `bearer` reads it for every request and never +caches it, so a token you change or clear applies to the next request. When +the token is `null`, `undefined` or `""`, the request goes without the +header. A request that already has an `Authorization` header keeps it, and +`bearer` doesn't read the token for it. + +With `refresh`, a `401` gets a new token, and the request is sent again, +once. See [Refresh a token](/docs/plugins/token-refresh). + +### logger + +`logger({ level? })` logs one entry per call with Effect's logger, such as +`GET https://api.example.com/todos/1 200 (35ms)`. A failed call logs +`… failed (35ms)` with the failure's cause. The entry is annotated with the +`method`, `url`, `status` and `durationMs`, and the call's +[route](/docs/plugins/writing#read-the-route), such as `GET /todos/:id`, to +group entries by. + +It logs no headers, and the URL leaves out the query string, so tokens and +cookies stay out of your logs. The failure's cause is logged as it is. + +Entries are logged at the Debug level by default. Effect's default minimum +log level is Info, so with the default logger a plain `logger()` prints +nothing. Pass `level: "Info"`, or lower the minimum level for your program +with `Effect.provideService(References.MinimumLogLevel, "Debug")`. + +The duration runs until the response headers arrive. It doesn't include +reading or decoding the body, which `consoleLogger` and `onExit` hooks do +count. For a stream from `api.sse` or `api.ndjson`, the entry is logged when +the headers arrive. An interrupted call isn't logged. + +### consoleLogger + +`consoleLogger(options?)` is for development. It prints each call to the +console as a line with the route, status, duration and outcome, which opens a +group with the full URL, headers, bodies and error. It redacts sensitive +headers, query parameters and body keys. See +[Log to the console](/docs/plugins/console-logging). + +### retry + +`retry({ times?, schedule?, methods?, statuses?, retryAfter?, budget? })` +sends a request again when it fails with a `NetworkError`, or gets a status +worth retrying. By default: + +- it retries `408`, `429`, `500`, `502`, `503` and `504` (`statuses`); +- it retries 2 times after the first attempt (`times`); +- it waits with jittered exponential backoff from 200ms (`schedule`, which + `times` still caps); +- it retries only the idempotent methods, `GET`, `HEAD`, `OPTIONS`, `PUT` + and `DELETE` (`methods`), so a `POST` is never sent twice. + +When the retries run out, the call ends with the last response as it is, so +a `503` still ends as an `HttpError` with that response's body. When the +last attempt fails with a `NetworkError`, that's the call's error. Other +failures, such as a `TimeoutError` from `timeout`, aren't +retried. + +`retry` retries everything after it in the plugin list. For a stream, it +retries getting the response, not a body that breaks off later. + +`retryAfter` waits as a `Retry-After` header asks, and `budget` limits the +whole call. See [Retry-After and a time limit](/docs/plugins/retry-after). + +### timeout + +`timeout({ duration })` fails the call with a `TimeoutError`, and aborts the +request, when the response headers don't arrive within `duration`. +`TimeoutError` comes from `@monarcode/effetch/plugins`, and has the +request's `method`, its `url` without the query string, and the `duration` +that ran out, such as `"10s"`. + +It covers the plugins after it in the list and the network, but not reading +the body. A large download, or a stream from `api.sse` or `api.ndjson`, that +starts in time isn't cut off while the body arrives. To learn where to put +it, see [Retry-After and a time limit](/docs/plugins/retry-after). ## Fail with a typed error from a token A `bearer` token function that throws, or whose promise rejects, makes the -call die. To fail with a typed error instead, pass an Effect: its error and -services become the client's, and the client's layer (or `Fetch.make`) asks -for the services. +call die (a defect: an Effect that dies, which you don't catch in normal +code). To fail with a typed error instead, pass an Effect as the token: -## Choose a time limit +```ts +import * as Context from "effect/Context"; +import * as Data from "effect/Data"; +import * as Effect from "effect/Effect"; + +import { Fetch } from "@monarcode/effetch"; +import { bearer } from "@monarcode/effetch/plugins"; -Time limits apply per attempt or to the whole call: +export class SignedOut extends Data.TaggedError("SignedOut")<{}> {} -- **Per attempt:** `timeout`, placed after `retry` in the plugin list, as in - the example on this page. Each attempt gets the full duration, and a - timed-out attempt isn't retried. -- **For the whole call:** `retry({ budget })`, every attempt and wait - included. For one call, or on a client without `retry`, wrap the call in - `Effect.timeout`. +export class Session extends Context.Service< + Session, + { readonly accessToken: Effect.Effect } +>()("Session") {} + +export class Api extends Fetch.Service()("Api", { + baseUrl: "https://api.example.com", + plugins: [ + bearer({ + token: Effect.gen(function* () { + const session = yield* Session; + return yield* session.accessToken; + }), + }), + ], +}) {} + +// Api.layer needs Session, and every call can fail with SignedOut. +export const todos = Effect.gen(function* () { + const api = yield* Api; + return yield* api.get("/todos"); +}).pipe(Effect.catchTag("SignedOut", () => Effect.succeed(undefined))); +``` + +The Effect's error joins the errors of every call the client makes. Its +services, such as `Session` here, are required by the client's layer (or +`Fetch.make`), once, so the calls themselves don't need them. + +## How plugins nest + +The order of a client's `plugins` list decides what each plugin covers. The +first plugin is the outermost: a request passes through the plugins in list +order on the way out, and the response comes back through them in reverse. + +A plugin's `wrap` hook encloses its own `onRequest` and `onResponse`, and +every plugin after it. For two plugins, `a` then `b`, that use every hook, a +call runs in this order: + +```text +a.wrap + a.onRequest + b.wrap + b.onRequest + the network + b.onResponse + a.onResponse +the status check and decoding +a.onError, then b.onError (only when the call failed or died) +a.onExit, then b.onExit +``` + +Because a `wrap` encloses everything inside it, a `wrap` that retries runs +its own `onRequest` and `onResponse` again on each attempt, along with every +plugin after it. + +`onError` and `onExit` don't nest. They run after the call, in list order, +wherever the plugin sits. To learn what each hook does, see +[Write a plugin](/docs/plugins/writing). + +### The recommended order + +List the built-in plugins as `logger`, `retry`, `timeout`, `bearer`, as in +the example on this page. With that order: + +- `logger` covers the whole call, retries included, and logs one entry for it. + After `retry`, it would log one entry per attempt. +- `consoleLogger` runs from `onExit`, so it covers the whole call wherever + it sits. +- Each retry gets its own timeout, and asks `bearer` for the token again. +- A timed-out attempt isn't retried. +- `retry`'s `budget` covers every attempt and wait, while `timeout` covers + one attempt. +- A `401` that `bearer` refreshes is sent again inside the same attempt, so + it shares that attempt's timeout. + +## Choose a time limit -To use both together, see -[Retry-After and a time limit](/docs/plugins/retry-after). +`timeout` limits each attempt, and `retry`'s `budget` limits the whole call, +every attempt and wait included. Both stop at the response headers: neither +covers reading the body. To choose between them, combine them, or cap the +body too, see [Retry-After and a time limit](/docs/plugins/retry-after). ## What's next - [Refresh a token](/docs/plugins/token-refresh): renew an expired token without failing the call. - [Retry-After and a time limit](/docs/plugins/retry-after): honor - `Retry-After` and cap the whole call. + `Retry-After`, and limit each attempt and the whole call. - [Change plugins for one call](/docs/plugins/per-call): skip or adjust a plugin on a single call. - [Write a plugin](/docs/plugins/writing): add behavior the built-in plugins diff --git a/site/content/docs/(latest)/plugins/meta.json b/site/content/docs/(latest)/plugins/meta.json index 2232e66..0092cc1 100644 --- a/site/content/docs/(latest)/plugins/meta.json +++ b/site/content/docs/(latest)/plugins/meta.json @@ -5,7 +5,6 @@ "token-refresh", "retry-after", "console-logging", - "order", "per-call", "writing", "recipes" diff --git a/site/content/docs/(latest)/plugins/order.mdx b/site/content/docs/(latest)/plugins/order.mdx deleted file mode 100644 index 26a05fb..0000000 --- a/site/content/docs/(latest)/plugins/order.mdx +++ /dev/null @@ -1,30 +0,0 @@ ---- -title: Plugin order -description: Learn the order plugins run in, and why logger, retry, timeout and bearer go in that order. ---- - -The order of a client's `plugins` list decides what each plugin sees. This -page explains how plugins nest, and why the order used in -[Built-in plugins](/docs/plugins) is the one to use. - -## How plugins nest - -The first plugin is the outermost: it runs first on the way out, and last on -the way back. - -## The recommended order - -List the built-in plugins as `logger`, `retry`, `timeout`, `bearer`, as in -the example in [Built-in plugins](/docs/plugins). With that order: - -- `logger` sees the whole call, retries included (`consoleLogger` sees the - whole call wherever it is); -- each retry gets its own timeout, and asks for the token again; -- a timed-out attempt isn't retried; -- `retry`'s `budget` covers every attempt and wait, while `timeout` covers - one attempt; -- a `401` that `bearer` refreshes is sent again inside the same attempt, so - it shares that attempt's timeout. - -For when each hook runs in that order, see the hooks table in -[Write a plugin](/docs/plugins/writing). diff --git a/site/content/docs/(latest)/plugins/per-call.mdx b/site/content/docs/(latest)/plugins/per-call.mdx index f1d4855..8211753 100644 --- a/site/content/docs/(latest)/plugins/per-call.mdx +++ b/site/content/docs/(latest)/plugins/per-call.mdx @@ -5,12 +5,14 @@ description: Turn off or adjust a client's plugin for one call. A client's plugins run on every call, but some calls need something different: a login that sends no token, or a slow export that needs more -time. This page shows how to change a client's plugins for one call. +time. Rather than build a second client for them, you change the plugins for +that one call. This page shows how, and how a call's changes combine with +the plugin's defaults and with an endpoint's. ## Skip or adjust a plugin -Any call can skip a plugin with `false`, and plugins with options take part of -them. TypeScript checks the plugin names and the option types: +Pass `plugins` in the call's options, keyed by the plugin's name. `false` +skips that plugin, and an object changes some of its options: ```ts import * as Effect from "effect/Effect"; @@ -43,8 +45,30 @@ export const program = Effect.gen(function* () { }); ``` -To see what each built-in plugin accepts per call, see the **Per call** column -in [Built-in plugins](/docs/plugins). +TypeScript checks the plugin names and the option types, so a misspelled +name or a wrong option doesn't compile. Each plugin decides which options a +call can change. To see what each built-in plugin accepts, see the +**Per call** column in [Built-in plugins](/docs/plugins#what-each-plugin-does). +A plugin you write accepts any of the options in its `defaults` (see +[Write a plugin](/docs/plugins/writing)). + +## How a call's changes apply + +A call's changes combine with the rest as follows: + +- **Options you leave out keep their defaults.** A call that passes + `{ consoleLogger: { detail: "summary" } }` changes `detail` only, and + keeps the other settings. A key + whose value is `undefined` at runtime keeps its default too, rather than + replacing it with `undefined`. +- **`false` skips the whole plugin.** Its `wrap`, `onRequest` and + `onResponse` don't run for that call, and neither do its `onError` and + `onExit`. A skipped `consoleLogger` prints nothing, for example. +- **A call's changes go on top of an endpoint's.** When you bind an + endpoint with `plugins` overrides, a call to it can pass its own. For each + plugin, the call's value wins, and when both are option objects they're + merged, key by key. See + [Call an endpoint](/docs/endpoints/calling). ## What's next diff --git a/site/content/docs/(latest)/plugins/recipes.mdx b/site/content/docs/(latest)/plugins/recipes.mdx index 495c464..1d844d5 100644 --- a/site/content/docs/(latest)/plugins/recipes.mdx +++ b/site/content/docs/(latest)/plugins/recipes.mdx @@ -3,15 +3,17 @@ title: Plugin recipes description: Copy a plugin that signs out on a 401, or one that sets a deadline with its own error. --- -These plugins solve common problems, and you can copy them into your app. -Each one shows a different part of the plugin API: hooks that need a service -and add an error, and a `wrap` with an option calls can override. +Some plugins come up in almost every app, and you can copy these two into +yours. Each one also shows a different part of the plugin API: hooks that +need a service and add an error, and a `wrap` with an option that calls can +override. ## Sign out on a 401 -The classic plugin: send the session's token, and when the API answers `401`, -sign out and fail with a typed `SessionExpired`. To renew the token instead, -see [Refresh a token](/docs/plugins/token-refresh). +When the API answers `401` to a request that carried the session's token, +the session is over. This plugin sends the session's token, and on such a +`401`, signs out and fails with a typed `SessionExpired`. To renew the token +instead, see [Refresh a token](/docs/plugins/token-refresh). The plugin reads the token from a `Session` service in `onRequest`, and signs out in `onResponse`: @@ -20,6 +22,7 @@ signs out in `onResponse`: import * as Context from "effect/Context"; import * as Data from "effect/Data"; import * as Effect from "effect/Effect"; +import * as Headers from "effect/http/Headers"; import * as HttpClientRequest from "effect/http/HttpClientRequest"; import { Fetch } from "@monarcode/effetch"; @@ -46,7 +49,8 @@ export const auth = Fetch.plugin({ }), onResponse: (response) => Effect.gen(function* () { - if (response.status !== 401) { + const sentToken = Headers.has(response.request.headers, "authorization"); + if (response.status !== 401 || !sentToken) { return response; } const session = yield* Session; @@ -55,16 +59,25 @@ export const auth = Fetch.plugin({ }), }); -// Api.layer now needs Session; calls fail with SessionExpired too. +// Api.layer needs Session, and calls can fail with SessionExpired too. export class Api extends Fetch.Service()("Api", { baseUrl: "https://api.example.com", plugins: [auth], }) {} ``` +The plugin signs out only when the refused request carried a token, as +`bearer` checks before it refreshes. A request sent without one, such as a +login with the wrong password while signed out, gets its `401` back as +usual. To keep the plugin off a call entirely, pass +`plugins: { auth: false }`. + ## Set a deadline with its own error -A `wrap` that adds its own error, with an option calls can override: +`timeout` and `retry`'s `budget` both fail with `TimeoutError`. When one +kind of slow call should fail with an error of its own, with its own fields, +so you can catch it apart from every other timeout, write a `wrap` that adds +that error: ```ts import * as Data from "effect/Data"; @@ -93,6 +106,50 @@ export const deadline = Fetch.plugin({ }); ``` +Like `timeout`, the deadline covers only the plugins after it in the list +and the network, up to the response headers. Reading the body isn't +covered. Put it first to cover every retry, or after `retry` to limit each +attempt. + +A call can change the deadline, because the plugin has `defaults`: + +```ts +import * as Data from "effect/Data"; +import * as Effect from "effect/Effect"; +import * as HttpClient from "effect/http/HttpClient"; + +import { Fetch } from "@monarcode/effetch"; + +class TooSlow extends Data.TaggedError("TooSlow")<{ readonly url: string }> {} + +const deadline = Fetch.plugin({ + name: "deadline", + defaults: { millis: 5000 }, + wrap: (client, options) => + HttpClient.transform(client, (response, request) => + Effect.gen(function* () { + const { millis } = yield* options; + return yield* Effect.timeoutOrElse(response, { + duration: millis, + orElse: () => Effect.fail(new TooSlow({ url: request.url })), + }); + }), + ), +}); + +class Api extends Fetch.Service()("Api", { + baseUrl: "https://api.example.com", + plugins: [deadline], +}) {} + +export const report = Effect.gen(function* () { + const api = yield* Api; + return yield* api.get("/reports/export", { + plugins: { deadline: { millis: 30_000 } }, + }); +}).pipe(Effect.catchTag("TooSlow", () => Effect.succeed(undefined))); +``` + ## What's next - [Write a plugin](/docs/plugins/writing): learn the hooks these recipes use. diff --git a/site/content/docs/(latest)/plugins/retry-after.mdx b/site/content/docs/(latest)/plugins/retry-after.mdx index 7a7247b..6aa538b 100644 --- a/site/content/docs/(latest)/plugins/retry-after.mdx +++ b/site/content/docs/(latest)/plugins/retry-after.mdx @@ -1,27 +1,94 @@ --- title: Retry-After and a time limit -description: Honor a Retry-After header without going past a deadline. +description: Honor a Retry-After header, and limit how long each attempt and the whole call may take. --- -Overloaded or slow servers can ask you to wait, or take too long to answer. -This page shows how to make `retry` wait as a server asks, and how to limit -the time a whole call may take. +A server that's overloaded can ask you to wait before you try again, and a +slow one can keep a call waiting far longer than your app should. `retry` +and `timeout` handle both: `retry` can wait as long as the server asks, and +the two plugins set time limits on each attempt and on the whole call. This +page shows how to use each limit, how to combine them, and what they don't +cover. -## Retry options for overloaded or slow servers +## Wait as Retry-After asks -`retry` has two options for servers that are overloaded or slow: +To wait as long as a server's `Retry-After` header asks, in place of the +retry schedule's delay, pass `retryAfter`: -- `retryAfter`: when a retried response has a `Retry-After` header, wait as - long as it asks (`Retry-After: 120`, or an HTTP date) in place of the - schedule's delay. `true` waits up to 1 minute, and `{ max }` up to `max`. - It's off by default, so a server can't make calls wait. -- `budget`: how long the whole call may take, every attempt and wait - included. No retry is made when its wait would end at or after the budget: - the call ends with its last response or `NetworkError`. When the budget runs - out during an attempt, the attempt is aborted, and the call fails with - `TimeoutError`. Calls can override it. +```ts +import { Fetch } from "@monarcode/effetch"; +import { retry } from "@monarcode/effetch/plugins"; + +export class Api extends Fetch.Service()("Api", { + baseUrl: "https://api.example.com", + plugins: [retry({ times: 5, retryAfter: { max: "30 seconds" } })], +}) {} +``` + +`retryAfter: true` waits up to 1 minute, and `{ max }` up to `max`. It's +off by default, so a server can't make your calls wait unless you allow it. + +`retry` reads the header from a response it's about to retry, such as a +`429` or `503`. The header can hold whole seconds (`Retry-After: 120`) or an +HTTP date. Each case works as follows: + +- With no header, or one that `retry` can't read, the schedule's delay is + kept. +- A date in the past retries at once. +- A wait longer than the cap is cut to the cap. The retry still happens. + +## Limit each attempt with timeout + +`timeout` fails an attempt with a `TimeoutError`, and aborts its request, +when the response headers don't arrive in time. Put it after `retry`, so +each attempt gets the full duration: + +```ts +import { Fetch } from "@monarcode/effetch"; +import { retry, timeout } from "@monarcode/effetch/plugins"; + +export class Api extends Fetch.Service()("Api", { + baseUrl: "https://api.example.com", + plugins: [retry(), timeout({ duration: "10 seconds" })], +}) {} +``` + +In that position, the limit is per attempt, and an attempt that times out +isn't retried: the call fails with the `TimeoutError`. Placed before `retry`, +one `timeout` would cover every attempt and wait together. To limit the +whole call, use a budget instead, which the next section shows. + +## Limit the whole call with a budget + +To limit how long the whole call may take, every attempt and every wait +between them included, give `retry` a `budget`: -## Limit each attempt and the whole call +```ts +import { Fetch } from "@monarcode/effetch"; +import { retry } from "@monarcode/effetch/plugins"; + +export class Api extends Fetch.Service()("Api", { + baseUrl: "https://api.example.com", + plugins: [retry({ times: 5, retryAfter: true, budget: "30 seconds" })], +}) {} +``` + +The budget works as follows: + +- **A retry that wouldn't fit isn't made.** When the wait before the next + retry would end at or after the budget, `retry` stops there. The call ends + as it does when the retries run out: with the last response, or the last + `NetworkError`. +- **An attempt that runs out of budget is aborted.** The call then fails + with a `TimeoutError`, the same class `timeout` uses. +- **Calls that aren't retried are limited too,** such as a `POST`, or a call + with `times: 0`. + +The budget ends when the last response's headers arrive. Like `timeout`, it +doesn't cover reading the body (see +[What the limits don't cover](#what-the-limits-dont-cover)). + +## Combine a per-attempt and a whole-call limit For "10 seconds per attempt, 30 seconds in all", use both `timeout` and a budget: @@ -37,14 +104,109 @@ export class Api extends Fetch.Service()("Api", { timeout({ duration: "10 seconds" }), ], }) {} +``` + +Both fail with a `TimeoutError` from `@monarcode/effetch/plugins`. It has the +request's `method`, its `url` without the query string, and the `duration` +that ran out, formatted, such as `"10s"` or `"30s"`. + +## Give one call a different limit + +A call can change either limit in its `plugins` option: + +```ts +import * as Effect from "effect/Effect"; + +import { Fetch } from "@monarcode/effetch"; +import { retry, timeout } from "@monarcode/effetch/plugins"; + +class Api extends Fetch.Service()("Api", { + baseUrl: "https://api.example.com", + plugins: [ + retry({ times: 5, budget: "30 seconds" }), + timeout({ duration: "10 seconds" }), + ], +}) {} + +export const report = Effect.gen(function* () { + const api = yield* Api; + return yield* api.get("/report", { + plugins: { + retry: { budget: "2 minutes" }, + timeout: { duration: "1 minute" }, + }, + }); +}); +``` + +A call can override the budget only when the client's `retry` has one. A +plain `retry()` takes only `{ times }` per call, and TypeScript rejects a +`budget`. To let calls set a budget without one for every call, pass a +`budget` whose type is `Duration.Input | undefined`, such as a value from +your config: + +```ts +import type * as Duration from "effect/Duration"; + +import { Fetch } from "@monarcode/effetch"; +import { retry } from "@monarcode/effetch/plugins"; + +declare const config: { readonly budget: Duration.Input | undefined }; + +export class Api extends Fetch.Service()("Api", { + baseUrl: "https://api.example.com", + plugins: [retry({ budget: config.budget })], +}) {} // Per call: api.get("/report", { plugins: { retry: { budget: "2 minutes" } } }) ``` +When the value is `undefined`, there's no limit until a call sets one. A +literal `budget: undefined` doesn't work for this: TypeScript reads it as a +plain `retry()`. + +## What the limits don't cover + +`timeout` and the budget both stop when the response headers arrive. Reading +and decoding the body come after that, so a large response that starts in +time isn't cut off while it downloads. For a stream from `api.sse` or +`api.ndjson`, they cover getting the response, and the stream then runs +without a limit. + +To cap the whole call, the body included, wrap a call that decodes its body +in `Effect.timeout`: + +```ts +import * as Effect from "effect/Effect"; +import * as Schema from "effect/Schema"; + +import type { Fetch } from "@monarcode/effetch"; + +declare const api: Fetch.Client; + +const Report = Schema.Struct({ rows: Schema.Array(Schema.String) }); + +export const report = api + .get("/report", { output: Report }) + .pipe(Effect.timeout("1 minute")); +``` + +The cap covers the body because the call reads it: with `output`, the call +ends after decoding. A call without `output` returns the response when the +headers arrive, so its timeout ends there too. + +`Effect.timeout` interrupts the call, which aborts its request, and fails +with Effect's own `TimeoutError`, from `effect/Cause`. That error has the +same `"TimeoutError"` tag as Effetch's, but no `method`, `url` or +`duration`, so `Effect.catchTag("TimeoutError", …)` catches both. On a +client without `retry`, `Effect.timeout` is also the way to limit one call +in all. + ## What's next - [Change plugins for one call](/docs/plugins/per-call): give one call a - longer budget or timeout. -- [Plugin order](/docs/plugins/order): see why `timeout` goes after `retry`. -- [Built-in plugins](/docs/plugins): see every option `retry` and `timeout` - take. + longer budget or timeout, or skip `retry`. +- [Built-in plugins](/docs/plugins#how-plugins-nest): see why `timeout` goes + after `retry`. +- [Catch errors](/docs/errors/catching): handle a `TimeoutError` where you + make the call. diff --git a/site/content/docs/(latest)/plugins/token-refresh.mdx b/site/content/docs/(latest)/plugins/token-refresh.mdx index 4fd69e0..8d2a78d 100644 --- a/site/content/docs/(latest)/plugins/token-refresh.mdx +++ b/site/content/docs/(latest)/plugins/token-refresh.mdx @@ -3,14 +3,16 @@ title: Refresh a token description: Renew an expired access token with the bearer plugin and send the request again. --- -To renew an expired access token without failing the call, give `bearer` a -`refresh`. This page shows how to set it up and how refreshing behaves. +Access tokens expire, often in the middle of a session, and a call made with +an expired one gets a `401`. Rather than fail that call, `bearer` can get a +new token and send the request again. This page shows how to set that up, +and how refreshing behaves when several calls are refused at the same time. ## Add a refresh function -When a request that `bearer` signed gets a `401`, `bearer` asks `refresh` for -a new token, then sends the request again with it. Pass `refresh` next to -`token`: +When a request that `bearer` sent a token with gets a `401`, `bearer` asks +`refresh` for a new token, then sends the request again with it. Pass +`refresh` next to `token`: ```ts import { Fetch } from "@monarcode/effetch"; @@ -29,36 +31,102 @@ export class Api extends Fetch.Service()("Api", { }) {} ``` -The new token is used for that request only. Store it where `token` reads it, -so later requests send it too. To sign out instead, see the -[Sign out on a 401](/docs/plugins/recipes#sign-out-on-a-401) recipe. +`refresh` gets the refused request, as it was sent, with its +`Authorization` header. Like `token`, it can be a function, sync or async, or +an Effect, whose error and services become the client's. + +`bearer` uses the new token for that request only. Have `refresh` store it +where `token` reads it, so later requests send it too. + +## Make the refresh call skip bearer + +When `refresh` is a function that runs your client to get the new token, the +refresh call must skip `bearer` with `plugins: { bearer: false }`. `bearer` +can't tell that call apart from any other, so without it, a `401` to the +refresh call would wait for the refresh it's part of, and never end: + +```ts +import * as Effect from "effect/Effect"; +import * as FetchHttpClient from "effect/http/FetchHttpClient"; +import * as Layer from "effect/Layer"; +import * as ManagedRuntime from "effect/ManagedRuntime"; +import * as Schema from "effect/Schema"; + +import { Fetch } from "@monarcode/effetch"; +import { bearer } from "@monarcode/effetch/plugins"; + +declare const tokens: { + readonly access: () => string | undefined; + readonly refresh: () => string | undefined; + readonly save: (access: string) => void; +}; + +const Renewed = Schema.Struct({ accessToken: Schema.String }); + +export class Api extends Fetch.Service()("Api", { + baseUrl: "https://api.example.com", + plugins: [bearer({ token: () => tokens.access(), refresh: () => renew() })], +}) {} + +const runtime = ManagedRuntime.make( + Api.layer.pipe(Layer.provide(FetchHttpClient.layer)), +); + +function renew(): Promise { + return runtime.runPromise( + Effect.gen(function* () { + const api = yield* Api; + const { accessToken } = yield* api.post("/auth/refresh", { + body: { refreshToken: tokens.refresh() }, + output: Renewed, + plugins: { bearer: false }, + }); + tokens.save(accessToken); + return accessToken; + }).pipe(Effect.orElseSucceed(() => undefined)), + ); +} +``` + +When the refresh call fails, such as when the refresh token has expired too, +`renew` gives `undefined`, so the original call ends with its `401`. A +promise that rejects would make the call die instead. + +An Effect `refresh` can't hang this way: calls made inside it never +refresh. Skipping `bearer` there still keeps the expired token off the +refresh call. ## How refreshing behaves +Refreshing follows these rules when calls are refused, fail or are sent +again: + -- `refresh` is a function of the refused request, as it was sent, sync or - async, or an Effect. Like `token`, an Effect's error and services become - the client's. -- Calls refused with the same token share one refresh, so the token is - renewed once, and they all get its token or its error. Calls refused with - different tokens, such as other users' on a server, get their own. -- A call that times out or is interrupted while it waits doesn't cancel the - refresh for the others. -- The request is sent again once. If the new token is refused too, the call - ends with that `401`. -- When `refresh` gives `null`, `undefined` or `""`, such as when the session - has ended, the call ends with the `401`, and nothing more is sent. -- A request with its own `Authorization` header, sent without a token, or - with a stream body, which can't be sent twice, isn't refreshed. Neither is - a call that skips `bearer`. -- Make the refresh call itself skip `bearer`: `plugins: { bearer: false }`. - Calls made inside an Effect `refresh` never refresh, but a function that - runs the client with `Effect.runPromise` can't be told apart: a `401` to - it would wait for the refresh it's part of. -- Every method is sent again, a `POST` included: a `401` means the server - didn't act on the request. +- **Calls refused together share one refresh.** Calls refused with the same + token, and sent before its refresh ended, share that refresh: `refresh` + runs once for all of them, and they all get its token, or its error. A + call refused later with the same token starts a new refresh, which happens + when `refresh` doesn't store the token where `token` reads it. +- **Different tokens refresh apart.** Calls refused with different tokens, + such as other users' on a server, get their own refresh. +- **One caller can't cancel it for the others.** The shared refresh runs on + its own. A call that times out or is interrupted while it waits stops + waiting, but the refresh carries on for the others. +- **The request is sent again once.** If the new token is refused too, + the call ends with that `401`, which fails as any other `401` does. +- **No token means no retry.** When `refresh` gives `null`, `undefined` or + `""`, such as when the session has ended, the call ends with the `401`, + and nothing more is sent. +- **Some requests aren't refreshed:** a request that came with its own + `Authorization` header, one sent without a token, and one with a stream + body, which can't be sent twice. Neither is a call that skips `bearer`. +- **Every method is sent again,** a `POST` included: a `401` means the + server refused the request before acting on it. +- **A throw is a defect.** A `refresh` function that throws, or whose + promise rejects, makes the call die. To fail with a typed error, pass an + Effect. @@ -67,7 +135,7 @@ so later requests send it too. To sign out instead, see the - [Plugin recipes](/docs/plugins/recipes): sign out and fail with a typed error on a `401`, in place of refreshing. -- [Change plugins for one call](/docs/plugins/per-call): make the refresh - call skip `bearer`. -- [Plugin order](/docs/plugins/order): see how a refreshed request shares its - attempt's timeout. +- [Change plugins for one call](/docs/plugins/per-call): skip `bearer` on + other calls, such as a login. +- [Built-in plugins](/docs/plugins#how-plugins-nest): see how a refreshed + request shares its attempt's timeout. diff --git a/site/content/docs/(latest)/plugins/writing.mdx b/site/content/docs/(latest)/plugins/writing.mdx index fe3fddd..6f0ac23 100644 --- a/site/content/docs/(latest)/plugins/writing.mdx +++ b/site/content/docs/(latest)/plugins/writing.mdx @@ -1,17 +1,23 @@ --- title: Write a plugin -description: Build a first plugin, then learn the hooks and how a plugin knows the route. +description: Build a first plugin step by step, then look up the hooks and how a plugin reads the route. --- -When the built-in plugins don't cover what you need, write your own. The -built-in ones are written with the same API. In this tutorial, you write a -plugin that pins the API version on every request, then learn the hooks a -plugin can use and how it knows which route a call is for. +When the built-in plugins don't cover what you need, such as a header your +API asks for on every request, write your own. The built-in plugins are +written with the same API. In this tutorial, you write a plugin that pins +the API version on every request and check that it works. After that, the +page describes every hook a plugin can use, and how a plugin reads which +route a call is for. ## Write your first plugin -A plugin is a name and one or more hooks. This one pins the API version on -every request, with an option that a call can change: +The plugin you build sends an `api-version` header with every request, with +a default version that one call can change. It takes four steps. + +### Step 1: Define the plugin + +A plugin is a name and one or more hooks. Create it with `Fetch.plugin`: ```ts import * as Effect from "effect/Effect"; @@ -27,6 +33,64 @@ export const apiVersion = Fetch.plugin({ HttpClientRequest.setHeader(request, "api-version", ctx.options.version), ), }); +``` + +The `onRequest` hook runs before each request is sent, and returns the +request to send. `ctx.options` holds the plugin's `defaults`, merged with +the call's changes, if it made any. A plugin needs `defaults` to take +options at all. + +`Fetch.plugin` infers the plugin's name, options, errors and services from +what you give it. Calls can then change `apiVersion` by name, and TypeScript +checks their options. + +### Step 2: Add it to a client + +List the plugin in the client's `plugins` option, as you would a built-in +one: + +```ts +import * as Effect from "effect/Effect"; +import * as HttpClientRequest from "effect/http/HttpClientRequest"; + +import { Fetch } from "@monarcode/effetch"; + +const apiVersion = Fetch.plugin({ + name: "apiVersion", + defaults: { version: "2024-06-01" }, + onRequest: (request, ctx) => + Effect.succeed( + HttpClientRequest.setHeader(request, "api-version", ctx.options.version), + ), +}); + +export class Api extends Fetch.Service()("Api", { + baseUrl: "https://api.example.com", + plugins: [apiVersion], +}) {} +``` + +Every call the client makes sends `api-version: 2024-06-01`. + +### Step 3: Change it for one call + +A call changes the plugin's options in its `plugins` option, under the +plugin's name: + +```ts +import * as Effect from "effect/Effect"; +import * as HttpClientRequest from "effect/http/HttpClientRequest"; + +import { Fetch } from "@monarcode/effetch"; + +const apiVersion = Fetch.plugin({ + name: "apiVersion", + defaults: { version: "2024-06-01" }, + onRequest: (request, ctx) => + Effect.succeed( + HttpClientRequest.setHeader(request, "api-version", ctx.options.version), + ), +}); class Api extends Fetch.Service()("Api", { baseUrl: "https://api.example.com", @@ -41,40 +105,119 @@ export const program = Effect.gen(function* () { }); ``` -`Fetch.plugin` infers the plugin's name, options, errors and services from -what you give it, so calls can override `apiVersion` by name, and their -options are checked. `ctx.options` is the plugin's `defaults` merged with the -call's override, so a plugin needs `defaults` to take options. +### Step 4: Check that it sends the header -## Hooks +To check the header without a server, run two calls against the fake +backend from `@monarcode/effetch/test`, and print the header each request +carried: -A plugin can define any of the following hooks: +```ts +import * as Effect from "effect/Effect"; +import * as HttpClientRequest from "effect/http/HttpClientRequest"; +import * as Layer from "effect/Layer"; -| Hook | Runs | -| ------------------------------ | -------------------------------------------------------------------------------------------------------------------------------------------- | -| `onRequest(request, ctx)` | Before the request is sent, in array order. Returns the request to send, or fails. It sees the full URL and the client's headers. | -| `onResponse(response, ctx)` | On every response, non-2xx included, in reverse order. Returns the response, or fails. The status check and decoding come after all plugins. | -| `onError(error, ctx)` | After a call fails or dies, in array order. It can't change the outcome. | -| `onExit(exit, ctx)` | After every call, whatever the outcome, in array order, after `onError`. It can't change the outcome. | -| `wrap(client, options, route)` | Wraps the plugins after it and the network, for retries, timeouts and the like. It can add errors but can't remove them. | +import { Fetch } from "@monarcode/effetch"; +import { FetchTest } from "@monarcode/effetch/test"; -`ctx.request` is the request: in `onResponse`, the one this plugin passed on; -in `onError` and `onExit`, the one the call built. +const apiVersion = Fetch.plugin({ + name: "apiVersion", + defaults: { version: "2024-06-01" }, + onRequest: (request, ctx) => + Effect.succeed( + HttpClientRequest.setHeader(request, "api-version", ctx.options.version), + ), +}); -### Record every call with onExit +class Api extends Fetch.Service()("Api", { + baseUrl: "https://api.test", + plugins: [apiVersion], +}) {} -`onExit` gets the call's `Exit`: its result (the decoded `output`, or the -response for a call without one), or the cause of its failure, defect or -interruption. Its `ctx` also has: +const getReports = Fetch.endpoint("GET /reports"); -- `response`: the one the plugins returned; when a plugin failed after a - response arrived, the last one the network sent; `undefined` when none - arrived; -- `durationMs`: the time from sending the request to decoding the body, - retries included. +const Backend = FetchTest.layer([ + FetchTest.respond(getReports, () => Effect.void), +]); -It suits logging and metrics, and is what `consoleLogger` uses. This plugin -records each call's route, outcome and duration: +const program = Effect.gen(function* () { + const api = yield* Api; + yield* api.get("/reports"); + yield* api.get("/reports", { + plugins: { apiVersion: { version: "2025-01-01" } }, + }); + for (const sent of yield* FetchTest.requests) { + console.log(sent.headers["api-version"]); + } +}).pipe(Effect.provide(Api.layer.pipe(Layer.provideMerge(Backend)))); + +Effect.runPromise(program); +``` + +It prints the default version for the first call, and the call's own for the +second: + +```text +2024-06-01 +2025-01-01 +``` + +To learn more about the fake backend, see +[Test with a fake backend](/docs/testing). + +## Hook reference + +The rest of this page describes what a plugin can do: each hook, when it +runs, and what it receives. + +### When each hook runs + +A plugin can define any of the following hooks: + +| Hook | When it runs | What it can do | +| ------------------------------ | --------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------- | +| `onRequest(request, ctx)` | Before the request is sent, in list order. It has the full URL and the client's headers. | Return the request to send, changed or not, or fail. | +| `onResponse(response, ctx)` | On every response, non-2xx included, in reverse list order. The status check and decoding come after every plugin's `onResponse`. | Return the response, changed or not, or fail. | +| `wrap(client, options, route)` | Around its own `onRequest` and `onResponse`, every plugin after it and the network. A retrying `wrap` runs all of them on each attempt. | Retry, time out and the like. It can add errors, but can't remove them. | +| `onError(error, ctx)` | After a call fails or dies, in list order, after the status check and decoding. | Observe only: it can't change the outcome. | +| `onExit(exit, ctx)` | After every call, whatever the outcome, in list order, after the `onError` hooks. | Observe only: it can't change the outcome. | + +To see the order the hooks of several plugins run in, see +[How plugins nest](/docs/plugins#how-plugins-nest). + +`ctx.request` is a different request in each hook: + +- in `onRequest`, the request the hook receives; +- in `onResponse`, the one this plugin passed on. Plugins after it may have + changed it further, and `response.request` is the one that was sent; +- in `onError` and `onExit`, the request as the call built it, before any + plugin ran. + +`onError`'s `error` is the call's error: an Effetch error such as +`HttpError`, another plugin's error, one of the call's `statusErrors`, or a +defect. + + + + +- Neither runs when the call dies before its request is built, such as for + a missing path parameter or a body that can't be encoded. Neither runs for + requests sent through `api.httpClient`, or for a plugin that the call + skips with `false`. +- `onError` doesn't run when the call is interrupted, since that isn't a + failure. `onExit` does, with the interruption in its `Exit`. +- For a stream (`api.sse`, `api.ndjson` or a stream endpoint), the call ends + when the response headers arrive. `onExit` runs then. Neither hook runs for + the body being read, or for a `DecodeError` while it's read. +- Neither hook can fail. If one dies, the defect is logged at the Debug + level and ignored. + + + + +### Record every call with onExit + +`onExit` suits logging and metrics, and is what `consoleLogger` uses. This +plugin records each call's route, outcome and duration: ```ts import * as Effect from "effect/Effect"; @@ -91,8 +234,24 @@ export const metrics = Fetch.plugin({ }); ``` -The call returns once every `onExit` hook is done, so keep them quick, and -fork anything slow. +The hook gets the call's `Exit`. On success, it holds the call's result: the +decoded `output`, or the response for a call without one. With +`responseMode: "decoded-and-response"`, it holds a pair of both. Otherwise, +it holds the cause of the call's failure, defect or interruption. + +Besides `request`, `options` and `route`, its `ctx` has: + +- `response`: the response the plugins returned. When a plugin failed after + a response arrived, it's the last one the network sent, whose body may not + have been read. It's `undefined` when no response arrived: after a network + failure, a timeout, or a plugin that failed before the request was sent. +- `durationMs`: how long the call took, in whole milliseconds, retries + included. It starts when the request enters the plugin chain, so + `onRequest` hooks, such as reading a token, count. It stops after the + status is checked and the body decoded, so `onError` hooks don't count. + +The call returns after every `onExit` hook is done, and the hooks can't be +interrupted. Keep them quick, and fork anything slow. ## Read the route @@ -100,7 +259,7 @@ fork anything slow. filled in: `"GET /users/:id"`, whether the call was `api.get("/users/:id", …)` or an [endpoint](/docs/endpoints). It's the same for every user ID, so it's what to group logs, metrics and error reports by. -It's `undefined` for requests sent through `client.httpClient`. +It's `undefined` for requests sent through `api.httpClient`. A `wrap` reads it from its third argument, an Effect like `options`. The following example reads the route in an `onError` hook and in a `wrap`: @@ -134,20 +293,22 @@ export const timing = Fetch.plugin({ Keep these rules in mind as you write plugins: -- Services a plugin needs are required once, by the client's layer (or by - `Fetch.make`). Calls don't need them. Services provided around a call win - over those the client was built with. -- Plugin names must be unique. -- Write `wrap` bodies with `Effect.gen`. A ternary that returns two different - Effects can't be typed. -- Pass plugin lists inline, or let TypeScript infer them. Annotating a list as - `Fetch.Plugin.Any[]` erases the plugins' types. +- **Services are required once.** The services a plugin needs are + required by the client's layer (or `Fetch.make`), not by each call. + Services provided around a call win over those the client was built with. +- **Names are unique within a client.** If two plugins have the same name, + building the client dies (with `Fetch.make` or the client's layer), with + the message `Two plugins are named "…"`. +- **Write `wrap` bodies with `Effect.gen`.** A ternary that returns two + different Effects can't be typed. +- **Pass plugin lists inline, or let TypeScript infer them.** Annotating a + list as `Fetch.Plugin.Any[]` erases the plugins' types. ## What's next - [Plugin recipes](/docs/plugins/recipes): copy a plugin that signs out on a `401`, or one that sets a deadline with its own error. -- [Plugin order](/docs/plugins/order): decide where your plugin goes in the - list. +- [Built-in plugins](/docs/plugins#how-plugins-nest): decide where your + plugin goes in the list. - [Change plugins for one call](/docs/plugins/per-call): skip or adjust your plugin on a single call. diff --git a/site/content/docs/(latest)/reference/compatibility.mdx b/site/content/docs/(latest)/reference/compatibility.mdx index dd7c1fd..0efccc9 100644 --- a/site/content/docs/(latest)/reference/compatibility.mdx +++ b/site/content/docs/(latest)/reference/compatibility.mdx @@ -1,63 +1,82 @@ --- title: Compatibility -description: The Effect versions, runtimes and TypeScript settings Effetch supports and is tested with. +description: The Effect versions, runtimes and TypeScript versions Effetch supports, and which of them CI tests. --- -Check this page before you upgrade Effect, or to see whether your runtime -and TypeScript settings are supported. +Before you upgrade Effect, or add Effetch to a project on an unusual +runtime, check here. This page lists what Effetch supports, and keeps what +CI tests separate from what Effetch is built for but CI doesn't test. ## Effect Effetch has one peer dependency, `effect`, in the range `^4.0.0`. Install it next to Effetch, as [Installation](/docs/installation) shows. -CI tests two versions in the range: +CI tests two versions in that range: -- The full check (types, tests, the build and the installed package) runs - with the `effect` version pinned in Effetch's own `devDependencies`, - which can be older than the newest 4.x. -- A second job typechecks, tests and builds with `effect` 4.0.0, the oldest - version in the range. +- **The full check** runs with the `effect` version pinned in Effetch's own + `devDependencies`, which can be older than the newest 4.x. It covers + types, tests, the build and the installed package. +- **A second job** typechecks, tests and builds with `effect` 4.0.0, the + oldest version in the range. + +One feature needs Effect 4.1. From 4.1 on, a query value can be `Redacted`: +it's sent as its value, and Effect keeps it out of its own logs. On 4.0, +the query type doesn't accept a `Redacted` value, and one forced in with a +cast is sent as the text ``. ## Runtimes -Effetch runs wherever Effect's `HttpClient` does: browsers, React Native -(with Hermes and Metro), Node.js 20 and newer, Bun and Deno. Its code uses -no Node.js modules or globals, and joins URLs as strings rather than with -the `URL` constructor. +Effetch is plain TypeScript with no platform-specific code: no Node.js +modules, no Node.js globals and no separate builds. Requests go through the +`HttpClient` you provide, so most of what a runtime needs comes from that +client. `FetchHttpClient.layer`, for example, uses the global `fetch`. + +The following table shows where Effetch is built to run, and which runtimes +CI tests: -Effetch sends requests through the `HttpClient` you provide, so what your -runtime needs depends on that client. `FetchHttpClient.layer` uses the -global `fetch`. For what differs in browsers and React Native, see -[Platform notes](/docs/platforms). +| Runtime | Tested in CI | +| ----------------------------------- | ------------------------------------------ | +| Node.js 24 | Yes: the tests and the installed package | +| Node.js 20 and 22 | No. The build targets ES2020. | +| Browsers | No. See [Platform notes](/docs/platforms). | +| React Native, with Hermes and Metro | No. See [Platform notes](/docs/platforms). | +| Bun and Deno | No | -CI runs the tests and the installed package on Node.js 24. +Effetch builds every URL as a string and never calls `new URL()` itself, +since React Native's `URL` is incomplete. Effect's `HttpClient` does use +`URL` when it sends a request, and so does an endpoint's `url` helper. For +what that means on React Native, see +[Platform notes](/docs/platforms#react-native). ## Modules -The package is ESM only, and marks itself as free of side effects -(`"sideEffects": false`), so bundlers drop what you don't import. Its +The package is ESM only. It marks itself as free of side effects +(`"sideEffects": false`), so bundlers drop what you don't import, and its `exports` map has a `types` and a `default` condition for each entry point. ## TypeScript -Effetch needs TypeScript 5.4 or newer. With `skipLibCheck: false`, Effect's -own declarations need TypeScript 5.7 or newer. +Effetch needs TypeScript 5.7 or later. Its declarations use typed arrays +with a type argument, such as `Uint8Array`, which older +versions reject. With `skipLibCheck: true`, TypeScript 5.4 to 5.6 compile +a project that uses Effetch, but some of its types, such as +`Fetch.bytes()`'s, quietly become `any`. -CI checks the types with TypeScript 6.0.3: +CI checks the types with TypeScript 6.0.3, in three ways: - A project that installs the packed package compiles under `NodeNext` and `Bundler` resolution, with `skipLibCheck: false`, and emits declaration files that name Effetch's types. -- Are the Types Wrong checks that the types resolve under Node.js's ESM - resolution and bundlers'. -- Effetch's tests, examples and the examples in these docs compile with - `exactOptionalPropertyTypes` and `noUncheckedIndexedAccess` on. The +- Are the Types Wrong checks that the types resolve for Node.js's ESM + resolution and for bundlers. +- Effetch's tests and examples, and the examples in these docs, compile + with `exactOptionalPropertyTypes` and `noUncheckedIndexedAccess` on. The installed-package project compiles with them off. ## What's next -- [Limitations](/docs/reference/limitations): the known limits of paths, - plugins and streams. -- [Platform notes](/docs/platforms): set up Effetch for browsers and React +- [Platform notes](/docs/platforms): set Effetch up for browsers and React Native. +- [Limitations](/docs/reference/limitations): check the known limits of + paths, plugins and streams. diff --git a/site/content/docs/(latest)/reference/fetch-test.mdx b/site/content/docs/(latest)/reference/fetch-test.mdx index d217a6f..49ab8d0 100644 --- a/site/content/docs/(latest)/reference/fetch-test.mdx +++ b/site/content/docs/(latest)/reference/fetch-test.mdx @@ -5,12 +5,16 @@ description: "Every member of the FetchTest namespace: the fake backend for test {/* Written by scripts/reference-docs.mjs from the JSDoc. Run `pnpm run docs:reference` after changing it; don't edit this page. */} -`@monarcode/effetch/test` exports one name, the `FetchTest` namespace. Its members: +`@monarcode/effetch/test` exports one name, the `FetchTest` namespace. Import it as follows: ```ts import { FetchTest } from "@monarcode/effetch/test"; ``` +Its exports follow, grouped by the guide that covers them. Each one has the +first paragraph of its docs, and what it needs and how it fails; your +editor shows the rest, with an example, when you hover the name. + ## Fake backend [#fake-backend] Guide: [Test with a fake backend](/docs/testing). @@ -19,6 +23,10 @@ Guide: [Test with a fake backend](/docs/testing). Makes a handler that answers every request to `endpoint` with the error status `status`, for [`layer`](#layer). To answer some requests with an error and others with data, return a [`reply`](#reply) from [`respond`](#respond) instead. +`body` is encoded as JSON with the first schema that encodes it: the endpoint's `statusErrors` schemas for `status`, then its `error` schema. So the client decodes it back into your domain error, or into `HttpError.body`. A definition made with `Fetch.endpoint` has no access to the client's `statusErrors` and `defaultError`, so without its own schemas, the body is sent by its runtime type (see [`reply`](#reply)). A body that no schema encodes is a defect. Without `body`, the response is empty. + +Throws when `endpoint` isn't one, `status` isn't from 300 to 599, or a `304` has a body. + ### FetchTest.layer [#layer] Makes a fake backend: an `HttpClient` layer that answers requests with `handlers`, without a network. Provide it where `FetchHttpClient.layer` goes, under a real client with its plugins, so a test runs the same code as production, schemas included. @@ -32,10 +40,16 @@ Makes a fake backend: an `HttpClient` layer that answers requests with `handlers Makes a response that a [`respond`](#respond) handler sends as it is, for any status: a `201` with a `location` header, a `404` for a missing item, a `500`. The body isn't checked against the endpoint's schemas. +Throws when the status isn't from 200 to 599, or when a `204`, `205` or `304` reply has a body. + ### FetchTest.respond [#respond] Makes a handler that answers `endpoint`'s requests with `handler`, for [`layer`](#layer). +The handler succeeds with a value of `output`'s `Type`, which is encoded with `output` before it's sent, so a `Date` goes over the wire as a string, as in production. With `Fetch.text()` or `Fetch.bytes()`, it's sent as text or bytes. A value that doesn't match `output` is a defect. Without `output`, the value is sent by its runtime type (see [`reply`](#reply)), and `undefined` sends no body. + +Throws when `endpoint` isn't one, or `options.status` isn't from 200 to 599. + ### FetchTest.FailBody [#failbody] The body [`fail`](#fail) takes for endpoint `EP` and status `S`: a value of the `statusErrors` schemas for `S`, or of the `error` schema. @@ -83,6 +97,18 @@ Options for a [`reply`](#reply) or a [`fail`](#fail) handler. name="ReplyOptions" /> +### FetchTest.RequestBody [#requestbody] + +The body a handler gets for route `R`, whose endpoint has the `input` schema `I`: + +- `undefined` for a route whose method takes no body, such as `GET`; +- the decoded body, typed by `I`, with an `input` schema; +- `unknown` otherwise: the JSON value for a JSON body, the text for a text or form body, the bytes for other bytes, the `FormData` or stream as it was sent, and `undefined` without a body. + +### FetchTest.RequestQuery [#requestquery] + +The query a handler gets: decoded with the endpoint's query schema `QS` when it has one, as the call gave it, and the raw [`QueryParams`](#queryparams) otherwise. + ### FetchTest.RespondOptions [#respondoptions] Options for the responses of a [`respond`](#respond) handler that aren't a [`Reply`](#reply-type). @@ -119,7 +145,7 @@ The path params a handler gets for route `R`: one key per `:param`, each a `stri ### FetchTest.TestEndpoint [#testendpoint] -An endpoint the fake backend can answer for: one made by `Fetch.endpoint`, `client.endpoint` or `client.bind`. The fake backend reads its route and its schemas. +An endpoint the fake backend can answer for: one made by `Fetch.endpoint`, `api.endpoint` or `api.bind`. The fake backend reads its route and its schemas. ### FetchTest.TestEvent [#testevent] @@ -142,17 +168,7 @@ The service that keeps the requests the fake backend received, in the order it r The requests the fake backend received so far, oldest first. -### FetchTest.RequestBody [#requestbody] - -The body a handler gets for route `R`, whose endpoint has the `input` schema `I`: - -- `undefined` for a route whose method takes no body, such as `GET`; -- the decoded body, typed by `I`, with an `input` schema; -- `unknown` otherwise: the JSON value for a JSON body, the text for a text or form body, the bytes for other bytes, the `FormData` or stream as it was sent, and `undefined` without a body. - -### FetchTest.RequestQuery [#requestquery] - -The query a handler gets: decoded with the endpoint's query schema `QS` when it has one, as the call gave it, and the raw [`QueryParams`](#queryparams) otherwise. +It needs the [`Recorder`](#recorder), which [`layer`](#layer) provides. Under a client's layer, `Layer.provide` hides it, so when a test reads it, provide the fake backend with `Layer.provideMerge` instead. ### FetchTest.SentRequest [#sentrequest] @@ -162,3 +178,10 @@ A request the fake backend received, as the [`Recorder`](#recorder) keeps it. path="node_modules/@monarcode/effetch/dist/test/FetchTest.d.ts" name="SentRequest" /> + +## Related pages + +- [Entry points](/docs/reference): what each entry point exports. +- [Fetch](/docs/reference/fetch): every member of the `Fetch` namespace. +- [Plugins](/docs/reference/plugins): the built-in plugins and their options. +- [Compatibility](/docs/reference/compatibility): the Effect, runtime and TypeScript versions Effetch supports. diff --git a/site/content/docs/(latest)/reference/fetch.mdx b/site/content/docs/(latest)/reference/fetch.mdx index f12146e..ef8d499 100644 --- a/site/content/docs/(latest)/reference/fetch.mdx +++ b/site/content/docs/(latest)/reference/fetch.mdx @@ -1,31 +1,41 @@ --- title: "Fetch" -description: "Every member of the Fetch namespace: clients, calls, errors, plugins, endpoints, streams and pages." +description: "Every member of the Fetch namespace: clients, calls, responses, uploads, errors, plugins, endpoints, streaming and pagination." --- {/* Written by scripts/reference-docs.mjs from the JSDoc. Run `pnpm run docs:reference` after changing it; don't edit this page. */} -`@monarcode/effetch` exports one name, the `Fetch` namespace. Its members, grouped by the guide that covers them: +`@monarcode/effetch` exports one name, the `Fetch` namespace. Import it as follows: ```ts import { Fetch } from "@monarcode/effetch"; ``` +Its exports follow, grouped by the guide that covers them. Each one has the +first paragraph of its docs, and what it needs and how it fails; your +editor shows the rest, with an example, when you hover the name. + ## Clients [#clients] Guide: [Declare a client](/docs/clients). -### Fetch.isService [#isservice] +### Fetch.Service [#service] -Returns `true` if `u` is a class made by [`Service`](#service), or a class that extends one. `false` for anything else, including a key made with `Context.Service` and a [`Client`](#client). +Declares a client as a service class: one class that is the client's service key, its layer and its config. + +It replaces writing `make`, `Context.Service` and `Layer.effect` by hand. The config has to be known when the module loads: a `baseUrl` Effect (such as a `Config`) works, since it only runs when the layer is built. A config that is itself the result of an Effect, or one made per request, needs `make` and a hand-written service. ### Fetch.make [#make] -Makes a [`Client`](#client). +Makes a [`Client`](#client). `make` is an Effect: it needs an `HttpClient` (for example `FetchHttpClient.layer`, or a mock in tests), whatever the `baseUrl` Effect needs, and the services the plugins need, and it fails with the `baseUrl` Effect's error. -### Fetch.Service [#service] +Invalid input is a defect, not a typed error, because it's a mistake in the calling code: two plugins with the same name, a missing path param, a body that can't be encoded, a body on a `GET` or `HEAD` request, a `baseUrl` with a query string or a fragment, and, outside browsers, a relative URL without a `baseUrl` (browsers resolve it against the page's URL). -Declares a client as a service class: one class that is the client's service key, its layer and its config. +An `HttpClient` that fails on non-2xx statuses (`filterStatusOk`) works too: Effetch takes the response back and reports the usual `HttpError`. + +### Fetch.isService [#isservice] + +Checks whether `u` is a class made by [`Service`](#service), or a class that extends one: `true` if it is, `false` for anything else, including a key made with `Context.Service` and a [`Client`](#client). ### Fetch.Client [#client] @@ -55,7 +65,7 @@ Any class made by [`Service`](#service), whatever its config. What [`isService`] ## Calls [#calls] -Guide: [Methods](/docs/calls). +Guide: [Make a call](/docs/calls). ### Fetch.AnySchema [#anyschema] @@ -175,7 +185,7 @@ Reads a 2xx body as bytes, a `Uint8Array`, for `output`. Use it for images, PDFs Reads a 2xx body as text, for `output`. Use it for plain-text tokens, CSV and other bodies that aren't JSON. - `Fetch.text()` gives the text as it was sent, as a `string`. An empty body is `""`. -- `Fetch.text(schema)` reads a single value, such as a count or a status: it trims the text, then decodes it with `schema`, whose encoded side is a string, such as `Schema.NumberFromString`. An empty body fails, as for JSON. +- `Fetch.text(schema)` reads a single value, such as a count or a status: it trims the text, then decodes it with `schema`, whose encoded side is a string, such as `Schema.NumberFromString`. An empty body fails with a `DecodeError`, where JSON would decode it as `null`. ### Fetch.BytesSchema [#bytesschema] @@ -204,6 +214,8 @@ Guide: [Upload files](/docs/calls/uploads). Sends a body as `multipart/form-data`, for `input`: the body is typed and checked by `schema`, as for JSON, then sent as `FormData`. Use it for file uploads. +A form can't hold a nested object or a list of lists: TypeScript rejects most schemas that encode to one, and a value that does at runtime makes the call die. A struct shaped like a [`NativeFile`](#nativefile), `{ uri, name }`, passes TypeScript, but isn't a file unless it's an [`UploadFile`](#uploadfile), so it dies too. To send one, encode it to a string in the schema, such as with `Schema.fromJsonString`. + ### Fetch.UploadFile [#uploadfile] A file to upload, for a field of a [`multipart`](#multipart) input schema. It takes the files each platform can send: @@ -247,13 +259,32 @@ Handles an `HttpError` with one of the given statuses, for one call: `f` gets th - `HttpError` stays in the error type, since other statuses can still fail. `f`'s own errors are added. - It works on any Effect whose errors include `HttpError`: calls, endpoints, and Effects built on them. +For a `404` that means "not found", [`optional`](#optional) gives an `Option` instead. Use `statusErrors` when a status means the same domain error for every caller. When `statusErrors` maps a status and the body decodes with the mapped schema, the call fails with the mapped error, so `catchStatus` doesn't see it. An empty or non-matching body is still an `HttpError`, which `catchStatus` handles. + ### Fetch.DecodeError [#decodeerror] -A 2xx response body didn't match the call's `output` schema, wasn't valid JSON, or couldn't be read. +The error a call fails with when a 2xx response body doesn't match the call's `output` schema, isn't valid JSON, or can't be read. A stream fails with it too, when a value doesn't decode or the body breaks off. Its fields: + +- `method`: the request's HTTP method. +- `url`: the request URL without its query string. +- `status`: the response's status code. +- `issue`: what went wrong: the schema issue when the body doesn't match `output`, the `SyntaxError` when the body isn't valid JSON, or the `HttpClientError` when the body couldn't be read. +- `message`: a readable summary of `issue`. + +An empty body (204, HEAD, …) is decoded as JSON `null`, so it only passes schemas that accept nothing, such as `Schema.Void`. With `Fetch.text(schema)`, an empty body fails too. + +A stream (`api.sse`, `api.ndjson` or a `stream` endpoint) fails with a `DecodeError` while it's read: when an event's data or a line doesn't decode (the message names it, as in `Line 3 doesn't match the output schema`), when the body breaks off, and, for `api.sse`, when the response's `Content-Type` isn't `text/event-stream`. ### Fetch.HttpError [#httperror] -The server answered with a non-2xx status. +The error a call fails with when the server answers with a status outside 200–299. Its fields: + +- `method`: the request's HTTP method. +- `url`: the request URL without its query string, so secrets in query parameters stay out of logs. +- `status`: the response's status code. +- `headers`: the response headers. They're Effect `Headers`, so sensitive ones (`set-cookie`, `authorization`, …) print as `` when the error is logged or serialized. +- `text`: the raw response body, always (`""` if it couldn't be read). +- `body`: the body decoded with the call's `error` schema (or the client's `defaultError`), or `undefined` if it didn't match. Without an `error` schema, `body` is the parsed JSON when `text` is valid JSON, else `undefined`. An empty body is always `undefined`. Reading `body` never fails the call. ### Fetch.HttpError.With [#httperror-with] @@ -261,16 +292,22 @@ An [`HttpError`](#httperror) whose `body` was decoded as `B`. `body` is `undefin ### Fetch.isFetchError [#isfetcherror] -Returns `true` if `u` is a [`NetworkError`](#networkerror), [`HttpError`](#httperror) or [`DecodeError`](#decodeerror). +Checks whether `u` is a [`NetworkError`](#networkerror), [`HttpError`](#httperror) or [`DecodeError`](#decodeerror): `true` if it is, `false` otherwise. ### Fetch.NetworkError [#networkerror] -The request never produced a response: DNS failure, connection refused, CORS rejection, the device is offline, and so on. +The error a call fails with when its request gets no response: a DNS failure, a refused connection, a CORS rejection, a device that's offline, and so on. Its fields: + +- `method`: the request's HTTP method. +- `url`: the request URL without its query string, so secrets in query parameters stay out of logs. +- `cause`: the underlying error from the platform's HTTP client. ### Fetch.optional [#optional] Turns a `404` into `Option.none()`, and a success into `Option.some`, for one call: the call succeeds with an `Option` of its value. Other errors, `HttpError`s with other statuses included, pass through. +It's [`catchStatus`](#catchstatus)`(404, …)` for the common case of a resource that may not exist. As there, a `404` whose body decodes with a schema `statusErrors` maps it to fails with the mapped error, and doesn't give `Option.none()`. + ### Fetch.CallError [#callerror] What a call can fail with: `NetworkError`, `HttpError` (with `body` typed by the `error` schema), `DecodeError` when there's an `output` schema, the plugins' errors, and the errors of the `statusErrors` maps that apply (see [`StatusError`](#statuserror)). @@ -336,7 +373,7 @@ The `onError` hook. `error` is a `FetchError`, another plugin's error, one of th ### Fetch.Plugin.OnExit [#plugin-onexit] -The `onExit` hook: runs once per call, when it's over, with the call's `Exit`. On success that holds the call's result: the decoded `output`, or the response for a call without one, or, with `responseMode: "decoded-and-response"`, a pair of that and the response. Otherwise it holds the cause of its failure, defect or interruption. To tell whether the body was read, compare the result, or its first item, with `ctx.response`: a call returns the response itself only when it didn't decode it. It sees the final outcome, `statusErrors` and decoding included, which suits logging and metrics. +The `onExit` hook: runs one time per call, after it's over, with the call's `Exit`. On success that holds the call's result: the decoded `output`, or the response for a call without one, or, with `responseMode: "decoded-and-response"`, a pair of that and the response. Otherwise it holds the cause of its failure, defect or interruption. To tell whether the body was read, compare the result, or its first item, with `ctx.response`: a call returns the response itself only when it didn't decode it. It sees the final outcome, `statusErrors` and decoding included, which suits logging and metrics. ### Fetch.Plugin.OnRequest [#plugin-onrequest] @@ -352,7 +389,7 @@ The options type of plugin `P`. ### Fetch.Plugin.Override [#plugin-override] -What one plugin accepts as a per-request override: `false` to skip it, or a partial of its options. Plugins without options accept only `false`. Keys set to `undefined` keep their default. +What one plugin accepts as a per-request override: `false` to skip it, or a partial of its options. Plugins without options accept only `false`. A key whose value is `undefined` at runtime keeps its default. ### Fetch.Plugin.Overrides [#plugin-overrides] @@ -399,38 +436,40 @@ What a plugin's `onExit` hook receives besides the call's `Exit`: the fields of name="PluginExitContext" /> -## Endpoints and services [#endpoints-and-services] +## Endpoint definitions [#endpoint-definitions] Guide: [Endpoints or methods](/docs/endpoints). ### Fetch.endpoint [#endpoint] -Defines an endpoint without a client: a route like `"GET /users/:id"` and the schemas and headers to call it with. You get back plain data, an [`UnboundEndpoint`](#unboundendpoint), that you can export from module level next to its schemas. `client.bind(definition)` turns it into an [`Endpoint`](#endpoint-type) of that client: the same one `client.endpoint(route, definition)` makes. +Defines an endpoint without a client: a route like `"GET /users/:id"` and the schemas and headers to call it with. You get back plain data, an [`UnboundEndpoint`](#unboundendpoint), that you can export from module level next to its schemas. `api.bind(definition)` turns it into an [`Endpoint`](#endpoint-type) of that client: the same one `api.endpoint(route, definition)` makes. -- The route is checked as you type, as with `client.endpoint`. A route that isn't valid (which the types prevent) throws here, when the module loads. +- The route is checked as you type, as with `api.endpoint`. A route that isn't valid (which the types prevent) throws here, when the module loads. - With an `input` schema, `body` is required on every call and typed by it. `GET`, `HEAD`, `OPTIONS` and `TRACE` endpoints take no `input`. - Without `error`, the endpoint uses the `defaultError` of the client it's bound to. - `statusErrors` (see [`StatusErrorMap`](#statuserrormap)) are tried before those of the client it's bound to. - With a `query` schema (see [`QuerySchema`](#queryschema)), each call's `query` is typed and encoded by it, and required when the schema has required fields. - With `stream: "sse"` or `stream: "ndjson"`, each call of the bound endpoint returns a `Stream` of the body's values. A `stream` that isn't one of those, or that comes with `responseMode` or a `Fetch.bytes()` output, throws here. -- Plugin overrides are given when binding: a definition doesn't know which plugins a client has. +- Plugin overrides are given when binding: a definition has no client yet, so it can't check plugin names. - `definition.url(options)` builds the URL a call would go to, without the client's `baseUrl`. ### Fetch.Endpoints [#endpoints] Declares a module's endpoints as a service class: one class that is the service key, its layer and its definitions. +Each entry is checked when the class is declared: one that isn't a definition throws then, as a malformed route does in `Fetch.endpoint`. + ### Fetch.AnyUnboundEndpoint [#anyunboundendpoint] Any [`UnboundEndpoint`](#unboundendpoint), whatever its route and schemas. Use it to constrain a parameter that takes definitions. ### Fetch.BindAllMethod [#bindallmethod] -The signature of `client.bindAll`: binds a record of definitions at once, as `client.bind` binds each one. `Ps`, `DefaultEB` and `ClientSE` are the client's, as in [`BindMethod`](#bindmethod). +The signature of `api.bindAll`: binds a record of definitions at once, as `api.bind` binds each one. `Ps`, `DefaultEB` and `ClientSE` are the client's, as in [`BindMethod`](#bindmethod). ### Fetch.BindMethod [#bindmethod] -The signature of `client.bind`: turns an [`UnboundEndpoint`](#unboundendpoint) into an [`Endpoint`](#endpoint-type) of the client, the same one `client.endpoint` makes from the same route and definition. +The signature of `api.bind`: turns an [`UnboundEndpoint`](#unboundendpoint) into an [`Endpoint`](#endpoint-type) of the client, the same one `api.endpoint` makes from the same route and definition. - `Ps`: the client's plugins. - `DefaultEB`: the client's `defaultError` schema, used when the definition has no `error`. @@ -438,7 +477,7 @@ The signature of `client.bind`: turns an [`UnboundEndpoint`](#unboundendpoint) i ### Fetch.BindOptions [#bindoptions] -What `client.bind` takes besides the definition: headers and plugin overrides for every call of the bound endpoint. +What `api.bind` takes besides the definition: headers and plugin overrides for every call of the bound endpoint. + +## Related pages + +- [Entry points](/docs/reference): what each entry point exports. +- [Plugins](/docs/reference/plugins): the built-in plugins and their options. +- [FetchTest](/docs/reference/fetch-test): the fake backend for tests. +- [Compatibility](/docs/reference/compatibility): the Effect, runtime and TypeScript versions Effetch supports. diff --git a/site/content/docs/(latest)/reference/index.mdx b/site/content/docs/(latest)/reference/index.mdx index b83fe14..b17480d 100644 --- a/site/content/docs/(latest)/reference/index.mdx +++ b/site/content/docs/(latest)/reference/index.mdx @@ -3,39 +3,62 @@ title: Entry points description: Find which entry point exports what, and the reference page that lists it. --- -This page lists Effetch's entry points and what each one exports. Each has a -reference page that lists every export, with the first paragraph of its docs -and a link to the guide that covers it. +The reference lists every export of Effetch, grouped by the guide that +covers it. Start here to find which import a name comes from, then follow +the link to its page. ## The entry points -Effetch has three entry points: +Effetch has three entry points, each with its own reference page: -| Import | What it exports | Reference | -| ---------------------------- | ------------------------------------------------------------------------------------ | --------------------------------------- | -| `@monarcode/effetch` | The `Fetch` namespace: clients, calls, errors, plugins, endpoints, streams and pages | [Fetch](/docs/reference/fetch) | -| `@monarcode/effetch/plugins` | The built-in plugins: `bearer`, `retry`, `timeout`, `logger` and `consoleLogger` | [Plugins](/docs/reference/plugins) | -| `@monarcode/effetch/test` | The `FetchTest` namespace: a fake backend for tests | [FetchTest](/docs/reference/fetch-test) | +| Import | What it exports | Reference | +| ---------------------------- | ------------------------------------------------------------------------------------------------------------------------------------ | --------------------------------------- | +| `@monarcode/effetch` | The `Fetch` namespace: clients, calls, responses, uploads, errors, plugins, endpoint definitions, streaming and pagination | [Fetch](/docs/reference/fetch) | +| `@monarcode/effetch/plugins` | The built-in plugins (`bearer`, `retry`, `timeout`, `logger` and `consoleLogger`), their option and plugin types, and `TimeoutError` | [Plugins](/docs/reference/plugins) | +| `@monarcode/effetch/test` | The `FetchTest` namespace: a fake backend for tests, and the requests it records | [FetchTest](/docs/reference/fetch-test) | -Two more subpaths export the same members without their namespace, for the -declaration files TypeScript writes. In your own code, import from the -entry points above, as [Installation](/docs/installation#import-effetch) -explains. +Each reference entry gives the first paragraph of the name's docs, plus +what it needs and how it fails. Your editor shows the full docs, with an +example, when you hover a name or go to its definition. -Every export is also documented, with an example, in the type declarations -your editor shows: hover a name, or go to its definition. +Two more subpaths, `@monarcode/effetch/Fetch` and +`@monarcode/effetch/test/FetchTest`, export the same members without the +namespace. They exist for the declaration files TypeScript writes, so you +may see them in a `.d.ts` file. In your own code, import from the three +entry points in the table, as [Installation](/docs/installation#import-effetch) +shows. ## Types for your own functions -To wrap the client in a function of your own, type it with the option and -result types under [Calls](/docs/reference/fetch#calls), such as -`Fetch.RequestOptions` and `Fetch.CallEffect`. `CallEffect` types a function -that returns a call. To take a call as an argument, accept any -`Effect.Effect`. +When you wrap a call in a function of your own, you can name its return +type with `Fetch.CallEffect`. It takes the output schema, the error body +schema, the input schema and the client's plugins, and works out the +call's errors and services from them: + +```ts +import * as Schema from "effect/Schema"; + +import type { Fetch } from "@monarcode/effetch"; + +declare const api: Fetch.Client; + +const Todo = Schema.Struct({ id: Schema.Finite, title: Schema.String }); + +type GetTodo = Fetch.CallEffect; + +export const getTodo = (id: number): GetTodo => + api.get("/todos/:id", { params: { id }, output: Todo }); +``` + +The option types, such as `Fetch.RequestOptions`, are under +[Calls](/docs/reference/fetch#calls) in the `Fetch` reference. To take a +call as an argument instead, accept any `Effect.Effect`, since +TypeScript can't infer `CallEffect`'s parameters from a call. ## What's next -- [Compatibility](/docs/reference/compatibility): the Effect versions, - runtimes and TypeScript settings Effetch supports. -- [Limitations](/docs/reference/limitations): the known limits of paths, - plugins and streams. +- [Fetch](/docs/reference/fetch): look up a member of the `Fetch` namespace. +- [Compatibility](/docs/reference/compatibility): check the Effect, + runtime and TypeScript versions Effetch supports. +- [Limitations](/docs/reference/limitations): check the known limits of + paths, plugins and streams before you rely on them. diff --git a/site/content/docs/(latest)/reference/limitations.mdx b/site/content/docs/(latest)/reference/limitations.mdx index a9506bd..5c86e70 100644 --- a/site/content/docs/(latest)/reference/limitations.mdx +++ b/site/content/docs/(latest)/reference/limitations.mdx @@ -1,37 +1,62 @@ --- title: Limitations -description: Check a known limit before you rely on it. +description: The known limits of paths, plugins and streams, and how to work around them. --- -This page lists the known limits of Effetch's paths, plugins and streams. -Check one before you rely on the behavior it describes. +A few things in Effetch work differently from what you might expect, or not +at all. They're collected here, each with a way around it, so you can check +one before your code depends on it. ## Paths -Paths and their parameters have these limits: +A path parameter is always a whole segment, from the `:` to the next `/`. +`/files/:name.json` has one parameter, called `name.json`. To send a file +name with its extension, make the whole segment the parameter, as in +`/files/:file`, and pass `"report.json"`. -- A path parameter is a whole segment: `/files/:name.json` has one parameter - called `name.json`. -- Path parameters can't be optional. Define one endpoint per path, or pass - the value in `query`. -- Paths shouldn't contain `?` or `#`. Pass query parameters with `query`. +Path parameters can't be optional. Define one endpoint for each path, or +pass the value in `query`. + +Don't put a query string or a fragment in a path. Effetch doesn't check +for one, and it isn't sent as a query. A `?` after a parameter +becomes part of its name, so `/items/:id?sort=asc` has a parameter called +`id?sort=asc`. Pass query parameters with `query`. A `baseUrl` with a `?` or +`#` is rejected outright: building the client dies. ## Plugins -Plugins have these limits: +Two plugins with the same name aren't a type error. Building the client, or +the layer of a `Fetch.Service`, dies with `Two plugins are named "NAME"` +instead. + +Durations stop at different points: -- `timeout`, and the duration `logger` logs, cover the time until the - response headers arrive, not downloading the body. `consoleLogger`'s - duration, and an `onExit` hook's `durationMs`, include decoding the body. -- Two plugins with the same name are only caught when the client is made. +- `timeout`, `retry`'s `budget` and the duration `logger` logs end when the + response headers arrive. Downloading and decoding the body isn't covered. + To limit the whole call, body included, wrap it in `Effect.timeout`. +- `consoleLogger`'s duration, and an `onExit` hook's `durationMs`, include + decoding the body. ## Streams -Streamed responses have these limits: +Streams don't reconnect. `api.sse` ignores `retry:` lines, and it doesn't +send a `Last-Event-ID` header by itself. To pick up where a stream stopped, +call it again with the last event's `id` in a header: +`headers: { "last-event-id": lastId }`. + +An SSE event larger than 10 MiB fails the stream with a `DecodeError`. + +For a stream, the call ends, as far as plugins go, when the response's +headers arrive. Their hooks don't run while the body is read, a +`DecodeError` while it's read doesn't reach them, and `timeout` doesn't +limit how long reading takes. Handle those on the stream +itself (see [Streaming responses](/docs/streaming)). + +## What's next -- Streams don't reconnect: `api.sse` ignores `retry:` lines and the - `Last-Event-ID` header. Repeat the call, with the last `id` in a header, - to pick up where a stream stopped. -- For a stream, plugins see the call end when the response's headers - arrive: they don't see the body being read, or a `DecodeError` while - reading it, and `timeout` doesn't bound it. +- [Compatibility](/docs/reference/compatibility): the Effect versions, + runtimes and TypeScript versions Effetch supports. +- [Streaming responses](/docs/streaming): read Server-Sent Events and + newline-delimited JSON, and handle a stream's errors. +- [Built-in plugins](/docs/plugins): see what each plugin does, and how to + pick a time limit. diff --git a/site/content/docs/(latest)/reference/plugins.mdx b/site/content/docs/(latest)/reference/plugins.mdx index 56858cd..f6d702f 100644 --- a/site/content/docs/(latest)/reference/plugins.mdx +++ b/site/content/docs/(latest)/reference/plugins.mdx @@ -5,7 +5,7 @@ description: "Every export of @monarcode/effetch/plugins: the built-in plugins a {/* Written by scripts/reference-docs.mjs from the JSDoc. Run `pnpm run docs:reference` after changing it; don't edit this page. */} -`@monarcode/effetch/plugins` exports the built-in plugins, their options and the types they return: +`@monarcode/effetch/plugins` exports the built-in plugins, their options, the types they return and `TimeoutError`. Import what you use: ```ts import { @@ -18,6 +18,10 @@ import { } from "@monarcode/effetch/plugins"; ``` +Its exports follow, grouped by the guide that covers them. Each one has the +first paragraph of its docs, and what it needs and how it fails; your +editor shows the rest, with an example, when you hover the name. + ## Bearer tokens [#bearer-tokens] Guide: [Refresh a token](/docs/plugins/token-refresh). @@ -64,7 +68,7 @@ Guide: [Retry-After and a time limit](/docs/plugins/retry-after). ### retry [#retry] -Retries a call that failed with a `NetworkError` or got a retryable status, for the configured methods only (idempotent ones by default, so a `POST` is never sent twice). +Retries a call that failed with a `NetworkError` or got a retryable status, for the configured methods only: the idempotent ones by default, so `retry` doesn't resend a `POST` unless you add it. With a `budget`, it also limits the whole call, every attempt and wait included, and fails with `TimeoutError` when the budget runs out. ### RetryBudgetOptions [#retrybudgetoptions] @@ -94,7 +98,7 @@ The plugin made by [`retry`](#retry). It adds no errors; calls can override `tim ## Time limits [#time-limits] -Guide: [Choose a time limit](/docs/plugins#choose-a-time-limit). +Guide: [Retry-After and a time limit](/docs/plugins/retry-after). ### timeout [#timeout] @@ -102,10 +106,11 @@ Fails the call with a [`TimeoutError`](#timeouterror), and aborts the request, w ### TimeoutError [#timeouterror] -No response arrived within the [`timeout`](#timeout) plugin's duration. The request was aborted. +The error a call fails with when a time limit runs out: the [`timeout`](#timeout) plugin's `duration` before the response headers arrive, or `retry`'s `budget` for the whole call. The request in flight is aborted. Its fields: -- `url` is the request URL without its query string. -- `duration` is the limit that was exceeded, formatted (`"10s"`). +- `method`: the request's HTTP method. +- `url`: the request URL without its query string. +- `duration`: the limit that ran out, formatted (`"10s"`). ### TimeoutOptions [#timeoutoptions] @@ -122,11 +127,11 @@ The plugin made by [`timeout`](#timeout): it adds [`TimeoutError`](#timeouterror ## Logging [#logging] -Guide: [Built-in plugins](/docs/plugins#what-each-plugin-does). +Guide: [Built-in plugins](/docs/plugins#logger). ### logger [#logger] -Logs one entry per call with Effect's logger: the method, the URL, the status and how long the response took, e.g. `GET https://api.example.com/todos 200 (35ms)`, or `… failed (35ms)` with the failure's cause. +Logs one entry per call with Effect's logger: the method, the URL, the status and how long the response took, for example `GET https://api.example.com/todos 200 (35ms)`, or `… failed (35ms)` with the failure's cause. An interrupted call isn't logged. Placed after `retry`, it logs each attempt instead of the call. ### LoggerOptions [#loggeroptions] @@ -149,6 +154,12 @@ Guide: [Log to the console](/docs/plugins/console-logging). Prints each call to the console while you develop: one line per call, opening a group with its URL, headers, bodies and error. +It logs each call after it's over, with its final outcome: the error a call fails with after `statusErrors` and decoding, or `interrupted`. Values are logged as objects, for devtools to expand. Everything goes through Effect's `Console` with `console.log` and groups, never `console.error`, which React Native turns into an error screen. + +It runs from the `onExit` hook, so it covers the whole call wherever it sits in the plugin list: retries are one entry, and `duration` includes them. When a plugin fails on a response (such as a 401), that response is shown. Without a response, the request shown is the one the call built, before plugins (such as `bearer`) changed it. + +Throws if `slow` isn't a duration. A call's own `slow` that isn't one flags nothing. + ### ConsoleLoggerCall [#consoleloggercall] The call `ConsoleLoggerOptions.filter` decides on. @@ -205,3 +216,10 @@ The options of [`consoleLogger`](#consolelogger) that calls can override, with ` path="node_modules/@monarcode/effetch/dist/plugins/consoleLogger.d.ts" name="ConsoleLoggerSettings" /> + +## Related pages + +- [Entry points](/docs/reference): what each entry point exports. +- [Fetch](/docs/reference/fetch): every member of the `Fetch` namespace. +- [FetchTest](/docs/reference/fetch-test): the fake backend for tests. +- [Compatibility](/docs/reference/compatibility): the Effect, runtime and TypeScript versions Effetch supports. diff --git a/site/content/docs/(latest)/streaming.mdx b/site/content/docs/(latest)/streaming.mdx index 9692611..c367ec0 100644 --- a/site/content/docs/(latest)/streaming.mdx +++ b/site/content/docs/(latest)/streaming.mdx @@ -4,7 +4,8 @@ description: Read Server-Sent Events or newline-delimited JSON as a Stream, and --- Some APIs send their answer a piece at a time: progress feeds, -notifications, exports, the answers of language models. `api.sse` and +notifications, exports, the answers of language models. Waiting for the +whole body would mean showing nothing until the end. `api.sse` and `api.ndjson` give such a body as an Effect `Stream`, one value at a time, as it arrives. This page shows how to read both formats, define stream endpoints, and handle a stream that fails or that you stop. @@ -33,42 +34,54 @@ export const followJob = (id: number) => ); ``` -The following rules apply to an SSE call: +`output` decodes each event's `data` as JSON. Without it, or with +`Fetch.text()`, `data` is the text as it was sent. -- `output` decodes each event's `data` as JSON. Without it, or with - `Fetch.text()`, `data` is the text as it was sent. -- `method` defaults to `"GET"`. APIs that stream the answer to a request - take `"POST"` and a `body`: +The request is a `GET` by default. An API that streams its answer to a +request usually takes a `POST` with a body, so pass `method` and `body`: - ```ts - import * as Schema from "effect/Schema"; +```ts +import * as Schema from "effect/Schema"; + +import type { Fetch } from "@monarcode/effetch"; + +declare const api: Fetch.Client; + +const Prompt = Schema.Struct({ prompt: Schema.String }); +const Delta = Schema.Struct({ text: Schema.String }); - import type { Fetch } from "@monarcode/effetch"; +export const complete = (prompt: string) => + api.sse("/completions", { + method: "POST", + input: Prompt, + body: { prompt }, + output: Delta, + }); +``` - declare const api: Fetch.Client; +The request sends `Accept: text/event-stream`, unless the call or the +client sets an `accept` header. - const Prompt = Schema.Struct({ prompt: Schema.String }); - const Delta = Schema.Struct({ text: Schema.String }); +### How events are parsed - export const complete = (prompt: string) => - api.sse("/completions", { - method: "POST", - input: Prompt, - body: { prompt }, - output: Delta, - }); - ``` +Events are parsed by the +[WHATWG rules](https://html.spec.whatwg.org/multipage/server-sent-events.html), +which most servers follow without you noticing. A few of them can surprise +you: -- The request sends `Accept: text/event-stream`, unless the call or the - client sets an `accept` header. -- Events are parsed by the - [WHATWG rules](https://html.spec.whatwg.org/multipage/server-sent-events.html): - comment lines are ignored, a multi-line `data` is joined with `\n`, and an - `id` carries over to the events after it. The stream doesn't reconnect, - and ignores `retry:` lines. -- A response whose `Content-Type` is set to another type than +- Comment lines are ignored. A multi-line `data` is joined with `\n`, and + an `id` carries over to the events after it. +- An event without any `data` line is dropped. +- An event ends at a blank line. When the server closes the connection + without one after its last event, that last event is dropped. +- An event over 10 MiB fails the stream with a `DecodeError`. +- A response whose `Content-Type` is set to a type other than `text/event-stream`, such as a login page from a proxy, fails the stream - with a `DecodeError`. + with a `DecodeError` before any event. +- The stream doesn't reconnect, and ignores `retry:` lines. + +[Limitations](/docs/reference/limitations#streams) shows how to pick up a +stream where it stopped. `api.sse` parses events with Effect's `encoding/Sse` module, which Effect @@ -77,10 +90,10 @@ The following rules apply to an SSE call: ### Stop at a sentinel -`output` decodes every event, so an event whose data doesn't match it -fails the stream, after the events before it. When the server ends with a -sentinel that isn't JSON, such as `data: [DONE]`, leave `output` out, stop -at the sentinel, then decode the rest: +`output` decodes every event, so an event whose data doesn't match it fails +the stream, after the events before it. Some servers end with a sentinel +that isn't JSON, such as `data: [DONE]`. For those, leave `output` out, +stop at the sentinel, then decode the rest: ```ts import * as Schema from "effect/Schema"; @@ -101,8 +114,8 @@ export const deltas = (prompt: string) => ## Read newline-delimited JSON -`api.ndjson` reads an `application/x-ndjson` body (also called JSON Lines): -one JSON value per line, decoded with `output`: +`api.ndjson` reads an `application/x-ndjson` body, also called JSON Lines: +one JSON value per line, each decoded with `output`: ```ts import * as Schema from "effect/Schema"; @@ -126,6 +139,9 @@ The following rules apply to an NDJSON call: - Blank lines are skipped, and the last line needs no line end. - The request sends `Accept: application/x-ndjson`, unless an `accept` header is set. +- Unlike SSE, the response's `Content-Type` isn't checked. A body that + isn't NDJSON, such as an HTML page, fails on its first line as invalid + JSON, unless you read the lines as text with `Fetch.text()`. ## Define a stream endpoint @@ -161,44 +177,61 @@ export const lastEvent = (id: number) => }); ``` +Its calls follow the same rules as `api.sse` or `api.ndjson`. + ## How a stream fails -A stream's request runs as any call does, up to the response's headers: +A stream fails in two stages: while its request is sent, and while its body +is read. + +The request runs as any call does, up to the response's headers: - Plugins run once. `retry` and `timeout` apply to getting the response, not to reading the body. - When no response arrives, the stream fails with a `NetworkError`. +- A plugin's error fails it too, such as the `TimeoutError` of the + `timeout` plugin. - An error status fails it with an `HttpError`, or a [`statusErrors`](/docs/errors/status-errors) error, before it gives any value. - A `204 No Content` or `205 Reset Content` gives an empty stream. -Then the body is read as it arrives. The values before a failure are given -first. A value that doesn't match `output`, or a body that breaks off, -fails the stream with a `DecodeError`, which names the event or the line: -`Line 3 doesn't match the output schema`. +Then the body is read as it arrives, and the values before a failure are +given first. A value that doesn't match `output`, or a body that breaks +off, fails the stream with a `DecodeError`, which names the event or the +line, as in `Line 3 doesn't match the output schema`. +On React Native, the built-in `fetch` doesn't stream response bodies, so +every stream fails there with a `DecodeError`. +[Platform notes](/docs/platforms#react-native) shows which `fetch` to use +instead. + +For plugins, a stream's call ends when the response's headers arrive: + +- `logger` times every call up to the headers, so for a stream, it logs the + time to the headers. +- `onExit` hooks, `consoleLogger`'s among them, run when the headers + arrive, and report the time to the headers. +- A `DecodeError` while the body is read reaches neither. -For plugins, the call ends when the response's headers arrive. Their -`onExit` hooks, and so `logger` and `consoleLogger`, report it then, with -the time to the headers, and a `DecodeError` while reading the body doesn't -reach them. Handle it on the stream, with `Stream.catchTag("DecodeError", …)` -or `Stream.tapError`. +Handle errors from the body on the stream itself, with +`Stream.catchTag("DecodeError", …)` or `Stream.tapError`. ## Stop a stream Interrupting the stream, or taking only part of it, as with `Stream.take`, -aborts the request. Nothing else is needed to close the connection. +aborts the request. You don't need to close the connection yourself. ## Options a stream doesn't take -A stream can't take `responseMode`, or an `output` made with -`Fetch.bytes()`. A call that passes one dies, and a definition with one -throws when it's made. +A stream can't take `responseMode`, since it gives the body's values, or an +`output` made with `Fetch.bytes()`, which can't decode them one at a time. +A call that passes one dies, and a definition with one throws when it's +made. ## What's next - [Pagination](/docs/pagination): follow a list's pages as a `Stream`. - [Test stream endpoints](/docs/testing/streams): answer a stream endpoint from a fake backend. -- [Errors by status](/docs/errors/status-errors): fail a stream with your - own error for a status. +- [Limitations](/docs/reference/limitations#streams): see what streams + don't do, such as reconnecting. diff --git a/site/content/docs/(latest)/structuring-an-app.mdx b/site/content/docs/(latest)/structuring-an-app.mdx index 430d230..7ab7951 100644 --- a/site/content/docs/(latest)/structuring-an-app.mdx +++ b/site/content/docs/(latest)/structuring-an-app.mdx @@ -3,17 +3,29 @@ title: Structure an app description: Lay out clients and endpoints in a small app, a feature-sliced app and an app with several backends. --- -This page shows where clients and endpoints can live as your app grows, from -a single client to several backends. +Your first few calls can live anywhere. As the app grows, you have to +decide where the client goes, where the endpoints go, and how the rest of +the code reaches them. This page shows three layouts that work, from a +small app to one that talks to several backends, so you can pick the one +that fits. -A client is declared once, and endpoints are bound to it once, in a layer. -Where each piece lives depends on the size of your app. These are patterns, -not rules: Effetch works the same way whichever you pick. +## What every layout has in common + +Whichever layout you pick, two things stay the same: + +- **The client is declared once,** as a service, with its base URL, error + body and plugins. +- **Endpoints are bound to it once,** in a layer, when the app starts. Code + that makes calls gets the bound endpoints from a service, and never binds + them itself. + +The rest is up to you. These layouts are patterns, not rules, and Effetch +works the same way whichever you use. ## A small app -Keep the client in one file, and each area's endpoints in its own file, as a -`Fetch.Endpoints` class. One layer puts them together: +In a small app, keep the client in one file, and each area's endpoints in +its own file, as a `Fetch.Endpoints` class. One layer puts them together: ```ts import * as Effect from "effect/Effect"; @@ -26,6 +38,11 @@ import { bearer } from "@monarcode/effetch/plugins"; const User = Schema.Struct({ id: Schema.Finite, name: Schema.String }); const NewUser = Schema.Struct({ name: Schema.String }); +const Credentials = Schema.Struct({ + user: Schema.String, + password: Schema.String, +}); +const Session = Schema.Struct({ token: Schema.String }); const Todo = Schema.Struct({ id: Schema.Finite, title: Schema.String }); // api.ts @@ -39,7 +56,10 @@ export class Users extends Fetch.Endpoints()("Users", Api, { get: Fetch.endpoint("GET /users/:id", { output: User }), create: Fetch.endpoint("POST /users", { input: NewUser, output: User }), login: [ - Fetch.endpoint("POST /auth/login", { output: User }), + Fetch.endpoint("POST /auth/login", { + input: Credentials, + output: Session, + }), { plugins: { bearer: false } }, ], }) {} @@ -65,57 +85,102 @@ export const program = Effect.gen(function* () { }); ``` -The plugin override on `login` is checked against `Api`'s plugins, and every -endpoint's errors are typed with `Api`'s `defaultError` and `statusErrors`. +`login` turns off the `bearer` plugin, so logging in sends no token. That +override is checked against `Api`'s plugins, and every endpoint's errors +are typed with `Api`'s `defaultError` and `statusErrors`. +`Layer.provideMerge` keeps `Api` itself in the layer, for the one-off calls +that aren't worth an endpoint. + +### Endpoints made with api.endpoint -### Endpoints made with client.endpoint +You may prefer to define each endpoint on the client with `api.endpoint`, +in one step. Then write each area as a function of the client, typed +`Effect.Success`, so overrides and errors are still checked +against `Api`'s plugins and `defaultError`. -To make endpoints with `client.endpoint` instead, write each area as a -function of the client, typed `Effect.Success`, so overrides and -errors are still checked against your plugins and `defaultError`: +That function makes new endpoints each time it runs, so don't call it per +request. Run it once, in a layer, and share what it returns as a service: ```ts +import * as Context from "effect/Context"; import * as Effect from "effect/Effect"; +import * as Layer from "effect/Layer"; import * as Schema from "effect/Schema"; import { Fetch } from "@monarcode/effetch"; import { bearer } from "@monarcode/effetch/plugins"; const User = Schema.Struct({ id: Schema.Finite, name: Schema.String }); +const Credentials = Schema.Struct({ + user: Schema.String, + password: Schema.String, +}); +const Session = Schema.Struct({ token: Schema.String }); class Api extends Fetch.Service()("Api", { baseUrl: "https://api.example.com", plugins: [bearer({ token: "token" })], }) {} +// The endpoints, made from the client export const users = (api: Effect.Success) => ({ get: api.endpoint("GET /users/:id", { output: User }), login: api.endpoint("POST /auth/login", { - output: User, + input: Credentials, + output: Session, plugins: { bearer: false }, }), }); + +// Made once, when the layer is built, and shared as a service +const makeUsers = Api.useSync(users); + +export class Users extends Context.Service< + Users, + Effect.Success +>()("Users") {} + +export const UsersLayer = Layer.effect(Users)(makeUsers); ``` +`Api.useSync(users)` is an Effect that gets the client and calls `users` +with it. `Layer.effect` runs that Effect once, when the layer is built. +Code then gets the endpoints with `yield* Users`, as with a +`Fetch.Endpoints` class. `Fetch.Endpoints` writes these three steps for +you, so it's the shorter choice when your endpoints are defined with +`Fetch.endpoint`. + ## A feature-sliced app -When your app is split into feature modules, each with its own schemas, the -client becomes shared infrastructure that knows nothing about the modules. -Each module defines its endpoints next to its schemas, with no client, and -binds them to the client in its data layer: +A larger app is often split into feature modules, each with its own +schemas. There, the client becomes shared infrastructure, and it imports +nothing from the modules. Each module defines its endpoints next to its +schemas, with no client, and binds them to the client in its data layer. + +[`examples/app`](https://github.com/monarcode/effetch/tree/main/examples/app) +is a complete app in this layout, with two modules and two backends. Here +are its files: ```text -src/ +examples/app/ ├── infrastructure/http/ -│ └── app-api-client.ts the client: base URL, error body, plugins +│ ├── app-api-client.ts the main backend's client +│ ├── wallet-api-client.ts the wallet backend's client +│ └── plugins.ts plugins both clients use ├── modules/ │ ├── todos/ -│ │ ├── contract/ schemas, and endpoints defined with Fetch.endpoint -│ │ ├── data/ the endpoints, bound to AppApiClient -│ │ ├── application/ workflows that take more than one call -│ │ └── public.ts +│ │ ├── contract/todos.ts schemas, and endpoints from Fetch.endpoint +│ │ ├── data/todo.api.ts the endpoints, bound to AppApiClient +│ │ ├── todo.layer.ts the module's layers, merged +│ │ └── public.ts what other code may import │ └── wallet/ -└── runtime.ts modules, on top of clients, on top of HttpClient +│ ├── application/ workflows that take more than one call +│ ├── contract/ +│ ├── data/ +│ ├── wallet.layer.ts +│ └── public.ts +├── runtime.ts modules, over the clients, over HttpClient +└── main.ts the program: imports modules only through public.ts ``` @@ -126,7 +191,9 @@ src/ layer. -The following code shows each file of the layout, with the `todos` module: +The following code puts the `todos` module's files in one block, each +under a comment with its path. It's shortened from the example, which has +more fields, endpoints and errors: ```ts import * as Config from "effect/Config"; @@ -137,7 +204,7 @@ import * as Schema from "effect/Schema"; import { Fetch } from "@monarcode/effetch"; -// infrastructure/http/app-api-client.ts: how to reach the backend, nothing else +// infrastructure/http/app-api-client.ts: how to reach the backend export class AppApiClient extends Fetch.Service()( "AppApiClient", { baseUrl: Config.String("APP_API_URL") }, @@ -156,7 +223,7 @@ export const createTodo = Fetch.endpoint("POST /todos", { output: Todo, }); -// modules/todos/data/todo.api.ts: the endpoints, bound, as the module's service +// modules/todos/data/todo.api.ts: the endpoints, bound, as a service export class TodoApi extends Fetch.Endpoints()( "TodoApi", AppApiClient, @@ -167,8 +234,11 @@ export class TodoApi extends Fetch.Endpoints()( }, ) {} -// runtime.ts -export const AppLayer = TodoApi.layer.pipe( +// modules/todos/todo.layer.ts: every layer the module has +export const TodoModuleLive = Layer.mergeAll(TodoApi.layer); + +// runtime.ts: the modules, on top of the client, on top of HttpClient +export const AppLayer = TodoModuleLive.pipe( Layer.provideMerge(AppApiClient.layer), Layer.provide(FetchHttpClient.layer), ); @@ -183,49 +253,94 @@ export const program = Effect.gen(function* () { ### Why this layout scales -This scales well as the app grows: +Each part of the app grows in its own place: - **The client file stays the same size,** however many endpoints the app - has, and it never imports a module: dependencies point from the modules to - the infrastructure. + has, and it never imports a module. Dependencies point from the modules + to the infrastructure. - **A module with 20 endpoints has 20 definitions** in its own `contract/` folder, beside their schemas, and 20 one-line entries in its `Fetch.Endpoints` class in `data/`. When they serve separate concerns, split them into several services, each in its own file. -- **Every module's data service is its endpoints,** as `TodoApi` is here: one - line per operation, and every type inferred, so every module's `data/` - folder looks the same. +- **Every module's data service is its endpoints,** as `TodoApi` is here. + There's one line per operation and every type is inferred, so every + module's `data/` folder looks the same. - **An operation that isn't one HTTP call** (it combines calls, reshapes a - response or adds a domain error) is a workflow over those endpoints, in the - module's `application/` folder. + response or adds a domain error) is a workflow over those endpoints, in + the module's `application/` folder, as `wallet` has. - **Declare a service's interface by hand only when you need another implementation,** such as an offline one or a fake for UI work, and implement it with the endpoints. -### client.endpoint in this layout +### api.endpoint in this layout -`client.endpoint` fits this layout too: make the endpoints in `data/`, and +`api.endpoint` fits this layout too. Make the endpoints in `data/`, and import only the schemas from `contract/`. Define them with `Fetch.endpoint` -when something should read the routes and schemas without a client. -[`examples/app`](https://github.com/monarcode/effetch/tree/main/examples/app) -is a complete app in this layout, with two modules and two backends: `todos` -declares its definitions with `Fetch.Endpoints`, and `wallet` uses -`client.endpoint`. +instead when something has to read the routes and schemas without a +client, such as a test's fake backend. + +The example app does both. `todos` defines its endpoints with +`Fetch.endpoint` in `contract/`, and binds them with `Fetch.Endpoints` in +`data/`. `wallet` makes its endpoints with its client's `endpoint` method +in `data/`, and shares them as a service the way +[Endpoints made with api.endpoint](#endpoints-made-with-apiendpoint) shows. ## Several backends -Declare one client per backend, each with its own id, `baseUrl`, -`defaultError` and plugins. Each module uses the client of the backend it -talks to, and one `HttpClient` layer serves them all. +When the app talks to more than one backend, declare one client for each, +with its own id, `baseUrl`, `defaultError` and plugins. Each module uses +the client of the backend it talks to, and one `HttpClient` layer serves +them all: + +```ts +import * as FetchHttpClient from "effect/http/FetchHttpClient"; +import * as Layer from "effect/Layer"; +import * as Schema from "effect/Schema"; + +import { Fetch } from "@monarcode/effetch"; +import { bearer } from "@monarcode/effetch/plugins"; + +declare const readToken: () => Promise; + +// One plugin value, shared by both clients +const auth = bearer({ token: () => readToken() }); + +export class AppApiClient extends Fetch.Service()( + "AppApiClient", + { + baseUrl: "https://api.example.com", + defaultError: Schema.Struct({ code: Schema.String }), + plugins: [auth], + }, +) {} + +export class WalletApiClient extends Fetch.Service()( + "WalletApiClient", + { + baseUrl: "https://wallet.example.com", + defaultError: Schema.Struct({ reason: Schema.String }), + plugins: [auth], + }, +) {} + +export const Clients = Layer.mergeAll( + AppApiClient.layer, + WalletApiClient.layer, +).pipe(Layer.provide(FetchHttpClient.layer)); +``` Keep the following in mind: -- Plugins are values: one `bearer` can serve several clients. -- `ctx.route` has no host. A plugin that groups by route and is shared by - several clients should take the backend's name, so each client gets its own - instance. -- Catch a backend's `HttpError` next to its calls, where `body` has that - backend's error shape. +- **Plugins are values,** so one `bearer` can serve several clients, as + `auth` does here. +- **A route doesn't say which backend it's for.** Plugins get the call's + route as `ctx.route` (see [Write a plugin](/docs/plugins/writing)). It's + the method and the path as written, with no base URL, so both backends + can have a `GET /health`. Only a route written as a full URL keeps its + host. A plugin that groups by route and is shared by several clients + should take the backend's name, so each client gets its own instance. +- **Catch a backend's `HttpError` next to its calls,** where `body` has + that backend's error shape. [`examples/backends.ts`](https://github.com/monarcode/effetch/blob/main/examples/backends.ts) does this in one file, and diff --git a/site/content/docs/(latest)/testing/errors.mdx b/site/content/docs/(latest)/testing/errors.mdx index 1b793b8..7baafd9 100644 --- a/site/content/docs/(latest)/testing/errors.mdx +++ b/site/content/docs/(latest)/testing/errors.mdx @@ -3,16 +3,16 @@ title: Test errors and statuses description: Make the fake backend fail or answer with another status. --- -This page shows how to make the [fake backend](/docs/testing) answer with an -error, or with another status, so you can test how your code -handles each one. +The error paths of your code are the hardest to reach against a real API: +you can't ask a server for a 503 on demand. With the +[fake backend](/docs/testing), you can answer any request with an error, or +with a status other than 200, and check that your code handles each one. +This page shows both. ## Fail every request to an endpoint To answer every request to an endpoint with an error, use `FetchTest.fail`, -with a status and an optional body. The body is encoded with the endpoint's -`statusErrors` schema for that status, then its `error` schema, so the client -decodes it back into your domain error: +with a status and an optional body: ```ts import * as Schema from "effect/Schema"; @@ -27,31 +27,46 @@ class TodoNotFound extends Schema.TaggedError()("TodoNotFound", { const getTodo = Fetch.endpoint("GET /todos/:id", { statusErrors: { 404: TodoNotFound }, }); +const listTodos = Fetch.endpoint("GET /todos"); export const Backend = FetchTest.layer([ // The call fails with a TodoNotFound. FetchTest.fail(getTodo, 404, new TodoNotFound({ message: "No todo 9" })), + // The call fails with an HttpError, status 503, asking to retry in 1 second. + FetchTest.fail(listTodos, 503, undefined, { + headers: { "retry-after": "1" }, + }), ]); ``` -## Answer with another status - -A handler answers with another status by returning -`FetchTest.reply(status, body)`, such as a `404` for one id and the todo for -the others. A reply's body is sent as it is, as a call's `body` without -`input` is: +`FetchTest.fail` encodes the body as JSON with the first schema that +encodes it: the endpoint's `statusErrors` schemas for that status, then its +`error` schema. The client then decodes it back into your domain error, or +into `HttpError.body`. Without a body, the response is empty, so the call +fails with an `HttpError`. + +A few more rules apply: + +- **The status** must be from 300 to 599, since `fail` answers with an + error. +- **Headers** go in the fourth argument, such as `retry-after` to test the + `retry` plugin. +- **The client's maps.** A `Fetch.endpoint` definition doesn't carry the + client's `statusErrors` or `defaultError`. Without schemas of its own, the + body is sent by its runtime type, so an error class goes as JSON. The + client still decodes it with its own maps, so + `FetchTest.fail(getTodo, 401, new SessionExpired(…))` fails with + `SessionExpired` when only the client maps 401. You don't need to repeat + the map on the endpoint. +- **A body that no schema encodes** is a defect, since it's a bug in the + test. -- no body -- a string as text -- bytes as bytes -- a `Blob`, `FormData` or `URLSearchParams` as it is -- anything else as JSON - -For a `2xx` with a typed body, such as a `201`, pass `{ status: 201 }` as -`respond`'s third argument instead. +## Answer with another status -The following backend answers `404` for every todo but the first, and `201` -with a `location` header when a todo is created: +To fail some requests and answer others, return `FetchTest.reply(status, +body)` from a `respond` handler. The following backend answers `404` for +every todo but the first, and `201` with a `location` header when a todo is +created: ```ts import * as Effect from "effect/Effect"; @@ -86,6 +101,19 @@ export const Backend = FetchTest.layer([ ]); ``` +A reply's body isn't checked against the endpoint's schemas. It's sent as +it is, the way a call's `body` without `input` is: + +- `undefined` as no body; +- a string as text; +- bytes as bytes; +- a `Blob`, `FormData` or `URLSearchParams` as it is; +- anything else as JSON. + +For a 2xx with a typed body, such as a `201`, don't use `reply`. Pass +`{ status: 201 }` as `respond`'s third argument instead, as `createTodo` +does, so the body is still encoded with `output`. + ## What's next - [Errors by status](/docs/errors/status-errors): declare the domain errors diff --git a/site/content/docs/(latest)/testing/http-client.mdx b/site/content/docs/(latest)/testing/http-client.mdx index 1011dca..4fbce16 100644 --- a/site/content/docs/(latest)/testing/http-client.mdx +++ b/site/content/docs/(latest)/testing/http-client.mdx @@ -1,17 +1,21 @@ --- title: Use a hand-written HttpClient -description: Fake the transport with your own HttpClient for what a fake backend doesn't do. +description: Fake the transport with your own HttpClient, for a network failure or a body that arrives slowly or breaks off. --- -This page shows how to provide an `HttpClient` of your own in tests, for what -a [fake backend](/docs/testing) doesn't do, such as a network failure or a -slow response. +The [fake backend](/docs/testing) covers most tests, slow responses +included. Two things are out of its reach: a request that never gets a +response, since a handler can't fail, and a body that arrives in pieces or +breaks off partway, since the fake backend sends each body in one piece. For +those, you provide an `HttpClient` of your own, which answers however you +need. This page shows how, with a sample for each case. ## Provide your own HttpClient Effetch sends every request through the `HttpClient` layer you provide, so a -test can provide one that answers however you need. The following client -records each request and answers with a todo: +test can provide one made with `HttpClient.make`. Its function gets each +request and its URL, and returns the response. The following client records +each request and answers with a todo: ```ts import * as Effect from "effect/Effect"; @@ -54,11 +58,141 @@ const todo = await Effect.runPromise( // todo: { id: 1, title: "Write docs" }; sent: ["GET https://api.test/todos/1"] ``` +`HttpClientResponse.fromWeb` turns a standard `Response` into Effect's +response, so you can build the answer with anything `Response` accepts. + +## Fail with a network error + +To test how your code handles a request that gets no response, such as when +the device is offline, fail with a transport error. Effetch turns it into a +`NetworkError`, as it does when `fetch` itself fails: + +```ts +import * as Effect from "effect/Effect"; +import * as HttpClient from "effect/http/HttpClient"; +import * as HttpClientError from "effect/http/HttpClientError"; +import * as Layer from "effect/Layer"; +import * as Schema from "effect/Schema"; + +import { Fetch } from "@monarcode/effetch"; + +const Todo = Schema.Struct({ id: Schema.Finite, title: Schema.String }); + +class Api extends Fetch.Service()("Api", { + baseUrl: "https://api.test", +}) {} + +// Every request fails, as if the device were offline +const Offline = Layer.succeed( + HttpClient.HttpClient, + HttpClient.make((request) => + Effect.fail( + new HttpClientError.HttpClientError({ + reason: new HttpClientError.TransportError({ + request, + cause: new TypeError("Failed to fetch"), + }), + }), + ), + ), +); + +const program = Effect.gen(function* () { + const api = yield* Api; + return yield* api.get("/todos/:id", { params: { id: 1 }, output: Todo }); +}).pipe( + Effect.catchTag("NetworkError", (error) => + Effect.succeed(`${error.message} (${String(error.cause)})`), + ), +); + +const result = await Effect.runPromise( + program.pipe(Effect.provide(Api.layer.pipe(Layer.provide(Offline)))), +); +// "GET https://api.test/todos/1: network error (TypeError: Failed to fetch)" +``` + +The `NetworkError` carries the request's method and URL, and its `cause` is +the `cause` you gave the `TransportError`. Only a `TransportError` becomes a +`NetworkError`. A `StatusCodeError` is handled as the response it carries, +and any other reason, such as an `InvalidUrlError`, makes the call die as a +defect. + +## Send a body that breaks off + +To test a stream that slows down or drops partway, answer with a `Response` +whose body is a `ReadableStream` you control. The following client sends one +line of newline-delimited JSON, waits, then breaks the connection: + +```ts +import * as Effect from "effect/Effect"; +import * as HttpClient from "effect/http/HttpClient"; +import * as HttpClientResponse from "effect/http/HttpClientResponse"; +import * as Layer from "effect/Layer"; +import * as Schema from "effect/Schema"; +import * as Stream from "effect/Stream"; + +import { Fetch } from "@monarcode/effetch"; + +const Progress = Schema.Struct({ percent: Schema.Finite }); + +class Api extends Fetch.Service()("Api", { + baseUrl: "https://api.test", +}) {} + +const encoder = new TextEncoder(); + +// One value, a pause, then the connection drops +const body = () => + new ReadableStream({ + async start(controller) { + controller.enqueue(encoder.encode('{"percent":50}\n')); + await new Promise((resolve) => setTimeout(resolve, 200)); + controller.error(new Error("Connection reset")); + }, + }); + +const Dropping = Layer.succeed( + HttpClient.HttpClient, + HttpClient.make((request) => + Effect.succeed( + HttpClientResponse.fromWeb( + request, + new Response(body(), { + headers: { "content-type": "application/x-ndjson" }, + }), + ), + ), + ), +); + +const program = Effect.gen(function* () { + const api = yield* Api; + yield* api + .ndjson("/jobs/1/progress", { output: Progress }) + .pipe(Stream.runForEach((value) => Effect.log(value.percent))); +}).pipe(Effect.catchTag("DecodeError", (error) => Effect.log(error.message))); + +await Effect.runPromise( + program.pipe(Effect.provide(Api.layer.pipe(Layer.provide(Dropping)))), +); +// Logs 50, then, 200 ms later: +// "Failed to read the response body: Connection reset" +``` + +Your code gets the first value as soon as it arrives. When the body breaks +off, the stream fails with a `DecodeError`. To test a slow stream that ends +normally, call `controller.close()` instead of `controller.error(…)`. For an +SSE endpoint, send `content-type: text/event-stream`, since `api.sse` checks +it. + ## What's next - [Test with a fake backend](/docs/testing): answer requests from your endpoints, with typed handlers. - [Test stream endpoints](/docs/testing/streams): fake a stream whose whole body arrives at once. -- [Platform notes](/docs/platforms): the `HttpClient` setup each platform - needs. +- [Streaming responses](/docs/streaming): see how a stream reads its body, + and how it fails. +- [Platform notes](/docs/platforms): see the `HttpClient` setup each + platform needs. diff --git a/site/content/docs/(latest)/testing/index.mdx b/site/content/docs/(latest)/testing/index.mdx index 951a0cf..048be8c 100644 --- a/site/content/docs/(latest)/testing/index.mdx +++ b/site/content/docs/(latest)/testing/index.mdx @@ -3,30 +3,38 @@ title: Test with a fake backend description: Test calls against a fake backend made from your endpoints. --- -This tutorial builds a fake backend from your endpoints and runs a call -against it, so you can test your code without a network. +Tests that call a real API are slow, flaky, and hard to point at an error +case. Effetch never touches the network itself: it sends every request +through the `HttpClient` you provide. In tests, `@monarcode/effetch/test` +gives you a fake one, made from your endpoints, so your code runs as it does +in production: the real client, with its plugins, `defaultError` and +`statusErrors`. -Effetch never touches the network itself: it sends every request through the -`HttpClient` you provide. In tests, `@monarcode/effetch/test` gives you a fake -one, made from your endpoints, so your code runs as it does in production: -the real client, with its plugins, `defaultError` and `statusErrors`. +In this tutorial, you write a test file that answers three endpoints from a +fake backend, then run it and check what comes back. -## Build a fake backend from your endpoints +## Before you begin -`FetchTest.layer` takes a list of handlers, one per route, and is an -`HttpClient` layer. Provide it where `FetchHttpClient.layer` goes. +You need: - - A client whose `layer` is - [overridden](/docs/clients/providing#build-the-httpclient-into-the-layer) to - provide its own `HttpClient` ignores the fake backend, so test with a layer - that doesn't. - +- endpoints defined with `Fetch.endpoint` (see + [Define endpoints](/docs/endpoints/defining)); +- a test runner. This tutorial uses [Vitest](https://vitest.dev) with + `@effect/vitest`, which runs an Effect as a test: + + ```bash + npm install --save-dev vitest @effect/vitest + ``` + +`FetchTest` doesn't depend on a test runner, so the same code works with Jest, +Bun or Deno: see [Run it without Vitest](#run-it-without-vitest). -The following example defines three endpoints, answers each one from the fake -backend, and gets a todo through the real client: +## Write the test + +Create a file named `todos.test.ts` with the following content: ```ts +import { expect, it } from "@effect/vitest"; import * as Effect from "effect/Effect"; import * as Layer from "effect/Layer"; import * as Schema from "effect/Schema"; @@ -34,6 +42,7 @@ import * as Schema from "effect/Schema"; import { Fetch } from "@monarcode/effetch"; import { FetchTest } from "@monarcode/effetch/test"; +// 1. The endpoints, the client and the service your app already has const Todo = Schema.Struct({ id: Schema.Finite, title: Schema.String, @@ -65,6 +74,7 @@ class TodoApi extends Fetch.Endpoints()("TodoApi", Api, { list: listTodos, }) {} +// 2. A handler for each endpoint const Backend = FetchTest.layer([ FetchTest.respond(getTodo, ({ params }) => // params are strings, as they are in the URL @@ -80,53 +90,171 @@ const Backend = FetchTest.layer([ FetchTest.fail(listTodos, 503), ]); +// 3. The real client, sending its requests to the fake backend const TestLayer = TodoApi.layer.pipe( Layer.provide(Api.layer), Layer.provide(Backend), ); -export const test = Effect.gen(function* () { - const todos = yield* TodoApi; - const todo = yield* todos.get({ params: { id: 1 } }); - // todo.due is a Date again: it went over the wire as a string - return todo; -}).pipe(Effect.provide(TestLayer)); +// 4. The tests, each one an Effect +it.effect("gets a todo", () => + Effect.gen(function* () { + const todos = yield* TodoApi; + const todo = yield* todos.get({ params: { id: 1 } }); + expect(todo.title).toBe("Write docs"); + // A Date again: it went over the wire as a string + expect(todo.due).toBeInstanceOf(Date); + }).pipe(Effect.provide(TestLayer)), +); + +it.effect("fails when the list is unavailable", () => + Effect.gen(function* () { + const todos = yield* TodoApi; + const error = yield* Effect.flip(todos.list()); + expect(error).toMatchObject({ _tag: "HttpError", status: 503 }); + }).pipe(Effect.provide(TestLayer)), +); +``` + +Each numbered part of the file is one step: + +1. **Define the endpoints.** These are the same `Fetch.endpoint` definitions, + client and `Fetch.Endpoints` class your app uses. In a real project, you + import them rather than declare them in the test. +2. **Write a handler for each endpoint.** `FetchTest.respond` answers an + endpoint with what its handler returns, and `FetchTest.fail` answers every + request with an error status. `FetchTest.layer` turns the list into a fake + backend. +3. **Provide the fake backend.** `FetchTest.layer` is an `HttpClient` layer + (a layer is how Effect builds a service, such as the client, for a + program that needs it), so it goes where `FetchHttpClient.layer` goes in + your app. Here it's provided under `Api.layer`, so the real client sends + its requests to it. +4. **Write the tests.** Each test gets the service, makes a call, and + checks what comes back. `Effect.flip` turns the failure into a value, so + the second test can check the error. + + + A client whose `layer` is + [overridden](/docs/clients/providing#build-the-httpclient-into-the-layer) to + provide its own `HttpClient` ignores the fake backend, so test with a layer + that doesn't. + + +## Run the test + +Run Vitest: + +```bash +npx vitest run +``` + +Both tests pass: + +```text + Test Files 1 passed (1) + Tests 2 passed (2) ``` +The first test checks that `todo.due` is a `Date`. The handler returned a +`Date`, the fake backend encoded it as a string, and the client decoded it +back, as it would with a real server. The second checks that `GET /todos` +failed with an `HttpError` whose status is 503. + ## What a handler gets and returns What a handler gets and returns is typed by its endpoint, and checked as a -real backend would check it: +real backend would check it. The handler gets one object, with these +properties: - **`params`** has the route's params, as strings. - **`body`** is decoded with the endpoint's `input` schema, so `body.due` is a - `Date` here. A [multipart](/docs/calls/uploads) body is read back from the - form, with its files as `File`s. + `Date` in the test. A [multipart](/docs/calls/uploads) body is read back + from the form, with its files as `File`s. - **`query`** is decoded with the endpoint's - [query schema](/docs/endpoints/typed-query), if it has one, and is the raw - query, as strings, otherwise. + [query schema](/docs/endpoints/typed-query), if it has one. Otherwise, it's + the raw query, as strings. +- **`headers`** are the request's headers, with lowercase names. +- **`url`** is the URL the request was sent to. +- **`request`** is the request itself, for anything else. + +A handler returns an Effect that can't fail. What it succeeds with is sent +back to the client: + - **The result** has `output`'s type, and is encoded with `output` before it's sent, so a `Date` goes over the wire as a string, as in production. With [`Fetch.text()` or `Fetch.bytes()`](/docs/calls/responses), it's sent as text or bytes. +- **Without `output`,** the result is sent by its runtime type, as a call's + `body` without `input` is, and `undefined` sends no body. +- **The status** is 200, or 204 when there's no body to send. + +To answer with another status or an error, return `FetchTest.reply` instead +(see [Test errors and statuses](/docs/testing/errors)). A body, query or result that doesn't match its schema is a defect that names the route: it's a bug in the code under test, or in the test. Handlers work the same for definitions made with `Fetch.endpoint`, endpoints made with -`client.endpoint` or `client.bind`, and a `Fetch.Endpoints` class's +`api.endpoint` or `api.bind`, and a `Fetch.Endpoints` class's `definitions`. ### Handlers that use services A handler can use services, such as a clock or a store of fake data. The -layer then needs them, and runs its handlers with the services it was built -with, and those of the call they answer, which win when both have one. +layer then needs those services to be built. Each handler runs with the +services the layer was built with, plus those of the call it answers. When +both have the same service, the call's wins. -## Run the test +### Slow responses + +A handler is an Effect, so it can wait before it answers, which lets you +test a `timeout` plugin or a loading state: + +```ts +import * as Effect from "effect/Effect"; +import * as Schema from "effect/Schema"; + +import { Fetch } from "@monarcode/effetch"; +import { FetchTest } from "@monarcode/effetch/test"; + +const Todo = Schema.Struct({ id: Schema.Finite, title: Schema.String }); +const getTodo = Fetch.endpoint("GET /todos/:id", { output: Todo }); + +// Answers after 2 seconds +export const SlowBackend = FetchTest.layer([ + FetchTest.respond(getTodo, () => + Effect.as(Effect.sleep("2 seconds"), { id: 1, title: "Write docs" }), + ), +]); +``` + +`it.effect` runs a test on a test clock, which only moves when you move it, +so a handler that sleeps waits forever. Run the test with `it.live` instead, +or fork the call and move the clock with `TestClock.adjust`. + +What the fake backend can't do is send a body in pieces: it sends the whole +body at once. For a body that arrives slowly or breaks off, see +[Use a hand-written HttpClient](/docs/testing/http-client). + +## Run it without Vitest + +A test is an Effect, so any runner can run it with `Effect.runPromise`. With +Jest, Bun or Deno, write the test as an Effect that uses your runner's +`expect`, as in [Write the test](#write-the-test), and run it inside the +runner's test function: + +```ts +import * as Effect from "effect/Effect"; + +// The Effect of a test, with Effect.provide(TestLayer) applied +declare const getsATodo: Effect.Effect; + +// Inside your runner's test function: +await Effect.runPromise(getsATodo); +``` -`FetchTest` doesn't depend on a test runner: a test is an Effect, so run it -with `it.effect` from `@effect/vitest`, or with `Effect.runPromise` in Jest, -Bun or Deno. +A failed `expect` throws inside the Effect, so `runPromise` rejects and the +test fails. A call that fails with an error you didn't catch rejects it too. ## What's next @@ -137,4 +265,4 @@ Bun or Deno. - [Test stream endpoints](/docs/testing/streams): answer a stream endpoint with a list of events or values. - [Use a hand-written HttpClient](/docs/testing/http-client): fake a network - failure or a slow response. + failure, or a body that arrives slowly or breaks off. diff --git a/site/content/docs/(latest)/testing/requests.mdx b/site/content/docs/(latest)/testing/requests.mdx index 2a6e5e8..506fc9f 100644 --- a/site/content/docs/(latest)/testing/requests.mdx +++ b/site/content/docs/(latest)/testing/requests.mdx @@ -3,16 +3,16 @@ title: Check what was sent description: Assert on the requests your code sent, and learn how they're matched. --- -This page shows how to read the requests the [fake backend](/docs/testing) -received, so you can assert on what your code sent, and explains how the -fake backend matches each request to a handler. +Sometimes what matters in a test isn't what comes back but what your code sent: +that a delete went to the right URL, or that a form carried the right +fields. The [fake backend](/docs/testing) records every request it +receives, so you can assert on them. This page shows how to read those +records, and how the fake backend picks a handler for each request. ## Read the recorded requests -The layer also provides `FetchTest.Recorder`, which keeps every request it -received, with a new record each time the layer is built. -`FetchTest.requests` reads it. Under a client's layer, `Layer.provide` would -hide it, so use `Layer.provideMerge`: +`FetchTest.requests` gives you the requests the fake backend received, +oldest first: ```ts import * as Effect from "effect/Effect"; @@ -41,9 +41,26 @@ export const test = Effect.gen(function* () { }).pipe(Effect.provide(Api.layer.pipe(Layer.provideMerge(Backend)))); ``` -Each recorded request has its `method`, `url`, the `route` and `params` it -matched, its raw `query`, its `headers`, and its `body`, read back as JSON, -text or bytes. +The records live in `FetchTest.Recorder`, a service that the fake backend's +layer provides, with a new, empty record each time the layer is built. +Notice `Layer.provideMerge` in the last line. Under a client's layer, +`Layer.provide` would hide the recorder from your test, while +`Layer.provideMerge` keeps it available. + +Each recorded request has the following properties: + +- `method`, such as `"DELETE"`; +- `url`, with its query string; +- `route` and `params`, the route and the path params it matched, as + strings; +- `query`, the raw query parameters; +- `headers`, with lowercase names; +- `body`, read back: the value of a JSON body, the text of a text or form + body, the bytes of other bytes, a `FormData` or stream as it was sent, or + `undefined` without one. + +A request that no route matched is recorded too, with `route` set to +`undefined` and `params` set to `{}`. ## How requests are matched @@ -61,8 +78,8 @@ The fake backend picks a handler for each request by these rules: segments wins, then the one with the most literal segments, so `GET /todos/count` wins over `GET /todos/:id`. After that, the one listed first wins. -- **Absolute routes** such as `POST https://uploads.example.com/files` match - that URL only. +- **Absolute routes,** such as `POST https://uploads.example.com/files`, + match that URL only. - **No match is a defect,** whose message lists the backend's routes, and the ones that match the path with another method: @@ -79,5 +96,5 @@ The fake backend picks a handler for each request by these rules: fail, or answer with another status. - [Use a hand-written HttpClient](/docs/testing/http-client): fake what the fake backend doesn't do, such as a network failure. -- [FetchTest](/docs/reference/fetch-test): every member of the `FetchTest` - namespace. +- [FetchTest](/docs/reference/fetch-test): look up every member of the + `FetchTest` namespace. diff --git a/site/content/docs/(latest)/testing/streams.mdx b/site/content/docs/(latest)/testing/streams.mdx index 03bc736..542ff89 100644 --- a/site/content/docs/(latest)/testing/streams.mdx +++ b/site/content/docs/(latest)/testing/streams.mdx @@ -3,21 +3,16 @@ title: Test stream endpoints description: Fake a streamed response with a list of events or values. --- -This page shows how to answer a [stream endpoint](/docs/streaming) from the -[fake backend](/docs/testing), so you can test code that reads Server-Sent -Events or newline-delimited JSON. +Code that reads Server-Sent Events or newline-delimited JSON is easiest to +test when you control exactly what the server sends. The +[fake backend](/docs/testing) answers a [stream endpoint](/docs/streaming) +from a list, so you can test how your code handles each event or value. +This page shows how. ## Answer with a list A handler for a stream endpoint returns a list, and `FetchTest` sends it as -the stream's body: - -- For `stream: "sse"`, the list holds events, each with its `data` and an - optional `event` and `id`. -- For `stream: "ndjson"`, the list holds values. - -Each value is encoded with the endpoint's `output`. The following backend -sends two events for a job: +the stream's body. The following backend sends two events for a job: ```ts import * as Effect from "effect/Effect"; @@ -43,17 +38,26 @@ export const Backend = FetchTest.layer([ ]); ``` +What the list holds depends on the endpoint's `stream`: + +- For `stream: "sse"`, the list holds events, each with its `data` and an + optional `event` and `id`. +- For `stream: "ndjson"`, the list holds values. + +Each value is encoded with the endpoint's `output` before it's sent, as a +plain response is. + ## Test slow or broken streams -The whole body is sent at once. To test how your code handles values that -arrive slowly, or a body that breaks off, use -[a hand-written `HttpClient`](/docs/testing/http-client) whose `Response` -has a `ReadableStream` body. +The fake backend sends the whole body at once. To test how your code +handles values that arrive slowly, or a body that breaks off partway, use +[a hand-written `HttpClient`](/docs/testing/http-client#send-a-body-that-breaks-off) +whose response has a `ReadableStream` body. ## What's next -- [Streaming responses](/docs/streaming): how stream endpoints read events - and values, and how a stream fails. +- [Streaming responses](/docs/streaming): see how stream endpoints read + events and values, and how a stream fails. - [Use a hand-written HttpClient](/docs/testing/http-client): send a body that arrives slowly or breaks off. - [Check what was sent](/docs/testing/requests): assert on the requests your diff --git a/site/content/docs/(latest)/upgrading.mdx b/site/content/docs/(latest)/upgrading.mdx index df007de..761b912 100644 --- a/site/content/docs/(latest)/upgrading.mdx +++ b/site/content/docs/(latest)/upgrading.mdx @@ -3,81 +3,162 @@ title: Upgrade from 0.1.0-rc.3 description: Move a project's imports to the Fetch namespace with the effetch-migrate command. --- -This page shows how to move a project written for 0.1.0-rc.3 or earlier to -the `Fetch` export, with the `effetch-migrate` command. +Up to 0.1.0-rc.3, Effetch's main entry exported each API by name, and you +imported it with `import * as Fetch` or name by name. From 0.1.0-rc.4, +everything in the main entry is under one export, `Fetch`, so code that +imports it the old way doesn't compile. The package comes with a command, +`effetch-migrate`, that rewrites those imports for you. This page walks you +through the upgrade, from installing 0.1.0-rc.4 or later to a project that +type-checks again. + +## What changes in your code + +The import and export lines change, and so does each use of a name you +imported on its own, which becomes a member of `Fetch`. Uses such as +`Fetch.endpoint` stay as they are. Here's a file before and after the +migration: + +```diff +-import * as Fetch from "@monarcode/effetch"; +-import { HttpError, type Client } from "@monarcode/effetch"; ++import { Fetch } from "@monarcode/effetch"; + + export const getTodo = Fetch.endpoint("GET /todos/:id"); + +-export const describe = (api: Client, error: HttpError) => ++export const describe = (api: Fetch.Client, error: Fetch.HttpError) => + `${error.status}`; + +-export { DecodeError } from "@monarcode/effetch"; ++export { DecodeError } from "@monarcode/effetch/Fetch"; +``` -Before 0.1.0-rc.4, the main entry exported each API by name, and you -imported it with `import * as Fetch`. Since 0.1.0-rc.4, everything in the -main entry is under one export, `Fetch` (see -[Installation](/docs/installation)). +The `/plugins` and `/test` entries didn't change, and the command leaves +their imports alone. ## Before you begin -Upgrade the project's `@monarcode/effetch` dependency first. Then run the -commands on this page in the directory of the package that depends on -Effetch. The commands use `npx`; with pnpm, run `pnpm exec effetch-migrate` -instead. +Check the following before you start: -## Preview the changes +- TypeScript is installed in the project. The command reads your code with + the project's own TypeScript. Without it, the command stops with an + error. +- You know which directory to run the commands in: the directory of the + package that depends on Effetch. In a monorepo, that's the package's own + directory, not the repository's root. -To list the files the migration would change, without changing them, run -the following command: +The commands on this page use npm. With pnpm, run `pnpm add` in place of +`npm install`, and `pnpm exec effetch-migrate` in place of +`npx -p @monarcode/effetch effetch-migrate`. -```bash -npx -p @monarcode/effetch effetch-migrate --dry-run -``` +## Migrate the project -## Run the migration +1. Upgrade `@monarcode/effetch` to 0.1.0-rc.4 or later: -To change the files, run the following command: + ```bash + npm install @monarcode/effetch@latest + ``` -```bash -npx -p @monarcode/effetch effetch-migrate -``` +2. Commit your changes, the upgrade included, or stash them. The command + rewrites files in place. With a clean working tree, `git diff` shows + exactly what it changed, and `git restore .` undoes it. +3. Preview the migration. The following command lists the files it would + change, and changes none: + + ```bash + npx -p @monarcode/effetch effetch-migrate --dry-run + ``` + +4. Run the migration: + + ```bash + npx -p @monarcode/effetch effetch-migrate + ``` + + It prints a line for each file it updated, a `Check` line for each place + it couldn't rewrite, and a summary such as + `3 of 4 files importing @monarcode/effetch changed, 1 to check by hand.` + +5. Change by hand each place it listed with `Check`. The file and line are + in the message, and [What you change by hand](#what-you-change-by-hand) + says what to do with each kind. +6. Run your formatter, since rewritten lines may need reflowing. +7. Run your type checker, such as `npx tsc --noEmit`. When it passes, the + migration is done. + +## What the command rewrites -The migration makes these changes: +The command reads only files that name the main entry, +`@monarcode/effetch`, in a string, such as an import. It makes the +following changes in them: - `import * as Fetch from "@monarcode/effetch"` becomes - `import { Fetch } from "@monarcode/effetch"`. + `import { Fetch } from "@monarcode/effetch"`. Under another name, as in + `import * as Api`, it becomes `import { Fetch as Api }`. A type-only + import stays type-only, unless the file also imports a value from + Effetch, which joins the same import. - Named imports, such as `import { HttpError, type Client }`, become `import { Fetch }`, and each use becomes `Fetch.HttpError` or - `Fetch.Client`. + `Fetch.Client`. When the file already has something called `Fetch`, the + import is named `Effetch`, then `EffetchFetch`, then `Fetch2`, `Fetch3` + and so on, whichever is free. +- A name that the file also re-exports, as in `export { HttpError }`, keeps + its name, and is imported from `@monarcode/effetch/Fetch`. - `export … from "@monarcode/effetch"` re-exports from - `@monarcode/effetch/Fetch`, and `import("@monarcode/effetch").Client` - types become `import("@monarcode/effetch").Fetch.Client`. -- Code that already imports `Fetch` is left as it is. + `@monarcode/effetch/Fetch`, which has the main entry's old exports. A + re-export of `Fetch` itself stays on the main entry. +- Types written as `import("@monarcode/effetch").Client` become + `import("@monarcode/effetch").Fetch.Client`. + +Code that already imports `Fetch` is left as it is. + +## What you change by hand + +The command lists what it can't rewrite, each with its file and line: + +- a dynamic `import()` of the package. Use its `Fetch` member, as in + `(await import("@monarcode/effetch")).Fetch`; +- the package's name passed to a call, such as + `vi.mock("@monarcode/effetch")`. The module exports only `Fetch`, so a + mock of it needs to as well; +- the package's name anywhere else in the code, as a string; +- an import or export inside a `declare module` block; +- a default import of the package, which has none; +- a `/** … */` comment that mentions the package; +- in a JavaScript file, a JSDoc comment that uses a name the command + rewrote, such as `{HttpError}`; +- comments inside an import or export it rewrote, which it dropped; +- a file that TypeScript couldn't read, which it left unchanged. + +The command doesn't read Markdown, so update code in your docs by hand. ## Choose the files it reads -The migration reads `.ts`, `.tsx`, `.js` and similar files, and uses the -project's own TypeScript. Which files it reads depends on where it runs: +The command reads `.ts`, `.tsx`, `.mts`, `.cts`, `.js`, `.jsx`, `.mjs` and +`.cjs` files. Which of them it reads depends on where it runs: - In a git repository, it reads the files git sees, so it skips what `.gitignore` does. - Elsewhere, it skips `node_modules`, `dist`, `build`, `coverage` and hidden directories, and lists the build output it skipped. -To choose what it reads, pass paths, such as `effetch-migrate src test`. - -## Change the rest by hand - -The migration lists, with their lines, what it can't rewrite. Change these -by hand: - -- a dynamic `import()`; -- a `vi.mock("@monarcode/effetch")`; -- an import inside a `declare module` block; -- JSDoc comments that use the old names. - -The migration doesn't read Markdown. +To choose what it reads, pass files or directories, as in +`effetch-migrate src test`. With no path, it reads the current directory. -## Finish the migration +## Other changes -After the migration, run your formatter and type checker. +The command covers the imports, which is the change that stops code from +compiling. 0.1.0-rc.4 changed one more thing: a `content-type` header set by +a call, an endpoint or the client is removed for a `FormData` body, so the +platform's multipart boundary is kept. Earlier releases changed other +things. The +[changelog](https://github.com/monarcode/effetch/blob/main/CHANGELOG.md) +lists every release's changes, and what to change in your code for each. +Read the entries from your version up. ## What's next -- [Installation](/docs/installation): see the entry points Effetch has now - and how to import from them. +- [Installation](/docs/installation): see Effetch's entry points, and how + to import from each one. - [Getting started](/docs/getting-started): write a complete program with the `Fetch` export. diff --git a/site/package.json b/site/package.json index a2c64cc..dc916e6 100644 --- a/site/package.json +++ b/site/package.json @@ -22,7 +22,8 @@ "fumadocs-ui": "npm:@fumadocs/base-ui@16.19.0", "lucide-react": "1.72.0", "react": "19.3.1", - "react-dom": "19.3.1" + "react-dom": "19.3.1", + "takumi-js": "2.22.1" }, "devDependencies": { "@tailwindcss/vite": "4.3.5", diff --git a/site/public/_headers b/site/public/_headers new file mode 100644 index 0000000..d6c58bc --- /dev/null +++ b/site/public/_headers @@ -0,0 +1,7 @@ +# Response headers. Cloudflare Pages reads this file. + +# Vite names each asset by its content's hash, so a changed file gets a new +# name and the old one can be cached for good. +/assets/* + ! Cache-Control + Cache-Control: public, max-age=31536000, immutable diff --git a/site/public/_redirects b/site/public/_redirects new file mode 100644 index 0000000..21662a2 --- /dev/null +++ b/site/public/_redirects @@ -0,0 +1,10 @@ +# Pages merged into another page. Cloudflare Pages reads this file. +/docs/calls/parameters /docs/calls#fill-in-path-parameters 301 +/docs/calls/parameters/ /docs/calls#fill-in-path-parameters 301 +/docs/calls/parameters.md /docs/calls.md 301 +/docs/errors/error-bodies /docs/errors/catching#read-the-error-body 301 +/docs/errors/error-bodies/ /docs/errors/catching#read-the-error-body 301 +/docs/errors/error-bodies.md /docs/errors/catching.md 301 +/docs/plugins/order /docs/plugins#how-plugins-nest 301 +/docs/plugins/order/ /docs/plugins#how-plugins-nest 301 +/docs/plugins/order.md /docs/plugins.md 301 diff --git a/site/src/components/landing/chrome.tsx b/site/src/components/landing/chrome.tsx index 162ef42..ae0cd77 100644 --- a/site/src/components/landing/chrome.tsx +++ b/site/src/components/landing/chrome.tsx @@ -112,7 +112,7 @@ export function Install() { > {copied ? (