diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 764da51..c0957c3 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -7,6 +7,11 @@ on: push: branches: [main] pull_request: + # Weekly, so a new Effect 4.x or TypeScript 7.x that breaks Effetch shows + # up without waiting for a push: those jobs install the newest versions. + schedule: + - cron: "0 6 * * 1" + workflow_dispatch: permissions: contents: read @@ -68,6 +73,130 @@ jobs: - name: Build and test run: pnpm run typecheck && pnpm test && pnpm run build + newest-effect: + name: check (newest effect) + runs-on: ubuntu-latest + timeout-minutes: 10 + steps: + - name: Check out repository + uses: actions/checkout@v7 + + - name: Set up pnpm + uses: pnpm/action-setup@v6 + with: + version: 10.12.1 + + - name: Set up Node.js + uses: actions/setup-node@v7 + with: + node-version: 24 + cache: pnpm + + - name: Install dependencies + run: pnpm install --frozen-lockfile + + # The peer range is `^4.0.0`, so a new 4.x reaches users without a + # release of Effetch. The versions are looked up, because pnpm keeps + # the lockfile's version for a range it already satisfies. + # npm lists versions in publish order, so a backport can come last: + # sort them first. + - name: Install newest effect 4.x + shell: bash + run: | + set -euo pipefail + newest() { + npm view "$1@^4" version --json | + node -p '[].concat(JSON.parse(require("fs").readFileSync(0, "utf8"))).sort((a, b) => a.localeCompare(b, "en", { numeric: true })).pop()' + } + effect="$(newest effect)" + vitest="$(newest @effect/vitest)" + for version in "$effect" "$vitest"; do + if ! [[ "$version" =~ ^4\.[0-9]+\.[0-9]+$ ]]; then + echo "::error::Couldn't look up the newest 4.x version (got '$version')" + exit 1 + fi + done + echo "Testing effect@$effect with @effect/vitest@$vitest" + pnpm add --workspace-root --save-dev --save-exact \ + "effect@$effect" "@effect/vitest@$vitest" + + - name: Build and test + run: pnpm run typecheck && pnpm test && pnpm run build + + # The installed package against the TypeScript versions and runtimes the + # docs name, beyond the `check` job's TypeScript 6 and Node.js 24. Each + # reuses the smoke test's consumer program (scripts/compat.sh). + compatibility: + name: ${{ matrix.name }} + runs-on: ubuntu-latest + timeout-minutes: 10 + strategy: + fail-fast: false + matrix: + include: + - name: typescript 5.7 (oldest supported) + mode: typescript + target: "5.7" + - name: typescript 7 + mode: typescript + target: "7" + - name: node.js 20 + mode: runtime + target: node + node: 20 + - name: node.js 22 + mode: runtime + target: node + node: 22 + - name: bun + mode: runtime + target: bun + - name: deno + mode: runtime + target: deno + steps: + - name: Check out repository + uses: actions/checkout@v7 + + - name: Set up pnpm + uses: pnpm/action-setup@v6 + with: + version: 10.12.1 + + - name: Set up Node.js + uses: actions/setup-node@v7 + with: + node-version: 24 + cache: pnpm + + - name: Install dependencies + run: pnpm install --frozen-lockfile + + # Builds, packs and writes the consumer program the check reuses. + - name: Smoke test + run: pnpm run smoke + + - name: Set up Node.js ${{ matrix.node }} + if: matrix.node + uses: actions/setup-node@v7 + with: + node-version: ${{ matrix.node }} + + - name: Set up Bun + if: matrix.target == 'bun' + uses: oven-sh/setup-bun@v2 + with: + bun-version: 1.x + + - name: Set up Deno + if: matrix.target == 'deno' + uses: denoland/setup-deno@v2 + with: + deno-version: 2.x + + - name: Check ${{ matrix.mode }} ${{ matrix.target }} + run: bash scripts/compat.sh ${{ matrix.mode }} ${{ matrix.target }} + site: name: build docs site runs-on: ubuntu-latest diff --git a/.oxlintrc.json b/.oxlintrc.json index 0f8293d..6fc92c7 100644 --- a/.oxlintrc.json +++ b/.oxlintrc.json @@ -76,6 +76,22 @@ ] } }, + { + "files": ["examples/store-react/**"], + "plugins": [ + "import", + "promise", + "typescript", + "unicorn", + "react", + "jsx-a11y" + ], + "env": { "browser": true, "node": true }, + "rules": { + "react/exhaustive-deps": "warn", + "jsx-a11y/alt-text": "error" + } + }, { "files": ["site/**"], "plugins": [ diff --git a/AGENTS.md b/AGENTS.md index 7de0dc1..a1e7e6f 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -24,7 +24,8 @@ inline conditional types. One exception: `CallEffect` and the call signatures (`NoBodyMethod`, `BodyMethod`, `RequestMethod`, `Endpoint`) write out the members of `CallError` and `CallServices`, so hovers show - the errors rather than the alias. Keep them in sync; the type tests check + the errors rather than the alias, and `Fetch.errorCodec` writes out + those of `ErrorCodecErrors`. Keep them in sync; the type tests check each one against the aliases. 4. **Runtime targets: browsers, React Native (Hermes/Metro), Node ≥ 20, Bun, Deno.** No `node:` imports, no Node globals, **no `new URL()`** (React diff --git a/CHANGELOG.md b/CHANGELOG.md index 7c785b7..83e26a0 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,12 +2,98 @@ All notable changes to `@monarcode/effetch`, newest first. -## Unreleased +## 0.1.0 + +The first stable release. From here, an update within 0.1.x doesn't break +code written for 0.1.0, apart from the few exceptions that +[Versioning](https://effetch.monarcode.dev/docs/reference/compatibility#versioning) +lists. The changes since 0.1.0-rc.5: + +### Added + +- `Fetch.errorCodec` builds a codec (a schema with a JSON encoding) for + every error a call can fail with, to send its failures where only data + goes: an Effect RPC's `error`, a server-rendered page, a worker. The + other side gets the same errors back, typed as on the server: an + `HttpError`'s body is decoded again from the response text with the + call's error schema, and the `statusErrors` errors come back as their own + classes. + - Give it a bound endpoint (`Fetch.errorCodec(todos.get)`), a definition + and its client (`Fetch.errorCodec(getTodo, { client: Api })`), or the + schemas of a plain method call + (`Fetch.errorCodec({ error: ApiError, statusErrors: { 404: NotFound } })`). + - Add plugins' errors, such as `TimeoutError`, as `errors`. + - Headers, a `NetworkError`'s `cause` and a `DecodeError`'s `issue` stay + behind. + - An error whose schema sends no `_tag` goes with its schema's name, + the `_tag` it leaves out or its identifier, such as a class's name, so + it decodes with its own schema, even when the other side lists its + errors in another order. A schema without a name of its own goes by + its place among those, so both sides must list them in the same order. + + It comes with the types `ErrorCodec`, `ErrorCodecErrors`, + `ErrorCodecSource`, `ErrorCodecClient` and `ErrorCodecOptions`. A new + page, + [Send errors across the wire](https://effetch.monarcode.dev/docs/errors/across-the-wire), + shows it with an RPC. + +### Fixed + +- `HttpError`, `NetworkError` and `DecodeError` now encode to JSON and + decode back into the same classes, so they can be an Effect RPC's `error` + or cross from the server to the browser. Before, + `Schema.toCodecJson(Fetch.HttpError)` couldn't decode any `HttpError`, and + the other two couldn't be encoded. What's sent: + - an `HttpError` goes without its headers, which decode as empty, so + `set-cookie` and the like stay where they were. Its `body` goes when + it's JSON. A body decoded into something else, such as a class, + doesn't, and decodes as `undefined`. + - a `NetworkError` goes without its `cause`, and a `DecodeError` without + its `issue`. Both decode as `undefined`. + + Constructing the errors and reading their fields are unchanged. Their + schemas' `Encoded` types now match what's sent. ### Changed - The documentation site moved to https://effetch.monarcode.dev. The old address, https://effetch.pages.dev, still serves it. +- CI now runs the installed package on Node.js 20 and 22, Bun 1 and Deno 2, + compiles it with TypeScript 5.7 (the oldest supported) and 7, and runs the + tests against the newest Effect 4.x. The + [Compatibility](https://effetch.monarcode.dev/docs/reference/compatibility) + page lists what each job covers. + +### Documentation + +- Effetch has a versioning policy, in the README and on the + [Compatibility](https://effetch.monarcode.dev/docs/reference/compatibility#versioning) + page. An update within 0.1.x doesn't break code written for 0.1.0: the + API, the fields errors encode to and the supported TypeScript versions + and runtimes stay as they are, and breaking changes wait for 0.2.0. The + exceptions follow Effect, which marks its HTTP modules and `encoding/Sse` + unstable: when they change, a 0.1.x update can change the types that come + from them, how Server-Sent Events behave, or the oldest `effect` it + supports. In 0.2.0, `retry` waits as a `Retry-After` header asks by + default. The "release candidate" notes are gone. +- The examples are new. Each one does a real task against a free public + API that needs no key, and runs with `pnpm example `: + - `github/` shows a repository and its open issues; + - `sign-in/` signs in and renews the access token; + - `live/` reads Wikipedia's edits and Lichess TV's moves as they stream; + - `upload/` sends a multipart body; + - `bff/` sends a server's call errors to the browser with + `Fetch.errorCodec`; + - `store/` is an app in feature modules. It replaces `app/`, with the + same layout; + - `store-react/` puts `store/`'s modules behind a React app routed with + TanStack Router. Its loaders cancel their requests when you leave the + page, and `pnpm example store-react` starts its dev server. + + Their tests run offline against `FetchTest`, as part of the test suite. + The old examples, which called an API that doesn't exist and were only + typechecked, are gone. See + [Examples](https://effetch.monarcode.dev/docs/examples). ## 0.1.0-rc.5 diff --git a/README.md b/README.md index d95f33a..828b2d1 100644 --- a/README.md +++ b/README.md @@ -50,15 +50,17 @@ export const getTodo = (id: number) => // NetworkError | DecodeError | HttpError, Api> ``` -> **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. +> **Versioning.** An update within 0.1.x doesn't break code written for +> 0.1.0, and breaking changes wait for 0.2.0, with notes in the +> [changelog](./CHANGELOG.md). The exceptions follow Effect, which marks its +> HTTP modules and Server-Sent Events parser unstable. +> [Versioning](https://effetch.monarcode.dev/docs/reference/compatibility#versioning) +> has the details. ## Documentation -The guides and the API reference are at -**[effetch.monarcode.dev/docs](https://effetch.monarcode.dev/docs)**. +The guides and the API reference are in the +**[Effetch website](https://effetch.monarcode.dev/)**. ## Install @@ -153,29 +155,27 @@ Calling an API from a web page on another origin? Read ## Examples -[`examples/`](examples) has complete programs, typechecked with the package so -they always match the current API: - -- [`basic.ts`](examples/basic.ts): a client in a service, the methods, and - handling each error. -- [`builtins.ts`](examples/builtins.ts): the built-in plugins, and changing - them for one call. -- [`plugins.ts`](examples/plugins.ts): writing plugins, from auth with a - service to a `wrap` with its own error. -- [`endpoints.ts`](examples/endpoints.ts): the same app as `builtins.ts`, with - endpoints. -- [`backends.ts`](examples/backends.ts): two backends in one file, with shared - plugins. -- [`status-errors.ts`](examples/status-errors.ts): your own errors by status, - for every call, per endpoint and for one call. -- [`streams.ts`](examples/streams.ts): Server-Sent Events, newline-delimited - JSON, and a list paged through by its `Link` header. -- [`testing.ts`](examples/testing.ts): tests for the `app/` todos module, - against a fake backend made from its endpoints. -- [`app/`](examples/app): a feature-sliced app, with clients as shared - infrastructure and each module defining its own endpoints. - -Its [README](examples/README.md) walks through each one. +[`examples/`](examples) has programs that use Effetch for a real task, +against free public APIs, with no key needed. Run one with +`pnpm example `: + +- [`github/`](examples/github): a repository and its open issues, with + endpoints, errors of your own, paging and a plugin. +- [`sign-in/`](examples/sign-in): signing in, and renewing the access token + when it's refused. +- [`live/`](examples/live): Wikipedia's edits and Lichess TV's moves, read + as they stream in. +- [`upload/`](examples/upload): a file and form fields, as a multipart body. +- [`bff/`](examples/bff): a server's call errors sent to the browser over + Effect RPC, with `Fetch.errorCodec`. +- [`store/`](examples/store): an app in feature modules, with a workflow and + its tests. +- [`store-react/`](examples/store-react): the same modules behind a React + app, whose TanStack Router loaders cancel their requests when you leave + the page. + +Each one has tests that run offline, against a fake backend. Its +[README](examples/README.md) says how to run them, and what each shows. ## Development @@ -197,6 +197,7 @@ pnpm run check | `pnpm run check:docs` | Checks every public export has a description, `@example` and `@since`, compiles every example in the JSDoc, this README and the docs site's pages, and checks the site's API reference matches the JSDoc. | | `pnpm run smoke` | Packs the package, installs it in a fresh project, typechecks and runs a consumer, and checks go-to-definition, hovers and completions. | | `pnpm run check` | All of the above, plus publint and attw. CI runs it on every push to `main` and every pull request. | +| `pnpm run compat` | After `smoke`, checks the installed package (not part of `check`; CI runs it) with another TypeScript version or runtime: `pnpm run compat typescript 5.7`, or `runtime node`, `bun` or `deno`. | | `pnpm run build:site` | Builds the package, then prerenders the docs site in `site/` to `site/dist/client`, failing on a type error in an example. `check` doesn't build the site; CI does. | | `pnpm run docs:reference` | Writes the site's API reference pages from the JSDoc. Run it after changing a public export or its docs. | | `pnpm run docs:snapshot` | Freezes an older release line's docs into the site, such as `pnpm run docs:snapshot 0.1` when `0.2` starts. | diff --git a/examples/README.md b/examples/README.md index 2327ecd..387a426 100644 --- a/examples/README.md +++ b/examples/README.md @@ -1,34 +1,54 @@ # Examples -Complete programs using Effetch. They're typechecked with the package -(`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 | -| -------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------ | -| [`basic.ts`](basic.ts) | A client in a service, the methods (`get`, `post`, `patch`, `del`) and handling each error. | -| [`builtins.ts`](builtins.ts) | The built-in plugins (`logger`, `consoleLogger`, `retry`, `timeout`, `bearer`) and per-call overrides. | -| [`plugins.ts`](plugins.ts) | Writing plugins: auth with a service, a header with options, a `wrap` with its own error, error reporting. | -| [`endpoints.ts`](endpoints.ts) | The same app as `builtins.ts` with endpoints: defined with `Fetch.endpoint`, shared with `Fetch.Endpoints`. | -| [`backends.ts`](backends.ts) | Two backends in one file: a client and endpoints for each, shared plugins, and each backend's errors caught next to its calls. | -| [`status-errors.ts`](status-errors.ts) | Your own errors by status: client-wide, per endpoint, a 400 told apart by its `code`, a renamed field, a one-off call. | -| [`streams.ts`](streams.ts) | Streams and pages: a job's progress as SSE, an NDJSON export, an answer that ends with `[DONE]`, and a list paged by `Link`. | -| [`testing.ts`](testing.ts) | Tests for the `app/` todos module against `FetchTest`: a fake backend from its endpoints, errors by status, and what was sent. | -| [`app/`](app) | A feature-sliced app: clients as shared infrastructure, each module defining its own endpoints next to its schemas. | - -`endpoints.ts` and `backends.ts` keep everything in one file, which suits a -small app. `app/` is a layout for an app with many endpoints and modules. - -A client shared as a service is a `Fetch.Service` class, with its layer as -`.layer`: `Api` in most examples, `UsersClient` and `WalletClient` in -`backends.ts`, and `AppApiClient` and `WalletApiClient` in `app/`. A record of -definitions shared as a service is a `Fetch.Endpoints` class: `TodoApi` in -`endpoints.ts`, `status-errors.ts` and `app/`, `StreamsApi` in `streams.ts`, -and `UsersApi` and `WalletApi` in `backends.ts`. The one endpoints service -written by hand is the `WalletApi` of `app/`, which shows `client.endpoint`: -`makeWalletApi` makes its endpoints from the client. - -## `app/`: endpoints in a feature-sliced app +Programs that use Effetch for a real task, against real, free APIs. None of +them needs a key or an account. Run one, read what it prints, then read its +code. + +## Run an example + +From the repository, after `pnpm install`: + +```sh +pnpm example github +``` + +`pnpm example` builds the package if `src` has changed since the last +build, then runs the example's `main.ts` with Node.js. That needs Node.js +22.18 or later, which runs TypeScript files as they are. Some examples take +arguments, which their `main.ts` lists, such as +`pnpm example github facebook/react`. + +`pnpm example store-react` starts that app's dev server instead: open the +address it prints. It's a package of its own in the workspace, so +`pnpm install` at the root installs React, TanStack Router and Vite for it. + +The examples call public services, which can be slow, rate-limited or down. +Their tests don't: each one runs against a fake backend made with +`FetchTest`, offline, as part of `pnpm test`. To run only the examples' +tests, use `pnpm vitest run examples`. + +## The examples + +Read them in this order. Each one builds on what the ones before it show. + +| Example | What it does | What it shows | +| ----------------------------- | ------------------------------------------------------------------------------------------------------------------ | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| [`github/`](github) | Shows a GitHub repository and its newest open issues. | A client as a service, endpoints with a typed query, GitHub's error body, `404` and rate-limit errors of your own, paging by the `Link` header, `Retry-After`, an optional token, a plugin of your own. | +| [`sign-in/`](sign-in) | Signs in to DummyJSON, renews the access token when it's refused, and signs out. | A session as an Effect service, `bearer` with `refresh`, a second client for the auth calls, `consoleLogger`, and testing the refresh. | +| [`live/`](live) | Prints the next edits to Wikipedia, then the moves of the game Lichess TV is showing. | Server-Sent Events and newline-delimited JSON, a union per line, ending a stream, and two clients for two backends. | +| [`upload/`](upload) | Uploads a file and two form fields to httpbin, which echoes what it received. | A plain `post` call with a multipart body, a list field, a file size check with an error of your own, and retrying a `POST` that's safe to send again. | +| [`bff/`](bff) | A server that calls DummyJSON, and a browser client that calls the server over Effect RPC. | `Fetch.errorCodec`: the call's errors cross to the client as JSON, and come back as the same classes. The example prints what crossed. | +| [`store/`](store) | A shop app in modules: products and a cart, with a workflow that buys the cheapest product. | A feature-sliced layout, endpoints next to their module's schemas, a workflow with domain errors, a `ManagedRuntime` for the UI, and testing the workflow. | +| [`store-react/`](store-react) | The `store/` modules behind a React app: categories, pages of products, a product's page, and buying the cheapest. | TanStack Router loaders that run their calls with the store's `ManagedRuntime` and the route's abort signal, `ProductNotFound` as the router's not-found, typed errors in an error component, search params checked by an Effect schema, a form that runs the workflow, and testing the routes. | + +Each example's files start with a comment that says what they're for. The +APIs: +[GitHub's REST API](https://docs.github.com/en/rest), +[DummyJSON](https://dummyjson.com/docs), +[Wikimedia EventStreams](https://wikitech.wikimedia.org/wiki/Event_Platform/EventStreams_HTTP_Service), +[Lichess](https://lichess.org/api) and [httpbin](https://httpbin.org). + +## `store/`: endpoints in a feature-sliced app > **This folder structure is a personal preference:** the layout Effetch's > author uses in their own apps (React Native, with Expo). Effetch doesn't @@ -37,64 +57,62 @@ written by hand is the `WalletApi` of `app/`, which shows `client.endpoint`: > in [the rules it follows](#the-rules-it-follows). ```text -app/ +store/ ├── infrastructure/ │ └── http/ -│ ├── plugins.ts shared plugins and errors: auth, SessionExpired -│ ├── app-api-client.ts AppApiClient: the main backend's client -│ └── wallet-api-client.ts WalletApiClient: a second backend's client +│ └── store-api-client.ts StoreApiClient: how to reach the backend ├── modules/ -│ ├── todos/ +│ ├── products/ │ │ ├── contract/ -│ │ │ └── todos.ts schemas, errors, endpoints: Todo, TodoNotFound, getTodo, … +│ │ │ └── products.ts schemas, errors, endpoints: Product, ProductNotFound, getProduct, … │ │ ├── data/ -│ │ │ └── todo.api.ts TodoApi: the endpoints, bound to a client -│ │ ├── todo.layer.ts the module's live layers -│ │ └── public.ts what other code may import -│ └── wallet/ +│ │ │ └── product.api.ts ProductApi: the endpoints, bound to the client +│ │ ├── products.layer.ts the module's live layers +│ │ └── public.ts what other code may import +│ └── cart/ │ ├── contract/ -│ │ └── wallet.ts schemas and errors: Balance, Transfer, TransferLimitExceeded +│ │ └── cart.ts schemas and endpoints: Cart, NewCart, createCart │ ├── data/ -│ │ └── wallet.api.ts WalletApi: the module's endpoints +│ │ └── cart.api.ts CartApi │ ├── application/ -│ │ └── send-money.ts a workflow over WalletApi -│ ├── wallet.layer.ts +│ │ └── buy-cheapest.ts a workflow over ProductApi and CartApi +│ ├── cart.test.ts the workflow, tested against a fake backend +│ ├── cart.layer.ts │ └── public.ts -├── runtime.ts composition root: modules, clients, HttpClient -└── main.ts code using the modules +├── runtime.ts composition root: modules, client, HttpClient +└── main.ts code using the modules, as a screen would ``` -Read it in that order: a client, a module, the runtime, then `main.ts`. +Read it in that order: the client, a module, the runtime, then `main.ts`. ### The rules it follows 1. **A client file says how to reach a backend, and nothing else:** its base - URL, the body of its errors, what a status means from every endpoint (its - `statusErrors`, such as `401: SessionExpired`) and its plugins. It holds - no endpoints and no module schemas, and never imports a module, so it - stays the same size however many endpoints the app has. -2. **A module's endpoints sit next to its schemas, and its `data/` folder - connects them to the client it talks to.** `todos` defines them in - `contract/todos.ts` with `Fetch.endpoint`, which needs no client, and - declares them as a service in `data/` with `Fetch.Endpoints`. `wallet` makes them in `data/` - with `client.endpoint`, importing the schemas from `contract/`. Both give - the same endpoints; use the first when something should read the routes - and schemas without a client. Either way, dependencies point one way: - module → infrastructure, never back. An endpoint's own `statusErrors` - (`404: TodoNotFound`) sit with it, and the module's `public.ts` exports - those errors, so other code can catch them. -3. **Endpoints are bound or made once, when the module's layer is built,** - never in code that runs per request. -4. **Every module's data service is its endpoints** (`TodoApi`, - `WalletApi`): one line per operation, and every type inferred, so every - `data/` folder looks the same. -5. **An operation that isn't one HTTP call is a workflow in `application/`.** - `sendMoney` reads the balance, fails with `InsufficientFunds` when it's too - low, then sends the transfer. The endpoints stay plain; the rules live in - the workflow. -6. **The runtime composes the module layers on top of the client layers, on - top of one `HttpClient`.** A new module is one line in `runtime.ts`; a new - backend is one client file and one line. + URL, the body of its errors, what a status means from every endpoint, + and its plugins. It holds no endpoints and no module schemas, and never + imports a module, so it stays the same size however many endpoints the + app has. +2. **A module's endpoints sit next to its schemas,** in `contract/`, defined + with `Fetch.endpoint`, which needs no client. So anything can read their + routes and schemas, such as the fake backend in `cart.test.ts`. An + endpoint's own `statusErrors` (`404: ProductNotFound`) sit with it, and + the module's `public.ts` exports those errors, so other code can catch + them. +3. **Every module's data service is its endpoints,** bound to the client + with `Fetch.Endpoints` in `data/`: one line per operation, and every type + inferred, so every `data/` folder looks the same. They're bound once, + when the module's layer is built, never in code that runs per request. +4. **An operation that isn't one HTTP call is a workflow in `application/`.** + `buyCheapest` finds the cheapest product in a category, fails with + `NothingToBuy` or `OutOfStock`, then makes the cart. The endpoints stay + plain; the rules live in the workflow. +5. **Dependencies point one way:** a module imports the infrastructure, + and other modules through their `public.ts`, never the other way. The + cart's workflow uses the products module through its `public.ts`. +6. **The runtime composes the module layers on top of the client layer, on + top of one `HttpClient`.** A new module is one line in `runtime.ts`; a + new backend is one client file and one line. The UI runs effects with + the `ManagedRuntime` it exports. 7. **Other code imports a module through its `public.ts`,** and never sees a route, a schema it doesn't need or a client. @@ -103,8 +121,8 @@ Read it in that order: a client, a module, the runtime, then `main.ts`. - A module with 20 or more endpoints still has one definition and one line in `data/` per endpoint, inside the module. Nothing outside the module grows. - When one module's endpoints serve separate concerns, split them into - several services, each in its own file (`wallet.api.ts` and - `transaction.api.ts`), and merge their layers in the module's + several services, each in its own file (`cart.api.ts` and + `checkout.api.ts`), and merge their layers in the module's `.layer.ts`. - When a module needs another implementation of its data service, such as an offline one or a fake for UI work, declare the service's interface by hand @@ -112,7 +130,56 @@ Read it in that order: a client, a module, the runtime, then `main.ts`. - When a capability gets its own screens, consumers and API, make it a module of its own. -### With one backend +### With several backends + +Add a client file per backend in `infrastructure/http/`, each with its own +base URL, error body and plugins, and merge their layers in `runtime.ts`. +Each module uses the client of the backend it talks to. [`live/`](live) has +two clients for two backends on one `HttpClient`. + +## `store-react/`: the modules behind a React app + +```text +store-react/ +├── src/ +│ ├── store.ts the store's modules, runtime and types, from store/ +│ ├── root.tsx the root route, with the runtime in the router's context +│ ├── home.tsx /: the categories +│ ├── category.tsx /categories/$category?page=2: a page of products, and buying +│ ├── product.tsx /products/$productId: a product, or the not-found +│ ├── route-error.tsx what a route shows when its loader fails +│ ├── messages.ts what the screens say about each error +│ ├── use-action.ts runs an effect from a form, with its pending state +│ ├── router.ts the route tree and the router +│ ├── main.tsx the app: the router, on the store's runtime +│ ├── styles.css +│ └── app.test.ts the routes and the messages, against a fake backend +├── index.html +├── vite.config.ts +├── tsconfig.json +└── package.json +``` + +1. **The app adds screens, and nothing else.** What it calls comes from + `store/`'s `public.ts` files and its runtime, which `src/store.ts` + imports once: the same modules `store/main.ts` uses. +2. **The runtime is in the router's context,** so each loader runs its + effect with `runtime.runPromise(effect, { signal: abortController.signal })`. + When the navigation moves on, TanStack Router aborts that signal, which + interrupts the effect and cancels its request. The router doesn't preload + on hover, as a preloaded loader would go on when the page is left. The + tests give the router a runtime on a fake backend instead. +3. **A loader's errors reach the route as they are.** `ProductNotFound`, + and a page past the last one, become the router's `notFound()`, which + shows the route's `notFoundComponent`. The rest go to `RouteError`, which tells them apart + by class. +4. **An action the user starts runs with `useAction`.** Its effect has + handled every error, so its error type is `never`, and leaving the page + while it runs interrupts it. +5. **Search params are an Effect schema.** `validateSearch` takes it as a + Standard Schema, so `?page=0` fails as the schema says, and the route's + `search` is typed from it. -Drop `wallet-api-client.ts`: every module uses `AppApiClient`. The layout is -otherwise the same. +Here, Effetch comes from the repository's `src`, and Effect from the root's +dependencies, so the app and the modules share one copy of each. In your +own app, install both. diff --git a/examples/app/infrastructure/http/app-api-client.ts b/examples/app/infrastructure/http/app-api-client.ts deleted file mode 100644 index 3d95645..0000000 --- a/examples/app/infrastructure/http/app-api-client.ts +++ /dev/null @@ -1,29 +0,0 @@ -import * as Config from "effect/Config"; -import * as Schema from "effect/Schema"; - -import { Fetch } from "@monarcode/effetch"; -import { logger, retry } from "@monarcode/effetch/plugins"; - -import { auth, reportErrors, SessionExpired } from "./plugins.js"; - -// The app's main backend: how to reach it, and nothing else. No endpoints -// and no module schemas live here, so this file stays the same size however -// many endpoints the modules define, and it never imports a module. What a -// status means from every endpoint, such as a 401, belongs here; what it -// means from one endpoint belongs with that endpoint. - -/** The body of this backend's non-2xx responses. */ -export const AppApiError = Schema.Struct({ - code: Schema.String, - message: Schema.String, -}); - -export class AppApiClient extends Fetch.Service()( - "infrastructure/http/AppApiClient", - { - baseUrl: Config.String("APP_API_URL"), - defaultError: AppApiError, - statusErrors: { 401: SessionExpired }, - plugins: [logger(), reportErrors("app"), retry(), auth], - }, -) {} diff --git a/examples/app/infrastructure/http/plugins.ts b/examples/app/infrastructure/http/plugins.ts deleted file mode 100644 index 4ee69b7..0000000 --- a/examples/app/infrastructure/http/plugins.ts +++ /dev/null @@ -1,33 +0,0 @@ -import * as Effect from "effect/Effect"; -import * as Schema from "effect/Schema"; - -import { Fetch } from "@monarcode/effetch"; -import { bearer } from "@monarcode/effetch/plugins"; - -// Plugins and errors shared by the app's clients. Plugins are plain values, -// so one `auth` serves every backend that takes the same token. - -export const session: { accessToken: string | undefined } = { - accessToken: undefined, -}; - -export const auth = bearer({ token: () => session.accessToken }); - -/** - * What a 401 means from any of the app's backends: the token is no longer - * valid. Each client turns it into this error with `statusErrors`. - */ -export class SessionExpired extends Schema.TaggedError()( - "SessionExpired", - { message: Schema.String }, -) {} - -// `ctx.route` is a method and a path, with no host: two backends can both -// have a `GET /health`. A plugin that groups by route takes the backend's -// name, and each client gets its own instance. -export const reportErrors = (backend: string) => - Fetch.plugin({ - name: "reportErrors", - onError: (error, ctx) => - Effect.logWarning(`${backend} ${ctx.route} failed`, error), - }); diff --git a/examples/app/infrastructure/http/wallet-api-client.ts b/examples/app/infrastructure/http/wallet-api-client.ts deleted file mode 100644 index e5c4ec8..0000000 --- a/examples/app/infrastructure/http/wallet-api-client.ts +++ /dev/null @@ -1,35 +0,0 @@ -import * as Config from "effect/Config"; -import * as Schema from "effect/Schema"; - -import { Fetch } from "@monarcode/effetch"; -import { logger, timeout } from "@monarcode/effetch/plugins"; - -import { auth, reportErrors, SessionExpired } from "./plugins.js"; - -// A second backend, with its own base URL, error body and plugins: one -// client per backend, each in its own service. - -/** The body of this backend's non-2xx responses. */ -export const WalletApiError = Schema.Struct({ - error: Schema.String, - reason: Schema.String, -}); - -export class WalletApiClient extends Fetch.Service()( - "infrastructure/http/WalletApiClient", - { - baseUrl: Config.String("WALLET_API_URL"), - defaultError: WalletApiError, - // The shared error, read from this backend's body: its message is - // `reason`. - statusErrors: { - 401: SessionExpired.pipe(Schema.encodeKeys({ message: "reason" })), - }, - plugins: [ - logger(), - reportErrors("wallet"), - timeout({ duration: "10 seconds" }), - auth, - ], - }, -) {} diff --git a/examples/app/main.ts b/examples/app/main.ts deleted file mode 100644 index 4684132..0000000 --- a/examples/app/main.ts +++ /dev/null @@ -1,49 +0,0 @@ -import * as Effect from "effect/Effect"; - -import { AppApiClient } from "./infrastructure/http/app-api-client.js"; -import { TodoApi } from "./modules/todos/public.js"; -import { sendMoney } from "./modules/wallet/public.js"; -import { AppLayer } from "./runtime.js"; - -// Code outside the modules uses what their `public.ts` exports. It never sees -// a route, a schema it doesn't need or a client. - -const payRent = Effect.gen(function* () { - const todos = yield* TodoApi; - - const task = yield* todos.create({ - body: { title: "Pay rent", due: new Date() }, - }); - const receipt = yield* sendMoney("w_me", "w_landlord", 1200); - yield* todos.update({ params: { id: task.id }, body: { done: true } }); - - const { todos: open } = yield* todos.list({ query: { done: false } }); - return { receipt: receipt.id, open: open.length }; -}).pipe( - Effect.catchTags({ - InsufficientFunds: (error) => - Effect.fail(`Only ${error.balance} left, ${error.amount} needed`), - TransferLimitExceeded: (error) => - Effect.fail(`Transfer refused: ${error.reason}`), - TodoNotFound: () => Effect.fail("The task was deleted meanwhile"), - SessionExpired: () => Effect.fail("Please sign in again"), - HttpError: (error) => - Effect.fail(`HTTP ${error.status} from ${error.url}`), - TimeoutError: (error) => - Effect.fail(`${error.url} didn't answer within ${error.duration}`), - NetworkError: () => Effect.fail("You appear to be offline"), - DecodeError: (error) => - Effect.fail(`Unexpected response: ${error.message}`), - }), -); - -// A one-off call, made with a client directly rather than an endpoint. -const ping = Effect.gen(function* () { - const client = yield* AppApiClient; - const response = yield* client.head("/health", { - plugins: { logger: false, retry: false }, - }); - return response.status; -}); - -export const main = Effect.all([payRent, ping]).pipe(Effect.provide(AppLayer)); diff --git a/examples/app/modules/todos/contract/todos.ts b/examples/app/modules/todos/contract/todos.ts deleted file mode 100644 index 1fac7e0..0000000 --- a/examples/app/modules/todos/contract/todos.ts +++ /dev/null @@ -1,58 +0,0 @@ -import * as Schema from "effect/Schema"; - -import { Fetch } from "@monarcode/effetch"; - -// The module's wire formats, and its endpoints next to the schemas they use. -// The endpoints are defined without a client, so they can be read (route, -// method, schemas) at module level; `data/todo.api.ts` binds them to the -// client the module talks to. - -export const Todo = Schema.Struct({ - id: Schema.Finite, - title: Schema.String, - done: Schema.Boolean, - due: Schema.Date, -}); -export type Todo = typeof Todo.Type; - -export const TodoPage = Schema.Struct({ - todos: Schema.Array(Todo), - total: Schema.Finite, -}); -export type TodoPage = typeof TodoPage.Type; - -export const NewTodo = Schema.Struct({ - title: Schema.String, - due: Schema.Date, -}); -export type NewTodo = typeof NewTodo.Type; - -export const TodoPatch = Schema.Struct({ done: Schema.Boolean }); -export type TodoPatch = typeof TodoPatch.Type; - -/** A 404 from an endpoint that takes a todo's id. */ -export class TodoNotFound extends Schema.TaggedError()( - "TodoNotFound", - { message: Schema.String }, -) {} - -const byId = { 404: TodoNotFound }; - -export const listTodos = Fetch.endpoint("GET /todos", { output: TodoPage }); -export const getTodo = Fetch.endpoint("GET /todos/:id", { - output: Todo, - statusErrors: byId, -}); -export const createTodo = Fetch.endpoint("POST /todos", { - input: NewTodo, - output: Todo, -}); -export const updateTodo = Fetch.endpoint("PATCH /todos/:id", { - input: TodoPatch, - output: Todo, - headers: { "content-type": "application/merge-patch+json" }, - statusErrors: byId, -}); -export const removeTodo = Fetch.endpoint("DELETE /todos/:id", { - statusErrors: byId, -}); diff --git a/examples/app/modules/todos/data/todo.api.ts b/examples/app/modules/todos/data/todo.api.ts deleted file mode 100644 index 204bf04..0000000 --- a/examples/app/modules/todos/data/todo.api.ts +++ /dev/null @@ -1,29 +0,0 @@ -import { Fetch } from "@monarcode/effetch"; - -import { AppApiClient } from "../../../infrastructure/http/app-api-client.js"; -import { - createTodo, - getTodo, - listTodos, - removeTodo, - updateTodo, -} from "../contract/todos.js"; - -// The module's endpoints are its data service. They're defined in -// `contract/todos.ts`, next to their schemas; here each is bound to the -// client, one line per operation, and every type (params, body, success and -// errors) is inferred: there's no interface to keep in step. -// -// `TodoApi.layer` binds them to the shared client once, when it's built. - -export class TodoApi extends Fetch.Endpoints()( - "modules/todos/TodoApi", - AppApiClient, - { - list: listTodos, - get: getTodo, - create: createTodo, - update: updateTodo, - remove: removeTodo, - }, -) {} diff --git a/examples/app/modules/todos/public.ts b/examples/app/modules/todos/public.ts deleted file mode 100644 index 0053c81..0000000 --- a/examples/app/modules/todos/public.ts +++ /dev/null @@ -1,4 +0,0 @@ -// What other code may use from the module. -export type { NewTodo, Todo, TodoPage, TodoPatch } from "./contract/todos.js"; -export { TodoNotFound } from "./contract/todos.js"; -export { TodoApi } from "./data/todo.api.js"; diff --git a/examples/app/modules/todos/todo.layer.ts b/examples/app/modules/todos/todo.layer.ts deleted file mode 100644 index 43a1693..0000000 --- a/examples/app/modules/todos/todo.layer.ts +++ /dev/null @@ -1,6 +0,0 @@ -import * as Layer from "effect/Layer"; - -import { TodoApi } from "./data/todo.api.js"; - -/** Every live layer of the module, for the app's runtime. */ -export const TodoModuleLive = Layer.mergeAll(TodoApi.layer); diff --git a/examples/app/modules/wallet/application/send-money.ts b/examples/app/modules/wallet/application/send-money.ts deleted file mode 100644 index 6e29f4f..0000000 --- a/examples/app/modules/wallet/application/send-money.ts +++ /dev/null @@ -1,26 +0,0 @@ -import * as Effect from "effect/Effect"; -import * as Schema from "effect/Schema"; - -import { WalletApi } from "../data/wallet.api.js"; - -// A workflow: an operation that isn't one HTTP call. It reads the balance, -// fails with a domain error when it's too low, then sends the transfer. The -// endpoints stay plain; the rules live here. - -export class InsufficientFunds extends Schema.TaggedError()( - "InsufficientFunds", - { balance: Schema.Finite, amount: Schema.Finite }, -) {} - -export const sendMoney = Effect.fn("sendMoney")(function* ( - from: string, - to: string, - amount: number, -) { - const wallet = yield* WalletApi; - const balance = yield* wallet.balance({ params: { walletId: from } }); - if (balance.amount < amount) { - return yield* new InsufficientFunds({ balance: balance.amount, amount }); - } - return yield* wallet.transfer({ body: { from, to, amount } }); -}); diff --git a/examples/app/modules/wallet/contract/wallet.ts b/examples/app/modules/wallet/contract/wallet.ts deleted file mode 100644 index 5077e8c..0000000 --- a/examples/app/modules/wallet/contract/wallet.ts +++ /dev/null @@ -1,30 +0,0 @@ -import * as Schema from "effect/Schema"; - -export const Balance = Schema.Struct({ - amount: Schema.Finite, - currency: Schema.String, -}); -export type Balance = typeof Balance.Type; - -export const Transfer = Schema.Struct({ - from: Schema.String, - to: Schema.String, - amount: Schema.Finite, -}); -export type Transfer = typeof Transfer.Type; - -export const Receipt = Schema.Struct({ id: Schema.String }); -export type Receipt = typeof Receipt.Type; - -/** - * A 422 from `POST /transfers` with `"error": "LIMIT_EXCEEDED"`. The wallet - * backend names its code `error`; `encodeKeys` reads it into `code`. - */ -export class TransferLimitExceeded extends Schema.TaggedError()( - "TransferLimitExceeded", - { code: Schema.Literal("LIMIT_EXCEEDED"), reason: Schema.String }, -) {} - -export const TransferLimitExceededBody = TransferLimitExceeded.pipe( - Schema.encodeKeys({ code: "error" }), -); diff --git a/examples/app/modules/wallet/data/wallet.api.ts b/examples/app/modules/wallet/data/wallet.api.ts deleted file mode 100644 index d78a85c..0000000 --- a/examples/app/modules/wallet/data/wallet.api.ts +++ /dev/null @@ -1,34 +0,0 @@ -import * as Context from "effect/Context"; -import type * as Effect from "effect/Effect"; -import * as Layer from "effect/Layer"; - -import { WalletApiClient } from "../../../infrastructure/http/wallet-api-client.js"; -import { - Balance, - Receipt, - Transfer, - TransferLimitExceededBody, -} from "../contract/wallet.js"; - -// Same shape as `todos`: the module's endpoints are its data service, made -// from the client of the backend the module talks to. Operations that take -// more than one call are workflows, in `application/`. - -const makeWalletApi = WalletApiClient.useSync((client) => ({ - balance: client.endpoint("GET /wallets/:walletId/balance", { - output: Balance, - }), - transfer: client.endpoint("POST /transfers", { - input: Transfer, - output: Receipt, - statusErrors: { 422: TransferLimitExceededBody }, - plugins: { timeout: { duration: "30 seconds" } }, - }), -})); - -export class WalletApi extends Context.Service< - WalletApi, - Effect.Success ->()("modules/wallet/WalletApi") {} - -export const WalletApiLive = Layer.effect(WalletApi)(makeWalletApi); diff --git a/examples/app/modules/wallet/public.ts b/examples/app/modules/wallet/public.ts deleted file mode 100644 index 0259151..0000000 --- a/examples/app/modules/wallet/public.ts +++ /dev/null @@ -1,5 +0,0 @@ -// What other code may use from the module. -export { InsufficientFunds, sendMoney } from "./application/send-money.js"; -export type { Balance, Receipt, Transfer } from "./contract/wallet.js"; -export { TransferLimitExceeded } from "./contract/wallet.js"; -export { WalletApi } from "./data/wallet.api.js"; diff --git a/examples/app/modules/wallet/wallet.layer.ts b/examples/app/modules/wallet/wallet.layer.ts deleted file mode 100644 index cabe376..0000000 --- a/examples/app/modules/wallet/wallet.layer.ts +++ /dev/null @@ -1,6 +0,0 @@ -import * as Layer from "effect/Layer"; - -import { WalletApiLive } from "./data/wallet.api.js"; - -/** Every live layer of the module, for the app's runtime. */ -export const WalletModuleLive = Layer.mergeAll(WalletApiLive); diff --git a/examples/app/runtime.ts b/examples/app/runtime.ts deleted file mode 100644 index 8b292fe..0000000 --- a/examples/app/runtime.ts +++ /dev/null @@ -1,21 +0,0 @@ -import * as FetchHttpClient from "effect/http/FetchHttpClient"; -import * as Layer from "effect/Layer"; - -import { AppApiClient } from "./infrastructure/http/app-api-client.js"; -import { WalletApiClient } from "./infrastructure/http/wallet-api-client.js"; -import { TodoModuleLive } from "./modules/todos/todo.layer.js"; -import { WalletModuleLive } from "./modules/wallet/wallet.layer.js"; - -// The composition root: every module's layer, on top of the clients they -// use, on top of one HttpClient. Adding a module adds one line here. - -const Clients = Layer.mergeAll(AppApiClient.layer, WalletApiClient.layer); - -const Modules = Layer.mergeAll(TodoModuleLive, WalletModuleLive); - -// `provideMerge` keeps the clients available too, for one-off calls that -// aren't worth an endpoint. -export const AppLayer = Modules.pipe( - Layer.provideMerge(Clients), - Layer.provide(FetchHttpClient.layer), -); diff --git a/examples/backends.ts b/examples/backends.ts deleted file mode 100644 index 1217c37..0000000 --- a/examples/backends.ts +++ /dev/null @@ -1,161 +0,0 @@ -import * as Config from "effect/Config"; -import * as Effect from "effect/Effect"; -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, logger, retry, timeout } from "@monarcode/effetch/plugins"; - -// Two backends, each with its own base URL, error shape and plugins: one -// client per backend, and each backend's endpoints as their own service. - -const User = Schema.Struct({ id: Schema.String, name: Schema.String }); - -const Balance = Schema.Struct({ - amount: Schema.Finite, - currency: Schema.String, -}); - -const Transfer = Schema.Struct({ to: Schema.String, amount: Schema.Finite }); - -const Receipt = Schema.Struct({ id: Schema.String }); - -const UsersError = Schema.Struct({ code: Schema.String }); - -const WalletError = Schema.Struct({ - error: Schema.String, - reason: Schema.String, -}); - -const session: { accessToken: string | undefined } = { - accessToken: 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, 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", - onError: (error, ctx) => - Effect.logWarning(`${backend} ${ctx.route} failed`, error), - }); - -// --- The users backend --- - -export class UsersClient extends Fetch.Service()( - "examples/backends/UsersClient", - { - baseUrl: Config.String("USERS_API_URL"), - defaultError: UsersError, - plugins: [logger(), reportErrors("users"), retry(), auth], - }, -) {} - -export class UsersApi extends Fetch.Endpoints()( - "examples/backends/UsersApi", - UsersClient, - { - me: Fetch.endpoint("GET /me", { output: User }), - getUser: Fetch.endpoint("GET /users/:id", { output: User }), - }, -) {} - -// --- The wallet backend --- - -export class WalletClient extends Fetch.Service()( - "examples/backends/WalletClient", - { - baseUrl: Config.String("WALLET_API_URL"), - defaultError: WalletError, - plugins: [ - logger(), - reportErrors("wallet"), - timeout({ duration: "10 seconds" }), - auth, - ], - }, -) {} - -export class WalletApi extends Fetch.Endpoints()( - "examples/backends/WalletApi", - WalletClient, - { - balance: Fetch.endpoint("GET /wallets/:userId/balance", { - output: Balance, - }), - transfer: [ - Fetch.endpoint("POST /transfers", { - input: Transfer, - output: Receipt, - }), - { plugins: { timeout: { duration: "30 seconds" } } }, - ], - }, -) {} - -// The endpoints, on top of both clients, on top of one HttpClient. -// `provideMerge` keeps the clients available, for one-off calls. -export const AppLayer = Layer.mergeAll(UsersApi.layer, WalletApi.layer).pipe( - Layer.provideMerge(Layer.mergeAll(UsersClient.layer, WalletClient.layer)), - Layer.provide(FetchHttpClient.layer), -); - -// --- Using them --- - -// Each backend's errors are caught next to its calls, where `HttpError.body` -// has that backend's error shape. -const currentUser = Effect.gen(function* () { - const users = yield* UsersApi; - return yield* users.me(); -}).pipe( - Effect.catchTag("HttpError", (error) => - Effect.fail(`users: ${error.body?.code ?? `HTTP ${error.status}`}`), - ), -); - -const sendHalf = (userId: string, to: string) => - Effect.gen(function* () { - const wallet = yield* WalletApi; - const { amount } = yield* wallet.balance({ params: { userId } }); - return yield* wallet.transfer({ body: { to, amount: amount / 2 } }); - }).pipe( - Effect.catchTag("HttpError", (error) => - Effect.fail(`wallet: ${error.body?.reason ?? `HTTP ${error.status}`}`), - ), - ); - -// A one-off call to the users backend, with the client rather than an -// endpoint. -const recordActivity = (userId: string, receiptId: string) => - Effect.gen(function* () { - const users = yield* UsersClient; - yield* users.post("/users/:id/activity", { - params: { id: userId }, - body: { type: "transfer", receipt: receiptId }, - }); - }).pipe( - Effect.catchTag("HttpError", (error) => - Effect.fail(`users: ${error.body?.code ?? `HTTP ${error.status}`}`), - ), - ); - -export const program = (to: string) => - Effect.gen(function* () { - const user = yield* currentUser; - const receipt = yield* sendHalf(user.id, to); - yield* recordActivity(user.id, receipt.id); - return receipt; - }).pipe( - Effect.catchTags({ - NetworkError: () => Effect.fail("You appear to be offline"), - DecodeError: (error) => - Effect.fail(`Unexpected response: ${error.message}`), - }), - ); - -export const main = (to: string) => program(to).pipe(Effect.provide(AppLayer)); diff --git a/examples/basic.ts b/examples/basic.ts deleted file mode 100644 index 465914f..0000000 --- a/examples/basic.ts +++ /dev/null @@ -1,61 +0,0 @@ -import * as Effect from "effect/Effect"; -import * as FetchHttpClient from "effect/http/FetchHttpClient"; -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, - done: Schema.Boolean, -}); - -const NewTodo = Schema.Struct({ title: Schema.String, due: Schema.Date }); - -const ApiError = Schema.Struct({ code: Schema.String, message: Schema.String }); - -class Api extends Fetch.Service()("Api", { - baseUrl: "https://api.example.com", - headers: { accept: "application/json" }, - defaultError: ApiError, -}) {} - -export const ApiLive = Api.layer.pipe(Layer.provide(FetchHttpClient.layer)); - -export const program = Effect.gen(function* () { - const api = yield* Api; - - const created = yield* api.post("/todos", { - input: NewTodo, - body: { title: "Write docs", due: new Date() }, - output: Todo, - }); - - const todos = yield* api.get("/todos", { - query: { page: 1, done: false, tags: ["work", "urgent"] }, - output: Schema.Array(Todo), - }); - - const updated = yield* api.patch("/todos/:id", { - params: { id: created.id }, - body: { done: true }, - output: Todo, - }); - - yield* api.del("/todos/:id", { params: { id: updated.id } }); - - return todos.length; -}).pipe( - // A 404 is handled on its own; any other error status is caught below. - Fetch.catchStatus(404, () => Effect.succeed(0)), - Effect.catchTags({ - HttpError: (error) => - Effect.fail(error.body?.message ?? `HTTP ${error.status}`), - NetworkError: () => Effect.fail("You appear to be offline"), - DecodeError: (error) => - Effect.fail(`Unexpected response: ${error.message}`), - }), -); - -export const main = program.pipe(Effect.provide(ApiLive)); diff --git a/examples/bff/bff.test.ts b/examples/bff/bff.test.ts new file mode 100644 index 0000000..36e7480 --- /dev/null +++ b/examples/bff/bff.test.ts @@ -0,0 +1,103 @@ +import { afterAll, describe, expect, it } from "@effect/vitest"; +import * as Effect from "effect/Effect"; +import * as FetchHttpClient from "effect/http/FetchHttpClient"; +import * as Layer from "effect/Layer"; +import * as RpcClient from "effect/rpc/RpcClient"; + +import { Fetch } from "@monarcode/effetch"; +import { FetchTest } from "@monarcode/effetch/test"; + +import { Transport } from "./client.ts"; +import { makeServer } from "./server.ts"; +import { + ApiProblem, + getProduct, + ProductNotFound, + ProductRpcs, + searchProducts, +} from "./shared.ts"; + +// The whole trip: the browser's RPC client, the server, and its calls to a +// fake DummyJSON. The errors go from the server to the client as JSON. + +const Backend = FetchTest.layer([ + FetchTest.respond(getProduct, ({ params }) => + Effect.succeed( + params.id === "1" + ? { id: 1, title: "Mascara", price: 9.99 } + : FetchTest.reply(404, { + message: `Product with id '${params.id}' not found`, + }), + ), + ), + FetchTest.respond(searchProducts, ({ query }) => + Effect.succeed( + query.limit < 1 + ? FetchTest.reply( + 400, + { message: "Invalid 'limit'" }, + { headers: { "set-cookie": "session=secret" } }, + ) + : { + products: [{ id: 1, title: "Mascara", price: 9.99 }], + total: 1, + }, + ), + ), +]); + +const server = makeServer(Backend); +afterAll(() => server.dispose()); + +const Browser = Transport("http://server.test/rpc").pipe( + Layer.provide( + Layer.succeed(FetchHttpClient.Fetch, (input, init) => + server.handler(new Request(input, init)), + ), + ), +); + +/** Runs a test with the RPC client, as the browser would. */ +const asBrowser = (test: Effect.Effect) => + test.pipe(Effect.scoped, Effect.provide(Browser)); + +describe("The browser's RPC client", () => { + it.effect("gets what the server's call returned", () => + asBrowser( + Effect.gen(function* () { + const rpc = yield* RpcClient.make(ProductRpcs); + const product = yield* rpc.GetProduct({ id: 1 }); + expect(product.title).toBe("Mascara"); + }), + ), + ); + + it.effect("gets a 404 as a ProductNotFound", () => + asBrowser( + Effect.gen(function* () { + const rpc = yield* RpcClient.make(ProductRpcs); + const error = yield* Effect.flip(rpc.GetProduct({ id: 9 })); + expect(error).toBeInstanceOf(ProductNotFound); + expect(error).toMatchObject({ + message: "Product with id '9' not found", + }); + }), + ), + ); + + it.effect("gets an HttpError with its body, but not its headers", () => + asBrowser( + Effect.gen(function* () { + const rpc = yield* RpcClient.make(ProductRpcs); + const error = yield* Effect.flip( + rpc.SearchProducts({ query: "phone", limit: 0 }), + ); + expect(error).toBeInstanceOf(Fetch.HttpError); + const http = error as Fetch.HttpError.With; + expect(http.status).toBe(400); + expect(http.body).toBeInstanceOf(ApiProblem); + expect(Object.keys(http.headers)).toStrictEqual([]); + }), + ), + ); +}); diff --git a/examples/bff/client.ts b/examples/bff/client.ts new file mode 100644 index 0000000..17e86c5 --- /dev/null +++ b/examples/bff/client.ts @@ -0,0 +1,47 @@ +import * as Console from "effect/Console"; +import * as Effect from "effect/Effect"; +import * as FetchHttpClient from "effect/http/FetchHttpClient"; +import * as Layer from "effect/Layer"; +import * as RpcClient from "effect/rpc/RpcClient"; +import * as RpcSerialization from "effect/rpc/RpcSerialization"; + +import { ProductRpcs } from "./shared.ts"; + +// The browser: it calls the RPCs, and catches the server's errors by tag, +// typed as they were on the server. + +/** How the browser reaches the server: RPC over HTTP, as JSON, at `url`. */ +export const Transport = (url: string) => + RpcClient.layerProtocolHttp({ url }).pipe( + Layer.provide(RpcSerialization.layerJson), + Layer.provide(FetchHttpClient.layer), + ); + +export const showProducts = Effect.gen(function* () { + const rpc = yield* RpcClient.make(ProductRpcs); + + const phones = yield* rpc.SearchProducts({ query: "phone", limit: 3 }); + yield* Console.log("Search for phone:"); + for (const phone of phones) { + yield* Console.log(` ${phone.title}, $${phone.price}`); + } + + // A 404 on the server is a ProductNotFound here. + yield* rpc.GetProduct({ id: 9999 }).pipe( + Effect.flatMap((product) => Console.log(product.title)), + Effect.catchTag("ProductNotFound", (error) => + Console.log(`\nGetProduct 9999: ${error.message}`), + ), + ); + + // Any other status is an HttpError, with the body decoded again from + // the response text: an ApiProblem, as it was on the server. + yield* rpc.SearchProducts({ query: "phone", limit: -1 }).pipe( + Effect.asVoid, + Effect.catchTag("HttpError", (error) => + Console.log( + `\nSearchProducts with limit -1: HTTP ${error.status}, ${error.body?.message ?? error.text}`, + ), + ), + ); +}).pipe(Effect.scoped); diff --git a/examples/bff/main.ts b/examples/bff/main.ts new file mode 100644 index 0000000..ddc4396 --- /dev/null +++ b/examples/bff/main.ts @@ -0,0 +1,33 @@ +import * as Effect from "effect/Effect"; +import * as FetchHttpClient from "effect/http/FetchHttpClient"; +import * as Layer from "effect/Layer"; + +import { showProducts, Transport } from "./client.ts"; +import { makeServer } from "./server.ts"; + +// A server that calls DummyJSON, and a browser client that calls the +// server over Effect RPC, with the call's errors going across as JSON: +// +// pnpm example bff +// +// In an app, the server runs behind `Deno.serve(server.handler)` or the +// like, and the browser's RPC client uses `fetch`. Here the client's `fetch` +// calls the handler directly, so both run in one process, with real HTTP +// requests and JSON between them. + +const server = makeServer(FetchHttpClient.layer); + +// Prints each failure as it crossed the wire. +const fetchServer: typeof fetch = async (input, init) => { + const response = await server.handler(new Request(input, init)); + const text = await response.clone().text(); + if (text.includes('"Failure"')) console.log(` (the wire: ${text.trim()})`); + return response; +}; + +const Browser = Transport("http://server.local/rpc").pipe( + Layer.provide(Layer.succeed(FetchHttpClient.Fetch, fetchServer)), +); + +await Effect.runPromise(showProducts.pipe(Effect.provide(Browser))); +await server.dispose(); diff --git a/examples/bff/server.ts b/examples/bff/server.ts new file mode 100644 index 0000000..dc4b8ab --- /dev/null +++ b/examples/bff/server.ts @@ -0,0 +1,60 @@ +import * as Effect from "effect/Effect"; +import type * as HttpClient from "effect/http/HttpClient"; +import * as HttpRouter from "effect/http/HttpRouter"; +import * as Layer from "effect/Layer"; +import * as RpcSerialization from "effect/rpc/RpcSerialization"; +import * as RpcServer from "effect/rpc/RpcServer"; + +import { Fetch } from "@monarcode/effetch"; +import { retry, timeout } from "@monarcode/effetch/plugins"; + +import { getProduct, ProductRpcs, searchProducts } from "./shared.ts"; + +// The server: it calls DummyJSON with Effetch, and serves the RPCs. Only +// the server imports this file. + +class DummyJson extends Fetch.Service()("DummyJson", { + baseUrl: "https://dummyjson.com", + plugins: [retry(), timeout({ duration: "10 seconds" })], +}) {} + +// Each handler returns the call as it is: its errors go to the browser +// through the RPC's `error` codec. +const Handlers = ProductRpcs.toLayer( + Effect.gen(function* () { + const dummyJson = yield* DummyJson; + const product = dummyJson.bind(getProduct); + const search = dummyJson.bind(searchProducts); + return { + GetProduct: ({ id }) => product({ params: { id } }), + SearchProducts: ({ query, limit }) => + search({ query: { q: query, limit, select: "title,price" } }).pipe( + Effect.map((page) => page.products), + ), + }; + }), +); + +/** + * The server as a web handler. `server.handler(request)` takes a `Request` + * and returns a `Response`, as `Deno.serve`, `Bun.serve` and most Node.js + * adapters expect. `httpClient` is what it calls DummyJSON with, and + * `server.dispose()` releases what it holds. + */ +export const makeServer = (httpClient: Layer.Layer) => + HttpRouter.toWebHandler( + RpcServer.layerHttp({ + group: ProductRpcs, + path: "/rpc", + protocol: "http", + }).pipe( + Layer.provide( + Layer.mergeAll( + Handlers.pipe(Layer.provide(DummyJson.layer)), + RpcSerialization.layerJson, + ), + ), + Layer.provide(httpClient), + ), + { disableLogger: true }, + ); diff --git a/examples/bff/shared.ts b/examples/bff/shared.ts new file mode 100644 index 0000000..5e3ab66 --- /dev/null +++ b/examples/bff/shared.ts @@ -0,0 +1,65 @@ +import * as Rpc from "effect/rpc/Rpc"; +import * as RpcGroup from "effect/rpc/RpcGroup"; +import * as Schema from "effect/Schema"; + +import { Fetch } from "@monarcode/effetch"; +import { TimeoutError } from "@monarcode/effetch/plugins"; + +// What the server and the browser share: the schemas, the endpoints the +// server calls, and the RPCs. It holds no client, so the browser's bundle +// gets no base URL and no plugins. The client is in `server.ts`. + +export const Product = Schema.Struct({ + id: Schema.Finite, + title: Schema.String, + price: Schema.Finite, +}); + +/** The body of DummyJSON's error responses. A class, so it comes back as one. */ +export class ApiProblem extends Schema.Class("ApiProblem")({ + message: Schema.String, +}) {} + +export class ProductNotFound extends Schema.TaggedError()( + "ProductNotFound", + { message: Schema.String }, +) {} + +// The endpoints carry their own `error`, rather than the client's +// `defaultError`, so `Fetch.errorCodec` needs no client to read. + +export const getProduct = Fetch.endpoint("GET /products/:id", { + output: Product, + error: ApiProblem, + statusErrors: { 404: ProductNotFound }, +}); + +export const searchProducts = Fetch.endpoint("GET /products/search", { + query: Schema.Struct({ + q: Schema.String, + limit: Schema.Finite, + select: Schema.String, + }), + output: Schema.Struct({ + products: Schema.Array(Product), + total: Schema.Finite, + }), + error: ApiProblem, +}); + +// Each RPC fails with what its call fails with. The server's client has +// `timeout`, whose error no endpoint lists, so it's added as `errors`. + +export const GetProduct = Rpc.make("GetProduct", { + payload: { id: Schema.Finite }, + success: Product, + error: Fetch.errorCodec(getProduct, { errors: [TimeoutError] }), +}); + +export const SearchProducts = Rpc.make("SearchProducts", { + payload: { query: Schema.String, limit: Schema.Finite }, + success: Schema.Array(Product), + error: Fetch.errorCodec(searchProducts, { errors: [TimeoutError] }), +}); + +export const ProductRpcs = RpcGroup.make(GetProduct, SearchProducts); diff --git a/examples/builtins.ts b/examples/builtins.ts deleted file mode 100644 index b1f355e..0000000 --- a/examples/builtins.ts +++ /dev/null @@ -1,111 +0,0 @@ -import * as Effect from "effect/Effect"; -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, - consoleLogger, - logger, - retry, - timeout, -} from "@monarcode/effetch/plugins"; - -const Todo = Schema.Struct({ - id: Schema.Finite, - title: Schema.String, - done: Schema.Boolean, -}); - -const Tokens = Schema.Struct({ accessToken: Schema.String }); - -const ApiError = Schema.Struct({ code: Schema.String, message: Schema.String }); - -// Set by your bundler, such as `__DEV__` in React Native or -// `import.meta.env.DEV` in Vite. -declare const isDevelopment: boolean; - -const session: { accessToken: string | undefined } = { - accessToken: undefined, -}; - -export class Api extends Fetch.Service()("Api", { - baseUrl: "https://api.example.com", - defaultError: ApiError, - plugins: [ - logger({ level: "Info" }), - // Prints every call to the console while developing; does nothing - // in production builds. - consoleLogger({ - enabled: isDevelopment, - slow: "1 second", - }), - retry(), - timeout({ duration: "10 seconds" }), - bearer({ token: () => session.accessToken }), - ], -}) {} - -export const ApiLive = Api.layer.pipe(Layer.provide(FetchHttpClient.layer)); - -export const signIn = (email: string, password: string) => - Effect.gen(function* () { - const api = yield* Api; - const { accessToken } = yield* api.post("/auth/login", { - body: { email, password }, - output: Tokens, - plugins: { bearer: false }, - }); - session.accessToken = accessToken; - }); - -export const listTodos = Effect.gen(function* () { - const api = yield* Api; - return yield* api.get("/todos", { output: Schema.Array(Todo) }); -}); - -export const exportTodos = Effect.gen(function* () { - const api = yield* Api; - return yield* api.get("/todos/export", { - output: Schema.Array(Todo), - plugins: { - timeout: { duration: "2 minutes" }, - retry: { times: 0 }, - // A large body: print the summary line only. - consoleLogger: { detail: "summary" }, - }, - }); -}); - -export const isHealthy = Effect.gen(function* () { - const api = yield* Api; - return yield* api - .head("/health", { - plugins: { logger: false, consoleLogger: false, retry: false }, - }) - .pipe( - Effect.as(true), - Effect.catchTag("HttpError", () => Effect.succeed(false)), - ); -}); - -export const program = (email: string, password: string) => - Effect.gen(function* () { - yield* signIn(email, password); - const todos = yield* listTodos; - return todos.filter((todo) => !todo.done).length; - }).pipe( - Effect.catchTags({ - TimeoutError: (error) => - Effect.fail(`${error.url} didn't answer within ${error.duration}`), - HttpError: (error) => - Effect.fail(error.body?.message ?? `HTTP ${error.status}`), - NetworkError: () => Effect.fail("You appear to be offline"), - DecodeError: (error) => - Effect.fail(`Unexpected response: ${error.message}`), - }), - ); - -export const main = (email: string, password: string) => - program(email, password).pipe(Effect.provide(ApiLive)); diff --git a/examples/endpoints.ts b/examples/endpoints.ts deleted file mode 100644 index a2173ee..0000000 --- a/examples/endpoints.ts +++ /dev/null @@ -1,151 +0,0 @@ -import * as Effect from "effect/Effect"; -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, logger, retry, timeout } from "@monarcode/effetch/plugins"; - -// The same app as `builtins.ts`, with endpoints: each route is defined once, -// next to its schemas, and shared as a service with `Fetch.Endpoints`. - -const Todo = Schema.Struct({ - id: Schema.Finite, - title: Schema.String, - done: Schema.Boolean, - due: Schema.Date, -}); - -const NewTodo = Schema.Struct({ title: Schema.String, due: Schema.Date }); - -const TodoFilters = Schema.Struct({ - done: Schema.optional(Schema.Boolean), - page: Schema.optional(Schema.Finite), -}); - -const Credentials = Schema.Struct({ - email: Schema.String, - password: Schema.String, -}); - -const Tokens = Schema.Struct({ accessToken: Schema.String }); - -const ApiError = Schema.Struct({ code: Schema.String, message: Schema.String }); - -const session: { accessToken: string | undefined } = { - accessToken: undefined, -}; - -// --- The client --- - -export class Api extends Fetch.Service()("examples/endpoints/Api", { - baseUrl: "https://api.example.com", - defaultError: ApiError, - plugins: [ - logger({ level: "Info" }), - retry(), - timeout({ duration: "10 seconds" }), - bearer({ token: () => session.accessToken }), - ], -}) {} - -// --- The endpoints, with no client --- - -export const login = Fetch.endpoint("POST /auth/login", { - input: Credentials, - output: Tokens, -}); - -export const listTodos = Fetch.endpoint("GET /todos", { - query: TodoFilters, - output: Schema.Array(Todo), -}); - -export const getTodo = Fetch.endpoint("GET /todos/:id", { output: Todo }); - -export const createTodo = Fetch.endpoint("POST /todos", { - input: NewTodo, - output: Todo, -}); - -export const completeTodo = Fetch.endpoint("PATCH /todos/:id", { - output: Todo, - headers: { "content-type": "application/merge-patch+json" }, -}); - -export const deleteTodo = Fetch.endpoint("DELETE /todos/:id"); - -export const exportTodos = Fetch.endpoint("GET /todos/export", { - output: Schema.Array(Todo), -}); - -// --- The endpoints, bound to the client, as a service --- - -// Plugin overrides are given when binding, where they're checked against -// `Api`'s plugins. -export class TodoApi extends Fetch.Endpoints()( - "examples/endpoints/TodoApi", - Api, - { - login: [login, { plugins: { bearer: false } }], - list: listTodos, - get: getTodo, - create: createTodo, - complete: completeTodo, - delete: deleteTodo, - export: [ - exportTodos, - { plugins: { timeout: { duration: "2 minutes" }, retry: false } }, - ], - }, -) {} - -export const AppLayer = TodoApi.layer.pipe( - Layer.provide(Api.layer), - Layer.provide(FetchHttpClient.layer), -); - -// --- Using them --- - -export const signIn = (email: string, password: string) => - Effect.gen(function* () { - const todos = yield* TodoApi; - const { accessToken } = yield* todos.login({ body: { email, password } }); - session.accessToken = accessToken; - }); - -export const program = (email: string, password: string) => - Effect.gen(function* () { - yield* signIn(email, password); - const todos = yield* TodoApi; - - const created = yield* todos.create({ - body: { title: "Write docs", due: new Date() }, - }); - yield* todos.complete({ - params: { id: created.id }, - body: { done: true }, - }); - const open = yield* todos.list({ query: { done: false, page: 1 } }); - - // A call can override what the binding set: this export is retried. - const all = yield* todos.export({ - plugins: { retry: { times: 2 } }, - }); - - yield* todos.delete({ params: { id: created.id } }); - return { open: open.length, all: all.length }; - }).pipe( - Effect.catchTags({ - TimeoutError: (error) => - Effect.fail(`${error.url} didn't answer within ${error.duration}`), - HttpError: (error) => - Effect.fail(error.body?.message ?? `HTTP ${error.status}`), - NetworkError: () => Effect.fail("You appear to be offline"), - DecodeError: (error) => - Effect.fail(`Unexpected response: ${error.message}`), - }), - ); - -export const main = (email: string, password: string) => - program(email, password).pipe(Effect.provide(AppLayer)); diff --git a/examples/github/github.test.ts b/examples/github/github.test.ts new file mode 100644 index 0000000..c666669 --- /dev/null +++ b/examples/github/github.test.ts @@ -0,0 +1,136 @@ +import { describe, expect, it } from "@effect/vitest"; +import * as ConfigProvider from "effect/ConfigProvider"; +import * as Effect from "effect/Effect"; +import * as Layer from "effect/Layer"; + +import { FetchTest } from "@monarcode/effetch/test"; + +import { + GitHub, + GitHubApi, + getRepo, + listIssues, + openIssues, + RateLimited, + RepoNotFound, +} from "./github.ts"; + +// The real GitHub client, with its plugins and errors, against a fake +// backend made from its endpoints. Nothing leaves the machine. + +const issue = (number: number, pullRequest = false) => ({ + number, + title: `Issue ${number}`, + user: { login: "octocat" }, + comments: 0, + ...(pullRequest ? { pull_request: { url: `https://pr/${number}` } } : {}), +}); + +const Backend = FetchTest.layer([ + FetchTest.respond(getRepo, ({ params }) => + Effect.succeed( + params.repo === "effect" + ? { + full_name: `${params.owner}/effect`, + description: null, + stargazers_count: 10, + open_issues_count: 3, + pushed_at: new Date("2026-11-01T00:00:00Z"), + } + : params.repo === "limited" + ? FetchTest.reply(403, { message: "API rate limit exceeded" }) + : params.repo === "blocked" + ? FetchTest.reply(403, { + message: "Repository access blocked", + }) + : FetchTest.reply(404, { message: "Not Found" }), + ), + ), + // Two pages. The first links to the second, as GitHub does. + FetchTest.respond(listIssues, ({ query }) => + Effect.succeed( + query.page === 1 + ? FetchTest.reply(200, [issue(3), issue(2, true)], { + headers: { + link: '; rel="next"', + }, + }) + : FetchTest.reply(200, [issue(1)]), + ), + ), +]); + +/** The client on the fake backend, with `env` as its environment. */ +const withEnv = (env: Record) => + GitHubApi.layer.pipe( + Layer.provide(GitHub.layer), + Layer.provideMerge(Backend), + Layer.provide(ConfigProvider.layer(ConfigProvider.fromUnknown(env))), + ); + +describe("GitHub", () => { + it.effect("decodes a repository", () => + Effect.gen(function* () { + const github = yield* GitHubApi; + const repo = yield* github.repo({ + params: { owner: "Effect-TS", repo: "effect" }, + }); + expect(repo.full_name).toBe("Effect-TS/effect"); + expect(repo.pushed_at).toBeInstanceOf(Date); + }).pipe(Effect.provide(withEnv({}))), + ); + + it.effect("turns a 404 into RepoNotFound", () => + Effect.gen(function* () { + const github = yield* GitHubApi; + const error = yield* Effect.flip( + github.repo({ params: { owner: "Effect-TS", repo: "nope" } }), + ); + expect(error).toBeInstanceOf(RepoNotFound); + }).pipe(Effect.provide(withEnv({}))), + ); + + it.effect("tells a rate limit from other 403s", () => + Effect.gen(function* () { + const github = yield* GitHubApi; + const limited = yield* Effect.flip( + github.repo({ params: { owner: "o", repo: "limited" } }), + ); + expect(limited).toBeInstanceOf(RateLimited); + const blocked = yield* Effect.flip( + github.repo({ params: { owner: "o", repo: "blocked" } }), + ); + expect(blocked).toMatchObject({ _tag: "HttpError", status: 403 }); + }).pipe(Effect.provide(withEnv({}))), + ); + + it.effect("follows the Link header, and leaves pull requests out", () => + Effect.gen(function* () { + const issues = yield* openIssues("o", "r", { perPage: 2, pages: 5 }); + expect(issues.map((issue) => issue.number)).toStrictEqual([3, 1]); + const pages = (yield* FetchTest.requests).map( + (sent) => sent.query.page, + ); + expect(pages).toStrictEqual(["1", "2"]); + }).pipe(Effect.provide(withEnv({}))), + ); + + it.effect("sends GITHUB_TOKEN when it's set, and nothing otherwise", () => + Effect.gen(function* () { + const sendsToken = Effect.gen(function* () { + const github = yield* GitHubApi; + yield* github.repo({ params: { owner: "o", repo: "effect" } }); + const [sent] = yield* FetchTest.requests; + return sent?.headers.authorization; + }); + expect( + yield* sendsToken.pipe( + Effect.provide(withEnv({ GITHUB_TOKEN: "ghp_test" })), + ), + ).toBe("Bearer ghp_test"); + expect(yield* sendsToken.pipe(Effect.provide(withEnv({})))).toBe( + undefined, + ); + }), + ); +}); diff --git a/examples/github/github.ts b/examples/github/github.ts new file mode 100644 index 0000000..8cd30a3 --- /dev/null +++ b/examples/github/github.ts @@ -0,0 +1,157 @@ +import * as Config from "effect/Config"; +import * as Effect from "effect/Effect"; +import * as Option from "effect/Option"; +import * as Redacted from "effect/Redacted"; +import * as Schema from "effect/Schema"; +import * as Stream from "effect/Stream"; + +import { Fetch } from "@monarcode/effetch"; +import { bearer, retry } from "@monarcode/effetch/plugins"; + +// A client for GitHub's REST API: what it sends, what its errors mean, and +// two endpoints. `main.ts` uses it, and `github.test.ts` tests it. + +// --- What GitHub sends --- + +export const Repo = Schema.Struct({ + full_name: Schema.String, + description: Schema.NullOr(Schema.String), + stargazers_count: Schema.Finite, + open_issues_count: Schema.Finite, + // Sent as an ISO string, decoded into a `Date`. + pushed_at: Schema.Date, +}); + +export const Issue = Schema.Struct({ + number: Schema.Finite, + title: Schema.String, + user: Schema.NullOr(Schema.Struct({ login: Schema.String })), + comments: Schema.Finite, + // GitHub lists pull requests as issues too, with this field set. + pull_request: Schema.optionalKey(Schema.Struct({ url: Schema.String })), +}); + +/** The body of GitHub's error responses. */ +export const GitHubError = Schema.Struct({ + message: Schema.String, + documentation_url: Schema.optionalKey(Schema.String), +}); + +// --- What its errors mean --- + +/** A 404: no such repository, or one the token can't see. */ +export class RepoNotFound extends Schema.TaggedError()( + "RepoNotFound", + { message: Schema.String }, +) {} + +/** + * The rate limit is used up. GitHub answers a 403 or a 429, with a message + * that says so. Any other 403 stays an `HttpError`. + */ +export class RateLimited extends Schema.TaggedError()( + "RateLimited", + { message: Schema.String.check(Schema.isIncluding("rate limit")) }, +) {} + +// --- The client --- + +// Optional. Without a token, GitHub allows 60 requests an hour. +const token = Config.option(Config.Redacted("GITHUB_TOKEN")).pipe( + Effect.map( + Option.match({ onNone: () => undefined, onSome: Redacted.value }), + ), + Effect.orElseSucceed(() => undefined), +); + +/** Warns when the rate limit is nearly used up. */ +const rateLimitWarning = Fetch.plugin({ + name: "rateLimitWarning", + defaults: { below: 10 }, + onResponse: (response, ctx) => { + const remaining = Number(response.headers["x-ratelimit-remaining"]); + return remaining < ctx.options.below + ? Effect.as( + Effect.logWarning( + `GitHub: ${remaining} requests left this hour`, + ), + response, + ) + : Effect.succeed(response); + }, +}); + +export class GitHub extends Fetch.Service()("GitHub", { + baseUrl: "https://api.github.com", + headers: { + accept: "application/vnd.github+json", + "x-github-api-version": "2022-11-28", + }, + defaultError: GitHubError, + statusErrors: { 403: RateLimited, 429: RateLimited }, + plugins: [ + // A 429 for a secondary rate limit says how long to wait. + retry({ retryAfter: { max: "30 seconds" } }), + rateLimitWarning, + bearer({ token }), + ], +}) {} + +// --- The endpoints --- + +export const getRepo = Fetch.endpoint("GET /repos/:owner/:repo", { + output: Repo, + statusErrors: { 404: RepoNotFound }, +}); + +export const listIssues = Fetch.endpoint("GET /repos/:owner/:repo/issues", { + query: Schema.Struct({ + state: Schema.Literals(["open", "closed", "all"]), + per_page: Schema.optionalKey(Schema.Finite), + page: Schema.optionalKey(Schema.Finite), + }), + output: Schema.Array(Issue), + statusErrors: { 404: RepoNotFound }, + // The response too, for its `Link` header. + responseMode: "decoded-and-response", +}); + +export class GitHubApi extends Fetch.Endpoints()( + "GitHubApi", + GitHub, + { repo: getRepo, issues: listIssues }, +) {} + +// --- Paging --- + +/** The page number in a `Link` header's `rel="next"` URL. */ +export const nextPage = (link: string | undefined): Option.Option => + Option.fromNullishOr( + /[?&]page=(\d+)[^>]*>;\s*rel="next"/.exec(link ?? "")?.[1], + ).pipe(Option.map(Number)); + +/** + * A repository's open issues, newest first, from its first `pages` pages, + * following the `Link` header. Pull requests are left out. + */ +export const openIssues = ( + owner: string, + repo: string, + { perPage, pages }: { readonly perPage: number; readonly pages: number }, +) => + Effect.gen(function* () { + const github = yield* GitHubApi; + return yield* Fetch.paginate(github.issues, { + start: 1, + request: (page) => ({ + params: { owner, repo }, + query: { state: "open", per_page: perPage, page }, + }), + next: (_issues, _page, response) => nextPage(response.headers.link), + }).pipe( + Stream.take(pages), + Stream.flattenIterable, + Stream.filter((issue) => issue.pull_request === undefined), + Stream.runCollect, + ); + }); diff --git a/examples/github/main.ts b/examples/github/main.ts new file mode 100644 index 0000000..c2915b0 --- /dev/null +++ b/examples/github/main.ts @@ -0,0 +1,55 @@ +import * as Console from "effect/Console"; +import * as Effect from "effect/Effect"; +import * as FetchHttpClient from "effect/http/FetchHttpClient"; +import * as Layer from "effect/Layer"; + +import { GitHub, GitHubApi, openIssues } from "./github.ts"; + +// Shows a repository and its newest open issues: +// +// pnpm example github # Effect-TS/effect +// pnpm example github facebook/react +// +// Set GITHUB_TOKEN to raise the rate limit from 60 requests an hour. + +const [owner = "", repo = ""] = (process.argv[2] ?? "Effect-TS/effect").split( + "/", +); + +const showRepo = Effect.gen(function* () { + const github = yield* GitHubApi; + + const details = yield* github.repo({ params: { owner, repo } }); + yield* Console.log(`${details.full_name}: ${details.description ?? ""}`); + yield* Console.log( + `★ ${details.stargazers_count}, ${details.open_issues_count} open issues and pull requests, last push ${details.pushed_at.toDateString()}\n`, + ); + + // Two pages of ten, so you can see it follow the Link header. + const issues = yield* openIssues(owner, repo, { perPage: 10, pages: 2 }); + for (const issue of issues) { + yield* Console.log( + `#${issue.number} ${issue.title} (${issue.user?.login ?? "ghost"}, ${issue.comments} comments)`, + ); + } +}).pipe( + // The errors this program has an answer for. Any other one, such as a + // NetworkError, ends the run with the error. + Effect.catchTags({ + RepoNotFound: () => + Console.error( + `No repository ${owner}/${repo}. If it's private, set GITHUB_TOKEN.`, + ), + RateLimited: (error) => + Console.error( + `${error.message}\nSet GITHUB_TOKEN to make more requests.`, + ), + }), +); + +const GitHubLive = GitHubApi.layer.pipe( + Layer.provide(GitHub.layer), + Layer.provide(FetchHttpClient.layer), +); + +Effect.runPromise(showRepo.pipe(Effect.provide(GitHubLive))); diff --git a/examples/live/lichess.ts b/examples/live/lichess.ts new file mode 100644 index 0000000..4f89671 --- /dev/null +++ b/examples/live/lichess.ts @@ -0,0 +1,71 @@ +import * as Effect from "effect/Effect"; +import * as Schema from "effect/Schema"; +import * as Stream from "effect/Stream"; + +import { Fetch } from "@monarcode/effetch"; +import { timeout } from "@monarcode/effetch/plugins"; + +// Lichess TV: the game Lichess features, move by move, as newline-delimited +// JSON. Each line is either a new featured game or a move in it, told +// apart by `t`. + +const Player = Schema.Struct({ + color: Schema.Literals(["white", "black"]), + // Absent for Lichess's computer opponent. + user: Schema.optionalKey( + Schema.Struct({ + name: Schema.String, + title: Schema.optionalKey(Schema.String), + }), + ), + rating: Schema.optionalKey(Schema.Finite), +}); + +/** A new game is featured. */ +const Featured = Schema.Struct({ + t: Schema.Literal("featured"), + d: Schema.Struct({ id: Schema.String, players: Schema.Array(Player) }), +}); + +/** A move: the position after it, the move itself, and both clocks. */ +const Move = Schema.Struct({ + t: Schema.Literal("fen"), + d: Schema.Struct({ + fen: Schema.String, + lm: Schema.String, + wc: Schema.Finite, + bc: Schema.Finite, + }), +}); + +export const TvEvent = Schema.Union([Featured, Move]); +export type TvEvent = typeof TvEvent.Type; + +export class Lichess extends Fetch.Service()("Lichess", { + baseUrl: "https://lichess.org/api", + plugins: [timeout({ duration: "10 seconds" })], +}) {} + +export const tvFeed = Fetch.endpoint("GET /tv/feed", { + output: TvEvent, + stream: "ndjson", +}); + +export class LichessApi extends Fetch.Endpoints()( + "LichessApi", + Lichess, + { tvFeed }, +) {} + +/** The first `count` lines of Lichess TV: the featured game, then moves. */ +export const tv = (count: number) => + Stream.unwrap( + Effect.gen(function* () { + const lichess = yield* LichessApi; + return lichess.tvFeed().pipe(Stream.take(count)); + }), + ); + +/** Who made the move that led to `fen`: the side that isn't to play. */ +export const movedBy = (fen: string): "white" | "black" => + fen.split(" ")[1] === "b" ? "white" : "black"; diff --git a/examples/live/live.test.ts b/examples/live/live.test.ts new file mode 100644 index 0000000..9c8f1f5 --- /dev/null +++ b/examples/live/live.test.ts @@ -0,0 +1,94 @@ +import { describe, expect, it } from "@effect/vitest"; +import * as Effect from "effect/Effect"; +import * as Layer from "effect/Layer"; +import * as Stream from "effect/Stream"; + +import { FetchTest } from "@monarcode/effetch/test"; + +import { Lichess, LichessApi, movedBy, tv, tvFeed } from "./lichess.ts"; +import { + type Change, + humanEdits, + recentChanges, + Wikimedia, + WikimediaApi, +} from "./wikipedia.ts"; + +// Both feeds against one fake backend: a list of events for the SSE +// endpoint, and a list of lines for the NDJSON one. + +const change = (title: string, overrides: Partial = {}): Change => ({ + type: "edit", + title, + user: "Ada", + bot: false, + server_name: "en.wikipedia.org", + length: { old: 100, new: 120 }, + ...overrides, +}); + +const Backend = FetchTest.layer([ + FetchTest.respond(recentChanges, () => + Effect.succeed([ + { data: change("By a bot", { bot: true }) }, + { + data: change("On another wiki", { + server_name: "de.wikipedia.org", + }), + }, + { data: change("A new page", { type: "new" }) }, + { event: "message", id: "1", data: change("Kept") }, + { data: change("Kept too") }, + { data: change("One too many") }, + ]), + ), + FetchTest.respond(tvFeed, () => + Effect.succeed([ + { + t: "featured", + d: { + id: "game1", + players: [ + { color: "white", user: { name: "Ada" }, rating: 2000 }, + { color: "black", rating: 1800 }, + ], + }, + }, + { + t: "fen", + d: { + fen: "8/8/8/8/4P3/8/8/8 b - - 0 1", + lm: "e2e4", + wc: 60, + bc: 60, + }, + }, + ] as const), + ), +]); + +const TestLayer = Layer.mergeAll( + WikimediaApi.layer.pipe(Layer.provide(Wikimedia.layer)), + LichessApi.layer.pipe(Layer.provide(Lichess.layer)), +).pipe(Layer.provide(Backend)); + +describe("Live feeds", () => { + it.effect("keeps people's edits to English Wikipedia, up to the count", () => + Effect.gen(function* () { + const edits = yield* Stream.runCollect(humanEdits(2)); + expect(edits.map((edit) => edit.title)).toStrictEqual([ + "Kept", + "Kept too", + ]); + }).pipe(Effect.provide(TestLayer)), + ); + + it.effect("tells Lichess TV's featured games and moves apart", () => + Effect.gen(function* () { + const [featured, move] = yield* Stream.runCollect(tv(5)); + expect(featured?.t).toBe("featured"); + expect(move).toMatchObject({ t: "fen", d: { lm: "e2e4" } }); + if (move?.t === "fen") expect(movedBy(move.d.fen)).toBe("white"); + }).pipe(Effect.provide(TestLayer)), + ); +}); diff --git a/examples/live/main.ts b/examples/live/main.ts new file mode 100644 index 0000000..7fa2d1f --- /dev/null +++ b/examples/live/main.ts @@ -0,0 +1,53 @@ +import * as Console from "effect/Console"; +import * as Effect from "effect/Effect"; +import * as FetchHttpClient from "effect/http/FetchHttpClient"; +import * as Layer from "effect/Layer"; +import * as Stream from "effect/Stream"; + +import { Lichess, LichessApi, movedBy, tv } from "./lichess.ts"; +import { humanEdits, Wikimedia, WikimediaApi } from "./wikipedia.ts"; + +// Two live feeds from two backends, each read as it arrives: +// +// pnpm example live +// +// First the next edits to English Wikipedia, then the moves of the game +// Lichess TV is showing. Both streams end after a few items. + +const edits = humanEdits(5).pipe( + Stream.runForEach((change) => { + const size = (change.length?.new ?? 0) - (change.length?.old ?? 0); + return Console.log( + ` ${change.title}, by ${change.user} (${size >= 0 ? "+" : ""}${size} bytes)`, + ); + }), +); + +const moves = tv(9).pipe( + Stream.runForEach((line) => { + if (line.t === "featured") { + const [white, black] = line.d.players.map((player) => + `${player.user?.title ?? ""} ${player.user?.name ?? "Computer"} (${player.rating ?? "?"})`.trim(), + ); + return Console.log(` ${white} vs ${black}`); + } + return Console.log( + ` ${movedBy(line.d.fen)} plays ${line.d.lm}. Clocks: white ${line.d.wc}s, black ${line.d.bc}s`, + ); + }), +); + +const program = Effect.gen(function* () { + yield* Console.log("Wikipedia, live:"); + yield* edits; + yield* Console.log("\nLichess TV, live:"); + yield* moves; +}); + +// One layer per backend, both on one HttpClient. +const Live = Layer.mergeAll( + WikimediaApi.layer.pipe(Layer.provide(Wikimedia.layer)), + LichessApi.layer.pipe(Layer.provide(Lichess.layer)), +).pipe(Layer.provide(FetchHttpClient.layer)); + +Effect.runPromise(program.pipe(Effect.provide(Live))); diff --git a/examples/live/wikipedia.ts b/examples/live/wikipedia.ts new file mode 100644 index 0000000..c05618f --- /dev/null +++ b/examples/live/wikipedia.ts @@ -0,0 +1,66 @@ +import * as Effect from "effect/Effect"; +import * as Schema from "effect/Schema"; +import * as Stream from "effect/Stream"; + +import { Fetch } from "@monarcode/effetch"; +import { timeout } from "@monarcode/effetch/plugins"; + +// Every change to every Wikimedia wiki, as it happens: Server-Sent Events +// from Wikimedia's EventStreams. Each event's `data` is one change. + +/** One change, as the `data` of an event. */ +export const Change = Schema.Struct({ + // "edit", "new", "log" or "categorize". + type: Schema.String, + title: Schema.String, + user: Schema.String, + bot: Schema.Boolean, + server_name: Schema.String, + // The page's size before and after, in bytes, for edits. + length: Schema.optionalKey( + Schema.Struct({ + old: Schema.optionalKey(Schema.Finite), + new: Schema.optionalKey(Schema.Finite), + }), + ), +}); +export type Change = typeof Change.Type; + +export class Wikimedia extends Fetch.Service()("Wikimedia", { + baseUrl: "https://stream.wikimedia.org/v2", + // Wikimedia asks clients for a User-Agent that names them. A browser + // can't set one, so send `api-user-agent` from a web page instead. + headers: { "user-agent": "effetch-examples" }, + // Until the response starts. Reading the stream has no time limit. + plugins: [timeout({ duration: "10 seconds" })], +}) {} + +export const recentChanges = Fetch.endpoint("GET /stream/recentchange", { + output: Change, + stream: "sse", +}); + +export class WikimediaApi extends Fetch.Endpoints()( + "WikimediaApi", + Wikimedia, + { recentChanges }, +) {} + +/** The next `count` edits to English Wikipedia made by people, not bots. */ +export const humanEdits = (count: number) => + Stream.unwrap( + Effect.gen(function* () { + const wikimedia = yield* WikimediaApi; + return wikimedia.recentChanges().pipe( + Stream.map((event) => event.data), + Stream.filter( + (change) => + change.server_name === "en.wikipedia.org" && + change.type === "edit" && + !change.bot, + ), + // Ends the stream, and closes the connection, after `count`. + Stream.take(count), + ); + }), + ); diff --git a/examples/plugins.ts b/examples/plugins.ts deleted file mode 100644 index 509dfdb..0000000 --- a/examples/plugins.ts +++ /dev/null @@ -1,188 +0,0 @@ -import * as Context from "effect/Context"; -import * as Data from "effect/Data"; -import type * as Duration from "effect/Duration"; -import * as Effect from "effect/Effect"; -import * as FetchHttpClient from "effect/http/FetchHttpClient"; -import * as HttpClient from "effect/http/HttpClient"; -import * as HttpClientRequest from "effect/http/HttpClientRequest"; -import * as Layer from "effect/Layer"; -import * as Ref from "effect/Ref"; -import * as Schema from "effect/Schema"; - -import { Fetch } from "@monarcode/effetch"; - -const Todo = Schema.Struct({ - id: Schema.Finite, - title: Schema.String, - done: Schema.Boolean, -}); - -const Tokens = Schema.Struct({ accessToken: Schema.String }); - -const ApiError = Schema.Struct({ code: Schema.String, message: Schema.String }); - -export class SessionExpired extends Data.TaggedError("SessionExpired")<{}> {} - -export class DeadlineExceeded extends Data.TaggedError("DeadlineExceeded")<{ - readonly method: string; - readonly url: string; -}> {} - -export class Session extends Context.Service< - Session, - { - readonly accessToken: Effect.Effect; - readonly signIn: (accessToken: string) => Effect.Effect; - readonly signOut: Effect.Effect; - } ->()("Session") {} - -export const SessionLive = Layer.effect(Session)( - Effect.gen(function* () { - const token = yield* Ref.make(undefined); - return { - accessToken: Ref.get(token), - signIn: (accessToken: string) => Ref.set(token, accessToken), - signOut: Ref.set(token, undefined), - }; - }), -); - -/** - * Sends the session's access token, and signs out and fails with - * `SessionExpired` when the API answers 401. It needs `Session`, so `make` - * does too; the calls don't. - */ -const auth = Fetch.plugin({ - name: "auth", - onRequest: (request) => - Effect.gen(function* () { - const session = yield* Session; - const token = yield* session.accessToken; - return token === undefined - ? request - : HttpClientRequest.bearerToken(request, token); - }), - onResponse: (response) => - Effect.gen(function* () { - if (response.status !== 401) { - return response; - } - const session = yield* Session; - yield* session.signOut; - return yield* new SessionExpired(); - }), -}); - -/** Pins the API version. A call can ask for another one. */ -const apiVersion = Fetch.plugin({ - name: "apiVersion", - defaults: { version: "2024-06-01" }, - onRequest: (request, ctx) => - Effect.succeed( - HttpClientRequest.setHeader( - request, - "api-version", - ctx.options.version, - ), - ), -}); - -const deadlineDefaults: { readonly duration: Duration.Input } = { - duration: "10 seconds", -}; - -/** - * Fails with `DeadlineExceeded` when no response arrives in time. Its - * `wrap` encloses the plugins after it, so the deadline covers them too. - */ -const deadline = Fetch.plugin({ - name: "deadline", - defaults: deadlineDefaults, - wrap: (client, options) => - HttpClient.transform(client, (response, request) => - Effect.gen(function* () { - const { duration } = yield* options; - return yield* Effect.timeoutOrElse(response, { - duration, - orElse: () => - Effect.fail( - new DeadlineExceeded({ - method: request.method, - url: request.url, - }), - ), - }); - }), - ), -}); - -/** Logs every failed call. It can't change the outcome. */ -const reportErrors = Fetch.plugin({ - name: "reportErrors", - onError: (error, ctx) => - Effect.logWarning( - `${ctx.request.method} ${ctx.request.url} failed`, - error, - ), -}); - -export class Api extends Fetch.Service()("Api", { - baseUrl: "https://api.example.com", - defaultError: ApiError, - plugins: [reportErrors, deadline, apiVersion, auth], -}) {} - -export const ApiLive = Api.layer.pipe( - Layer.provide(FetchHttpClient.layer), - Layer.provideMerge(SessionLive), -); - -export const signIn = (email: string, password: string) => - Effect.gen(function* () { - const api = yield* Api; - const session = yield* Session; - const { accessToken } = yield* api.post("/auth/login", { - body: { email, password }, - output: Tokens, - plugins: { auth: false }, - }); - yield* session.signIn(accessToken); - }); - -export const listTodos = Effect.gen(function* () { - const api = yield* Api; - return yield* api.get("/todos", { output: Schema.Array(Todo) }); -}); - -export const exportTodos = Effect.gen(function* () { - const api = yield* Api; - return yield* api.get("/todos/export", { - output: Schema.Array(Todo), - plugins: { - deadline: { duration: "2 minutes" }, - apiVersion: { version: "2025-01-01" }, - }, - }); -}); - -export const program = (email: string, password: string) => - Effect.gen(function* () { - yield* signIn(email, password); - const todos = yield* listTodos; - return todos.length; - }).pipe( - Effect.catchTags({ - SessionExpired: () => Effect.fail("Please sign in again"), - DeadlineExceeded: (error) => - Effect.fail(`${error.method} ${error.url} took too long`), - HttpError: (error) => - Effect.fail(error.body?.message ?? `HTTP ${error.status}`), - NetworkError: () => Effect.fail("You appear to be offline"), - DecodeError: (error) => - Effect.fail(`Unexpected response: ${error.message}`), - }), - ); - -export const main = (email: string, password: string) => - program(email, password).pipe(Effect.provide(ApiLive)); diff --git a/examples/sign-in/dummyjson.ts b/examples/sign-in/dummyjson.ts new file mode 100644 index 0000000..1612239 --- /dev/null +++ b/examples/sign-in/dummyjson.ts @@ -0,0 +1,168 @@ +import * as Context from "effect/Context"; +import * as Effect from "effect/Effect"; +import * as Layer from "effect/Layer"; +import * as Option from "effect/Option"; +import * as Ref from "effect/Ref"; +import * as Schema from "effect/Schema"; + +import { Fetch } from "@monarcode/effetch"; +import { bearer, consoleLogger } from "@monarcode/effetch/plugins"; + +// Signing in to DummyJSON, a free fake API, and staying signed in. Two +// clients for one backend: `Auth` signs in and renews tokens, and +// `DummyJson` makes every other call with the session's token. + +// --- What DummyJSON sends --- + +export const Tokens = Schema.Struct({ + accessToken: Schema.String, + refreshToken: Schema.String, +}); +export type Tokens = typeof Tokens.Type; + +export const User = Schema.Struct({ + id: Schema.Finite, + firstName: Schema.String, + email: Schema.String, +}); + +export const Carts = Schema.Struct({ + carts: Schema.Array( + Schema.Struct({ + id: Schema.Finite, + totalQuantity: Schema.Finite, + discountedTotal: Schema.Finite, + }), + ), +}); + +/** The body of DummyJSON's error responses. */ +const ApiError = Schema.Struct({ message: Schema.String }); + +/** A 400 from the login: the username or password is wrong. */ +export class InvalidCredentials extends Schema.TaggedError()( + "InvalidCredentials", + { message: Schema.String }, +) {} + +/** A 401 that renewing the token couldn't fix: sign in again. */ +export class SignedOut extends Schema.TaggedError()("SignedOut", { + message: Schema.String, +}) {} + +// --- Signing in --- + +export const login = Fetch.endpoint("POST /auth/login", { + input: Schema.Struct({ + username: Schema.String, + password: Schema.String, + expiresInMins: Schema.Finite, + }), + output: Tokens, + statusErrors: { 400: InvalidCredentials }, +}); + +export const renew = Fetch.endpoint("POST /auth/refresh", { + input: Schema.Struct({ + refreshToken: Schema.String, + expiresInMins: Schema.Finite, + }), + output: Tokens, +}); + +/** Signs in and renews tokens. It sends no token of its own. */ +export class Auth extends Fetch.Service()("Auth", { + baseUrl: "https://dummyjson.com", + defaultError: ApiError, + plugins: [consoleLogger({ detail: "summary" })], +}) {} + +/** + * The signed-in user's tokens. They're kept in memory here. An app keeps + * them in secure storage, so that a restart doesn't sign the user out. + */ +export class Session extends Context.Service()("Session", { + make: Effect.gen(function* () { + const auth = yield* Auth; + const signIn = auth.bind(login); + const refresh = auth.bind(renew); + const tokens = yield* Ref.make(Option.none()); + const signOut = Ref.set(tokens, Option.none()); + + return { + /** The access token to send, or `undefined` when signed out. */ + accessToken: Effect.map(Ref.get(tokens), (saved) => + Option.getOrUndefined(Option.map(saved, (t) => t.accessToken)), + ), + /** + * A new access token, from the refresh token. `undefined` when + * there's none, or when the server refuses it (a 400, 401 or 403), + * which signs out. Any other failure, such as a 503, fails the + * call, and keeps the session for the next try. + */ + refresh: Effect.gen(function* () { + const saved = yield* Ref.get(tokens); + if (Option.isNone(saved)) return undefined; + const renewed = yield* refresh({ + body: { + refreshToken: saved.value.refreshToken, + expiresInMins: 30, + }, + }); + yield* Ref.set(tokens, Option.some(renewed)); + return renewed.accessToken; + }).pipe( + Fetch.catchStatus([400, 401, 403], () => + Effect.as(signOut, undefined), + ), + ), + signIn: Effect.fn("Session.signIn")(function* ( + username: string, + password: string, + ) { + const signedIn = yield* signIn({ + body: { username, password, expiresInMins: 30 }, + }); + yield* Ref.set(tokens, Option.some(signedIn)); + }), + signOut, + /** The tokens, to save until the next launch. */ + saved: Ref.get(tokens), + /** Restores the tokens an earlier launch saved. */ + restore: (saved: Tokens) => Ref.set(tokens, Option.some(saved)), + }; + }), +}) { + static readonly layer = Layer.effect(Session, Session.make); +} + +// --- Everything else --- + +/** + * The rest of the API. `bearer` sends the session's token, and when the + * server answers 401, it asks the session for a new one and sends the + * request again, once. + */ +export class DummyJson extends Fetch.Service()("DummyJson", { + ...Auth.config, + // What a 401 means once renewing the token has failed. + statusErrors: { 401: SignedOut }, + plugins: [ + consoleLogger({ detail: "summary" }), + bearer({ + token: Session.use((session) => session.accessToken), + refresh: Session.use((session) => session.refresh), + }), + ], +}) {} + +export const me = Fetch.endpoint("GET /auth/me", { output: User }); + +export const userCarts = Fetch.endpoint("GET /auth/carts/user/:id", { + output: Carts, +}); + +export class Account extends Fetch.Endpoints()("Account", DummyJson, { + me, + carts: userCarts, +}) {} diff --git a/examples/sign-in/main.ts b/examples/sign-in/main.ts new file mode 100644 index 0000000..f614ae3 --- /dev/null +++ b/examples/sign-in/main.ts @@ -0,0 +1,68 @@ +import * as Console from "effect/Console"; +import * as Effect from "effect/Effect"; +import * as FetchHttpClient from "effect/http/FetchHttpClient"; +import * as Layer from "effect/Layer"; +import * as Option from "effect/Option"; + +import { Account, Auth, DummyJson, Session } from "./dummyjson.ts"; + +// Signs in to DummyJSON's demo account, renews the access token when it's +// refused, and signs out: +// +// pnpm example sign-in +// +// Each call prints a line, so you can see what was sent. A renewed token +// shows as a `POST /auth/refresh` line before the call it was renewed for. + +const program = Effect.gen(function* () { + const session = yield* Session; + const account = yield* Account; + + yield* Console.log("1. Sign in with the wrong password:"); + yield* session + .signIn("emilys", "wrong") + .pipe( + Effect.catchTag("InvalidCredentials", (error) => + Console.log(` ${error.message}`), + ), + ); + + yield* Console.log("\n2. Sign in, and load the profile:"); + yield* session.signIn("emilys", "emilyspass"); + const user = yield* account.me(); + yield* Console.log(` Signed in as ${user.firstName} (${user.email})`); + + yield* Console.log( + "\n3. The access token expires. bearer renews it, and sends the request again:", + ); + // Rather than wait half an hour for it to expire, make it stale now. + const saved = yield* session.saved; + if (Option.isSome(saved)) { + yield* session.restore({ ...saved.value, accessToken: "stale" }); + } + const { carts } = yield* account.carts({ params: { id: user.id } }); + for (const cart of carts) { + yield* Console.log( + ` Cart ${cart.id}: ${cart.totalQuantity} items, $${cart.discountedTotal}`, + ); + } + + yield* Console.log("\n4. Sign out. The next call fails with SignedOut:"); + yield* session.signOut; + yield* account + .me() + .pipe( + Effect.catchTag("SignedOut", (error) => + Console.log(` ${error.message}: sign in again`), + ), + ); +}); + +const Live = Account.layer.pipe( + Layer.provide(DummyJson.layer), + Layer.provideMerge(Session.layer), + Layer.provide(Auth.layer), + Layer.provide(FetchHttpClient.layer), +); + +Effect.runPromise(program.pipe(Effect.provide(Live))); diff --git a/examples/sign-in/sign-in.test.ts b/examples/sign-in/sign-in.test.ts new file mode 100644 index 0000000..bb4d852 --- /dev/null +++ b/examples/sign-in/sign-in.test.ts @@ -0,0 +1,134 @@ +import { describe, expect, it } from "@effect/vitest"; +import * as Console from "effect/Console"; +import * as Effect from "effect/Effect"; +import * as Layer from "effect/Layer"; +import * as Option from "effect/Option"; + +import { FetchTest } from "@monarcode/effetch/test"; + +import { + Account, + Auth, + DummyJson, + InvalidCredentials, + login, + me, + renew, + Session, + SignedOut, +} from "./dummyjson.ts"; + +// The sign-in flow against a fake DummyJSON: a backend that hands out +// numbered tokens, and accepts only the newest one. + +const tokens = (n: number) => ({ + accessToken: `access-${n}`, + refreshToken: `refresh-${n}`, +}); + +const Backend = FetchTest.layer([ + FetchTest.respond(login, ({ body }) => + Effect.succeed( + body.password === "right" + ? tokens(1) + : FetchTest.reply(400, { message: "Invalid credentials" }), + ), + ), + FetchTest.respond(renew, ({ body }) => + Effect.succeed( + body.refreshToken === "refresh-1" + ? tokens(2) + : body.refreshToken === "while-down" + ? FetchTest.reply(503, { message: "Service unavailable" }) + : FetchTest.reply(403, { message: "Invalid refresh token" }), + ), + ), + FetchTest.respond(me, ({ headers }) => + Effect.succeed( + headers.authorization === "Bearer access-2" + ? { id: 1, firstName: "Emily", email: "emily@example.com" } + : FetchTest.reply(401, { message: "Invalid/Expired Token!" }), + ), + ), +]); + +// `consoleLogger` prints through Effect's `Console`: keep the tests quiet. +const Quiet = Layer.succeed(Console.Console, { + ...globalThis.console, + log: () => {}, + group: () => {}, + groupCollapsed: () => {}, + groupEnd: () => {}, +}); + +const TestLayer = Account.layer.pipe( + Layer.provide(DummyJson.layer), + Layer.provideMerge(Session.layer), + Layer.provide(Auth.layer), + Layer.provideMerge(Backend), + Layer.provide(Quiet), +); + +describe("Signing in", () => { + it.effect("turns a wrong password into InvalidCredentials", () => + Effect.gen(function* () { + const session = yield* Session; + const error = yield* Effect.flip(session.signIn("emilys", "wrong")); + expect(error).toBeInstanceOf(InvalidCredentials); + }).pipe(Effect.provide(TestLayer)), + ); + + it.effect("renews a refused token, and sends the request again", () => + Effect.gen(function* () { + const session = yield* Session; + const account = yield* Account; + // The backend refuses access-1, the token the login gives. + yield* session.signIn("emilys", "right"); + const user = yield* account.me(); + expect(user.firstName).toBe("Emily"); + + const sent = (yield* FetchTest.requests).map( + (request) => + `${request.route} ${request.headers.authorization ?? ""}`, + ); + expect(sent).toStrictEqual([ + "POST /auth/login ", + "GET /auth/me Bearer access-1", + "POST /auth/refresh ", + "GET /auth/me Bearer access-2", + ]); + const saved = yield* session.saved; + expect(Option.map(saved, (t) => t.accessToken)).toStrictEqual( + Option.some("access-2"), + ); + }).pipe(Effect.provide(TestLayer)), + ); + + it.effect("signs out when the refresh token is refused too", () => + Effect.gen(function* () { + const session = yield* Session; + const account = yield* Account; + yield* session.restore({ + accessToken: "stale", + refreshToken: "revoked", + }); + const error = yield* Effect.flip(account.me()); + expect(error).toBeInstanceOf(SignedOut); + expect(Option.isNone(yield* session.saved)).toBe(true); + }).pipe(Effect.provide(TestLayer)), + ); + + it.effect("keeps the session when renewing fails for another reason", () => + Effect.gen(function* () { + const session = yield* Session; + const account = yield* Account; + yield* session.restore({ + accessToken: "stale", + refreshToken: "while-down", + }); + const error = yield* Effect.flip(account.me()); + expect(error).toMatchObject({ _tag: "HttpError", status: 503 }); + expect(Option.isSome(yield* session.saved)).toBe(true); + }).pipe(Effect.provide(TestLayer)), + ); +}); diff --git a/examples/status-errors.ts b/examples/status-errors.ts deleted file mode 100644 index 29d6fe5..0000000 --- a/examples/status-errors.ts +++ /dev/null @@ -1,174 +0,0 @@ -import * as Effect from "effect/Effect"; -import * as FetchHttpClient from "effect/http/FetchHttpClient"; -import * as Layer from "effect/Layer"; -import * as Schedule from "effect/Schedule"; -import * as Schema from "effect/Schema"; - -import { Fetch } from "@monarcode/effetch"; - -// The backend's error body, for responses that aren't one of the errors -// below. -const ApiError = Schema.Struct({ code: Schema.String, message: Schema.String }); - -// The app's own errors. The backend never sends a `_tag`: Effetch adds it -// before decoding, so plain `Schema.TaggedError` classes work. - -/** A 401 from any endpoint: the session is over. */ -export class SessionExpired extends Schema.TaggedError()( - "SessionExpired", - { message: Schema.String }, -) {} - -/** A 429 from any endpoint. */ -export class RateLimited extends Schema.TaggedError()( - "RateLimited", - { retryAfter: Schema.Finite }, -) {} - -/** A 404 from the todo endpoints. */ -export class TodoNotFound extends Schema.TaggedError()( - "TodoNotFound", - { message: Schema.String }, -) {} - -// Two 400s from `POST /todos/:id/assignees`, told apart by their literal -// `code`. Any other 400 stays an `HttpError`. - -export class UnknownUser extends Schema.TaggedError()( - "UnknownUser", - { code: Schema.Literal("UNKNOWN_USER"), message: Schema.String }, -) {} - -export class AlreadyAssigned extends Schema.TaggedError()( - "AlreadyAssigned", - { - code: Schema.Literal("ALREADY_ASSIGNED"), - message: Schema.String, - assignee: Schema.String, - }, -) {} - -/** A 409 from `GET /reports/:id`, while the report is being built. */ -export class ReportNotReady extends Schema.TaggedError()( - "ReportNotReady", - { message: Schema.String }, -) {} - -const Todo = Schema.Struct({ - id: Schema.Finite, - title: Schema.String, - assignees: Schema.Array(Schema.String), -}); - -const Report = Schema.Struct({ url: Schema.String }); - -// --- For every call: the client's map --- - -export class Api extends Fetch.Service()("examples/status-errors/Api", { - baseUrl: "https://api.example.com", - defaultError: ApiError, - // What these statuses mean from any endpoint. The backend sends - // `retry_after_seconds`; `encodeKeys` reads it into `retryAfter`. - statusErrors: { - 401: SessionExpired, - 429: RateLimited.pipe( - Schema.encodeKeys({ retryAfter: "retry_after_seconds" }), - ), - }, -}) {} - -// --- For every call to an endpoint: the endpoint's map --- - -export const getTodo = Fetch.endpoint("GET /todos/:id", { - output: Todo, - statusErrors: { 404: TodoNotFound }, -}); - -export const assign = Fetch.endpoint("POST /todos/:id/assignees", { - input: Schema.Struct({ userId: Schema.String }), - output: Todo, - // A list is tried in order: the first that decodes the body wins. - statusErrors: { - 404: TodoNotFound, - 400: [UnknownUser, AlreadyAssigned], - }, -}); - -export class TodoApi extends Fetch.Endpoints()( - "examples/status-errors/TodoApi", - Api, - { get: getTodo, assign }, -) {} - -// `provideMerge` keeps `Api` available too, for `report`'s one-off call. -export const AppLayer = TodoApi.layer.pipe( - Layer.provideMerge(Api.layer), - Layer.provide(FetchHttpClient.layer), -); - -// --- For one call: the call's map --- - -export const report = (id: number) => - Effect.gen(function* () { - const api = yield* Api; - return yield* api.get("/reports/:id", { - params: { id }, - output: Report, - statusErrors: { 409: ReportNotReady }, - }); - }); - -// --- Using them --- - -// A missing todo is `undefined`; every other error stays in the type, for -// the caller to handle. -export const findTodo = (id: number) => - Effect.gen(function* () { - const todos = yield* TodoApi; - return yield* todos.get({ params: { id } }); - }).pipe(Effect.catchTag("TodoNotFound", () => Effect.undefined)); - -// Each error comes with its own fields: `assignee` is typed and decoded. -export const assignTo = (id: number, userId: string) => - Effect.gen(function* () { - const todos = yield* TodoApi; - return yield* todos.assign({ params: { id }, body: { userId } }); - }).pipe( - Effect.catchTags({ - AlreadyAssigned: (error) => - Effect.fail(`Already assigned to ${error.assignee}`), - UnknownUser: (error) => Effect.fail(error.message), - }), - ); - -export const program = Effect.gen(function* () { - const todo = yield* findTodo(1); - if (todo === undefined) { - return "No todo 1"; - } - yield* assignTo(todo.id, "u_ada"); - const { url } = yield* report(todo.id).pipe( - Effect.retry({ - while: (error) => error._tag === "ReportNotReady", - schedule: Schedule.spaced("2 seconds"), - times: 3, - }), - ); - return url; -}).pipe( - Effect.catchTags({ - SessionExpired: () => Effect.fail("Please sign in again"), - RateLimited: (error) => - Effect.fail(`Too many requests: try again in ${error.retryAfter}s`), - ReportNotReady: () => Effect.fail("The report isn't ready yet"), - TodoNotFound: (error) => Effect.fail(error.message), - // Whatever the maps don't cover is still an HttpError. - HttpError: (error) => - Effect.fail(error.body?.message ?? `HTTP ${error.status}`), - NetworkError: () => Effect.fail("You appear to be offline"), - DecodeError: (error) => - Effect.fail(`Unexpected response: ${error.message}`), - }), -); - -export const main = program.pipe(Effect.provide(AppLayer)); diff --git a/examples/store-react/index.html b/examples/store-react/index.html new file mode 100644 index 0000000..f6a852b --- /dev/null +++ b/examples/store-react/index.html @@ -0,0 +1,12 @@ + + + + + + Effetch store + + +
+ + + diff --git a/examples/store-react/package.json b/examples/store-react/package.json new file mode 100644 index 0000000..24f687f --- /dev/null +++ b/examples/store-react/package.json @@ -0,0 +1,22 @@ +{ + "name": "effetch-example-store-react", + "private": true, + "description": "The store example's modules behind a small React app, routed with TanStack Router", + "type": "module", + "scripts": { + "dev": "vite", + "build": "vite build", + "preview": "vite preview" + }, + "dependencies": { + "@tanstack/react-router": "1.170.46", + "react": "19.3.1", + "react-dom": "19.3.1" + }, + "devDependencies": { + "@types/react": "19.3.0", + "@types/react-dom": "19.3.0", + "@vitejs/plugin-react": "6.3.0", + "vite": "8.3.7" + } +} diff --git a/examples/store-react/src/app.test.ts b/examples/store-react/src/app.test.ts new file mode 100644 index 0000000..e498797 --- /dev/null +++ b/examples/store-react/src/app.test.ts @@ -0,0 +1,257 @@ +import * as Effect from "effect/Effect"; +import * as Layer from "effect/Layer"; +import * as ManagedRuntime from "effect/ManagedRuntime"; + +import { Fetch } from "@monarcode/effetch"; +import { FetchTest } from "@monarcode/effetch/test"; +import { + createMemoryHistory, + RouterProvider, + SearchParamError, +} from "@tanstack/react-router"; +import { createElement } from "react"; +import { renderToString } from "react-dom/server"; +import { afterEach, describe, expect, it } from "vitest"; + +import { StoreApiClient } from "../../store/infrastructure/http/store-api-client.ts"; +import { CartModuleLive } from "../../store/modules/cart/cart.layer.ts"; +import { createCart } from "../../store/modules/cart/contract/cart.ts"; +import { + getProduct, + listCategories, + productsInCategory, +} from "../../store/modules/products/contract/products.ts"; +import { ProductModuleLive } from "../../store/modules/products/products.layer.ts"; +import { buyCheapestMessage, describeError } from "./messages.ts"; +import { makeRouter } from "./router.ts"; +import type { StoreRuntime } from "./store.ts"; + +// The app as it runs: the store's real modules and client, with only the +// HttpClient under them fake. The route tests build the app's router at a +// URL, load it, then read what the loaders gave the page's route, and what +// the page shows. + +const phone = { + id: 1, + title: "iPhone 9", + category: "smartphones", + price: 549, + stock: 94, +}; + +/** A runtime whose calls `handlers` answer, disposed after each test. */ +const runtimeWith = (...handlers: ReadonlyArray) => { + const runtime = ManagedRuntime.make( + Layer.mergeAll(ProductModuleLive, CartModuleLive).pipe( + Layer.provide(StoreApiClient.layer), + Layer.provideMerge(FetchTest.layer(handlers)), + ), + ); + runtimes.push(runtime); + return runtime; +}; +const runtimes: Array> = []; +afterEach(async () => { + await Promise.all(runtimes.splice(0).map((runtime) => runtime.dispose())); +}); + +/** + * The app's routes at `url`, after their loaders ran, as a browser runs + * them: Node would otherwise count as the server, where `navigate` doesn't + * load. + */ +const loaded = async (runtime: StoreRuntime, url: string) => { + const router = makeRouter(runtime, { + history: createMemoryHistory({ initialEntries: [url] }), + isServer: false, + // What the browser's `window.origin` would be. + origin: "http://localhost", + }); + await router.load(); + return router; +}; + +type LoadedRouter = Awaited>; + +/** The deepest match: the page's route. */ +const page = (router: LoadedRouter) => router.state.matches.at(-1); + +/** The page's text, as React renders it. */ +const text = (router: LoadedRouter) => + renderToString(createElement(RouterProvider, { router })) + .replaceAll(/<[^>]+>/g, " ") + .replaceAll("'", "'") + .replaceAll(/\s+/g, " "); + +describe("store-react routes", () => { + it("loads the categories", async () => { + const runtime = runtimeWith( + FetchTest.respond(listCategories, () => + Effect.succeed([{ slug: "smartphones", name: "Smartphones" }]), + ), + ); + const router = await loaded(runtime, "/"); + expect(page(router)?.loaderData).toStrictEqual([ + { slug: "smartphones", name: "Smartphones" }, + ]); + }); + + it("reads the page from the search params", async () => { + const runtime = runtimeWith( + FetchTest.respond(productsInCategory, () => + Effect.succeed({ products: [phone], total: 20 }), + ), + ); + const router = await loaded(runtime, "/categories/smartphones?page=2"); + expect(page(router)?.status).toBe("success"); + expect(text(router)).toContain("Page 2 of 3"); + const [sent] = await runtime.runPromise(FetchTest.requests); + expect(sent?.params).toStrictEqual({ category: "smartphones" }); + expect(sent?.query).toStrictEqual({ limit: "8", skip: "8" }); + }); + + it("rejects a page the search schema doesn't take", async () => { + const runtime = runtimeWith(); + const router = await loaded(runtime, "/categories/smartphones?page=0"); + const match = page(router); + expect(match?.status).toBe("error"); + expect(match?.error).toBeInstanceOf(SearchParamError); + expect(await runtime.runPromise(FetchTest.requests)).toStrictEqual([]); + }); + + it("shows the not-found for a page past the last one", async () => { + const runtime = runtimeWith( + FetchTest.respond(productsInCategory, () => + Effect.succeed({ products: [], total: 20 }), + ), + ); + const router = await loaded(runtime, "/categories/smartphones?page=9"); + expect(page(router)?.status).toBe("notFound"); + expect(text(router)).toContain("There's no such page."); + }); + + it("shows a product's page", async () => { + const runtime = runtimeWith( + FetchTest.respond(getProduct, () => Effect.succeed(phone)), + ); + const router = await loaded(runtime, "/products/1"); + expect(text(router)).toContain("iPhone 9"); + expect(text(router)).toContain("94 in stock"); + }); + + it("turns ProductNotFound into the route's not-found", async () => { + const runtime = runtimeWith( + FetchTest.respond(getProduct, () => + Effect.succeed( + FetchTest.reply(404, { message: "Product not found" }), + ), + ), + ); + const router = await loaded(runtime, "/products/9999"); + expect(page(router)?.status).toBe("notFound"); + expect(text(router)).toContain("This product isn't in the store."); + }); + + it("hands other errors to the route's error component, typed", async () => { + const runtime = runtimeWith( + FetchTest.respond(getProduct, () => + Effect.succeed(FetchTest.reply(500, { message: "Down" })), + ), + ); + const router = await loaded(runtime, "/products/1"); + const match = page(router); + expect(match?.status).toBe("error"); + expect(match?.error).toBeInstanceOf(Fetch.HttpError); + // React can't render an error boundary to a string, so this checks + // what `RouteError` shows for it. + expect(describeError(match?.error)).toBe( + "The store answered with an error (500).", + ); + }); + + it("interrupts a loader's call when the navigation moves on", async () => { + let started: () => void = () => {}; + const asked = new Promise((resolve) => { + started = resolve; + }); + let interrupted = false; + const runtime = runtimeWith( + // The store never answers, so only leaving the page ends the call. + FetchTest.respond(getProduct, () => + Effect.sync(started).pipe( + Effect.andThen(Effect.never), + Effect.onInterrupt(() => + Effect.sync(() => { + interrupted = true; + }), + ), + ), + ), + FetchTest.respond(listCategories, () => Effect.succeed([])), + ); + const router = await loaded(runtime, "/"); + void router.navigate({ + to: "/products/$productId", + params: { productId: "1" }, + }); + await asked; + await router.navigate({ to: "/" }); + + await Effect.runPromise(Effect.sleep("10 millis")); + expect(interrupted).toBe(true); + }); +}); + +describe("buyCheapestMessage", () => { + const store = (stock: number, status = 201) => + runtimeWith( + FetchTest.respond(productsInCategory, ({ params }) => + Effect.succeed( + params.category === "smartphones" + ? { products: [{ ...phone, stock }], total: 1 } + : { products: [], total: 0 }, + ), + ), + FetchTest.respond( + createCart, + ({ body }) => + Effect.succeed( + status === 201 + ? { + id: 51, + products: body.products.map((line) => ({ + ...line, + title: phone.title, + })), + discountedTotal: phone.price * 2, + } + : FetchTest.reply(status, { message: "Down" }), + ), + { status: 201 }, + ), + ); + + it("says what went in the cart", async () => { + const message = await store(94).runPromise( + buyCheapestMessage("smartphones", 2), + ); + expect(message).toBe("Cart 51: 2 × iPhone 9, $1098"); + }); + + it("gives each of the workflow's errors its own message", async () => { + const runtime = store(3); + expect( + await runtime.runPromise(buyCheapestMessage("smartphones", 5)), + ).toBe("Only 3 iPhone 9 left, not 5."); + expect( + await runtime.runPromise(buyCheapestMessage("flying-cars", 1)), + ).toBe("There's nothing to buy here."); + }); + + it("describes the store's errors", async () => { + const message = await store(94, 503).runPromise( + buyCheapestMessage("smartphones", 2), + ); + expect(message).toBe("The store answered with an error (503)."); + }); +}); diff --git a/examples/store-react/src/category.tsx b/examples/store-react/src/category.tsx new file mode 100644 index 0000000..26bf97b --- /dev/null +++ b/examples/store-react/src/category.tsx @@ -0,0 +1,144 @@ +import * as Effect from "effect/Effect"; +import * as Schema from "effect/Schema"; + +import { createRoute, Link, notFound } from "@tanstack/react-router"; +import { useState } from "react"; + +import { buyCheapestMessage } from "./messages.ts"; +import { rootRoute } from "./root.tsx"; +import { RouteError } from "./route-error.tsx"; +import { ProductApi } from "./store.ts"; +import { useAction } from "./use-action.ts"; + +/** How many products a page shows. */ +const perPage = 8; + +/** + * The page's search params, such as `?page=2`. TanStack Router takes an + * Effect schema as a Standard Schema, and types `search` from it. + */ +const CategorySearch = Schema.Struct({ + page: Schema.optionalKey(Schema.Int.check(Schema.isGreaterThanOrEqualTo(1))), +}); + +export const categoryRoute = createRoute({ + getParentRoute: () => rootRoute, + path: "/categories/$category", + validateSearch: Schema.toStandardSchemaV1(CategorySearch), + // The page is the loader's dependency, so another page loads again. + loaderDeps: ({ search }) => ({ page: search.page ?? 1 }), + loader: ({ context: { runtime }, params, deps, abortController }) => + runtime.runPromise( + ProductApi.use((products) => + products.inCategory({ + params: { category: params.category }, + query: { limit: perPage, skip: (deps.page - 1) * perPage }, + }), + ).pipe( + // A page past the last one is the router's not-found. + Effect.filterOrFail( + (result) => deps.page === 1 || result.products.length > 0, + () => notFound(), + ), + ), + { signal: abortController.signal }, + ), + component: CategoryPage, + notFoundComponent: () => ( +

