@rapidoc/cli 0.0.0-stage → 0.1.0

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.
Files changed (56) hide show
  1. package/LICENSE.txt +22 -0
  2. package/README.md +57 -2
  3. package/package.json +59 -4
  4. package/src/bundle/components.js +187 -0
  5. package/src/bundle/dereference.js +67 -0
  6. package/src/bundle/write.js +20 -0
  7. package/src/commands/build.js +59 -0
  8. package/src/commands/bundle.js +187 -0
  9. package/src/commands/completion.js +37 -0
  10. package/src/commands/dev.js +51 -0
  11. package/src/commands/doctor.js +214 -0
  12. package/src/commands/init.js +163 -0
  13. package/src/commands/lint.js +160 -0
  14. package/src/commands/mcp.js +190 -0
  15. package/src/commands/migrate.js +112 -0
  16. package/src/commands/mock.js +200 -0
  17. package/src/commands/preview.js +218 -0
  18. package/src/commands/serve.js +95 -0
  19. package/src/commands/validate.js +139 -0
  20. package/src/index.js +126 -0
  21. package/src/lib/args.js +156 -0
  22. package/src/lib/completion.js +222 -0
  23. package/src/lib/engines.js +74 -0
  24. package/src/lib/errors.js +32 -0
  25. package/src/lib/help.js +75 -0
  26. package/src/lib/open.js +23 -0
  27. package/src/lib/openapi-shape.js +110 -0
  28. package/src/lib/output.js +38 -0
  29. package/src/lib/ports.js +65 -0
  30. package/src/lib/prompt.js +73 -0
  31. package/src/lib/suggest.js +36 -0
  32. package/src/lint/config.js +112 -0
  33. package/src/lint/rules/index.js +40 -0
  34. package/src/lint/rules/info-contact.js +12 -0
  35. package/src/lint/rules/info-license.js +11 -0
  36. package/src/lint/rules/media-example.js +35 -0
  37. package/src/lint/rules/no-server-example-com.js +30 -0
  38. package/src/lint/rules/no-unused-components.js +41 -0
  39. package/src/lint/rules/operation-2xx-response.js +17 -0
  40. package/src/lint/rules/operation-4xx-response.js +17 -0
  41. package/src/lint/rules/operation-description.js +12 -0
  42. package/src/lint/rules/operation-operationId-unique.js +24 -0
  43. package/src/lint/rules/operation-operationId-url-safe.js +18 -0
  44. package/src/lint/rules/operation-operationId.js +12 -0
  45. package/src/lint/rules/operation-summary.js +12 -0
  46. package/src/lint/rules/operation-tag-defined.js +22 -0
  47. package/src/lint/rules/path-kebab-case.js +16 -0
  48. package/src/lint/rules/security-defined.js +23 -0
  49. package/src/lint/rules/security-scheme-defined.js +28 -0
  50. package/src/lint/rules/tag-description.js +11 -0
  51. package/src/lint/run.js +50 -0
  52. package/src/lint/traverse.js +114 -0
  53. package/src/lint/types.js +46 -0
  54. package/src/validate/bundle.js +238 -0
  55. package/src/validate/check.js +122 -0
  56. package/src/validate/report.js +140 -0
