arthron 1.0.0 → 1.1.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.
@@ -0,0 +1,293 @@
1
+ //#region src/types/request.types.d.ts
2
+ /**
3
+ * What plugins see and return. `init.headers` is always a plain record with
4
+ * lowercased names — spread it, read it, add to it — and the pipeline puts
5
+ * it back into that shape after every request interceptor.
6
+ */
7
+ interface RequestContext {
8
+ url: string;
9
+ init: Omit<RequestInit, "headers"> & {
10
+ headers: Record<string, string>;
11
+ };
12
+ /** Per-call settings for plugins (`RequestOptions.meta`); never sent. */
13
+ meta: ArthronMeta;
14
+ }
15
+ /**
16
+ * Per-call settings for plugins, passed as `api.get(path, { meta })` and
17
+ * carried next to `init` — never sent to fetch. The built-in plugins read
18
+ * `bearerAuth`, `retry` and `timeout`; your own add keys by augmentation:
19
+ *
20
+ * ```ts
21
+ * declare module "arthron" {
22
+ * interface ArthronMeta { skipTrace?: boolean }
23
+ * }
24
+ * ```
25
+ */
26
+ interface ArthronMeta {
27
+ /**
28
+ * `false` sends this call without the `bearerAuth()` token and never refreshes
29
+ * on its 401 — for the login and token-refresh endpoints.
30
+ */
31
+ bearerAuth?: false;
32
+ /** `false` turns `retry()` off for this call; an object overrides its options. */
33
+ retry?: false | Omit<RetryOptions, "sleep">;
34
+ /** Deadline for this call in ms, overriding `timeout(ms)`. `Infinity` lifts it. */
35
+ timeout?: number;
36
+ }
37
+ type RetryOptions = {
38
+ /** Number of retries after the first attempt. Default 2 (3 requests total). */
39
+ retries?: number;
40
+ /** Statuses worth retrying. Network errors (status 0) always are. */
41
+ retryOn?: readonly number[];
42
+ /** Methods safe to repeat (QUERY is, per RFC 10008). Compared case-insensitively. */
43
+ methods?: readonly string[];
44
+ /**
45
+ * Backoff in ms for retry number `retry` (0-based). Default "full jitter":
46
+ * a random share of 300 · 2^retry, so clients that failed together do not
47
+ * retry together.
48
+ */
49
+ delay?: (retry: number, error: unknown) => number;
50
+ /**
51
+ * Your own verdict on one failure: `true` retries, `false` stops,
52
+ * `undefined` leaves it to `retryOn`/`methods`. It sees every error — a
53
+ * TimeoutError from a `timeout()` placed after `retry()` included — but
54
+ * cannot exceed `retries`, resend a `ReadableStream` body, or retry a call
55
+ * the caller aborted.
56
+ */
57
+ shouldRetry?: (error: unknown, attempt: number, ctx: RequestContext) => boolean | undefined;
58
+ /** Called before each wait, for logs and metrics. */
59
+ onRetry?: (error: unknown, attempt: number, waitMs: number) => void;
60
+ /** Injectable for tests. Default `setTimeout`; rejects with the abort reason. */
61
+ sleep?: (ms: number, signal?: AbortSignal | null) => Promise<void>;
62
+ /**
63
+ * Longest `Retry-After` (ms) worth honouring. Beyond it the request is not
64
+ * retried at all. Default 60 000.
65
+ */
66
+ maxRetryAfter?: number;
67
+ };
68
+ type QueryValue = string | number | boolean | null | undefined;
69
+ /**
70
+ * Query parameters. `null`/`undefined` values are skipped, an array becomes
71
+ * repeated keys (`ids=1&ids=2`), and a `URLSearchParams` is used as is.
72
+ */
73
+ type QueryParams = Record<string, QueryValue | readonly QueryValue[]> | URLSearchParams;
74
+ /**
75
+ * Headers as config and per-call options accept them: anything fetch's
76
+ * `headers` takes, or a plain object whose `null`/`undefined` values delete
77
+ * that header from the layer underneath (a client default, an inherited
78
+ * header). Not spelled `HeadersInit`: that name exists only in the DOM lib,
79
+ * and a Node project typed with `@types/node` alone does not have it.
80
+ */
81
+ type HeadersOption = NonNullable<RequestInit["headers"]> | Record<string, string | null | undefined>;
82
+ //#endregion
83
+ //#region src/error/arthron-error.d.ts
84
+ type ArthronErrorInit = {
85
+ message: string;
86
+ status: number;
87
+ statusText: string;
88
+ headers: Headers;
89
+ data: unknown;
90
+ detail?: string | undefined;
91
+ request: RequestContext;
92
+ response?: Response;
93
+ cause?: unknown;
94
+ };
95
+ /**
96
+ * The only error arthron itself produces. Two sources: a response with
97
+ * `ok === false`, or fetch rejecting outright (network failure, `status` 0).
98
+ * Everything else — cancellation, interceptor bugs — is rethrown untouched.
99
+ */
100
+ declare class ArthronError extends Error {
101
+ readonly name = "ArthronError";
102
+ /** HTTP status of the failed response; `0` when fetch itself failed (network). */
103
+ readonly status: number;
104
+ readonly statusText: string;
105
+ /** Response headers; empty for network failures. Not enumerable — kept out of logs. */
106
+ readonly headers: Headers;
107
+ /** Parsed body: JSON if it parses, else the text, else `undefined`. */
108
+ readonly data: unknown;
109
+ /**
110
+ * The server's own explanation, picked out of `data` (by default
111
+ * `message` → `error` → `error.message` → `detail`; see the `errorDetail`
112
+ * config). `undefined` when the body had none. Untrusted server text: show
113
+ * it to users as text, never as HTML. `message`, by contrast, is written by
114
+ * arthron — method, URL without query, status — and is meant for logs.
115
+ */
116
+ readonly detail: string | undefined;
117
+ /**
118
+ * The context that was sent — url and init after request interceptors.
119
+ * Not enumerable: it holds credentials, so `JSON.stringify`, `console.error`
120
+ * and error trackers leave it out. Read it directly when you need it.
121
+ */
122
+ readonly request: RequestContext;
123
+ /** The failed Response, still readable — its body holds what arthron read (at most 64 KiB). Absent for network failures. Not enumerable. */
124
+ readonly response: Response | undefined;
125
+ /** The underlying error for network failures. */
126
+ readonly cause: unknown;
127
+ constructor(init: ArthronErrorInit);
128
+ /** `instanceof ArthronError` holds for an error from any copy of the package. */
129
+ static [Symbol.hasInstance](value: unknown): boolean;
130
+ /** What serializers see: no headers, no body, no query or userinfo. */
131
+ toJSON(): {
132
+ name: string;
133
+ message: string;
134
+ detail: string | undefined;
135
+ status: number;
136
+ statusText: string;
137
+ method: string;
138
+ url: string;
139
+ data: unknown;
140
+ };
141
+ }
142
+ /** `true` for errors arthron produced: a `!ok` response or a network failure. Cancellations and plugin bugs are not ArthronErrors. */
143
+ declare function isArthronError(error: unknown): error is ArthronError;
144
+ //#endregion
145
+ //#region src/types/plugin.types.d.ts
146
+ /** Runs before each attempt. Returns the context to send (may be a new object). */
147
+ type RequestInterceptor = (ctx: RequestContext) => RequestContext | Promise<RequestContext>;
148
+ /** Runs after a successful attempt. The body is single-use — `clone()` to peek. */
149
+ type ResponseInterceptor = (res: Response, ctx: RequestContext) => Response | Promise<Response>;
150
+ /** Runs after a failed attempt. Returns the error to throw; it is always thrown. */
151
+ type ErrorInterceptor = (err: ArthronError, ctx: RequestContext) => ArthronError | Promise<ArthronError>;
152
+ /**
153
+ * Wraps the whole call. `next` runs everything below it (request interceptors →
154
+ * fetch → response/error interceptors) and may be called again to retry.
155
+ * `next` rejects with an `ArthronError`, or with the untouched original when the
156
+ * failure was a cancellation or a bug in a plugin.
157
+ */
158
+ type Middleware = (ctx: RequestContext, next: (ctx: RequestContext) => Promise<Response>) => Promise<Response>;
159
+ interface Plugin {
160
+ /**
161
+ * Identity within a client: `use`/`extend` replace the plugin of the same
162
+ * name in place, `without(name)` removes it. The built-ins are named
163
+ * "bearerAuth", "logging", "retry" and "timeout". Leave it out to always
164
+ * append.
165
+ */
166
+ name?: string;
167
+ middleware?: Middleware;
168
+ request?: RequestInterceptor;
169
+ response?: ResponseInterceptor;
170
+ error?: ErrorInterceptor;
171
+ }
172
+ //#endregion
173
+ //#region src/plugins/bearer-auth/bearer-auth.types.d.ts
174
+ type BearerAuthOptions = {
175
+ /**
176
+ * Where the token may go: a URL, or several. Only their origins count, so
177
+ * your `baseURL` works as is. A request anywhere else — a CDN, a URL taken
178
+ * from a response body — is sent without the token.
179
+ */
180
+ origin: string | readonly string[];
181
+ /**
182
+ * The current access token, read on every attempt. `null`, `undefined` or
183
+ * `""` sends no `authorization` header.
184
+ */
185
+ token: () => string | null | undefined | Promise<string | null | undefined>;
186
+ /**
187
+ * Get a new token after a 401; the call is then redone once. Concurrent
188
+ * 401s share one refresh, and a call whose token was already replaced
189
+ * retries without one. Throw when the refresh fails — every waiting call
190
+ * rejects with that error. Requests the refresh makes through the same
191
+ * client need `meta: { bearerAuth: false }`. Without `refresh`, or for a
192
+ * `ReadableStream` body (already read, so it cannot be resent), a 401 is
193
+ * thrown as is.
194
+ */
195
+ refresh?: () => Promise<void>;
196
+ };
197
+ //#endregion
198
+ //#region src/plugins/bearer-auth/bearer-auth.d.ts
199
+ /**
200
+ * Bearer-token auth. A request interceptor sets `authorization: Bearer
201
+ * <token>` on every attempt to `origin`; with `refresh`, a middleware turns a
202
+ * 401 into one refresh and one more try. Concurrent 401s share the refresh
203
+ * (with refresh-token rotation, parallel refreshes revoke each other), and a
204
+ * call whose token was replaced meanwhile just retries. A call opts out with
205
+ * `meta: { bearerAuth: false }`.
206
+ */
207
+ declare function bearerAuth(options: BearerAuthOptions): Plugin;
208
+ //#endregion
209
+ //#region src/plugins/logging/logging.types.d.ts
210
+ type LogEventBase = {
211
+ method: string;
212
+ path: string;
213
+ };
214
+ type LogEvent = ({
215
+ phase: "start";
216
+ } & LogEventBase) | ({
217
+ phase: "success";
218
+ status: number;
219
+ ms: number;
220
+ } & LogEventBase) | ({
221
+ phase: "error";
222
+ /** HTTP status for an ArthronError (0 = network); undefined for anything else. */
223
+ status: number | undefined;
224
+ ms: number;
225
+ error: unknown;
226
+ } & LogEventBase);
227
+ type LoggingOptions = {
228
+ /** Default `true`. The library never reads `NODE_ENV` — pass `isDev` yourself. */
229
+ enabled?: boolean;
230
+ logger?: Pick<Console, "log" | "error">;
231
+ /** Receive structured events instead of the default console lines. */
232
+ onEvent?: (event: LogEvent) => void;
233
+ /** Clock in ms. Injectable for tests. */
234
+ now?: () => number;
235
+ };
236
+ //#endregion
237
+ //#region src/plugins/logging/logging.d.ts
238
+ /**
239
+ * One event when a request starts, one when it settles, with status and
240
+ * elapsed time. Wraps the whole call, so retries are included in the time.
241
+ * Default output is a console line per event; pass `onEvent` to get the
242
+ * structured event instead. Cancellations are not reported.
243
+ */
244
+ declare function logging(options?: LoggingOptions): Plugin;
245
+ //#endregion
246
+ //#region src/plugins/retry/retry.d.ts
247
+ /**
248
+ * Retry on network errors and the configured statuses by calling `next`
249
+ * again — the whole attempt (request interceptors included) is re-run.
250
+ * Only `ArthronError` is considered; cancellation and plugin bugs pass through.
251
+ * A call can turn it off or override its options with `meta.retry`.
252
+ */
253
+ declare function retry(options?: RetryOptions): Plugin;
254
+ //#endregion
255
+ //#region src/plugins/timeout/timeout.types.d.ts
256
+ type TimeoutOptions = {
257
+ /**
258
+ * Abort after this many ms in all, counted until the body has been fully
259
+ * read — the same deadline as `timeout(ms)`. Default: none.
260
+ */
261
+ total?: number;
262
+ /**
263
+ * Abort when no data has arrived for this many ms — while waiting for the
264
+ * headers and between body chunks. Unlike `total`, a stream that keeps
265
+ * flowing is never cut off: `timeout({ idle: 30_000 })`.
266
+ */
267
+ idle?: number;
268
+ };
269
+ //#endregion
270
+ //#region src/plugins/timeout/timeout.d.ts
271
+ /**
272
+ * Abort the request when it takes longer than `ms` — counted from the start
273
+ * of the attempt until the body has been fully read, so a server that sends
274
+ * headers and then stalls still trips it. `timeout({ idle })` instead aborts
275
+ * once no data has arrived for that long, and never cuts off a stream that
276
+ * keeps flowing; `timeout({ total, idle })` does both. Rejects with a
277
+ * `TimeoutError` (a `DOMException`, like `AbortSignal.timeout()` would give);
278
+ * it is not an `ArthronError`, so error interceptors and `retry` leave it
279
+ * alone.
280
+ *
281
+ * A call can change the total deadline with `meta.timeout`.
282
+ *
283
+ * Deadlines are timers on an AbortController — not `AbortSignal.timeout`,
284
+ * since the idle one restarts — joined to the caller's signal with
285
+ * `AbortSignal.any`.
286
+ */
287
+ declare function timeout(ms: number): Plugin;
288
+ declare function timeout(options: TimeoutOptions): Plugin;
289
+ /** @deprecated Use `timeout({ total: ms, idle })`; this form goes in the next major. */
290
+ declare function timeout(ms: number, options: Pick<TimeoutOptions, "idle">): Plugin;
291
+ //#endregion
292
+ export { HeadersOption as _, LogEvent as a, RetryOptions as b, BearerAuthOptions as c, Plugin as d, RequestInterceptor as f, ArthronMeta as g, isArthronError as h, logging as i, ErrorInterceptor as l, ArthronError as m, TimeoutOptions as n, LoggingOptions as o, ResponseInterceptor as p, retry as r, bearerAuth as s, timeout as t, Middleware as u, QueryParams as v, RequestContext as y };
293
+ //# sourceMappingURL=index-Bz1P80JN.d.mts.map