@vigilbase/cli
Version:
Vigilbase CLI — security scanners, agent tools, and Vigilbase One from the terminal.
113 lines (112 loc) • 6.85 kB
JavaScript
// GENERATED from packages/api-contract/src/core/operation.ts by scripts/vendor-api-contract.mjs — do not edit
import { z } from 'zod';
import { ERROR_STATUS } from './errors.js';
export const API_ORIGIN = 'https://api.vigilbase.com';
export const PRODUCTS = ['tools', 'one', 'docs', 'os'];
export const HTTP_METHODS = ['GET', 'HEAD', 'POST', 'PUT', 'PATCH', 'DELETE'];
export const SAFE_METHODS = new Set(['GET', 'HEAD']);
/** `https://api.vigilbase.com/{product}/{version}`: every operation path is relative to it. */
export function serverUrl(product, version = 'v1') {
return `${API_ORIGIN}/${product}/${version}`;
}
/** Keeps the literal types of an operation so implementations and clients are typed by it. */
export const defineOperation = (operation) => operation;
export function responseSchema(spec) {
return spec instanceof z.ZodType ? spec : spec.schema;
}
export function responseContentType(spec) {
return (spec instanceof z.ZodType ? undefined : spec.contentType) ?? 'application/json';
}
// ---------------------------------------------------------------- validation
const ID = /^[a-z][a-z0-9]*(?:\.[a-z][a-zA-Z0-9]*)+$/;
const PATH = /^(?:\/(?:[a-z0-9][a-z0-9._-]*|\{[A-Za-z][A-Za-z0-9]*\}))+$/;
export function pathParamNames(path) {
return [...path.matchAll(/\{([^}]+)\}/g)].map((match) => match[1]);
}
/** The problems with a product's operation list; empty when it is consistent. */
export function operationProblems(product, operations) {
const problems = [];
const ids = new Set();
const routes = new Map();
const templates = new Map();
for (const op of operations) {
const at = op.id || `${op.method} ${op.path}`;
if (!ID.test(op.id) || !op.id.startsWith(`${product}.`))
problems.push(`${at}: id must look like ${product}.<resource>.<action>`);
if (ids.has(op.id))
problems.push(`${at}: duplicate operation id`);
ids.add(op.id);
if (op.product !== product)
problems.push(`${at}: product is ${op.product}, expected ${product}`);
if (!PATH.test(op.path))
problems.push(`${at}: path ${op.path} is not a lower-case template`);
// Two templates that differ only in parameter names are the same route.
const shape = `${op.method} ${op.path.replace(/\{[^}]+\}/g, '{}')}`;
if (routes.has(shape))
problems.push(`${at}: same method and path as ${routes.get(shape)}`);
routes.set(shape, op.id);
// One route, one template: GET /x/{id} and DELETE /x/{itemId} would be two OpenAPI paths for one URL.
const skeleton = op.path.replace(/\{[^}]+\}/g, '{}');
const template = templates.get(skeleton);
if (template && template !== op.path)
problems.push(`${at}: path ${op.path} names its parameters differently from ${template}`);
templates.set(skeleton, template ?? op.path);
if (!op.summary.trim())
problems.push(`${at}: summary is empty`);
if (!op.tags.length)
problems.push(`${at}: needs a tag`);
const names = pathParamNames(op.path);
const shapeKeys = op.request.params instanceof z.ZodObject ? Object.keys(op.request.params.shape).sort() : null;
if (names.length && !shapeKeys)
problems.push(`${at}: path parameters need a z.object params schema`);
if (shapeKeys && shapeKeys.join() !== [...names].sort().join())
problems.push(`${at}: params schema keys ${shapeKeys.join()} differ from path ${names.join()}`);
if (op.request.query && !(op.request.query instanceof z.ZodObject))
problems.push(`${at}: query must be a z.object`);
if (SAFE_METHODS.has(op.method) && op.request.body)
problems.push(`${at}: ${op.method} takes no body`);
if (SAFE_METHODS.has(op.method) && op.idempotency)
problems.push(`${at}: ${op.method} is already idempotent`);
// The fingerprint covers JSON bodies only; two different uploads would share one.
if (op.idempotency && op.request.contentType === 'multipart/form-data')
problems.push(`${at}: multipart uploads cannot declare idempotency`);
const statuses = Object.keys(op.responses).map(Number);
if (!statuses.length)
problems.push(`${at}: declares no response`);
if (statuses.some((status) => !Number.isInteger(status) || status < 100 || status >= 400))
problems.push(`${at}: responses are for 1xx–3xx; errors go in \`errors\``);
for (const code of op.errors)
if (!(code in ERROR_STATUS))
problems.push(`${at}: unknown error code ${code}`);
if (op.auth.some((scheme) => scheme.kind === 'anonymous') && op.stepUp)
problems.push(`${at}: an anonymous operation cannot need step-up`);
if (op.pagination === 'cursor' && !(op.request.query instanceof z.ZodObject && 'cursor' in op.request.query.shape && 'limit' in op.request.query.shape)) {
problems.push(`${at}: cursor pagination needs cursor and limit in the query (extend CursorParams)`);
}
if (op.deprecated?.sunset && op.deprecated.sunset.getTime() < op.deprecated.at.getTime())
problems.push(`${at}: sunset is before the deprecation`);
for (const alias of op.legacy ?? []) {
if (!alias.path.startsWith('/api/'))
problems.push(`${at}: legacy alias ${alias.path} is not under /api/`);
// The successor link fills the v1 path with the alias's parameters by position.
if (pathParamNames(alias.path).length !== names.length)
problems.push(`${at}: legacy alias ${alias.path} has a different number of path parameters`);
if (alias.permanent && alias.deprecated?.sunset)
problems.push(`${at}: legacy alias ${alias.path} is permanent and cannot have a sunset`);
if (alias.embedded && !alias.permanent)
problems.push(`${at}: legacy alias ${alias.path} is embedded and must be permanent`);
if (alias.embedded && alias.deprecated)
problems.push(`${at}: legacy alias ${alias.path} is embedded and announces no deprecation`);
if (alias.deprecated?.sunset && alias.deprecated.sunset.getTime() < alias.deprecated.at.getTime())
problems.push(`${at}: legacy alias ${alias.path} sunsets before its deprecation`);
}
}
return problems;
}
/** A product's operations, checked once at module load: a bad declaration fails every test that imports it. */
export function defineOperations(product, operations) {
const problems = operationProblems(product, operations);
if (problems.length)
throw new Error(`invalid ${product} operations:\n- ${problems.join('\n- ')}`);
return operations;
}