From 93004e106186d51b6c394d2290eb6e01d239b4f7 Mon Sep 17 00:00:00 2001 From: monarcode Date: Tue, 24 Nov 2026 16:56:50 +0100 Subject: [PATCH 1/3] fix: accept undefined plugin options, and stop paginate's request from passing plugins --- CHANGELOG.md | 13 +++++ site/content/docs/(latest)/pagination.mdx | 5 +- .../docs/(latest)/plugins/per-call.mdx | 9 ++-- .../content/docs/(latest)/reference/fetch.mdx | 4 +- src/Options.ts | 5 +- src/Paginate.ts | 48 ++++++++++++------- src/Plugin.ts | 28 +++++++---- test/endpoint.test.ts | 5 +- test/plugins.test.ts | 7 ++- test/streams.test.ts | 47 ++++++++++++++++++ test/types/plugin.test-d.ts | 31 ++++++++++++ test/types/streams.test-d.ts | 30 ++++++++++++ 12 files changed, 188 insertions(+), 44 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index e5d9256..a960385 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -42,6 +42,19 @@ All notable changes to `@monarcode/effetch`, newest first. `Uint8Array`, which TypeScript 5.6 and older reject. With `skipLibCheck: true`, an older TypeScript compiles a project that uses Effetch, but some of its types become `any`. +- 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 diff --git a/site/content/docs/(latest)/pagination.mdx b/site/content/docs/(latest)/pagination.mdx index 6b790a7..028de6d 100644 --- a/site/content/docs/(latest)/pagination.mdx +++ b/site/content/docs/(latest)/pagination.mdx @@ -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 diff --git a/site/content/docs/(latest)/plugins/per-call.mdx b/site/content/docs/(latest)/plugins/per-call.mdx index 8211753..33095ac 100644 --- a/site/content/docs/(latest)/plugins/per-call.mdx +++ b/site/content/docs/(latest)/plugins/per-call.mdx @@ -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. diff --git a/site/content/docs/(latest)/reference/fetch.mdx b/site/content/docs/(latest)/reference/fetch.mdx index ef8d499..981a128 100644 --- a/site/content/docs/(latest)/reference/fetch.mdx +++ b/site/content/docs/(latest)/reference/fetch.mdx @@ -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] @@ -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] diff --git a/src/Options.ts b/src/Options.ts index 608aa80..06a8ced 100644 --- a/src/Options.ts +++ b/src/Options.ts @@ -436,8 +436,9 @@ export interface BaseOptions< readonly statusErrors?: SE; /** * Per-request plugin overrides, by plugin name: `false` skips the - * plugin's hooks and `wrap` for this call, and a partial of its options - * is merged over its `defaults`. + * plugin's hooks and `wrap` for this call, and some of its options are + * merged over its `defaults`. An option set to `undefined` keeps the + * value it would have without it. */ readonly plugins?: Plugin.Overrides | undefined; } diff --git a/src/Paginate.ts b/src/Paginate.ts index e309454..0cabb2e 100644 --- a/src/Paginate.ts +++ b/src/Paginate.ts @@ -51,7 +51,9 @@ export interface PageEndpoint { /** * The options of one page's call, as {@link PaginateOptions}' `request` * returns them for endpoint `EP`: `params`, `body`, `query` and `headers`, - * typed as for any call of the endpoint. + * 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. * * @example * ```ts @@ -68,21 +70,26 @@ export interface PageEndpoint { * * @since 0.1.0 */ -export type PageRequest = EP extends { - readonly route: infer R extends string; -} - ? ParamsOption> & - EndpointBody & - EndpointQuery & { - /** Headers for this page's call. */ - readonly headers?: Headers.Input | undefined; - /** - * Not allowed: the endpoint's `responseMode` decides what each - * page is. - */ - readonly responseMode?: undefined; - } - : never; +export type PageRequest = + // The route is read by index, not with a conditional `infer`, so a + // literal returned from `request`, such as `sort: "asc"`, keeps its type + // while the endpoint's type is being inferred. + ParamsOption> & + EndpointBody & + EndpointQuery & { + /** Headers for this page's call. */ + readonly headers?: Headers.Input | undefined; + /** + * Not allowed: give plugin overrides when binding the endpoint, + * and every page's call uses them. + */ + readonly plugins?: undefined; + /** + * Not allowed: the endpoint's `responseMode` decides what each + * page is. + */ + readonly responseMode?: undefined; + }; /** * One page of endpoint `EP`: its `output`'s type, or the raw response @@ -260,9 +267,14 @@ export const paginate = ( const both = endpoint.responseMode === "decoded-and-response"; return Stream.paginate(options.start, (state: S) => Effect.map( - // The endpoint's mode, even if `request` gives another. + // The endpoint's mode and plugin overrides, even if `request` + // gives others. Effect.suspend(() => - call({ ...options.request(state), responseMode: undefined }), + call({ + ...options.request(state), + plugins: undefined, + responseMode: undefined, + }), ), (result) => { const [page, response] = both diff --git a/src/Plugin.ts b/src/Plugin.ts index 7a38398..8d3548c 100644 --- a/src/Plugin.ts +++ b/src/Plugin.ts @@ -170,8 +170,8 @@ export interface PluginExitContext extends PluginContext { * the client don't need them. * * `Opts` is the type of the options calls can override, and `defaults` - * holds their values. Calls override them with - * `plugins: { [name]: { ...partial } }`, and any plugin can be skipped for + * holds their values. Calls override some of them with + * `plugins: { [name]: { ...options } }`, and any plugin can be skipped for * one call with `plugins: { [name]: false }`. A plugin with options must * have `defaults`; {@link plugin} enforces this. * @@ -202,7 +202,7 @@ export interface Plugin< > { /** Unique within a client. Used as the key for per-request overrides. */ readonly name: Name; - /** Default options. Enables per-request `Partial` overrides. */ + /** Default options. Enables per-request overrides of any of them. */ readonly defaults?: Opts | undefined; /** Runs before the request is sent, in array order. */ readonly onRequest?: Plugin.OnRequest | undefined; @@ -523,7 +523,7 @@ export declare namespace Plugin { > { /** Unique within a client. Used as the key for per-request overrides. */ readonly name: Name; - /** Default options. Enables per-request `Partial` overrides. */ + /** Default options. Enables per-request overrides of any of them. */ readonly defaults?: Opts | undefined; /** Runs before the request is sent, in array order. */ readonly onRequest?: @@ -599,9 +599,10 @@ export declare namespace Plugin { /** * 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. + * 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. * * @example * ```ts @@ -610,14 +611,23 @@ export declare namespace Plugin { * type RetryOverride = Fetch.Plugin.Override< * Fetch.Plugin<"retry", never, never, { times: number }> * >; - * // ^? false | Partial<{ times: number }> + * // ^? false | { times?: number | undefined } + * + * declare const times: number | undefined; + * export const override: RetryOverride = { times }; * ``` * * @since 0.1.0 */ export type Override

