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
5 changes: 4 additions & 1 deletion src/cli/dynamic-commands.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import { validateResponse } from "../validator/schema.js";
import { filterPii } from "@lucianfialho/pii-filter";
import { printDryRun } from "./dry-run.js";
import { simplifyName } from "./agent-help.js";
import { sanitizeCommandName, uniqueName } from "./sanitize.js";
import type { RuntimeConfig } from "../executor/types.js";
import type { OperationGroup, OpenAPISpec } from "../parser/types.js";

Expand All @@ -14,8 +15,10 @@ export function buildDynamicCommands(
config: RuntimeConfig,
spec?: OpenAPISpec
): void {
const usedNames = new Set<string>();
for (const group of groups) {
const groupCmd = prog.command(group.tag).description(group.description);
const groupName = uniqueName(sanitizeCommandName(group.tag), usedNames);
const groupCmd = prog.command(groupName).description(group.description);

for (const op of group.operations) {
const cmdName = simplifyName(op.id, group.tag);
Expand Down
11 changes: 11 additions & 0 deletions src/cli/sanitize.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
export function sanitizeCommandName(name: string): string {
return name.toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-+|-+$/g, "") || "group";
}

export function uniqueName(name: string, used: Set<string>): string {
let candidate = name;
let n = 2;
while (used.has(candidate)) candidate = `${name}-${n++}`;
used.add(candidate);
return candidate;
}
137 changes: 137 additions & 0 deletions src/executor/commander-builder.json-params.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,137 @@
import { describe, it, expect, vi, beforeEach } from "vitest";
import { Command } from "commander";
import { loadSpec } from "../parser/loader.js";
import { buildCommands } from "./commander-builder.js";
import type { RuntimeConfig } from "./types.js";
import path from "node:path";

const FIXTURE = path.resolve("test/fixtures/petstore.yaml");

const config: RuntimeConfig = {
specPath: FIXTURE,
baseUrl: "https://example.com",
auth: { type: "none", value: "" },
output: "json",
verbose: false,
quiet: false,
dryRun: false,
validate: false,
};

describe("collectParams JSON parsing", () => {
beforeEach(() => {
vi.restoreAllMocks();
});

it("parses object params from JSON strings", async () => {
const op: Operation = {
id: "createVideos",
method: "POST",
path: "/videos",
summary: "Create video",
description: "",
params: [
{ name: "name", in: "body", type: "string", required: true, description: "" },
{ name: "content", in: "body", type: "object", required: true, description: "" },
],
bodyRequired: true,
security: [],
};

let capturedBody: unknown;
vi.stubGlobal("fetch", vi.fn().mockImplementation((_url: string, init: RequestInit) => {
capturedBody = JSON.parse(init.body as string);
return Promise.resolve({
status: 200,
statusText: "OK",
headers: new Map([["content-type", "application/json"]]),
text: () => Promise.resolve("{}"),
});
}));

const spec = await loadSpec(FIXTURE);
const program = new Command();
program.exitOverride();
buildCommands(program, [{ tag: "Videos", description: "", operations: [op] }], config, spec);

await program.parseAsync(["node", "test", "videos", "create", "--name", "Test", "--content", '{"text":"hello"}']);

expect(capturedBody).toEqual({ name: "Test", content: { text: "hello" } });

vi.unstubAllGlobals();
});

it("parses array params from JSON strings", async () => {
const op: Operation = {
id: "createItem",
method: "POST",
path: "/items",
summary: "Create items",
description: "",
params: [
{ name: "tags", in: "body", type: "array", required: true, description: "" },
],
bodyRequired: true,
security: [],
};

let capturedBody: unknown;
vi.stubGlobal("fetch", vi.fn().mockImplementation((_url: string, init: RequestInit) => {
capturedBody = JSON.parse(init.body as string);
return Promise.resolve({
status: 200,
statusText: "OK",
headers: new Map([["content-type", "application/json"]]),
text: () => Promise.resolve("{}"),
});
}));

const spec = await loadSpec(FIXTURE);
const program = new Command();
program.exitOverride();
buildCommands(program, [{ tag: "Items", description: "", operations: [op] }], config, spec);

await program.parseAsync(["node", "test", "items", "create", "--tags", '["a","b"]']);

expect(capturedBody).toEqual({ tags: ["a", "b"] });

vi.unstubAllGlobals();
});

it("falls back to string when JSON parse fails", async () => {
const op: Operation = {
id: "createThings",
method: "POST",
path: "/things",
summary: "Create thing",
description: "",
params: [
{ name: "data", in: "body", type: "object", required: true, description: "" },
],
bodyRequired: true,
security: [],
};

let capturedBody: unknown;
vi.stubGlobal("fetch", vi.fn().mockImplementation((_url: string, init: RequestInit) => {
capturedBody = JSON.parse(init.body as string);
return Promise.resolve({
status: 200,
statusText: "OK",
headers: new Map([["content-type", "application/json"]]),
text: () => Promise.resolve("{}"),
});
}));

const spec = await loadSpec(FIXTURE);
const program = new Command();
program.exitOverride();
buildCommands(program, [{ tag: "Things", description: "", operations: [op] }], config, spec);

await program.parseAsync(["node", "test", "things", "create", "--data", "not-json"]);

expect(capturedBody).toEqual({ data: "not-json" });

vi.unstubAllGlobals();
});
});
117 changes: 0 additions & 117 deletions src/executor/commander-builder.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -107,120 +107,3 @@ describe("buildCommands", () => {
});
});

