Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
27 changes: 26 additions & 1 deletion CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@

All notable changes to `@monarcode/effetch`, newest first.

## Unreleased
## 0.1.0-rc.5

### Added

Expand Down Expand Up @@ -34,6 +34,18 @@ All notable changes to `@monarcode/effetch`, newest first.
the client `client` (as in `client.bind`). They say "bind" or "your
client's endpoint or bind method", so they read the same whatever you
name your client.
- A call without an `error` schema, on a client without a `defaultError`,
now shows its error as `HttpError` rather than `HttpError.With<unknown>`:
`Effect<Todo, NetworkError | DecodeError | HttpError>`. They're the same
type, so values and assignments are unaffected. With a schema, the error
is still `HttpError.With<…>`, typed by it, and `Schema.Any` still gives
`HttpError.With<any>`. One thing can break: a
function generic over the error schema, such as one that takes a
`Fetch.CallEffect<O, EB, …>` with `EB` still a type parameter, can no
longer use `Effect.catchTag("HttpError", …)` on it, because TypeScript
can't tell which of the two the error is. Check `error._tag ===
"HttpError"` instead, or type the parameter as any
`Effect.Effect<A, E, R>`, as the `CallEffect` docs advise.

### Fixed

Expand All @@ -42,6 +54,19 @@ All notable changes to `@monarcode/effetch`, newest first.
`Uint8Array<ArrayBuffer>`, which TypeScript 5.6 and older reject. With
`skipLibCheck: true`, an older TypeScript compiles a project that uses
Effetch, but some of its types become `any`.
- A plugin override can set an option to `undefined`, which keeps the
option's default, with `exactOptionalPropertyTypes` on too. Calls already
worked this way, but the type rejected it, so passing a value that may be
missing, as in `plugins: { retry: { times: maybeTimes } }`, needed a
cast.
- `Fetch.paginate` ignores a `plugins` key returned from `request`, as its
type always said. The key reached each page's call, unchecked, so an
unknown plugin name or a wrong option went unnoticed. Give plugin
overrides when you bind the endpoint, and every page's call uses them.
`PageRequest`'s `plugins` key says so in its hover.
- A literal value returned from `Fetch.paginate`'s `request` keeps its
type, so a query field typed `"asc" | "desc"` accepts `"asc"`. It was
widened to `string`, which failed to compile.

## 0.1.0-rc.4

Expand Down
9 changes: 1 addition & 8 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -47,7 +47,7 @@ export const getTodo = (id: number) =>
return yield* api.get("/todos/:id", { params: { id }, output: Todo });
});
// Effect<{ readonly id: number; readonly title: string },
// NetworkError | DecodeError | HttpError.With<unknown>, Api>
// NetworkError | DecodeError | HttpError, Api>
```

