@rapidoc/cli 0.2.0 → 0.2.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/README.md CHANGED
@@ -31,6 +31,7 @@ Node.js 22.12 or later.
31
31
  | `rapidoc validate [spec\|dir]` | Validates one OpenAPI 2.0 / 3.x spec, or every spec in the portal |
32
32
  | `rapidoc lint [spec\|dir]` | Checks what a spec needs for a good portal: operationIds, summaries, examples |
33
33
  | `rapidoc bundle <spec>` | Joins a spec split over several files into one |
34
+ | `rapidoc pdf <spec>` | Writes the API reference of a spec as a PDF (needs `rapipdf`) |
34
35
  | `rapidoc mcp <export\|serve> <spec>` | Turns a spec into MCP tools: export a server project, or serve over stdio |
35
36
  | `rapidoc migrate` | Converts a Redocly or Zudoku project to `rapidoc.config.yaml` |
36
37
  | `rapidoc doctor [dir]` | Checks Node, package versions, the portal config and the browser bundle |
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@rapidoc/cli",
3
- "version": "0.2.0",
3
+ "version": "0.2.2",
4
4
  "description": "The rapidoc command: developer portal dev/build/serve/init, OpenAPI validation and config migration",
5
5
  "homepage": "https://portal.rapidocui.com",
6
6
  "bugs": {
@@ -29,17 +29,18 @@
29
29
  },
30
30
  "dependencies": {
31
31
  "@clack/prompts": "^1.8.1",
32
- "@rapidoc/mcp": "^0.2.0",
32
+ "@rapidoc/mcp": "^0.2.2",
33
33
  "@scalar/openapi-validator": "^0.1.18",
34
- "create-rapidoc": "^0.2.0",
35
- "rapidoc": "^13.0.0",
34
+ "create-rapidoc": "^0.2.2",
35
+ "rapidoc": "^14.0.0",
36
36
  "yaml": "^2.9.1"
37
37
  },
38
38
  "peerDependencies": {
39
39
  "@modelcontextprotocol/sdk": "^1.32.2",
40
- "@rapidoc/mock": "^0.2.0",
41
- "@rapidoc/portal": "^0.2.0",
42
- "@rapidoc/server": "^0.2.0"
40
+ "@rapidoc/mock": "^0.2.2",
41
+ "@rapidoc/portal": "^0.2.2",
42
+ "@rapidoc/server": "^0.2.2",
43
+ "rapipdf": "^3.0.0"
43
44
  },
44
45
  "peerDependenciesMeta": {
45
46
  "@modelcontextprotocol/sdk": {
@@ -53,6 +54,9 @@
53
54
  },
54
55
  "@rapidoc/server": {
55
56
  "optional": true
57
+ },
58
+ "rapipdf": {
59
+ "optional": true
56
60
  }
57
61
  },