describe("collectParams JSON parsing", () => {
beforeEach(() => {
vi.restoreAllMocks();
});

it("parses object params from JSON strings", async () => {
const op: Operation = {
id: "createVideos",
method: "POST",
path: "/videos",
summary: "Create video",
description: "",
params: [
{ name: "name", in: "body", type: "string", required: true, description: "" },
{ name: "content", in: "body", type: "object", required: true, description: "" },
],
bodyRequired: true,
security: [],
};

let capturedBody: unknown;
vi.stubGlobal("fetch", vi.fn().mockImplementation((_url: string, init: RequestInit) => {
capturedBody = JSON.parse(init.body as string);
return Promise.resolve({
status: 200,
statusText: "OK",
headers: new Map([["content-type", "application/json"]]),
text: () => Promise.resolve("{}"),
});
}));

const spec = await loadSpec(FIXTURE);
const program = new Command();
program.exitOverride();
buildCommands(program, [{ tag: "Videos", description: "", operations: [op] }], config, spec);

await program.parseAsync(["node", "test", "Videos", "create", "--name", "Test", "--content", '{"text":"hello"}']);

expect(capturedBody).toEqual({ name: "Test", content: { text: "hello" } });

vi.unstubAllGlobals();
});

it("parses array params from JSON strings", async () => {
const op: Operation = {
id: "createItem",
method: "POST",
path: "/items",
summary: "Create items",
description: "",
params: [
{ name: "tags", in: "body", type: "array", required: true, description: "" },
],
bodyRequired: true,
security: [],
};

let capturedBody: unknown;
vi.stubGlobal("fetch", vi.fn().mockImplementation((_url: string, init: RequestInit) => {
capturedBody = JSON.parse(init.body as string);
return Promise.resolve({
status: 200,
statusText: "OK",
headers: new Map([["content-type", "application/json"]]),
text: () => Promise.resolve("{}"),
});
}));

const spec = await loadSpec(FIXTURE);
const program = new Command();
program.exitOverride();
buildCommands(program, [{ tag: "Items", description: "", operations: [op] }], config, spec);

await program.parseAsync(["node", "test", "Items", "create", "--tags", '["a","b"]']);

expect(capturedBody).toEqual({ tags: ["a", "b"] });

vi.unstubAllGlobals();
});

it("falls back to string when JSON parse fails", async () => {
const op: Operation = {
id: "createThings",
method: "POST",
path: "/things",
summary: "Create thing",
description: "",
params: [
{ name: "data", in: "body", type: "object", required: true, description: "" },
],
bodyRequired: true,
security: [],
};

let capturedBody: unknown;
vi.stubGlobal("fetch", vi.fn().mockImplementation((_url: string, init: RequestInit) => {
capturedBody = JSON.parse(init.body as string);
return Promise.resolve({
status: 200,
statusText: "OK",
headers: new Map([["content-type", "application/json"]]),
text: () => Promise.resolve("{}"),
});
}));

const spec = await loadSpec(FIXTURE);
const program = new Command();
program.exitOverride();
buildCommands(program, [{ tag: "Things", description: "", operations: [op] }], config, spec);

await program.parseAsync(["node", "test", "Things", "create", "--data", "not-json"]);

expect(capturedBody).toEqual({ data: "not-json" });

vi.unstubAllGlobals();
});
});
6 changes: 5 additions & 1 deletion src/executor/commander-builder.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,16 +2,19 @@ import { Command } from "commander";
import type { OperationGroup, Operation, OpenAPISpec } from "../parser/types.js";
import type { RuntimeConfig } from "./types.js";
import { executeRequest } from "./http.js";
import { sanitizeCommandName, uniqueName } from "../cli/sanitize.js";

export function buildCommands(
program: Command,
groups: OperationGroup[],
config: RuntimeConfig,
spec: OpenAPISpec
): void {
const usedNames = new Set<string>();
for (const group of groups) {
const groupName = uniqueName(sanitizeCommandName(group.tag), usedNames);
const groupCmd = program
.command(group.tag)
.command(groupName)
.description(group.description);

for (const op of group.operations) {
Expand Down Expand Up @@ -128,3 +131,4 @@ function simplifyName(operationId: string, tag: string): string {

return operationId.toLowerCase();
}

Loading