// Shared server-side transport for the additional REST examples.
let root;
try { root = new URL(process.env.API_ROOT_URL || 'invalid:'); }
catch { throw new Error('Set a valid API_ROOT_URL.'); }
const key = process.env.API_KEY;
if (!['http:', 'https:'].includes(root.protocol) || root.username || root.password
|| root.search || root.hash || !key?.trim()) {
throw new Error('Set HTTP(S) API_ROOT_URL without credentials/query/fragment and API_KEY.');
}
export async function request(path, options = {}) {
if (!path.startsWith('/') || path.startsWith('//') || /[?#\\]/.test(path)
|| path.split('/').some((part) => ['.', '..'].includes(part))) {
throw new Error('Invalid gateway path.');
}
const response = await fetch(`${root.href.replace(/\/+$/, '')}${path}`, {
...options, redirect: 'error', signal: AbortSignal.timeout(60_000),
headers: { ...options.headers, Authorization: `Bearer ${key}` },
});
if (!response.ok) {
await response.body?.cancel();
throw new Error(`Request failed (HTTP ${response.status}). No automatic retry.`);
}
return response;
}
export async function readBody(response, limit) {
const reader = response.body?.getReader();
if (!reader) throw new Error('Missing response body.');
const chunks = [];
let size = 0;
try {
while (true) {
const { done, value } = await reader.read();
if (done) break;
size += value.length;
if (size > limit) throw new Error('Example response size limit exceeded.');
chunks.push(value);
}
} finally {
await reader.cancel();
reader.releaseLock();
}
return Buffer.concat(chunks);
}
export async function requestJSON(path, body) {
const response = await request(path, body === undefined ? {} : {
method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(body),
});
if (!/^application\/(?:[\w.-]+\+)?json(?:\s*;|$)/i.test(response.headers.get('content-type') || '')) {
await response.body?.cancel();
throw new Error('Expected a JSON response.');
}
const result = JSON.parse((await readBody(response, 1024 * 1024)).toString('utf8'));
if (!result || typeof result !== 'object' || Array.isArray(result) || result.error || result.success === false) {
throw new Error('Invalid or unsuccessful JSON response.');
}
return result;
}