> **Release candidate.** Effetch is in release candidates (`0.1.0-rc.N`)
Expand All @@ -66,13 +66,6 @@ The guides and the API reference are at
pnpm add @monarcode/effetch effect
```

With Expo:

```bash
npx expo install effect
pnpm add @monarcode/effetch
```

You'll need:

- `effect` 4.x, which is a peer dependency;
Expand Down
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "@monarcode/effetch",
"version": "0.1.0-rc.4",
"version": "0.1.0-rc.5",
"description": "Typed, schema-driven HTTP calls on Effect v4's HttpClient: path params, object queries, decoded responses and plugins",
"keywords": [
"effect",
Expand Down
8 changes: 7 additions & 1 deletion scripts/editor-check.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -433,6 +433,7 @@ const errorsAndServices = (hover) => {
: undefined;
};

// `typed` has a `defaultError`, so its calls fail with `HttpError.With<…>`.
const callErrors = ["DecodeError", "HttpError.With", "NetworkError"];
for (const [marker, errors, services] of [
["todoCall", callErrors, ["never"]],
Expand All @@ -441,7 +442,12 @@ for (const [marker, errors, services] of [
["boundCall", callErrors, ["never"]],
["postCall", callErrors, ["never"]],
["requestCall", callErrors, ["never"]],
["timedCall", [...callErrors, "TimeoutError"].sort(), ["never"]],
// `timed` has no `defaultError`, so its body isn't typed: plain `HttpError`.
[
"timedCall",
["DecodeError", "HttpError", "NetworkError", "TimeoutError"],
["never"],
],
["servicesCall", callErrors, ["Locale", "Signer"]],
["statusGet", [...callErrors, "TodoNotFound"].sort(), ["never"]],
[
Expand Down
6 changes: 4 additions & 2 deletions site/content/docs/(latest)/errors/catching.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -114,15 +114,17 @@ always send what the schema expects:

- With a schema, `body` is the decoded body, or `undefined` when it doesn't
match.
- Without one, `body` is the parsed JSON, typed `unknown`.
- Without one, `body` is the parsed JSON, typed `unknown`, and the call's
error type shows a plain `HttpError`.
- With or without one, `body` is `undefined` when the response body is empty
or isn't JSON.

Reading the body never fails the call: you always get the `HttpError`. The
raw body is always on `text`, or `""` if it couldn't be read.

For your own function signatures, `Fetch.HttpError.With<B>` is the type of an
`HttpError` whose `body` is `B | undefined`.
`HttpError` whose `body` is `B | undefined`, as a call with an `error` schema
shows it.

## Catch a status

Expand Down
9 changes: 1 addition & 8 deletions site/content/docs/(latest)/installation.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -29,14 +29,7 @@ To install Effetch and Effect, run the command for your package manager:
- Yarn: `yarn add @monarcode/effetch effect`
- Bun: `bun add @monarcode/effetch effect`

In an Expo project, add `effect` with Expo's installer:

```bash
npx expo install effect
```

Then add Effetch with your package manager, as in
`npm install @monarcode/effetch`.
An Expo or React Native project uses the same command.

## Import Effetch

Expand Down
5 changes: 3 additions & 2 deletions site/content/docs/(latest)/pagination.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -55,8 +55,9 @@ export const allTodos = Effect.gen(function* () {
cursor.
- **`request(state)`** gives the options for that page's call: `params`,
`query`, `body` and `headers`, typed by the endpoint. Plugin overrides
aren't among them, so give those when you bind the endpoint. The
endpoint's `responseMode` always decides what each page is.
aren't among them, so give those when you bind the endpoint, and every
page's call uses them. The endpoint's `responseMode` always decides what
each page is.
- **`next(page, state, response)`** gives the next page's state, or
`Option.none()` after the last page. `response` is the page's
`HttpClientResponse` when the endpoint's `responseMode` is
Expand Down
9 changes: 6 additions & 3 deletions site/content/docs/(latest)/plugins/per-call.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -58,9 +58,12 @@ A call's changes combine with the rest as follows:

- **Options you leave out keep their defaults.** A call that passes
`{ consoleLogger: { detail: "summary" } }` changes `detail` only, and
keeps the other settings. A key
whose value is `undefined` at runtime keeps its default too, rather than
replacing it with `undefined`.
keeps the other settings. A key set to `undefined` is left out too, so it
keeps the value it would have without it, and you can pass a value that
may be missing, such as `{ retry: { times: maybeTimes } }`, as it is.
Any object still turns the plugin on, even one whose keys are all
`undefined`: on an endpoint bound with `retry: false`, that call
retries.
- **`false` skips the whole plugin.** Its `wrap`, `onRequest` and
`onResponse` don't run for that call, and neither do its `onError` and
`onExit`. A skipped `consoleLogger` prints nothing, for example.
Expand Down
10 changes: 5 additions & 5 deletions site/content/docs/(latest)/reference/fetch.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -263,7 +263,7 @@ For a `404` that means "not found", [`optional`](#optional) gives an `Option` in

### Fetch.DecodeError [#decodeerror]

The error a call fails with when a 2xx response body doesn't match the call's `output` schema, isn't valid JSON, or can't be read. A stream fails with it too, when a value doesn't decode or the body breaks off. Its fields:
The error a call fails with when a 2xx response body doesn't match the call's `output` schema, isn't valid JSON, or can't be read, and the error a stream fails with while it's read (see below). Its fields:

- `method`: the request's HTTP method.
- `url`: the request URL without its query string.
Expand All @@ -288,7 +288,7 @@ The error a call fails with when the server answers with a status outside 200–

### Fetch.HttpError.With [#httperror-with]

An [`HttpError`](#httperror) whose `body` was decoded as `B`. `body` is `undefined` when the response didn't match the error schema.
An [`HttpError`](#httperror) whose `body` was decoded as `B`. `body` is `undefined` when the response didn't match the error schema. A call with an `error` schema, or a client with a `defaultError`, fails with one. Without either, a call fails with a plain `HttpError`.

### Fetch.isFetchError [#isfetcherror]

Expand All @@ -310,7 +310,7 @@ It's [`catchStatus`](#catchstatus)`(404, …)` for the common case of a resource

### Fetch.CallError [#callerror]

What a call can fail with: `NetworkError`, `HttpError` (with `body` typed by the `error` schema), `DecodeError` when there's an `output` schema, the plugins' errors, and the errors of the `statusErrors` maps that apply (see [`StatusError`](#statuserror)).
What a call can fail with: `NetworkError`, `HttpError`, `DecodeError` when there's an `output` schema, the plugins' errors, and the errors of the `statusErrors` maps that apply (see [`StatusError`](#statuserror)). With an `error` schema, or the client's `defaultError`, the `HttpError` is an `HttpError.With<…>` whose `body` has the schema's type. Without one, it's a plain `HttpError`, whose `body` is `unknown`.

- `SE`: the `statusErrors` maps of the call, the endpoint and the client, as a union. `undefined` (the default) when there are none.

Expand Down Expand Up @@ -389,7 +389,7 @@ The options type of plugin `P`.

### Fetch.Plugin.Override [#plugin-override]

What one plugin accepts as a per-request override: `false` to skip it, or a partial of its options. Plugins without options accept only `false`. A key whose value is `undefined` at runtime keeps its default.
What one plugin accepts as a per-request override: `false` to skip it, or some of its options. Plugins without options accept only `false`. A key set to `undefined` keeps the value it would have without it: the endpoint's override, else the default. So a value that may be missing can be passed as it is.

### Fetch.Plugin.Overrides [#plugin-overrides]

Expand Down Expand Up @@ -656,7 +656,7 @@ One page of endpoint `EP`: its `output`'s type, or the raw response without `out