58
62
  "engines": {
@@ -9,7 +9,7 @@ import { canAsk, confirm } from "../lib/prompt.js";
9
9
  /*
10
10
  * rapidoc mcp export <spec>: writes the MCP server project for a spec (the same files as <rapi-doc>'s
11
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
12
+ * mcp.json). rapidoc mcp serve <spec>: runs that server over stdio right away, for an
13
13
  * AI agent's config, without writing files. Both use @rapidoc/mcp; serve also needs the MCP SDK.
14
14
  */
15
15
 
@@ -17,7 +17,7 @@ const isUrl = (target) => /^https?:\/\//i.test(target);
17
17
  const relative = (file) => path.relative(process.cwd(), file) || ".";
18
18
 
19
19
  /** The manifest (and the rest of generateMcpServer's result) for a spec file or URL. */
20
- async function generate(specTarget, values) {
20
+ async function generate(specTarget, values, extra = {}) {
21
21
  const { bundleSpec } = await import("../validate/bundle.js");
22
22
  const { generateMcpServer, parseArazzo } = await import("@rapidoc/mcp");
23
23
  const location = isUrl(specTarget) ? specTarget : path.resolve(specTarget);
@@ -44,6 +44,7 @@ async function generate(specTarget, values) {
44
44
  return generateMcpServer(spec, {
45
45
  ...(values["server-name"] && { serverName: values["server-name"] }),
46
46
  ...(arazzo && { arazzo }),
47
+ ...extra,
47
48
  });
48
49
  } catch (err) {
49
50
  throw new ProblemError(`Can't build MCP tools from ${specTarget}: ${err.message}`);
@@ -66,7 +67,9 @@ async function exportProject(specTarget, values) {
66
67
  }
67
68
  }
68
69
 
69
- const result = await generate(specTarget, values);
70
+ const result = await generate(specTarget, values, {
71
+ serverPath: path.join(outDir, "server.ts"),
72
+ });
70
73
  for (const [file, content] of Object.entries(result.files)) {
71
74
  const target = path.join(outDir, file);
72
75
  fs.mkdirSync(path.dirname(target), { recursive: true });
@@ -85,20 +88,22 @@ async function exportProject(specTarget, values) {
85
88
  info(`\nNext steps:`);
86
89
  info(` cd ${relative(outDir)}`);
87
90
  info(` npm install`);
88
- info(` npm start # or add claude_desktop_config.json's entry to your agent\n`);
91
+ info(` npm start # or add mcp.json's entry to your AI app\n`);
89
92
  }
90
93
 
91
94
  async function serve(specTarget, values) {
92
95
  // stdout carries the MCP protocol: nothing else may go there.
93
96
  setQuiet(true);
94
97
  const sdk = await loadMcpSdk();
95
- const { createMcpRuntime, credentialsFromEnv } = await import("@rapidoc/mcp");
98
+ const { createMcpRuntime, credentialsFromEnv, externalHostsFromEnv } =
99
+ await import("@rapidoc/mcp");
96
100
  const { manifest, problems } = await generate(specTarget, values);
97
101
  const baseUrls = values["base-url"]
98
102
  ? Object.fromEntries(Object.keys(manifest.sources).map((name) => [name, values["base-url"]]))
99
103
  : undefined;
100
104
  const runtime = createMcpRuntime(manifest, {
101
105
  credentials: credentialsFromEnv(manifest, process.env),
106
+ externalHosts: externalHostsFromEnv(process.env),
102
107
  ...(baseUrls && { baseUrls }),
103
108
  });
104
109
 
@@ -133,7 +138,7 @@ export default {
133
138
  usage: "mcp <export|serve> <spec>",
134
139
  summary: "Turns an OpenAPI spec into MCP tools: export a server project, or serve it over stdio",
135
140
  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).",
141
+ "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).\nEXTERNAL_HOSTS (comma-separated, * for any) lists the hosts a workflow's x-operation URL computed at run time may go to, besides those the workflow names.",
137
142
  positionals: { name: "action", max: 2, choices: ["export", "serve"] },
138
143
  options: {
139
144
  "out-dir": {
@@ -0,0 +1,221 @@
1
+ import fs from "node:fs";
2
+ import path from "node:path";
3
+ import { loadPdf, loadPortal } from "../lib/engines.js";
4
+ import { ProblemError, UsageError } from "../lib/errors.js";
5
+ import { icon, info, success } from "../lib/output.js";
6
+
7
+ /*
8
+ * rapidoc pdf <spec>: the API reference of a spec as a PDF, the document <rapi-pdf> makes in the
9
+ * browser: a cover page, a table of contents, the security schemes and every operation with its
10
+ * parameters, request bodies and responses. rapipdf (an optional peer) does the work.
11
+ */
12
+
13
+ const isUrl = (target) => /^https?:\/\//i.test(target);
14
+ /** A URL as is; a path relative to the current folder, or absolute when it's outside it. */
15
+ function displayPath(location) {
16
+ if (isUrl(location)) return location;
17
+ const relative = path.relative(process.cwd(), location);
18
+ return relative.startsWith("..") ? location : relative || ".";
19
+ }
20
+
21
+ /** The spec of the API `id` in the portal config of the current folder. */
22
+ async function specOfApi(id) {
23
+ const portal = await loadPortal("pdf --api");
24
+ let config;
25
+ try {
26
+ ({ config } = await portal.loadConfig(process.cwd()));
27
+ } catch (err) {
28
+ throw new ProblemError(err.message);
29
+ }
30
+ const api = (config.apis ?? []).find((entry) => entry.id === id);
31
+ if (!api) {
32
+ const ids = (config.apis ?? []).map((entry) => entry.id).join(", ") || "none";
33
+ throw new ProblemError(`No API "${id}" in rapidoc.config.* (APIs: ${ids})`);
34
+ }
35
+ const [version] = api.versions;
36
+ return version.isRemote ? version.spec : version.fullPath;
37
+ }
38
+
39
+ /** `openapi.yaml` → `openapi.pdf` in the current folder; a URL's last path segment likewise. */
40
+ function defaultOutput(entry) {
41
+ const name = isUrl(entry) ? new URL(entry).pathname.split("/").filter(Boolean).pop() : entry;
42
+ const base = path.basename(name ?? "", path.extname(name ?? "")) || "api";
43
+ return `${base}.pdf`;
44
+ }
45
+
46
+ /** The labels file: a JSON object of label name to text. */
47
+ function readLabels(file) {
48
+ const location = path.resolve(file);
49
+ if (!fs.existsSync(location)) throw new ProblemError(`File not found: ${location}`);
50
+ let labels;
51
+ try {
52
+ labels = JSON.parse(fs.readFileSync(location, "utf8"));
53
+ } catch (err) {
54
+ throw new ProblemError(`${displayPath(location)} is not valid JSON: ${err.message}`);
55
+ }
56
+ if (labels === null || typeof labels !== "object" || Array.isArray(labels))
57
+ throw new ProblemError(`${displayPath(location)} must be a JSON object of label to text`);
58
+ return labels;
59
+ }
60
+
61
+ export default {
62
+ name: "pdf",
63
+ usage: "pdf <spec>",
64
+ summary: "Writes the API reference of a spec as a PDF",
65
+ description:
66
+ "Loads the spec (OpenAPI 3.x or Swagger 2.0, a file or a URL, with the files its $refs reach) and\nwrites a PDF: a cover page, a table of contents, the security schemes and every operation with its\nparameters, request bodies and responses. The same document <rapi-pdf> makes in the browser.",
67
+ positionals: { name: "spec", max: 1 },
68
+ options: {
69
+ output: {
70
+ type: "string",
71
+ short: "o",
72
+ value: "file",
73
+ description: "Write here (default: the spec's name with .pdf, in the current folder)",
74
+ },
75
+ api: {
76
+ type: "string",
77
+ value: "id",
78
+ description: "Use the spec of this API from rapidoc.config.* instead of a file",
79
+ },
80
+ title: {
81
+ type: "string",
82
+ value: "text",
83
+ description: 'Title on the cover page (default: "API Reference")',
84
+ },
85
+ footer: {
86
+ type: "string",
87
+ value: "text",
88
+ description: "Text at the bottom left of every page",
89
+ },
90
+ "schema-style": {
91
+ type: "string",
92
+ value: "style",
93
+ choices: ["object", "table"],
94
+ description: "Schemas as an indented object tree or as a table (default: object)",
95
+ },
96
+ examples: {
97
+ type: "boolean",
98
+ description: "Include request and response examples",
99
+ },
100
+ "api-list": {
101
+ type: "boolean",
102
+ description: "Add a closing list of every operation, by tag",
103
+ },
104
+ info: {
105
+ type: "boolean",
106
+ negatable: true,
107
+ default: true,
108
+ description: "Leave out the cover page",
109
+ },
110
+ toc: {
111
+ type: "boolean",
112
+ negatable: true,
113
+ default: true,
114
+ description: "Leave out the table of contents",
115
+ },
116
+ security: {
117
+ type: "boolean",
118
+ negatable: true,
119
+ default: true,
120
+ description: "Leave out the security schemes",
121
+ },
122
+ "api-details": {
123
+ type: "boolean",
124
+ negatable: true,
125
+ default: true,
126
+ description: "Leave out the operations",
127
+ },
128
+ "sort-tags": {
129
+ type: "boolean",
130
+ negatable: true,
131
+ default: true,
132
+ description: "Keep the tags in the spec's order instead of sorting them by name",
133
+ },
134
+ "primary-color": {
135
+ type: "string",
136
+ value: "color",
137
+ description: "Color of headings and operation titles (default: #b44646)",
138
+ },
139
+ "alternate-color": {
140
+ type: "string",
141
+ value: "color",
142
+ description: "Color of section labels and table headers (default: #005b96)",
143
+ },
144
+ labels: {
145
+ type: "string",
146
+ value: "file",
147
+ description: "A JSON file of labels to replace, for a PDF in another language",
148
+ },
149
+ font: {
150
+ type: "string",
151
+ value: "file",
152
+ description: "A .ttf or .otf font in place of Roboto (for Chinese, Japanese, Korean, ...)",
153
+ },
154
+ "mono-font": {
155
+ type: "string",
156
+ value: "file",
157
+ description: "A .ttf or .otf font in place of Roboto Mono",
158
+ },
159
+ },
160
+ examples: [
161
+ "rapidoc pdf openapi.yaml",
162
+ "rapidoc pdf openapi.yaml -o dist/reference.pdf --title 'Orders API' --examples",
163
+ "rapidoc pdf https://example.com/openapi.json --schema-style table",
164
+ "rapidoc pdf --api orders -o orders.pdf",
165
+ ],
166
+
167
+ async run({ values, positionals }) {
168
+ const [target] = positionals;
169
+ if (target && values.api)
170
+ throw new UsageError("Give a spec or --api <id>, not both", { command: "pdf" });
171
+ if (!target && !values.api)
172
+ throw new UsageError("rapidoc pdf needs a spec: rapidoc pdf <spec>", { command: "pdf" });
173
+
174
+ let entry = values.api ? await specOfApi(values.api) : target;
175
+ if (!isUrl(entry)) {
176
+ entry = path.resolve(entry);
177
+ if (!fs.existsSync(entry) || !fs.statSync(entry).isFile())
178
+ throw new ProblemError(`File not found: ${entry}`);
179
+ }
180
+ for (const font of [values.font, values["mono-font"]]) {
181
+ if (font && !fs.existsSync(path.resolve(font)))
182
+ throw new ProblemError(`Font file not found: ${path.resolve(font)}`);
183
+ }
184
+ const localize = values.labels ? readLabels(values.labels) : undefined;
185
+
186
+ const { generatePdf } = await loadPdf();
187
+ const options = {
188
+ includeInfo: values.info,
189
+ includeToc: values.toc,
190
+ includeSecurity: values.security,
191
+ includeApiDetails: values["api-details"],
192
+ includeApiList: Boolean(values["api-list"]),
193
+ includeExample: Boolean(values.examples),
194
+ pdfSortTags: values["sort-tags"],
195
+ ...(values.title !== undefined ? { pdfTitle: values.title } : {}),
196
+ ...(values.footer !== undefined ? { pdfFooterText: values.footer } : {}),
197
+ ...(values["schema-style"] ? { pdfSchemaStyle: values["schema-style"] } : {}),
198
+ ...(values["primary-color"] ? { pdfPrimaryColor: values["primary-color"] } : {}),
199
+ ...(values["alternate-color"] ? { pdfAlternateColor: values["alternate-color"] } : {}),
200
+ ...(localize ? { localize } : {}),
201
+ ...(values.font ? { font: values.font } : {}),
202
+ ...(values["mono-font"] ? { monoFont: values["mono-font"] } : {}),
203
+ };
204
+
205
+ let pdf;
206
+ try {
207
+ pdf = await generatePdf(entry, options);
208
+ } catch (err) {
209
+ throw new ProblemError(`${displayPath(entry)}: ${err.message}`);
210
+ }
211
+
212
+ const output = path.resolve(values.output ?? defaultOutput(entry));
213
+ fs.mkdirSync(path.dirname(output), { recursive: true });
214
+ fs.writeFileSync(output, pdf);
215
+
216
+ const pages = (pdf.toString("latin1").match(/\/Type \/Page\b/g) ?? []).length;
217
+ const size = (pdf.length / 1024).toFixed(1);
218
+ info(`\n${icon("📄")}${displayPath(entry)} → ${displayPath(output)}`);
219
+ success(`${pages} page(s), ${size} KB.\n`, " ");
220
+ },
221
+ };
package/src/index.js CHANGED
@@ -20,6 +20,7 @@ import serve from "./commands/serve.js";
20
20
  import mock from "./commands/mock.js";
21
21
  import validate from "./commands/validate.js";
22
22
  import bundle from "./commands/bundle.js";
23
+ import pdf from "./commands/pdf.js";
23
24
  import lint from "./commands/lint.js";
24
25
  import migrate from "./commands/migrate.js";
25
26
  import preview from "./commands/preview.js";
@@ -37,6 +38,7 @@ const COMMANDS = [
37
38
  validate,
38
39
  lint,
39
40
  bundle,
41
+ pdf,
40
42
  mcp,
41
43
  migrate,
42
44
  doctor,
@@ -3,7 +3,7 @@ import { ProblemError } from "./errors.js";
3
3
  /*
4
4
  * The engines behind the commands are optional peers, imported only by the commands that need them:
5
5
  * @rapidoc/portal (dev, build, migrate, folder-wide validate, mock of a portal folder), @rapidoc/server
6
- * (serve) and @rapidoc/mock (mock). Never import them at the top of a module.
6
+ * (serve), @rapidoc/mock (mock) and rapipdf (pdf). Never import them at the top of a module.
7
7
  * RAPIDOC_PORTAL_MODULE, RAPIDOC_SERVER_MODULE and RAPIDOC_MOCK_MODULE swap the module names (tests use
8
8
  * them to simulate a missing engine).
9
9
  */
@@ -55,6 +55,29 @@ export async function loadMock() {
55
55
  return mock;
56
56
  }
57
57
 
58
+ // RapiPdf's Node entry, for `rapidoc pdf` only. RAPIDOC_PDF_MODULE swaps the module name (tests use
59
+ // it to simulate a missing package).
60
+ const PDF_MODULE = process.env.RAPIDOC_PDF_MODULE || "rapipdf";
61
+
62
+ export async function loadPdf() {
63
+ let pdf;
64
+ try {
65
+ pdf = await tryImport(`${PDF_MODULE}/node`, PDF_MODULE);
66
+ } catch (err) {
67
+ // rapipdf 2.x is the browser element only: it has no ./node entry
68
+ if (err.code !== "ERR_PACKAGE_PATH_NOT_EXPORTED") throw err;
69
+ throw new ProblemError(
70
+ "`rapidoc pdf` needs rapipdf 3 or later. Update it next to the CLI:\n npm install -D rapipdf@latest",
71
+ );
72
+ }
73
+ if (!pdf) {
74
+ throw new ProblemError(
75
+ "`rapidoc pdf` needs rapipdf. Install it next to the CLI:\n npm install -D rapipdf",
76
+ );
77
+ }
78
+ return pdf;
79
+ }
80
+
58
81
  // The MCP SDK, for `rapidoc mcp serve` only (export writes a project that installs it itself).
59
82
  // RAPIDOC_MCP_SDK_MODULE swaps the module name (tests use it to simulate a missing SDK).
60
83
  const MCP_SDK_MODULE = process.env.RAPIDOC_MCP_SDK_MODULE || "@modelcontextprotocol/sdk";