= [Options

] extends [undefined] ? false - : false | Partial>; + : // Each member of a union of options on its own, as `Partial` does. + | false + | (Options

extends infer O + ? O extends object + ? { [K in keyof O]?: O[K] | undefined } + : O + : never); /** * The `plugins` option of a call: an override per plugin name in `Ps`. diff --git a/test/endpoint.test.ts b/test/endpoint.test.ts index edf553a..4f1090e 100644 --- a/test/endpoint.test.ts +++ b/test/endpoint.test.ts @@ -286,11 +286,8 @@ describe("plugin overrides", () => { const list = api.endpoint("GET /todos", { plugins: { flags: { a: "endpoint", b: "endpoint" } }, }); - const withUndefined = { a: "call", b: undefined } as { - readonly a: string; - }; yield* list({ plugins: { flags: { b: "call" } } }); - yield* list({ plugins: { flags: withUndefined } }); + yield* list({ plugins: { flags: { a: "call", b: undefined } } }); expect(wire(mock, 0).headers).toMatchObject({ "x-a": "endpoint", "x-b": "call", diff --git a/test/plugins.test.ts b/test/plugins.test.ts index 1b3234f..b24d0df 100644 --- a/test/plugins.test.ts +++ b/test/plugins.test.ts @@ -313,10 +313,9 @@ describe("per-call overrides", () => { const { mock, api } = yield* setup([reply.json({})], { plugins: [headers], }); - const withUndefined = { a: "A", b: undefined } as { - readonly a: string; - }; - yield* api.get("/todos", { plugins: { headers: withUndefined } }); + yield* api.get("/todos", { + plugins: { headers: { a: "A", b: undefined } }, + }); yield* api.get("/todos"); expect(wire(mock, 0).headers).toMatchObject({ "x-a": "A", diff --git a/test/streams.test.ts b/test/streams.test.ts index 5ee20f5..f40104f 100644 --- a/test/streams.test.ts +++ b/test/streams.test.ts @@ -4,6 +4,7 @@ import * as Effect from "effect/Effect"; import * as Exit from "effect/Exit"; import * as Fiber from "effect/Fiber"; import * as HttpClient from "effect/http/HttpClient"; +import * as HttpClientRequest from "effect/http/HttpClientRequest"; import * as HttpClientResponse from "effect/http/HttpClientResponse"; import * as Layer from "effect/Layer"; import * as Option from "effect/Option"; @@ -830,6 +831,52 @@ describe("Fetch.paginate", () => { }), ); + it.effect("keeps the endpoint's plugin overrides, ignoring a page's", () => + Effect.gen(function* () { + const tag = Fetch.plugin({ + name: "tag", + defaults: { source: "client" }, + onRequest: (request, ctx) => + Effect.succeed( + HttpClientRequest.setHeader( + request, + "x-source", + ctx.options.source, + ), + ), + }); + const sent = yield* Effect.gen(function* () { + const api = yield* Fetch.make({ baseUrl: base, plugins: [tag] }); + yield* collect( + Fetch.paginate( + api.bind(listTodos, { + plugins: { tag: { source: "endpoint" } }, + }), + { + start: 1, + // The type doesn't allow plugins; JavaScript can still pass them. + request: (page) => + ({ + query: { page }, + plugins: { tag: { source: "page" } }, + }) as never, + next: (todos, page) => + todos.length === 0 + ? Option.none() + : Option.some(page + 1), + }, + ), + ); + return yield* FetchTest.requests; + }).pipe(Effect.provide(backend())); + expect(sent.map((request) => request.headers["x-source"])).toEqual([ + "endpoint", + "endpoint", + "endpoint", + ]); + }), + ); + it.effect("is lazy: take(1) sends one request", () => Effect.gen(function* () { const sent = yield* Effect.gen(function* () { diff --git a/test/types/plugin.test-d.ts b/test/types/plugin.test-d.ts index 3884290..b3b1b6d 100644 --- a/test/types/plugin.test-d.ts +++ b/test/types/plugin.test-d.ts @@ -256,6 +256,37 @@ describe("Plugin.Overrides", () => { expectTypeOf({ retry: { times: "0" } }).not.toExtend(); }); + it("accepts undefined for an option, which keeps its default", () => { + expectTypeOf>().toEqualTypeOf< + false | { times?: number | undefined } + >(); + const times = 0 as number | undefined; + const maybe: Overrides = { retry: { times } }; + const missing: Overrides = { retry: { times: undefined } }; + void [maybe, missing]; + }); + + it("keeps each member of a union of options apart", () => { + type Union = Plugin< + "union", + never, + never, + { kind: "a"; a: string } | { kind: "b"; b: number } + >; + expectTypeOf>().toEqualTypeOf< + | false + | { kind?: "a" | undefined; a?: string | undefined } + | { kind?: "b" | undefined; b?: number | undefined } + >(); + type Maybe = Plugin<"maybe", never, never, { n: number } | undefined>; + const ok: Plugin.Override = { n: 1 }; + // @ts-expect-error: n is a number + const wrong: Plugin.Override = { n: "x" }; + // @ts-expect-error: not an override + const nonsense: Plugin.Override = "nonsense"; + void [ok, wrong, nonsense]; + }); + it("types option keys", () => { // @ts-expect-error times is a number const wrongType: Overrides = { retry: { times: "0" } }; diff --git a/test/types/streams.test-d.ts b/test/types/streams.test-d.ts index 0c33dcc..b57b76e 100644 --- a/test/types/streams.test-d.ts +++ b/test/types/streams.test-d.ts @@ -313,6 +313,36 @@ describe("Fetch.paginate", () => { }); }); + it("leaves plugin overrides to the binding", () => { + const bound = withAuth.bind(listTodos, { + plugins: { timeout: { duration: "5 seconds" } }, + }); + const request: Fetch.PageRequest = { + params: { org: "acme" }, + query: { page: 1 }, + // @ts-expect-error: give plugin overrides when binding + plugins: { timeout: false }, + }; + void request; + }); + + it("keeps a literal query value's type", () => { + const sorted = Fetch.endpoint("GET /rows", { + query: Schema.Struct({ + sort: Schema.Literals(["asc", "desc"]), + page: Schema.Finite, + }), + output: Todos, + }); + Fetch.paginate(api.bind(sorted), { + start: 1, + request: (page) => ({ + query: { sort: page === 1 ? "asc" : "desc", page }, + }), + next: () => Option.none(), + }); + }); + it("leaves responseMode to the endpoint", () => { Fetch.paginate(api.bind(listByCursor), { start: 1, From 703edbe0acb1aeed083c1c3e0cc5e7b8a715b7f0 Mon Sep 17 00:00:00 2001 From: monarcode Date: Tue, 24 Nov 2026 17:24:04 +0100 Subject: [PATCH 2/3] feat!: show plain HttpError when a call has no error schema --- CHANGELOG.md | 12 +++++ README.md | 2 +- scripts/editor-check.mjs | 8 ++- .../content/docs/(latest)/errors/catching.mdx | 6 ++- .../content/docs/(latest)/reference/fetch.mdx | 4 +- site/src/components/landing/sections.tsx | 3 +- site/src/components/landing/specimen.tsx | 53 +++++++++++-------- site/src/lib/landing.ts | 18 +++++-- src/Endpoint.ts | 12 ++++- src/Errors.ts | 4 +- src/Options.ts | 46 ++++++++++++---- src/Plugin.ts | 5 +- src/Streams.ts | 6 ++- src/internal/response.ts | 7 +-- test/types/builtins.test-d.ts | 5 +- test/types/client.test-d.ts | 41 +++++++++++--- test/types/endpoint.test-d.ts | 8 +-- test/types/make.test-d.ts | 4 +- test/types/plugin.test-d.ts | 8 +++ test/types/response.test-d.ts | 12 +---- test/types/streams.test-d.ts | 8 +-- 21 files changed, 182 insertions(+), 90 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index a960385..2cc87bd 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -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`: + `Effect`. 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`. One thing can break: a + function generic over the error schema, such as one that takes a + `Fetch.CallEffect` 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`, as the `CallEffect` docs advise. ### Fixed diff --git a/README.md b/README.md index 13bfd95..e5e328a 100644 --- a/README.md +++ b/README.md @@ -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, Api> +// NetworkError | DecodeError | HttpError, Api> ``` > **Release candidate.** Effetch is in release candidates (`0.1.0-rc.N`) diff --git a/scripts/editor-check.mjs b/scripts/editor-check.mjs index 3471dd4..a307cc1 100644 --- a/scripts/editor-check.mjs +++ b/scripts/editor-check.mjs @@ -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"]], @@ -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"]], [ diff --git a/site/content/docs/(latest)/errors/catching.mdx b/site/content/docs/(latest)/errors/catching.mdx index c3bb3df..c86288c 100644 --- a/site/content/docs/(latest)/errors/catching.mdx +++ b/site/content/docs/(latest)/errors/catching.mdx @@ -114,7 +114,8 @@ 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. @@ -122,7 +123,8 @@ Reading the body never fails the call: you always get the `HttpError`. The raw body is always on `text`, or `""` if it couldn't be read. For your own function signatures, `Fetch.HttpError.With` is the type of an -`HttpError` whose `body` is `B | undefined`. +`HttpError` whose `body` is `B | undefined`, as a call with an `error` schema +shows it. ## Catch a status diff --git a/site/content/docs/(latest)/reference/fetch.mdx b/site/content/docs/(latest)/reference/fetch.mdx index 981a128..7c4f8b4 100644 --- a/site/content/docs/(latest)/reference/fetch.mdx +++ b/site/content/docs/(latest)/reference/fetch.mdx @@ -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] @@ -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. diff --git a/site/src/components/landing/sections.tsx b/site/src/components/landing/sections.tsx index 575022a..79404b6 100644 --- a/site/src/components/landing/sections.tsx +++ b/site/src/components/landing/sections.tsx @@ -397,8 +397,7 @@ const FAILURES: Record = { 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": - "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.", }; diff --git a/site/src/components/landing/specimen.tsx b/site/src/components/landing/specimen.tsx index 96fe040..fd7ba3d 100644 --- a/site/src/components/landing/specimen.tsx +++ b/site/src/components/landing/specimen.tsx @@ -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` 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) { @@ -333,7 +340,8 @@ export function SpecimenSignature({ <> {"\u200B"} - + + {slot.member} < {slot.arguments.map((a) => ( @@ -344,7 +352,7 @@ export function SpecimenSignature({ {a} ))} - + > {comma} @@ -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!))], + }; + }); } /** diff --git a/site/src/lib/landing.ts b/site/src/lib/landing.ts index 3826192..9450aee 100644 --- a/site/src/lib/landing.ts +++ b/site/src/lib/landing.ts @@ -419,11 +419,17 @@ async function readSpecimen(): Promise { }); 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` 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 @@ -437,7 +443,9 @@ async function readSpecimen(): Promise { ); } 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`); diff --git a/src/Endpoint.ts b/src/Endpoint.ts index cc6ec36..4cead44 100644 --- a/src/Endpoint.ts +++ b/src/Endpoint.ts @@ -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 + | ([unknown] extends [EB["Type"]] + ? 0 extends 1 & EB["Type"] + ? HttpError.With + : HttpError + : HttpError.With) | DecodeError | Plugin.Errors | StatusError, @@ -496,7 +500,11 @@ export interface Endpoint< Success>, // CallError and CallServices, written out (see CallEffect) | NetworkError - | HttpError.With + | ([unknown] extends [EB["Type"]] + ? 0 extends 1 & EB["Type"] + ? HttpError.With + : HttpError + : HttpError.With) | (O extends AnySchema ? DecodeError : never) | Plugin.Errors | StatusError, diff --git a/src/Errors.ts b/src/Errors.ts index 2dc9d82..20b6acf 100644 --- a/src/Errors.ts +++ b/src/Errors.ts @@ -119,7 +119,9 @@ export class HttpError extends Schema.TaggedError()("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 diff --git a/src/Options.ts b/src/Options.ts index 06a8ced..9a838d0 100644 --- a/src/Options.ts +++ b/src/Options.ts @@ -597,10 +597,12 @@ export type Success< : HttpClientResponse.HttpClientResponse; /** - * 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 {@link 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 {@link 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. @@ -627,7 +629,15 @@ export type CallError< SE extends StatusErrorMap | undefined = undefined, > = | NetworkError - | HttpError.With + // A body typed `unknown` gives plain `HttpError`, which is the same type + // and reads better. `any` keeps `With`, so its body stays `any` + // (`0 extends 1 & B` holds only for `any`). The brackets keep a union + // body whole. The signatures that write these members out do the same. + | ([unknown] extends [EB["Type"]] + ? 0 extends 1 & EB["Type"] + ? HttpError.With + : HttpError + : HttpError.With) | (O extends AnySchema ? DecodeError : never) | Plugin.Errors | StatusError; @@ -701,7 +711,7 @@ export type CallServices< * Schema.Unknown, * [] * >; - * // ^? Effect<{ readonly id: number }, NetworkError | DecodeError | HttpError.With, never> + * // ^? Effect<{ readonly id: number }, NetworkError | DecodeError | HttpError, never> * ``` * * @since 0.1.0 @@ -720,7 +730,11 @@ export type CallEffect< // print `CallError<…>` rather than the members. The method and endpoint // signatures spell them out the same way. | NetworkError - | HttpError.With + | ([unknown] extends [EB["Type"]] + ? 0 extends 1 & EB["Type"] + ? HttpError.With + : HttpError + : HttpError.With) | (O extends AnySchema ? DecodeError : never) | Plugin.Errors | StatusError, @@ -771,7 +785,11 @@ export interface NoBodyMethod< Success>, // CallError and CallServices, written out (see CallEffect) | NetworkError - | HttpError.With + | ([unknown] extends [EB["Type"]] + ? 0 extends 1 & EB["Type"] + ? HttpError.With + : HttpError + : HttpError.With) | (O extends AnySchema ? DecodeError : never) | Plugin.Errors | StatusError> @@ -829,7 +847,11 @@ export interface BodyMethod< Success>, // CallError and CallServices, written out (see CallEffect) | NetworkError - | HttpError.With + | ([unknown] extends [EB["Type"]] + ? 0 extends 1 & EB["Type"] + ? HttpError.With + : HttpError + : HttpError.With) | (O extends AnySchema ? DecodeError : never) | Plugin.Errors | StatusError> @@ -889,7 +911,11 @@ export interface RequestMethod< Success>, // CallError and CallServices, written out (see CallEffect) | NetworkError - | HttpError.With + | ([unknown] extends [EB["Type"]] + ? 0 extends 1 & EB["Type"] + ? HttpError.With + : HttpError + : HttpError.With) | (O extends AnySchema ? DecodeError : never) | Plugin.Errors | StatusError> diff --git a/src/Plugin.ts b/src/Plugin.ts index 8d3548c..bc309cc 100644 --- a/src/Plugin.ts +++ b/src/Plugin.ts @@ -626,7 +626,10 @@ export declare namespace Plugin { | (Options

extends infer O ? O extends object ? { [K in keyof O]?: O[K] | undefined } - : O + : // Options typed `unknown` take `{}`, as `Partial` gives. + unknown extends O + ? {} + : O : never); /** diff --git a/src/Streams.ts b/src/Streams.ts index e2e41b4..021b338 100644 --- a/src/Streams.ts +++ b/src/Streams.ts @@ -221,7 +221,11 @@ export interface StreamMethod< // CallError and CallServices, written out (see CallEffect), with // DecodeError always: reading the stream can fail. | NetworkError - | HttpError.With + | ([unknown] extends [EB["Type"]] + ? 0 extends 1 & EB["Type"] + ? HttpError.With + : HttpError + : HttpError.With) | DecodeError | Plugin.Errors | StatusError> diff --git a/src/internal/response.ts b/src/internal/response.ts index d88e14a..12c4ce9 100644 --- a/src/internal/response.ts +++ b/src/internal/response.ts @@ -62,10 +62,7 @@ const readErrorBody = ( */ export function checkStatus( response: HttpClientResponse.HttpClientResponse, -): Effect.Effect< - HttpClientResponse.HttpClientResponse, - HttpError.With ->; +): Effect.Effect; export function checkStatus( response: HttpClientResponse.HttpClientResponse, errorSchema: EB, @@ -79,7 +76,7 @@ export function checkStatus( errorSchema: EB | undefined, ): Effect.Effect< HttpClientResponse.HttpClientResponse, - HttpError.With, + HttpError, EB["DecodingServices"] >; export function checkStatus( diff --git a/test/types/builtins.test-d.ts b/test/types/builtins.test-d.ts index 525cced..2ab28df 100644 --- a/test/types/builtins.test-d.ts +++ b/test/types/builtins.test-d.ts @@ -187,10 +187,7 @@ describe("make with the built-ins", () => { it("adds TimeoutError and the token's error to calls", () => { const call = api.get("/todos"); expectTypeOf>().toEqualTypeOf< - | Fetch.NetworkError - | Fetch.HttpError.With - | TimeoutError - | TokenError + Fetch.NetworkError | Fetch.HttpError | TimeoutError | TokenError >(); }); diff --git a/test/types/client.test-d.ts b/test/types/client.test-d.ts index 7de3dff..5b13867 100644 --- a/test/types/client.test-d.ts +++ b/test/types/client.test-d.ts @@ -226,11 +226,7 @@ describe("body", () => { describe("return type", () => { it("is the raw response without output", () => { expectTypeOf(get("/todos")).toEqualTypeOf< - Effect.Effect< - Response, - NetworkError | HttpError.With | TimeoutError, - never - > + Effect.Effect >(); }); @@ -240,7 +236,7 @@ describe("return type", () => { ).toEqualTypeOf< Effect.Effect< Todo, - NetworkError | HttpError.With | DecodeError | TimeoutError, + NetworkError | HttpError | DecodeError | TimeoutError, never > >(); @@ -273,6 +269,39 @@ describe("return type", () => { >(); }); + it("shows plain HttpError for an unknown body, and With for a typed one", () => { + expectTypeOf>>>().toEqualTypeOf< + NetworkError | HttpError | TimeoutError + >(); + // `any` stays `any`, so `error.body.code` still compiles. + expectTypeOf(get("/x", { error: Schema.Any })).toEqualTypeOf< + Effect.Effect< + Response, + NetworkError | HttpError.With | TimeoutError, + never + > + >(); + const Either = Schema.Union([ApiError, Schema.String]); + expectTypeOf(get("/x", { error: Either })).toEqualTypeOf< + Effect.Effect< + Response, + | NetworkError + | HttpError.With<{ readonly code: string } | string> + | TimeoutError, + never + > + >(); + }); + + it("narrows by _tag in code generic over the error schema", () => { + // `catchTag` can't read the tag of the still-open conditional member; + // checking `_tag` works. + const status = ( + error: CallError, + ) => (error._tag === "HttpError" ? error.status : 0); + expectTypeOf(status).returns.toEqualTypeOf(); + }); + it("fits CallEffect, CallError and CallServices in generic code", () => { // The methods write these types out (so hovers show the members); // wrappers generic over the schemas must still accept them. diff --git a/test/types/endpoint.test-d.ts b/test/types/endpoint.test-d.ts index 04651c4..7f2fb82 100644 --- a/test/types/endpoint.test-d.ts +++ b/test/types/endpoint.test-d.ts @@ -294,11 +294,7 @@ describe("return type", () => { expectTypeOf( endpoint("DELETE /todos/:id")({ params: { id: 1 } }), ).toEqualTypeOf< - Effect.Effect< - Response, - NetworkError | HttpError.With | TimeoutError, - never - > + Effect.Effect >(); }); @@ -307,7 +303,7 @@ describe("return type", () => { expectTypeOf(getTodo({ params: { id: 1 } })).toEqualTypeOf< Effect.Effect< Todo, - NetworkError | HttpError.With | DecodeError | TimeoutError, + NetworkError | HttpError | DecodeError | TimeoutError, never > >(); diff --git a/test/types/make.test-d.ts b/test/types/make.test-d.ts index 2099b63..c3a2c8c 100644 --- a/test/types/make.test-d.ts +++ b/test/types/make.test-d.ts @@ -168,7 +168,7 @@ describe("make with plugins written inline", () => { >().toEqualTypeOf(); const call = inlineApi.get("/todos"); expectTypeOf>().toEqualTypeOf< - Fetch.NetworkError | Fetch.HttpError.With + Fetch.NetworkError | Fetch.HttpError >(); inlineApi.get("/todos", { plugins: { plain: false, withOptions: { version: "2" } }, @@ -189,7 +189,7 @@ describe("Client with plugins", () => { const call = plugged.get("/todos", { output: Todo }); expectTypeOf>().toEqualTypeOf< | Fetch.NetworkError - | Fetch.HttpError.With + | Fetch.HttpError | Fetch.DecodeError | TokenError | Unavailable diff --git a/test/types/plugin.test-d.ts b/test/types/plugin.test-d.ts index b3b1b6d..d3a319f 100644 --- a/test/types/plugin.test-d.ts +++ b/test/types/plugin.test-d.ts @@ -287,6 +287,14 @@ describe("Plugin.Overrides", () => { void [ok, wrong, nonsense]; }); + it("takes {} for options typed unknown, as Partial does", () => { + type Loose = Plugin<"loose", never, never, unknown>; + expectTypeOf>().toEqualTypeOf(); + // @ts-expect-error: null isn't an override + const none: Plugin.Override = null; + void none; + }); + it("types option keys", () => { // @ts-expect-error times is a number const wrongType: Overrides = { retry: { times: "0" } }; diff --git a/test/types/response.test-d.ts b/test/types/response.test-d.ts index 8bbc153..ce5084a 100644 --- a/test/types/response.test-d.ts +++ b/test/types/response.test-d.ts @@ -21,11 +21,7 @@ declare const maybeApiError: typeof ApiError | undefined; describe("checkStatus", () => { it("keeps the response and types the body as unknown without a schema", () => { expectTypeOf(checkStatus(response)).toEqualTypeOf< - Effect.Effect< - HttpClientResponse.HttpClientResponse, - HttpError.With, - never - > + Effect.Effect >(); }); @@ -41,11 +37,7 @@ describe("checkStatus", () => { it("types the body as unknown when the schema may be undefined", () => { expectTypeOf(checkStatus(response, maybeApiError)).toEqualTypeOf< - Effect.Effect< - HttpClientResponse.HttpClientResponse, - HttpError.With, - never - > + Effect.Effect >(); }); diff --git a/test/types/streams.test-d.ts b/test/types/streams.test-d.ts index b57b76e..88f65f2 100644 --- a/test/types/streams.test-d.ts +++ b/test/types/streams.test-d.ts @@ -45,9 +45,7 @@ describe("api.sse and api.ndjson", () => { expectTypeOf(api.sse("/events")).toEqualTypeOf< Stream.Stream< Fetch.SseEvent, - | Fetch.NetworkError - | Fetch.HttpError.With - | Fetch.DecodeError, + Fetch.NetworkError | Fetch.HttpError | Fetch.DecodeError, never > >(); @@ -182,9 +180,7 @@ describe("stream endpoints", () => { expectTypeOf(api.bind(plain)()).toEqualTypeOf< Effect.Effect< { readonly id: number }, - | Fetch.NetworkError - | Fetch.HttpError.With - | Fetch.DecodeError, + Fetch.NetworkError | Fetch.HttpError | Fetch.DecodeError, never > >(); From 4678f95717cc513c2abba3efc15f56bb99714190 Mon Sep 17 00:00:00 2001 From: monarcode Date: Tue, 24 Nov 2026 18:22:29 +0100 Subject: [PATCH 3/3] chore: release 0.1.0-rc.5 - Drop the Expo-only `npx expo install effect` step from the README and installation docs - Tighten DecodeError's summary and regenerate the reference - Remove an unused Stream import from the type tests --- CHANGELOG.md | 2 +- README.md | 7 ------- package.json | 2 +- site/content/docs/(latest)/installation.mdx | 9 +-------- site/content/docs/(latest)/reference/fetch.mdx | 2 +- src/Errors.ts | 5 ++--- test/types/endpoints-service.test-d.ts | 1 - 7 files changed, 6 insertions(+), 22 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 2cc87bd..5e737d1 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,7 +2,7 @@ All notable changes to `@monarcode/effetch`, newest first. -## Unreleased +## 0.1.0-rc.5 ### Added diff --git a/README.md b/README.md index e5e328a..ec7d7d7 100644 --- a/README.md +++ b/README.md @@ -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; diff --git a/package.json b/package.json index e19c2c2..68a7b4d 100644 --- a/package.json +++ b/package.json @@ -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", diff --git a/site/content/docs/(latest)/installation.mdx b/site/content/docs/(latest)/installation.mdx index 490a20c..2bd237c 100644 --- a/site/content/docs/(latest)/installation.mdx +++ b/site/content/docs/(latest)/installation.mdx @@ -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 diff --git a/site/content/docs/(latest)/reference/fetch.mdx b/site/content/docs/(latest)/reference/fetch.mdx index 7c4f8b4..9be7571 100644 --- a/site/content/docs/(latest)/reference/fetch.mdx +++ b/site/content/docs/(latest)/reference/fetch.mdx @@ -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. diff --git a/src/Errors.ts b/src/Errors.ts index 20b6acf..71327ab 100644 --- a/src/Errors.ts +++ b/src/Errors.ts @@ -139,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. diff --git a/test/types/endpoints-service.test-d.ts b/test/types/endpoints-service.test-d.ts index a6a6c56..281dcb4 100644 --- a/test/types/endpoints-service.test-d.ts +++ b/test/types/endpoints-service.test-d.ts @@ -7,7 +7,6 @@ import * as Effect from "effect/Effect"; import * as HttpClientRequest from "effect/http/HttpClientRequest"; import type * as Layer from "effect/Layer"; import * as Schema from "effect/Schema"; -import type * as Stream from "effect/Stream"; import { describe, expectTypeOf, it } from "vitest";