### Fetch.PageRequest [#pagerequest]

The options of one page's call, as [`PaginateOptions`](#paginateoptions)' `request` returns them for endpoint `EP`: `params`, `body`, `query` and `headers`, typed as for any call of the endpoint.
The options of one page's call, as [`PaginateOptions`](#paginateoptions)' `request` returns them for endpoint `EP`: `params`, `body`, `query` and `headers`, typed as for any call of the endpoint. Plugin overrides aren't among them: give those when binding the endpoint, and every page's call uses them.

### Fetch.PageResponse [#pageresponse]

Expand Down
3 changes: 1 addition & 2 deletions site/src/components/landing/sections.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -397,8 +397,7 @@ const FAILURES: Record<string, string> = {
SchemaError: "A JSON body that doesn't match Todo.",
DecodeError: "A 2xx body that isn't JSON or doesn't match Todo.",
NetworkError: "No response: offline, DNS failure, connection refused, CORS.",
"HttpError.With<unknown>":
"A status outside 200–299, with its headers and body.",
HttpError: "A status outside 200–299, with its headers and body.",
HttpClient: "Needs an HttpClient layer before it runs.",
never: "Needs nothing more to run.",
};
Expand Down
53 changes: 30 additions & 23 deletions site/src/components/landing/specimen.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -164,16 +164,23 @@ function TypeText({ text }: { text: string }) {
);
}

/** An error's name and its type argument: `HttpError.With`, `unknown`. */
/**
* An error's name, the member of its namespace it's typed through, and its
* type argument: `HttpError.With<ApiError>` is `HttpError`, `.With` and
* `ApiError`. A plain `HttpError` is the same error, untyped, so both share
* a slot.
*/
export function parts(error: string) {
const open = error.indexOf("<");
return open < 0
? { name: error, argument: undefined }
: { name: error.slice(0, open), argument: error.slice(open + 1, -1) };
const [, name = error, member = "", argument] =
/^([^.<]+)(\.[^<]+)?(?:<(.*)>)?$/s.exec(error) ?? [];
return { name, member, argument };
}

/** Every error a signature can carry, with every type argument it takes. */
export type ErrorSlot = { name: string; arguments: string[] };
/**
* Every error a signature can carry, with every type argument it takes and
* the member that takes them (`.With`), if any.
*/
export type ErrorSlot = { name: string; member: string; arguments: string[] };

