@akilin/api-kit 0.0.0-stage → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 akilin
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,289 @@
1
- # Temporary Holding Version
1
+ # @akilin/api-kit
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ > **Personal project — not intended for use by others; no support or stability guarantees.**
4
+
5
+ Library-agnostic TypeScript API client for ASP.NET Core APIs built with `akilin.ApiKit` (RFC 9457 Problem Details
6
+ with stable error codes). ESM-only, zero runtime dependencies; runs in browsers and React Native.
7
+
8
+ ## Runtime
9
+
10
+ - ESM-only: there is no CommonJS build. React Native's Jest preset runs CommonJS, so let it transform the package:
11
+ `transformIgnorePatterns: ['node_modules/(?!((jest-)?react-native|@react-native(-community)?|@akilin/api-kit)/)']`.
12
+ - Compiled to ES2022 (class `#private` fields, `Error` `cause`): Safari 15+ and other current browsers, Node 24+ (what
13
+ the tests run on), React Native (Hermes). It needs a global `fetch` (or the `fetch` option) and `AbortController`.
14
+
15
+ ## Setup
16
+
17
+ Pass the generated error map: `createApi<AppErrors>(…)`. TypeScript can't infer it from the options, so without it
18
+ the client is typed against an empty map (no codes) and the first `.on(errorCodes.…)` fails to compile with
19
+ "not assignable to parameter of type 'never'". Every type that takes the map defaults to that empty one, so pass it
20
+ there too: `ApiError<AppErrors>`, `ApiResult<T, AppErrors>`, `ApiOptions<AppErrors>`. `e instanceof ApiError` narrows
21
+ to an error of any kind with untyped codes (`ApiError<Record<string, unknown>>`). The option groups are exported as
22
+ `RequestDefaults` (`headers`, `credentials`, `fetch`, `timeout`) and `Policies<AppErrors>`.
23
+
24
+ ### One client for the app
25
+
26
+ Create the client once, in a module of its own, and hand out that one instance, here through a `useApi` hook. Calls
27
+ made through it are typed from `AppErrors` without passing the map again: `.on(code, …)` types the error's `payload`
28
+ from the code.
29
+
30
+ ```ts
31
+ // api.ts
32
+ import { createApi } from '@akilin/api-kit';
33
+ import type { AppErrors } from './api-types.g';
34
+
35
+ const api = createApi<AppErrors>({
36
+ baseUrl: '/api',
37
+ onUnauthorized: () => router.navigate('/login'),
38
+ onUnexpected: () => router.navigate('/error'),
39
+ defaultErrorCodeHandler: (e) => toast(t(`errorCodes.${e.code}`, e.payload)),
40
+ });
41
+
42
+ export function useApi() {
43
+ return api;
44
+ }
45
+ ```
46
+
47
+ ```ts
48
+ // in a component
49
+ import { errorCodes, type User } from './api-types.g';
50
+
51
+ const api = useApi();
52
+
53
+ api.get<User>('/users/1')
54
+ .on(errorCodes.users.planRequired, (e) => {
55
+ e.payload.plan; // Plan
56
+ e.payload.limit; // compile error: limitReached's payload, not planRequired's
57
+ });
58
+ ```
59
+
60
+ - Call `createApi` outside the hook, not in its body. Then `useApi()` returns the same object on every render, so it
61
+ is safe in a `useEffect` dependency list, and the telemetry cap (see [Telemetry](#telemetry)) counts the app's
62
+ traces, not one render's.
63
+ - The handler gets the whole error, with its `code`, `status`, `field`, `headers` and `traceId` as well as `payload`.
64
+ - Pass the code from the generated `errorCodes` (or as a string literal). Its literal type selects the payload type; a
65
+ value typed `string` doesn't compile.
66
+ - Policies are fixed when the client is created, so they can't call React hooks: call a router instance or
67
+ `location` (see [Global error policies](#global-error-policies)).
68
+ - Type annotations you write yourself still take the map: `ApiError<AppErrors>`, `ApiResult<User, AppErrors>`.
69
+
70
+ The request and response types come from the generated file too, beside `AppErrors`: the generator writes every JSON
71
+ request body type and 2xx response body type of the API's endpoints, and the types nested in them, under their C#
72
+ names. Import them from there rather than declaring your own, so the compiler reports a DTO that changed on the
73
+ server once the file is regenerated. `User`, `Order` and the other types in the examples here are such generated
74
+ types. The client doesn't tie a route to its types: a call names the type it reads (`api.get<User>('/users/1')`), and
75
+ the body you pass is typed by your own annotation (`const form: CreateUser = …`).
76
+
77
+ `baseUrl` and the per-call url are joined with exactly one `/`, whichever side has it: `/api/` + `/users` and `/api` +
78
+ `users` both fetch `/api/users`. A url that is empty or starts with `?`/`#` is appended as it is (`/api/users` +
79
+ `?page=2`). An absolute per-call url (`https://files.example.com/a.pdf`, `//host/…`) is fetched as it is, without
80
+ `baseUrl`; any other `name:` start is a path (`items:batchGet` fetches `/api/items:batchGet`).
81
+
82
+ ### Headers, credentials, fetch, timeout
83
+
84
+ ```ts
85
+ export const api = createApi<AppErrors>({
86
+ baseUrl: 'https://api.example.com',
87
+ headers: async () => ({ Authorization: `Bearer ${await auth.token()}` }), // or a plain object; called per request
88
+ credentials: 'include', // cookie auth on another origin (fetch's default, 'same-origin', sends no cookies there)
89
+ fetch: myFetch, // optional; default: the global fetch
90
+ timeout: 10_000, // ms; optional; default: 30 000; 0 or Infinity turns it off
91
+ // …the three policies below
92
+ });
93
+
94
+ await api.put(`/users/${id}`, user, { headers: { 'If-Match': etag } }); // per call, over the client's by name
95
+ await api.post('/files', file, { timeout: 0 }); // per call, over the client's: no timeout for a large upload
96
+ ```
97
+
98
+ - `headers`, `credentials`, `fetch` and `timeout` apply to every request, telemetry traces included (`headers` only on
99
+ the API's origin, see below). A call's own `headers` replace the client's of the same name, whatever the case.
100
+ - Every request has a timeout, 30 seconds unless you set another: on the client, or on a call (which wins). It runs
101
+ from the call to the end of the response body, the `headers` function included, so give a large upload or download a
102
+ longer one, or `0` for none. A request over it is cancelled and fails as kind `network`, with an error named
103
+ `TimeoutError` as `cause`, so it goes to `onUnexpected`.
104
+ - `Infinity`, or anything from 2³¹−1 ms (~24.8 days, the most a timer can wait) up, is none too. A negative or `NaN`
105
+ timeout throws a `RangeError`: on the client at `createApi`, on a call at the call (nothing is sent).
106
+ - The client's `headers` (an `Authorization` token, say) go only to the origin of `baseUrl`, or the page's when
107
+ `baseUrl` is relative or empty. An absolute per-call url on another origin (a file link the server returned, a
108
+ third-party URL) gets none of them, and the `headers` function isn't called for it; pass the call's own `headers` to
109
+ send some there. Origins are compared as written, case aside: `https://api.example.com:443` and
110
+ `//api.example.com` are not `https://api.example.com`, so write absolute urls to the API the way `baseUrl` is written,
111
+ or use paths.
112
+ - If the `headers` function throws or rejects, nothing is sent and the call fails as kind `network`, with what it threw
113
+ as `cause` (so it goes to `onUnexpected`).
114
+
115
+ ### Cancelling a call
116
+
117
+ Pass an `AbortSignal` as a call's `signal`. If it aborts, before the call or during it (the `headers` function and the
118
+ body included), the request is cancelled and the call fails as kind `aborted`, with the signal's `reason` as `cause`.
119
+ That error goes only to the caller: `await` rejects with it and `.result()` resolves with it, but no per-call handler,
120
+ `.onAnyError` or policy gets it (`.finally` still runs), and no telemetry trace is sent. A signal already aborted sends
121
+ nothing. A timeout is not an abort: it stays kind `network`, whichever comes first wins.
122
+
123
+ ```ts
124
+ // TanStack Query: it aborts the signal when the query is cancelled. `async`, so queryFn returns a Promise of the data.
125
+ useQuery({ queryKey: ['user', id], queryFn: async ({ signal }) => api.get<User>(`/users/${id}`, { signal }) });
126
+
127
+ // React: abort on cleanup. `.result()`, so the abort is no unhandled rejection.
128
+ useEffect(() => {
129
+ const controller = new AbortController();
130
+ void api.get<User>(`/users/${id}`, { signal: controller.signal }).result().then((r) => r.ok && setUser(r.data));
131
+ return () => controller.abort();
132
+ }, [id]);
133
+ ```
134
+
135
+ ### Responses
136
+
137
+ `get`, `post`, `put`, `patch` and `delete` resolve with the body, parsed as JSON (no reviver, so dates stay strings).
138
+ A 204 or an empty (or whitespace-only) body resolves with `undefined`. There is no other way to read a body: a success body that isn't JSON
139
+ fails as kind `unexpected`.
140
+
141
+ `.result()` also gives the response's status and headers on success (`r.ok && r.response.headers.get('ETag')`), and
142
+ `.onSuccess(fn)` gets them as its second argument. Problem and unexpected errors carry `headers` too
143
+ (`error.headers?.get('Retry-After')`).
144
+
145
+ `PagedData<T>` is the body of a paged list, as the server's `PagedData<T>` (package `akilin.ApiKit`) writes it:
146
+ `api.get<PagedData<User>>('/users', { query: { pageNumber: 2 } })` resolves with `{ data, totalPages }`. Import it
147
+ from this package (`import type { PagedData } from '@akilin/api-kit'`): the generated file imports it from here too
148
+ when one of its types has a `PagedData` member, and doesn't declare one of its own.
149
+
150
+ ## Per-call handlers
151
+
152
+ `.on(code)`, `.onFieldError(fn)` and `.onStatus(status, fn)` claim an error: the handler runs instead of a global
153
+ policy, and the error's `handled` is `true`. A network failure has no code, field or status, so no per-call handler
154
+ claims it.
155
+
156
+ `.on(code)` gets only 4xx problems. Every 5xx (a crash, or an app code thrown with a 5xx status) is kind `unexpected`,
157
+ so an `.on` handler for a 5xx code never runs. Use `.onStatus(503, …)` instead: an unexpected error whose body is a
158
+ problem keeps its `code`, untyped (`error.code === errorCodes.ops.maintenance`), and its `payload` when that is an
159
+ object (`{}` when the body has none). A 4xx problem whose `payload` isn't an object is kind `unexpected` too.
160
+
161
+ A problem about one field of the request has a `field`: its camelCase path (`name`, `address.zip`, `items[0].name`).
162
+ `.onFieldError(fn)` claims every such problem, whatever its code, so one handler can put the server's error on the
163
+ form. A response reports one field, the first check that failed:
164
+
165
+ ```ts
166
+ api.post<User>('/users', form)
167
+ .onFieldError((e) => setFieldError(e.field, t(`errorCodes.${e.code}`, e.payload)));
168
+ ```
169
+
170
+ A `.on(code)` handler for the problem's code wins over `.onFieldError`; the problem it gets has the `field` too.
171
+
172
+ `.onAnyError(fn)` observes every failed call, whatever the kind (`problem`, `unexpected` or `network`), except an
173
+ aborted one. It runs after
174
+ the per-call handler or the policy that dealt with the error has finished, and before `.finally`. It claims nothing:
175
+ the error's `handled` stays as it was, and the policies run as if it weren't registered.
176
+
177
+ ```ts
178
+ api.post<User>('/users', form)
179
+ .onFieldError(showOnField)
180
+ .onAnyError((e) => log('saving the user failed', e)); // also runs when .onFieldError or a policy got the error
181
+ ```
182
+
183
+ If the handler or the policy before it throws, `.onAnyError` doesn't run.
184
+
185
+ A `FormData`, `Blob`, `URLSearchParams`, `ArrayBuffer` or typed array/`DataView` body is sent as it is, with no
186
+ `Content-Type` from the client: fetch sets it (multipart, the Blob's type, `application/x-www-form-urlencoded`), or
187
+ pass one in `headers` for bytes. Any other body goes through `JSON.stringify` and is sent as JSON. A body that can't be
188
+ JSON-serialized (a `BigInt`, a cycle) throws at the call, like an invalid `Date` in `query`; nothing is sent.
189
+
190
+ `.finally` runs whatever the outcome: after `.onSuccess`, or after the error handler (or the policy) and
191
+ `.onAnyError`. It is not `Promise.prototype.finally`: it returns the request, not a new promise, so the chain goes on;
192
+ like every handler, it is registered once and before dispatch (a second `.finally`, or one after an `await`, throws);
193
+ and it runs whether or not anything awaits the call.
194
+
195
+ Handlers, policies, `.onSuccess` and `.finally` may return anything (`(e) => toast(e.code)`): the result is ignored,
196
+ after awaiting it if it is a promise. If one throws, `.finally` still runs, then `await` (and `.result()`) rejects with
197
+ what it threw, not with the `ApiError`: the rejection reason is `unknown`, so check it (`e instanceof ApiError`).
198
+
199
+ ## Global error policies
200
+
201
+ `createApi` requires three app-wide policies for errors that no per-call handler (`.on`, `.onFieldError`,
202
+ `.onStatus`) claimed:
203
+
204
+ ```ts
205
+ export const api = createApi<AppErrors>({
206
+ baseUrl: '/api',
207
+ onUnauthorized: (error) => navigate('/login'), // any 401: a problem, or a proxy's 401 without one
208
+ onUnexpected: (error) => navigate('/something-went-wrong'), // a crash, a non-problem response, a network failure
209
+ defaultErrorCodeHandler: (error) => toast(t(`errorCodes.${error.code}`, error.payload)), // any other problem
210
+ });
211
+ ```
212
+
213
+ - All three are required, so no unclaimed error is dropped because a policy was forgotten. To ignore a kind on
214
+ purpose, pass `() => {}` (e.g. `onUnauthorized` in an app without auth). A missing one fails to compile.
215
+ - Policies are fixed when the client is created. One that needs a router calls a router instance
216
+ (`router.navigate(...)`) or `location`, not a hook.
217
+ - Each unclaimed error goes to exactly one policy (an `aborted` call, to none). `defaultErrorCodeHandler` gets a problem: an error with a `code`.
218
+ It never gets a 401, which goes only to `onUnauthorized`, nor a 5xx, which is kind `unexpected` even with a code in
219
+ its body and goes to `onUnexpected`.
220
+ - A policy runs where a per-call handler would have: before `.onAnyError` and `.finally`, and before `await` /
221
+ `.result()` settle. Async policies are awaited. `await` still rejects afterwards, so code after the `await` never
222
+ runs on failure.
223
+ - `await` rejects even when a per-call handler claimed the error. In an event handler that nothing awaits (a React
224
+ `onSubmit`, say), that rejection is unhandled: it shows in the console and in error trackers. Use `.result()` there:
225
+
226
+ ```ts
227
+ async function onSubmit(form: Form) {
228
+ const r = await api.post<User>('/users', form).onFieldError(showOnField).result();
229
+ if (!r.ok) return; // a handler or a policy already dealt with it
230
+ navigate(`/users/${r.data.id}`);
231
+ }
232
+ ```
233
+ - **`onUnauthorized` must be idempotent.** Concurrent requests that all get a 401 each call it; there is no
234
+ de-duplication.
235
+ - `.result()` runs the policies exactly like `await`; it only avoids the rejection. Code after `.result()` runs even
236
+ when a policy redirected, so check `r.ok` (e.g. `if (!r.ok) return;`).
237
+ - `.skipDefaultErrorCodeHandler()` keeps one call's problems from `defaultErrorCodeHandler`, for a call that shows
238
+ its errors itself:
239
+
240
+ ```ts
241
+ const r = await api.post<Order>('/orders', cart).skipDefaultErrorCodeHandler().result();
242
+ if (!r.ok) showInlineError(r.error); // a problem went to no policy: no toast, handled === false
243
+ ```
244
+
245
+ Only that policy is skipped: a 401 still goes to `onUnauthorized`, and an unexpected response or a network failure
246
+ to `onUnexpected`. Per-call handlers, `.onAnyError` and `.finally` run as usual, and `await` still rejects.
247
+ - To keep a 401 from `onUnauthorized` for one call, claim it with `.onStatus(401, …)`:
248
+
249
+ ```ts
250
+ const r = await api.get<User>('/me').onStatus(401, () => {}).result();
251
+ if (!r.ok) showSignedOut(); // handled === true for the 401; onUnauthorized didn't run
252
+ ```
253
+ - Nothing claims every error of a call at once: `.onAnyError` only observes.
254
+
255
+ ## Telemetry
256
+
257
+ Every `unexpected` error (a crash, a non-problem response) is posted to the server's client-logs endpoint as a
258
+ trace, even when a per-call handler claimed it, up to the cap below. The server has that endpoint only if the app calls
259
+ `app.MapApiKitClientLogs()`. The client's defaults match that call's, so nothing needs configuring then. If the app
260
+ doesn't call it, turn telemetry off. `telemetry: false` turns it off, and no trace is sent:
261
+
262
+ ```ts
263
+ export const api = createApi<AppErrors>({
264
+ baseUrl: '/api',
265
+ // …the three policies above
266
+ telemetry: { url: '/api/client-logs', context: () => ({ appVersion, route: location.pathname }) }, // both optional
267
+ });
268
+ ```
269
+
270
+ - The trace is `{ kind, method, url, status?, traceId?, responseBodySnippet, durationMs, timestamp, context? }`: the
271
+ first 2,000 characters of the response body, never request bodies or headers. `url` is the URL that was fetched
272
+ (joined as above) **without its query or fragment**, which may carry tokens or personal data, cut at 2,000
273
+ characters.
274
+ - Keep `context()` small: the server rejects a trace over ~16 KB, and the client doesn't cut `context`.
275
+ - Only `unexpected` errors are reported. Network failures (which often can't reach the server anyway) and JS crashes
276
+ outside API calls are not, in v1.
277
+ - `telemetry.url` is not prefixed with `baseUrl`. A path goes to the origin of `baseUrl` (with
278
+ `baseUrl: 'https://api.example.com/v1'`, the default goes to `https://api.example.com/api/client-logs`); an absolute
279
+ URL is used as it is. Like any request, a trace gets the client's `headers` only on the origin of `baseUrl`.
280
+ - At most 10 traces per 60 seconds are sent per client (`createApi`), so an outage (a proxy answering every call with
281
+ a 502 page) doesn't add a telemetry request to every failed call. Traces beyond the cap are dropped silently: no
282
+ request, no `context()` call. The cap is fixed.
283
+ - The trace is posted with fetch's `keepalive`, so a full-page navigation in `onUnexpected` or `onUnauthorized`
284
+ (`location.href = …`) doesn't cancel it.
285
+ - Telemetry never delays a call and never reports its own failures. A failed telemetry request, a throwing `context()`
286
+ or a `context()` result that can't be serialized drops the trace silently.
287
+ - The endpoint is open to anyone unless the app sets a fallback authorization policy; with one, signed-out users'
288
+ traces get a 401. To also get those, open it to anonymous clients and rate limit it
289
+ (`app.MapApiKitClientLogs().AllowAnonymous().RequireRateLimiting(...)`).
@@ -0,0 +1,100 @@
1
+ /** Codes of an error map `E` (the generated `AppErrors`, code → payload). */
2
+ export type CodeOf<E> = keyof E & string;
3
+ interface ApiErrorBase extends Error {
4
+ /** `true` once a per-call handler (`.on`, `.onFieldError`, `.onStatus`) claimed the error. Never for `aborted`. */
5
+ readonly handled: boolean;
6
+ }
7
+ /**
8
+ * The error map as the client reads a body before it is typed as the app's: any string is a code, payloads `unknown`.
9
+ * What `instanceof ApiError` narrows to.
10
+ */
11
+ export type UntypedErrors = Record<string, unknown>;
12
+ /** A parsed ProblemDetails body. Narrowing on `code` types `payload`. */
13
+ export type ProblemError<E extends object = {}, C extends CodeOf<E> = CodeOf<E>> = {
14
+ [K in C]: ApiErrorBase & {
15
+ readonly kind: 'problem';
16
+ readonly code: K;
17
+ readonly status: number;
18
+ /** The response headers (e.g. `Retry-After`); absent on an error built by hand. */
19
+ readonly headers?: Headers;
20
+ /** The body's `payload` member. `{}` for plain codes, which have none. */
21
+ readonly payload: E[K];
22
+ /**
23
+ * The camelCase path of the request field the error is about: `name`, `address.zip`, `items[0].name`.
24
+ * Absent when the error isn't about one field.
25
+ */
26
+ readonly field?: string;
27
+ readonly traceId: string | undefined;
28
+ };
29
+ }[C];
30
+ export type FieldError<E extends object = {}> = ProblemError<E> & {
31
+ readonly field: string;
32
+ };
33
+ /**
34
+ * What a failed request rejects with. `E` is the app's error map (the generated `AppErrors`); pass it, as to
35
+ * `createApi`: without it the map is empty, so there is no code and no kind `problem`.
36
+ */
37
+ export type ApiError<E extends object = {}> = ProblemError<E> | NetworkError | UnexpectedError | AbortedError;
38
+ /**
39
+ * Kind `network`: `fetch` itself threw (or reading the body failed), or the request timed out: the client's or the
40
+ * call's `timeout` passed. `cause` is what was thrown; for a timeout it is an error named `TimeoutError`.
41
+ */
42
+ export type NetworkError = ApiErrorBase & NetworkInit;
43
+ /**
44
+ * Kind `unexpected`: a response outside the contract. An error status whose body isn't a parseable
45
+ * `application/problem+json` object with a `code` (and, if it has a `payload`, one that is an object), any 5xx (problem
46
+ * or not), or a success body that isn't the JSON it should be. `cause` is the parse error, when there was one.
47
+ */
48
+ export type UnexpectedError = ApiErrorBase & UnexpectedInit;
49
+ /**
50
+ * Kind `aborted`: the call's own `signal` aborted, before or during the request. It goes only to the caller (`await`
51
+ * rejects, `.result()` resolves with it): no handler or policy gets it and no telemetry trace is sent. `cause` is the
52
+ * signal's `reason`. A timeout is not this: it is kind `network`.
53
+ */
54
+ export type AbortedError = ApiErrorBase & AbortedInit;
55
+ interface ProblemInit {
56
+ readonly kind: 'problem';
57
+ readonly code: string;
58
+ readonly status: number;
59
+ readonly headers?: Headers;
60
+ readonly payload: unknown;
61
+ /** Only for a problem about one field of the request. */
62
+ readonly field?: string;
63
+ readonly traceId: string | undefined;
64
+ }
65
+ interface NetworkInit {
66
+ readonly kind: 'network';
67
+ readonly cause: unknown;
68
+ }
69
+ interface UnexpectedInit {
70
+ readonly kind: 'unexpected';
71
+ readonly status: number;
72
+ /** The response headers; absent on an error built by hand. */
73
+ readonly headers?: Headers;
74
+ /** From the body when it is a problem (5xx problems carry one), else `undefined`. */
75
+ readonly traceId: string | undefined;
76
+ /**
77
+ * The body's `code` when it is a problem with one (a 5xx problem: an app code thrown with a 5xx status, or
78
+ * `http.internal-server-error`), else `undefined`. Untyped: 5xx codes never reach `.on`.
79
+ */
80
+ readonly code?: string;
81
+ /**
82
+ * The `payload` of such a problem body, untyped (`{}` when it has none); `undefined` when `code` is, or when the
83
+ * body's `payload` isn't an object.
84
+ */
85
+ readonly payload?: Readonly<Record<string, unknown>>;
86
+ readonly responseText: string;
87
+ readonly cause?: unknown;
88
+ }
89
+ interface AbortedInit {
90
+ readonly kind: 'aborted';
91
+ readonly cause: unknown;
92
+ }
93
+ export type ApiErrorInit = ProblemInit | NetworkInit | UnexpectedInit | AbortedInit;
94
+ /**
95
+ * Runtime constructor of {@link ApiError}, for `instanceof` checks. The class knows no error map, so `instanceof`
96
+ * narrows to an error of any kind whose codes are plain strings (`ApiError<Record<string, unknown>>`).
97
+ */
98
+ export declare const ApiError: new (init: ApiErrorInit) => ApiError<UntypedErrors>;
99
+ export declare function markHandled(error: ApiError<UntypedErrors>): void;
100
+ export {};
@@ -0,0 +1,30 @@
1
+ // One class for every kind, so `instanceof ApiError` covers them all. A class can't be a discriminated union, so it is
2
+ // exported cast to the `ApiError` union.
3
+ class ApiErrorClass extends Error {
4
+ name = 'ApiError';
5
+ handled = false;
6
+ constructor(init) {
7
+ super(message(init), 'cause' in init && init.cause !== undefined ? { cause: init.cause } : undefined);
8
+ Object.assign(this, init);
9
+ }
10
+ }
11
+ function message(init) {
12
+ switch (init.kind) {
13
+ case 'problem':
14
+ return `API error ${init.status} ${init.code}`;
15
+ case 'unexpected':
16
+ return `API request failed: unexpected response (status ${init.status}${init.code ? ` ${init.code}` : ''})`;
17
+ case 'network':
18
+ return 'API request failed: network error';
19
+ case 'aborted':
20
+ return 'API request aborted';
21
+ }
22
+ }
23
+ /**
24
+ * Runtime constructor of {@link ApiError}, for `instanceof` checks. The class knows no error map, so `instanceof`
25
+ * narrows to an error of any kind whose codes are plain strings (`ApiError<Record<string, unknown>>`).
26
+ */
27
+ export const ApiError = ApiErrorClass;
28
+ export function markHandled(error) {
29
+ error.handled = true;
30
+ }
package/dist/body.d.ts ADDED
@@ -0,0 +1,2 @@
1
+ import type { SendRequest } from './send.js';
2
+ export declare function jsonBody(body: unknown): SendRequest['body'];
package/dist/body.js ADDED
@@ -0,0 +1,20 @@
1
+ // Read off `globalThis`, not named as a global: URLSearchParams is outside the platform subset (incomplete in React
2
+ // Native). The client only recognizes the caller's own instance, to hand it to fetch; it never builds or reads one.
3
+ const searchParams = () => globalThis.URLSearchParams;
4
+ /** What fetch takes as it is, setting the content type itself (form, multipart boundary, the Blob's type) or none. */
5
+ function isRawBody(body) {
6
+ // The `typeof` guards: a platform may lack any of these globals.
7
+ if (typeof FormData !== 'undefined' && body instanceof FormData)
8
+ return true;
9
+ if (typeof Blob !== 'undefined' && body instanceof Blob)
10
+ return true;
11
+ const SearchParams = searchParams();
12
+ if (SearchParams && body instanceof SearchParams)
13
+ return true;
14
+ return body instanceof ArrayBuffer || ArrayBuffer.isView(body);
15
+ }
16
+ export function jsonBody(body) {
17
+ if (body === undefined || isRawBody(body))
18
+ return body;
19
+ return JSON.stringify(body);
20
+ }
@@ -0,0 +1,65 @@
1
+ import { ApiRequest, type Policies } from './request.js';
2
+ import { type Query } from './query.js';
3
+ import { type RequestDefaults, type RequestHeaders } from './send.js';
4
+ import { type TelemetryOptions } from './telemetry.js';
5
+ export interface ApiOptions<E extends object = {}> extends RequestDefaults, Policies<E> {
6
+ /**
7
+ * Prefix for every request URL, e.g. `/api` or `https://api.example.com`. Default: `''`. Joined with exactly one `/`
8
+ * whichever side has it (`/api/` + `/users` and `/api` + `users` are both `/api/users`); a url that is empty or
9
+ * starts with `?`/`#` is appended as it is. An absolute per-call url (`https://…`, `//host/…`) is not prefixed.
10
+ */
11
+ readonly baseUrl?: string;
12
+ /**
13
+ * Where and with what every `unexpected` error is reported. Default: `/api/client-logs`, no context; `false` sends
14
+ * no trace at all. At most 10 traces per 60 s per client are sent; the rest are dropped silently, and so is a trace
15
+ * that fails.
16
+ */
17
+ readonly telemetry?: TelemetryOptions | false;
18
+ }
19
+ export interface RequestOptions {
20
+ /**
21
+ * Added to the URL's query, before any `#fragment`: arrays as repeated keys, `null`/`undefined` skipped, `Date` as an
22
+ * ISO string.
23
+ */
24
+ readonly query?: Query;
25
+ /**
26
+ * How long this call may take, in ms, over the client's `timeout` (default 30 000); `0`, `Infinity` or anything from
27
+ * 2³¹−1 up turns the timeout off, for a large upload or download, say. A negative or `NaN` one throws a `RangeError`
28
+ * at the call. A call over it is cancelled and fails as kind `network`, with a `TimeoutError` as `cause`.
29
+ */
30
+ readonly timeout?: number;
31
+ /** Headers for this call only (`If-Match`, say), over the client's `headers` by name, whatever the case. */
32
+ readonly headers?: RequestHeaders;
33
+ /**
34
+ * Cancels the call when it aborts, before or during the request (the `headers` function included). The call then
35
+ * fails as kind `aborted`, which goes only to the caller: `await` rejects, `.result()` resolves with it; no handler
36
+ * or policy runs (`.finally` does) and no telemetry trace is sent.
37
+ */
38
+ readonly signal?: AbortSignal;
39
+ }
40
+ /**
41
+ * Every method resolves with the success body parsed as JSON (no reviver, so dates stay strings), or with `undefined`
42
+ * for a 204 or an empty (or whitespace-only) body. A success body that isn't JSON fails as kind `unexpected`.
43
+ */
44
+ export interface Api<E extends object = {}> {
45
+ get<T>(url: string, opts?: RequestOptions): ApiRequest<T, E>;
46
+ /**
47
+ * `FormData`, `Blob`, `URLSearchParams`, `ArrayBuffer` and typed arrays/`DataView` as `body` go as they are, the
48
+ * content type left to fetch; anything else is JSON-serialized with `Content-Type: application/json`. A body that
49
+ * can't be (a `BigInt`, a cycle) throws at the call; nothing is sent.
50
+ */
51
+ post<T>(url: string, body?: unknown, opts?: RequestOptions): ApiRequest<T, E>;
52
+ /** Takes `body` like {@link Api.post}. */
53
+ put<T>(url: string, body?: unknown, opts?: RequestOptions): ApiRequest<T, E>;
54
+ /** Takes `body` like {@link Api.post}. */
55
+ patch<T>(url: string, body?: unknown, opts?: RequestOptions): ApiRequest<T, E>;
56
+ delete<T>(url: string, opts?: RequestOptions): ApiRequest<T, E>;
57
+ }
58
+ /**
59
+ * Always pass the generated error map, `createApi<AppErrors>(…)`: nothing in the options lets TypeScript infer it, so
60
+ * without it the client is typed against an empty map (`{}`, no codes) and the first `.on(code)` fails to compile with
61
+ * "not assignable to parameter of type 'never'".
62
+ *
63
+ * The three policies are required, so an unclaimed error never goes unnoticed by accident.
64
+ */
65
+ export declare function createApi<E extends object = {}>(options: ApiOptions<E>): Api<E>;
@@ -0,0 +1,48 @@
1
+ import { jsonBody } from './body.js';
2
+ import { assertTimeout } from './deadline.js';
3
+ import { ApiRequest } from './request.js';
4
+ import { withQuery } from './query.js';
5
+ import { send } from './send.js';
6
+ import { createReporter } from './telemetry.js';
7
+ /**
8
+ * Always pass the generated error map, `createApi<AppErrors>(…)`: nothing in the options lets TypeScript infer it, so
9
+ * without it the client is typed against an empty map (`{}`, no codes) and the first `.on(code)` fails to compile with
10
+ * "not assignable to parameter of type 'never'".
11
+ *
12
+ * The three policies are required, so an unclaimed error never goes unnoticed by accident.
13
+ */
14
+ export function createApi(options) {
15
+ const { headers, credentials, fetch, timeout } = options;
16
+ assertTimeout(timeout);
17
+ const config = { baseUrl: options.baseUrl ?? '', headers, credentials, fetch, timeout };
18
+ const report = options.telemetry === false ? undefined : createReporter(config, options.telemetry);
19
+ const request = (method, url, body, opts = {}) => {
20
+ // Built here, not in `dispatch`, so a bad query value (an invalid Date), a body that can't be serialized (a
21
+ // BigInt, a cycle) or a negative timeout throws at the call.
22
+ assertTimeout(opts.timeout);
23
+ const req = {
24
+ method,
25
+ url: withQuery(url, opts.query),
26
+ body: jsonBody(body),
27
+ headers: opts.headers,
28
+ timeout: opts.timeout,
29
+ signal: opts.signal,
30
+ };
31
+ const dispatch = async () => {
32
+ const started = Date.now();
33
+ const outcome = await send(config, req);
34
+ // Reported here, before any handler runs: telemetry fires even when a per-call handler claims the error.
35
+ if (!outcome.ok && outcome.error.kind === 'unexpected')
36
+ report?.(req, outcome.error, Date.now() - started);
37
+ return outcome;
38
+ };
39
+ return new ApiRequest(dispatch, options);
40
+ };
41
+ return {
42
+ get: (url, opts) => request('GET', url, undefined, opts),
43
+ post: (url, body, opts) => request('POST', url, body, opts),
44
+ put: (url, body, opts) => request('PUT', url, body, opts),
45
+ patch: (url, body, opts) => request('PATCH', url, body, opts),
46
+ delete: (url, opts) => request('DELETE', url, undefined, opts),
47
+ };
48
+ }
@@ -0,0 +1,16 @@
1
+ import type { Outcome } from './response.js';
2
+ export declare const defaultTimeoutMs = 30000;
3
+ /** Throws at the call, like a body that can't be serialized: a negative or NaN timeout is a bug, not a no-timeout. */
4
+ export declare function assertTimeout(timeoutMs: number | undefined): void;
5
+ interface Deadline {
6
+ /** For fetch: aborts at the timeout or when the caller's signal does. */
7
+ readonly signal: AbortSignal | undefined;
8
+ /** Resolves with the failure at whichever comes first, the timeout or the caller's abort; else never. */
9
+ readonly expired: Promise<Outcome<never>>;
10
+ /** Stops the timer and removes the listener from the caller's signal, which may outlive the request. */
11
+ readonly clear: () => void;
12
+ }
13
+ /** The end of a request other than its answer: the timeout, or the caller's `signal` aborting. */
14
+ export declare function startDeadline(timeoutMs: number, callerSignal: AbortSignal | undefined): Deadline;
15
+ export declare function aborted(signal: AbortSignal): Outcome<never>;
16
+ export {};