+ There's no such page. Back to the store +

+ ), + errorComponent: RouteError, +}); + +function CategoryPage() { + const { category } = categoryRoute.useParams(); + const { page } = categoryRoute.useLoaderDeps(); + const { products, total } = categoryRoute.useLoaderData(); + const pages = Math.max(1, Math.ceil(total / perPage)); + return ( + <> +

{category}

+ + {products.length === 0 ? ( +

No products here.

+ ) : ( +
    + {products.map((product) => ( +
  • + + {product.title} + + ${product.price} +
  • + ))} +
+ )} + + + ); +} + +/** + * The cart workflow, from a form: the button waits while it runs, and its + * message, such as an `OutOfStock`, shows under it. Leaving the page + * while it runs interrupts it. + */ +function BuyCheapest({ category }: { readonly category: string }) { + const { runtime } = categoryRoute.useRouteContext(); + const action = useAction(runtime); + // The field's text, so it can be emptied and typed again. The browser + // checks it's a whole number of at least 1 before the form submits. + const [quantity, setQuantity] = useState("1"); + return ( +
{ + event.preventDefault(); + action.run(buyCheapestMessage(category, Number(quantity))); + }} + > + + + {action.result !== undefined &&

{action.result}

} +
+ ); +} diff --git a/examples/store-react/src/home.tsx b/examples/store-react/src/home.tsx new file mode 100644 index 0000000..00f41c1 --- /dev/null +++ b/examples/store-react/src/home.tsx @@ -0,0 +1,41 @@ +import { createRoute, Link } from "@tanstack/react-router"; + +import { rootRoute } from "./root.tsx"; +import { RouteError } from "./route-error.tsx"; +import { ProductApi } from "./store.ts"; + +export const homeRoute = createRoute({ + getParentRoute: () => rootRoute, + path: "/", + // Each loader runs its effect with the route's abort signal: leaving the + // page before the store answers interrupts the effect, and so cancels + // the request. + loader: ({ context: { runtime }, abortController }) => + runtime.runPromise( + ProductApi.use((products) => products.categories()), + { signal: abortController.signal }, + ), + component: Home, + errorComponent: RouteError, +}); + +function Home() { + const categories = homeRoute.useLoaderData(); + return ( + <> +

Categories

+
    + {categories.map((category) => ( +
  • + + {category.name} + +
  • + ))} +
+ + ); +} diff --git a/examples/store-react/src/main.tsx b/examples/store-react/src/main.tsx new file mode 100644 index 0000000..5b4a321 --- /dev/null +++ b/examples/store-react/src/main.tsx @@ -0,0 +1,21 @@ +import { RouterProvider } from "@tanstack/react-router"; +import { StrictMode } from "react"; +import { createRoot } from "react-dom/client"; + +import { makeRouter } from "./router.ts"; +import { runtime } from "./store.ts"; + +import "./styles.css"; + +// The store example's runtime: its modules, on its client, on the browser's +// `fetch`. The router hands it to every loader in its context. +const router = makeRouter(runtime); + +const root = document.querySelector("#root"); +if (root === null) throw new Error("index.html has no #root element"); + +createRoot(root).render( + + + , +); diff --git a/examples/store-react/src/messages.ts b/examples/store-react/src/messages.ts new file mode 100644 index 0000000..a310781 --- /dev/null +++ b/examples/store-react/src/messages.ts @@ -0,0 +1,52 @@ +import * as Effect from "effect/Effect"; + +import { Fetch } from "@monarcode/effetch"; +import { TimeoutError } from "@monarcode/effetch/plugins"; + +import { buyCheapest } from "./store.ts"; + +// What the screens tell the user. Plain functions and effects, with no +// React in them, so the tests check them without rendering anything. + +/** + * What to say about an error the store's calls can fail with, and the + * screen didn't handle itself. A loader's errors reach the route's error + * component as they are, typed, so they can be told apart here. + */ +export const describeError = (error: unknown): string => { + if (error instanceof Fetch.HttpError) { + return `The store answered with an error (${error.status}).`; + } + if (error instanceof Fetch.NetworkError) { + return "Couldn't reach the store. Check your connection."; + } + if (error instanceof TimeoutError) { + return "The store took too long to answer."; + } + if (error instanceof Fetch.DecodeError) { + return "The store sent something this app doesn't understand."; + } + return "Something went wrong."; +}; + +/** + * Buys the cheapest product in `category`, and says what happened. The + * workflow's own errors each get their own message, and the rest the one + * `describeError` gives, so the effect can't fail: its error type is + * `never`, as `useAction` asks. + */ +export const buyCheapestMessage = (category: string, quantity: number) => + buyCheapest(1, category, quantity).pipe( + Effect.map((cart) => { + const [line] = cart.products; + return `Cart ${cart.id}: ${line?.quantity} × ${line?.title}, $${cart.discountedTotal}`; + }), + Effect.catchTags({ + NothingToBuy: () => Effect.succeed("There's nothing to buy here."), + OutOfStock: (error) => + Effect.succeed( + `Only ${error.stock} ${error.product} left, not ${error.wanted}.`, + ), + }), + Effect.catch((error) => Effect.succeed(describeError(error))), + ); diff --git a/examples/store-react/src/product.tsx b/examples/store-react/src/product.tsx new file mode 100644 index 0000000..25544ea --- /dev/null +++ b/examples/store-react/src/product.tsx @@ -0,0 +1,47 @@ +import * as Effect from "effect/Effect"; + +import { createRoute, Link, notFound } from "@tanstack/react-router"; + +import { rootRoute } from "./root.tsx"; +import { RouteError } from "./route-error.tsx"; +import { ProductApi } from "./store.ts"; + +export const productRoute = createRoute({ + getParentRoute: () => rootRoute, + path: "/products/$productId", + loader: ({ context: { runtime }, params, abortController }) => + runtime.runPromise( + ProductApi.use((products) => + products.get({ params: { id: params.productId } }), + ).pipe( + // A product the store doesn't have is the router's not-found, which + // shows the route's `notFoundComponent`, rather than an error. + Effect.catchTag("ProductNotFound", () => Effect.fail(notFound())), + ), + { signal: abortController.signal }, + ), + component: ProductPage, + notFoundComponent: () => ( +