/** The text a screen reader reads for a signature. */
export function spoken(effect: EffectParts) {
Expand Down Expand Up @@ -333,7 +340,8 @@ export function SpecimenSignature({
<>
{"\u200B"}
<span className="spec-pair spec-error">
<Member on={on}>
<Member on={present[slot.name] !== undefined}>
{slot.member}
<span className="spec-punct">&lt;</span>
</Member>
{slot.arguments.map((a) => (
Expand All @@ -344,7 +352,7 @@ export function SpecimenSignature({
{a}
</Member>
))}
<Member on={on}>
<Member on={present[slot.name] !== undefined}>
<span className="spec-punct">&gt;</span>
</Member>
{comma}
Expand All @@ -367,21 +375,20 @@ export function SpecimenSignature({

/** Every error a set of signatures carries, in the order `names` gives. */
export function slotsOf(names: string[], effects: EffectParts[]): ErrorSlot[] {
return names.map((name) => ({
name,
arguments: [
...new Set(
effects.flatMap((effect) =>
effect.errors
.map(parts)
.filter((error) => error.name === name)
.flatMap((error) =>
error.argument === undefined ? [] : [error.argument],
),
return names.map((name) => {
const typed = effects.flatMap((effect) =>
effect.errors
.map(parts)
.filter(
(error) => error.name === name && error.argument !== undefined,
),
),
],
}));
);
return {
name,
member: typed[0]?.member ?? "",
arguments: [...new Set(typed.map((error) => error.argument!))],
};
});
}

/**
Expand Down
18 changes: 13 additions & 5 deletions site/src/lib/landing.ts
Original file line number Diff line number Diff line change
Expand Up @@ -419,11 +419,17 @@ async function readSpecimen(): Promise<Specimen> {
});
if (combos.length !== 16)
throw new Error(`specimen.ts: ${combos.length} combinations, not 16`);
// One order for every error, by name before any type argument, that
// each union follows.
const key = (error: string) => error.split("<")[0]!;
// One order for every error, by name before any member or type
// argument, that each union follows. `HttpError` and
// `HttpError.With<ApiError>` are one slot. TypeScript prints the plain
// one first and the typed one last, so the typed combinations set the
// order, and the check below leaves the plain one out.
const key = (error: string) => error.split(/[.<]/)[0]!;
const errors: string[] = [];
for (const combo of combos)
const typedFirst = [...combos].sort(
(a, b) => Number(b.error) - Number(a.error),
);
for (const combo of typedFirst)
for (const error of combo.effect.errors)
if (!errors.includes(key(error))) {
const before = combo.effect.errors
Expand All @@ -437,7 +443,9 @@ async function readSpecimen(): Promise<Specimen> {
);
}
for (const combo of combos) {
const order = combo.effect.errors.map(key);
const order = combo.effect.errors
.filter((error) => error !== "HttpError")
.map(key);
const kept = errors.filter((error) => order.includes(error));
if (kept.join() !== order.join())
throw new Error(`specimen.ts: ${combo.call} orders its errors apart`);
Expand Down
12 changes: 10 additions & 2 deletions src/Endpoint.ts
Original file line number Diff line number Diff line change
Expand Up @@ -481,7 +481,11 @@ export interface Endpoint<
// CallError and CallServices, written out (see CallEffect), with
// DecodeError always: reading the stream can fail.
| NetworkError
| HttpError.With<EB["Type"]>
| ([unknown] extends [EB["Type"]]
? 0 extends 1 & EB["Type"]
? HttpError.With<EB["Type"]>
: HttpError
: HttpError.With<EB["Type"]>)
| DecodeError
| Plugin.Errors<Ps>
| StatusError<SE>,
Expand All @@ -496,7 +500,11 @@ export interface Endpoint<
Success<O, NoInfer<CM extends undefined ? M : CM>>,
// CallError and CallServices, written out (see CallEffect)
| NetworkError
| HttpError.With<EB["Type"]>
| ([unknown] extends [EB["Type"]]
? 0 extends 1 & EB["Type"]
? HttpError.With<EB["Type"]>
: HttpError
: HttpError.With<EB["Type"]>)
| (O extends AnySchema ? DecodeError : never)
| Plugin.Errors<Ps>
| StatusError<SE>,
Expand Down
9 changes: 5 additions & 4 deletions src/Errors.ts
Original file line number Diff line number Diff line change
Expand Up @@ -119,7 +119,9 @@ export class HttpError extends Schema.TaggedError<HttpError>()("HttpError", {
export declare namespace HttpError {
/**
* An {@link HttpError} whose `body` was decoded as `B`. `body` is
* `undefined` when the response didn't match the error schema.
* `undefined` when the response didn't match the error schema. A call
* with an `error` schema, or a client with a `defaultError`, fails with
* one. Without either, a call fails with a plain `HttpError`.
*
* @example
* ```ts
Expand All @@ -137,9 +139,8 @@ export declare namespace HttpError {

/**
* The error a call fails with when a 2xx response body doesn't match the
* call's `output` schema, isn't valid JSON, or can't be read. A stream fails
* with it too, when a value doesn't decode or the body breaks off. Its
* fields:
* call's `output` schema, isn't valid JSON, or can't be read, and the error
* a stream fails with while it's read (see below). Its fields:
*
* - `method`: the request's HTTP method.
* - `url`: the request URL without its query string.
Expand Down
Loading