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.
- package/README.md +101 -51
- package/dist/index-Bz1P80JN.d.cts +293 -0
- package/dist/index-Bz1P80JN.d.mts +293 -0
- package/dist/index.cjs +78 -653
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +16 -238
- package/dist/index.d.mts +16 -238
- package/dist/index.mjs +70 -645
- package/dist/index.mjs.map +1 -1
- package/dist/plugins-CVrzb8x6.cjs +864 -0
- package/dist/plugins-CVrzb8x6.cjs.map +1 -0
- package/dist/plugins-ChNZ2Q8t.mjs +757 -0
- package/dist/plugins-ChNZ2Q8t.mjs.map +1 -0
- package/dist/plugins.cjs +6 -0
- package/dist/plugins.d.cts +2 -0
- package/dist/plugins.d.mts +2 -0
- package/dist/plugins.mjs +1 -0
- package/llms.txt +13 -14
- package/package.json +14 -1
- package/plugins/package.json +6 -0
package/dist/index.mjs
CHANGED
|
@@ -1,163 +1,4 @@
|
|
|
1
|
-
|
|
2
|
-
const ABSOLUTE_URL = /^[a-z][a-z0-9+.-]*:\/\//i;
|
|
3
|
-
const HTTP_URL = /^https?:\/\//i;
|
|
4
|
-
function isAbsoluteUrl(path) {
|
|
5
|
-
return ABSOLUTE_URL.test(path);
|
|
6
|
-
}
|
|
7
|
-
/**
|
|
8
|
-
* Origin + pathname only — the query and userinfo tend to carry secrets.
|
|
9
|
-
* For anything printed: log lines, error messages, `ArthronError.toJSON`.
|
|
10
|
-
*/
|
|
11
|
-
function redactUrl(url) {
|
|
12
|
-
try {
|
|
13
|
-
const parsed = new URL(url);
|
|
14
|
-
return `${parsed.origin}${parsed.pathname}`;
|
|
15
|
-
} catch {
|
|
16
|
-
return url.split(/[?#]/)[0] ?? url;
|
|
17
|
-
}
|
|
18
|
-
}
|
|
19
|
-
/**
|
|
20
|
-
* `undefined` when `url` has no origin of its own. A relative baseURL takes
|
|
21
|
-
* the page's origin in a browser and has none elsewhere.
|
|
22
|
-
*/
|
|
23
|
-
function originOf(url) {
|
|
24
|
-
const page = globalThis.location?.href;
|
|
25
|
-
try {
|
|
26
|
-
return new URL(url, page).origin;
|
|
27
|
-
} catch {
|
|
28
|
-
return;
|
|
29
|
-
}
|
|
30
|
-
}
|
|
31
|
-
/** `path` is absolute and points away from `baseURL`'s origin. */
|
|
32
|
-
function leavesBase(baseURL, path) {
|
|
33
|
-
if (baseURL === void 0 || !isAbsoluteUrl(path)) return false;
|
|
34
|
-
const base = originOf(baseURL);
|
|
35
|
-
return base === void 0 || originOf(path) !== base;
|
|
36
|
-
}
|
|
37
|
-
function toQueryString(params) {
|
|
38
|
-
if (!params) return "";
|
|
39
|
-
if (Object.prototype.toString.call(params) === "[object URLSearchParams]") return params.toString();
|
|
40
|
-
const search = new URLSearchParams();
|
|
41
|
-
for (const [key, value] of Object.entries(params)) for (const item of Array.isArray(value) ? value : [value]) {
|
|
42
|
-
if (item === null || item === void 0) continue;
|
|
43
|
-
if (typeof item === "object" || typeof item === "function") throw new TypeError(`arthron: params.${key} is not a string, number or boolean — pass one of those or an array of them (dates: date.toISOString())`);
|
|
44
|
-
search.append(key, String(item));
|
|
45
|
-
}
|
|
46
|
-
return search.toString();
|
|
47
|
-
}
|
|
48
|
-
/**
|
|
49
|
-
* Fill `{name}` placeholders with encoded values, so each one stays inside
|
|
50
|
-
* its segment: "/", "?" and "#" are encoded, and the values WHATWG URL would
|
|
51
|
-
* turn into a different path — "", "." and ".." — are refused. A placeholder
|
|
52
|
-
* without a value, or a value without a placeholder, is a mistake too.
|
|
53
|
-
*/
|
|
54
|
-
function fillPath(template, values) {
|
|
55
|
-
const used = /* @__PURE__ */ new Set();
|
|
56
|
-
const filled = template.replace(/\{([^{}/]+)\}/g, (_, name) => {
|
|
57
|
-
if (!Object.hasOwn(values, name)) throw new TypeError(`arthron: path "${template}" has {${name}} but no value for it — pass path: { ${name}: … }`);
|
|
58
|
-
used.add(name);
|
|
59
|
-
const value = String(values[name]);
|
|
60
|
-
if (value === "" || value === "." || value === "..") throw new TypeError(`arthron: path value ${name}=${JSON.stringify(value)} would change the path, not fill a segment — pass a real id`);
|
|
61
|
-
return encodeURIComponent(value);
|
|
62
|
-
});
|
|
63
|
-
const unused = Object.keys(values).find((name) => !used.has(name));
|
|
64
|
-
if (unused !== void 0) throw new TypeError(`arthron: path "${template}" has no {${unused}} — add the placeholder or drop the value`);
|
|
65
|
-
return filled;
|
|
66
|
-
}
|
|
67
|
-
/**
|
|
68
|
-
* Join `baseURL` and `path` by plain string concatenation so a path prefix in
|
|
69
|
-
* the base (`/v1`) survives a leading slash in the path. WHATWG `new URL()`
|
|
70
|
-
* would drop it. An absolute path replaces the base only when it stays on the
|
|
71
|
-
* base's origin, or when `allowAbsoluteUrls` says other origins are fine — a
|
|
72
|
-
* path built from user input or an API response must not carry the client's
|
|
73
|
-
* credentials somewhere else.
|
|
74
|
-
*/
|
|
75
|
-
function resolveUrl(baseURL, path, params, allowAbsoluteUrls = false) {
|
|
76
|
-
let url;
|
|
77
|
-
if (isAbsoluteUrl(path)) {
|
|
78
|
-
if (!HTTP_URL.test(path)) {
|
|
79
|
-
const scheme = path.slice(0, path.indexOf(":") + 1);
|
|
80
|
-
throw new TypeError(`arthron: only http(s) URLs can be requested, got a "${scheme}" URL — use an http:// or https:// URL`);
|
|
81
|
-
}
|
|
82
|
-
if (!allowAbsoluteUrls && leavesBase(baseURL, path)) throw new TypeError(`arthron: ${originOf(path)} is outside baseURL ${(baseURL && originOf(baseURL)) ?? baseURL} — pass a path relative to baseURL, or set arthron({ allowAbsoluteUrls: true }) to allow other origins (config headers are not sent to them)`);
|
|
83
|
-
url = path;
|
|
84
|
-
} else {
|
|
85
|
-
if (baseURL === void 0) throw new TypeError(`arthron: relative path "${redactUrl(path)}" needs a baseURL — pass baseURL in arthron({ baseURL }) or use an absolute URL`);
|
|
86
|
-
url = `${baseURL.replace(/\/+$/, "")}/${path.replace(/^\/+/, "")}`;
|
|
87
|
-
}
|
|
88
|
-
const query = toQueryString(params);
|
|
89
|
-
if (!query) return url;
|
|
90
|
-
const hash = url.indexOf("#");
|
|
91
|
-
const [base, fragment] = hash === -1 ? [url, ""] : [url.slice(0, hash), url.slice(hash)];
|
|
92
|
-
return `${base}${base.includes("?") ? "&" : "?"}${query}${fragment}`;
|
|
93
|
-
}
|
|
94
|
-
//#endregion
|
|
95
|
-
//#region src/error/arthron-error.ts
|
|
96
|
-
/**
|
|
97
|
-
* Marks an ArthronError across copies of this package. The ESM and CJS
|
|
98
|
-
* builds can both end up loaded (a CJS dependency creates the client, ESM
|
|
99
|
-
* app code catches), each with its own class — `Symbol.for` is shared.
|
|
100
|
-
*/
|
|
101
|
-
const BRAND = Symbol.for("arthron.ArthronError");
|
|
102
|
-
/**
|
|
103
|
-
* The only error arthron itself produces. Two sources: a response with
|
|
104
|
-
* `ok === false`, or fetch rejecting outright (network failure, `status` 0).
|
|
105
|
-
* Everything else — cancellation, interceptor bugs — is rethrown untouched.
|
|
106
|
-
*/
|
|
107
|
-
var ArthronError = class ArthronError extends Error {
|
|
108
|
-
name = "ArthronError";
|
|
109
|
-
/** HTTP status of the failed response; `0` when fetch itself failed (network). */
|
|
110
|
-
status;
|
|
111
|
-
statusText;
|
|
112
|
-
/** Parsed body: JSON if it parses, else the text, else `undefined`. */
|
|
113
|
-
data;
|
|
114
|
-
/**
|
|
115
|
-
* The server's own explanation, picked out of `data` (by default
|
|
116
|
-
* `message` → `error` → `error.message` → `detail`; see the `errorDetail`
|
|
117
|
-
* config). `undefined` when the body had none. Untrusted server text: show
|
|
118
|
-
* it to users as text, never as HTML. `message`, by contrast, is written by
|
|
119
|
-
* arthron — method, URL without query, status — and is meant for logs.
|
|
120
|
-
*/
|
|
121
|
-
detail;
|
|
122
|
-
/** The underlying error for network failures. */
|
|
123
|
-
cause;
|
|
124
|
-
constructor(init) {
|
|
125
|
-
super(init.message);
|
|
126
|
-
this.status = init.status;
|
|
127
|
-
this.statusText = init.statusText;
|
|
128
|
-
this.data = init.data;
|
|
129
|
-
this.detail = init.detail;
|
|
130
|
-
this.cause = init.cause;
|
|
131
|
-
Object.defineProperties(this, {
|
|
132
|
-
headers: { value: init.headers },
|
|
133
|
-
request: { value: init.request },
|
|
134
|
-
response: { value: init.response },
|
|
135
|
-
[BRAND]: { value: true }
|
|
136
|
-
});
|
|
137
|
-
}
|
|
138
|
-
/** `instanceof ArthronError` holds for an error from any copy of the package. */
|
|
139
|
-
static [Symbol.hasInstance](value) {
|
|
140
|
-
return this === ArthronError ? isArthronError(value) : Function.prototype[Symbol.hasInstance].call(this, value);
|
|
141
|
-
}
|
|
142
|
-
/** What serializers see: no headers, no body, no query or userinfo. */
|
|
143
|
-
toJSON() {
|
|
144
|
-
return {
|
|
145
|
-
name: this.name,
|
|
146
|
-
message: this.message,
|
|
147
|
-
detail: this.detail,
|
|
148
|
-
status: this.status,
|
|
149
|
-
statusText: this.statusText,
|
|
150
|
-
method: this.request.init.method ?? "GET",
|
|
151
|
-
url: redactUrl(this.request.url),
|
|
152
|
-
data: this.data
|
|
153
|
-
};
|
|
154
|
-
}
|
|
155
|
-
};
|
|
156
|
-
/** `true` for errors arthron produced: a `!ok` response or a network failure. Cancellations and plugin bugs are not ArthronErrors. */
|
|
157
|
-
function isArthronError(error) {
|
|
158
|
-
return typeof error === "object" && error !== null && error[BRAND] === true;
|
|
159
|
-
}
|
|
160
|
-
//#endregion
|
|
1
|
+
import { _ as redactUrlIn, a as isCancellation, d as serializeBody, f as ArthronError, g as redactUrl, h as leavesBase, i as cancellationError, l as isReadableStream, m as fillPath, n as retry$1, o as networkError, p as isArthronError, r as logging$1, s as responseError, t as timeout$1, u as runtimeStreamsRequestBody, v as resolveUrl } from "./plugins-ChNZ2Q8t.mjs";
|
|
161
2
|
//#region src/request/headers.ts
|
|
162
3
|
const isPlainRecord = (headers) => !Array.isArray(headers) && Object.prototype.toString.call(headers) !== "[object Headers]";
|
|
163
4
|
/**
|
|
@@ -225,6 +66,15 @@ function normalize(ctx, previous) {
|
|
|
225
66
|
};
|
|
226
67
|
}
|
|
227
68
|
/**
|
|
69
|
+
* A plugin written in JS (or with a cast) that forgets to return would hand
|
|
70
|
+
* `undefined` on — and an error interceptor's would be what the caller
|
|
71
|
+
* catches. Name the plugin slot instead.
|
|
72
|
+
*/
|
|
73
|
+
function returned(value, who, what, cause, verb = "returned") {
|
|
74
|
+
if (value != null) return value;
|
|
75
|
+
throw new TypeError(`arthron: ${who} ${verb} ${value} — return ${what}`, cause === void 0 ? void 0 : { cause });
|
|
76
|
+
}
|
|
77
|
+
/**
|
|
228
78
|
* Owns the order of one request.
|
|
229
79
|
*
|
|
230
80
|
* Middleware wraps the whole call, outermost first in registration order.
|
|
@@ -246,98 +96,30 @@ async function runPipeline(plugins, ctx, send) {
|
|
|
246
96
|
}
|
|
247
97
|
const attempt = async (input) => {
|
|
248
98
|
let current = cloneContext(input);
|
|
99
|
+
for (const interceptor of request) current = normalize(returned(await interceptor(current), "a request interceptor", "the context (ctx or a changed copy)"), current);
|
|
100
|
+
let res;
|
|
249
101
|
try {
|
|
250
|
-
|
|
251
|
-
let res = await send(current);
|
|
252
|
-
for (const interceptor of response) res = await interceptor(res, current);
|
|
253
|
-
return res;
|
|
102
|
+
res = await send(current);
|
|
254
103
|
} catch (thrown) {
|
|
255
104
|
if (!isArthronError(thrown)) throw thrown;
|
|
256
105
|
let err = thrown;
|
|
257
|
-
for (const interceptor of error) err = await interceptor(err, current);
|
|
106
|
+
for (const interceptor of error) err = returned(await interceptor(err, current), "an error interceptor", "the error (err or a changed one)", thrown);
|
|
258
107
|
throw err;
|
|
259
108
|
}
|
|
109
|
+
for (const interceptor of response) res = returned(await interceptor(res, current), "a response interceptor", "the Response (res or a new one)");
|
|
110
|
+
return res;
|
|
260
111
|
};
|
|
261
|
-
const dispatch = (index, input) => {
|
|
112
|
+
const dispatch = async (index, input) => {
|
|
262
113
|
const middleware = middlewares[index];
|
|
263
114
|
if (!middleware) return attempt(input);
|
|
264
|
-
return middleware(input, (next) => dispatch(index + 1, {
|
|
115
|
+
return returned(await middleware(input, (next) => dispatch(index + 1, {
|
|
265
116
|
...next,
|
|
266
117
|
meta: next.meta ?? input.meta
|
|
267
|
-
}));
|
|
118
|
+
})), "a middleware", "the Response, usually `return next(ctx)`", void 0, "resolved with");
|
|
268
119
|
};
|
|
269
120
|
return dispatch(0, ctx);
|
|
270
121
|
}
|
|
271
122
|
//#endregion
|
|
272
|
-
//#region src/request/body.ts
|
|
273
|
-
const RAW_TAGS = /* @__PURE__ */ new Set([
|
|
274
|
-
"FormData",
|
|
275
|
-
"Blob",
|
|
276
|
-
"File",
|
|
277
|
-
"ArrayBuffer",
|
|
278
|
-
"URLSearchParams",
|
|
279
|
-
"ReadableStream"
|
|
280
|
-
]);
|
|
281
|
-
/**
|
|
282
|
-
* `Symbol.toStringTag`, not `instanceof`: a body from another realm or a
|
|
283
|
-
* polyfill (formdata-node, fetch-blob) must not be JSON-encoded into `{}`.
|
|
284
|
-
*/
|
|
285
|
-
const tagOf = (value) => Object.prototype.toString.call(value).slice(8, -1);
|
|
286
|
-
function isReadableStream(value) {
|
|
287
|
-
return tagOf(value) === "ReadableStream";
|
|
288
|
-
}
|
|
289
|
-
/**
|
|
290
|
-
* What JSON.stringify would turn into `{}`, `undefined` or internal state
|
|
291
|
-
* instead of the data — with the fix, so it reads as an error message.
|
|
292
|
-
*/
|
|
293
|
-
function mangledByJson(body) {
|
|
294
|
-
if (typeof body === "function" || typeof body === "symbol") return `a ${typeof body}, which JSON cannot carry — send its data instead`;
|
|
295
|
-
if (typeof body !== "object" || body === null || Array.isArray(body)) return;
|
|
296
|
-
if (Symbol.asyncIterator in body) return "an async iterable (a Node stream?) — pass a ReadableStream (Readable.toWeb(stream)) or collect it first";
|
|
297
|
-
if (Symbol.iterator in body) return "an iterable such as a Map, Set or generator — convert it to an array or plain object first";
|
|
298
|
-
}
|
|
299
|
-
/** Bodies fetch already knows how to send. Content-Type is left to the caller / runtime. */
|
|
300
|
-
function isRawBody(body) {
|
|
301
|
-
if (typeof body === "string") return true;
|
|
302
|
-
if (ArrayBuffer.isView(body)) return true;
|
|
303
|
-
return RAW_TAGS.has(tagOf(body));
|
|
304
|
-
}
|
|
305
|
-
/**
|
|
306
|
-
* Turn a caller-supplied body into something fetch accepts. Raw bodies pass
|
|
307
|
-
* through untouched; anything else is JSON with `content-type` set — unless
|
|
308
|
-
* the caller already set one (headers arrive lowercased, so a plain lookup is
|
|
309
|
-
* enough).
|
|
310
|
-
*/
|
|
311
|
-
function serializeBody(body, headers) {
|
|
312
|
-
if (body === void 0) return {
|
|
313
|
-
body: void 0,
|
|
314
|
-
headers
|
|
315
|
-
};
|
|
316
|
-
if (tagOf(body) === "FormData") {
|
|
317
|
-
const { "content-type": _dropped, ...rest } = headers;
|
|
318
|
-
return {
|
|
319
|
-
body,
|
|
320
|
-
headers: rest
|
|
321
|
-
};
|
|
322
|
-
}
|
|
323
|
-
if (isRawBody(body)) return {
|
|
324
|
-
body,
|
|
325
|
-
headers
|
|
326
|
-
};
|
|
327
|
-
const mangled = mangledByJson(body);
|
|
328
|
-
if (mangled) throw new TypeError(`arthron: the body is ${mangled}`);
|
|
329
|
-
const type = headers["content-type"];
|
|
330
|
-
if (type !== void 0 && !/\bjson\b/i.test(type)) throw new TypeError(`arthron: a ${typeof body} body is sent as JSON, but content-type is "${type}" — pass a string, URLSearchParams or FormData for that content type, or drop the header`);
|
|
331
|
-
const withType = "content-type" in headers ? headers : {
|
|
332
|
-
...headers,
|
|
333
|
-
"content-type": "application/json"
|
|
334
|
-
};
|
|
335
|
-
return {
|
|
336
|
-
body: JSON.stringify(body),
|
|
337
|
-
headers: withType
|
|
338
|
-
};
|
|
339
|
-
}
|
|
340
|
-
//#endregion
|
|
341
123
|
//#region src/response/schema-validation.ts
|
|
342
124
|
const pathOf = (issue) => (issue.path ?? []).map((part) => String(typeof part === "object" && part !== null ? part.key : part)).join(".");
|
|
343
125
|
/**
|
|
@@ -372,6 +154,10 @@ const DEFAULT_LIMIT = 8388608;
|
|
|
372
154
|
*/
|
|
373
155
|
async function* lines(response, maxLineLength) {
|
|
374
156
|
if (!response.body) return;
|
|
157
|
+
const checked = (line) => {
|
|
158
|
+
if (line.length <= maxLineLength) return line;
|
|
159
|
+
throw new RangeError(`arthron: a stream line is longer than ${maxLineLength} characters — pass a larger maxLineLength to .sse() / .ndjson() if that is expected`);
|
|
160
|
+
};
|
|
375
161
|
const reader = response.body.getReader();
|
|
376
162
|
const decoder = new TextDecoder();
|
|
377
163
|
const breaks = /\r\n|\r|\n/g;
|
|
@@ -389,12 +175,11 @@ async function* lines(response, maxLineLength) {
|
|
|
389
175
|
let start = 0;
|
|
390
176
|
breaks.lastIndex = 0;
|
|
391
177
|
for (let m = breaks.exec(text); m; m = breaks.exec(text)) {
|
|
392
|
-
yield pending + text.slice(start, m.index);
|
|
178
|
+
yield checked(pending + text.slice(start, m.index));
|
|
393
179
|
pending = "";
|
|
394
180
|
start = breaks.lastIndex;
|
|
395
181
|
}
|
|
396
|
-
pending
|
|
397
|
-
if (pending.length > maxLineLength) throw new RangeError(`arthron: a stream line is longer than ${maxLineLength} characters — pass a larger maxLineLength to .sse() / .ndjson() if that is expected`);
|
|
182
|
+
pending = checked(pending + text.slice(start));
|
|
398
183
|
if (done) break;
|
|
399
184
|
}
|
|
400
185
|
if (pending) yield pending;
|
|
@@ -471,28 +256,35 @@ async function* parseNdjson(response, { maxLineLength = DEFAULT_LIMIT } = {}) {
|
|
|
471
256
|
//#endregion
|
|
472
257
|
//#region src/response/arthron-promise.ts
|
|
473
258
|
/** Defer the Response until iteration starts, so the helper itself never rejects. */
|
|
474
|
-
function iterate(promise, parse) {
|
|
259
|
+
function iterate(promise, parse, signal) {
|
|
475
260
|
promise.catch(() => {});
|
|
476
261
|
return { async *[Symbol.asyncIterator]() {
|
|
477
|
-
|
|
262
|
+
try {
|
|
263
|
+
yield* parse(await promise);
|
|
264
|
+
} catch (error) {
|
|
265
|
+
throw cancellationError(error, signal);
|
|
266
|
+
}
|
|
478
267
|
} };
|
|
479
268
|
}
|
|
480
269
|
/**
|
|
481
270
|
* Sugar over `Promise<Response>`: `.json()` is `(await p).json()`. Awaiting
|
|
482
271
|
* without a helper still yields the untouched `Response`.
|
|
483
272
|
*/
|
|
484
|
-
function toArthronPromise(promise) {
|
|
273
|
+
function toArthronPromise(promise, signal) {
|
|
274
|
+
const read = (body) => promise.then(body).catch((error) => {
|
|
275
|
+
throw cancellationError(error, signal);
|
|
276
|
+
});
|
|
485
277
|
return Object.assign(promise, {
|
|
486
|
-
json: ((schema) =>
|
|
278
|
+
json: ((schema) => read(async (res) => {
|
|
487
279
|
const data = await res.json();
|
|
488
280
|
return schema ? validate(schema, data) : data;
|
|
489
281
|
})),
|
|
490
|
-
text: () =>
|
|
491
|
-
blob: () =>
|
|
492
|
-
arrayBuffer: () =>
|
|
493
|
-
formData: () =>
|
|
494
|
-
sse: (options) => iterate(promise, (res) => parseSse(res, options)),
|
|
495
|
-
ndjson: (options) => iterate(promise, (res) => parseNdjson(res, options))
|
|
282
|
+
text: () => read((res) => res.text()),
|
|
283
|
+
blob: () => read((res) => res.blob()),
|
|
284
|
+
arrayBuffer: () => read((res) => res.arrayBuffer()),
|
|
285
|
+
formData: () => read((res) => res.formData()),
|
|
286
|
+
sse: (options) => iterate(promise, (res) => parseSse(res, options), signal),
|
|
287
|
+
ndjson: (options) => iterate(promise, (res) => parseNdjson(res, options), signal)
|
|
496
288
|
});
|
|
497
289
|
}
|
|
498
290
|
//#endregion
|
|
@@ -547,130 +339,6 @@ function resolveConfig(config) {
|
|
|
547
339
|
};
|
|
548
340
|
}
|
|
549
341
|
//#endregion
|
|
550
|
-
//#region src/response/rebuild-response.ts
|
|
551
|
-
/**
|
|
552
|
-
* A new Response with `body` but everything else taken from `original`. The
|
|
553
|
-
* constructor resets `url`, `redirected` and `type`, so those are copied over
|
|
554
|
-
* as own properties — callers that resolve relative links or detect
|
|
555
|
-
* redirects keep working.
|
|
556
|
-
*/
|
|
557
|
-
function rebuildResponse(original, body) {
|
|
558
|
-
return withFetchedFields(new Response(body, {
|
|
559
|
-
status: original.status,
|
|
560
|
-
statusText: original.statusText,
|
|
561
|
-
headers: original.headers
|
|
562
|
-
}), original);
|
|
563
|
-
}
|
|
564
|
-
/** Copy the fields the constructor resets — onto `clone()`s as well. */
|
|
565
|
-
function withFetchedFields(target, from) {
|
|
566
|
-
const clone = target.clone.bind(target);
|
|
567
|
-
return Object.defineProperties(target, {
|
|
568
|
-
url: { value: from.url },
|
|
569
|
-
redirected: { value: from.redirected },
|
|
570
|
-
type: { value: from.type },
|
|
571
|
-
clone: { value: () => withFetchedFields(clone(), from) }
|
|
572
|
-
});
|
|
573
|
-
}
|
|
574
|
-
//#endregion
|
|
575
|
-
//#region src/error/create-error.ts
|
|
576
|
-
/**
|
|
577
|
-
* Cancellation is not an HTTP failure. Matched by name so it works across
|
|
578
|
-
* realms — or by the request's own `signal`, since `abort(reason)` rejects
|
|
579
|
-
* with whatever reason the caller chose.
|
|
580
|
-
*/
|
|
581
|
-
function isCancellation(error, signal) {
|
|
582
|
-
if (signal?.aborted) return true;
|
|
583
|
-
const name = error?.name;
|
|
584
|
-
return name === "AbortError" || name === "TimeoutError";
|
|
585
|
-
}
|
|
586
|
-
const isRecord = (value) => typeof value === "object" && value !== null;
|
|
587
|
-
/** `message` → `error` (string) → `error.message` → `detail`. */
|
|
588
|
-
function defaultErrorDetail(data) {
|
|
589
|
-
if (!isRecord(data)) return void 0;
|
|
590
|
-
if (typeof data.message === "string") return data.message;
|
|
591
|
-
if (typeof data.error === "string") return data.error;
|
|
592
|
-
if (isRecord(data.error) && typeof data.error.message === "string") return data.error.message;
|
|
593
|
-
if (typeof data.detail === "string") return data.detail;
|
|
594
|
-
}
|
|
595
|
-
/** How much of an error body arthron reads. Error bodies are for diagnosis; a hostile or broken server must not be able to fill memory with one. */
|
|
596
|
-
const MAX_ERROR_BODY_BYTES = 65536;
|
|
597
|
-
/** Up to `limit` bytes of the body; the rest is cancelled unread. `undefined` when there is no body or reading it failed. */
|
|
598
|
-
async function readCapped(response, limit) {
|
|
599
|
-
if (!response.body) return void 0;
|
|
600
|
-
let reader;
|
|
601
|
-
const chunks = [];
|
|
602
|
-
let size = 0;
|
|
603
|
-
try {
|
|
604
|
-
reader = response.body.getReader();
|
|
605
|
-
while (size <= limit) {
|
|
606
|
-
const { value, done } = await reader.read();
|
|
607
|
-
if (done) break;
|
|
608
|
-
chunks.push(value);
|
|
609
|
-
size += value.byteLength;
|
|
610
|
-
}
|
|
611
|
-
} catch {
|
|
612
|
-
return;
|
|
613
|
-
} finally {
|
|
614
|
-
await reader?.cancel().catch(() => {});
|
|
615
|
-
reader?.releaseLock();
|
|
616
|
-
}
|
|
617
|
-
const bytes = new Uint8Array(size);
|
|
618
|
-
let offset = 0;
|
|
619
|
-
for (const chunk of chunks) {
|
|
620
|
-
bytes.set(chunk, offset);
|
|
621
|
-
offset += chunk.byteLength;
|
|
622
|
-
}
|
|
623
|
-
return size > limit ? {
|
|
624
|
-
bytes: bytes.subarray(0, limit),
|
|
625
|
-
truncated: true
|
|
626
|
-
} : {
|
|
627
|
-
bytes,
|
|
628
|
-
truncated: false
|
|
629
|
-
};
|
|
630
|
-
}
|
|
631
|
-
/** JSON if the whole body parses, else the text (cut at the limit), else `undefined` when empty. */
|
|
632
|
-
function parseBody(read) {
|
|
633
|
-
const text = new TextDecoder().decode(read.bytes);
|
|
634
|
-
if (text === "") return void 0;
|
|
635
|
-
if (read.truncated) return text;
|
|
636
|
-
try {
|
|
637
|
-
return JSON.parse(text);
|
|
638
|
-
} catch {
|
|
639
|
-
return text;
|
|
640
|
-
}
|
|
641
|
-
}
|
|
642
|
-
/** The request as error messages name it: method and URL, no query or userinfo. */
|
|
643
|
-
function describeRequest(request) {
|
|
644
|
-
return `${request.init.method ?? "GET"} ${redactUrl(request.url)}`;
|
|
645
|
-
}
|
|
646
|
-
async function responseError(response, request, resolve = defaultErrorDetail) {
|
|
647
|
-
const read = await readCapped(response, MAX_ERROR_BODY_BYTES);
|
|
648
|
-
const data = read && parseBody(read);
|
|
649
|
-
if (read) response = rebuildResponse(response, read.bytes);
|
|
650
|
-
const status = response.statusText ? `${response.status} ${response.statusText}` : String(response.status);
|
|
651
|
-
return new ArthronError({
|
|
652
|
-
message: `${describeRequest(request)} failed with ${status}`,
|
|
653
|
-
detail: resolve(data, response) || void 0,
|
|
654
|
-
status: response.status,
|
|
655
|
-
statusText: response.statusText,
|
|
656
|
-
headers: response.headers,
|
|
657
|
-
data,
|
|
658
|
-
request,
|
|
659
|
-
response
|
|
660
|
-
});
|
|
661
|
-
}
|
|
662
|
-
function networkError(cause, request) {
|
|
663
|
-
return new ArthronError({
|
|
664
|
-
message: `${describeRequest(request)} failed: ${cause instanceof Error && cause.message ? cause.message : "network error"}`,
|
|
665
|
-
status: 0,
|
|
666
|
-
statusText: "",
|
|
667
|
-
headers: new Headers(),
|
|
668
|
-
data: void 0,
|
|
669
|
-
request,
|
|
670
|
-
cause
|
|
671
|
-
});
|
|
672
|
-
}
|
|
673
|
-
//#endregion
|
|
674
342
|
//#region src/client/send.ts
|
|
675
343
|
/**
|
|
676
344
|
* The global fetch rejects a malformed URL or method with a TypeError that
|
|
@@ -684,12 +352,21 @@ function assertSendable(url, method) {
|
|
|
684
352
|
try {
|
|
685
353
|
new Request(url, { method });
|
|
686
354
|
} catch (cause) {
|
|
687
|
-
const
|
|
688
|
-
|
|
689
|
-
throw new TypeError(`arthron: cannot send ${method} ${shown} (${reason}) — use an absolute URL or a baseURL with a scheme (https://…), and a valid HTTP method`, { cause });
|
|
355
|
+
const reason = redactUrlIn(cause instanceof Error ? cause.message : String(cause), url);
|
|
356
|
+
throw new TypeError(`arthron: cannot send ${method} ${redactUrl(url)} (${reason}) — use an absolute URL or a baseURL with a scheme (https://…), and a valid HTTP method`, { cause });
|
|
690
357
|
}
|
|
691
358
|
}
|
|
692
359
|
/**
|
|
360
|
+
* A ReadableStream body the browser cannot stream is rejected before it is
|
|
361
|
+
* sent: Firefox would send the text "[object ReadableStream]", older Safari
|
|
362
|
+
* fails with a bare network error. Only for the global fetch, like
|
|
363
|
+
* assertSendable.
|
|
364
|
+
*/
|
|
365
|
+
function assertStreamable(url, method, body) {
|
|
366
|
+
if (!isReadableStream(body) || runtimeStreamsRequestBody()) return;
|
|
367
|
+
throw new TypeError(`arthron: cannot send ${method} ${redactUrl(url)} with a ReadableStream body — this browser cannot stream a request body and would send it garbled or not at all; pass a Blob or ArrayBuffer instead`);
|
|
368
|
+
}
|
|
369
|
+
/**
|
|
693
370
|
* Non-ok responses the caller asked for are not failures: an opaque one
|
|
694
371
|
* (`mode: "no-cors"`) and the 3xx of `redirect: "manual"`.
|
|
695
372
|
*/
|
|
@@ -700,13 +377,17 @@ function failedByDefault(res, init) {
|
|
|
700
377
|
/** The one place a failure becomes an ArthronError. Cancellation passes through. */
|
|
701
378
|
async function send(resolved, ctx, throwOn) {
|
|
702
379
|
const fetchImpl = resolved.fetch ?? globalThis.fetch;
|
|
703
|
-
if (resolved.fetch === void 0)
|
|
380
|
+
if (resolved.fetch === void 0) {
|
|
381
|
+
const method = ctx.init.method ?? "GET";
|
|
382
|
+
assertSendable(ctx.url, method);
|
|
383
|
+
assertStreamable(ctx.url, method, ctx.init.body);
|
|
384
|
+
}
|
|
704
385
|
const { signal } = ctx.init;
|
|
705
386
|
let res;
|
|
706
387
|
try {
|
|
707
388
|
res = await fetchImpl(ctx.url, ctx.init);
|
|
708
389
|
} catch (thrown) {
|
|
709
|
-
if (isCancellation(thrown, signal)) throw thrown;
|
|
390
|
+
if (isCancellation(thrown, signal)) throw cancellationError(thrown, signal);
|
|
710
391
|
throw networkError(thrown, ctx);
|
|
711
392
|
}
|
|
712
393
|
if (res.ok) return res;
|
|
@@ -743,7 +424,8 @@ function arthron(config = {}) {
|
|
|
743
424
|
if (rawBody !== void 0 && BODYLESS_METHODS.has(upper)) throw new TypeError(`arthron: ${upper} requests cannot carry a body — send it as params (query) or switch to POST`);
|
|
744
425
|
if (pathValues) path = fillPath(path, pathValues);
|
|
745
426
|
const url = resolveUrl(resolved.baseURL, path, params, resolved.allowAbsoluteUrls);
|
|
746
|
-
const
|
|
427
|
+
const defaults = leavesBase(resolved.baseURL, path) ? void 0 : resolved.headers;
|
|
428
|
+
const { body, headers } = serializeBody(rawBody, mergeHeaders(defaults, callHeaders));
|
|
747
429
|
const requestInit = {
|
|
748
430
|
...initDefaults,
|
|
749
431
|
...init,
|
|
@@ -756,7 +438,7 @@ function arthron(config = {}) {
|
|
|
756
438
|
url,
|
|
757
439
|
init: requestInit,
|
|
758
440
|
meta: { ...meta }
|
|
759
|
-
}, (ctx) => send(resolved, ctx, throwOn)));
|
|
441
|
+
}, (ctx) => send(resolved, ctx, throwOn)), init.signal);
|
|
760
442
|
} catch (thrown) {
|
|
761
443
|
return toArthronPromise(Promise.reject(thrown));
|
|
762
444
|
}
|
|
@@ -803,270 +485,13 @@ const defineInterceptor = {
|
|
|
803
485
|
/** Identity helper: type-checks a plugin object literal without an annotation. */
|
|
804
486
|
const definePlugin = (plugin) => plugin;
|
|
805
487
|
//#endregion
|
|
806
|
-
//#region src/
|
|
807
|
-
|
|
808
|
-
|
|
809
|
-
|
|
810
|
-
|
|
811
|
-
|
|
812
|
-
|
|
813
|
-
}
|
|
814
|
-
/**
|
|
815
|
-
* One event when a request starts, one when it settles, with status and
|
|
816
|
-
* elapsed time. Wraps the whole call, so retries are included in the time.
|
|
817
|
-
* Default output is a console line per event; pass `onEvent` to get the
|
|
818
|
-
* structured event instead. Cancellations are not reported.
|
|
819
|
-
*/
|
|
820
|
-
function logging(options = {}) {
|
|
821
|
-
const { enabled = true, logger = console, onEvent, now = () => performance.now() } = options;
|
|
822
|
-
const emit = onEvent ?? consoleSink(logger);
|
|
823
|
-
return {
|
|
824
|
-
name: "logging",
|
|
825
|
-
middleware: async (ctx, next) => {
|
|
826
|
-
if (!enabled) return next(ctx);
|
|
827
|
-
const method = ctx.init.method ?? "GET";
|
|
828
|
-
const path = redactUrl(ctx.url);
|
|
829
|
-
const started = now();
|
|
830
|
-
const ms = () => Math.round(now() - started);
|
|
831
|
-
emit({
|
|
832
|
-
phase: "start",
|
|
833
|
-
method,
|
|
834
|
-
path
|
|
835
|
-
});
|
|
836
|
-
let res;
|
|
837
|
-
try {
|
|
838
|
-
res = await next(ctx);
|
|
839
|
-
} catch (error) {
|
|
840
|
-
if (!isCancellation(error, ctx.init.signal)) {
|
|
841
|
-
const status = isArthronError(error) ? error.status : void 0;
|
|
842
|
-
emit({
|
|
843
|
-
phase: "error",
|
|
844
|
-
method,
|
|
845
|
-
path,
|
|
846
|
-
status,
|
|
847
|
-
ms: ms(),
|
|
848
|
-
error
|
|
849
|
-
});
|
|
850
|
-
}
|
|
851
|
-
throw error;
|
|
852
|
-
}
|
|
853
|
-
emit({
|
|
854
|
-
phase: "success",
|
|
855
|
-
method,
|
|
856
|
-
path,
|
|
857
|
-
status: res.status,
|
|
858
|
-
ms: ms()
|
|
859
|
-
});
|
|
860
|
-
return res;
|
|
861
|
-
}
|
|
862
|
-
};
|
|
863
|
-
}
|
|
864
|
-
//#endregion
|
|
865
|
-
//#region src/plugins/retry/retry.ts
|
|
866
|
-
const DEFAULT_RETRY_ON = [
|
|
867
|
-
408,
|
|
868
|
-
429,
|
|
869
|
-
500,
|
|
870
|
-
502,
|
|
871
|
-
503,
|
|
872
|
-
504
|
|
873
|
-
];
|
|
874
|
-
const DEFAULT_METHODS = [
|
|
875
|
-
"GET",
|
|
876
|
-
"HEAD",
|
|
877
|
-
"OPTIONS",
|
|
878
|
-
"QUERY",
|
|
879
|
-
"PUT",
|
|
880
|
-
"DELETE"
|
|
881
|
-
];
|
|
882
|
-
const DEFAULT_MAX_RETRY_AFTER = 6e4;
|
|
883
|
-
/** setTimeout fires at once past this, so every wait is capped to it. */
|
|
884
|
-
const MAX_TIMER_MS$1 = 2 ** 31 - 1;
|
|
885
|
-
function defaultSleep(ms, signal) {
|
|
886
|
-
return new Promise((resolve, reject) => {
|
|
887
|
-
if (signal?.aborted) return reject(signal.reason);
|
|
888
|
-
const onAbort = () => {
|
|
889
|
-
clearTimeout(timer);
|
|
890
|
-
reject(signal?.reason);
|
|
891
|
-
};
|
|
892
|
-
const timer = setTimeout(() => {
|
|
893
|
-
signal?.removeEventListener("abort", onAbort);
|
|
894
|
-
resolve();
|
|
895
|
-
}, ms);
|
|
896
|
-
signal?.addEventListener("abort", onAbort, { once: true });
|
|
897
|
-
});
|
|
898
|
-
}
|
|
899
|
-
/** `Retry-After` as ms — seconds or an HTTP-date. `undefined` when absent or unparsable. */
|
|
900
|
-
function retryAfterMs(error) {
|
|
901
|
-
const value = error.headers.get("retry-after")?.trim();
|
|
902
|
-
if (!value) return void 0;
|
|
903
|
-
const seconds = Number(value);
|
|
904
|
-
if (!Number.isNaN(seconds)) return Math.max(0, seconds * 1e3);
|
|
905
|
-
const at = Date.parse(value);
|
|
906
|
-
if (Number.isNaN(at)) return void 0;
|
|
907
|
-
return Math.max(0, at - Date.now());
|
|
908
|
-
}
|
|
909
|
-
/** The rule without `shouldRetry`: a network error or a `retryOn` status, on a method in `methods`. */
|
|
910
|
-
function byDefault(thrown, method, settings) {
|
|
911
|
-
if (!settings.allowed.has(method) || !isArthronError(thrown)) return false;
|
|
912
|
-
return thrown.status === 0 || settings.retryOn.includes(thrown.status);
|
|
913
|
-
}
|
|
914
|
-
/** Defaults filled in and `retries` checked — `attempt >= NaN` is never true, so an unset env var would retry forever. */
|
|
915
|
-
function settle(options, where) {
|
|
916
|
-
const { retries = 2, retryOn = DEFAULT_RETRY_ON, methods = DEFAULT_METHODS, delay = (retry) => Math.random() * 300 * 2 ** retry, maxRetryAfter = DEFAULT_MAX_RETRY_AFTER, shouldRetry, onRetry } = options;
|
|
917
|
-
if (!Number.isInteger(retries) || retries < 0) throw new TypeError(`arthron: ${where} retries: ${retries} needs a whole number ≥ 0 — e.g. retries: 2`);
|
|
918
|
-
return {
|
|
919
|
-
retries,
|
|
920
|
-
retryOn,
|
|
921
|
-
allowed: new Set(methods.map((m) => m.toUpperCase())),
|
|
922
|
-
delay,
|
|
923
|
-
maxRetryAfter,
|
|
924
|
-
shouldRetry,
|
|
925
|
-
onRetry
|
|
926
|
-
};
|
|
927
|
-
}
|
|
928
|
-
/**
|
|
929
|
-
* Retry on network errors and the configured statuses by calling `next`
|
|
930
|
-
* again — the whole attempt (request interceptors included) is re-run.
|
|
931
|
-
* Only `ArthronError` is considered; cancellation and plugin bugs pass through.
|
|
932
|
-
* A call can turn it off or override its options with `meta.retry`.
|
|
933
|
-
*/
|
|
934
|
-
function retry(options = {}) {
|
|
935
|
-
const { sleep = defaultSleep, ...rest } = options;
|
|
936
|
-
const base = settle(rest, "retry()");
|
|
937
|
-
return {
|
|
938
|
-
name: "retry",
|
|
939
|
-
middleware: async (ctx, next) => {
|
|
940
|
-
const override = ctx.meta?.retry;
|
|
941
|
-
if (override === false) return next(ctx);
|
|
942
|
-
const settings = override ? settle({
|
|
943
|
-
...rest,
|
|
944
|
-
...override
|
|
945
|
-
}, "meta.retry") : base;
|
|
946
|
-
const method = (ctx.init.method ?? "GET").toUpperCase();
|
|
947
|
-
const resendable = !isReadableStream(ctx.init.body);
|
|
948
|
-
for (let attempt = 0;; attempt += 1) try {
|
|
949
|
-
return await next(ctx);
|
|
950
|
-
} catch (thrown) {
|
|
951
|
-
if (!resendable || attempt >= settings.retries) throw thrown;
|
|
952
|
-
if (ctx.init.signal?.aborted) throw thrown;
|
|
953
|
-
const verdict = settings.shouldRetry?.(thrown, attempt, ctx);
|
|
954
|
-
if (verdict === false) throw thrown;
|
|
955
|
-
if (verdict === void 0 && !byDefault(thrown, method, settings)) throw thrown;
|
|
956
|
-
const retryAfter = isArthronError(thrown) ? retryAfterMs(thrown) : void 0;
|
|
957
|
-
if (retryAfter !== void 0 && retryAfter > settings.maxRetryAfter) throw thrown;
|
|
958
|
-
const wait = Math.min(retryAfter ?? settings.delay(attempt, thrown), MAX_TIMER_MS$1);
|
|
959
|
-
settings.onRetry?.(thrown, attempt, wait);
|
|
960
|
-
await sleep(wait, ctx.init.signal);
|
|
961
|
-
}
|
|
962
|
-
}
|
|
963
|
-
};
|
|
964
|
-
}
|
|
965
|
-
//#endregion
|
|
966
|
-
//#region src/plugins/timeout/timeout.ts
|
|
967
|
-
const MAX_TIMER_MS = 2 ** 31 - 1;
|
|
968
|
-
/**
|
|
969
|
-
* Wrap `body` so the deadline keeps running until it is fully read, and so an
|
|
970
|
-
* abort while reading surfaces as a stream error instead of a silent stall.
|
|
971
|
-
*/
|
|
972
|
-
function guardBody(body, signal, finish, onChunk) {
|
|
973
|
-
const reader = body.getReader();
|
|
974
|
-
return new ReadableStream({
|
|
975
|
-
start(controller) {
|
|
976
|
-
signal.addEventListener("abort", () => {
|
|
977
|
-
controller.error(signal.reason);
|
|
978
|
-
reader.cancel(signal.reason).catch(() => {});
|
|
979
|
-
}, { once: true });
|
|
980
|
-
},
|
|
981
|
-
async pull(controller) {
|
|
982
|
-
const { value, done } = await reader.read();
|
|
983
|
-
if (done) {
|
|
984
|
-
finish();
|
|
985
|
-
controller.close();
|
|
986
|
-
return;
|
|
987
|
-
}
|
|
988
|
-
onChunk();
|
|
989
|
-
controller.enqueue(value);
|
|
990
|
-
},
|
|
991
|
-
cancel(reason) {
|
|
992
|
-
finish();
|
|
993
|
-
return reader.cancel(reason);
|
|
994
|
-
}
|
|
995
|
-
});
|
|
996
|
-
}
|
|
997
|
-
/** setTimeout fires at once for NaN, negatives and anything past 2^31-1. */
|
|
998
|
-
function checkDeadline(ms, where) {
|
|
999
|
-
if (ms === Number.POSITIVE_INFINITY || ms >= 0 && ms <= MAX_TIMER_MS) return;
|
|
1000
|
-
throw new TypeError(`arthron: ${where} needs 0–${MAX_TIMER_MS} ms — pass Infinity for no deadline`);
|
|
1001
|
-
}
|
|
1002
|
-
/** A timer that aborts `controller` with a TimeoutError and never keeps Node alive on its own. */
|
|
1003
|
-
function deadlineTimer(controller, ms, message) {
|
|
1004
|
-
const timer = setTimeout(() => controller.abort(new DOMException(message, "TimeoutError")), ms);
|
|
1005
|
-
timer.unref?.();
|
|
1006
|
-
return timer;
|
|
1007
|
-
}
|
|
1008
|
-
/**
|
|
1009
|
-
* Abort the request when it takes longer than `ms` — counted from the start
|
|
1010
|
-
* of the attempt until the body has been fully read, so a server that sends
|
|
1011
|
-
* headers and then stalls still trips it. With `idle`, also abort once no
|
|
1012
|
-
* data has arrived for that long. Rejects with a `TimeoutError` (a
|
|
1013
|
-
* `DOMException`, like `AbortSignal.timeout()` would give); it is not an
|
|
1014
|
-
* `ArthronError`, so error interceptors and `retry` leave it alone.
|
|
1015
|
-
*
|
|
1016
|
-
* A call can change the total deadline with `meta.timeout`.
|
|
1017
|
-
*
|
|
1018
|
-
* Deadlines are timers on an AbortController — not `AbortSignal.timeout`,
|
|
1019
|
-
* since the idle one restarts — joined to the caller's signal with
|
|
1020
|
-
* `AbortSignal.any`.
|
|
1021
|
-
*/
|
|
1022
|
-
function timeout(ms, options = {}) {
|
|
1023
|
-
checkDeadline(ms, `timeout(${ms})`);
|
|
1024
|
-
const { idle } = options;
|
|
1025
|
-
if (idle !== void 0) checkDeadline(idle, `timeout(…, { idle: ${idle} })`);
|
|
1026
|
-
return {
|
|
1027
|
-
name: "timeout",
|
|
1028
|
-
middleware: async (ctx, next) => {
|
|
1029
|
-
const deadline = ctx.meta?.timeout ?? ms;
|
|
1030
|
-
if (deadline !== ms) checkDeadline(deadline, `meta.timeout: ${deadline}`);
|
|
1031
|
-
const idleMs = idle === Number.POSITIVE_INFINITY ? void 0 : idle;
|
|
1032
|
-
if (deadline === Number.POSITIVE_INFINITY && idleMs === void 0) return next(ctx);
|
|
1033
|
-
const controller = new AbortController();
|
|
1034
|
-
const outer = ctx.init.signal;
|
|
1035
|
-
const signal = outer ? AbortSignal.any([outer, controller.signal]) : controller.signal;
|
|
1036
|
-
const total = deadline === Number.POSITIVE_INFINITY ? void 0 : deadlineTimer(controller, deadline, `arthron: request timed out after ${deadline}ms`);
|
|
1037
|
-
let quiet;
|
|
1038
|
-
const stillAlive = () => {
|
|
1039
|
-
if (idleMs === void 0) return;
|
|
1040
|
-
clearTimeout(quiet);
|
|
1041
|
-
quiet = deadlineTimer(controller, idleMs, `arthron: no data for ${idleMs}ms`);
|
|
1042
|
-
};
|
|
1043
|
-
const finish = () => {
|
|
1044
|
-
clearTimeout(total);
|
|
1045
|
-
clearTimeout(quiet);
|
|
1046
|
-
};
|
|
1047
|
-
stillAlive();
|
|
1048
|
-
let res;
|
|
1049
|
-
try {
|
|
1050
|
-
res = await next({
|
|
1051
|
-
...ctx,
|
|
1052
|
-
init: {
|
|
1053
|
-
...ctx.init,
|
|
1054
|
-
signal
|
|
1055
|
-
}
|
|
1056
|
-
});
|
|
1057
|
-
} catch (thrown) {
|
|
1058
|
-
finish();
|
|
1059
|
-
throw thrown;
|
|
1060
|
-
}
|
|
1061
|
-
if (!res.body) {
|
|
1062
|
-
finish();
|
|
1063
|
-
return res;
|
|
1064
|
-
}
|
|
1065
|
-
stillAlive();
|
|
1066
|
-
return rebuildResponse(res, guardBody(res.body, signal, finish, stillAlive));
|
|
1067
|
-
}
|
|
1068
|
-
};
|
|
1069
|
-
}
|
|
488
|
+
//#region src/index.ts
|
|
489
|
+
/** @deprecated Import from "arthron/plugins"; this export goes in the next major. */
|
|
490
|
+
const logging = logging$1;
|
|
491
|
+
/** @deprecated Import from "arthron/plugins"; this export goes in the next major. */
|
|
492
|
+
const retry = retry$1;
|
|
493
|
+
/** @deprecated Import from "arthron/plugins"; this export goes in the next major. */
|
|
494
|
+
const timeout = timeout$1;
|
|
1070
495
|
//#endregion
|
|
1071
496
|
export { ArthronError, SchemaError, arthron, defineInterceptor, defineMiddleware, definePlugin, isArthronError, logging, retry, timeout };
|
|
1072
497
|
|