@profullstack/chat-plugins 0.0.0-stage → 0.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/src/mcp.js ADDED
@@ -0,0 +1,323 @@
1
+ // MCP client over Streamable HTTP (protocol 2025-06-18): JSON and SSE responses,
2
+ // Mcp-Session-Id handling, timeouts and size caps.
3
+
4
+ import { PluginError, readCapped, safeFetch } from "./net.js";
5
+
6
+ export const PROTOCOL_VERSION = "2025-06-18";
7
+ export const CLIENT_INFO = { name: "@profullstack/chat-plugins", version: "0.1.0" };
8
+ /** Text handed to the model per tool result. The UI keeps the full text. */
9
+ export const MODEL_TEXT_LIMIT = 16 * 1024;
10
+
11
+ let nextId = 1;
12
+
13
+ /**
14
+ * Parse a text/event-stream body and return the JSON-RPC message answering `id`.
15
+ * @param {string} text
16
+ * @param {number | string} id
17
+ */
18
+ export function parseSse(text, id) {
19
+ const events = [];
20
+ let data = [];
21
+ for (const raw of text.split(/\r?\n/)) {
22
+ if (raw === "") {
23
+ if (data.length) events.push(data.join("\n"));
24
+ data = [];
25
+ continue;
26
+ }
27
+ if (raw.startsWith(":")) continue;
28
+ const idx = raw.indexOf(":");
29
+ const field = idx === -1 ? raw : raw.slice(0, idx);
30
+ let value = idx === -1 ? "" : raw.slice(idx + 1);
31
+ if (value.startsWith(" ")) value = value.slice(1);
32
+ if (field === "data") data.push(value);
33
+ }
34
+ if (data.length) events.push(data.join("\n"));
35
+ let fallback = null;
36
+ for (const ev of events) {
37
+ let msg;
38
+ try {
39
+ msg = JSON.parse(ev);
40
+ } catch {
41
+ continue;
42
+ }
43
+ for (const m of Array.isArray(msg) ? msg : [msg]) {
44
+ if (m && m.id === id && ("result" in m || "error" in m)) return m;
45
+ if (m && ("result" in m || "error" in m) && m.id === undefined) fallback = m;
46
+ }
47
+ }
48
+ return fallback;
49
+ }
50
+
51
+ /**
52
+ * Read an SSE stream until the response for `id` arrives (servers may keep the
53
+ * stream open after it).
54
+ * @param {Response} res
55
+ * @param {number | string} id
56
+ * @param {number} maxBytes
57
+ */
58
+ async function readSseFor(res, id, maxBytes) {
59
+ if (!res.body) return null;
60
+ const reader = res.body.getReader();
61
+ const decoder = new TextDecoder();
62
+ let buf = "";
63
+ let total = 0;
64
+ try {
65
+ for (;;) {
66
+ const { done, value } = await reader.read();
67
+ if (value) {
68
+ total += value.byteLength;
69
+ if (total > maxBytes) throw new PluginError(`Response larger than ${maxBytes} bytes`, { code: "too_large" });
70
+ buf += decoder.decode(value, { stream: true });
71
+ // Only parse complete events.
72
+ const cut = Math.max(buf.lastIndexOf("\n\n"), buf.lastIndexOf("\r\n\r\n"));
73
+ if (cut !== -1) {
74
+ const msg = parseSse(buf.slice(0, cut + 2), id);
75
+ if (msg && msg.id === id) return msg;
76
+ }
77
+ }
78
+ if (done) break;
79
+ }
80
+ return parseSse(buf + "\n\n", id);
81
+ } finally {
82
+ try {
83
+ await reader.cancel();
84
+ } catch {}
85
+ }
86
+ }
87
+
88
+ /**
89
+ * @typedef {import("../index.js").Connection} Connection
90
+ * @typedef {import("../index.js").NetOptions} NetOptions
91
+ */
92
+
93
+ /**
94
+ * Send one JSON-RPC message. Returns { result, sessionId } for requests.
95
+ * @param {Connection} conn
96
+ * @param {string} method
97
+ * @param {any} params
98
+ * @param {NetOptions & { sessionId?: string, notification?: boolean }} [opts]
99
+ */
100
+ export async function rpc(conn, method, params, opts = {}) {
101
+ const id = opts.notification ? undefined : nextId++;
102
+ /** @type {Record<string,string>} */
103
+ const headers = {
104
+ "content-type": "application/json",
105
+ accept: "application/json, text/event-stream",
106
+ "mcp-protocol-version": PROTOCOL_VERSION,
107
+ };
108
+ if (conn.token) headers.authorization = `Bearer ${conn.token}`;
109
+ if (opts.sessionId) headers["mcp-session-id"] = opts.sessionId;
110
+ const body = JSON.stringify({ jsonrpc: "2.0", ...(id !== undefined ? { id } : {}), method, ...(params !== undefined ? { params } : {}) });
111
+ const { res, done } = await safeFetch(conn.url, { method: "POST", headers, body }, opts);
112
+ try {
113
+ const sessionId = res.headers.get("mcp-session-id") || opts.sessionId;
114
+ const maxBytes = opts.maxBytes ?? 4_000_000;
115
+ if (res.status === 401 || res.status === 403) {
116
+ await res.body?.cancel().catch(() => {});
117
+ const err = new PluginError(res.status === 401 ? "Sign-in required" : "Not allowed", {
118
+ code: res.status === 401 ? "unauthorized" : "forbidden",
119
+ status: res.status,
120
+ });
121
+ /** @type {any} */ (err).wwwAuthenticate = res.headers.get("www-authenticate") || "";
122
+ throw err;
123
+ }
124
+ if (res.status === 404 && opts.sessionId) {
125
+ await res.body?.cancel().catch(() => {});
126
+ throw new PluginError("MCP session expired", { code: "session_expired", status: 404 });
127
+ }
128
+ if (id === undefined) {
129
+ await res.body?.cancel().catch(() => {});
130
+ if (!res.ok && res.status !== 202) {
131
+ throw new PluginError(`${method} failed: HTTP ${res.status}`, { code: "http_error", status: res.status });
132
+ }
133
+ return { result: undefined, sessionId };
134
+ }
135
+ const ct = res.headers.get("content-type") || "";
136
+ let msg;
137
+ if (/text\/event-stream/i.test(ct)) {
138
+ msg = await readSseFor(res, id, maxBytes);
139
+ } else {
140
+ const text = await readCapped(res, maxBytes);
141
+ try {
142
+ const parsed = JSON.parse(text);
143
+ msg = Array.isArray(parsed) ? parsed.find((m) => m && m.id === id) : parsed;
144
+ } catch {
145
+ msg = null;
146
+ }
147
+ if (!res.ok && !(msg && msg.error)) {
148
+ throw new PluginError(`${method} failed: HTTP ${res.status}`, { code: "http_error", status: res.status });
149
+ }
150
+ }
151
+ if (!msg) throw new PluginError(`${method}: no JSON-RPC response from ${new URL(conn.url).host}`, { code: "bad_response" });
152
+ if (msg.error) {
153
+ throw new PluginError(`${method}: ${msg.error.message || "error"}`, { code: "rpc_error", status: msg.error.code });
154
+ }
155
+ return { result: msg.result, sessionId };
156
+ } finally {
157
+ done();
158
+ }
159
+ }
160
+
161
+ /** @type {Map<string, { sessionId?: string, info: any, at: number }>} */
162
+ const sessions = new Map();
163
+ const SESSION_TTL_MS = 10 * 60 * 1000;
164
+
165
+ /** @param {Connection} conn */
166
+ function sessionKey(conn) {
167
+ // The token is part of the key so two people never share a session.
168
+ return `${conn.url}\u0000${conn.token || ""}`;
169
+ }
170
+
171
+ /**
172
+ * initialize + notifications/initialized. Returns the server's InitializeResult.
173
+ * @param {Connection} conn
174
+ * @param {NetOptions} [opts]
175
+ */
176
+ export async function initialize(conn, opts = {}) {
177
+ const { result, sessionId } = await rpc(
178
+ conn,
179
+ "initialize",
180
+ { protocolVersion: PROTOCOL_VERSION, capabilities: {}, clientInfo: opts.clientInfo || CLIENT_INFO },
181
+ opts,
182
+ );
183
+ try {
184
+ await rpc(conn, "notifications/initialized", undefined, { ...opts, sessionId, notification: true });
185
+ } catch (err) {
186
+ if (/** @type {any} */ (err)?.code === "unauthorized") throw err;
187
+ // Some servers answer notifications oddly; the session still works.
188
+ }
189
+ return { info: result || {}, sessionId };
190
+ }
191
+
192
+ /**
193
+ * @param {Connection} conn
194
+ * @param {NetOptions} opts
195
+ */
196
+ async function getSession(conn, opts) {
197
+ const key = sessionKey(conn);
198
+ const hit = sessions.get(key);
199
+ if (hit && Date.now() - hit.at < SESSION_TTL_MS) return hit;
200
+ const s = await initialize(conn, opts);
201
+ const entry = { ...s, at: Date.now() };
202
+ sessions.set(key, entry);
203
+ if (sessions.size > 500) sessions.delete(sessions.keys().next().value);
204
+ return entry;
205
+ }
206
+
207
+ /**
208
+ * Request inside a (cached) session; re-initializes once if the session expired.
209
+ * @param {Connection} conn
210
+ * @param {string} method
211
+ * @param {any} params
212
+ * @param {NetOptions} [opts]
213
+ */
214
+ export async function request(conn, method, params, opts = {}) {
215
+ let s = await getSession(conn, opts);
216
+ try {
217
+ return (await rpc(conn, method, params, { ...opts, sessionId: s.sessionId })).result;
218
+ } catch (err) {
219
+ const code = /** @type {any} */ (err)?.code;
220
+ if (code === "session_expired" || (code === "http_error" && /** @type {any} */ (err).status === 400 && s.sessionId)) {
221
+ sessions.delete(sessionKey(conn));
222
+ s = await getSession(conn, opts);
223
+ return (await rpc(conn, method, params, { ...opts, sessionId: s.sessionId })).result;
224
+ }
225
+ if (code === "unauthorized") sessions.delete(sessionKey(conn));
226
+ throw err;
227
+ }
228
+ }
229
+
230
+ /** Forget cached sessions (all, or one connection's). @param {Connection} [conn] */
231
+ export function resetSessions(conn) {
232
+ if (conn) sessions.delete(sessionKey(conn));
233
+ else sessions.clear();
234
+ }
235
+
236
+ /**
237
+ * List every tool the server offers (follows nextCursor, capped).
238
+ * @param {Connection} conn
239
+ * @param {NetOptions & { maxTools?: number }} [opts]
240
+ * @returns {Promise<import("../index.js").McpTool[]>}
241
+ */
242
+ export async function listTools(conn, opts = {}) {
243
+ const max = opts.maxTools ?? 128;
244
+ const tools = [];
245
+ let cursor;
246
+ for (let page = 0; page < 10; page++) {
247
+ const result = await request(conn, "tools/list", cursor ? { cursor } : {}, { timeoutMs: 20_000, ...opts });
248
+ for (const t of result?.tools || []) {
249
+ if (!t || typeof t.name !== "string") continue;
250
+ tools.push({
251
+ name: t.name,
252
+ title: typeof t.title === "string" ? t.title : t.annotations?.title,
253
+ description: typeof t.description === "string" ? t.description.slice(0, 2000) : "",
254
+ inputSchema: t.inputSchema && typeof t.inputSchema === "object" ? t.inputSchema : { type: "object", properties: {} },
255
+ annotations: t.annotations && typeof t.annotations === "object" ? t.annotations : {},
256
+ });
257
+ if (tools.length >= max) return tools;
258
+ }
259
+ cursor = result?.nextCursor;
260
+ if (!cursor) break;
261
+ }
262
+ return tools;
263
+ }
264
+
265
+ /**
266
+ * Flatten MCP content blocks to text.
267
+ * @param {any[]} content
268
+ * @param {any} [structured]
269
+ */
270
+ export function contentToText(content, structured) {
271
+ const parts = [];
272
+ for (const c of Array.isArray(content) ? content : []) {
273
+ if (!c || typeof c !== "object") continue;
274
+ if (c.type === "text" && typeof c.text === "string") parts.push(c.text);
275
+ else if (c.type === "resource" && c.resource) {
276
+ if (typeof c.resource.text === "string") parts.push(c.resource.text);
277
+ else parts.push(`[resource ${c.resource.uri || ""}]`);
278
+ } else if (c.type === "resource_link") parts.push(`[link ${c.name || ""} ${c.uri || ""}]`.trim());
279
+ else if (c.type === "image") parts.push(`[image ${c.mimeType || ""}]`);
280
+ else if (c.type === "audio") parts.push(`[audio ${c.mimeType || ""}]`);
281
+ }
282
+ if (!parts.length && structured !== undefined) {
283
+ try {
284
+ parts.push(JSON.stringify(structured, null, 2));
285
+ } catch {}
286
+ }
287
+ return parts.join("\n\n");
288
+ }
289
+
290
+ /**
291
+ * Cut text to a byte budget on a character boundary, with a marker.
292
+ * @param {string} text
293
+ * @param {number} [limit]
294
+ */
295
+ export function truncateForModel(text, limit = MODEL_TEXT_LIMIT) {
296
+ const enc = new TextEncoder();
297
+ const bytes = enc.encode(text);
298
+ if (bytes.length <= limit) return text;
299
+ let cut = new TextDecoder().decode(bytes.slice(0, limit));
300
+ cut = cut.replace(/�+$/, "");
301
+ return `${cut}\n\n[truncated: ${bytes.length - enc.encode(cut).length} more bytes not shown]`;
302
+ }
303
+
304
+ /**
305
+ * Call one tool.
306
+ * @param {Connection} conn
307
+ * @param {string} name
308
+ * @param {Record<string, unknown>} [args]
309
+ * @param {NetOptions & { modelTextLimit?: number }} [opts]
310
+ * @returns {Promise<import("../index.js").ToolResult>}
311
+ */
312
+ export async function callTool(conn, name, args = {}, opts = {}) {
313
+ const result = await request(conn, "tools/call", { name, arguments: args || {} }, { timeoutMs: 60_000, ...opts });
314
+ const content = Array.isArray(result?.content) ? result.content : [];
315
+ const text = contentToText(content, result?.structuredContent);
316
+ return {
317
+ isError: result?.isError === true,
318
+ content,
319
+ structuredContent: result?.structuredContent,
320
+ text,
321
+ modelText: truncateForModel(text, opts.modelTextLimit ?? MODEL_TEXT_LIMIT),
322
+ };
323
+ }
package/src/net.js ADDED
@@ -0,0 +1,299 @@
1
+ // Network guard: every request this package makes goes through safeFetch.
2
+ //
3
+ // - https only (http allowed for localhost when `allowHttpLocalhost`, or anywhere
4
+ // when `allowPrivate` is set, which tests and local dev use).
5
+ // - SSRF: the hostname is resolved (node:dns when available) and every address
6
+ // must be public. Private, loopback, link-local, CGNAT, multicast and
7
+ // reserved ranges are refused unless `allowPrivate`.
8
+ // - Redirects are followed by hand, re-checked at every hop, and a request that
9
+ // carries a bearer token is never forwarded to a different origin.
10
+ // - Response bodies are read with a byte cap.
11
+
12
+ export class PluginError extends Error {
13
+ /**
14
+ * @param {string} message
15
+ * @param {{ code?: string, status?: number, cause?: unknown }} [info]
16
+ */
17
+ constructor(message, info = {}) {
18
+ super(message);
19
+ this.name = "PluginError";
20
+ this.code = info.code || "plugin_error";
21
+ if (info.status !== undefined) this.status = info.status;
22
+ if (info.cause !== undefined) this.cause = info.cause;
23
+ }
24
+ }
25
+
26
+ const LOCAL_NAMES = new Set(["localhost", "localhost.localdomain", "ip6-localhost", "ip6-loopback"]);
27
+
28
+ /** @param {string} host */
29
+ function stripBrackets(host) {
30
+ return host.startsWith("[") && host.endsWith("]") ? host.slice(1, -1) : host;
31
+ }
32
+
33
+ /** @param {string} ip */
34
+ function parseV4(ip) {
35
+ const m = /^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})$/.exec(ip);
36
+ if (!m) return null;
37
+ const parts = m.slice(1).map(Number);
38
+ if (parts.some((p) => p > 255)) return null;
39
+ return parts;
40
+ }
41
+
42
+ /**
43
+ * True when an IP literal is not a public unicast address.
44
+ * @param {string} ip
45
+ */
46
+ export function isPrivateAddress(ip) {
47
+ ip = stripBrackets(String(ip).trim()).toLowerCase();
48
+ const v4 = parseV4(ip);
49
+ if (v4) {
50
+ const [a, b, c] = v4;
51
+ if (a === 0 || a === 10 || a === 127) return true;
52
+ if (a === 100 && b >= 64 && b <= 127) return true; // CGNAT
53
+ if (a === 169 && b === 254) return true; // link-local, cloud metadata
54
+ if (a === 172 && b >= 16 && b <= 31) return true;
55
+ if (a === 192 && b === 168) return true;
56
+ if (a === 192 && b === 0 && (c === 0 || c === 2)) return true;
57
+ if (a === 198 && (b === 18 || b === 19)) return true; // benchmarking
58
+ if (a === 198 && b === 51 && c === 100) return true;
59
+ if (a === 203 && b === 0 && c === 113) return true;
60
+ if (a >= 224) return true; // multicast, reserved, broadcast
61
+ return false;
62
+ }
63
+ if (!ip.includes(":")) return false; // not an IP literal
64
+ if (ip === "::" || ip === "::1") return true;
65
+ const mapped = /^::(?:ffff:)?(\d+\.\d+\.\d+\.\d+)$/.exec(ip);
66
+ if (mapped) return isPrivateAddress(mapped[1]);
67
+ const mappedHex = /^::ffff:([0-9a-f]{1,4}):([0-9a-f]{1,4})$/.exec(ip);
68
+ if (mappedHex) {
69
+ const hi = parseInt(mappedHex[1], 16);
70
+ const lo = parseInt(mappedHex[2], 16);
71
+ return isPrivateAddress(`${hi >> 8}.${hi & 255}.${lo >> 8}.${lo & 255}`);
72
+ }
73
+ const groups = ip.split(":");
74
+ const first = parseInt(groups[0] || "0", 16);
75
+ if ((first & 0xfe00) === 0xfc00) return true; // fc00::/7 unique local
76
+ if ((first & 0xffc0) === 0xfe80) return true; // fe80::/10 link-local
77
+ if ((first & 0xffc0) === 0xfec0) return true; // site-local (deprecated)
78
+ if ((first & 0xff00) === 0xff00) return true; // multicast
79
+ if (first === 0x2001 && groups[1] === "db8") return true; // documentation
80
+ if (first === 0x64 && groups[1] === "ff9b") return true; // NAT64 reaches v4 private
81
+ if (first === 0x2002) return true; // 6to4 embeds an arbitrary v4
82
+ return false;
83
+ }
84
+
85
+ /** @param {string} host */
86
+ function isIpLiteral(host) {
87
+ host = stripBrackets(host);
88
+ return !!parseV4(host) || host.includes(":");
89
+ }
90
+
91
+ /** @param {string} host */
92
+ export function isLocalHostname(host) {
93
+ host = stripBrackets(host).toLowerCase().replace(/\.$/, "");
94
+ if (LOCAL_NAMES.has(host) || host.endsWith(".localhost")) return true;
95
+ if (isIpLiteral(host)) {
96
+ const v4 = parseV4(host);
97
+ return (v4 && v4[0] === 127) || host === "::1";
98
+ }
99
+ return false;
100
+ }
101
+
102
+ /** @type {any} */
103
+ let dnsLookup;
104
+ async function getLookup() {
105
+ if (dnsLookup !== undefined) return dnsLookup;
106
+ try {
107
+ const dns = await import("node:dns/promises");
108
+ dnsLookup = dns.lookup;
109
+ } catch {
110
+ dnsLookup = null; // browser / edge: literal checks only
111
+ }
112
+ return dnsLookup;
113
+ }
114
+
115
+ /**
116
+ * Throws a PluginError unless `url` is safe to fetch from a server.
117
+ * @param {string | URL} input
118
+ * @param {import("../index.js").NetOptions} [opts]
119
+ * @returns {Promise<URL>}
120
+ */
121
+ export async function assertSafeUrl(input, opts = {}) {
122
+ let url;
123
+ try {
124
+ url = new URL(String(input));
125
+ } catch {
126
+ throw new PluginError(`Not a valid URL: ${String(input).slice(0, 200)}`, { code: "bad_url" });
127
+ }
128
+ if (url.username || url.password) {
129
+ throw new PluginError("Plugin URLs cannot carry credentials", { code: "bad_url" });
130
+ }
131
+ const host = url.hostname;
132
+ const local = isLocalHostname(host);
133
+ if (url.protocol === "http:") {
134
+ if (!(opts.allowPrivate || (opts.allowHttpLocalhost && local))) {
135
+ throw new PluginError("Plugin URLs must use https", { code: "insecure_url" });
136
+ }
137
+ } else if (url.protocol !== "https:") {
138
+ throw new PluginError(`Unsupported URL scheme ${url.protocol}`, { code: "bad_url" });
139
+ }
140
+ if (!opts.allowPrivate && !(opts.allowHttpLocalhost && local)) {
141
+ if (local) throw new PluginError("Plugin URL points at this machine", { code: "private_address" });
142
+ if (isIpLiteral(host)) {
143
+ if (isPrivateAddress(host)) {
144
+ throw new PluginError("Plugin URL points at a private address", { code: "private_address" });
145
+ }
146
+ } else {
147
+ const lookup = await getLookup();
148
+ if (lookup) {
149
+ let addrs;
150
+ try {
151
+ addrs = await lookup(host, { all: true, verbatim: true });
152
+ } catch (err) {
153
+ throw new PluginError(`Cannot resolve ${host}`, { code: "dns_failed", cause: err });
154
+ }
155
+ if (!addrs.length) throw new PluginError(`Cannot resolve ${host}`, { code: "dns_failed" });
156
+ for (const a of addrs) {
157
+ if (isPrivateAddress(a.address)) {
158
+ throw new PluginError(`${host} resolves to a private address`, { code: "private_address" });
159
+ }
160
+ }
161
+ }
162
+ }
163
+ }
164
+ if (opts.guard) await opts.guard(url);
165
+ return url;
166
+ }
167
+
168
+ /**
169
+ * Read a response body as text with a byte cap.
170
+ * @param {Response} res
171
+ * @param {number} maxBytes
172
+ */
173
+ export async function readCapped(res, maxBytes) {
174
+ if (!res.body) return "";
175
+ const reader = res.body.getReader();
176
+ const decoder = new TextDecoder();
177
+ let total = 0;
178
+ let out = "";
179
+ for (;;) {
180
+ const { done, value } = await reader.read();
181
+ if (done) break;
182
+ total += value.byteLength;
183
+ if (total > maxBytes) {
184
+ try {
185
+ await reader.cancel();
186
+ } catch {}
187
+ throw new PluginError(`Response larger than ${maxBytes} bytes`, { code: "too_large" });
188
+ }
189
+ out += decoder.decode(value, { stream: true });
190
+ }
191
+ return out + decoder.decode();
192
+ }
193
+
194
+ /**
195
+ * fetch with the guard, a timeout, and hand-followed redirects (each hop re-checked;
196
+ * an authenticated request never leaves its origin). The caller must call done().
197
+ * @param {string | URL} input
198
+ * @param {RequestInit & { headers?: Record<string,string> }} init
199
+ * @param {import("../index.js").NetOptions} [opts]
200
+ * @returns {Promise<{ res: Response, url: URL, done: () => void }>}
201
+ */
202
+ export async function safeFetch(input, init = {}, opts = {}) {
203
+ const f = opts.fetch || globalThis.fetch;
204
+ if (!f) throw new PluginError("No fetch implementation available");
205
+ const ctrl = new AbortController();
206
+ const timeoutMs = opts.timeoutMs ?? 30_000;
207
+ const timer = setTimeout(() => ctrl.abort(), timeoutMs);
208
+ const done = () => clearTimeout(timer);
209
+ try {
210
+ let url = await assertSafeUrl(input, opts);
211
+ const origin0 = url.origin;
212
+ const headers = { ...(init.headers || {}) };
213
+ const hasAuth = Object.keys(headers).some((k) => k.toLowerCase() === "authorization");
214
+ let method = init.method || "GET";
215
+ let body = init.body;
216
+ for (let hop = 0; hop < 5; hop++) {
217
+ let res;
218
+ try {
219
+ res = await f(url.toString(), { ...init, method, body, headers, redirect: "manual", signal: ctrl.signal });
220
+ } catch (err) {
221
+ if (ctrl.signal.aborted) {
222
+ throw new PluginError(`Request to ${url.host} timed out after ${timeoutMs} ms`, { code: "timeout" });
223
+ }
224
+ throw new PluginError(`Could not reach ${url.host}: ${/** @type {any} */ (err)?.message || err}`, {
225
+ code: "network",
226
+ cause: err,
227
+ });
228
+ }
229
+ const loc = res.headers.get("location");
230
+ if (res.status >= 300 && res.status < 400 && loc) {
231
+ const next = new URL(loc, url);
232
+ try {
233
+ await res.body?.cancel();
234
+ } catch {}
235
+ if (hasAuth && next.origin !== origin0) {
236
+ throw new PluginError("Plugin redirected an authenticated request to another host", {
237
+ code: "cross_origin_redirect",
238
+ });
239
+ }
240
+ url = await assertSafeUrl(next, opts);
241
+ if (res.status === 303) {
242
+ method = "GET";
243
+ body = undefined;
244
+ }
245
+ continue;
246
+ }
247
+ return { res, url, done };
248
+ }
249
+ throw new PluginError("Too many redirects", { code: "redirect_loop" });
250
+ } catch (err) {
251
+ done();
252
+ throw err;
253
+ }
254
+ }
255
+
256
+ /**
257
+ * Fetch and parse JSON. With `soft`, returns null instead of throwing on a
258
+ * non-2xx status or a body that is not a JSON object (an HTML 200 included).
259
+ * @param {string | URL} url
260
+ * @param {RequestInit & { headers?: Record<string,string> }} init
261
+ * @param {import("../index.js").NetOptions & { soft?: boolean }} [opts]
262
+ * @returns {Promise<any>}
263
+ */
264
+ export async function fetchJson(url, init = {}, opts = {}) {
265
+ let r;
266
+ try {
267
+ r = await safeFetch(url, init, opts);
268
+ } catch (err) {
269
+ if (opts.soft && /** @type {any} */ (err)?.code !== "private_address" && /** @type {any} */ (err)?.code !== "insecure_url") {
270
+ return null;
271
+ }
272
+ throw err;
273
+ }
274
+ const { res, done } = r;
275
+ try {
276
+ const text = await readCapped(res, opts.maxBytes ?? 1_000_000);
277
+ let json = null;
278
+ if (/^\s*[{[]/.test(text)) {
279
+ try {
280
+ json = JSON.parse(text);
281
+ } catch {
282
+ json = null;
283
+ }
284
+ }
285
+ if (!res.ok || json === null || typeof json !== "object" || Array.isArray(json)) {
286
+ if (opts.soft) return null;
287
+ const msg =
288
+ (json && (json.error_description || json.error?.message || json.error || json.message)) ||
289
+ `HTTP ${res.status}`;
290
+ throw new PluginError(`${new URL(String(url)).host}: ${typeof msg === "string" ? msg : JSON.stringify(msg)}`, {
291
+ code: "http_error",
292
+ status: res.status,
293
+ });
294
+ }
295
+ return json;
296
+ } finally {
297
+ done();
298
+ }
299
+ }