@@ -0,0 +1,218 @@
1
+ import fs from "node:fs";
2
+ import http from "node:http";
3
+ import path from "node:path";
4
+ import { fileURLToPath } from "node:url";
5
+ import { ProblemError, UsageError } from "../lib/errors.js";
6
+ import { openBrowser } from "../lib/open.js";
7
+ import { icon, info } from "../lib/output.js";
8
+ import { startOnFreePort } from "../lib/ports.js";
9
+
10
+ /*
11
+ * rapidoc preview <spec>: one spec in <rapi-doc>, no portal and no config. A small HTTP server sends
12
+ * / the page: a full-screen <rapi-doc> and a script that reloads the spec on change
13
+ * /rapidoc-min.js the browser bundle of the `rapidoc` package (and its .LICENSE.txt)
14
+ * /spec/<path> files of the spec's folder (so relative $refs resolve), never cached
15
+ * /events server-sent events: "reload" when a file in that folder changes
16
+ * A spec given as a URL is loaded from there, without reloading.
17
+ */
18
+
19
+ const TYPES = {
20
+ ".yaml": "application/yaml",
21
+ ".yml": "application/yaml",
22
+ ".json": "application/json",
23
+ ".js": "text/javascript",
24
+ ".txt": "text/plain",
25
+ };
26
+ const isUrl = (target) => /^https?:\/\//i.test(target);
27
+ const escapeHtml = (text) => String(text).replace(/[&<>"']/g, (c) => `&#${c.charCodeAt(0)};`);
28
+ const encodePath = (relative) => relative.split(path.sep).map(encodeURIComponent).join("/");
29
+
30
+ /** The `rapidoc` package's dist/rapidoc-min.js. */
31
+ function rapidocBundle() {
32
+ let bundle;
33
+ try {
34
+ bundle = fileURLToPath(import.meta.resolve("rapidoc"));
35
+ } catch {
36
+ throw new ProblemError(
37
+ "`rapidoc preview` needs the rapidoc package:\n npm install -D rapidoc",
38
+ );
39
+ }
40
+ if (!fs.existsSync(bundle))
41
+ throw new ProblemError(`${bundle} is missing; build it with \`npm run build:rapidoc\`.`);
42
+ return bundle;
43
+ }
44
+
45
+ function page({ title, specUrl, theme, live }) {
46
+ return `<!doctype html>
47
+ <html lang="en">
48
+ <head>
49
+ <meta charset="utf-8">
50
+ <meta name="viewport" content="width=device-width, initial-scale=1">
51
+ <title>${escapeHtml(title)} · RapiDoc preview</title>
52
+ <style>html, body { margin: 0; height: 100%; } rapi-doc { width: 100%; height: 100%; }</style>
53
+ <script type="module" src="/rapidoc-min.js"></script>
54
+ </head>
55
+ <body>
56
+ <rapi-doc spec-url="${escapeHtml(specUrl)}" show-header="false" color-scheme="auto"${theme ? ` theme="${escapeHtml(theme)}"` : ""}></rapi-doc>
57
+ ${
58
+ live
59
+ ? `<script>
60
+ // Reload the spec when a file changes (rapidoc preview watches the spec's folder).
61
+ const doc = document.querySelector("rapi-doc");
62
+ const specUrl = ${JSON.stringify(specUrl)};
63
+ new EventSource("/events").onmessage = () =>
64
+ doc.setAttribute("spec-url", specUrl + "?v=" + Date.now());
65
+ </script>`
66
+ : ""
67
+ }
68
+ </body>
69
+ </html>
70
+ `;
71
+ }
72
+
73
+ export default {
74
+ name: "preview",
75
+ usage: "preview <spec>",
76
+ summary: "Shows one OpenAPI spec in <rapi-doc>, reloading on save (no portal needed)",
77
+ description:
78
+ "Serves the spec (a file or URL) in a page with <rapi-doc>, on localhost. Relative $refs to other\nfiles in the spec's folder work; when any file there changes, the page reloads the spec.",
79
+ positionals: { name: "spec", max: 1 },
80
+ options: {
81
+ port: {
82
+ type: "string",
83
+ kind: "port",
84
+ value: "number",
85
+ default: 4000,
86
+ description: "Port to listen on",
87
+ },
88
+ host: {
89
+ type: "string",
90
+ value: "host",
91
+ default: "localhost",
92
+ description: "Address to listen on (0.0.0.0 shares the spec's folder with your network)",
93
+ },
94
+ open: { type: "boolean", description: "Open the preview in the browser" },
95
+ theme: {
96
+ type: "string",
97
+ value: "name",
98
+ description: "<rapi-doc> theme (for example ember, cobalt, mono)",
99
+ },
100
+ },
101
+ examples: [
102
+ "rapidoc preview openapi.yaml",
103
+ "rapidoc preview specs/orders.yaml --open --port 4100",
104
+ "rapidoc preview https://example.com/openapi.json",
105
+ ],
106
+
107
+ async run({ values, positionals }) {
108
+ const target = positionals[0];
109
+ if (!target)
110
+ throw new UsageError("rapidoc preview needs a spec: rapidoc preview <spec>", {
111
+ command: "preview",
112
+ });
113
+ const bundle = rapidocBundle();
114
+
115
+ let specUrl;
116
+ let folder;
117
+ let title;
118
+ if (isUrl(target)) {
119
+ specUrl = target;
120
+ title = new URL(target).pathname.split("/").pop() || target;
121
+ } else {
122
+ const fullPath = path.resolve(target);
123
+ if (!fs.existsSync(fullPath) || !fs.statSync(fullPath).isFile())
124
+ throw new ProblemError(`File not found: ${fullPath}`);
125
+ folder = path.dirname(fullPath);
126
+ title = path.basename(fullPath);
127
+ specUrl = `/spec/${encodePath(path.basename(fullPath))}`;
128
+ }
129
+
130
+ const html = page({ title, specUrl, theme: values.theme, live: Boolean(folder) });
131
+ const listeners = new Set();
132
+ const send = (res, status, type, body) => {
133
+ res.writeHead(status, { "content-type": type, "cache-control": "no-store" });
134
+ res.end(body);
135
+ };
136
+
137
+ const handler = (req, res) => {
138
+ const url = new URL(req.url, "http://preview");
139
+ if (url.pathname === "/") return send(res, 200, "text/html; charset=utf-8", html);
140
+ if (url.pathname === "/rapidoc-min.js" || url.pathname === "/rapidoc-min.js.LICENSE.txt") {
141
+ const file = url.pathname.endsWith(".txt") ? `${bundle}.LICENSE.txt` : bundle;
142
+ if (!fs.existsSync(file)) return send(res, 404, "text/plain", "Not found");
143
+ return send(res, 200, TYPES[path.extname(file)], fs.readFileSync(file));
144
+ }
145
+ if (url.pathname === "/events" && folder) {
146
+ res.writeHead(200, {
147
+ "content-type": "text/event-stream",
148
+ "cache-control": "no-store",
149
+ connection: "keep-alive",
150
+ });
151
+ res.write(": connected\n\n");
152
+ listeners.add(res);
153
+ req.on("close", () => listeners.delete(res));
154
+ return undefined;
155
+ }
156
+ if (url.pathname.startsWith("/spec/") && folder) {
157
+ const file = path.resolve(folder, decodeURIComponent(url.pathname.slice("/spec/".length)));
158
+ // Only files inside the spec's folder.
159
+ if (
160
+ !file.startsWith(folder + path.sep) ||
161
+ !fs.existsSync(file) ||
162
+ !fs.statSync(file).isFile()
163
+ )
164
+ return send(res, 404, "text/plain", "Not found");
165
+ return send(
166
+ res,
167
+ 200,
168
+ TYPES[path.extname(file)] ?? "application/octet-stream",
169
+ fs.readFileSync(file),
170
+ );
171
+ }
172
+ return send(res, 404, "text/plain", "Not found");
173
+ };
174
+
175
+ const server = await startOnFreePort(
176
+ (port) =>
177
+ new Promise((resolve, reject) => {
178
+ const candidate = http.createServer(handler);
179
+ candidate.once("error", reject);
180
+ candidate.listen(port, values.host, () => resolve(candidate));
181
+ }),
182
+ values.port,
183
+ { host: values.host },
184
+ );
185
+ const { port } = server.address();
186
+ const shownHost = ["0.0.0.0", "::"].includes(values.host) ? "localhost" : values.host;
187
+ const pageUrl = `http://${shownHost}:${port}/`;
188
+
189
+ let watcher;
190
+ if (folder) {
191
+ let timer;
192
+ watcher = fs.watch(folder, { recursive: true }, () => {
193
+ clearTimeout(timer);
194
+ timer = setTimeout(() => {
195
+ for (const res of listeners) res.write("data: reload\n\n");
196
+ }, 100);
197
+ });
198
+ }
199
+
200
+ info(`\n${icon("👀")}Previewing ${title}`);
201
+ info(` • URL: ${pageUrl}`);
202
+ info(
203
+ folder
204
+ ? ` • Reloads: when a file in ${folder} changes`
205
+ : " • Source: loaded from the URL (no reload)",
206
+ );
207
+ info("");
208
+ if (values.open) openBrowser(pageUrl);
209
+
210
+ const stop = () => {
211
+ watcher?.close();
212
+ for (const res of listeners) res.end();
213
+ server.close(() => process.exit(0));
214
+ };
215
+ process.once("SIGINT", stop);
216
+ process.once("SIGTERM", stop);
217
+ },
218
+ };
@@ -0,0 +1,95 @@
1
+ import path from "node:path";
2
+ import { loadServer } from "../lib/engines.js";
3
+ import { ProblemError } from "../lib/errors.js";
4
+ import { icon, info, warn } from "../lib/output.js";
5
+ import { startOnFreePort } from "../lib/ports.js";
6
+
7
+ export default {
8
+ name: "serve",
9
+ usage: "serve [dist]",
10
+ summary: "Serves a built portal; enforces sign-in and access rules (default: dist)",
11
+ description:
12
+ "Secrets come from the environment (RAPIDOC_SESSION_SECRET, RAPIDOC_AUTH_ISSUER, ...), never from options.",
13
+ positionals: { name: "dist", max: 1 },
14
+ options: {
15
+ port: {
16
+ type: "string",
17
+ kind: "port",
18
+ value: "number",
19
+ description: "Port to listen on (default $PORT, else 8080)",
20
+ },
21
+ host: {
22
+ type: "string",
23
+ value: "host",
24
+ description: "Address to listen on (default $HOST, else 0.0.0.0)",
25
+ },
26
+ "mount-path": {
27
+ type: "string",
28
+ value: "path",
29
+ description:
30
+ "Path requests arrive under, when a proxy strips part of the portal's path\n(default $RAPIDOC_MOUNT_PATH, else the path of site.url)",
31
+ },
32
+ },
33
+ examples: ["rapidoc serve", "rapidoc serve dist --port 8080"],
34
+
35
+ async run({ values, positionals }) {
36
+ const distDir = path.resolve(positionals[0] || "dist");
37
+ const { startServer } = await loadServer();
38
+ // The server's defaults ($PORT, else 8080; $HOST), to offer another port when that one is taken.
39
+ const host = values.host ?? process.env.HOST ?? "0.0.0.0";
40
+ const port = values.port ?? Number(process.env.PORT || 8080);
41
+ let server;
42
+ try {
43
+ server = await startOnFreePort(
44
+ (portToUse) =>
45
+ startServer({
46
+ distDir,
47
+ port: portToUse,
48
+ host: values.host,
49
+ mountPath: values["mount-path"],
50
+ }),
51
+ port,
52
+ { host },
53
+ );
54
+ } catch (err) {
55
+ if (err.exitCode) throw err; // a busy port without --port, or a cancelled question
56
+ throw new ProblemError(
57
+ err.name === "SettingsError" ? err.message : `Server failed: ${err.message}`,
58
+ );
59
+ }
60
+
61
+ const { settings } = server;
62
+ info(`\n${icon("🌐")}Serving ${distDir}`);
63
+ info(` • URL: ${server.url}`);
64
+ if (server.mcp?.count)
65
+ info(` • MCP: ${server.url.replace(/\/$/, "")}/mcp (${server.mcp.count} tools)`);
66
+ if (settings.mountPath !== settings.basePath) {
67
+ info(
68
+ ` • Paths: requests arrive under ${settings.mountPath || "/"}; links use ${settings.basePath || "/"}`,
69
+ );
70
+ }
71
+ if (settings.mode === "static") {
72
+ info(" • Access: everything public (no sign-in configured)");
73
+ } else {
74
+ if (settings.auth) info(` • Sign-in: ${settings.auth.issuer}`);
75
+ const zones = Object.keys(settings.manifest.access.zones).filter((zone) => zone !== "public");
76
+ info(
77
+ ` • Access: ${Object.keys(settings.manifest.files).length} protected file(s) in ${zones.length} zone(s)`,
78
+ );
79
+ if (settings.auth && !settings.publicUrl) {
80
+ warn(
81
+ "RAPIDOC_PUBLIC_URL is not set: the sign-in redirect URL is taken from each request.",
82
+ " ",
83
+ );
84
+ }
85
+ }
86
+ info("");
87
+
88
+ const stop = async () => {
89
+ await server.close();
90
+ process.exit(0);
91
+ };
92
+ process.once("SIGINT", stop);
93
+ process.once("SIGTERM", stop);
94
+ },
95
+ };
@@ -0,0 +1,139 @@
1
+ import fs from "node:fs";
2
+ import path from "node:path";
3
+ import pkg from "../../package.json" with { type: "json" };
4
+ import { loadPortal, tryLoadPortal } from "../lib/engines.js";
5
+ import { ProblemError } from "../lib/errors.js";
6
+ import { info, setQuiet, success } from "../lib/output.js";
7
+
8
+ /*
9
+ * rapidoc validate [spec|dir]: one spec (a file or URL), or every spec and workflow file of the portal in a
10
+ * folder. Specs are checked strictly against the OpenAPI Specification (src/validate/check.js), with
11
+ * file:line:col for each error, files reached through $ref included. With the portal engine installed,
12
+ * its link checks add warnings. Exit 1 on errors, or on warnings with --strict.
13
+ */
14
+
15
+ // Not imported from validate/bundle.js: that loads yaml, and every command module is loaded for help.
16
+ const isUrl = (target) => /^https?:\/\//i.test(target);
17
+
18
+ const warning = (message, rule, location) => ({ severity: "warning", rule, message, location });
19
+
20
+ async function checkSpecItem(id, location, { remote, portal }) {
21
+ const { checkSpec } = await import("../validate/check.js");
22
+ const result = await checkSpec(location, { remote });
23
+ const problems = [...result.problems];
24
+ if (portal && !isUrl(location)) {
25
+ for (const message of portal.checkApiSpec({ id, fullPath: location }) ?? [])
26
+ problems.push(warning(message, "portal", location));
27
+ }
28
+ for (const skipped of result.skipped)
29
+ problems.push(
30
+ warning(`$ref to ${skipped} not checked (remote; use --remote)`, "ref", location),
31
+ );
32
+ return { kind: "spec", id, location, problems };
33
+ }
34
+
35
+ export default {
36
+ name: "validate",
37
+ usage: "validate [spec|dir]",
38
+ summary:
39
+ "Validates one OpenAPI 2.0 / 3.x spec, or every spec in a portal's apis: (default: current folder)",
40
+ description:
41
+ "Checks against the OpenAPI Specification: required fields, types, path parameters, $refs, including\nfiles reached through $ref. Errors show file:line:col. A portal folder also checks its workflow files\nand, with @rapidoc/portal installed, links between the docs and the specs (warnings).",
42
+ positionals: { name: "spec|dir", max: 1 },
43
+ options: {
44
+ format: {
45
+ type: "string",
46
+ value: "format",
47
+ choices: ["pretty", "json", "sarif"],
48
+ default: "pretty",
49
+ description: "Output format: json for scripts, sarif for GitHub code scanning",
50
+ },
51
+ strict: { type: "boolean", description: "Fail on warnings too" },
52
+ remote: {
53
+ type: "boolean",
54
+ description: "Also fetch and check remote specs and remote $refs (skipped by default)",
55
+ },
56
+ },
57
+ examples: [
58
+ "rapidoc validate",
59
+ "rapidoc validate ./specs/orders-api.yaml",
60
+ "rapidoc validate https://example.com/openapi.json",
61
+ "rapidoc validate --strict --format sarif > rapidoc.sarif",
62
+ ],
63
+
64
+ async run({ values, positionals }) {
65
+ const { format, strict, remote } = values;
66
+ const pretty = format === "pretty";
67
+ // json and sarif print one document on stdout; nothing else goes there.
68
+ if (!pretty) setQuiet(true);
69
+ const { printItem, counts, toJson, toSarif } = await import("../validate/report.js");
70
+ const items = [];
71
+ const done = (item) => {
72
+ items.push(item);
73
+ if (pretty) printItem(item);
74
+ };
75
+
76
+ const target = positionals[0] || ".";
77
+ if (isUrl(target)) {
78
+ info(`\nValidating ${target}...`);
79
+ done(await checkSpecItem(target, target, { remote: true }));
80
+ } else {
81
+ const fullPath = path.resolve(target);
82
+ if (!fs.existsSync(fullPath)) throw new ProblemError(`File not found: ${fullPath}`);
83
+
84
+ if (fs.statSync(fullPath).isFile()) {
85
+ info(`\nValidating ${path.basename(fullPath)}...`);
86
+ const portal = await tryLoadPortal();
87
+ done(await checkSpecItem(path.basename(fullPath), fullPath, { remote, portal }));
88
+ } else {
89
+ const portal = await loadPortal("validate");
90
+ let config;
91
+ try {
92
+ ({ config } = await portal.loadConfig(fullPath));
93
+ } catch (err) {
94
+ throw new ProblemError(err.message);
95
+ }
96
+ info(`\nValidating the specs in ${fullPath}...`);
97
+ for (const api of config.apis || []) {
98
+ for (const version of api.versions) {
99
+ const id = api.versioned ? `${api.id} ${version.version}` : api.id;
100
+ if (version.isRemote && !remote) {
101
+ done({ kind: "spec", id, location: version.spec, skipped: true, problems: [] });
102
+ } else {
103
+ const location = version.isRemote ? version.spec : version.fullPath;
104
+ done(await checkSpecItem(id, location, { remote, portal }));
105
+ }
106
+ }
107
+ }
108
+ for (const workflow of config.workflows || []) {
109
+ const problems = portal
110
+ .checkWorkflow(workflow, config.apis)
111
+ .map((message) => warning(message, "workflow", workflow.fullPath));
112
+ done({ kind: "workflows", id: workflow.id, location: workflow.fullPath, problems });
113
+ }
114
+ }
115
+ }
116
+
117
+ const { errors, warnings } = counts(items);
118
+ const specs = items.filter((item) => item.kind === "spec" && !item.skipped).length;
119
+ const failed = errors > 0 || (strict && warnings > 0);
120
+ if (format === "json")
121
+ process.stdout.write(`${JSON.stringify(toJson(items, { strict }), null, 2)}\n`);
122
+ if (format === "sarif")
123
+ process.stdout.write(
124
+ `${JSON.stringify(toSarif(items, { version: pkg.version }), null, 2)}\n`,
125
+ );
126
+
127
+ const summary = `${specs} spec(s) checked: ${errors} error(s), ${warnings} warning(s)`;
128
+ if (!failed) {
129
+ success(`${summary}.\n`, "\n");
130
+ return;
131
+ }
132
+ // In json and sarif the report already says what failed; scripts read the exit code.
133
+ if (!pretty) {
134
+ process.exitCode = 1;
135
+ return;
136
+ }
137
+ throw new ProblemError(errors ? `${summary}.` : `${summary}; --strict fails on warnings.`);
138
+ },
139
+ };
package/src/index.js ADDED
@@ -0,0 +1,126 @@
1
+ #!/usr/bin/env node
2
+
3
+ /**
4
+ * The `rapidoc` command: picks the command, parses its arguments (lib/args.js), prints help, runs it, and
5
+ * turns thrown errors into messages and exit codes (lib/errors.js): 0 success, 1 problems in the input,
6
+ * 2 a wrong command line. Commands live in commands/, one file each, and declare their own options;
7
+ * help is generated from those declarations.
8
+ */
9
+ import pkg from "../package.json" with { type: "json" };
10
+ import { parseCommandArgs } from "./lib/args.js";
11
+ import { CancelledError, UsageError } from "./lib/errors.js";
12
+ import { commandHelp, overviewHelp } from "./lib/help.js";
13
+ import { error, setQuiet } from "./lib/output.js";
14
+ import { canAsk, select, setAssumeYes } from "./lib/prompt.js";
15
+ import { closest } from "./lib/suggest.js";
16
+ import init from "./commands/init.js";
17
+ import dev from "./commands/dev.js";
18
+ import build from "./commands/build.js";
19
+ import serve from "./commands/serve.js";
20
+ import mock from "./commands/mock.js";
21
+ import validate from "./commands/validate.js";
22
+ import bundle from "./commands/bundle.js";
23
+ import lint from "./commands/lint.js";
24
+ import migrate from "./commands/migrate.js";
25
+ import preview from "./commands/preview.js";
26
+ import mcp from "./commands/mcp.js";
27
+ import doctor from "./commands/doctor.js";
28
+ import completion from "./commands/completion.js";
29
+
30
+ const COMMANDS = [
31
+ init,
32
+ dev,
33
+ build,
34
+ serve,
35
+ preview,
36
+ mock,
37
+ validate,
38
+ lint,
39
+ bundle,
40
+ mcp,
41
+ migrate,
42
+ doctor,
43
+ completion,
44
+ ];
45
+ const byName = new Map(COMMANDS.map((command) => [command.name, command]));
46
+
47
+ function unknownCommand(name) {
48
+ if (name.startsWith("-")) {
49
+ const suggestion = closest(name, ["--help", "--version"]);
50
+ return new UsageError(
51
+ `Unknown option ${name}.${suggestion ? ` Did you mean ${suggestion}?` : ""}`,
52
+ );
53
+ }
54
+ const suggestion = closest(name, [...byName.keys(), "help"]);
55
+ return new UsageError(
56
+ `Unknown command "${name}".${suggestion ? ` Did you mean "${suggestion}"?` : ""}`,
57
+ );
58
+ }
59
+
60
+ // `rapidoc` alone in a terminal: what most people come to do, then help.
61
+ const MENU = [
62
+ { value: "dev", label: "Start the dev server", hint: "rapidoc dev" },
63
+ { value: "build", label: "Build the portal", hint: "rapidoc build" },
64
+ { value: "validate", label: "Validate the specs", hint: "rapidoc validate" },
65
+ { value: "mock", label: "Run the mock server", hint: "rapidoc mock" },
66
+ { value: "init", label: "Create a portal here", hint: "rapidoc init" },
67
+ { value: "help", label: "Show all commands and options", hint: "rapidoc --help" },
68
+ ];
69
+
70
+ async function runCommand(command, argv) {
71
+ // Help wins over everything else on the line, even a mistake (`rapidoc build --outdir x --help`).
72
+ if (argv.includes("--help") || argv.includes("-h")) {
73
+ process.stdout.write(commandHelp(command));
74
+ return;
75
+ }
76
+ const { values, positionals } = parseCommandArgs(command, argv);
77
+ setQuiet(values.quiet);
78
+ setAssumeYes(values.yes);
79
+ await command.run({ values, positionals, commands: COMMANDS });
80
+ }
81
+
82
+ async function main(argv) {
83
+ const [name, ...rest] = argv;
84
+ if (!name && canAsk()) {
85
+ const choice = await select({ message: "What do you want to do?", options: MENU });
86
+ if (choice !== "help") return runCommand(byName.get(choice), []);
87
+ }
88
+ if (!name || name === "--help" || name === "-h") {
89
+ process.stdout.write(overviewHelp(COMMANDS));
90
+ return;
91
+ }
92
+ if (name === "--version" || name === "-v") {
93
+ process.stdout.write(`${pkg.version}\n`);
94
+ return;
95
+ }
96
+ if (name === "help") {
97
+ if (!rest.length) return void process.stdout.write(overviewHelp(COMMANDS));
98
+ const command = byName.get(rest[0]);
99
+ if (!command) throw unknownCommand(rest[0]);
100
+ return void process.stdout.write(commandHelp(command));
101
+ }
102
+
103
+ const command = byName.get(name);
104
+ if (!command) throw unknownCommand(name);
105
+ await runCommand(command, rest);
106
+ }
107
+
108
+ try {
109
+ await main(process.argv.slice(2));
110
+ } catch (err) {
111
+ const exitCode = err.exitCode ?? 1;
112
+ if (err instanceof CancelledError) {
113
+ process.stderr.write(`${err.message}\n`);
114
+ process.exit(exitCode);
115
+ }
116
+ process.stderr.write("\n");
117
+ error(err.message);
118
+ if (err instanceof UsageError) {
119
+ const help = err.command ? `rapidoc ${err.command} --help` : "rapidoc --help";
120
+ process.stderr.write(`Run \`${help}\` for usage.\n`);
121
+ } else if (!err.exitCode && process.env.RAPIDOC_DEBUG) {
122
+ process.stderr.write(`${err.stack}\n`);
123
+ }
124
+ process.stderr.write("\n");
125
+ process.exitCode = exitCode;
126
+ }