This product isn't in the store.

+ ), + errorComponent: RouteError, +}); + +function ProductPage() { + const product = productRoute.useLoaderData(); + return ( +
+

{product.title}

+

+ + {product.category} + +

+

${product.price}

+

{product.stock} in stock

+
+ ); +} diff --git a/examples/store-react/src/root.tsx b/examples/store-react/src/root.tsx new file mode 100644 index 0000000..3a3e630 --- /dev/null +++ b/examples/store-react/src/root.tsx @@ -0,0 +1,32 @@ +import { + createRootRouteWithContext, + Link, + Outlet, +} from "@tanstack/react-router"; + +import type { StoreRuntime } from "./store.ts"; + +/** What the router gives every route's loader and component. */ +export interface RouterContext { + readonly runtime: StoreRuntime; +} + +export const rootRoute = createRootRouteWithContext()({ + component: Layout, + notFoundComponent: () =>

There's no page here.

, +}); + +function Layout() { + return ( + <> +
+ + Effetch store + +
+
+ +
+ + ); +} diff --git a/examples/store-react/src/route-error.tsx b/examples/store-react/src/route-error.tsx new file mode 100644 index 0000000..03f2885 --- /dev/null +++ b/examples/store-react/src/route-error.tsx @@ -0,0 +1,32 @@ +import { + type ErrorComponentProps, + Link, + SearchParamError, + useRouter, +} from "@tanstack/react-router"; + +import { describeError } from "./messages.ts"; + +/** + * A route's error component: what went wrong, and a way to try again. A + * search param its schema rejects, such as `?page=0`, lands here too. + */ +export function RouteError({ error }: ErrorComponentProps) { + const router = useRouter(); + if (error instanceof SearchParamError) { + return ( +
+

This page's address has a search param it can't read.

+ Back to the store +
+ ); + } + return ( +
+

{describeError(error)}

+ +
+ ); +} diff --git a/examples/store-react/src/router.ts b/examples/store-react/src/router.ts new file mode 100644 index 0000000..b3bbb73 --- /dev/null +++ b/examples/store-react/src/router.ts @@ -0,0 +1,37 @@ +import { createRouter, type RouterHistory } from "@tanstack/react-router"; + +import { categoryRoute } from "./category.tsx"; +import { homeRoute } from "./home.tsx"; +import { productRoute } from "./product.tsx"; +import { rootRoute } from "./root.tsx"; +import type { StoreRuntime } from "./store.ts"; + +export const routeTree = rootRoute.addChildren([ + homeRoute, + categoryRoute, + productRoute, +]); + +/** What the tests change, to run the router in Node as a browser runs it. */ +export interface TestOptions { + readonly history?: RouterHistory; + readonly isServer?: boolean; + readonly origin?: string; +} + +/** + * The app's router. Its loaders run their effects with `runtime`: the + * store's in the app, one with a fake backend in the tests. + * + * It doesn't preload on hover (`defaultPreload`): a preloaded loader keeps + * running when the click's navigation is left, so leaving the page + * wouldn't cancel its request. + */ +export const makeRouter = (runtime: StoreRuntime, options?: TestOptions) => + createRouter({ routeTree, context: { runtime }, ...options }); + +declare module "@tanstack/react-router" { + interface Register { + router: ReturnType; + } +} diff --git a/examples/store-react/src/store.ts b/examples/store-react/src/store.ts new file mode 100644 index 0000000..98b12f7 --- /dev/null +++ b/examples/store-react/src/store.ts @@ -0,0 +1,33 @@ +import type * as ManagedRuntime from "effect/ManagedRuntime"; + +import type { CartApi } from "../../store/modules/cart/public.ts"; +import type { ProductApi } from "../../store/modules/products/public.ts"; + +// The store example's modules, used through their `public.ts` files, as +// any screen uses them. This app only adds screens: the modules, the +// client and the runtime are the store example's own. + +export { + buyCheapest, + NothingToBuy, + OutOfStock, +} from "../../store/modules/cart/public.ts"; +export { + ProductApi, + ProductNotFound, +} from "../../store/modules/products/public.ts"; +export type { + Category, + Product, + ProductPage, +} from "../../store/modules/products/public.ts"; +export { runtime } from "../../store/runtime.ts"; + +/** The services the screens' effects use. */ +export type StoreServices = ProductApi | CartApi; + +/** What the routes run effects with: the store's runtime, or a test's. */ +export type StoreRuntime = ManagedRuntime.ManagedRuntime< + StoreServices, + unknown +>; diff --git a/examples/store-react/src/styles.css b/examples/store-react/src/styles.css new file mode 100644 index 0000000..eb6adb6 --- /dev/null +++ b/examples/store-react/src/styles.css @@ -0,0 +1,113 @@ +:root { + --text: #1d1d1f; + --muted: #6e6e73; + --surface: #ffffff; + --line: #e3e3e6; + --accent: #2459d6; + color-scheme: light dark; + font-family: system-ui, sans-serif; + line-height: 1.5; + color: var(--text); + background: var(--surface); +} + +@media (prefers-color-scheme: dark) { + :root { + --text: #f2f2f4; + --muted: #a1a1a6; + --surface: #161618; + --line: #2f2f33; + --accent: #7aa2ff; + } +} + +body { + margin: 0; +} + +header, +main { + max-width: 44rem; + margin: 0 auto; + padding: 1rem; +} + +header { + border-bottom: 1px solid var(--line); +} + +a { + color: var(--accent); +} + +.brand { + font-weight: 600; + text-decoration: none; +} + +h1 { + text-transform: capitalize; +} + +.categories { + display: grid; + grid-template-columns: repeat(auto-fill, minmax(10rem, 1fr)); + gap: 0.5rem; + padding: 0; + list-style: none; +} + +.products { + padding: 0; + list-style: none; +} + +.products li { + display: flex; + justify-content: space-between; + gap: 1rem; + padding: 0.5rem 0; + border-bottom: 1px solid var(--line); +} + +.products span, +.pages span, +.notice { + color: var(--muted); +} + +.pages { + display: flex; + gap: 1rem; + align-items: center; + margin-top: 1rem; +} + +.buy { + display: flex; + flex-wrap: wrap; + gap: 0.75rem; + align-items: center; + padding: 0.75rem; + border: 1px solid var(--line); + border-radius: 0.5rem; +} + +.buy label { + display: flex; + gap: 0.5rem; + align-items: center; +} + +.buy input { + width: 5rem; +} + +.buy p { + flex-basis: 100%; + margin: 0; +} + +.price { + font-size: 1.5rem; +} diff --git a/examples/store-react/src/use-action.ts b/examples/store-react/src/use-action.ts new file mode 100644 index 0000000..3da3e75 --- /dev/null +++ b/examples/store-react/src/use-action.ts @@ -0,0 +1,57 @@ +import type * as Effect from "effect/Effect"; + +import { useCallback, useEffect, useRef, useState } from "react"; + +import type { StoreRuntime, StoreServices } from "./store.ts"; + +/** What a component shows of an action: whether it's running, and its result. */ +export interface ActionState { + readonly pending: boolean; + readonly result: A | undefined; +} + +/** + * Runs an effect from an event handler, such as a form's submit, and keeps + * the state a component shows. Running it again, or unmounting the + * component, interrupts the run in progress, which cancels its requests. + * + * The effect handles its own errors, as its `never` error type says, so + * the component decides what each one shows. + */ +export const useAction = (runtime: StoreRuntime) => { + const [state, setState] = useState>({ + pending: false, + result: undefined, + }); + const running = useRef(undefined); + useEffect(() => () => running.current?.abort(), []); + + const run = useCallback( + (effect: Effect.Effect) => { + running.current?.abort(); + const controller = new AbortController(); + running.current = controller; + setState((current) => ({ ...current, pending: true })); + void runtime.runPromise(effect, { signal: controller.signal }).then( + (result) => { + if (running.current === controller) { + setState({ pending: false, result }); + } + }, + (defect: unknown) => { + // Interrupted by a newer run or by unmounting: nothing to show. + if (controller.signal.aborted) return; + // A defect, as the effect handles its errors: stop waiting, and + // let it reach the console. + if (running.current === controller) { + setState((current) => ({ ...current, pending: false })); + } + throw defect; + }, + ); + }, + [runtime], + ); + + return { ...state, run }; +}; diff --git a/examples/store-react/tsconfig.json b/examples/store-react/tsconfig.json new file mode 100644 index 0000000..9197880 --- /dev/null +++ b/examples/store-react/tsconfig.json @@ -0,0 +1,20 @@ +{ + // The app imports the store example's modules, which import each other + // with `.ts` extensions, and Effetch from `src`, as the tests do. Effect + // comes from the repository's root, so the app and the modules share one + // copy of it, whichever version the root has. + "extends": "../../tsconfig.json", + "compilerOptions": { + "module": "ESNext", + "moduleResolution": "Bundler", + "jsx": "react-jsx", + "allowImportingTsExtensions": true, + "types": ["vite/client", "node"], + "paths": { + "@monarcode/effetch": ["../../src/index.ts"], + "@monarcode/effetch/plugins": ["../../src/plugins/index.ts"], + "@monarcode/effetch/test": ["../../src/test/index.ts"] + } + }, + "include": ["src", "vite.config.ts"] +} diff --git a/examples/store-react/vite.config.ts b/examples/store-react/vite.config.ts new file mode 100644 index 0000000..4acf5dd --- /dev/null +++ b/examples/store-react/vite.config.ts @@ -0,0 +1,22 @@ +import path from "node:path"; + +import react from "@vitejs/plugin-react"; +import { defineConfig } from "vite"; + +const source = (file: string) => + path.resolve(import.meta.dirname, "../../src", file); + +export default defineConfig({ + plugins: [react()], + resolve: { + // Effetch from the repository's `src`, as the tests use it, so the app + // never runs a stale build. + alias: [ + { find: /^@monarcode\/effetch$/, replacement: source("index.ts") }, + { + find: /^@monarcode\/effetch\/plugins$/, + replacement: source("plugins/index.ts"), + }, + ], + }, +}); diff --git a/examples/store/infrastructure/http/store-api-client.ts b/examples/store/infrastructure/http/store-api-client.ts new file mode 100644 index 0000000..2b3aadb --- /dev/null +++ b/examples/store/infrastructure/http/store-api-client.ts @@ -0,0 +1,26 @@ +import * as Config from "effect/Config"; +import * as Schema from "effect/Schema"; + +import { Fetch } from "@monarcode/effetch"; +import { retry, timeout } from "@monarcode/effetch/plugins"; + +// The store's backend: how to reach it, and nothing else. No endpoints and +// no module schemas live here, so this file stays the same size however +// many endpoints the modules define, and it never imports a module. What a +// status means from every endpoint belongs here; what it means from one +// endpoint belongs with that endpoint. + +/** The body of the backend's error responses. */ +export const StoreApiError = Schema.Struct({ message: Schema.String }); + +export class StoreApiClient extends Fetch.Service()( + "infrastructure/http/StoreApiClient", + { + // DummyJSON, a free fake store, unless STORE_API_URL says otherwise. + baseUrl: Config.String("STORE_API_URL").pipe( + Config.withDefault("https://dummyjson.com"), + ), + defaultError: StoreApiError, + plugins: [retry(), timeout({ duration: "10 seconds" })], + }, +) {} diff --git a/examples/store/main.ts b/examples/store/main.ts new file mode 100644 index 0000000..6a1b713 --- /dev/null +++ b/examples/store/main.ts @@ -0,0 +1,56 @@ +import * as Effect from "effect/Effect"; + +import { buyCheapest } from "./modules/cart/public.ts"; +import { ProductApi } from "./modules/products/public.ts"; +import { runtime } from "./runtime.ts"; + +// Code outside the modules, here standing in for a screen. It imports the +// modules only through their `public.ts`, and never sees a route, a schema +// it doesn't need, or the client: +// +// pnpm example store + +/** Buys the cheapest product in `category`, and says what happened. */ +const buy = (category: string, quantity: number) => + buyCheapest(1, category, quantity).pipe( + Effect.map((cart) => { + const [line] = cart.products; + return `Cart ${cart.id}: ${line?.quantity} × ${line?.title}, $${cart.discountedTotal}`; + }), + // A message for each error the screen knows about... + Effect.catchTags({ + NothingToBuy: (error) => + Effect.succeed(`There's nothing in ${error.category}`), + OutOfStock: (error) => + Effect.succeed( + `Only ${error.stock} ${error.product} left, not ${error.wanted}`, + ), + }), + // ...and one for the rest, such as being offline. + Effect.catch((error) => + Effect.succeed(`Something went wrong (${error._tag})`), + ), + ); + +/** A product page, or a message when the product is gone. */ +const productPage = (id: number) => + Effect.gen(function* () { + const products = yield* ProductApi; + const product = yield* products.get({ params: { id } }); + return `${product.title}: $${product.price}, ${product.stock} in stock`; + }).pipe( + Effect.catchTag("ProductNotFound", (error) => + Effect.succeed(error.message), + ), + Effect.catch((error) => + Effect.succeed(`Something went wrong (${error._tag})`), + ), + ); + +console.log(await runtime.runPromise(buy("smartphones", 2))); +console.log(await runtime.runPromise(buy("smartphones", 500))); +console.log(await runtime.runPromise(buy("flying-cars", 1))); +console.log(await runtime.runPromise(productPage(1))); +console.log(await runtime.runPromise(productPage(9999))); + +await runtime.dispose(); diff --git a/examples/store/modules/cart/application/buy-cheapest.ts b/examples/store/modules/cart/application/buy-cheapest.ts new file mode 100644 index 0000000..f93614b --- /dev/null +++ b/examples/store/modules/cart/application/buy-cheapest.ts @@ -0,0 +1,51 @@ +import * as Effect from "effect/Effect"; +import * as Schema from "effect/Schema"; + +import { ProductApi } from "../../products/public.ts"; +import { CartApi } from "../data/cart.api.ts"; + +// A workflow: an operation that isn't one HTTP call. It finds the cheapest +// product in a category, fails with a domain error when there's none or not +// enough of it, then puts it in a new cart. The endpoints stay plain; the +// rules live here. It uses the products module through its `public.ts`. + +/** The category has no products. */ +export class NothingToBuy extends Schema.TaggedError()( + "NothingToBuy", + { category: Schema.String }, +) {} + +/** Fewer are in stock than the quantity asked for. */ +export class OutOfStock extends Schema.TaggedError()("OutOfStock", { + product: Schema.String, + stock: Schema.Finite, + wanted: Schema.Finite, +}) {} + +export const buyCheapest = Effect.fn("buyCheapest")(function* ( + userId: number, + category: string, + quantity: number, +) { + const products = yield* ProductApi; + const carts = yield* CartApi; + + const page = yield* products.inCategory({ + params: { category }, + query: { sortBy: "price", order: "asc", limit: 1 }, + }); + const [cheapest] = page.products; + if (cheapest === undefined) { + return yield* new NothingToBuy({ category }); + } + if (cheapest.stock < quantity) { + return yield* new OutOfStock({ + product: cheapest.title, + stock: cheapest.stock, + wanted: quantity, + }); + } + return yield* carts.create({ + body: { userId, products: [{ id: cheapest.id, quantity }] }, + }); +}); diff --git a/examples/store/modules/cart/cart.layer.ts b/examples/store/modules/cart/cart.layer.ts new file mode 100644 index 0000000..5313809 --- /dev/null +++ b/examples/store/modules/cart/cart.layer.ts @@ -0,0 +1,6 @@ +import * as Layer from "effect/Layer"; + +import { CartApi } from "./data/cart.api.ts"; + +/** Every live layer of the module, for the app's runtime. */ +export const CartModuleLive = Layer.mergeAll(CartApi.layer); diff --git a/examples/store/modules/cart/cart.test.ts b/examples/store/modules/cart/cart.test.ts new file mode 100644 index 0000000..0517431 --- /dev/null +++ b/examples/store/modules/cart/cart.test.ts @@ -0,0 +1,92 @@ +import { describe, expect, it } from "@effect/vitest"; +import * as Effect from "effect/Effect"; +import * as Layer from "effect/Layer"; + +import { FetchTest } from "@monarcode/effetch/test"; + +import { StoreApiClient } from "../../infrastructure/http/store-api-client.ts"; +import { productsInCategory } from "../products/contract/products.ts"; +import { ProductModuleLive } from "../products/products.layer.ts"; +import { CartModuleLive } from "./cart.layer.ts"; +import { createCart } from "./contract/cart.ts"; +import { buyCheapest, NothingToBuy, OutOfStock } from "./public.ts"; + +// The workflow, run as in production: the real modules and the real +// `StoreApiClient`, with its plugins and errors. Only the HttpClient under +// it is fake, answering from the endpoints' own definitions. + +const phone = { + id: 128, + title: "Realme C35", + category: "smartphones", + price: 149.99, + stock: 3, +}; + +const Backend = FetchTest.layer([ + FetchTest.respond(productsInCategory, ({ params }) => + Effect.succeed({ + products: params.category === "smartphones" ? [phone] : [], + total: params.category === "smartphones" ? 1 : 0, + }), + ), + // `body` is decoded with `NewCart`, as the real backend would read it. + FetchTest.respond( + createCart, + ({ body }) => + Effect.succeed({ + id: 1, + products: body.products.map((line) => ({ + ...line, + title: phone.title, + })), + discountedTotal: phone.price * (body.products[0]?.quantity ?? 0), + }), + { status: 201 }, + ), +]); + +const TestLayer = Layer.mergeAll(ProductModuleLive, CartModuleLive).pipe( + Layer.provide(StoreApiClient.layer), + Layer.provideMerge(Backend), +); + +describe("buyCheapest", () => { + it.effect("asks for the cheapest product, and puts it in a cart", () => + Effect.gen(function* () { + const cart = yield* buyCheapest(7, "smartphones", 2); + expect(cart.products).toStrictEqual([ + { id: 128, title: "Realme C35", quantity: 2 }, + ]); + + const [search, created] = yield* FetchTest.requests; + expect(search?.query).toStrictEqual({ + sortBy: "price", + order: "asc", + limit: "1", + }); + expect(created?.body).toStrictEqual({ + userId: 7, + products: [{ id: 128, quantity: 2 }], + }); + }).pipe(Effect.provide(TestLayer)), + ); + + it.effect("fails with OutOfStock, and makes no cart", () => + Effect.gen(function* () { + const error = yield* Effect.flip(buyCheapest(7, "smartphones", 5)); + expect(error).toStrictEqual( + new OutOfStock({ product: "Realme C35", stock: 3, wanted: 5 }), + ); + const routes = (yield* FetchTest.requests).map((sent) => sent.route); + expect(routes).toStrictEqual(["GET /products/category/:category"]); + }).pipe(Effect.provide(TestLayer)), + ); + + it.effect("fails with NothingToBuy for an empty category", () => + Effect.gen(function* () { + const error = yield* Effect.flip(buyCheapest(7, "flying-cars", 1)); + expect(error).toBeInstanceOf(NothingToBuy); + }).pipe(Effect.provide(TestLayer)), + ); +}); diff --git a/examples/store/modules/cart/contract/cart.ts b/examples/store/modules/cart/contract/cart.ts new file mode 100644 index 0000000..0424c61 --- /dev/null +++ b/examples/store/modules/cart/contract/cart.ts @@ -0,0 +1,31 @@ +import * as Schema from "effect/Schema"; + +import { Fetch } from "@monarcode/effetch"; + +// The cart's wire formats and endpoints, laid out as the products module's. + +export const NewCart = Schema.Struct({ + userId: Schema.Finite, + products: Schema.Array( + Schema.Struct({ id: Schema.Finite, quantity: Schema.Finite }), + ), +}); +export type NewCart = typeof NewCart.Type; + +export const Cart = Schema.Struct({ + id: Schema.Finite, + products: Schema.Array( + Schema.Struct({ + id: Schema.Finite, + title: Schema.String, + quantity: Schema.Finite, + }), + ), + discountedTotal: Schema.Finite, +}); +export type Cart = typeof Cart.Type; + +export const createCart = Fetch.endpoint("POST /carts/add", { + input: NewCart, + output: Cart, +}); diff --git a/examples/store/modules/cart/data/cart.api.ts b/examples/store/modules/cart/data/cart.api.ts new file mode 100644 index 0000000..a31cdb0 --- /dev/null +++ b/examples/store/modules/cart/data/cart.api.ts @@ -0,0 +1,12 @@ +import { Fetch } from "@monarcode/effetch"; + +import { StoreApiClient } from "../../../infrastructure/http/store-api-client.ts"; +import { createCart } from "../contract/cart.ts"; + +// The same shape as the products module's `data/`: the endpoints, bound. + +export class CartApi extends Fetch.Endpoints()( + "modules/cart/CartApi", + StoreApiClient, + { create: createCart }, +) {} diff --git a/examples/store/modules/cart/public.ts b/examples/store/modules/cart/public.ts new file mode 100644 index 0000000..b8aec32 --- /dev/null +++ b/examples/store/modules/cart/public.ts @@ -0,0 +1,8 @@ +// What other code may use from the module. +export { + buyCheapest, + NothingToBuy, + OutOfStock, +} from "./application/buy-cheapest.ts"; +export type { Cart } from "./contract/cart.ts"; +export { CartApi } from "./data/cart.api.ts"; diff --git a/examples/store/modules/products/contract/products.ts b/examples/store/modules/products/contract/products.ts new file mode 100644 index 0000000..e104007 --- /dev/null +++ b/examples/store/modules/products/contract/products.ts @@ -0,0 +1,57 @@ +import * as Schema from "effect/Schema"; + +import { Fetch } from "@monarcode/effetch"; + +// The module's wire formats, and its endpoints next to the schemas they +// use. The endpoints have no client, so anything can read their routes and +// schemas, such as a test's fake backend. `data/product.api.ts` binds them +// to the client. + +export const Product = Schema.Struct({ + id: Schema.Finite, + title: Schema.String, + category: Schema.String, + price: Schema.Finite, + stock: Schema.Finite, +}); +export type Product = typeof Product.Type; + +export const Category = Schema.Struct({ + slug: Schema.String, + name: Schema.String, +}); +export type Category = typeof Category.Type; + +export const ProductPage = Schema.Struct({ + products: Schema.Array(Product), + total: Schema.Finite, +}); +export type ProductPage = typeof ProductPage.Type; + +/** A 404 from an endpoint that takes a product's id. */ +export class ProductNotFound extends Schema.TaggedError()( + "ProductNotFound", + { message: Schema.String }, +) {} + +export const listCategories = Fetch.endpoint("GET /products/categories", { + output: Schema.Array(Category), +}); + +export const getProduct = Fetch.endpoint("GET /products/:id", { + output: Product, + statusErrors: { 404: ProductNotFound }, +}); + +export const productsInCategory = Fetch.endpoint( + "GET /products/category/:category", + { + query: Schema.Struct({ + sortBy: Schema.optionalKey(Schema.Literals(["price", "rating"])), + order: Schema.optionalKey(Schema.Literals(["asc", "desc"])), + limit: Schema.optionalKey(Schema.Finite), + skip: Schema.optionalKey(Schema.Finite), + }), + output: ProductPage, + }, +); diff --git a/examples/store/modules/products/data/product.api.ts b/examples/store/modules/products/data/product.api.ts new file mode 100644 index 0000000..93a33ec --- /dev/null +++ b/examples/store/modules/products/data/product.api.ts @@ -0,0 +1,23 @@ +import { Fetch } from "@monarcode/effetch"; + +import { StoreApiClient } from "../../../infrastructure/http/store-api-client.ts"; +import { + getProduct, + listCategories, + productsInCategory, +} from "../contract/products.ts"; + +// The module's data service is its endpoints, bound to the client: one line +// per operation, and every type (params, query, success and errors) +// inferred, so there's no interface to keep in step. `ProductApi.layer` +// binds them once, when it's built. + +export class ProductApi extends Fetch.Endpoints()( + "modules/products/ProductApi", + StoreApiClient, + { + categories: listCategories, + get: getProduct, + inCategory: productsInCategory, + }, +) {} diff --git a/examples/store/modules/products/products.layer.ts b/examples/store/modules/products/products.layer.ts new file mode 100644 index 0000000..00db95e --- /dev/null +++ b/examples/store/modules/products/products.layer.ts @@ -0,0 +1,6 @@ +import * as Layer from "effect/Layer"; + +import { ProductApi } from "./data/product.api.ts"; + +/** Every live layer of the module, for the app's runtime. */ +export const ProductModuleLive = Layer.mergeAll(ProductApi.layer); diff --git a/examples/store/modules/products/public.ts b/examples/store/modules/products/public.ts new file mode 100644 index 0000000..cd6be12 --- /dev/null +++ b/examples/store/modules/products/public.ts @@ -0,0 +1,4 @@ +// What other code may use from the module. +export type { Category, Product, ProductPage } from "./contract/products.ts"; +export { ProductNotFound } from "./contract/products.ts"; +export { ProductApi } from "./data/product.api.ts"; diff --git a/examples/store/runtime.ts b/examples/store/runtime.ts new file mode 100644 index 0000000..3dc0e33 --- /dev/null +++ b/examples/store/runtime.ts @@ -0,0 +1,25 @@ +import * as FetchHttpClient from "effect/http/FetchHttpClient"; +import * as Layer from "effect/Layer"; +import * as ManagedRuntime from "effect/ManagedRuntime"; + +import { StoreApiClient } from "./infrastructure/http/store-api-client.ts"; +import { CartModuleLive } from "./modules/cart/cart.layer.ts"; +import { ProductModuleLive } from "./modules/products/products.layer.ts"; + +// The composition root: every module's layer, on top of the client they +// use, on top of one HttpClient. A new module is one line here, and a new +// backend is one client file and one line. + +const Modules = Layer.mergeAll(ProductModuleLive, CartModuleLive); + +export const AppLayer = Modules.pipe( + Layer.provide(StoreApiClient.layer), + Layer.provide(FetchHttpClient.layer), +); + +/** + * What the UI runs effects with: `runtime.runPromise(effect)` from a React + * or React Native component, an event handler or a route loader. It builds + * the layers once, the first time it runs something. + */ +export const runtime = ManagedRuntime.make(AppLayer); diff --git a/examples/streams.ts b/examples/streams.ts deleted file mode 100644 index f7de18e..0000000 --- a/examples/streams.ts +++ /dev/null @@ -1,129 +0,0 @@ -import * as Effect from "effect/Effect"; -import * as FetchHttpClient from "effect/http/FetchHttpClient"; -import * as Layer from "effect/Layer"; -import * as Option from "effect/Option"; -import * as Schema from "effect/Schema"; -import * as Stream from "effect/Stream"; - -import { Fetch } from "@monarcode/effetch"; -import { retry, timeout } from "@monarcode/effetch/plugins"; - -// Streams and pages: a job's progress as Server-Sent Events, an export as -// newline-delimited JSON, a language model's answer that ends with a -// sentinel, and a list paged by a cursor in a `Link` header. - -const ApiError = Schema.Struct({ code: Schema.String }); - -export class Api extends Fetch.Service()("examples/streams/Api", { - baseUrl: "https://api.example.com", - defaultError: ApiError, - // `retry` and `timeout` apply to getting each response, not to reading - // a stream's body. - plugins: [retry(), timeout({ duration: "10 seconds" })], -}) {} - -export const ApiLive = Api.layer.pipe(Layer.provide(FetchHttpClient.layer)); - -// --- Schemas and endpoints --- - -export const JobProgress = Schema.Struct({ - percent: Schema.Finite, - step: Schema.String, -}); - -export const User = Schema.Struct({ id: Schema.Finite, email: Schema.String }); - -/** A job's progress, one event per step, until `percent` reaches 100. */ -export const jobEvents = Fetch.endpoint("GET /jobs/:id/events", { - output: JobProgress, - stream: "sse", -}); - -/** Every user, one per line. */ -export const exportUsers = Fetch.endpoint("GET /exports/users", { - output: User, - stream: "ndjson", -}); - -/** A page of users. The next page's link is in the `Link` header. */ -export const listUsers = Fetch.endpoint("GET /users", { - output: Schema.Array(User), - responseMode: "decoded-and-response", -}); - -export class StreamsApi extends Fetch.Endpoints()( - "examples/streams/StreamsApi", - Api, - { jobEvents, exportUsers, listUsers }, -) {} - -// --- Using them --- - -/** Logs a job's progress, and ends when it's done. */ -export const followJob = (id: string) => - Effect.gen(function* () { - const api = yield* StreamsApi; - return yield* api.jobEvents({ params: { id } }).pipe( - Stream.tap((event) => - Effect.log(`${event.data.step}: ${event.data.percent}%`), - ), - Stream.takeUntil((event) => event.data.percent >= 100), - Stream.runLast, - ); - }); - -/** Counts the users of an export, as they arrive. */ -export const countUsers = Effect.gen(function* () { - const api = yield* StreamsApi; - return yield* Stream.runCount(api.exportUsers()); -}); - -const Delta = Schema.fromJsonString(Schema.Struct({ text: Schema.String })); - -/** - * A language model's answer, as it's written. The server ends with - * `data: [DONE]`, which isn't JSON, so the events are read as text, and - * decoded up to the sentinel. - */ -export const complete = (prompt: string) => - Effect.gen(function* () { - const api = yield* Api; - return yield* api - .sse("/completions", { - method: "POST", - input: Schema.Struct({ prompt: Schema.String }), - body: { prompt }, - }) - .pipe( - Stream.takeWhile((event) => event.data !== "[DONE]"), - Stream.mapEffect((event) => - Schema.decodeUnknownEffect(Delta)(event.data), - ), - Stream.map((delta) => delta.text), - Stream.mkString, - ); - }); - -/** - * The `cursor` of a `Link` header's `rel="next"` URL, decoded: it's - * percent-encoded in the URL, and `query` encodes it again. - */ -const nextCursor = (link: string | undefined): Option.Option => - Option.fromNullishOr( - /<[^>]*[?&]cursor=([^&>]+)[^>]*>;\s*rel="next"/.exec(link ?? "")?.[1], - ).pipe(Option.flatMap(Option.liftThrowable(decodeURIComponent))); - -/** Every user, page by page, following the `Link` header. */ -export const allUsers = Effect.gen(function* () { - const api = yield* StreamsApi; - return yield* Fetch.paginate(api.listUsers, { - start: Option.none(), - request: (cursor) => - Option.match(cursor, { - onNone: () => ({}), - onSome: (value) => ({ query: { cursor: value } }), - }), - next: (_users, _cursor, response) => - Option.map(nextCursor(response.headers.link), Option.some), - }).pipe(Stream.flattenIterable, Stream.runCollect); -}); diff --git a/examples/testing.ts b/examples/testing.ts deleted file mode 100644 index da3a34a..0000000 --- a/examples/testing.ts +++ /dev/null @@ -1,121 +0,0 @@ -import * as ConfigProvider from "effect/ConfigProvider"; -import * as Effect from "effect/Effect"; -import * as Layer from "effect/Layer"; - -import { FetchTest } from "@monarcode/effetch/test"; - -import { AppApiClient } from "./app/infrastructure/http/app-api-client.js"; -import { SessionExpired } from "./app/infrastructure/http/plugins.js"; -import { - createTodo, - getTodo, - listTodos, - removeTodo, - TodoNotFound, -} from "./app/modules/todos/contract/todos.js"; -import { TodoApi } from "./app/modules/todos/public.js"; - -// Tests for the todos module of `app/`, against a fake backend made from its -// endpoints. The module runs as in production: the real `AppApiClient`, with -// its plugins, `defaultError` and `statusErrors`. Only the `HttpClient` under -// it is fake. -// -// Each test is an Effect that fails when a check doesn't hold, so any test -// runner can run it: `it.effect` with `@effect/vitest`, or -// `Effect.runPromise` in Jest, Bun or Deno. - -const due = new Date(Date.UTC(2026, 0, 31)); - -/** The fake backend: one handler per endpoint the tests call. */ -const Backend = FetchTest.layer([ - // `params.id` is a string, as it is in a URL. - FetchTest.respond(getTodo, ({ params }) => - Effect.succeed( - params.id === "1" - ? { id: 1, title: "Write docs", done: false, due } - : // Decoded by the client into `TodoNotFound`, by `statusErrors`. - FetchTest.reply(404, { message: `No todo ${params.id}` }), - ), - ), - // `body` is decoded with `NewTodo`, so `due` is a `Date` here, and the - // result is encoded with `Todo`, so it goes back as a string. - FetchTest.respond( - createTodo, - ({ body }) => Effect.succeed({ id: 2, done: false, ...body }), - { status: 201 }, - ), - FetchTest.respond(removeTodo, () => Effect.void), - // `fail` encodes the body with the client's `statusErrors` schema for - // 401, once the endpoint is bound: here the definition has none, so it's - // sent as it is, and the client decodes it into `SessionExpired`. - FetchTest.fail(listTodos, 401, { message: "Session expired" }), -]); - -/** - * The module's layer on the fake backend. `provideMerge` keeps the - * backend's `Recorder` reachable from the tests, for `FetchTest.requests`. - */ -const TestLayer = TodoApi.layer.pipe( - Layer.provide(AppApiClient.layer), - Layer.provideMerge(Backend), - Layer.provide( - ConfigProvider.layer( - ConfigProvider.fromUnknown({ APP_API_URL: "https://api.test/v1" }), - ), - ), -); - -/** Fails the test with `message` unless `ok`. */ -const check = (ok: boolean, message: string) => - ok ? Effect.void : Effect.die(new Error(message)); - -export const getsATodo = Effect.gen(function* () { - const todos = yield* TodoApi; - const todo = yield* todos.get({ params: { id: 1 } }); - yield* check(todo.due instanceof Date, "due should be decoded to a Date"); - yield* check(todo.title === "Write docs", `unexpected title ${todo.title}`); -}).pipe(Effect.provide(TestLayer)); - -export const failsWithTodoNotFound = Effect.gen(function* () { - const todos = yield* TodoApi; - const error = yield* Effect.flip(todos.get({ params: { id: 9 } })); - yield* check( - error instanceof TodoNotFound && error.message === "No todo 9", - `expected TodoNotFound, got ${String(error)}`, - ); -}).pipe(Effect.provide(TestLayer)); - -export const createsATodo = Effect.gen(function* () { - const todos = yield* TodoApi; - const todo = yield* todos.create({ body: { title: "Ship rc.3", due } }); - yield* check(todo.id === 2, `unexpected id ${todo.id}`); - // What was sent, as the backend received it. - const [sent] = yield* FetchTest.requests; - yield* check( - sent?.url === "https://api.test/v1/todos", - `unexpected URL ${sent?.url}`, - ); - yield* check( - JSON.stringify(sent?.body) === - JSON.stringify({ title: "Ship rc.3", due: due.toISOString() }), - `unexpected body ${JSON.stringify(sent?.body)}`, - ); -}).pipe(Effect.provide(TestLayer)); - -export const removesATodo = Effect.gen(function* () { - const todos = yield* TodoApi; - const response = yield* todos.remove({ params: { id: 1 } }); - yield* check( - response.status === 204, - `unexpected status ${response.status}`, - ); -}).pipe(Effect.provide(TestLayer)); - -export const failsWithSessionExpired = Effect.gen(function* () { - const todos = yield* TodoApi; - const error = yield* Effect.flip(todos.list()); - yield* check( - error instanceof SessionExpired, - `expected SessionExpired, got ${String(error)}`, - ); -}).pipe(Effect.provide(TestLayer)); diff --git a/examples/tsconfig.json b/examples/tsconfig.json new file mode 100644 index 0000000..5787a83 --- /dev/null +++ b/examples/tsconfig.json @@ -0,0 +1,10 @@ +{ + // The examples import each other with `.ts` extensions, so Node.js runs + // them as they are, with no build step. Their `main.ts` files read + // `process.argv`. + "extends": "../tsconfig.json", + "compilerOptions": { "allowImportingTsExtensions": true, "types": ["node"] }, + "include": ["."], + // A package of its own, with its own tsconfig.json. + "exclude": ["store-react"] +} diff --git a/examples/upload/httpbin.ts b/examples/upload/httpbin.ts new file mode 100644 index 0000000..e513708 --- /dev/null +++ b/examples/upload/httpbin.ts @@ -0,0 +1,66 @@ +import * as Effect from "effect/Effect"; +import * as Option from "effect/Option"; +import * as Schema from "effect/Schema"; + +import { Fetch } from "@monarcode/effetch"; +import { retry } from "@monarcode/effetch/plugins"; + +// Uploading a file with two form fields to httpbin.org, which answers with +// what it received. The upload is a plain `post` call, without an endpoint. + +/** A file under 1 MB. A check on `Fetch.UploadFile` runs on a `Blob`. */ +export const SmallFile = Fetch.UploadFile.check( + Schema.makeFilter( + (file) => !(file instanceof Blob) || file.size < 1_000_000, + { expected: "a file under 1 MB" }, + ), +); + +/** The form: each field becomes a part, and a list one part per item. */ +export const Note = Fetch.multipart( + Schema.Struct({ + title: Schema.String, + tags: Schema.Array(Schema.String), + file: SmallFile, + }), +); + +/** What httpbin echoes: the form's text fields, and each file's contents. */ +export const Received = Schema.Struct({ + form: Schema.Record( + Schema.String, + Schema.Union([Schema.String, Schema.Array(Schema.String)]), + ), + files: Schema.Record(Schema.String, Schema.String), + headers: Schema.Record(Schema.String, Schema.String), +}); + +/** The file is too large to send. */ +export class FileTooLarge extends Schema.TaggedError()( + "FileTooLarge", + { name: Schema.String, size: Schema.Finite }, +) {} + +export class Httpbin extends Fetch.Service()("Httpbin", { + baseUrl: "https://httpbin.org", + // httpbin only echoes, so sending a POST again is safe. Most POSTs aren't + // retried, which is why `retry` leaves them out by default. + plugins: [retry({ methods: ["POST"] })], +}) {} + +/** + * Uploads `file` with a title and tags. A file that fails `SmallFile` in + * the call would be a bug, and make the call die, so it's checked first, + * and fails with `FileTooLarge`. + */ +export const uploadNote = Effect.fn("uploadNote")(function* (file: File) { + if (Option.isNone(Schema.decodeUnknownOption(SmallFile)(file))) { + return yield* new FileTooLarge({ name: file.name, size: file.size }); + } + const httpbin = yield* Httpbin; + return yield* httpbin.post("/post", { + input: Note, + body: { title: "Meeting notes", tags: ["work", "draft"], file }, + output: Received, + }); +}); diff --git a/examples/upload/main.ts b/examples/upload/main.ts new file mode 100644 index 0000000..73512a9 --- /dev/null +++ b/examples/upload/main.ts @@ -0,0 +1,47 @@ +import * as Console from "effect/Console"; +import * as Effect from "effect/Effect"; +import * as FetchHttpClient from "effect/http/FetchHttpClient"; +import * as Layer from "effect/Layer"; + +import { Httpbin, uploadNote } from "./httpbin.ts"; + +// Uploads a small file, then a large one, to httpbin.org: +// +// pnpm example upload + +// In a browser, a `File` comes from an . In React Native, +// pass a `Fetch.NativeFile`: `{ uri, name, type }`. +const notes = new File(["# Notes\n\n- Ship 0.1.0\n"], "notes.md", { + type: "text/markdown", +}); +const video = new File([new Uint8Array(2_500_000)], "demo.mp4", { + type: "video/mp4", +}); + +const upload = (file: File) => + uploadNote(file).pipe( + Effect.flatMap((received) => + Console.log( + [ + `Sent ${file.name}. httpbin received:`, + ` content-type: ${received.headers["Content-Type"]}`, + ` fields: ${JSON.stringify(received.form)}`, + ` file: ${JSON.stringify(received.files.file)}`, + ].join("\n"), + ), + ), + Effect.catchTag("FileTooLarge", (error) => + Console.log( + `${error.name} is ${(error.size / 1_000_000).toFixed(1)} MB. The limit is 1 MB.`, + ), + ), + ); + +const program = Effect.gen(function* () { + yield* upload(notes); + yield* upload(video); +}); + +const Live = Httpbin.layer.pipe(Layer.provide(FetchHttpClient.layer)); + +Effect.runPromise(program.pipe(Effect.provide(Live))); diff --git a/examples/upload/upload.test.ts b/examples/upload/upload.test.ts new file mode 100644 index 0000000..31fdb5a --- /dev/null +++ b/examples/upload/upload.test.ts @@ -0,0 +1,63 @@ +import { describe, expect, it } from "@effect/vitest"; +import * as Effect from "effect/Effect"; +import * as Layer from "effect/Layer"; + +import { Fetch } from "@monarcode/effetch"; +import { FetchTest } from "@monarcode/effetch/test"; + +import { + FileTooLarge, + Httpbin, + Note, + Received, + uploadNote, +} from "./httpbin.ts"; + +// The upload is a plain `post` call, so the test defines the endpoint it +// serves, from the same schemas. +const echo = Fetch.endpoint("POST /post", { input: Note, output: Received }); + +const Backend = FetchTest.layer([ + // `body` is the form, read back with `Note`: the file is a `File` again. + FetchTest.respond(echo, ({ body }) => + Effect.gen(function* () { + const text = yield* Effect.promise(() => + body.file instanceof Blob ? body.file.text() : Promise.resolve(""), + ); + return { + form: { title: body.title, tags: [...body.tags] }, + files: { file: text }, + headers: { "Content-Type": "multipart/form-data" }, + }; + }), + ), +]); + +const TestLayer = Httpbin.layer.pipe(Layer.provideMerge(Backend)); + +describe("uploadNote", () => { + it.effect("sends the file and the fields as a form", () => + Effect.gen(function* () { + const file = new File(["hello"], "notes.md", { + type: "text/markdown", + }); + const received = yield* uploadNote(file); + expect(received.form).toStrictEqual({ + title: "Meeting notes", + tags: ["work", "draft"], + }); + expect(received.files.file).toBe("hello"); + }).pipe(Effect.provide(TestLayer)), + ); + + it.effect("fails with FileTooLarge, and sends nothing", () => + Effect.gen(function* () { + const file = new File([new Uint8Array(1_000_000)], "big.bin"); + const error = yield* Effect.flip(uploadNote(file)); + expect(error).toStrictEqual( + new FileTooLarge({ name: "big.bin", size: 1_000_000 }), + ); + expect(yield* FetchTest.requests).toStrictEqual([]); + }).pipe(Effect.provide(TestLayer)), + ); +}); diff --git a/package.json b/package.json index f92c711..2c3b657 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "@monarcode/effetch", - "version": "0.1.0-rc.5", + "version": "0.1.0", "description": "Typed, schema-driven HTTP calls on Effect v4's HttpClient: path params, object queries, decoded responses and plugins", "keywords": [ "effect", @@ -66,21 +66,24 @@ "prepare": "husky", "lint": "oxlint .", "lint:fix": "oxlint --fix .", - "lint:effect": "effect-language-service diagnostics --project tsconfig.json --format text", + "lint:effect": "effect-language-service diagnostics --project tsconfig.json --format text && effect-language-service diagnostics --project examples/tsconfig.json --format text && effect-language-service diagnostics --project examples/store-react/tsconfig.json --format text", "format": "oxfmt --write .", "format:check": "oxfmt --check .", "build": "tsdown", "build:site": "pnpm run build && pnpm --dir site run build", + "build:examples": "pnpm --dir examples/store-react run build", "dev": "tsdown --watch", - "typecheck": "tsc --noEmit", + "typecheck": "tsc --noEmit && tsc --noEmit -p examples && tsc --noEmit -p examples/store-react", "check:docs": "node scripts/check-docs.mjs", "docs:reference": "node scripts/reference-docs.mjs", "docs:snapshot": "node scripts/snapshot-docs.mjs", "test": "vitest run", "test:watch": "vitest", + "example": "node scripts/example.mjs", "check:package": "publint --strict && attw --pack . --profile esm-only", "smoke": "bash scripts/smoke.sh", - "check": "pnpm run lint && pnpm run format:check && pnpm run typecheck && pnpm run check:docs && pnpm run lint:effect && pnpm test && pnpm run build && pnpm run check:package && pnpm run smoke", + "compat": "bash scripts/compat.sh", + "check": "pnpm run lint && pnpm run format:check && pnpm run typecheck && pnpm run check:docs && pnpm run lint:effect && pnpm test && pnpm run build && pnpm run build:examples && pnpm run check:package && pnpm run smoke", "prepublishOnly": "pnpm run check" }, "devDependencies": { diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index c85db7c..3325605 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -48,6 +48,31 @@ importers: specifier: 5.0.3 version: 5.0.3(@types/node@26.6.5)(vite@8.3.7(@types/node@26.6.5)(esbuild@0.28.2)(jiti@2.7.0)(yaml@2.9.1)) + examples/store-react: + dependencies: + '@tanstack/react-router': + specifier: 1.170.46 + version: 1.170.46(@types/react@19.3.0)(react-dom@19.3.1(react@19.3.1))(react@19.3.1) + react: + specifier: 19.3.1 + version: 19.3.1 + react-dom: + specifier: 19.3.1 + version: 19.3.1(react@19.3.1) + devDependencies: + '@types/react': + specifier: 19.3.0 + version: 19.3.0 + '@types/react-dom': + specifier: 19.3.0 + version: 19.3.0(@types/react@19.3.0) + '@vitejs/plugin-react': + specifier: 6.3.0 + version: 6.3.0(vite@8.3.7(@types/node@26.6.5)(esbuild@0.28.2)(jiti@2.7.0)(yaml@2.9.1)) + vite: + specifier: 8.3.7 + version: 8.3.7(@types/node@26.6.5)(esbuild@0.28.2)(jiti@2.7.0)(yaml@2.9.1) + site: dependencies: '@fontsource-variable/recursive': diff --git a/pnpm-workspace.yaml b/pnpm-workspace.yaml index 11e9edf..f7ab13d 100644 --- a/pnpm-workspace.yaml +++ b/pnpm-workspace.yaml @@ -1,2 +1,3 @@ packages: - site + - examples/store-react diff --git a/scripts/compat.sh b/scripts/compat.sh new file mode 100644 index 0000000..7baa610 --- /dev/null +++ b/scripts/compat.sh @@ -0,0 +1,104 @@ +#!/usr/bin/env bash +# Checks the packed package against a TypeScript version or a runtime that +# the smoke test doesn't use. It reuses the consumer program and tsconfigs +# that `pnpm run smoke` writes to `.smoke/consumer`, so run that first. +# +# bash scripts/compat.sh typescript 5.7 typecheck under NodeNext and Bundler +# bash scripts/compat.sh runtime node run the consumer with `node` +# bash scripts/compat.sh runtime bun … with `bun` +# bash scripts/compat.sh runtime deno … with `deno` +# +# A runtime runs the consumer compiled to JavaScript, so Node.js versions +# without type stripping can run it too. The runtime must be on PATH. +set -euo pipefail + +root="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)" +mode="${1:-}" +target="${2:-}" +smoke="$root/.smoke" +source="$smoke/consumer" + +if [ -z "$mode" ] || [ -z "$target" ]; then + echo "Usage: bash scripts/compat.sh typescript | runtime " >&2 + exit 2 +fi +tarballs=("$smoke"/monarcode-effetch-*.tgz) +if [ ! -f "$source/consumer.ts" ] || [ "${#tarballs[@]}" -ne 1 ] || [ ! -f "${tarballs[0]}" ]; then + echo "✗ No smoke consumer in $source: run \`pnpm run smoke\` first" >&2 + exit 1 +fi +tarball="${tarballs[0]}" + +cd "$root" +# The tarball must be packed from the current source. +newer="$(find src package.json -newer "$tarball" -print -quit)" +if [ -n "$newer" ]; then + echo "✗ $newer changed after the smoke test packed $tarball: run \`pnpm run smoke\` again" >&2 + exit 1 +fi +effect_version="$(node -p 'require("./package.json").devDependencies.effect')" +typescript_version="$(node -p 'require("./package.json").devDependencies.typescript')" + +# Outside the repository: Bun applies the nearest tsconfig.json's `paths`, +# and the repository's tsconfig.json points `@monarcode/effetch` at `src`. +dir="$(mktemp -d "${TMPDIR:-/tmp}/effetch-compat.XXXXXX")" +trap 'rm -rf "$dir"' EXIT +cp "$source/consumer.ts" "$source/tsconfig.nodenext.json" "$source/tsconfig.bundler.json" "$dir/" +cd "$dir" +echo '{ "name": "effetch-compat-consumer", "private": true, "type": "module" }' >package.json + +case "$mode" in +typescript) + echo "› Installing the tarball (effect@$effect_version, typescript@$target)" + npm install --loglevel=error --no-audit --no-fund \ + "$tarball" "effect@$effect_version" "typescript@$target" >/dev/null + echo "› Typechecking with TypeScript $(./node_modules/.bin/tsc -v | sed 's/^Version //')" + ./node_modules/.bin/tsc -p tsconfig.nodenext.json + ./node_modules/.bin/tsc -p tsconfig.bundler.json + ;; +runtime) + case "$target" in + node | bun | deno) ;; + *) + echo "✗ Unknown runtime: $target (node, bun or deno)" >&2 + exit 2 + ;; + esac + echo "› Installing the tarball (effect@$effect_version)" + npm install --loglevel=error --no-audit --no-fund \ + "$tarball" "effect@$effect_version" "typescript@$typescript_version" >/dev/null + # Plain JavaScript, so the runtime's own TypeScript support isn't tested. + cat >tsconfig.emit.json <<'JSON' +{ + "extends": "./tsconfig.nodenext.json", + "compilerOptions": { + "noEmit": false, + "allowImportingTsExtensions": false, + "outDir": "out" + } +} +JSON + ./node_modules/.bin/tsc -p tsconfig.emit.json + case "$target" in + node) + echo "› Running the consumer with Node.js $(node --version)" + node out/consumer.js + ;; + bun) + echo "› Running the consumer with Bun $(bun --version)" + bun out/consumer.js + ;; + deno) + echo "› Running the consumer with $(deno --version | head -1)" + # Only reads: the package and its dependencies from node_modules. + deno run --allow-read out/consumer.js + ;; + esac + ;; +*) + echo "✗ Unknown mode: $mode (typescript or runtime)" >&2 + exit 2 + ;; +esac + +echo "✓ Compatibility check passed: $mode $target" diff --git a/scripts/editor-check.mjs b/scripts/editor-check.mjs index a307cc1..048b5b1 100644 --- a/scripts/editor-check.mjs +++ b/scripts/editor-check.mjs @@ -122,6 +122,7 @@ export const /*pages*/pages = Fetch./*paginate*/paginate(typed.bind(listTodos), request: () => ({}), next: (todos, page) => (todos.length === 0 ? Option.none() : Option.some(page + 1)), }); +export const /*errorCodec*/errorCodec = Fetch.errorCodec(getTodo); export const namespace = /*fetchTestNamespace*/FetchTest; export const fetchNamespace = /*fetchNamespace*/Fetch; export const members = Fetch./*fetchMembers*/; @@ -477,6 +478,24 @@ for (const [marker, errors, services] of [ ); } +// Fetch.errorCodec's result hovers with the call's errors, not the +// alias that computes them. +const errorCodecHover = ts + .displayPartsToString( + service.getQuickInfoAtPosition(probe, at("errorCodec"))?.displayParts, + ) + .replace(/\s+/g, " "); +const errorCodecArgs = /: (Fetch\.)?ErrorCodec<(.*)>$/.exec(errorCodecHover); +const errorCodecParts = + errorCodecArgs === null ? [] : splitTopLevel(errorCodecArgs[2], ","); +expect( + errorCodecParts.length === 3 && + members(errorCodecParts[0]).join(" | ") === callErrors.join(" | ") && + errorCodecParts[1] === "never" && + errorCodecParts[2] === "never", + `Hover on Fetch.errorCodec's result doesn't show ErrorCodec<${callErrors.join(" | ")}, never, never>: ${errorCodecHover}`, +); + // A Fetch.Endpoints service's endpoints hover as Endpoint types. const todosGetHover = ts .displayPartsToString( diff --git a/scripts/example.mjs b/scripts/example.mjs new file mode 100644 index 0000000..c835eba --- /dev/null +++ b/scripts/example.mjs @@ -0,0 +1,100 @@ +// Runs one of the examples: `pnpm example [args...]`. +// +// An example with a `main.ts` is a program. It imports `@monarcode/effetch`, +// which Node resolves to `dist` through the package's `exports`, so this +// builds `dist` first when `src` is newer. Node runs the example's `.ts` +// files as they are, which needs Node.js 22.18 or later. +// +// An example with a `package.json`, such as `store-react`, is an app: this +// starts its dev server, which reads Effetch from `src`. + +import { spawnSync } from "node:child_process"; +import { existsSync, readdirSync, statSync } from "node:fs"; +import path from "node:path"; +import { fileURLToPath } from "node:url"; + +const root = path.resolve(path.dirname(fileURLToPath(import.meta.url)), ".."); +const examples = path.join(root, "examples"); + +/** Whether the example is an app with a dev server, rather than a program. */ +const isApp = (name) => existsSync(path.join(examples, name, "package.json")); + +const names = readdirSync(examples, { withFileTypes: true }) + .filter( + (entry) => + entry.isDirectory() && + (isApp(entry.name) || + existsSync(path.join(examples, entry.name, "main.ts"))), + ) + .map((entry) => entry.name) + .sort(); + +const [name, ...args] = process.argv.slice(2); + +if (name === undefined || !names.includes(name)) { + console.error( + `${name === undefined ? "Name an example" : `No example "${name}"`}: pnpm example [args...]\n\nExamples: ${names.join(", ")}`, + ); + process.exit(1); +} + +if (isApp(name)) { + // From the app's folder, so a space in the path doesn't split the + // command where Windows needs a shell. + const dev = spawnSync("pnpm", ["run", "dev", ...args], { + cwd: path.join(examples, name), + stdio: "inherit", + shell: process.platform === "win32", + }); + if (dev.error) { + console.error(`Couldn't run pnpm to start the app: ${dev.error.message}`); + process.exit(1); + } + process.exit(dev.status ?? 1); +} + +if (!process.features.typescript) { + console.error( + `Node.js ${process.versions.node} can't run TypeScript files. Use Node.js 22.18 or later.`, + ); + process.exit(1); +} + +/** The newest modification time of the files under `dir`, in ms. */ +const newest = (dir) => + Math.max( + ...readdirSync(dir, { withFileTypes: true, recursive: true }) + .filter((entry) => entry.isFile()) + .map( + (entry) => + statSync(path.join(entry.parentPath, entry.name)).mtimeMs, + ), + ); + +const built = path.join(root, "dist", "index.js"); +if ( + !existsSync(built) || + statSync(built).mtimeMs < newest(path.join(root, "src")) +) { + console.error("› Building the package first"); + const build = spawnSync("pnpm", ["run", "--silent", "build"], { + cwd: root, + stdio: ["ignore", "ignore", "inherit"], + // pnpm is a `.cmd` shim on Windows, which needs a shell. + shell: process.platform === "win32", + }); + if (build.error) { + console.error( + `Couldn't run pnpm to build the package: ${build.error.message}`, + ); + process.exit(1); + } + if (build.status !== 0) process.exit(build.status ?? 1); +} + +const run = spawnSync( + process.execPath, + [path.join(examples, name, "main.ts"), ...args], + { cwd: root, stdio: "inherit" }, +); +process.exit(run.status ?? 1); diff --git a/scripts/reference-docs.mjs b/scripts/reference-docs.mjs index d368058..b835195 100644 --- a/scripts/reference-docs.mjs +++ b/scripts/reference-docs.mjs @@ -59,6 +59,7 @@ const PAGES = [ "src/Input.ts": "Uploads", "src/Errors.ts": "Errors", "src/Status.ts": "Errors", + "src/ErrorCodec.ts": "Errors", "src/Plugin.ts": "Plugins", "src/Endpoint.ts": "Endpoint definitions", "src/Endpoints.ts": "Endpoint definitions", diff --git a/scripts/smoke.sh b/scripts/smoke.sh index f3cf55f..31bcbf7 100755 --- a/scripts/smoke.sh +++ b/scripts/smoke.sh @@ -494,6 +494,33 @@ if ( throw new Error(`Unexpected stream result: ${JSON.stringify(streamed)}`); } +// Errors sent as JSON and decoded back: by their own classes, and by +// Fetch.errorCodec with an endpoint's schemas. +const sentError = new Fetch.HttpError({ + method: "GET", + url: "https://api.test/todos/9", + status: 500, + headers: Headers.fromInput({ "set-cookie": "session=secret" }), + text: '{"code":"down"}', + body: { code: "down" }, +}); +const errorJson = Schema.toCodecJson(Fetch.HttpError); +const classWire = JSON.stringify(Schema.encodeUnknownSync(errorJson)(sentError)); +const fromClass = Schema.decodeUnknownSync(errorJson)(JSON.parse(classWire)); +const missingErrors = Schema.toCodecJson(Fetch.errorCodec(getMissing)); +const endpointWire = JSON.stringify( + Schema.encodeUnknownSync(missingErrors)(new TodoNotFound({ message: "No todo 9" })), +); +const fromEndpoint = Schema.decodeUnknownSync(missingErrors)(JSON.parse(endpointWire)); +if ( + classWire.includes("secret") || + !(fromClass instanceof Fetch.HttpError) || + JSON.stringify(fromClass.body) !== '{"code":"down"}' || + !(fromEndpoint instanceof TodoNotFound) +) { + throw new Error(`Unexpected errors over JSON: ${classWire} ${endpointWire}`); +} + console.log("smoke: ok"); TS diff --git a/site/PRODUCT.md b/site/PRODUCT.md index 46e6460..0e5fe59 100644 --- a/site/PRODUCT.md +++ b/site/PRODUCT.md @@ -100,9 +100,13 @@ the API's error body is decoded onto `HttpError`, and the client's plugins compiles against the package (`scripts/check-docs.mjs`); 955 tests and 246 checked examples at the time of writing. - Runtime support, as above. -- Release status: `0.1.0` release candidate, API settled; the changelog - lists anything that needs a change in your code. -- Runnable programs in `examples/`. +- Release status: `0.1.0`. An update within 0.1.x doesn't break code + written for 0.1.0, and breaking changes wait for 0.2.0. The exceptions + follow Effect's unstable modules (its HTTP modules and `encoding/Sse`); + the Compatibility page's Versioning section has them, with the decided + `Retry-After` default for 0.2.0. +- Runnable programs in `examples/`, against free public APIs, each with + offline tests. Absent, and not to be invented: users, adopters or company logos, testimonials, download or adoption numbers, benchmarks, and claims of diff --git a/site/content/docs/(latest)/errors/across-the-wire.mdx b/site/content/docs/(latest)/errors/across-the-wire.mdx new file mode 100644 index 0000000..fe5685a --- /dev/null +++ b/site/content/docs/(latest)/errors/across-the-wire.mdx @@ -0,0 +1,197 @@ +--- +title: Send errors across the wire +description: Send a call's errors from the server to the browser, an RPC client or a worker, and get the same typed errors back. +--- + +When your server makes the call and something else shows the result, the +failure has to travel too. An Effect RPC, a server-rendered page and a +worker only carry data, so each error is encoded to JSON on one side and +decoded on the other. `Fetch.errorCodec` builds the codec that does that: +a schema for every error a call can fail with, whose JSON encoding the +other side decodes, so it catches the same errors, with the same types, as +the server did. + +Before you send one, decide whether you should. An `HttpError` carries the +URL your server called and the backend's response text. Often the browser +needs less: catch the error on the server, and send an error of your own. + +## Send a call's errors over an RPC + +Give `Fetch.errorCodec` the endpoint the call uses, and use what it returns +as the RPC's `error`. The following app shares one RPC between the server, +which calls the backend, and the browser, which catches the failures: + +```ts +import * as Effect from "effect/Effect"; +import * as Rpc from "effect/rpc/Rpc"; +import * as RpcClient from "effect/rpc/RpcClient"; +import * as RpcGroup from "effect/rpc/RpcGroup"; +import * as Schema from "effect/Schema"; + +import { Fetch } from "@monarcode/effetch"; +import { TimeoutError, timeout } from "@monarcode/effetch/plugins"; + +class ApiProblem extends Schema.Class("ApiProblem")({ + code: Schema.String, +}) {} + +class TodoNotFound extends Schema.TaggedError()("TodoNotFound", { + id: Schema.Finite, +}) {} + +const Todo = Schema.Struct({ id: Schema.Finite, title: Schema.String }); + +export class Api extends Fetch.Service()("Api", { + baseUrl: "https://api.example.com", + defaultError: ApiProblem, + statusErrors: { 404: TodoNotFound }, + plugins: [timeout({ duration: "5 seconds" })], +}) {} + +export const getTodo = Fetch.endpoint("GET /todos/:id", { output: Todo }); + +// Shared: what the RPC takes, returns and fails with. +export const GetTodo = Rpc.make("GetTodo", { + payload: { id: Schema.Finite }, + success: Todo, + error: Fetch.errorCodec(getTodo, { client: Api, errors: [TimeoutError] }), +}); +export const TodoRpcs = RpcGroup.make(GetTodo); + +// The server: the call's failures go to the browser as they are. +export const handlers = TodoRpcs.toLayer( + Effect.gen(function* () { + const api = yield* Api; + const todos = api.bind(getTodo); + return { GetTodo: ({ id }) => todos({ params: { id } }) }; + }), +); + +// The browser: the same errors come back, typed as on the server. +export const program = Effect.gen(function* () { + const client = yield* RpcClient.make(TodoRpcs); + return yield* client.GetTodo({ id: 9 }).pipe( + Effect.map((todo) => todo.title), + Effect.catchTag("TodoNotFound", (error) => + Effect.succeed(`No todo ${error.id}`), + ), + Effect.catchTag("HttpError", (error) => + Effect.succeed(error.body?.code ?? `HTTP ${error.status}`), + ), + ); +}); +``` + +In the browser, `error.body` is an `ApiProblem` again, decoded from the +response text as the server's call decoded it. `TodoNotFound` comes back as +a `TodoNotFound`. When `Api` gains another status error, the RPC's errors +include it, with nothing else to change. + +`getTodo` here is a definition, made at module level so the browser can +import it. A definition only knows its own schemas, so `client` gives the +client's `defaultError` and `statusErrors`. An endpoint bound to a client +already has both, so inside an Effect, `Fetch.errorCodec(todos)` is enough. + +The browser then imports `Api` too, and its bundle has the class's config: +the `baseUrl` and the plugins. If those are for the server only, give the +schemas themselves instead, as the next section shows, and keep `Api` in a +module the browser doesn't import. + +Plugins' errors aren't listed on an endpoint or a client. Add the ones your +calls can fail with as `errors`, such as `TimeoutError`. + +## Send the errors of a plain method call + +A call made with `api.get` or the other methods has no endpoint to read. +Give `Fetch.errorCodec` the call's schemas instead: + +```ts +import * as Schema from "effect/Schema"; + +import { Fetch } from "@monarcode/effetch"; + +const ApiProblem = Schema.Struct({ code: Schema.String }); + +class TodoNotFound extends Schema.TaggedError()("TodoNotFound", { + id: Schema.Finite, +}) {} + +export const errors = Fetch.errorCodec({ + error: ApiProblem, + statusErrors: { 404: TodoNotFound }, +}); +``` + +Without `output`, the errors' type includes a `DecodeError`, as a call +with an `output` schema can fail with one. An endpoint or a definition that +has neither `output` nor `stream` can't, so its type leaves it out. + +## What's sent + +Each error goes as JSON, and some of its fields stay on the server: + +| Error | What's sent | What stays behind | +| ---------------------------------------- | --------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------- | +| `HttpError` | `method`, `url`, `status` and `text` | The headers, which decode as empty, so `set-cookie` and the like never leave the server. `body` is decoded again from `text`. | +| `NetworkError` | `method` and `url` | `cause`, which decodes as `undefined` | +| `DecodeError` | `method`, `url`, `status` and `message` | `issue`, which decodes as `undefined` | +| Your `statusErrors` errors, and `errors` | What their own schemas encode | Nothing | + +The URL and the response text do go, and so does a `DecodeError`'s +`message`, which can quote values from the response body. Keep secrets out +of the URLs your server calls and out of the backend's responses, or catch +the error and send one of your own. + +A `statusErrors` error, or one of `errors`, whose schema sends no `_tag` +goes with its schema's name: the `_tag` it leaves out, as +`Schema.tagDefaultOmit` does, or else its identifier, such as a +`Schema.Class`'s name. It decodes with the schema that has that name, +wherever each side lists it. So when the server and the browser run +different versions, an error both know still decodes, and one the browser +doesn't know fails to decode, rather than turning into another. + +A schema without a name of its own, such as a plain struct or a second +class named like another, goes by its place among those, so it only +decodes as itself when both sides list them in the same order. The members +of a plain `Schema.Union` each count as a schema. Give errors that cross a +`_tag`, with `Schema.TaggedError`, or at least an identifier of their own: + +```ts +import * as Schema from "effect/Schema"; + +export const ApiProblem = Schema.Struct({ code: Schema.String }).annotate({ + identifier: "ApiProblem", +}); +``` + +## Use the error classes on their own + +`Fetch.HttpError`, `Fetch.NetworkError` and `Fetch.DecodeError` are schemas +that encode to JSON themselves, so you can also list them in a schema of +your own: + +```ts +import * as Schema from "effect/Schema"; + +import { Fetch } from "@monarcode/effetch"; + +export const errors = Schema.Union([ + Fetch.HttpError, + Fetch.NetworkError, + Fetch.DecodeError, +]); +``` + +They send what the table shows, with one difference: they don't know the +call's error schema, so an `HttpError` sends its `body` when it's JSON, and +the other side reads it as `unknown`. A body decoded into something else, +such as a class, stays behind and decodes as `undefined`. To get a typed +body back, use `Fetch.errorCodec`. + +## What's next + +- [Call errors](/docs/errors): see each error a call can fail with, and its + fields. +- [Errors by status](/docs/errors/status-errors): turn statuses into errors + of your own, which the schema sends too. +- [Endpoints](/docs/endpoints): define the endpoints whose errors you send. diff --git a/site/content/docs/(latest)/errors/index.mdx b/site/content/docs/(latest)/errors/index.mdx index f6dd985..e69070a 100644 --- a/site/content/docs/(latest)/errors/index.mdx +++ b/site/content/docs/(latest)/errors/index.mdx @@ -96,5 +96,7 @@ mistakes. your own domain error. - [Logging and defects](/docs/errors/logging-and-defects): see what stays out of logged errors, and which mistakes are defects. +- [Send errors across the wire](/docs/errors/across-the-wire): send a + call's errors to the browser or an RPC client, typed as on the server. - [Test errors and statuses](/docs/testing/errors): make a fake backend fail, to test your handlers. diff --git a/site/content/docs/(latest)/errors/meta.json b/site/content/docs/(latest)/errors/meta.json index a71bf05..0152694 100644 --- a/site/content/docs/(latest)/errors/meta.json +++ b/site/content/docs/(latest)/errors/meta.json @@ -1,4 +1,10 @@ { "title": "Errors", - "pages": ["index", "catching", "status-errors", "logging-and-defects"] + "pages": [ + "index", + "catching", + "status-errors", + "logging-and-defects", + "across-the-wire" + ] } diff --git a/site/content/docs/(latest)/errors/status-errors.mdx b/site/content/docs/(latest)/errors/status-errors.mdx index 73dc988..a657f12 100644 --- a/site/content/docs/(latest)/errors/status-errors.mdx +++ b/site/content/docs/(latest)/errors/status-errors.mdx @@ -178,10 +178,11 @@ need to repeat it on the endpoint. See ## See it in a full program -[`examples/status-errors.ts`](https://github.com/monarcode/effetch/blob/main/examples/status-errors.ts) -puts all of this in one program, and -[`examples/app`](https://github.com/monarcode/effetch/tree/main/examples/app) -uses it across modules. +[`examples/github`](https://github.com/monarcode/effetch/tree/main/examples/github) +turns GitHub's `404` into an error of its own on each endpoint, and tells a +rate limit apart from other `403`s by its message, for every call. +[`examples/store`](https://github.com/monarcode/effetch/tree/main/examples/store) +uses them across modules. ## What's next diff --git a/site/content/docs/(latest)/examples.mdx b/site/content/docs/(latest)/examples.mdx index ba6ba23..73c7789 100644 --- a/site/content/docs/(latest)/examples.mdx +++ b/site/content/docs/(latest)/examples.mdx @@ -1,49 +1,74 @@ --- title: Examples -description: Find a complete program that uses Effetch, typechecked with the package. +description: Run complete programs that use Effetch against free public APIs, and read their tests. --- -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 +The guides show one feature at a time. 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: - -- [`basic.ts`](https://github.com/monarcode/effetch/blob/main/examples/basic.ts): - a client in a service, the methods, and handling each error. -- [`builtins.ts`](https://github.com/monarcode/effetch/blob/main/examples/builtins.ts): - the built-in plugins, and changing them for one call. -- [`plugins.ts`](https://github.com/monarcode/effetch/blob/main/examples/plugins.ts): - writing plugins, from auth with a service to a `wrap` with its own error. -- [`endpoints.ts`](https://github.com/monarcode/effetch/blob/main/examples/endpoints.ts): - the same app as `builtins.ts`, with endpoints. -- [`backends.ts`](https://github.com/monarcode/effetch/blob/main/examples/backends.ts): - two backends in one file, with shared plugins. -- [`status-errors.ts`](https://github.com/monarcode/effetch/blob/main/examples/status-errors.ts): - your own errors by status, for every call, per endpoint and for one call. -- [`streams.ts`](https://github.com/monarcode/effetch/blob/main/examples/streams.ts): - Server-Sent Events, newline-delimited JSON, and a list paged through by its - `Link` header. -- [`testing.ts`](https://github.com/monarcode/effetch/blob/main/examples/testing.ts): - tests for the `app/` todos module, against a fake backend made from its - endpoints. -- [`app/`](https://github.com/monarcode/effetch/tree/main/examples/app): a - feature-sliced app, with clients as shared infrastructure and each module - defining its own endpoints. +folder has programs that use them together for a real task, against free +public APIs that need no key or account. Each one prints what it did, so +you can run it, then read its code. + +## Run an example + +Clone the repository, run `pnpm install`, then name the example: + +```sh +pnpm example github +``` + +This builds the package if its source has changed, then runs the +example's `main.ts`. It needs Node.js 22.18 or later, which runs TypeScript +files as they are. `pnpm example store-react` starts that app's dev server +instead. + +The public APIs can be slow, rate-limited or down. The examples' tests +don't call them: each one runs against a fake backend made with +`FetchTest`, offline. Run them with `pnpm vitest run examples`. + +The examples on the `main` branch 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`. + +## The examples + +Read them in this order, since each builds on the ones before it: + +- [`github/`](https://github.com/monarcode/effetch/tree/main/examples/github): + shows a repository and its open issues, with a client as a service, + endpoints, errors of your own for a `404` and a rate limit, paging by the + `Link` header, `Retry-After` and a plugin of your own. +- [`sign-in/`](https://github.com/monarcode/effetch/tree/main/examples/sign-in): + signs in, renews the access token with `bearer`'s `refresh` when the + server refuses it, and signs out. The session is an Effect service. +- [`live/`](https://github.com/monarcode/effetch/tree/main/examples/live): + prints Wikipedia's edits as Server-Sent Events, and the moves of Lichess + TV's game as newline-delimited JSON, with a client for each backend. +- [`upload/`](https://github.com/monarcode/effetch/tree/main/examples/upload): + uploads a file and form fields as a multipart body, after checking the + file's size. +- [`bff/`](https://github.com/monarcode/effetch/tree/main/examples/bff): a + server calls a backend, and a browser client calls the server over Effect + RPC. `Fetch.errorCodec` sends the call's errors across, and the example + prints what crossed. +- [`store/`](https://github.com/monarcode/effetch/tree/main/examples/store): + a shop app in feature modules, with a workflow that spans two of them, a + `ManagedRuntime` for the UI, and the workflow's tests. +- [`store-react/`](https://github.com/monarcode/effetch/tree/main/examples/store-react): + the same modules behind a React app routed with TanStack Router. Its + loaders run their calls with the store's runtime and the route's abort + signal, so leaving a page cancels its request. A missing product is the + router's not-found page, and the other errors reach the route's error + component, typed. The examples' [README](https://github.com/monarcode/effetch/blob/main/examples/README.md) -walks through each one, and explains how `app/` is laid out. +lists the APIs each one calls, and explains how `store/` and +`store-react/` are 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`. +- [Structure an app](/docs/structuring-an-app): see the layout that + `store/` follows, and when to use it. +- [Test with a fake backend](/docs/testing): write tests like the + examples' own. diff --git a/site/content/docs/(latest)/index.mdx b/site/content/docs/(latest)/index.mdx index a89b9c3..7bcb0d1 100644 --- a/site/content/docs/(latest)/index.mdx +++ b/site/content/docs/(latest)/index.mdx @@ -12,11 +12,12 @@ it returns and every way it can fail. 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 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. + + An update within 0.1.x doesn't break code written for 0.1.0, and breaking + changes wait for 0.2.0, with notes in the + [changelog](https://github.com/monarcode/effetch/blob/main/CHANGELOG.md). The + exceptions follow Effect, which marks its HTTP modules and Server-Sent Events + parser unstable. See [Versioning](/docs/reference/compatibility#versioning). ## Why Effetch diff --git a/site/content/docs/(latest)/plugins/retry-after.mdx b/site/content/docs/(latest)/plugins/retry-after.mdx index 6aa538b..265e36f 100644 --- a/site/content/docs/(latest)/plugins/retry-after.mdx +++ b/site/content/docs/(latest)/plugins/retry-after.mdx @@ -26,7 +26,9 @@ export class Api extends Fetch.Service()("Api", { ``` `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. +off by default in 0.1.x, and +[Versioning](/docs/reference/compatibility#versioning) says what 0.2.0 +changes. `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 diff --git a/site/content/docs/(latest)/reference/compatibility.mdx b/site/content/docs/(latest)/reference/compatibility.mdx index 0efccc9..720b9b7 100644 --- a/site/content/docs/(latest)/reference/compatibility.mdx +++ b/site/content/docs/(latest)/reference/compatibility.mdx @@ -1,24 +1,80 @@ --- title: Compatibility -description: The Effect versions, runtimes and TypeScript versions Effetch supports, and which of them CI tests. +description: What an Effetch update can change, the Effect versions, runtimes and TypeScript versions Effetch supports, and which of them CI tests. --- -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. +Before you upgrade Effetch or Effect, or add Effetch to a project on an +unusual runtime, check here. This page says what an update can change, +lists what Effetch supports, and keeps what CI tests separate from what +Effetch is built for but CI doesn't test. + +## Versioning + +Effetch uses semantic versioning, with the rule most 0.x packages follow: +while it's at 0.x, the second number marks a breaking change. So an update +within 0.1.x doesn't break code written for 0.1.0, apart from the +exceptions below. A breaking change waits for 0.2.0, and the +[changelog](https://github.com/monarcode/effetch/blob/main/CHANGELOG.md) +says what to change in your code. + +Through 0.1.x, these stay as they are: + +- **The API.** What the package's entry points export + (`@monarcode/effetch`, `@monarcode/effetch/plugins` and + `@monarcode/effetch/test`, and their `Fetch` and `FetchTest` subpaths), + their types, and the behavior these docs describe. +- **What errors send.** The fields of the JSON that `Fetch.errorCodec` and + the error classes encode to, so a server and a browser on different 0.1.x + versions still read each other's errors. +- **What Effetch supports.** TypeScript 5.7 and later, and the runtimes on + this page. Dropping one of them is a breaking change. + +An update can add exports, options and methods. It can also fix a bug, even +when your code relied on the old behavior, if that behavior contradicted the +docs. The changelog lists each fix under **Fixed**. + +Some things aren't part of the API, so any update can change them. These +include the wording of error messages, the lines the `logger` and +`consoleLogger` plugins print, and how a type displays in your editor. An error keeps its fields, but the +wording of its message can change. + +Two exceptions come from Effect, which marks some of the modules Effetch +builds on as unstable: + +- **Effect's HTTP modules.** Effetch's types use `HttpClient`, + `HttpClientRequest`, `HttpClientResponse`, `Headers` and the other + `effect/http` modules. When an Effect 4.x release changes them, a 0.1.x + update of Effetch follows. That can change the types that come from those + modules, or raise the oldest `effect` version Effetch supports, and the + changelog says when it does. +- **Server-Sent Events.** `api.sse`, and endpoints with `stream: "sse"`, + read events with Effect's `encoding/Sse`. A 0.1.x update can change how + these streams behave, to keep up with it. Their JSDoc says + `@stability unstable`, which your editor shows on hover. Newline-delimited + JSON streams aren't affected: Effetch reads them itself. + +You get a newer Effect 4.x by updating `effect` alone, since the peer range, +`^4.0.0`, takes it. CI tests the newest 4.x every week, and when one needs a +fix in Effetch, the fix ships as a 0.1.x update. + +One change is decided for 0.2.0. In 0.1.x, `retry` waits as a `Retry-After` +header asks only when you pass `retryAfter`. In 0.2.0, it waits that way by +default, for up to 1 minute, so an existing `retry` can wait longer. To keep +the 0.1 behavior, pass `retryAfter: false`, which 0.1.x already accepts. ## 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 that range: +CI tests three versions in that 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. +- **Two more jobs** typecheck, test and build with `effect` 4.0.0, the + oldest version in the range, and with the newest 4.x on npm, which is + what a new install gets. 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, @@ -38,10 +94,16 @@ CI tests: | Runtime | Tested in CI | | ----------------------------------- | ------------------------------------------ | | Node.js 24 | Yes: the tests and the installed package | -| Node.js 20 and 22 | No. The build targets ES2020. | +| Node.js 20 and 22 | Yes: the installed package | +| Bun 1 and Deno 2 | Yes: the installed package | | Browsers | No. See [Platform notes](/docs/platforms). | | React Native, with Hermes and Metro | No. See [Platform notes](/docs/platforms). | -| Bun and Deno | No | + +"The installed package" is a test program in a project of its own, which +installs Effetch from its packed tarball, as npm would install it. It makes +calls, streams and pages through clients that answer in memory, including +`FetchTest`. Effetch's own tests run on Node.js 24 only. Neither sends a +real request, so CI doesn't test a runtime's own `fetch`. 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 @@ -55,6 +117,9 @@ 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. +The JavaScript targets ES2020, so it runs without transpiling on any runtime +that supports ES2020. + ## TypeScript Effetch needs TypeScript 5.7 or later. Its declarations use typed arrays @@ -74,6 +139,10 @@ CI checks the types with TypeScript 6.0.3, in three ways: with `exactOptionalPropertyTypes` and `noUncheckedIndexedAccess` on. The installed-package project compiles with them off. +Two more jobs compile the installed-package project, under `NodeNext` and +`Bundler`, with TypeScript 5.7, the oldest supported version, and with the +newest TypeScript 7. + ## What's next - [Platform notes](/docs/platforms): set Effetch up for browsers and React diff --git a/site/content/docs/(latest)/reference/fetch.mdx b/site/content/docs/(latest)/reference/fetch.mdx index 9be7571..167e635 100644 --- a/site/content/docs/(latest)/reference/fetch.mdx +++ b/site/content/docs/(latest)/reference/fetch.mdx @@ -275,6 +275,10 @@ An empty body (204, HEAD, …) is decoded as JSON `null`, so it only passes sche 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.errorCodec [#errorcodec] + +Builds a codec for every error a call can fail with: a schema whose JSON encoding (`Schema.toCodecJson`) turns each error into JSON, and decodes it back into the same class, typed as the call types it. Use it to send a call's failures where only data goes: to the browser from a server-rendered page, to an RPC client, to a worker. + ### Fetch.HttpError [#httperror] The error a call fails with when the server answers with a status outside 200–299. Its fields: @@ -282,7 +286,7 @@ The error a call fails with when the server answers with a status outside 200– - `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. +- `headers`: the response headers. They're Effect `Headers`, so sensitive ones (`set-cookie`, `authorization`, …) print as `` when the error is logged or passed to `JSON.stringify`. The error's JSON encoding leaves them out (see below). - `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. @@ -318,6 +322,35 @@ What a call can fail with: `NetworkError`, `HttpError`, `DecodeError` when there The error [`catchStatus`](#catchstatus)'s handler gets: an `HttpError` whose `status` is narrowed to the statuses `S` it was given. Its `body` is `unknown`: to read it typed by the `error` schema, use `Effect.catchTag("HttpError", …)`. +### Fetch.ErrorCodec [#errorcodec-type] + +What [`errorCodec`](#errorcodec) returns: a codec, the schema for the errors a call can fail with, `E`, whose JSON encoding can cross to a browser, a worker or an RPC client. `RD` and `RE` are the services its schemas need to decode and encode, `never` for most. + +### Fetch.ErrorCodecClient [#errorcodecclient] + +The client [`errorCodec`](#errorcodec) takes the `defaultError` and `statusErrors` of: a `Fetch.Service` class, or anything with a `config` like one. + +### Fetch.ErrorCodecErrors [#errorcodecerrors] + +The errors [`errorCodec`](#errorcodec) describes for a source `S`, a client `C` and more errors `Es`: the call's errors, as [`CallError`](#callerror) gives them, without the plugins' errors, plus `Es`. + +### Fetch.ErrorCodecOptions [#errorcodecoptions] + +Options for [`errorCodec`](#errorcodec). + + + +### Fetch.ErrorCodecSource [#errorcodecsource] + +Where [`errorCodec`](#errorcodec) reads a call's error schemas from: anything with the `output`, `error` and `statusErrors` an endpoint has. + +- An endpoint, bound to a client. It already carries the client's `defaultError` and `statusErrors`. +- A definition made with `Fetch.endpoint`, at module level. It only knows its own schemas, so give the client as `client`. +- The schemas themselves, for calls made with the plain methods: `{ error: ApiError, statusErrors: { 404: NotFound } }`. + ### Fetch.FetchError [#fetcherror] Every error the library itself can fail a call with. Plugins may add their own errors on top of these. diff --git a/site/content/docs/(latest)/structuring-an-app.mdx b/site/content/docs/(latest)/structuring-an-app.mdx index 7ab7951..dd34f78 100644 --- a/site/content/docs/(latest)/structuring-an-app.mdx +++ b/site/content/docs/(latest)/structuring-an-app.mdx @@ -157,30 +157,29 @@ 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: +[`examples/store`](https://github.com/monarcode/effetch/tree/main/examples/store) +is a complete app in this layout: a shop with a products module and a cart +module, which you can run against a free fake store. Here are its files: ```text -examples/app/ +examples/store/ ├── infrastructure/http/ -│ ├── app-api-client.ts the main backend's client -│ ├── wallet-api-client.ts the wallet backend's client -│ └── plugins.ts plugins both clients use +│ └── store-api-client.ts the backend's client ├── modules/ -│ ├── todos/ -│ │ ├── 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/ -│ ├── application/ workflows that take more than one call +│ ├── products/ +│ │ ├── contract/products.ts schemas, and endpoints from Fetch.endpoint +│ │ ├── data/product.api.ts the endpoints, bound to StoreApiClient +│ │ ├── products.layer.ts the module's layers, merged +│ │ └── public.ts what other code may import +│ └── cart/ +│ ├── application/ workflows that take more than one call │ ├── contract/ │ ├── data/ -│ ├── wallet.layer.ts +│ ├── cart.test.ts a workflow's tests, against a fake backend +│ ├── cart.layer.ts │ └── public.ts -├── runtime.ts modules, over the clients, over HttpClient -└── main.ts the program: imports modules only through public.ts +├── runtime.ts modules, over the client, over HttpClient +└── main.ts the program: imports modules only through public.ts ``` @@ -191,9 +190,14 @@ examples/app/ layer. -The following code puts the `todos` module's files in one block, each +The same modules also run behind a React app: +[`examples/store-react`](https://github.com/monarcode/effetch/tree/main/examples/store-react) +routes them with TanStack Router, and its loaders run their calls with the +store's `ManagedRuntime`, so leaving a page cancels its request. + +The following code puts the `products` 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: +more fields and errors: ```ts import * as Config from "effect/Config"; @@ -204,50 +208,54 @@ import * as Schema from "effect/Schema"; import { Fetch } from "@monarcode/effetch"; -// infrastructure/http/app-api-client.ts: how to reach the backend -export class AppApiClient extends Fetch.Service()( - "AppApiClient", - { baseUrl: Config.String("APP_API_URL") }, +// infrastructure/http/store-api-client.ts: how to reach the backend +export class StoreApiClient extends Fetch.Service()( + "StoreApiClient", + { baseUrl: Config.String("STORE_API_URL") }, ) {} -// modules/todos/contract/todos.ts: schemas and endpoints, no client -const Todo = Schema.Struct({ id: Schema.Finite, title: Schema.String }); -const NewTodo = Schema.Struct({ title: Schema.String }); - -export const listTodos = Fetch.endpoint("GET /todos", { - output: Schema.Array(Todo), +// modules/products/contract/products.ts: schemas and endpoints, no client +const Product = Schema.Struct({ + id: Schema.Finite, + title: Schema.String, + price: Schema.Finite, }); -export const getTodo = Fetch.endpoint("GET /todos/:id", { output: Todo }); -export const createTodo = Fetch.endpoint("POST /todos", { - input: NewTodo, - output: Todo, +const ProductPage = Schema.Struct({ products: Schema.Array(Product) }); + +export const getProduct = Fetch.endpoint("GET /products/:id", { + output: Product, }); +export const productsInCategory = Fetch.endpoint( + "GET /products/category/:category", + { output: ProductPage }, +); -// modules/todos/data/todo.api.ts: the endpoints, bound, as a service -export class TodoApi extends Fetch.Endpoints()( - "TodoApi", - AppApiClient, +// modules/products/data/product.api.ts: the endpoints, bound, as a service +export class ProductApi extends Fetch.Endpoints()( + "ProductApi", + StoreApiClient, { - list: listTodos, - get: getTodo, - create: createTodo, + get: getProduct, + inCategory: productsInCategory, }, ) {} -// modules/todos/todo.layer.ts: every layer the module has -export const TodoModuleLive = Layer.mergeAll(TodoApi.layer); +// modules/products/products.layer.ts: every layer the module has +export const ProductModuleLive = Layer.mergeAll(ProductApi.layer); // runtime.ts: the modules, on top of the client, on top of HttpClient -export const AppLayer = TodoModuleLive.pipe( - Layer.provideMerge(AppApiClient.layer), +export const AppLayer = ProductModuleLive.pipe( + Layer.provideMerge(StoreApiClient.layer), Layer.provide(FetchHttpClient.layer), ); // anywhere export const program = Effect.gen(function* () { - const todos = yield* TodoApi; - const todo = yield* todos.create({ body: { title: "Write docs" } }); - return yield* todos.get({ params: { id: todo.id } }); + const products = yield* ProductApi; + const page = yield* products.inCategory({ + params: { category: "smartphones" }, + }); + return page.products.map((product) => product.title); }); ``` @@ -262,12 +270,12 @@ Each part of the app grows in its own place: 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. +- **Every module's data service is its endpoints,** as `ProductApi` 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, as `wallet` has. + the module's `application/` folder, as the cart's `buyCheapest` is. - **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. @@ -279,10 +287,9 @@ import only the schemas from `contract/`. Define them with `Fetch.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 +The example app uses `Fetch.endpoint` in both modules, because +`cart.test.ts` serves the endpoints from a fake backend. With `api.endpoint`, +share them as a service the way [Endpoints made with api.endpoint](#endpoints-made-with-apiendpoint) shows. ## Several backends @@ -342,10 +349,9 @@ Keep the following in mind: - **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 -[`examples/app`](https://github.com/monarcode/effetch/tree/main/examples/app) -across modules. +[`examples/live`](https://github.com/monarcode/effetch/tree/main/examples/live) +has two clients for two backends, Wikimedia and Lichess, on one +`HttpClient`. ## What's next diff --git a/site/src/components/landing/sections.tsx b/site/src/components/landing/sections.tsx index 79404b6..8fabca6 100644 --- a/site/src/components/landing/sections.tsx +++ b/site/src/components/landing/sections.tsx @@ -527,15 +527,25 @@ export function Specifications({ version }: { version: string }) { new URL() - , so it runs on Hermes too. CI tests on Node.js 24. + , so it runs on Hermes too. CI runs it on Node.js 20 to 24, + Bun and Deno.

