@rapidoc/cli 0.0.0-stage → 0.1.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE.txt +22 -0
- package/README.md +57 -2
- package/package.json +59 -4
- package/src/bundle/components.js +187 -0
- package/src/bundle/dereference.js +67 -0
- package/src/bundle/write.js +20 -0
- package/src/commands/build.js +59 -0
- package/src/commands/bundle.js +187 -0
- package/src/commands/completion.js +37 -0
- package/src/commands/dev.js +51 -0
- package/src/commands/doctor.js +214 -0
- package/src/commands/init.js +163 -0
- package/src/commands/lint.js +160 -0
- package/src/commands/mcp.js +190 -0
- package/src/commands/migrate.js +112 -0
- package/src/commands/mock.js +200 -0
- package/src/commands/preview.js +218 -0
- package/src/commands/serve.js +95 -0
- package/src/commands/validate.js +139 -0
- package/src/index.js +126 -0
- package/src/lib/args.js +156 -0
- package/src/lib/completion.js +222 -0
- package/src/lib/engines.js +74 -0
- package/src/lib/errors.js +32 -0
- package/src/lib/help.js +75 -0
- package/src/lib/open.js +23 -0
- package/src/lib/openapi-shape.js +110 -0
- package/src/lib/output.js +38 -0
- package/src/lib/ports.js +65 -0
- package/src/lib/prompt.js +73 -0
- package/src/lib/suggest.js +36 -0
- package/src/lint/config.js +112 -0
- package/src/lint/rules/index.js +40 -0
- package/src/lint/rules/info-contact.js +12 -0
- package/src/lint/rules/info-license.js +11 -0
- package/src/lint/rules/media-example.js +35 -0
- package/src/lint/rules/no-server-example-com.js +30 -0
- package/src/lint/rules/no-unused-components.js +41 -0
- package/src/lint/rules/operation-2xx-response.js +17 -0
- package/src/lint/rules/operation-4xx-response.js +17 -0
- package/src/lint/rules/operation-description.js +12 -0
- package/src/lint/rules/operation-operationId-unique.js +24 -0
- package/src/lint/rules/operation-operationId-url-safe.js +18 -0
- package/src/lint/rules/operation-operationId.js +12 -0
- package/src/lint/rules/operation-summary.js +12 -0
- package/src/lint/rules/operation-tag-defined.js +22 -0
- package/src/lint/rules/path-kebab-case.js +16 -0
- package/src/lint/rules/security-defined.js +23 -0
- package/src/lint/rules/security-scheme-defined.js +28 -0
- package/src/lint/rules/tag-description.js +11 -0
- package/src/lint/run.js +50 -0
- package/src/lint/traverse.js +114 -0
- package/src/lint/types.js +46 -0
- package/src/validate/bundle.js +238 -0
- package/src/validate/check.js +122 -0
- package/src/validate/report.js +140 -0
|
@@ -0,0 +1,190 @@
|
|
|
1
|
+
import fs from "node:fs";
|
|
2
|
+
import path from "node:path";
|
|
3
|
+
import pkg from "../../package.json" with { type: "json" };
|
|
4
|
+
import { loadMcpSdk } from "../lib/engines.js";
|
|
5
|
+
import { CancelledError, ProblemError, UsageError } from "../lib/errors.js";
|
|
6
|
+
import { icon, info, setQuiet, warn } from "../lib/output.js";
|
|
7
|
+
import { canAsk, confirm } from "../lib/prompt.js";
|
|
8
|
+
|
|
9
|
+
/*
|
|
10
|
+
* rapidoc mcp export <spec>: writes the MCP server project for a spec (the same files as <rapi-doc>'s
|
|
11
|
+
* Export MCP Server button: manifest.json, server.ts, runtime.js, package.json, README.md,
|
|
12
|
+
* claude_desktop_config.json). rapidoc mcp serve <spec>: runs that server over stdio right away, for an
|
|
13
|
+
* AI agent's config, without writing files. Both use @rapidoc/mcp; serve also needs the MCP SDK.
|
|
14
|
+
*/
|
|
15
|
+
|
|
16
|
+
const isUrl = (target) => /^https?:\/\//i.test(target);
|
|
17
|
+
const relative = (file) => path.relative(process.cwd(), file) || ".";
|
|
18
|
+
|
|
19
|
+
/** The manifest (and the rest of generateMcpServer's result) for a spec file or URL. */
|
|
20
|
+
async function generate(specTarget, values) {
|
|
21
|
+
const { bundleSpec } = await import("../validate/bundle.js");
|
|
22
|
+
const { generateMcpServer, parseArazzo } = await import("@rapidoc/mcp");
|
|
23
|
+
const location = isUrl(specTarget) ? specTarget : path.resolve(specTarget);
|
|
24
|
+
if (!isUrl(location) && !fs.existsSync(location))
|
|
25
|
+
throw new ProblemError(`File not found: ${location}`);
|
|
26
|
+
let spec;
|
|
27
|
+
try {
|
|
28
|
+
spec = (await bundleSpec(location, { remote: values.remote })).value;
|
|
29
|
+
} catch (err) {
|
|
30
|
+
throw new ProblemError(`Can't read ${specTarget}: ${err.message}`);
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
let arazzo;
|
|
34
|
+
if (values.arazzo) {
|
|
35
|
+
const file = path.resolve(values.arazzo);
|
|
36
|
+
if (!fs.existsSync(file)) throw new ProblemError(`--arazzo ${values.arazzo}: file not found`);
|
|
37
|
+
try {
|
|
38
|
+
arazzo = parseArazzo(fs.readFileSync(file, "utf8"));
|
|
39
|
+
} catch (err) {
|
|
40
|
+
throw new ProblemError(`--arazzo ${values.arazzo}: ${err.message}`);
|
|
41
|
+
}
|
|
42
|
+
}
|
|
43
|
+
try {
|
|
44
|
+
return generateMcpServer(spec, {
|
|
45
|
+
...(values["server-name"] && { serverName: values["server-name"] }),
|
|
46
|
+
...(arazzo && { arazzo }),
|
|
47
|
+
});
|
|
48
|
+
} catch (err) {
|
|
49
|
+
throw new ProblemError(`Can't build MCP tools from ${specTarget}: ${err.message}`);
|
|
50
|
+
}
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
async function exportProject(specTarget, values) {
|
|
54
|
+
const outDir = path.resolve(values["out-dir"]);
|
|
55
|
+
if (fs.existsSync(outDir) && fs.readdirSync(outDir).length) {
|
|
56
|
+
if (!values.force) {
|
|
57
|
+
if (!canAsk())
|
|
58
|
+
throw new ProblemError(
|
|
59
|
+
`${relative(outDir)} is not empty: pass --force to overwrite, or another --out-dir.`,
|
|
60
|
+
);
|
|
61
|
+
const ok = await confirm({
|
|
62
|
+
message: `${relative(outDir)} is not empty. Overwrite its files?`,
|
|
63
|
+
initialValue: false,
|
|
64
|
+
});
|
|
65
|
+
if (!ok) throw new CancelledError("Cancelled; nothing was written.");
|
|
66
|
+
}
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
const result = await generate(specTarget, values);
|
|
70
|
+
for (const [file, content] of Object.entries(result.files)) {
|
|
71
|
+
const target = path.join(outDir, file);
|
|
72
|
+
fs.mkdirSync(path.dirname(target), { recursive: true });
|
|
73
|
+
fs.writeFileSync(target, content, "utf8");
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
const { budget, manifest, problems } = result;
|
|
77
|
+
info(`\n${icon("🤖")}MCP server "${manifest.server.name}" written to ${relative(outDir)}`);
|
|
78
|
+
info(
|
|
79
|
+
` • Tools: ${budget.totalTools} (${budget.consequentialCount} not read-only), ${budget.totalResources} resource(s)`,
|
|
80
|
+
);
|
|
81
|
+
info(` • Context: ~${budget.estimatedTokens} tokens per turn for the tool list`);
|
|
82
|
+
info(` • Files: ${Object.keys(result.files).join(", ")}`);
|
|
83
|
+
for (const warning of budget.warnings) warn(warning, " ");
|
|
84
|
+
for (const problem of problems) warn(`workflow left out: ${problem.message}`, " ");
|
|
85
|
+
info(`\nNext steps:`);
|
|
86
|
+
info(` cd ${relative(outDir)}`);
|
|
87
|
+
info(` npm install`);
|
|
88
|
+
info(` npm start # or add claude_desktop_config.json's entry to your agent\n`);
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
async function serve(specTarget, values) {
|
|
92
|
+
// stdout carries the MCP protocol: nothing else may go there.
|
|
93
|
+
setQuiet(true);
|
|
94
|
+
const sdk = await loadMcpSdk();
|
|
95
|
+
const { createMcpRuntime, credentialsFromEnv } = await import("@rapidoc/mcp");
|
|
96
|
+
const { manifest, problems } = await generate(specTarget, values);
|
|
97
|
+
const baseUrls = values["base-url"]
|
|
98
|
+
? Object.fromEntries(Object.keys(manifest.sources).map((name) => [name, values["base-url"]]))
|
|
99
|
+
: undefined;
|
|
100
|
+
const runtime = createMcpRuntime(manifest, {
|
|
101
|
+
credentials: credentialsFromEnv(manifest, process.env),
|
|
102
|
+
...(baseUrls && { baseUrls }),
|
|
103
|
+
});
|
|
104
|
+
|
|
105
|
+
const server = new sdk.Server(
|
|
106
|
+
{ name: manifest.server.name, version: manifest.server.version || pkg.version },
|
|
107
|
+
{ capabilities: { tools: {}, resources: {} } },
|
|
108
|
+
);
|
|
109
|
+
server.setRequestHandler(sdk.ListToolsRequestSchema, async () => ({
|
|
110
|
+
tools: runtime.listTools(),
|
|
111
|
+
}));
|
|
112
|
+
server.setRequestHandler(sdk.CallToolRequestSchema, async (request) =>
|
|
113
|
+
runtime.callTool(request.params.name, request.params.arguments ?? {}),
|
|
114
|
+
);
|
|
115
|
+
server.setRequestHandler(sdk.ListResourcesRequestSchema, async () => ({
|
|
116
|
+
resources: runtime.listResources(),
|
|
117
|
+
}));
|
|
118
|
+
server.setRequestHandler(sdk.ReadResourceRequestSchema, async (request) =>
|
|
119
|
+
runtime.readResource(request.params.uri),
|
|
120
|
+
);
|
|
121
|
+
await server.connect(new sdk.StdioServerTransport());
|
|
122
|
+
|
|
123
|
+
const where = values["base-url"] ? ` against ${values["base-url"]}` : "";
|
|
124
|
+
process.stderr.write(
|
|
125
|
+
`rapidoc mcp serve: "${manifest.server.name}", ${manifest.tools.length} tool(s)${where}, over stdio\n`,
|
|
126
|
+
);
|
|
127
|
+
for (const problem of problems)
|
|
128
|
+
process.stderr.write(`rapidoc mcp serve: workflow left out: ${problem.message}\n`);
|
|
129
|
+
}
|
|
130
|
+
|
|
131
|
+
export default {
|
|
132
|
+
name: "mcp",
|
|
133
|
+
usage: "mcp <export|serve> <spec>",
|
|
134
|
+
summary: "Turns an OpenAPI spec into MCP tools: export a server project, or serve it over stdio",
|
|
135
|
+
description:
|
|
136
|
+
"export writes the MCP server project (the same files as <rapi-doc>'s Export MCP Server button).\nserve runs it over stdio for an AI agent, without files; it needs @modelcontextprotocol/sdk.\nCredentials come from the environment, one variable per security scheme (see the project's README).",
|
|
137
|
+
positionals: { name: "action", max: 2, choices: ["export", "serve"] },
|
|
138
|
+
options: {
|
|
139
|
+
"out-dir": {
|
|
140
|
+
type: "string",
|
|
141
|
+
value: "path",
|
|
142
|
+
default: "mcp-server",
|
|
143
|
+
description: "export: the folder to write the project to",
|
|
144
|
+
},
|
|
145
|
+
force: {
|
|
146
|
+
type: "boolean",
|
|
147
|
+
short: "f",
|
|
148
|
+
description: "export: overwrite files in a non-empty folder",
|
|
149
|
+
},
|
|
150
|
+
arazzo: {
|
|
151
|
+
type: "string",
|
|
152
|
+
value: "file",
|
|
153
|
+
description: "An Arazzo file whose workflows become tools too",
|
|
154
|
+
},
|
|
155
|
+
"server-name": {
|
|
156
|
+
type: "string",
|
|
157
|
+
value: "name",
|
|
158
|
+
description: "The MCP server's name (default: the API title)",
|
|
159
|
+
},
|
|
160
|
+
"base-url": {
|
|
161
|
+
type: "string",
|
|
162
|
+
value: "url",
|
|
163
|
+
description:
|
|
164
|
+
"serve: call the API here instead of the spec's server (for example rapidoc mock)",
|
|
165
|
+
},
|
|
166
|
+
remote: { type: "boolean", description: "Also fetch remote $refs" },
|
|
167
|
+
},
|
|
168
|
+
examples: [
|
|
169
|
+
"rapidoc mcp export openapi.yaml",
|
|
170
|
+
"rapidoc mcp export openapi.yaml --out-dir petstore-mcp --arazzo flows.arazzo.yaml",
|
|
171
|
+
"rapidoc mcp serve openapi.yaml",
|
|
172
|
+
"rapidoc mcp serve openapi.yaml --base-url http://localhost:4010/openapi",
|
|
173
|
+
],
|
|
174
|
+
|
|
175
|
+
async run({ values, positionals }) {
|
|
176
|
+
const [action, specTarget] = positionals;
|
|
177
|
+
if (!["export", "serve"].includes(action)) {
|
|
178
|
+
const what = action ? `Unknown action "${action}"` : "Missing action";
|
|
179
|
+
throw new UsageError(`${what}: rapidoc mcp export <spec> or rapidoc mcp serve <spec>`, {
|
|
180
|
+
command: "mcp",
|
|
181
|
+
});
|
|
182
|
+
}
|
|
183
|
+
if (!specTarget)
|
|
184
|
+
throw new UsageError(`rapidoc mcp ${action} needs a spec: rapidoc mcp ${action} <spec>`, {
|
|
185
|
+
command: "mcp",
|
|
186
|
+
});
|
|
187
|
+
if (action === "export") await exportProject(specTarget, values);
|
|
188
|
+
else await serve(specTarget, values);
|
|
189
|
+
},
|
|
190
|
+
};
|
|
@@ -0,0 +1,112 @@
|
|
|
1
|
+
import fs from "node:fs";
|
|
2
|
+
import path from "node:path";
|
|
3
|
+
import { loadPortal } from "../lib/engines.js";
|
|
4
|
+
import { CancelledError, ProblemError, UsageError } from "../lib/errors.js";
|
|
5
|
+
import { icon, info, success } from "../lib/output.js";
|
|
6
|
+
import { assumingYes, canAsk, confirm, select } from "../lib/prompt.js";
|
|
7
|
+
|
|
8
|
+
const LABELS = { redocly: "Redocly", zudoku: "Zudoku" };
|
|
9
|
+
|
|
10
|
+
/**
|
|
11
|
+
* The source to migrate from: --from, else the project found in the folder (MIGRATION_SOURCES lists
|
|
12
|
+
* each tool's config file names). In a terminal it asks to confirm (or to pick, when there are two);
|
|
13
|
+
* with --yes it takes the one found; otherwise it fails naming --from.
|
|
14
|
+
*/
|
|
15
|
+
async function chooseSource(targetDir, from, sources) {
|
|
16
|
+
if (from) return from;
|
|
17
|
+
const found = Object.entries(sources).flatMap(([source, files]) => {
|
|
18
|
+
const file = files.find((name) => fs.existsSync(path.join(targetDir, name)));
|
|
19
|
+
return file ? [{ source, file }] : [];
|
|
20
|
+
});
|
|
21
|
+
const fromOption = `--from ${Object.keys(sources).join("|")}`;
|
|
22
|
+
if (!found.length) {
|
|
23
|
+
throw new UsageError(
|
|
24
|
+
`No Redocly (redocly.yaml) or Zudoku (zudoku.config.*) project in ${targetDir}. Run it in the project's folder, or pass ${fromOption}.`,
|
|
25
|
+
{ command: "migrate" },
|
|
26
|
+
);
|
|
27
|
+
}
|
|
28
|
+
if (canAsk()) {
|
|
29
|
+
if (found.length === 1) {
|
|
30
|
+
const [{ source, file }] = found;
|
|
31
|
+
const ok = await confirm({
|
|
32
|
+
message: `Found ${file}. Migrate this ${LABELS[source] ?? source} project?`,
|
|
33
|
+
initialValue: true,
|
|
34
|
+
});
|
|
35
|
+
if (!ok) throw new CancelledError();
|
|
36
|
+
return source;
|
|
37
|
+
}
|
|
38
|
+
return select({
|
|
39
|
+
message: "Which project do you want to migrate?",
|
|
40
|
+
options: found.map(({ source, file }) => ({
|
|
41
|
+
value: source,
|
|
42
|
+
label: LABELS[source] ?? source,
|
|
43
|
+
hint: file,
|
|
44
|
+
})),
|
|
45
|
+
});
|
|
46
|
+
}
|
|
47
|
+
if (assumingYes() && found.length === 1) return found[0].source;
|
|
48
|
+
if (found.length === 1) {
|
|
49
|
+
const [{ source, file }] = found;
|
|
50
|
+
throw new UsageError(`Found ${file}: pass --from ${source} (or --yes) to migrate it.`, {
|
|
51
|
+
command: "migrate",
|
|
52
|
+
});
|
|
53
|
+
}
|
|
54
|
+
const list = found.map(({ file }) => file).join(" and ");
|
|
55
|
+
throw new UsageError(`Found ${list}: pass ${fromOption} to say which to migrate.`, {
|
|
56
|
+
command: "migrate",
|
|
57
|
+
});
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
export default {
|
|
61
|
+
name: "migrate",
|
|
62
|
+
usage: "migrate [--from <src>]",
|
|
63
|
+
summary: "Converts a Redocly or a Zudoku project to rapidoc.config.yaml (redocly, zudoku)",
|
|
64
|
+
description:
|
|
65
|
+
"Reads the project in the current folder and writes rapidoc.config.yaml next to it, listing what\nwasn't migrated and what to fix before building. Without --from it looks for redocly.yaml or\nzudoku.config.* and, in a terminal, asks to confirm. An existing rapidoc.config.yaml is replaced\n(after asking, in a terminal).",
|
|
66
|
+
positionals: { name: "", max: 0 },
|
|
67
|
+
options: {
|
|
68
|
+
from: {
|
|
69
|
+
type: "string",
|
|
70
|
+
value: "src",
|
|
71
|
+
choices: ["redocly", "zudoku"],
|
|
72
|
+
description: "The tool the project comes from (default: the one found in the folder)",
|
|
73
|
+
},
|
|
74
|
+
},
|
|
75
|
+
examples: [
|
|
76
|
+
"rapidoc migrate",
|
|
77
|
+
"rapidoc migrate --from redocly",
|
|
78
|
+
"rapidoc migrate --from zudoku --yes",
|
|
79
|
+
],
|
|
80
|
+
|
|
81
|
+
async run({ values }) {
|
|
82
|
+
const { migrateConfig, MIGRATION_SOURCES } = await loadPortal("migrate");
|
|
83
|
+
const targetDir = process.cwd();
|
|
84
|
+
const from = await chooseSource(targetDir, values.from, MIGRATION_SOURCES);
|
|
85
|
+
|
|
86
|
+
if (fs.existsSync(path.join(targetDir, "rapidoc.config.yaml")) && canAsk()) {
|
|
87
|
+
const ok = await confirm({
|
|
88
|
+
message: "rapidoc.config.yaml exists. Replace it?",
|
|
89
|
+
initialValue: false,
|
|
90
|
+
});
|
|
91
|
+
if (!ok) throw new CancelledError("Cancelled; rapidoc.config.yaml was left as it was.");
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
info(`\n${icon("🔄")}Migrating ${from} config in ${targetDir} to rapidoc.config.yaml...`);
|
|
95
|
+
let result;
|
|
96
|
+
try {
|
|
97
|
+
result = await migrateConfig(targetDir, { from, overwrite: true });
|
|
98
|
+
} catch (err) {
|
|
99
|
+
throw new ProblemError(`Migration failed: ${err.message}`);
|
|
100
|
+
}
|
|
101
|
+
success(`Successfully generated rapidoc.config.yaml at: ${result.filePath}`, "\n");
|
|
102
|
+
if (result.warnings.length) {
|
|
103
|
+
info(`\n${icon("⚠️ ")}Not migrated:\n${result.warnings.map((w) => ` - ${w}`).join("\n")}`);
|
|
104
|
+
}
|
|
105
|
+
if (result.problems.length) {
|
|
106
|
+
info(
|
|
107
|
+
`\n${icon("⚠️ ")}Fix these before building:\n${result.problems.map((p) => ` - ${p}`).join("\n")}`,
|
|
108
|
+
);
|
|
109
|
+
}
|
|
110
|
+
info("");
|
|
111
|
+
},
|
|
112
|
+
};
|
|
@@ -0,0 +1,200 @@
|
|
|
1
|
+
import fs from "node:fs";
|
|
2
|
+
import path from "node:path";
|
|
3
|
+
import { loadMock, loadPortal } from "../lib/engines.js";
|
|
4
|
+
import { ProblemError, UsageError } from "../lib/errors.js";
|
|
5
|
+
import { icon, info, warn } from "../lib/output.js";
|
|
6
|
+
import { startOnFreePort } from "../lib/ports.js";
|
|
7
|
+
|
|
8
|
+
// The portal's config file names (CONFIG_CANDIDATES in @rapidoc/portal), checked without loading the portal engine.
|
|
9
|
+
export const hasPortalConfig = (dir) =>
|
|
10
|
+
fs.readdirSync(dir).some((name) => /^rapidoc\.config\.(ya?ml|json|m?js|ts)$/.test(name));
|
|
11
|
+
|
|
12
|
+
const slug = (text) =>
|
|
13
|
+
text
|
|
14
|
+
.toLowerCase()
|
|
15
|
+
.replace(/[^a-z0-9]+/g, "-")
|
|
16
|
+
.replace(/^-|-$/g, "") || "api";
|
|
17
|
+
|
|
18
|
+
/**
|
|
19
|
+
* Mock ids for spec files: the file name without its extension (`specs/orders-api.yaml` → `orders-api`). Files that
|
|
20
|
+
* would share an id get their parent folders in front until they differ (`billing-v2/openapi.yaml` →
|
|
21
|
+
* `billing-v2-openapi`); the same input always gives the same ids.
|
|
22
|
+
*/
|
|
23
|
+
export function mockApisFromFiles(files) {
|
|
24
|
+
const fullPaths = [...new Set(files.map((file) => path.resolve(file)))];
|
|
25
|
+
const segments = fullPaths.map((fullPath) => {
|
|
26
|
+
const parts = fullPath.split(path.sep).filter(Boolean);
|
|
27
|
+
parts[parts.length - 1] = parts.at(-1).replace(/\.(ya?ml|json)$/i, "");
|
|
28
|
+
return parts;
|
|
29
|
+
});
|
|
30
|
+
const idOf = (parts, depth) => slug(parts.slice(-depth).join("-"));
|
|
31
|
+
const ids = segments.map((parts) => idOf(parts, 1));
|
|
32
|
+
const groups = new Map();
|
|
33
|
+
ids.forEach((id, i) => groups.set(id, [...(groups.get(id) || []), i]));
|
|
34
|
+
for (const indices of groups.values()) {
|
|
35
|
+
if (indices.length < 2) continue;
|
|
36
|
+
const longest = Math.max(...indices.map((i) => segments[i].length));
|
|
37
|
+
let depth = 2;
|
|
38
|
+
while (
|
|
39
|
+
depth < longest &&
|
|
40
|
+
new Set(indices.map((i) => idOf(segments[i], depth))).size < indices.length
|
|
41
|
+
)
|
|
42
|
+
depth++;
|
|
43
|
+
for (const i of indices) ids[i] = idOf(segments[i], depth);
|
|
44
|
+
}
|
|
45
|
+
const used = new Set();
|
|
46
|
+
return fullPaths.map((fullPath, i) => {
|
|
47
|
+
let id = ids[i];
|
|
48
|
+
for (let n = 2; used.has(id); n++) id = `${ids[i]}-${n}`;
|
|
49
|
+
used.add(id);
|
|
50
|
+
return { id, fullPath };
|
|
51
|
+
});
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
/** The local specs in a portal's apis:, every version: the default under /<id>, the others under /<id>/<version>. */
|
|
55
|
+
async function apisFromPortal(folder) {
|
|
56
|
+
const portal = await loadPortal("mock");
|
|
57
|
+
let config;
|
|
58
|
+
try {
|
|
59
|
+
({ config } = await portal.loadConfig(folder));
|
|
60
|
+
} catch (err) {
|
|
61
|
+
throw new ProblemError(err.message);
|
|
62
|
+
}
|
|
63
|
+
const apis = [];
|
|
64
|
+
for (const api of config.apis || []) {
|
|
65
|
+
// The other versions go first: the mock server tries the APIs in order, and /<id>/* would also take
|
|
66
|
+
// /<id>/<version>/... requests.
|
|
67
|
+
for (const version of [...api.versions.slice(1), api.versions[0]]) {
|
|
68
|
+
const id = version.isDefault ? api.id : `${api.id}/${version.version}`;
|
|
69
|
+
if (version.isRemote) info(`${icon("⏭️ ")}${id}: ${version.spec} (remote, not mocked)`);
|
|
70
|
+
else apis.push({ id, title: api.title, fullPath: version.fullPath });
|
|
71
|
+
}
|
|
72
|
+
}
|
|
73
|
+
if (!apis.length) throw new ProblemError(`${folder} has no local specs under apis: to mock.`);
|
|
74
|
+
return apis;
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
export default {
|
|
78
|
+
name: "mock",
|
|
79
|
+
usage: "mock [dir|spec...]",
|
|
80
|
+
summary: "Mock server for a portal's APIs, a folder of specs or spec files, each under /<api id>",
|
|
81
|
+
description:
|
|
82
|
+
"A portal folder mocks the local specs in its apis:. A folder without rapidoc.config.yaml is mocked\nfile by file (orders-api.yaml under /orders-api), as are spec files given by name.",
|
|
83
|
+
positionals: { name: "dir|spec", max: Infinity },
|
|
84
|
+
options: {
|
|
85
|
+
port: {
|
|
86
|
+
type: "string",
|
|
87
|
+
kind: "port",
|
|
88
|
+
value: "number",
|
|
89
|
+
description: "Port to listen on (default 4010)",
|
|
90
|
+
},
|
|
91
|
+
host: { type: "string", value: "host", description: "Address to listen on (default 0.0.0.0)" },
|
|
92
|
+
issuer: {
|
|
93
|
+
type: "string",
|
|
94
|
+
value: "url",
|
|
95
|
+
description: "OpenID Connect issuer whose tokens are accepted (default $RAPIDOC_MOCK_ISSUER)",
|
|
96
|
+
},
|
|
97
|
+
audience: {
|
|
98
|
+
type: "string",
|
|
99
|
+
value: "id",
|
|
100
|
+
description: "Audience tokens must be issued for (default $RAPIDOC_MOCK_AUDIENCE)",
|
|
101
|
+
},
|
|
102
|
+
seed: {
|
|
103
|
+
type: "string",
|
|
104
|
+
kind: "int",
|
|
105
|
+
value: "number",
|
|
106
|
+
description: "Seed for generated data (default 1)",
|
|
107
|
+
},
|
|
108
|
+
},
|
|
109
|
+
examples: [
|
|
110
|
+
"rapidoc mock",
|
|
111
|
+
"rapidoc mock ./specs --port 4011",
|
|
112
|
+
"rapidoc mock orders-api.yaml billing-api.yaml",
|
|
113
|
+
"rapidoc mock --issuer https://example.us.auth0.com/ --audience https://api.example.com",
|
|
114
|
+
],
|
|
115
|
+
|
|
116
|
+
async run({ values, positionals }) {
|
|
117
|
+
const targets = positionals.map((target) => path.resolve(target));
|
|
118
|
+
if (!targets.length) targets.push(process.cwd());
|
|
119
|
+
for (const target of targets) {
|
|
120
|
+
if (!fs.existsSync(target)) throw new ProblemError(`Not found: ${target}`);
|
|
121
|
+
}
|
|
122
|
+
|
|
123
|
+
let apis;
|
|
124
|
+
const folder =
|
|
125
|
+
targets.length === 1 && fs.statSync(targets[0]).isDirectory() ? targets[0] : null;
|
|
126
|
+
if (folder && hasPortalConfig(folder)) {
|
|
127
|
+
apis = await apisFromPortal(folder);
|
|
128
|
+
} else if (folder) {
|
|
129
|
+
const { findOpenApiSpecs } = await import("create-rapidoc/scaffold");
|
|
130
|
+
const files = findOpenApiSpecs(folder).map((file) => path.join(folder, file));
|
|
131
|
+
if (!files.length)
|
|
132
|
+
throw new ProblemError(
|
|
133
|
+
`${folder} has no rapidoc.config.yaml and no OpenAPI files to mock.`,
|
|
134
|
+
);
|
|
135
|
+
info(
|
|
136
|
+
`\n${icon("📂")}No rapidoc.config.yaml in ${folder}: mocking the ${files.length} OpenAPI file(s) found there.`,
|
|
137
|
+
);
|
|
138
|
+
apis = mockApisFromFiles(files);
|
|
139
|
+
} else {
|
|
140
|
+
const dirs = targets.filter((target) => fs.statSync(target).isDirectory());
|
|
141
|
+
if (dirs.length) {
|
|
142
|
+
throw new UsageError(
|
|
143
|
+
`Pass one folder, or one or more spec files (not both): ${dirs.join(", ")}`,
|
|
144
|
+
{ command: "mock" },
|
|
145
|
+
);
|
|
146
|
+
}
|
|
147
|
+
apis = mockApisFromFiles(targets);
|
|
148
|
+
}
|
|
149
|
+
|
|
150
|
+
const issuer = values.issuer || process.env.RAPIDOC_MOCK_ISSUER || undefined;
|
|
151
|
+
const audience = values.audience || process.env.RAPIDOC_MOCK_AUDIENCE || undefined;
|
|
152
|
+
const { startMockServer, DEFAULT_PORT } = await loadMock();
|
|
153
|
+
let server;
|
|
154
|
+
try {
|
|
155
|
+
server = await startOnFreePort(
|
|
156
|
+
(port) =>
|
|
157
|
+
startMockServer({ apis, port, host: values.host, issuer, audience, seed: values.seed }),
|
|
158
|
+
values.port ?? DEFAULT_PORT ?? 4010,
|
|
159
|
+
{ host: values.host ?? "0.0.0.0" }, // the mock server's default host
|
|
160
|
+
);
|
|
161
|
+
} catch (err) {
|
|
162
|
+
if (err.exitCode) throw err; // a busy port without --port, or a cancelled question
|
|
163
|
+
throw new ProblemError(`Mock server failed: ${err.message}`);
|
|
164
|
+
}
|
|
165
|
+
|
|
166
|
+
info(`\n${icon("🧪")}Mock server: ${server.url}`);
|
|
167
|
+
const fileOf = new Map(apis.map((api) => [api.id, path.relative(process.cwd(), api.fullPath)]));
|
|
168
|
+
for (const api of server.apis) {
|
|
169
|
+
info(
|
|
170
|
+
` • ${server.url}/${api.id} ${api.title ? `${api.title}, ` : ""}${api.operations} operation(s) (${fileOf.get(api.id)})`,
|
|
171
|
+
);
|
|
172
|
+
}
|
|
173
|
+
for (const api of server.skipped)
|
|
174
|
+
warn(`${api.id}: not served (${api.error.split("\n")[0]})`, " ");
|
|
175
|
+
if (issuer) {
|
|
176
|
+
info(
|
|
177
|
+
` • Tokens: verified against ${issuer}${audience ? ` for ${audience}` : ""}; scopes from scope, scp or permissions`,
|
|
178
|
+
);
|
|
179
|
+
if (!audience)
|
|
180
|
+
warn(
|
|
181
|
+
"No audience set (--audience or RAPIDOC_MOCK_AUDIENCE): tokens for any API are accepted.",
|
|
182
|
+
" ",
|
|
183
|
+
);
|
|
184
|
+
} else {
|
|
185
|
+
info(
|
|
186
|
+
" • Tokens: not verified, any bearer token passes (set --issuer or RAPIDOC_MOCK_ISSUER to check them)",
|
|
187
|
+
);
|
|
188
|
+
}
|
|
189
|
+
info(
|
|
190
|
+
" • Try: Prefer: code=404 picks a documented response; Prefer: example=<name> an example\n",
|
|
191
|
+
);
|
|
192
|
+
|
|
193
|
+
const stop = async () => {
|
|
194
|
+
await server.close();
|
|
195
|
+
process.exit(0);
|
|
196
|
+
};
|
|
197
|
+
process.once("SIGINT", stop);
|
|
198
|
+
process.once("SIGTERM", stop);
|
|
199
|
+
},
|
|
200
|
+
};
|