@vigilbase/cli
Version:
Vigilbase CLI — security scanners, agent tools, and Vigilbase One from the terminal.
107 lines (106 loc) • 5.7 kB
JavaScript
/**
* One's v1 API (api.vigilbase.com/one/v1) from the CLI: the operations come from the vendored
* `@vigilbase/api-contract` (src/vendor/api-contract), and `callOperation` checks every input against the
* request schemas and every answer against the declared response schema. Problems become VigilbaseApiErrors
* with One's code, detail and request ID.
*/
import { ApiCallError } from '../vendor/api-contract/client/index.js';
import { PAGE_LIMIT_MAX } from '../vendor/api-contract/core/pagination.js';
import { ONE_V1_OPERATIONS } from '../vendor/api-contract/one/v1/index.js';
import { shellQuote } from '../auth/store.js';
import { VigilbaseApiError } from './client.js';
import { singleLine } from './format.js';
import { oneErrorHint } from './one-error-hints.js';
export { ONE_V1_OPERATIONS };
/** The v1 operation the CLI names `id`, from the contract; a typo fails at module load in tests. */
export function v1Operation(id) {
const op = ONE_V1_OPERATIONS.find((candidate) => candidate.id === id);
if (!op)
throw new Error(`Unknown One v1 operation ${id}.`);
return op;
}
/** Detail text from a problem: One's v1 details are written for API callers, but stay one bounded line. */
const MAX_DETAIL = 300;
/**
* A v1 failure as the CLI reports it. Errors that aren't the client's own pass through unchanged.
* `retryAfterHeader` is the answer's Retry-After, for a 429 whose problem body names none.
*/
export function v1Error(op, query, error, retryAfterHeader) {
if (!(error instanceof ApiCallError))
return error;
const { status, problem } = error;
const requestId = error.requestId ?? problem?.requestId ?? undefined;
const code = problem?.code;
const hasCustomerScope = Boolean(query && typeof query === 'object' && 'customerId' in query && query.customerId);
const hint = oneErrorHint({ method: op.method, path: op.path, status, code, hasCustomerScope });
const options = { status, code, requestId, hint, isCliAuthored: true, retryAfterSec: problem?.retryAfterSeconds ?? retryAfterHeader, body: problem ?? undefined };
if (status === 401)
return new VigilbaseApiError('Authentication required. Run `vigilbase login`.', options);
if (problem) {
const detail = singleLine(problem.detail, MAX_DETAIL) || singleLine(problem.title, MAX_DETAIL);
return new VigilbaseApiError(detail || `Request failed (HTTP ${status}).`, { ...options, reason: detail || undefined });
}
// Without a problem body, the legacy client's wording.
if (status === 403)
return new VigilbaseApiError("You don't have access to this.", options);
if (status >= 400)
return new VigilbaseApiError(status === 429 ? 'Rate limit exceeded.' : `Request failed (HTTP ${status}).`, options);
// An undeclared status, or a body that does not match the declared schema.
return new VigilbaseApiError(`Invalid One API response for ${op.id} (HTTP ${status}).`, options);
}
/** The largest page an operation accepts: 200 by the contract's CursorParams, less where it narrows `limit`. */
function pageMax(op) {
const shape = op.request.query?.shape;
for (const size of [PAGE_LIMIT_MAX, 100, 50])
if (shape?.limit?.safeParse(size).success)
return size;
return 50;
}
/** Following every page stops here; the answer then carries nextCursor so the caller can go on. */
export const MAX_FOLLOWED_ITEMS = 10_000;
/**
* A v1 list, page by page. --cursor reads one page; --limit reads pages until it has that many items, asking
* each page for only what is left so the returned nextCursor continues exactly where the items end; without
* either, `all` follows nextCursor to the end and `page` reads the API's default page.
*/
export async function listV1(client, op, input, selection) {
const base = input;
const page = async (query) => {
const { body } = await client.callV1(op, { ...base, query: { ...base.query, ...query } });
return body;
};
if (selection.cursor !== undefined)
return page({ cursor: selection.cursor, ...(selection.limit ? { limit: Math.min(selection.limit, pageMax(op)) } : {}) });
if (selection.limit === undefined && selection.defaultScope === 'page')
return page({});
const wanted = selection.limit ?? MAX_FOLLOWED_ITEMS;
const items = [];
const seen = new Set();
let cursor;
for (;;) {
const next = await page({ limit: Math.min(wanted - items.length, pageMax(op)), ...(cursor ? { cursor } : {}) });
items.push(...next.items);
cursor = next.nextCursor;
if (!cursor || items.length >= wanted)
break;
// A cursor that comes back again would loop forever.
if (seen.has(cursor))
throw new VigilbaseApiError(`One API returned a repeated cursor for ${op.id}.`, { status: 200, isCliAuthored: true });
seen.add(cursor);
if (!next.items.length)
break;
}
return cursor ? { items, nextCursor: cursor } : { items };
}
/**
* `More: vigilbase <args…> --cursor <next>` for a list with another page. One binds a cursor to the filters it
* was issued with, so `args` must repeat every filter of the request (and --limit when one was given). Each word
* is shell-quoted: filter values and the opaque cursor are pasted into a shell.
*/
export function moreCommand(args, nextCursor) {
return `More: vigilbase ${[...args.filter((arg) => arg !== undefined), '--cursor', nextCursor].map(shellQuote).join(' ')}`;
}
/** `[flag, value]` when the value was given, for moreCommand. */
export function flagArgs(flag, value) {
return value === undefined ? [] : [flag, String(value)];
}