Effect v4's HttpClient and Schema. - A release candidate,{" "} - {version}, on the - way to 0.1.0. When a release candidate changes the API, the - changelog says what to change in your code. + {version}. An + update within 0.1.x doesn't break your code, and a breaking + change waits for 0.2.0. The exceptions follow Effect's own + unstable modules:{" "} + + Versioning + + . Every example in the docs and the README is compiled against the diff --git a/src/ErrorCodec.ts b/src/ErrorCodec.ts new file mode 100644 index 0000000..daec0cb --- /dev/null +++ b/src/ErrorCodec.ts @@ -0,0 +1,731 @@ +import * as Effect from "effect/Effect"; +import * as Exit from "effect/Exit"; +import * as Headers from "effect/http/Headers"; +import * as Schema from "effect/Schema"; +import * as SchemaAST from "effect/SchemaAST"; +import * as SchemaIssue from "effect/SchemaIssue"; +import * as SchemaParser from "effect/SchemaParser"; +import * as SchemaTransformation from "effect/SchemaTransformation"; + +import { DecodeError, HttpError, NetworkError } from "./Errors.js"; +import { parseErrorBody, readErrorBody } from "./internal/response.js"; +import { joinStatusErrors, sentTagOf, tagOf } from "./internal/statusErrors.js"; +import type { + AnySchema, + CallError, + StatusError, + StatusErrorMap, + StatusErrorSchema, +} from "./Options.js"; +import type { StreamFormat } from "./Streams.js"; + +/** + * Where {@link errorCodec} reads a call's error schemas from: anything + * with the `output`, `error` and `statusErrors` an endpoint has. + * + * - An endpoint, bound to a client. It already carries the client's + * `defaultError` and `statusErrors`. + * - A definition made with `Fetch.endpoint`, at module level. It only knows + * its own schemas, so give the client as `client`. + * - The schemas themselves, for calls made with the plain methods: + * `{ error: ApiError, statusErrors: { 404: NotFound } }`. + * + * `output` and `stream` decide whether a `DecodeError` is one of the + * errors' types: an endpoint or definition with neither has none. Leave + * `output` out of an object of your own to include it. + * + * @example + * ```ts + * import * as Schema from "effect/Schema"; + * import { Fetch } from "@monarcode/effetch"; + * + * const ApiError = Schema.Struct({ code: Schema.String }); + * + * const source: Fetch.ErrorCodecSource = { error: ApiError }; + * ``` + * + * @since 0.1.0 + */ +export interface ErrorCodecSource { + /** The schema the call's response is decoded with, if it has one. */ + readonly output?: AnySchema | undefined; + /** The schema `HttpError.body` is decoded with. */ + readonly error?: AnySchema | undefined; + /** The errors that statuses turn into. */ + readonly statusErrors?: StatusErrorMap | undefined; + /** How the call streams its body, if it does. */ + readonly stream?: StreamFormat | undefined; +} + +/** + * The client {@link errorCodec} takes the `defaultError` and + * `statusErrors` of: a `Fetch.Service` class, or anything with a `config` + * like one. + * + * @example + * ```ts + * import { Fetch } from "@monarcode/effetch"; + * + * class Api extends Fetch.Service()("Api", { + * baseUrl: "https://api.example.com", + * }) {} + * + * const client: Fetch.ErrorCodecClient = Api; + * ``` + * + * @since 0.1.0 + */ +export interface ErrorCodecClient { + /** The client's config, as `Fetch.Service` classes keep it. */ + readonly config: { + readonly defaultError?: AnySchema | undefined; + readonly statusErrors?: StatusErrorMap | undefined; + }; +} + +/** + * Options for {@link errorCodec}. + * + * @example + * ```ts + * import { Fetch } from "@monarcode/effetch"; + * import { TimeoutError } from "@monarcode/effetch/plugins"; + * + * class Api extends Fetch.Service()("Api", { + * baseUrl: "https://api.example.com", + * }) {} + * + * const options = { client: Api, errors: [TimeoutError] } satisfies Fetch.ErrorCodecOptions< + * typeof Api, + * [typeof TimeoutError] + * >; + * ``` + * + * @since 0.1.0 + */ +export interface ErrorCodecOptions< + C extends ErrorCodecClient | undefined = undefined, + Es extends ReadonlyArray = [], +> { + /** + * The client whose `defaultError` and `statusErrors` to use. Its + * `defaultError` is used when the source has no `error` of its own, and + * its `statusErrors` are tried after the source's. A bound endpoint + * already has both. + */ + readonly client?: C | undefined; + /** + * More errors to send, such as plugins' errors (`TimeoutError`), which + * endpoints and clients don't list. Each must be a schema that encodes. + */ + readonly errors?: Es | undefined; +} + +/** + * What {@link errorCodec} returns: a codec, the schema for the errors a + * call can fail with, `E`, whose JSON encoding can cross to a browser, a + * worker or an RPC client. `RD` and `RE` are the services its schemas + * need to decode and encode, `never` for most. + * + * @example + * ```ts + * import { Fetch } from "@monarcode/effetch"; + * + * declare const errors: Fetch.ErrorCodec; + * ``` + * + * @since 0.1.0 + */ +export type ErrorCodec = Schema.Codec< + E, + unknown, + RD, + RE +>; + +/** + * The errors {@link errorCodec} describes for a source `S`, a client `C` + * and more errors `Es`: the call's errors, as {@link CallError} gives them, + * without the plugins' errors, plus `Es`. + * + * @example + * ```ts + * import * as Schema from "effect/Schema"; + * import type { Fetch } from "@monarcode/effetch"; + * + * type E = Fetch.ErrorCodecErrors< + * { readonly error: Schema.Struct<{ readonly code: Schema.String }> }, + * undefined, + * [] + * >; + * // ^? NetworkError | HttpError.With<{ readonly code: string }> | DecodeError + * ``` + * + * @since 0.1.0 + */ +export type ErrorCodecErrors< + S extends ErrorCodecSource, + C extends ErrorCodecClient | undefined, + Es extends ReadonlyArray, +> = + | CallError, BodyOf, [], StatusErrorsOf> + | Es[number]["Type"]; + +/** + * `undefined` when `S` has no `output` and doesn't stream, so the errors + * have no `DecodeError`. A stream fails with one while it's read. + */ +type OutputOf = S extends { + readonly output: undefined; + readonly stream?: undefined; +} + ? undefined + : AnySchema; + +/** A schema, or `Schema.Unknown` for `undefined` or nothing. */ +type SchemaOrUnknown = [Exclude] extends [never] + ? Schema.Unknown + : Exclude extends AnySchema + ? Exclude + : Schema.Unknown; + +/** The schema `HttpError.body` is decoded with: the source's, else the client's. */ +type BodyOf = S extends { readonly error: infer EB extends AnySchema } + ? EB + : C extends { readonly config: { readonly defaultError?: infer EB } } + ? SchemaOrUnknown + : Schema.Unknown; + +/** The source's `statusErrors` maps, and the client's. */ +type StatusErrorsOf = + | (S extends { readonly statusErrors: infer SE } + ? Extract + : never) + | (C extends { readonly config: { readonly statusErrors?: infer SE } } + ? Extract + : never); + +/** + * An `HttpError` as it's sent: no headers, so `set-cookie` and the like + * stay put, and no `body`, which is decoded again from `text` with `body`, + * as the call decoded it. + */ +const httpErrorFromText = (body: AnySchema | undefined) => + Schema.TaggedStruct("HttpError", { + method: Schema.String, + url: Schema.String, + status: Schema.Finite, + text: Schema.String, + }).pipe( + Schema.decodeTo( + Schema.instanceOf(HttpError, { expected: "an HttpError" }), + SchemaTransformation.transformEffect({ + decode: ({ method, url, status, text }) => + Effect.map( + readErrorBody(parseErrorBody(text), body), + (decoded) => + new HttpError({ + method, + url, + status, + text, + headers: Headers.empty, + body: decoded, + }), + ), + encode: (error) => + Effect.succeed({ + _tag: "HttpError" as const, + method: error.method, + url: error.url, + status: error.status, + text: error.text, + }), + }), + ), + ); + +/** The `_tag` that sets apart the errors whose schemas send no `_tag`. */ +const untaggedTag = "effetch/UntaggedError"; + +/** + * What an error whose schema sends no `_tag` goes with, so the other side + * decodes it with the same schema: the `_tag` its schema leaves out, as + * with `Schema.tagDefaultOmit`, else its schema's identifier, such as a + * class's name, when no other schema has the same; else its schema's place + * among the rest. + */ +type UntaggedKey = + | { readonly tag: string } + | { readonly identifier: string } + | { readonly index: number }; + +/** An error schema that sends no `_tag`. */ +interface Untagged { + /** Its JSON codec. The services it needs are the codec's, as its type says. */ + readonly json: Schema.Codec; + readonly key: UntaggedKey; + /** Whether its type takes `value`, extra fields and all. */ + readonly is: (value: unknown) => boolean; + /** Whether its type takes `value` without leaving out any of its fields. */ + readonly isExact: (value: unknown) => boolean; + /** Its type is a declaration, such as a class, rather than a struct. */ + readonly declaration: boolean; + readonly schema: AnySchema; + /** Its type's identifier, such as a class's name. */ + readonly identifier: string | undefined; + /** Its type's keys, when it's a struct. */ + readonly keys: ReadonlySet | undefined; +} + +const exactly: SchemaAST.ParseOptions = { onExcessProperty: "error" }; + +/** A struct's keys, or `undefined` for anything else. */ +const structKeys = (ast: SchemaAST.AST) => + SchemaAST.isObjects(ast) && ast.indexSignatures.length === 0 + ? new Set(ast.propertySignatures.map((signature) => signature.name)) + : undefined; + +/** + * The schemas that send no `_tag`, each with its key. A name, the `_tag` + * a schema leaves out or its identifier, is a key only when no other + * schema has it: schemas that share one, such as two classes named + * `ApiError`, go by place instead, as the other side couldn't tell them + * apart by name. + */ +const untaggedEntries = ( + schemas: ReadonlyArray, +): ReadonlyArray => { + const named = schemas.map((schema) => { + const type = Schema.toType(schema as Schema.Top); + const tag = tagOf(schema); + const identifier = SchemaAST.resolveIdentifier(type.ast); + const name = + tag !== undefined + ? `_tag ${tag}` + : identifier !== undefined + ? `identifier ${identifier}` + : undefined; + return { schema, type, tag, identifier, name }; + }); + const counts = new Map(); + for (const { name } of named) { + if (name !== undefined) { + counts.set(name, (counts.get(name) ?? 0) + 1); + } + } + let index = 0; + return named.map(({ schema, type, tag, identifier, name }): Untagged => { + const unique = name !== undefined && counts.get(name) === 1; + const key: UntaggedKey = + unique && tag !== undefined + ? { tag } + : unique && identifier !== undefined + ? { identifier } + : { index: index++ }; + const validate = SchemaParser.decodeUnknownExit(type); + return { + json: Schema.toCodecJson( + schema as Schema.Top, + ) as unknown as Schema.Codec, + key, + is: Schema.is(type), + isExact: (value) => { + try { + return Exit.isSuccess(validate(value, exactly)); + } catch { + return false; + } + }, + declaration: SchemaAST.isDeclaration(type.ast), + schema, + identifier, + keys: structKeys(type.ast), + }; + }); +}; + +/** + * How well a struct's `keys` fit `value`: whether they cover all of its + * own keys, then how many of them they cover. + */ +const fit = ( + keys: ReadonlySet | undefined, + value: unknown, +): ReadonlyArray => { + if (keys === undefined || typeof value !== "object" || value === null) { + return [0, 0]; + } + const own = Object.keys(value); + const covered = own.filter((key) => keys.has(key)).length; + return [covered === own.length ? 1 : 0, covered]; +}; + +/** + * How far up `value`'s prototype chain the entry's class is: 0 for the + * value's own class. A class matches itself; a copy of one, such as + * `Conflict.annotate(…)`, matches by the `identifier` a `Schema.Class` + * has, a half step further, so two classes with the same name aren't + * taken for each other. + */ +const classDistance = (value: object, entry: Untagged) => { + let found = Number.POSITIVE_INFINITY; + let distance = 0; + for ( + let proto: unknown = Object.getPrototypeOf(value); + typeof proto === "object" && proto !== null && proto !== Object.prototype; + proto = Object.getPrototypeOf(proto) + ) { + const { constructor } = proto as { readonly constructor?: unknown }; + if (constructor === entry.schema) { + return Math.min(found, distance); + } + if ( + found === Number.POSITIVE_INFINITY && + entry.identifier !== undefined && + typeof constructor === "function" && + (constructor as { readonly identifier?: unknown }).identifier === + entry.identifier + ) { + found = distance + 0.5; + } + distance++; + } + return found; +}; + +/** Whether `a` ranks above `b`, comparing each place in turn. */ +const ranksAbove = (a: ReadonlyArray, b: ReadonlyArray) => { + for (let i = 0; i < a.length; i++) { + if (a[i] !== b[i]) { + return a[i]! > b[i]!; + } + } + return false; +}; + +/** + * The schemas that take `value`: those that keep all its fields, so + * `{ message, id }` doesn't go as a `{ message }` struct, else those that + * take it with fields to spare. + */ +const takersOf = (entries: ReadonlyArray, value: unknown) => { + const exact = entries.filter((entry) => entry.isExact(value)); + return exact.length > 0 ? exact : entries.filter((entry) => entry.is(value)); +}; + +/** + * The schema `value` goes as, of those that take it: a class instance's + * nearest class, then the struct that covers most of its fields. Ties go + * to the first listed. + */ +const schemaFor = (entries: ReadonlyArray, value: unknown) => { + const takers = takersOf(entries, value); + const instance = + typeof value === "object" && + value !== null && + Object.getPrototypeOf(value) !== Object.prototype && + Object.getPrototypeOf(value) !== null; + let found: Untagged | undefined; + let top: ReadonlyArray = []; + for (const entry of takers) { + const asClass = instance && entry.declaration; + const rank = [ + asClass ? 1 : 0, + asClass ? -classDistance(value, entry) : 0, + ...fit(entry.keys, value), + ]; + if (found === undefined || ranksAbove(rank, top)) { + found = entry; + top = rank; + } + } + return found; +}; + +/** The key the wire names, or why it names none. */ +const keyOf = (wire: { + readonly tag?: string; + readonly identifier?: string; + readonly index?: number; +}): UntaggedKey | undefined => { + const { tag, identifier, index } = wire; + const given = [tag, identifier, index].filter((key) => key !== undefined); + if (given.length !== 1) { + return undefined; + } + return tag !== undefined + ? { tag } + : identifier !== undefined + ? { identifier } + : { index: index! }; +}; + +/** + * The errors whose schemas send no `_tag`, as one member. Each goes as + * `{ _tag: "effetch/UntaggedError", error }` with its key, `tag`, + * `identifier` or `index`, and decodes with only the schema that has it. + * One the other side doesn't know fails to decode, rather than decoding as + * another. + */ +const untaggedErrors = (entries: ReadonlyArray) => { + const byKey = new Map( + entries.map((entry) => [JSON.stringify(entry.key), entry] as const), + ); + /** The schema the wire's key names, or why none does. */ + const find = ( + wire: Parameters[0], + options: SchemaAST.ParseOptions, + ): Untagged | SchemaIssue.Issue => { + const key = keyOf(wire); + if (key === undefined) { + return new SchemaIssue.InvalidValue( + { + message: + "an error without a _tag goes with an identifier, a tag or an index", + }, + wire, + options, + ); + } + const entry = byKey.get(JSON.stringify(key)); + if (entry !== undefined) { + return entry; + } + const [name, value] = Object.entries(key)[0]!; + return new SchemaIssue.Pointer( + [name], + new SchemaIssue.InvalidValue( + { + message: + "index" in key + ? `no error schema without an identifier is at index ${key.index}` + : `no error schema has the ${"tag" in key ? "_tag" : "identifier"} ${JSON.stringify(value)}`, + }, + value, + options, + ), + ); + }; + + return Schema.Struct({ + _tag: Schema.Literal(untaggedTag), + tag: Schema.optionalKey(Schema.String), + identifier: Schema.optionalKey(Schema.String), + index: Schema.optionalKey(Schema.Int), + error: Schema.Unknown, + }).pipe( + Schema.decodeTo( + Schema.declare( + (value): value is unknown => takersOf(entries, value).length > 0, + { expected: "an error one of the error schemas takes" }, + ), + SchemaTransformation.transformEffect({ + decode: (wire, options) => { + const found = find(wire, options); + return "json" in found + ? SchemaParser.decodeUnknownEffect(found.json)( + wire.error, + options, + ).pipe( + Effect.mapError( + (issue) => new SchemaIssue.Pointer(["error"], issue), + ), + ) + : Effect.fail(found); + }, + encode: (value, options) => { + // The declaration above only lets through values some schema takes. + const entry = schemaFor(entries, value)!; + return SchemaParser.encodeUnknownEffect(entry.json)( + value, + options, + ).pipe( + Effect.map((error) => ({ + _tag: untaggedTag as typeof untaggedTag, + ...entry.key, + error, + })), + Effect.mapError( + (issue) => new SchemaIssue.Pointer(["error"], issue), + ), + ); + }, + }), + ), + ); +}; + +/** + * Whether the schema is a plain `Schema.Union`, with no checks, + * transformation or identifier of its own, whose members can go as + * themselves. + */ +const isPlainUnion = ( + schema: AnySchema, +): schema is AnySchema & { readonly members: ReadonlyArray } => { + const { ast } = schema; + return ( + SchemaAST.isUnion(ast) && + Array.isArray((schema as { readonly members?: unknown }).members) && + ast.checks === undefined && + ast.encoding === undefined && + (ast as { readonly encodingChecks?: unknown }).encodingChecks === + undefined && + ast.options?.mode !== "oneOf" && + SchemaAST.resolveIdentifier(ast) === undefined + ); +}; + +/** A plain union's members, in turn, or the schema itself. */ +const membersOf = (schema: AnySchema): ReadonlyArray => + isPlainUnion(schema) ? schema.members.flatMap(membersOf) : [schema]; + +/** + * Builds a codec for every error a call can fail with: a schema whose JSON + * encoding (`Schema.toCodecJson`) turns each error into JSON, and decodes + * it back into the same class, typed as the call types it. Use it to send a + * call's failures where only data goes: to the browser from a + * server-rendered page, to an RPC client, to a worker. + * + * Give it where the call's schemas are: + * + * - an endpoint bound to a client: `Fetch.errorCodec(todos.get)`; + * - a definition and its client, at module level: + * `Fetch.errorCodec(getTodo, { client: Api })`; + * - the schemas themselves, for the plain methods: + * `Fetch.errorCodec({ error: ApiError, statusErrors: { 404: NotFound } })`. + * + * What's sent: + * + * - An `HttpError` goes with its `method`, `url`, `status` and `text`. Its + * `body` is decoded again from `text`, with the call's error schema, so + * it's typed on the other side too. The headers aren't sent, and decode + * as empty. + * - A `NetworkError` goes without its `cause`, and a `DecodeError` without + * its `issue`. Both decode as `undefined`. + * - The `statusErrors` errors, and the `errors` you add, go as their own + * schemas encode them. One whose schema sends no `_tag` goes with its + * schema's name: the `_tag` it leaves out, as with + * `Schema.tagDefaultOmit`, or its identifier, such as a class's name. It + * decodes with the schema that has that name, wherever the other side + * lists it. A schema without a name of its own, such as a plain struct, + * goes by its place among those, so both sides must list them in the + * same order. A plain `Schema.Union`'s members each count as a schema. + * + * Plugins' errors aren't on an endpoint or a client, so add the ones a call + * can fail with as `errors`, such as `TimeoutError`. + * + * The request URL, the response text and a `DecodeError`'s `message`, + * which can quote the response body, are sent. Keep secrets out of the URLs + * your server calls and out of the backend's responses, or catch the error + * and send one of your own. + * + * @example + * ```ts + * import * as Rpc from "effect/rpc/Rpc"; + * import * as Schema from "effect/Schema"; + * import { Fetch } from "@monarcode/effetch"; + * import { TimeoutError, timeout } from "@monarcode/effetch/plugins"; + * + * class ApiProblem extends Schema.Class("ApiProblem")({ + * code: Schema.String, + * }) {} + * + * class TodoNotFound extends Schema.TaggedError()( + * "TodoNotFound", + * { id: Schema.Finite }, + * ) {} + * + * class Api extends Fetch.Service()("Api", { + * baseUrl: "https://api.example.com", + * defaultError: ApiProblem, + * statusErrors: { 404: TodoNotFound }, + * plugins: [timeout({ duration: "5 seconds" })], + * }) {} + * + * const Todo = Schema.Struct({ id: Schema.Finite, title: Schema.String }); + * const getTodo = Fetch.endpoint("GET /todos/:id", { output: Todo }); + * + * // An RPC that fails with what the call fails with. + * export const GetTodo = Rpc.make("GetTodo", { + * payload: { id: Schema.Finite }, + * success: Todo, + * error: Fetch.errorCodec(getTodo, { client: Api, errors: [TimeoutError] }), + * }); + * ``` + * + * @since 0.1.0 + */ +// The return type writes out the members of ErrorCodecErrors, so a hover shows +// the errors rather than the alias (as the call signatures do with +// CallError). Keep the two in sync: the type tests check they're equal. +export function errorCodec< + S extends ErrorCodecSource, + C extends ErrorCodecClient | undefined = undefined, + const Es extends ReadonlyArray = [], +>( + source: S, + options?: ErrorCodecOptions, +): ErrorCodec< + | NetworkError + | ([unknown] extends [BodyOf["Type"]] + ? 0 extends 1 & BodyOf["Type"] + ? HttpError.With["Type"]> + : HttpError + : HttpError.With["Type"]>) + | (S extends { readonly output: undefined; readonly stream?: undefined } + ? never + : DecodeError) + | StatusError> + | Es[number]["Type"], + | BodyOf["DecodingServices"] + | StatusErrorSchema>["DecodingServices"] + | Es[number]["DecodingServices"], + | StatusErrorSchema>["EncodingServices"] + | Es[number]["EncodingServices"] +>; +export function errorCodec( + source: ErrorCodecSource, + options?: ErrorCodecOptions< + ErrorCodecClient | undefined, + ReadonlyArray + >, +): unknown { + const config = options?.client?.config; + // The schemas statuses turn into, read as calls read them (the source's, + // then the client's), then the errors added, each once. A plain union's + // members come after the schemas listed themselves, so a member doesn't + // take the place of a schema listed with the same `_tag`. + const listed = [ + ...new Set([ + ...Object.values( + joinStatusErrors([source.statusErrors, config?.statusErrors]), + ).flat(), + ...(options?.errors ?? []), + ]), + ]; + const others = new Set([ + ...listed.filter((schema) => !isPlainUnion(schema)), + ...listed.filter(isPlainUnion).flatMap(membersOf), + ]); + const tagged = [...others].filter( + (schema) => sentTagOf(schema) !== undefined, + ); + const rest = untaggedEntries( + [...others].filter((schema) => sentTagOf(schema) === undefined), + ); + // Effetch's own errors first, then the other tagged ones, then the rest, + // as one member that names each error's schema: a schema that sends no + // `_tag` can then neither take another's value when encoding, nor its + // JSON when decoding. A `DecodeError` is always decoded, though the type + // leaves it out for a call that can't fail with one. + const members: ReadonlyArray = [ + httpErrorFromText(source.error ?? config?.defaultError), + NetworkError, + DecodeError, + ...tagged, + ...(rest.length === 0 ? [] : [untaggedErrors(rest)]), + ]; + return Schema.Union(members as unknown as ReadonlyArray); +} diff --git a/src/Errors.ts b/src/Errors.ts index 71327ab..d2cccd1 100644 --- a/src/Errors.ts +++ b/src/Errors.ts @@ -1,5 +1,61 @@ import * as Headers from "effect/http/Headers"; +import * as Option from "effect/Option"; import * as Schema from "effect/Schema"; +import * as SchemaGetter from "effect/SchemaGetter"; + +// The errors encode to JSON, so they can cross to a browser, a worker or an +// RPC client, and decode back into the same classes. What isn't safe or +// isn't JSON stays behind: these fields aren't encoded. Decoding never +// fails on them, so values built in memory still decode as before. + +/** + * `HttpError.headers`: never sent, so `set-cookie` and the like stay put. + * Anything but an Effect `Headers` value decodes as empty, so headers can't + * be sent in either. + */ +const headersNotSent = Schema.optionalKey(Schema.Unknown).pipe( + Schema.decodeTo(Schema.declare(Headers.isHeaders), { + decode: SchemaGetter.transformOptional((headers) => + Option.some( + Option.isSome(headers) && Headers.isHeaders(headers.value) + ? headers.value + : Headers.empty, + ), + ), + encode: SchemaGetter.omit(), + }), +); + +/** + * `NetworkError.cause` and `DecodeError.issue`: platform values, not JSON, + * so never sent. They decode as `undefined` when they're missing. + */ +const unknownNotSent = Schema.optionalKey(Schema.Unknown).pipe( + Schema.decodeTo(Schema.Unknown, { + decode: SchemaGetter.transformOptional((value) => + Option.some(Option.getOrUndefined(value)), + ), + encode: SchemaGetter.omit(), + }), +); + +const isJson = Schema.is(Schema.Json); + +/** + * `HttpError.body`: sent when it's JSON, as it is without an error schema. + * A body decoded into something else, such as a class, stays behind, and + * decodes as `undefined`. + */ +const bodyAsJson = Schema.optionalKey(Schema.Unknown).pipe( + Schema.decodeTo(Schema.Unknown, { + decode: SchemaGetter.transformOptional((body) => + Option.some(Option.getOrUndefined(body)), + ), + encode: SchemaGetter.transformOptional((body) => + Option.filter(body, (value) => value !== undefined && isJson(value)), + ), + }), +); /** * The error a call fails with when its request gets no response: a DNS @@ -11,6 +67,10 @@ import * as Schema from "effect/Schema"; * parameters stay out of logs. * - `cause`: the underlying error from the platform's HTTP client. * + * It encodes to JSON, as its schema: `Schema.toCodecJson(Fetch.NetworkError)` + * sends `method` and `url`, and decodes a `NetworkError` whose `cause` is + * `undefined`. So an RPC or a server-rendered page can fail with it. + * * @example * ```ts * import * as Effect from "effect/Effect"; @@ -32,7 +92,7 @@ export class NetworkError extends Schema.TaggedError()( { method: Schema.String, url: Schema.String, - cause: Schema.Unknown, + cause: unknownNotSent, }, ) { /** `" : network error"`. */ @@ -51,7 +111,8 @@ export class NetworkError extends Schema.TaggedError()( * - `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. + * `` when the error is logged or passed to `JSON.stringify`. + * The error's JSON encoding leaves them out (see below). * - `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 @@ -64,6 +125,13 @@ export class NetworkError extends Schema.TaggedError()( * with `redirect: "manual"` or a conditional request answered with * `304 Not Modified`. Catch it by `status` if you expect one. * + * It encodes to JSON, as its schema, so an RPC or a server-rendered page + * can fail with it: `Schema.toCodecJson(Fetch.HttpError)` sends `method`, + * `url`, `status`, `text`, and `body` when it's JSON, and decodes an + * `HttpError`. The headers are never sent, and decode as empty. A `body` + * decoded into something other than JSON, such as a class, isn't sent + * either. + * * Use {@link HttpError.With} for the type of an `HttpError` whose `body` was * decoded with a known schema. To handle some statuses at a call, use * `Fetch.catchStatus` or `Fetch.optional`; to turn a status into your own @@ -94,9 +162,9 @@ export class HttpError extends Schema.TaggedError()("HttpError", { method: Schema.String, url: Schema.String, status: Schema.Finite, - headers: Schema.declare(Headers.isHeaders), + headers: headersNotSent, text: Schema.String, - body: Schema.Unknown, + body: bodyAsJson, }) { /** `" : HTTP "`. */ override get message(): string { @@ -150,6 +218,10 @@ export declare namespace HttpError { * `HttpClientError` when the body couldn't be read. * - `message`: a readable summary of `issue`. * + * It encodes to JSON, as its schema: `Schema.toCodecJson(Fetch.DecodeError)` + * sends every field but `issue`, and decodes a `DecodeError` whose `issue` is + * `undefined`. + * * 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. @@ -182,7 +254,7 @@ export class DecodeError extends Schema.TaggedError()( method: Schema.String, url: Schema.String, status: Schema.Finite, - issue: Schema.Unknown, + issue: unknownNotSent, message: Schema.String, }, ) {} diff --git a/src/Fetch.ts b/src/Fetch.ts index 56aaae2..894c856 100644 --- a/src/Fetch.ts +++ b/src/Fetch.ts @@ -33,6 +33,14 @@ export { NetworkError, } from "./Errors.js"; export type { FetchError } from "./Errors.js"; +export { errorCodec } from "./ErrorCodec.js"; +export type { + ErrorCodec, + ErrorCodecClient, + ErrorCodecErrors, + ErrorCodecOptions, + ErrorCodecSource, +} from "./ErrorCodec.js"; export type { AnySchema, Args, diff --git a/src/internal/response.ts b/src/internal/response.ts index 12c4ce9..ff1e814 100644 --- a/src/internal/response.ts +++ b/src/internal/response.ts @@ -21,7 +21,7 @@ const parseBody = (text: string): unknown => text.trim() === "" ? undefined : JSON.parse(text); /** The parsed JSON of an error body, or `undefined` when it's empty or isn't JSON. */ -const parseErrorBody = (text: string): unknown => { +export const parseErrorBody = (text: string): unknown => { try { return parseBody(text); } catch { @@ -29,7 +29,7 @@ const parseErrorBody = (text: string): unknown => { } }; -const readErrorBody = ( +export const readErrorBody = ( json: unknown, schema: EB | undefined, ): Effect.Effect => diff --git a/src/internal/statusErrors.ts b/src/internal/statusErrors.ts index ed009e4..4aa2226 100644 --- a/src/internal/statusErrors.ts +++ b/src/internal/statusErrors.ts @@ -81,19 +81,17 @@ export const joinStatusErrors = ( return Object.freeze(joined); }; -/** The `_tag` of each schema seen, or `null` for a schema without one. */ -const tags = new WeakMap(); +/** The literal `_tag` of each schema seen, or `null` for a schema without one. */ +const tags = new WeakMap< + AnySchema, + { readonly tag: string; readonly optional: boolean } | null +>(); -/** - * The literal `_tag` the schema's JSON form has, such as `"InvalidRole"` - * for a `Schema.TaggedError` class, or `undefined` without one. It's read - * from the encoded side, so it also works through `Schema.encodeKeys` and - * `Schema.tagDefaultOmit`. - */ -export const tagOf = (schema: AnySchema): string | undefined => { - let tag = tags.get(schema); - if (tag === undefined) { - tag = null; +/** The literal `_tag` property of the schema's JSON form, if it has one. */ +const tagProperty = (schema: AnySchema) => { + let found = tags.get(schema); + if (found === undefined) { + found = null; const encoded = SchemaAST.toEncoded(Schema.toCodecJson(schema).ast); if (SchemaAST.isObjects(encoded)) { const property = encoded.propertySignatures.find( @@ -104,12 +102,34 @@ export const tagOf = (schema: AnySchema): string | undefined => { SchemaAST.isLiteral(property.type) && typeof property.type.literal === "string" ) { - tag = property.type.literal; + found = { + tag: property.type.literal, + optional: SchemaAST.isOptional(property.type), + }; } } - tags.set(schema, tag); + tags.set(schema, found); } - return tag ?? undefined; + return found ?? undefined; +}; + +/** + * The literal `_tag` the schema's JSON form has, such as `"InvalidRole"` + * for a `Schema.TaggedError` class, even when it may be left out. + */ +export const tagOf = (schema: AnySchema): string | undefined => + tagProperty(schema)?.tag; + +/** + * The literal `_tag` the schema's JSON form always has: none when it may + * be left out, as with `Schema.tagDefaultOmit`, whose JSON can then be + * any other schema's. + */ +export const sentTagOf = (schema: AnySchema): string | undefined => { + const property = tagProperty(schema); + return property === undefined || property.optional + ? undefined + : property.tag; }; /** diff --git a/test/errorCodec.test.ts b/test/errorCodec.test.ts new file mode 100644 index 0000000..5900978 --- /dev/null +++ b/test/errorCodec.test.ts @@ -0,0 +1,779 @@ +import { it } from "@effect/vitest"; +import * as Effect from "effect/Effect"; +import * as Exit from "effect/Exit"; +import * as Headers from "effect/http/Headers"; +import * as Option from "effect/Option"; +import * as Rpc from "effect/rpc/Rpc"; +import * as Schema from "effect/Schema"; +import * as SchemaTransformation from "effect/SchemaTransformation"; + +import { describe, expect } from "vitest"; + +import { Fetch } from "../src/index.js"; +import { TimeoutError } from "../src/plugins/index.js"; +import { setup } from "./utils/client.js"; +import { failure, type Step } from "./utils/mockClient.js"; +import { reply } from "./utils/reply.js"; + +class ApiProblem extends Schema.Class("ApiProblem")({ + code: Schema.String, +}) { + get retryable() { + return this.code === "rate_limited"; + } +} + +class TodoNotFound extends Schema.TaggedError()("TodoNotFound", { + id: Schema.Finite, +}) {} + +const Todo = Schema.Struct({ id: Schema.Finite, title: Schema.String }); +const getTodo = Fetch.endpoint("GET /todos/:id", { output: Todo }); + +const config = { + defaultError: ApiProblem, + statusErrors: { 404: TodoNotFound }, +} as const; + +class Api extends Fetch.Service()("Api", { + baseUrl: "https://api.test", + ...config, +}) {} + +/** Encodes `value` to JSON text, as an RPC or a page would send it. */ +const send =
(schema: Schema.Codec, value: A): string => + JSON.stringify(Schema.encodeUnknownSync(Schema.toCodecJson(schema))(value)); + +/** Decodes what `send` sent. */ +const receive = (schema: Schema.Codec, wire: string): A => + Schema.decodeUnknownSync(Schema.toCodecJson(schema))(JSON.parse(wire)); + +/** Sends `value` with `schema`, and decodes what was sent. */ +const roundTrip = (schema: Schema.Top, value: unknown): unknown => { + const codec = schema as Schema.Codec; + return receive(codec, send(codec, value)); +}; + +/** Runs `f` with `a` and `b`, then with them the other way round. */ +const inBothOrders = ( + a: A, + b: B, + f: (first: A | B, second: A | B) => void, +) => { + f(a, b); + f(b, a); +}; + +/** The error `getTodo` fails with when the server answers with `step`. */ +const failWith = (step: Step) => + Effect.gen(function* () { + const { api } = yield* setup([step], config); + const todos = api.bind(getTodo); + return { todos, error: yield* Effect.flip(todos({ params: { id: 9 } })) }; + }); + +describe("Fetch.errorCodec", () => { + it.effect("sends an HttpError and decodes its body again", () => + Effect.gen(function* () { + const { todos, error } = yield* failWith( + reply.json( + { code: "rate_limited" }, + { status: 429, headers: { "set-cookie": "session=secret" } }, + ), + ); + const schema = Fetch.errorCodec(todos); + const wire = send(schema, error); + expect(JSON.parse(wire)).toStrictEqual({ + _tag: "HttpError", + method: "GET", + url: "https://api.test/todos/9", + status: 429, + text: '{"code":"rate_limited"}', + }); + expect(wire).not.toContain("secret"); + const back = receive(schema, wire); + expect(back).toBeInstanceOf(Fetch.HttpError); + const http = back as Fetch.HttpError.With; + expect(http.body).toBeInstanceOf(ApiProblem); + expect(http.body?.retryable).toBe(true); + expect(Object.keys(http.headers)).toStrictEqual([]); + expect(http.message).toBe("GET https://api.test/todos/9: HTTP 429"); + }), + ); + + it.effect( + "decodes a body that doesn't match as undefined, as the call did", + () => + Effect.gen(function* () { + const { todos, error } = yield* failWith( + reply.text("Bad gateway", { status: 502 }), + ); + const back = receive( + Fetch.errorCodec(todos), + send(Fetch.errorCodec(todos), error), + ) as Fetch.HttpError; + expect(back.body).toBeUndefined(); + expect(back.text).toBe("Bad gateway"); + }), + ); + + it.effect("sends the statusErrors errors as their schemas encode them", () => + Effect.gen(function* () { + const { todos, error } = yield* failWith( + reply.json({ id: 9 }, { status: 404 }), + ); + expect(error).toBeInstanceOf(TodoNotFound); + const back = receive( + Fetch.errorCodec(todos), + send(Fetch.errorCodec(todos), error), + ); + expect(back).toBeInstanceOf(TodoNotFound); + expect(back).toMatchObject({ id: 9 }); + }), + ); + + it.effect("sends a NetworkError without its cause", () => + Effect.gen(function* () { + const { todos, error } = yield* failWith(failure()); + const wire = send(Fetch.errorCodec(todos), error); + expect(JSON.parse(wire)).toStrictEqual({ + _tag: "NetworkError", + method: "GET", + url: "https://api.test/todos/9", + }); + const back = receive(Fetch.errorCodec(todos), wire); + expect(back).toBeInstanceOf(Fetch.NetworkError); + }), + ); + + it.effect("sends a DecodeError without its issue", () => + Effect.gen(function* () { + const { todos, error } = yield* failWith(reply.json({ id: "nine" })); + expect(error).toBeInstanceOf(Fetch.DecodeError); + const wire = send(Fetch.errorCodec(todos), error); + expect(JSON.parse(wire)).not.toHaveProperty("issue"); + const back = receive(Fetch.errorCodec(todos), wire); + expect(back).toBeInstanceOf(Fetch.DecodeError); + expect((back as Fetch.DecodeError).issue).toBeUndefined(); + }), + ); + + it.effect("reads a definition's schemas with its client's", () => + Effect.gen(function* () { + const { error } = yield* failWith( + reply.json({ code: "rate_limited" }, { status: 429 }), + ); + const schema = Fetch.errorCodec(getTodo, { client: Api }); + const back = receive(schema, send(schema, error)); + expect((back as Fetch.HttpError.With).body).toBeInstanceOf( + ApiProblem, + ); + const notFound = new TodoNotFound({ id: 9 }); + expect(receive(schema, send(schema, notFound))).toBeInstanceOf( + TodoNotFound, + ); + }), + ); + + it.effect("takes the schemas themselves, for the plain methods", () => + Effect.gen(function* () { + const { error } = yield* failWith( + reply.json({ code: "down" }, { status: 503 }), + ); + const schema = Fetch.errorCodec({ + error: ApiProblem, + statusErrors: { 404: TodoNotFound }, + }); + const back = receive(schema, send(schema, error)); + expect((back as Fetch.HttpError.With).body).toBeInstanceOf( + ApiProblem, + ); + }), + ); + + it("sends a plain HttpError body as JSON without an error schema", () => { + const schema = Fetch.errorCodec({}); + const error = new Fetch.HttpError({ + method: "GET", + url: "/x", + status: 500, + headers: Headers.empty, + text: '{"a":1}', + body: { a: 1 }, + }); + expect( + (receive(schema, send(schema, error)) as Fetch.HttpError).body, + ).toStrictEqual({ a: 1 }); + }); + + it("adds the errors given, such as a plugin's", () => { + const timedOut = new TimeoutError({ + method: "GET", + url: "/x", + duration: "5 seconds", + }); + expect(() => send(Fetch.errorCodec({}) as never, timedOut)).toThrow(); + const schema = Fetch.errorCodec({}, { errors: [TimeoutError] }); + expect(receive(schema, send(schema, timedOut))).toBeInstanceOf( + TimeoutError, + ); + }); + + it("keeps schemas without a _tag from taking other errors", () => { + const Loose = Schema.Struct({ message: Schema.String }); + const schema = Fetch.errorCodec( + { statusErrors: { 400: Loose, 404: TodoNotFound } }, + { errors: [TimeoutError] }, + ); + expect( + receive(schema, send(schema, new TodoNotFound({ id: 9 }))), + ).toBeInstanceOf(TodoNotFound); + const timedOut = new TimeoutError({ + method: "GET", + url: "/x", + duration: "5 seconds", + }); + expect(receive(schema, send(schema, timedOut))).toBeInstanceOf( + TimeoutError, + ); + expect(receive(schema, send(schema, { message: "m" }))).toStrictEqual({ + message: "m", + }); + }); + + it("tells schemas without a _tag apart, even with the same fields", () => { + class Invalid extends Schema.Class("Invalid")({ + code: Schema.String, + }) {} + class Conflict extends Schema.Class("Conflict")({ + code: Schema.String, + }) {} + inBothOrders(Invalid, Conflict, (a, b) => { + const schema = Fetch.errorCodec({ statusErrors: { 400: a, 409: b } }); + const wire = send(schema, new Conflict({ code: "c" })); + expect(JSON.parse(wire)).toStrictEqual({ + _tag: "effetch/UntaggedError", + identifier: "Conflict", + error: { code: "c" }, + }); + expect(receive(schema, wire)).toBeInstanceOf(Conflict); + expect(roundTrip(schema, new Invalid({ code: "i" }))).toBeInstanceOf( + Invalid, + ); + }); + }); + + it("sends a struct without an identifier by its place among those", () => { + const Short = Schema.Struct({ message: Schema.String }); + const Long = Schema.Struct({ message: Schema.String, id: Schema.Finite }); + const schema = Fetch.errorCodec( + { statusErrors: { 400: Short, 404: TodoNotFound, 409: Long } }, + { errors: [TimeoutError] }, + ); + expect(JSON.parse(send(schema, { message: "m", id: 1 }))).toStrictEqual({ + _tag: "effetch/UntaggedError", + index: 1, + error: { message: "m", id: 1 }, + }); + inBothOrders(Short, Long, (a, b) => { + const schema = Fetch.errorCodec({ statusErrors: { 400: a, 409: b } }); + expect(roundTrip(schema, { message: "m", id: 1 })).toStrictEqual({ + message: "m", + id: 1, + }); + expect(roundTrip(schema, { message: "m" })).toStrictEqual({ + message: "m", + }); + // More fields than either takes: it goes as the one that keeps most. + const extra = { message: "m", id: 1, extra: true }; + expect(roundTrip(schema, extra)).toStrictEqual({ + message: "m", + id: 1, + }); + }); + }); + + it("sends a struct as the schema it was made with, not one with the same JSON", () => { + inBothOrders( + Schema.Struct({ at: Schema.String }), + Schema.Struct({ at: Schema.Date }), + (a, b) => { + const schema = Fetch.errorCodec({ + statusErrors: { 400: a, 409: b }, + }); + const back = roundTrip(schema, { at: new Date(0) }); + expect(back).toStrictEqual({ at: new Date(0) }); + expect(roundTrip(schema, { at: "noon" })).toStrictEqual({ + at: "noon", + }); + }, + ); + inBothOrders( + Schema.Struct({ message: Schema.String, request_id: Schema.String }), + Schema.Struct({ + message: Schema.String, + requestId: Schema.String, + }).pipe(Schema.encodeKeys({ requestId: "request_id" })), + (a, b) => { + const schema = Fetch.errorCodec({ + statusErrors: { 400: a, 409: b }, + }); + expect( + roundTrip(schema, { message: "m", requestId: "r" }), + ).toStrictEqual({ message: "m", requestId: "r" }); + expect( + roundTrip(schema, { message: "m", request_id: "r" }), + ).toStrictEqual({ message: "m", request_id: "r" }); + }, + ); + }); + + it("doesn't send an error as a schema that drops some of its fields", () => { + const Message = Schema.Struct({ message: Schema.String }); + inBothOrders( + Schema.Union([ + Schema.Struct({ message: Schema.String, id: Schema.Finite }), + Schema.Struct({ code: Schema.String }), + ]), + Message, + (a, b) => { + const schema = Fetch.errorCodec({ + statusErrors: { 400: a, 409: b }, + }); + expect(roundTrip(schema, { message: "m", id: 1 })).toStrictEqual({ + message: "m", + id: 1, + }); + expect(roundTrip(schema, { code: "c" })).toStrictEqual({ + code: "c", + }); + }, + ); + inBothOrders( + Schema.Record(Schema.String, Schema.String), + Message, + (a, b) => { + const schema = Fetch.errorCodec({ + statusErrors: { 400: a, 409: b }, + }); + const fields = { message: "m", other: "o" }; + expect(roundTrip(schema, fields)).toStrictEqual(fields); + }, + ); + class Conflict extends Schema.Class("Conflict")({ + message: Schema.String, + id: Schema.Finite, + }) {} + inBothOrders(Message, Conflict, (a, b) => { + const schema = Fetch.errorCodec({ statusErrors: { 400: a, 409: b } }); + const back = roundTrip(schema, new Conflict({ message: "m", id: 1 })); + expect(back).toBeInstanceOf(Conflict); + expect(back).toMatchObject({ id: 1 }); + }); + }); + + it("sends the members of a union as themselves", () => { + class Gone extends Schema.TaggedError()("Gone", { + id: Schema.Finite, + }) {} + inBothOrders( + Schema.Union([TodoNotFound, Gone]), + Schema.Struct({ id: Schema.Finite }), + (a, b) => { + const schema = Fetch.errorCodec({ + statusErrors: { 404: a, 409: b }, + }); + const wire = send(schema, new Gone({ id: 1 })); + expect(JSON.parse(wire)).toStrictEqual({ _tag: "Gone", id: 1 }); + expect(receive(schema, wire)).toBeInstanceOf(Gone); + expect(roundTrip(schema, { id: 1 })).toStrictEqual({ id: 1 }); + }, + ); + // A union of its own, with a check or an identifier, stays one. + const Problem = Schema.Union([ + Schema.Struct({ code: Schema.String }), + Schema.Struct({ message: Schema.String }), + ]).annotate({ identifier: "Problem" }); + const schema = Fetch.errorCodec({ + statusErrors: { 400: Problem, 409: Problem, 422: [Problem] }, + }); + expect(JSON.parse(send(schema, { code: "c" }))).toStrictEqual({ + _tag: "effetch/UntaggedError", + identifier: "Problem", + error: { code: "c" }, + }); + }); + + it("sends a class as the nearest class listed", () => { + class Base extends Schema.Class("Base")({ a: Schema.String }) {} + class Mid extends Base.extend("Mid")({ b: Schema.String }) {} + class Sub extends Mid {} + class Other extends Schema.Class("Other")({ + c: Schema.String, + }) {} + const mid = new Mid({ a: "a", b: "b" }); + const check = (schema: Schema.Top) => { + const back = roundTrip(schema, mid); + expect(back).toBeInstanceOf(Mid); + expect(back).toMatchObject({ a: "a", b: "b" }); + expect(roundTrip(schema, new Sub({ a: "a", b: "b" }))).toBeInstanceOf( + Mid, + ); + expect(roundTrip(schema, new Base({ a: "a" }))).not.toBeInstanceOf( + Mid, + ); + }; + inBothOrders(Base, Mid, (a, b) => { + check(Fetch.errorCodec({ statusErrors: { 400: a, 409: b } })); + }); + inBothOrders(Base, Mid.annotate({ description: "A mid" }), (a, b) => { + check(Fetch.errorCodec({ statusErrors: { 400: a, 409: b } })); + }); + inBothOrders(Base, Schema.Union([Mid, Other]), (a, b) => { + check(Fetch.errorCodec({ statusErrors: { 400: a, 409: b } })); + }); + // A struct with the same fields is no class. + inBothOrders( + Schema.Struct({ a: Schema.String, b: Schema.String }), + Mid, + (a, b) => { + const schema = Fetch.errorCodec({ + statusErrors: { 400: a, 409: b }, + }); + expect(roundTrip(schema, mid)).toBeInstanceOf(Mid); + expect(roundTrip(schema, { a: "a", b: "b" })).not.toBeInstanceOf( + Mid, + ); + }, + ); + }); + + it("tells apart errors whose _tag isn't sent", () => { + const Invalid = Schema.Struct({ + _tag: Schema.tagDefaultOmit("Invalid"), + code: Schema.String, + }); + const Conflict = Schema.Struct({ + _tag: Schema.tagDefaultOmit("Conflict"), + code: Schema.String, + }); + inBothOrders(Invalid, Conflict, (a, b) => { + const schema = Fetch.errorCodec({ statusErrors: { 400: a, 409: b } }); + const wire = send(schema, { _tag: "Conflict" as const, code: "c" }); + expect(JSON.parse(wire)).toStrictEqual({ + _tag: "effetch/UntaggedError", + tag: "Conflict", + error: { code: "c" }, + }); + expect(receive(schema, wire)).toStrictEqual({ + _tag: "Conflict", + code: "c", + }); + }); + // A class with the tag's name is another error. + class ConflictClass extends Schema.Class("Conflict")({ + code: Schema.String, + }) {} + inBothOrders(Conflict, ConflictClass, (a, b) => { + const schema = Fetch.errorCodec({ statusErrors: { 400: a, 409: b } }); + expect( + roundTrip(schema, new ConflictClass({ code: "c" })), + ).toBeInstanceOf(ConflictClass); + expect( + roundTrip(schema, { _tag: "Conflict" as const, code: "c" }), + ).not.toBeInstanceOf(ConflictClass); + }); + }); + + it("tells apart schemas with the same identifier by their place", () => { + class Mid extends Schema.Class("Mid")({ a: Schema.String }) {} + inBothOrders(Mid, Mid.annotate({ description: "A mid" }), (a, b) => { + const schema = Fetch.errorCodec({ statusErrors: { 400: a, 409: b } }); + expect(roundTrip(schema, new Mid({ a: "a" }))).toBeInstanceOf(Mid); + }); + inBothOrders(Mid, Schema.toType(Mid), (a, b) => { + const schema = Fetch.errorCodec({ statusErrors: { 409: [a, b] } }); + expect(roundTrip(schema, new Mid({ a: "a" }))).toBeInstanceOf(Mid); + }); + const First = class ApiError extends Schema.Class("ApiError")({ + message: Schema.String, + }) {}; + const Second = class ApiError extends Schema.Class("ApiError")({ + message: Schema.String, + code: Schema.optional(Schema.String), + }) {}; + inBothOrders(First, Second, (a, b) => { + const schema = Fetch.errorCodec({ statusErrors: { 400: a, 409: b } }); + const wire = JSON.parse( + send(schema as never, new Second({ message: "m" })), + ); + expect(wire).not.toHaveProperty("identifier"); + expect(wire).toHaveProperty("index"); + expect(roundTrip(schema, new First({ message: "m" }))).toBeInstanceOf( + First, + ); + expect(roundTrip(schema, new Second({ message: "m" }))).toBeInstanceOf( + Second, + ); + expect( + roundTrip(schema, new Second({ message: "m", code: "c" })), + ).toBeInstanceOf(Second); + }); + const Invalid = Schema.Struct({ + _tag: Schema.tagDefaultOmit("Invalid"), + code: Schema.String, + }); + const InvalidField = Schema.Struct({ + _tag: Schema.tagDefaultOmit("Invalid"), + code: Schema.String, + field: Schema.String, + }); + inBothOrders(Invalid, InvalidField, (a, b) => { + const schema = Fetch.errorCodec({ statusErrors: { 400: a, 422: b } }); + const field = { _tag: "Invalid" as const, code: "c", field: "f" }; + expect(roundTrip(schema, field)).toStrictEqual(field); + const code = { _tag: "Invalid" as const, code: "c" }; + expect(roundTrip(schema, code)).toStrictEqual(code); + }); + }); + + it("builds from an endpoint and a client that list copies of a class", () => { + class Conflict extends Schema.Class("Conflict")({ + code: Schema.String, + }) {} + class Shop extends Fetch.Service()("Shop", { + baseUrl: "https://api.test", + statusErrors: { 409: Conflict }, + }) {} + const order = Fetch.endpoint("POST /orders", { + statusErrors: { 409: Conflict.annotate({ title: "Conflict" }) }, + }); + const schema = Fetch.errorCodec(order, { client: Shop }); + expect(roundTrip(schema, new Conflict({ code: "c" }))).toBeInstanceOf( + Conflict, + ); + }); + + it("sends an error made by hand with fields to spare", () => { + const Conflict = Schema.Struct({ + _tag: Schema.tagDefaultOmit("Conflict"), + code: Schema.String, + }); + const Named = Schema.Struct({ + _tag: Schema.String, + message: Schema.String, + }); + const schema = Fetch.errorCodec({ + statusErrors: { 400: Named, 409: Conflict }, + }); + expect( + roundTrip(schema, { _tag: "Conflict", code: "c", extra: 1 }), + ).toStrictEqual({ _tag: "Conflict", code: "c" }); + expect( + roundTrip(schema, { _tag: "Named", message: "m", extra: 1 }), + ).toStrictEqual({ _tag: "Named", message: "m" }); + }); + + it("puts a union's tagged members after the tagged schemas listed", () => { + const Message = Schema.Struct({ message: Schema.String }); + const ShortNotFound = Schema.TaggedStruct("NotFound", { + id: Schema.Finite, + }); + const LongNotFound = Schema.TaggedStruct("NotFound", { + id: Schema.Finite, + name: Schema.String, + }); + const schema = Fetch.errorCodec({ + statusErrors: { + 400: Schema.Union([ShortNotFound, Message]), + 409: LongNotFound, + }, + }); + const long = { _tag: "NotFound" as const, id: 1, name: "n" }; + expect(roundTrip(schema, long)).toStrictEqual(long); + const short = { _tag: "NotFound" as const, id: 1 }; + expect(roundTrip(schema, short)).toStrictEqual(short); + class First extends Schema.TaggedError()("NotFound", { + id: Schema.Finite, + }) {} + class Second extends Schema.TaggedError()("NotFound", { + id: Schema.Finite, + }) {} + const classes = Fetch.errorCodec({ + statusErrors: { 400: Schema.Union([First, Message]), 409: Second }, + }); + expect(roundTrip(classes, new Second({ id: 1 }))).toBeInstanceOf(Second); + }); + + it("decodes an error by its identifier, wherever each side lists it", () => { + class Invalid extends Schema.Class("Invalid")({ + field: Schema.String, + }) {} + class Conflict extends Schema.Class("Conflict")({ + message: Schema.String, + }) {} + class Gone extends Schema.Class("Gone")({ + message: Schema.String, + }) {} + // An older client lists fewer errors, elsewhere, than the server. + const older = Fetch.errorCodec({ + statusErrors: { 409: [Gone, Conflict] }, + }); + const newer = Fetch.errorCodec( + { statusErrors: { 400: Invalid, 409: Conflict, 410: Gone } }, + { errors: [TimeoutError] }, + ); + expect( + receive(older, send(newer, new Conflict({ message: "m" }))), + ).toBeInstanceOf(Conflict); + expect( + receive(older, send(newer, new Gone({ message: "m" }))), + ).toBeInstanceOf(Gone); + // An error the older client doesn't know fails to decode, rather than + // decoding as another. + expect(() => + receive(older, send(newer, new Invalid({ field: "f" }))), + ).toThrow('no error schema has the identifier "Invalid"'); + }); + + it("decodes an error with only the schema it names", () => { + const Plain = Schema.Struct({ message: Schema.String }); + const Throws = Schema.Struct({ + message: Schema.String.pipe( + Schema.decodeTo( + Schema.String, + SchemaTransformation.transform({ + decode: () => { + throw new Error("decoded with the wrong schema"); + }, + encode: (message) => message, + }), + ), + ), + only: Schema.optionalKey(Schema.String), + }); + const schema = Fetch.errorCodec({ + statusErrors: { 400: Plain, 409: Throws }, + }); + expect(roundTrip(schema, { message: "m" })).toStrictEqual({ + message: "m", + }); + }); + + it("says why an error without a _tag doesn't decode", () => { + class Conflict extends Schema.Class("Conflict")({ + message: Schema.String, + }) {} + const schema = Fetch.errorCodec({ + statusErrors: { + 400: Schema.Struct({ message: Schema.String }), + 409: Conflict, + }, + }); + const decode = (wire: object) => () => + Schema.decodeUnknownSync(Schema.toCodecJson(schema))({ + _tag: "effetch/UntaggedError", + error: { message: "m" }, + ...wire, + }); + expect(decode({ tag: "Conflict" })).toThrow( + 'no error schema has the _tag "Conflict"', + ); + expect(decode({ index: 1 })).toThrow( + "no error schema without an identifier is at index 1", + ); + expect(decode({})).toThrow( + "an error without a _tag goes with an identifier, a tag or an index", + ); + expect(decode({ identifier: "Conflict", index: 0 })).toThrow( + "an error without a _tag goes with an identifier, a tag or an index", + ); + expect(() => send(schema as never, { code: 1 })).toThrow( + "Expected an error one of the error schemas takes", + ); + }); + + it("passes the parse options to the error's schema", () => { + const Problem = Schema.Struct({ message: Schema.String }); + const schema = Fetch.errorCodec({ statusErrors: { 400: Problem } }); + const wire = { + _tag: "effetch/UntaggedError", + index: 0, + error: { message: "m", extra: 1 }, + }; + expect(() => + Schema.decodeUnknownSync(Schema.toCodecJson(schema))(wire, { + onExcessProperty: "error", + }), + ).toThrow(/extra/); + expect(() => + Schema.decodeUnknownSync(Schema.toCodecJson(schema))({ + ...wire, + error: { message: 1 }, + }), + ).toThrow(/\["error"\]\["message"\]/); + expect(() => + Schema.encodeUnknownSync(Schema.toCodecJson(schema))( + { message: "m", extra: 1 }, + { onExcessProperty: "error" }, + ), + ).toThrow(/extra/); + }); + + it("reads statusErrors as calls do", () => { + const schema = Fetch.errorCodec({ + statusErrors: { + 404: undefined, + notAStatus: Schema.Struct({ method: Schema.String }), + } as unknown as Fetch.StatusErrorMap, + }); + const timedOut = new TimeoutError({ + method: "GET", + url: "/x", + duration: "1 second", + }); + // Neither entry is a schema calls try, so neither is a member. + expect(() => send(schema as never, timedOut)).toThrow(); + }); + + it("keeps an HttpError from a loose status error schema", () => { + const Loose = Schema.Struct({ status: Schema.Finite }); + const schema = Fetch.errorCodec({ statusErrors: { 409: Loose } }); + const error = new Fetch.HttpError({ + method: "GET", + url: "/x", + status: 409, + headers: Headers.empty, + text: "", + body: undefined, + }); + expect(receive(schema, send(schema, error))).toBeInstanceOf( + Fetch.HttpError, + ); + }); + + it.effect("crosses an RPC as its error", () => + Effect.gen(function* () { + const { todos, error } = yield* failWith( + reply.json({ code: "rate_limited" }, { status: 429 }), + ); + const GetTodo = Rpc.make("GetTodo", { + success: Todo, + error: Fetch.errorCodec(todos, { errors: [TimeoutError] }), + }); + // What RpcSerialization.json does with a result. + const codec = Schema.toCodecJson(Rpc.exitSchema(GetTodo)); + const wire = JSON.stringify( + Schema.encodeUnknownSync(codec)(Exit.fail(error)), + ); + const exit = Schema.decodeUnknownSync(codec)( + JSON.parse(wire), + ) as Exit.Exit; + const back = Option.getOrThrow(Exit.findErrorOption(exit)); + expect(back).toBeInstanceOf(Fetch.HttpError); + expect((back as Fetch.HttpError.With).body).toBeInstanceOf( + ApiProblem, + ); + }), + ); +}); diff --git a/test/errors.test.ts b/test/errors.test.ts index a98ed40..f5c26e8 100644 --- a/test/errors.test.ts +++ b/test/errors.test.ts @@ -1,4 +1,8 @@ +import * as Exit from "effect/Exit"; import * as Headers from "effect/http/Headers"; +import * as Option from "effect/Option"; +import * as Rpc from "effect/rpc/Rpc"; +import * as Schema from "effect/Schema"; import { describe, expect, it } from "vitest"; @@ -69,4 +73,171 @@ describe("errors", () => { expect(isFetchError(new Error("x"))).toBe(false); expect(isFetchError({ _tag: "HttpError" })).toBe(false); }); + + describe("as JSON", () => { + // What `Schema.toCodecJson` makes of each class: what an RPC's JSON + // serialization and effetch-query's server rendering use. + const roundTrip = (schema: Schema.Codec, value: A) => { + const codec = Schema.toCodecJson(schema); + const wire = JSON.stringify(Schema.encodeUnknownSync(codec)(value)); + return { + wire, + back: Schema.decodeUnknownSync(codec)(JSON.parse(wire)), + }; + }; + + it("send an HttpError without its headers", () => { + const { wire, back } = roundTrip(HttpError, httpError()); + expect(JSON.parse(wire)).toStrictEqual({ + _tag: "HttpError", + method: "GET", + url: "https://api.test/me", + status: 401, + text: "{}", + body: {}, + }); + expect(wire).not.toContain("secret"); + expect(wire).not.toContain("content-type"); + expect(back).toBeInstanceOf(HttpError); + expect(isFetchError(back)).toBe(true); + expect(back.message).toBe("GET https://api.test/me: HTTP 401"); + expect(back.body).toStrictEqual({}); + expect(Headers.isHeaders(back.headers)).toBe(true); + expect(Object.keys(back.headers)).toStrictEqual([]); + }); + + it("send an HttpError body only when it's JSON", () => { + class Problem extends Schema.Class("Problem")({ + code: Schema.String, + }) {} + const withBody = (body: unknown) => + new HttpError({ + method: "GET", + url: "/x", + status: 500, + headers: Headers.empty, + text: '{"code":"down"}', + body, + }); + for (const body of [undefined, new Problem({ code: "down" })]) { + const { wire, back } = roundTrip(HttpError, withBody(body)); + expect(JSON.parse(wire)).not.toHaveProperty("body"); + expect(back.body).toBeUndefined(); + expect(back.text).toBe('{"code":"down"}'); + } + expect( + roundTrip(HttpError, withBody(["a", 1, null])).back.body, + ).toStrictEqual(["a", 1, null]); + }); + + it("send a NetworkError without its cause", () => { + const { wire, back } = roundTrip( + NetworkError, + new NetworkError({ + method: "GET", + url: "/x", + cause: new TypeError("fetch failed"), + }), + ); + expect(JSON.parse(wire)).toStrictEqual({ + _tag: "NetworkError", + method: "GET", + url: "/x", + }); + expect(back).toBeInstanceOf(NetworkError); + expect(back.cause).toBeUndefined(); + expect(back.message).toBe("GET /x: network error"); + }); + + it("send a DecodeError without its issue", () => { + const { wire, back } = roundTrip( + DecodeError, + new DecodeError({ + method: "GET", + url: "/x", + status: 200, + issue: new SyntaxError("Unexpected token"), + message: "Unexpected token", + }), + ); + expect(JSON.parse(wire)).toStrictEqual({ + _tag: "DecodeError", + method: "GET", + url: "/x", + status: 200, + message: "Unexpected token", + }); + expect(back).toBeInstanceOf(DecodeError); + expect(back.issue).toBeUndefined(); + expect(back.message).toBe("Unexpected token"); + }); + + it("never take headers from what's decoded", () => { + const decode = (schema: Schema.Codec, input: unknown) => + Schema.decodeUnknownSync(Schema.toCodecJson(schema))(input); + const http = decode(HttpError, { + _tag: "HttpError", + method: "GET", + url: "/x", + status: 500, + text: "", + headers: { "set-cookie": "session=secret" }, + }); + expect(Object.keys(http.headers)).toStrictEqual([]); + expect(http.body).toBeUndefined(); + expect( + decode(NetworkError, { + _tag: "NetworkError", + method: "GET", + url: "/x", + }).cause, + ).toBeUndefined(); + }); + + it("still decode values built in memory, as before", () => { + // Their own schema, not its JSON form: a copy of an error decodes + // whatever its body, and keeps its headers, cause and issue. + class Problem extends Schema.Class("Problem")({ + code: Schema.String, + }) {} + for (const body of [undefined, new Problem({ code: "x" })]) { + const decoded = Schema.decodeUnknownSync(HttpError)({ + ...httpError(), + body, + }); + expect(decoded.body).toBe(body); + expect(decoded.headers["content-type"]).toBe("application/json"); + } + const cause = new TypeError("fetch failed"); + expect( + Schema.decodeUnknownSync(NetworkError)({ + _tag: "NetworkError", + method: "GET", + url: "/x", + cause, + }).cause, + ).toBe(cause); + }); + + it("cross an RPC as its error", () => { + const GetMe = Rpc.make("GetMe", { + error: Schema.Union([HttpError, NetworkError, DecodeError]), + }); + // What RpcSerialization.json does with a result. + const codec = Schema.toCodecJson(Rpc.exitSchema(GetMe)); + const wire = JSON.stringify( + Schema.encodeUnknownSync(codec)(Exit.fail(httpError())), + ); + expect(wire).not.toContain("secret"); + const error = Exit.findErrorOption( + Schema.decodeUnknownSync(codec)(JSON.parse(wire)) as Exit.Exit< + void, + HttpError | NetworkError | DecodeError + >, + ); + expect(Option.isSome(error)).toBe(true); + expect(Option.getOrThrow(error)).toBeInstanceOf(HttpError); + expect(Option.getOrThrow(error)).toMatchObject({ status: 401 }); + }); + }); }); diff --git a/test/example-streams.test.ts b/test/example-streams.test.ts deleted file mode 100644 index ba38f3b..0000000 --- a/test/example-streams.test.ts +++ /dev/null @@ -1,98 +0,0 @@ -import { it } from "@effect/vitest"; -import * as Effect from "effect/Effect"; -import * as Layer from "effect/Layer"; -import * as Option from "effect/Option"; -import * as Schema from "effect/Schema"; - -import { describe, expect } from "vitest"; - -import { - Api, - StreamsApi, - allUsers, - complete, - countUsers, - exportUsers, - followJob, - jobEvents, - listUsers, -} from "../examples/streams.js"; -import { Fetch } from "../src/index.js"; -import { FetchTest } from "../src/test/index.js"; - -const completions = Fetch.endpoint("POST /completions", { - input: Schema.Struct({ prompt: Schema.String }), - output: Fetch.text(), - stream: "sse", -}); - -const Backend = FetchTest.layer([ - FetchTest.respond(jobEvents, () => - Effect.succeed([ - { data: { percent: 50, step: "build" } }, - { data: { percent: 100, step: "deploy" } }, - // Not read: the job is done. - { data: { percent: 100, step: "extra" } }, - ]), - ), - FetchTest.respond(exportUsers, () => - Effect.succeed([ - { id: 1, email: "a@example.com" }, - { id: 2, email: "b@example.com" }, - ]), - ), - FetchTest.respond(completions, ({ body }) => - Effect.succeed([ - { data: JSON.stringify({ text: "Echo: " }) }, - { data: JSON.stringify({ text: body.prompt }) }, - { data: "[DONE]" }, - ]), - ), - FetchTest.respond(listUsers, ({ query }) => - Effect.succeed( - // The cursor arrives decoded once, as it was before encoding. - query.cursor === "YQ==" - ? FetchTest.reply(200, [{ id: 2, email: "b@example.com" }]) - : FetchTest.reply(200, [{ id: 1, email: "a@example.com" }], { - headers: { link: '; rel="next"' }, - }), - ), - ), -]); - -const TestLive = StreamsApi.layer.pipe( - Layer.provideMerge(Api.layer), - Layer.provide(Backend), -); - -// Runs `examples/streams.ts` against a fake backend, so it keeps working, -// not only compiling. -describe("examples/streams.ts", () => { - it.effect("follows a job until it's done", () => - Effect.gen(function* () { - const last = yield* followJob("7"); - expect(Option.map(last, (event) => event.data.step)).toEqual( - Option.some("deploy"), - ); - }).pipe(Effect.provide(TestLive)), - ); - - it.effect("counts an export's users", () => - Effect.gen(function* () { - expect(yield* countUsers).toBe(2); - }).pipe(Effect.provide(TestLive)), - ); - - it.effect("reads an answer up to its sentinel", () => - Effect.gen(function* () { - expect(yield* complete("Hi")).toBe("Echo: Hi"); - }).pipe(Effect.provide(TestLive)), - ); - - it.effect("follows the Link header", () => - Effect.gen(function* () { - const users = yield* allUsers; - expect(users.map((user) => user.id)).toEqual([1, 2]); - }).pipe(Effect.provide(TestLive)), - ); -}); diff --git a/test/example-testing.test.ts b/test/example-testing.test.ts deleted file mode 100644 index f6044be..0000000 --- a/test/example-testing.test.ts +++ /dev/null @@ -1,14 +0,0 @@ -import { it } from "@effect/vitest"; -import type * as Effect from "effect/Effect"; - -import { describe } from "vitest"; - -import * as Testing from "../examples/testing.js"; - -// Runs `examples/testing.ts`, so its tests keep passing, not only compiling. -describe("examples/testing.ts", () => { - const tests: Record> = Testing; - for (const [name, test] of Object.entries(tests)) { - it.effect(name, () => test); - } -}); diff --git a/test/exports.test.ts b/test/exports.test.ts index af57dd6..a07048e 100644 --- a/test/exports.test.ts +++ b/test/exports.test.ts @@ -17,6 +17,7 @@ describe("public entry points", () => { "bytes", "catchStatus", "endpoint", + "errorCodec", "isFetchError", "isService", "make", diff --git a/test/types/errorCodec.test-d.ts b/test/types/errorCodec.test-d.ts new file mode 100644 index 0000000..d5b9046 --- /dev/null +++ b/test/types/errorCodec.test-d.ts @@ -0,0 +1,155 @@ +// @effect-diagnostics floatingEffect:off + +import type * as Effect from "effect/Effect"; +import * as Rpc from "effect/rpc/Rpc"; +import * as Schema from "effect/Schema"; +import type * as Stream from "effect/Stream"; + +import { describe, expectTypeOf, it } from "vitest"; + +import { Fetch } from "../../src/index.js"; +import { TimeoutError, type TimeoutPlugin } from "../../src/plugins/index.js"; + +class ApiProblem extends Schema.Class("ApiProblem")({ + code: Schema.String, +}) {} + +class TodoNotFound extends Schema.TaggedError()("TodoNotFound", { + id: Schema.Finite, +}) {} + +const Todo = Schema.Struct({ id: Schema.Finite, title: Schema.String }); +const getTodo = Fetch.endpoint("GET /todos/:id", { output: Todo }); +const deleteTodo = Fetch.endpoint("DELETE /todos/:id"); + +type StatusErrors = { readonly 404: typeof TodoNotFound }; + +declare const api: Fetch.Client< + [TimeoutPlugin], + typeof ApiProblem, + StatusErrors +>; + +class Api extends Fetch.Service()("Api", { + baseUrl: "https://api.test", + defaultError: ApiProblem, + statusErrors: { 404: TodoNotFound }, +}) {} + +const todos = api.bind(getTodo); +type CallErrors = + ReturnType extends Effect.Effect + ? E + : never; + +type ErrorsOf = C extends Schema.Codec ? E : never; + +describe("Fetch.errorCodec", () => { + it("types a bound endpoint's errors as its calls fail", () => { + const schema = Fetch.errorCodec(todos, { errors: [TimeoutError] }); + expectTypeOf>().toEqualTypeOf(); + expectTypeOf().toEqualTypeOf< + | Fetch.NetworkError + | Fetch.DecodeError + | Fetch.HttpError.With + | TodoNotFound + | TimeoutError + >(); + }); + + it("writes out the members of ErrorCodecErrors", () => { + const schema = Fetch.errorCodec(todos, { errors: [TimeoutError] }); + expectTypeOf>().toEqualTypeOf< + Fetch.ErrorCodecErrors + >(); + const fromDefinition = Fetch.errorCodec(deleteTodo, { client: Api }); + expectTypeOf>().toEqualTypeOf< + Fetch.ErrorCodecErrors + >(); + expectTypeOf< + Fetch.ErrorCodecErrors< + { readonly error: Schema.Struct<{ readonly code: Schema.String }> }, + undefined, + [] + > + >().toEqualTypeOf< + | Fetch.NetworkError + | Fetch.HttpError.With<{ readonly code: string }> + | Fetch.DecodeError + >(); + }); + + it("leaves plugins' errors to `errors`", () => { + const schema = Fetch.errorCodec(todos); + expectTypeOf>().toEqualTypeOf< + Exclude + >(); + }); + + it("reads a definition with its client", () => { + const schema = Fetch.errorCodec(getTodo, { client: Api }); + expectTypeOf>().toEqualTypeOf< + Exclude + >(); + }); + + it("types a definition without a client with a plain HttpError", () => { + const schema = Fetch.errorCodec(getTodo); + expectTypeOf>().toEqualTypeOf< + Fetch.NetworkError | Fetch.DecodeError | Fetch.HttpError + >(); + }); + + it("takes the schemas themselves, with a DecodeError", () => { + const schema = Fetch.errorCodec({ + error: ApiProblem, + statusErrors: { 404: TodoNotFound }, + }); + expectTypeOf>().toEqualTypeOf< + Exclude + >(); + }); + + it("has no DecodeError without output", () => { + const schema = Fetch.errorCodec(deleteTodo, { client: Api }); + expectTypeOf>().toEqualTypeOf< + Fetch.NetworkError | Fetch.HttpError.With | TodoNotFound + >(); + }); + + it("has a DecodeError for a stream without output", () => { + const events = api.endpoint("GET /events", { stream: "sse" }); + type StreamErrors = + ReturnType extends Stream.Stream + ? E + : never; + const schema = Fetch.errorCodec(events); + expectTypeOf>().toEqualTypeOf< + Exclude + >(); + expectTypeOf().toExtend>(); + }); + + it("needs no services for schemas that need none", () => { + const schema = Fetch.errorCodec(todos, { errors: [TimeoutError] }); + expectTypeOf(schema).toExtend< + Schema.Codec + >(); + expectTypeOf(schema).toEqualTypeOf< + Fetch.ErrorCodec + >(); + }); + + it("is an RPC's error", () => { + const GetTodo = Rpc.make("GetTodo", { + success: Todo, + error: Fetch.errorCodec(todos, { errors: [TimeoutError] }), + }); + expectTypeOf>().toEqualTypeOf(); + }); + + it("rejects a client without a config", () => { + // @ts-expect-error: `client` must be a Fetch.Service class or have one's `config`. + Fetch.errorCodec(getTodo, { client: {} }); + }); +}); diff --git a/test/types/errors.test-d.ts b/test/types/errors.test-d.ts new file mode 100644 index 0000000..07ae344 --- /dev/null +++ b/test/types/errors.test-d.ts @@ -0,0 +1,66 @@ +import type * as Headers from "effect/http/Headers"; +import * as Schema from "effect/Schema"; + +import { describe, expectTypeOf, it } from "vitest"; + +import { Fetch } from "../../src/index.js"; + +// The errors' JSON encoding leaves fields out, but what you construct them +// with and read from them is unchanged: code that builds them by hand, such +// as effetch-query's, keeps compiling. +describe("error classes", () => { + it("take the same constructor arguments", () => { + expectTypeOf< + Omit[0], "_tag"> + >().toEqualTypeOf<{ + readonly method: string; + readonly url: string; + readonly status: number; + readonly headers: Headers.Headers; + readonly text: string; + readonly body: unknown; + }>(); + expectTypeOf< + Omit[0], "_tag"> + >().toEqualTypeOf<{ + readonly method: string; + readonly url: string; + readonly cause: unknown; + }>(); + expectTypeOf< + Omit[0], "_tag"> + >().toEqualTypeOf<{ + readonly method: string; + readonly url: string; + readonly status: number; + readonly issue: unknown; + readonly message: string; + }>(); + }); + + it("keep their fields", () => { + expectTypeOf< + Fetch.HttpError["headers"] + >().toEqualTypeOf(); + expectTypeOf().toEqualTypeOf(); + expectTypeOf().toEqualTypeOf(); + expectTypeOf().toEqualTypeOf(); + }); + + it("encode to what they send", () => { + expectTypeOf< + Schema.Codec.Encoded + >().toEqualTypeOf<{ + readonly _tag: "HttpError"; + readonly method: string; + readonly url: string; + readonly status: number; + readonly headers?: unknown; + readonly text: string; + readonly body?: unknown; + }>(); + expectTypeOf(Schema.toCodecJson(Fetch.NetworkError)).toExtend< + Schema.Codec + >(); + }); +}); diff --git a/tsconfig.json b/tsconfig.json index 73aae88..5cc18eb 100644 --- a/tsconfig.json +++ b/tsconfig.json @@ -21,5 +21,5 @@ }, "plugins": [{ "name": "@effect/language-service" }] }, - "include": ["src", "test", "examples", "*.config.ts"] + "include": ["src", "test", "*.config.ts"] } diff --git a/vitest.config.ts b/vitest.config.ts index bbfd27f..27acc71 100644 --- a/vitest.config.ts +++ b/vitest.config.ts @@ -21,7 +21,7 @@ export default defineConfig({ ], }, test: { - include: ["test/**/*.test.ts"], + include: ["test/**/*.test.ts", "examples/**/*.test.ts"], typecheck: { enabled: true, include: ["test/**/*.test-d.ts"],