Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
160 changes: 160 additions & 0 deletions src/commands/experimental.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,160 @@
import assert from "node:assert/strict";
import { afterEach, beforeEach, describe, it, mock } from "node:test";
import { jsonResponse, stubFetch, useTempHome } from "../test-support.js";
import { experimentalRequest, runSdk } from "./helpers.js";

describe("experimental endpoint errors", () => {
let home: Awaited<ReturnType<typeof useTempHome>>;
let net: ReturnType<typeof stubFetch>;
let output: string;
let warning: string;
let dryRun: boolean;

const run = () =>
runSdk(
() => ({
dryRun,
verbose: false,
pretty: false,
agentMode: false,
apiBase: "https://api.vanta.com/v1",
clientId: "test-client",
clientSecret: "test-secret",
}),
(api) =>
experimentalRequest("try-something-new", () =>
api.client.request({
method: "GET",
url: "/experimental/odd:route",
security: [{ type: "http", scheme: "bearer" }],
}),
),
);

beforeEach(async () => {
home = await useTempHome();
output = "";
warning = "";
dryRun = false;
mock.method(process.stdout, "write", (chunk: string) => {
output += chunk;
return true;
});
mock.method(process.stderr, "write", (chunk: string) => {
warning += chunk;
return true;
});
net = stubFetch((req) =>
req.url.endsWith("/oauth/token")
? jsonResponse(200, { access_token: "test-token", expires_in: 3600 })
: jsonResponse(200, { ok: true }),
);
});
afterEach(async () => {
net.restore();
mock.restoreAll();
await home.restore();
});

function endpoint(response: () => Response): void {
net.restore();
net = stubFetch((req) =>
req.url.endsWith("/oauth/token")
? jsonResponse(200, { access_token: "test-token", expires_in: 3600 })
: response(),
);
}

it("warns on stderr and preserves successful output and authorization", async () => {
await run();
assert.deepEqual(JSON.parse(output), { ok: true });
assert.match(warning, /may change or be removed/);
assert.equal(
net.requests.at(-1)!.headers.get("authorization"),
"Bearer test-token",
);
});

it("explains endpoint failures and retains full API details", async () => {
for (const status of [400, 404, 405, 410, 422, 500, 503]) {
const error = {
message: "Request no longer supported",
fields: { newField: "Required" },
};
endpoint(() => jsonResponse(status, error));
await assert.rejects(run(), (err) => {
assert(err instanceof Error);
assert.match(
err.message,
new RegExp(`vanta experimental try-something-new.*HTTP ${status}`),
);
if ([404, 405, 410].includes(status))
assert.match(err.message, /is unavailable/);
assert.match(err.message, /endpoint may have changed or been removed/);
assert.match(err.message, /Update the Vanta CLI/);
assert.match(err.message, /newField/);
assert.deepEqual(err.cause, error);
return true;
});
}
assert.equal(output, "");
});

it("handles text, empty errors and changed JSON responses", async () => {
for (const [status, body, contentType, detail] of [
[404, "Route was removed", "text/plain", /Route was removed/],
[410, "", "text/plain", /HTTP 410/],
[200, "{broken json", "application/json", /API error:/],
] as const) {
endpoint(
() =>
new Response(body, {
status,
headers: { "content-type": contentType },
}),
);
await assert.rejects(run(), (err) => {
assert(err instanceof Error);
assert.match(err.message, /endpoint may have changed or been removed/);
assert.match(err.message, detail);
return true;
});
}
});

it("preserves authentication and rate-limit diagnostics", async () => {
for (const status of [401, 403, 429]) {
const error = { message: `Specific failure ${status}` };
endpoint(() => jsonResponse(status, error));
await assert.rejects(run(), (err) => {
assert.deepEqual(err, error);
return true;
});
}
});

it("preserves transport and local failures", async () => {
const offline = new TypeError("Connection failed");
endpoint(() => {
throw offline;
});
await assert.rejects(run(), (err) => err === offline);
const local = new Error("Local input error");
await assert.rejects(
experimentalRequest("test", async () => {
throw local;
}),
(err) => err === local,
);
});

it("dry runs never send requests", async () => {
dryRun = true;
await run();
assert.match(
output,
/DRY RUN GET https:\/\/api.vanta.com\/v1\/experimental\/odd:route/,
);
assert.equal(net.requests.length, 0);
});
});
34 changes: 34 additions & 0 deletions src/commands/helpers.ts
Original file line number Diff line number Diff line change
Expand Up @@ -232,3 +232,37 @@ export async function writeDownloadedMedia(
`unsupported media response type: ${Object.prototype.toString.call(data)}`,
);
}

// Wrap only endpoint failures: local input, transport, auth and rate-limit
// errors retain their original diagnostics.
export async function experimentalRequest<
T extends { error?: unknown; response?: Response },
>(command: string, call: () => Promise<T>): Promise<T> {
process.stderr.write(
"Experimental: these endpoints may change or be removed without prior notice. Commands may require a CLI update.\n",
);
const result = await call();
if (
result.error &&
result.response &&
![401, 403, 429].includes(result.response.status)
) {
const error = result.error;
const details =
error instanceof Error
? error.message
: typeof error === "string"
? error
: JSON.stringify(error, null, 2);
const outcome = [404, 405, 410].includes(result.response.status)
? "is unavailable"
: "failed";
throw new Error(
`Experimental command "vanta experimental ${command}" ${outcome} (HTTP ${result.response.status}).\n` +
"The underlying experimental endpoint may have changed or been removed, so this command may no longer be available. Update the Vanta CLI and try again.\n" +
`API error: ${details || result.response.statusText || "No error details returned"}`,
{ cause: error },
);
}
return result;
}
2 changes: 1 addition & 1 deletion src/test-support.ts
Original file line number Diff line number Diff line change
Expand Up @@ -51,7 +51,7 @@ export function stubFetch(
globalThis.fetch = (async (input: RequestInfo | URL, init?: RequestInit) => {
const req: RecordedRequest = {
url: input instanceof Request ? input.url : String(input),
method: init?.method ?? "GET",
method: init?.method ?? (input instanceof Request ? input.method : "GET"),
headers: new Headers(init?.headers),
body:
typeof init?.body === "string"
Expand Down