@vigilbase/cli
Version:
Vigilbase CLI — security scanners, agent tools, and Vigilbase One from the terminal.
126 lines (125 loc) • 5.8 kB
JavaScript
// GENERATED from packages/api-contract/src/client/index.ts by scripts/vendor-api-contract.mjs — do not edit
import { z } from 'zod';
import { PROBLEM_CONTENT_TYPE } from '../core/errors.js';
import { IDEMPOTENCY_HEADER, REQUEST_ID_HEADER } from '../core/headers.js';
import { responseContentType, responseSchema, serverUrl, } from '../core/operation.js';
/**
* Problems as a client reads them: any `code` string, so a code added to the
* contract later still reaches the caller.
*/
const ReceivedProblem = z.looseObject({
type: z.string(),
title: z.string(),
status: z.number(),
detail: z.string(),
code: z.string(),
requestId: z.string().optional(),
docs: z.string().optional(),
errors: z.array(z.object({ pointer: z.string(), message: z.string() })).optional(),
retryAfterSeconds: z.number().optional(),
});
/** A problem answer, or a response the contract does not declare. */
export class ApiCallError extends Error {
status;
problem;
requestId;
body;
constructor(status, problem, requestId, message,
/** The parsed JSON body as sent, whatever its shape; null when it was not JSON. */
body = null) {
super(message);
this.status = status;
this.problem = problem;
this.requestId = requestId;
this.body = body;
this.name = 'ApiCallError';
}
}
/** The URL an operation call goes to: the path template filled in, the query appended. */
export function operationUrl(op, input, baseUrl = serverUrl(op.product, op.version)) {
const params = (input.params ?? {});
const path = op.path.replace(/\{([^}]+)\}/g, (_whole, name) => {
const value = params[name];
if (value === undefined || value === null || value === '')
throw new Error(`${op.id}: missing path parameter ${name}`);
return encodeURIComponent(String(value));
});
const search = new URLSearchParams();
for (const [key, value] of Object.entries((input.query ?? {}))) {
// `[]` goes as no parameter: the dispatcher reads a missing non-optional array as empty.
if (value === undefined || value === null)
continue;
for (const item of Array.isArray(value) ? value : [value])
search.append(key, String(item));
}
const suffix = search.size ? `?${search.toString()}` : '';
return `${baseUrl.replace(/\/+$/, '')}${path}${suffix}`;
}
/**
* Calls a declared operation and returns its parsed, typed response. The input
* is checked against the request schemas before anything is sent; the answer is
* checked against the declared response for its status. Problems and
* undeclared answers throw ApiCallError.
*/
export async function callOperation(op, input, options = {}) {
const values = input;
const multipart = op.request.contentType === 'multipart/form-data';
for (const [part, schema] of [['params', op.request.params], ['query', op.request.query], ['body', multipart ? undefined : op.request.body]]) {
if (schema)
schema.parse(values[part]);
}
const headers = new Headers(options.headers);
headers.set('Accept', `application/json, ${PROBLEM_CONTENT_TYPE}`);
const url = operationUrl(op, values, options.baseUrl);
if (options.token) {
const dpop = options.tokenType?.toLowerCase() === 'dpop';
if (dpop && !options.dpopProof)
throw new Error('DPoP tokens require a proof signer');
headers.set('Authorization', `${dpop ? 'DPoP' : 'Bearer'} ${options.token}`);
if (dpop)
headers.set('DPoP', await options.dpopProof(url, op.method));
}
if (options.idempotencyKey)
headers.set(IDEMPOTENCY_HEADER, options.idempotencyKey);
// RequestInit, not the DOM-only BodyInit: the CLI vendors this file and compiles without DOM types.
let body;
if (op.request.contentType === 'multipart/form-data') {
// fetch writes the multipart Content-Type with its boundary.
if (!(values.body instanceof FormData))
throw new Error(`${op.id}: send the upload as FormData`);
body = values.body;
}
else if (op.request.body && values.body !== undefined) {
headers.set('Content-Type', 'application/json');
body = JSON.stringify(values.body);
}
const response = await (options.fetch ?? fetch)(url, {
method: op.method,
headers,
body,
signal: options.signal,
});
const requestId = response.headers.get(REQUEST_ID_HEADER);
const type = response.headers.get('content-type') ?? '';
if (response.status >= 400) {
// Media types are case-insensitive (RFC 9110 §8.3.1).
const raw = /json/i.test(type) ? await response.json().catch(() => null) : null;
const parsed = ReceivedProblem.safeParse(raw);
const problem = parsed.success ? parsed.data : null;
throw new ApiCallError(response.status, problem, requestId, problem ? `${op.id}: ${problem.code}: ${problem.detail}` : `${op.id}: HTTP ${response.status}`, raw);
}
const spec = op.responses[response.status];
if (!spec)
throw new ApiCallError(response.status, null, requestId, `${op.id}: undeclared status ${response.status}`);
let data;
if (response.status === 204 || op.method === 'HEAD')
data = undefined;
else if (/json/.test(responseContentType(spec)))
data = await response.json();
else
data = await response.text();
const checked = responseSchema(spec).safeParse(data);
if (!checked.success)
throw new ApiCallError(response.status, null, requestId, `${op.id}: the ${response.status} response does not match the contract`);
return { status: response.status, body: checked.data, requestId, headers: response.headers };
}