@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.
- 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,37 @@
|
|
|
1
|
+
import { UsageError } from "../lib/errors.js";
|
|
2
|
+
|
|
3
|
+
/*
|
|
4
|
+
* rapidoc completion <zsh|bash|fish>: prints a completion script for the shell, generated from the
|
|
5
|
+
* command declarations (lib/completion.js). Load it in the shell's startup file, or write it where the
|
|
6
|
+
* shell looks for completions (the fastest: the CLI doesn't start on every shell).
|
|
7
|
+
*/
|
|
8
|
+
|
|
9
|
+
const SHELLS = ["zsh", "bash", "fish"];
|
|
10
|
+
|
|
11
|
+
export default {
|
|
12
|
+
name: "completion",
|
|
13
|
+
usage: "completion <zsh|bash|fish>",
|
|
14
|
+
summary: "Prints a shell completion script for commands, options and their values",
|
|
15
|
+
description:
|
|
16
|
+
'Generated from the commands\' declarations, so it matches this version. Load it:\n zsh: rapidoc completion zsh > ~/.zsh/completions/_rapidoc (a folder in $fpath, before compinit)\n or: eval "$(rapidoc completion zsh)" in ~/.zshrc\n bash: eval "$(rapidoc completion bash)" in ~/.bashrc\n fish: rapidoc completion fish > ~/.config/fish/completions/rapidoc.fish',
|
|
17
|
+
positionals: { name: "shell", max: 1, choices: SHELLS },
|
|
18
|
+
options: {},
|
|
19
|
+
examples: [
|
|
20
|
+
"rapidoc completion zsh > ~/.zsh/completions/_rapidoc",
|
|
21
|
+
'eval "$(rapidoc completion bash)"',
|
|
22
|
+
"rapidoc completion fish > ~/.config/fish/completions/rapidoc.fish",
|
|
23
|
+
],
|
|
24
|
+
|
|
25
|
+
async run({ positionals, commands }) {
|
|
26
|
+
const [shell] = positionals;
|
|
27
|
+
if (!SHELLS.includes(shell))
|
|
28
|
+
throw new UsageError(
|
|
29
|
+
shell
|
|
30
|
+
? `Unknown shell "${shell}": one of ${SHELLS.join(", ")}`
|
|
31
|
+
: `rapidoc completion needs a shell: ${SHELLS.join(", ")}`,
|
|
32
|
+
{ command: "completion" },
|
|
33
|
+
);
|
|
34
|
+
const generators = await import("../lib/completion.js");
|
|
35
|
+
process.stdout.write(generators[shell](commands));
|
|
36
|
+
},
|
|
37
|
+
};
|
|
@@ -0,0 +1,51 @@
|
|
|
1
|
+
import path from "node:path";
|
|
2
|
+
import { loadPortal } from "../lib/engines.js";
|
|
3
|
+
import { ProblemError } from "../lib/errors.js";
|
|
4
|
+
import { icon, info } from "../lib/output.js";
|
|
5
|
+
import { choosePort } from "../lib/ports.js";
|
|
6
|
+
import { openBrowser } from "../lib/open.js";
|
|
7
|
+
|
|
8
|
+
export default {
|
|
9
|
+
name: "dev",
|
|
10
|
+
usage: "dev [dir]",
|
|
11
|
+
summary: "Launches the local development server with HMR (Astro + Starlight)",
|
|
12
|
+
description:
|
|
13
|
+
"Serves the portal in dir (default: current folder) and rebuilds it as files change.",
|
|
14
|
+
positionals: { name: "dir", max: 1 },
|
|
15
|
+
options: {
|
|
16
|
+
port: {
|
|
17
|
+
type: "string",
|
|
18
|
+
kind: "port",
|
|
19
|
+
value: "number",
|
|
20
|
+
default: 4321,
|
|
21
|
+
description: "Server port",
|
|
22
|
+
},
|
|
23
|
+
open: { type: "boolean", description: "Open the portal in the browser once the server is up" },
|
|
24
|
+
debug: {
|
|
25
|
+
type: "boolean",
|
|
26
|
+
description:
|
|
27
|
+
"Keep the temporary Astro workspace and print its path (for debugging the engine)",
|
|
28
|
+
},
|
|
29
|
+
},
|
|
30
|
+
examples: ["rapidoc dev", "rapidoc dev --open", "rapidoc dev ./my-portal --port 3000"],
|
|
31
|
+
|
|
32
|
+
async run({ values, positionals }) {
|
|
33
|
+
const targetDir = path.resolve(positionals[0] || ".");
|
|
34
|
+
info(`\n${icon("✨")}Starting RapiDoc Portal Dev Server in: ${targetDir}`);
|
|
35
|
+
info(` Engine: Astro + Starlight\n`);
|
|
36
|
+
|
|
37
|
+
const { startDevServer } = await loadPortal("dev");
|
|
38
|
+
let devServer;
|
|
39
|
+
try {
|
|
40
|
+
devServer = await startDevServer(targetDir, {
|
|
41
|
+
// Astro moves to the next free port by itself; in a terminal we ask first.
|
|
42
|
+
port: await choosePort(values.port, { host: "localhost" }),
|
|
43
|
+
keepWorkspace: values.debug,
|
|
44
|
+
});
|
|
45
|
+
} catch (err) {
|
|
46
|
+
throw new ProblemError(`Dev server failed: ${err.message}`);
|
|
47
|
+
}
|
|
48
|
+
if (values.debug) info(` • Workspace (kept): ${devServer.workspaceDir}\n`);
|
|
49
|
+
if (values.open) openBrowser(`http://localhost:${devServer.port}/`);
|
|
50
|
+
},
|
|
51
|
+
};
|
|
@@ -0,0 +1,214 @@
|
|
|
1
|
+
import fs from "node:fs";
|
|
2
|
+
import path from "node:path";
|
|
3
|
+
import { fileURLToPath } from "node:url";
|
|
4
|
+
import pkg from "../../package.json" with { type: "json" };
|
|
5
|
+
import { tryLoadPortal } from "../lib/engines.js";
|
|
6
|
+
import { ProblemError } from "../lib/errors.js";
|
|
7
|
+
import { icon, info, setQuiet } from "../lib/output.js";
|
|
8
|
+
|
|
9
|
+
/*
|
|
10
|
+
* rapidoc doctor [dir]: what a bug report needs and what usually goes wrong. Node against the CLI's
|
|
11
|
+
* engines; each package the CLI uses (installed version against the CLI's range; optional ones may be
|
|
12
|
+
* missing); the portal config in dir (does it load?); the rapidoc browser bundle (is it built?).
|
|
13
|
+
* Exit 1 when something is wrong (too old a Node, a version outside the range, a config that doesn't
|
|
14
|
+
* load, a missing bundle); a missing optional package is only reported.
|
|
15
|
+
*/
|
|
16
|
+
|
|
17
|
+
const parse = (version) => {
|
|
18
|
+
const match = String(version).match(/(\d+)\.(\d+)\.(\d+)/);
|
|
19
|
+
return match ? match.slice(1, 4).map(Number) : null;
|
|
20
|
+
};
|
|
21
|
+
const compare = (a, b) => a[0] - b[0] || a[1] - b[1] || a[2] - b[2];
|
|
22
|
+
|
|
23
|
+
/** `version` satisfies `range` (`^x.y.z`, `>=x.y.z`, `x.y.z` or `*`; the forms package.json files here use). */
|
|
24
|
+
export function satisfies(version, range) {
|
|
25
|
+
const v = parse(version);
|
|
26
|
+
if (!v) return false;
|
|
27
|
+
if (range === "*" || range === "latest") return true;
|
|
28
|
+
const min = parse(range);
|
|
29
|
+
if (!min) return true;
|
|
30
|
+
if (range.startsWith(">=")) return compare(v, min) >= 0;
|
|
31
|
+
if (range.startsWith("^")) {
|
|
32
|
+
if (compare(v, min) < 0) return false;
|
|
33
|
+
if (min[0] > 0) return v[0] === min[0];
|
|
34
|
+
if (min[1] > 0) return v[0] === 0 && v[1] === min[1];
|
|
35
|
+
return v[0] === 0 && v[1] === 0 && v[2] === min[2];
|
|
36
|
+
}
|
|
37
|
+
return compare(v, min) === 0;
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
/** An installed package's package.json (found from its entry point, as the CLI imports it), or null. */
|
|
41
|
+
function installed(name) {
|
|
42
|
+
let file;
|
|
43
|
+
try {
|
|
44
|
+
file = fileURLToPath(import.meta.resolve(name));
|
|
45
|
+
} catch {
|
|
46
|
+
return null;
|
|
47
|
+
}
|
|
48
|
+
for (let dir = path.dirname(file); dir !== path.dirname(dir); dir = path.dirname(dir)) {
|
|
49
|
+
const manifest = path.join(dir, "package.json");
|
|
50
|
+
if (fs.existsSync(manifest)) {
|
|
51
|
+
const json = JSON.parse(fs.readFileSync(manifest, "utf8"));
|
|
52
|
+
if (json.name === name) return { version: json.version, dir };
|
|
53
|
+
}
|
|
54
|
+
}
|
|
55
|
+
return null;
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
const PURPOSE = {
|
|
59
|
+
"@rapidoc/portal": "dev, build, migrate, validate of a portal",
|
|
60
|
+
"@rapidoc/server": "serve",
|
|
61
|
+
"@rapidoc/mock": "mock",
|
|
62
|
+
"@modelcontextprotocol/sdk": "mcp serve",
|
|
63
|
+
"@rapidoc/mcp": "mcp",
|
|
64
|
+
rapidoc: "preview, the portal's API pages",
|
|
65
|
+
"@scalar/openapi-validator": "validate",
|
|
66
|
+
"create-rapidoc": "init",
|
|
67
|
+
"@clack/prompts": "questions in a terminal",
|
|
68
|
+
};
|
|
69
|
+
|
|
70
|
+
function checks(dir) {
|
|
71
|
+
const items = [];
|
|
72
|
+
const add = (group, name, status, detail) => items.push({ group, name, status, detail });
|
|
73
|
+
|
|
74
|
+
const node = process.versions.node;
|
|
75
|
+
const engines = pkg.engines?.node ?? ">=22.12.0";
|
|
76
|
+
add("runtime", "node", satisfies(node, engines) ? "ok" : "error", `${node} (needs ${engines})`);
|
|
77
|
+
add("runtime", "@rapidoc/cli", "ok", pkg.version);
|
|
78
|
+
|
|
79
|
+
const wanted = [
|
|
80
|
+
...Object.entries(pkg.dependencies ?? {}).map(([name, range]) => ({
|
|
81
|
+
name,
|
|
82
|
+
range,
|
|
83
|
+
optional: false,
|
|
84
|
+
})),
|
|
85
|
+
...Object.entries(pkg.peerDependencies ?? {}).map(([name, range]) => ({
|
|
86
|
+
name,
|
|
87
|
+
range,
|
|
88
|
+
optional: Boolean(pkg.peerDependenciesMeta?.[name]?.optional),
|
|
89
|
+
})),
|
|
90
|
+
];
|
|
91
|
+
for (const { name, range, optional } of wanted) {
|
|
92
|
+
const found = installed(name);
|
|
93
|
+
const used = PURPOSE[name] ? `; for ${PURPOSE[name]}` : "";
|
|
94
|
+
if (!found)
|
|
95
|
+
add(
|
|
96
|
+
"packages",
|
|
97
|
+
name,
|
|
98
|
+
optional ? "missing" : "error",
|
|
99
|
+
`not installed (wants ${range}${used})`,
|
|
100
|
+
);
|
|
101
|
+
else if (!satisfies(found.version, range))
|
|
102
|
+
add("packages", name, "error", `${found.version}, outside ${range}${used}`);
|
|
103
|
+
else add("packages", name, "ok", `${found.version}${used}`);
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
const bundle = installed("rapidoc");
|
|
107
|
+
if (bundle) {
|
|
108
|
+
const file = path.join(bundle.dir, "dist/rapidoc-min.js");
|
|
109
|
+
add(
|
|
110
|
+
"files",
|
|
111
|
+
"rapidoc bundle",
|
|
112
|
+
fs.existsSync(file) ? "ok" : "error",
|
|
113
|
+
fs.existsSync(file)
|
|
114
|
+
? path.relative(process.cwd(), file)
|
|
115
|
+
: `${file} missing (npm run build:rapidoc)`,
|
|
116
|
+
);
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
const config = fs.existsSync(dir)
|
|
120
|
+
? fs.readdirSync(dir).find((name) => /^rapidoc\.config\.(ya?ml|json|m?js|ts)$/.test(name))
|
|
121
|
+
: undefined;
|
|
122
|
+
return { items, config };
|
|
123
|
+
}
|
|
124
|
+
|
|
125
|
+
export default {
|
|
126
|
+
name: "doctor",
|
|
127
|
+
usage: "doctor [dir]",
|
|
128
|
+
summary: "Checks the setup: Node, package versions, the portal config, the browser bundle",
|
|
129
|
+
description:
|
|
130
|
+
"Prints what a bug report needs. Fails (exit 1) on too old a Node, a package version outside the\nCLI's range, a portal config that doesn't load, or a missing rapidoc bundle; a missing optional\npackage is only noted (it's needed by the commands listed next to it).",
|
|
131
|
+
positionals: { name: "dir", max: 1 },
|
|
132
|
+
options: {
|
|
133
|
+
format: {
|
|
134
|
+
type: "string",
|
|
135
|
+
value: "format",
|
|
136
|
+
choices: ["pretty", "json"],
|
|
137
|
+
default: "pretty",
|
|
138
|
+
description: "json for bug reports and scripts",
|
|
139
|
+
},
|
|
140
|
+
},
|
|
141
|
+
examples: ["rapidoc doctor", "rapidoc doctor ./my-portal --format json"],
|
|
142
|
+
|
|
143
|
+
async run({ values, positionals }) {
|
|
144
|
+
const dir = path.resolve(positionals[0] || ".");
|
|
145
|
+
if (values.format === "json") setQuiet(true);
|
|
146
|
+
const { items, config } = checks(dir);
|
|
147
|
+
|
|
148
|
+
if (config) {
|
|
149
|
+
const portal = await tryLoadPortal();
|
|
150
|
+
if (!portal) {
|
|
151
|
+
items.push({
|
|
152
|
+
group: "portal",
|
|
153
|
+
name: config,
|
|
154
|
+
status: "missing",
|
|
155
|
+
detail: "found; @rapidoc/portal isn't installed to load it",
|
|
156
|
+
});
|
|
157
|
+
} else {
|
|
158
|
+
try {
|
|
159
|
+
const { config: loaded } = await portal.loadConfig(dir);
|
|
160
|
+
const apis = loaded.apis?.length ?? 0;
|
|
161
|
+
items.push({
|
|
162
|
+
group: "portal",
|
|
163
|
+
name: config,
|
|
164
|
+
status: "ok",
|
|
165
|
+
detail: `loads; ${apis} API(s)`,
|
|
166
|
+
});
|
|
167
|
+
} catch (err) {
|
|
168
|
+
items.push({
|
|
169
|
+
group: "portal",
|
|
170
|
+
name: config,
|
|
171
|
+
status: "error",
|
|
172
|
+
detail: err.message.split("\n")[0],
|
|
173
|
+
});
|
|
174
|
+
}
|
|
175
|
+
}
|
|
176
|
+
} else {
|
|
177
|
+
items.push({
|
|
178
|
+
group: "portal",
|
|
179
|
+
name: "rapidoc.config.*",
|
|
180
|
+
status: "missing",
|
|
181
|
+
detail: `none in ${dir}`,
|
|
182
|
+
});
|
|
183
|
+
}
|
|
184
|
+
|
|
185
|
+
const errors = items.filter((item) => item.status === "error");
|
|
186
|
+
if (values.format === "json") {
|
|
187
|
+
const report = {
|
|
188
|
+
ok: errors.length === 0,
|
|
189
|
+
platform: `${process.platform} ${process.arch}`,
|
|
190
|
+
cwd: process.cwd(),
|
|
191
|
+
items,
|
|
192
|
+
};
|
|
193
|
+
process.stdout.write(`${JSON.stringify(report, null, 2)}\n`);
|
|
194
|
+
if (errors.length) process.exitCode = 1;
|
|
195
|
+
return;
|
|
196
|
+
}
|
|
197
|
+
|
|
198
|
+
const mark = {
|
|
199
|
+
ok: icon("✅", "ok "),
|
|
200
|
+
missing: icon("➖", "missing "),
|
|
201
|
+
error: icon("❌", "error "),
|
|
202
|
+
};
|
|
203
|
+
const width = Math.max(...items.map((item) => item.name.length)) + 2;
|
|
204
|
+
let group;
|
|
205
|
+
info(`\n${icon("🩺")}rapidoc doctor (${process.platform} ${process.arch})`);
|
|
206
|
+
for (const item of items) {
|
|
207
|
+
if (item.group !== group)
|
|
208
|
+
info(`\n${(group = item.group)[0].toUpperCase()}${group.slice(1)}:`);
|
|
209
|
+
info(` ${mark[item.status]}${item.name.padEnd(width)}${item.detail}`);
|
|
210
|
+
}
|
|
211
|
+
info("");
|
|
212
|
+
if (errors.length) throw new ProblemError(`${errors.length} problem(s): see above.`);
|
|
213
|
+
},
|
|
214
|
+
};
|
|
@@ -0,0 +1,163 @@
|
|
|
1
|
+
import fs from "node:fs";
|
|
2
|
+
import path from "node:path";
|
|
3
|
+
import { spawnSync } from "node:child_process";
|
|
4
|
+
import { CancelledError, ProblemError } from "../lib/errors.js";
|
|
5
|
+
import { icon, info, warn } from "../lib/output.js";
|
|
6
|
+
import { canAsk, confirm, intro, multiselect, text } from "../lib/prompt.js";
|
|
7
|
+
|
|
8
|
+
const slash = (file) => file.split(path.sep).join("/");
|
|
9
|
+
const quote = (value) => (/^[\w./@:-]+$/.test(value) ? value : JSON.stringify(value));
|
|
10
|
+
|
|
11
|
+
/** `rapidoc init …` that does the same as this run without asking anything. */
|
|
12
|
+
function equivalentCommand({ targetDir, title, specs, starter, install }) {
|
|
13
|
+
const parts = ["rapidoc init"];
|
|
14
|
+
const relDir = slash(path.relative(process.cwd(), targetDir));
|
|
15
|
+
if (relDir) parts.push(quote(relDir));
|
|
16
|
+
if (title) parts.push(`--title ${quote(title)}`);
|
|
17
|
+
if (starter) parts.push("--starter-spec");
|
|
18
|
+
for (const spec of specs ?? [])
|
|
19
|
+
parts.push(
|
|
20
|
+
`--spec ${quote(slash(path.relative(process.cwd(), path.join(targetDir, spec))) || ".")}`,
|
|
21
|
+
);
|
|
22
|
+
if (install === false) parts.push("--no-install");
|
|
23
|
+
return parts.join(" ");
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
export default {
|
|
27
|
+
name: "init",
|
|
28
|
+
usage: "init [dir]",
|
|
29
|
+
summary:
|
|
30
|
+
"Scaffolds a developer portal (default: current folder); uses OpenAPI files already there",
|
|
31
|
+
description:
|
|
32
|
+
"The same scaffold as `npm create rapidoc`, built around the OpenAPI files already in dir (all of\nthem unless --spec or --starter-spec says otherwise). In a terminal it asks for what the options\ndon't say: the title, which specs, whether to run npm install; then prints the command that does\nthe same without asking.",
|
|
33
|
+
positionals: { name: "dir", max: 1 },
|
|
34
|
+
options: {
|
|
35
|
+
title: { type: "string", value: "title", description: "Site title" },
|
|
36
|
+
spec: {
|
|
37
|
+
type: "string",
|
|
38
|
+
value: "file",
|
|
39
|
+
multiple: true,
|
|
40
|
+
description: "An OpenAPI file to include (repeat for more); default: every one found",
|
|
41
|
+
},
|
|
42
|
+
"starter-spec": {
|
|
43
|
+
type: "boolean",
|
|
44
|
+
description: "Use the starter spec, not the OpenAPI files found in dir",
|
|
45
|
+
},
|
|
46
|
+
force: {
|
|
47
|
+
type: "boolean",
|
|
48
|
+
short: "f",
|
|
49
|
+
description: "Overwrite existing files (asks first in a terminal)",
|
|
50
|
+
},
|
|
51
|
+
install: { type: "boolean", negatable: true, description: "Skip npm install" },
|
|
52
|
+
},
|
|
53
|
+
examples: [
|
|
54
|
+
"rapidoc init",
|
|
55
|
+
'rapidoc init my-portal --title "Acme Developer Portal"',
|
|
56
|
+
"rapidoc init --spec specs/orders.yaml --spec specs/billing.yaml",
|
|
57
|
+
"rapidoc init --yes --no-install",
|
|
58
|
+
],
|
|
59
|
+
|
|
60
|
+
async run({ values, positionals }) {
|
|
61
|
+
const { scaffoldProject, planScaffold, findOpenApiSpecs } =
|
|
62
|
+
await import("create-rapidoc/scaffold");
|
|
63
|
+
const targetDir = path.resolve(positionals[0] || ".");
|
|
64
|
+
const foundSpecs = fs.existsSync(targetDir) ? findOpenApiSpecs(targetDir) : [];
|
|
65
|
+
|
|
66
|
+
if (values.spec && values["starter-spec"]) {
|
|
67
|
+
throw new ProblemError("Pass --spec or --starter-spec, not both.");
|
|
68
|
+
}
|
|
69
|
+
let specsGiven;
|
|
70
|
+
if (values["starter-spec"]) specsGiven = [];
|
|
71
|
+
if (values.spec) {
|
|
72
|
+
specsGiven = values.spec.map((file) => {
|
|
73
|
+
const fullPath = path.resolve(file);
|
|
74
|
+
if (!fs.existsSync(fullPath)) throw new ProblemError(`--spec ${file}: file not found`);
|
|
75
|
+
return slash(path.relative(targetDir, fullPath));
|
|
76
|
+
});
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
// Ask for what the options didn't say (in a terminal only; otherwise the defaults).
|
|
80
|
+
const hasPackageJson = fs.existsSync(path.join(targetDir, "package.json"));
|
|
81
|
+
const known = { title: values.title, specs: specsGiven, install: values.install };
|
|
82
|
+
const open =
|
|
83
|
+
known.title === undefined ||
|
|
84
|
+
(known.specs === undefined && foundSpecs.length > 0) ||
|
|
85
|
+
(known.install === undefined && !hasPackageJson);
|
|
86
|
+
let answers = known;
|
|
87
|
+
const asked = open && canAsk();
|
|
88
|
+
if (asked) {
|
|
89
|
+
const { askInitQuestions } = await import("create-rapidoc/wizard");
|
|
90
|
+
await intro("Create a RapiDoc developer portal");
|
|
91
|
+
answers = await askInitQuestions({
|
|
92
|
+
ask: { text, multiselect, confirm },
|
|
93
|
+
targetDir,
|
|
94
|
+
foundSpecs,
|
|
95
|
+
known,
|
|
96
|
+
askInstall: !hasPackageJson,
|
|
97
|
+
});
|
|
98
|
+
}
|
|
99
|
+
const title = answers.title || undefined;
|
|
100
|
+
const specs = answers.specs ?? foundSpecs;
|
|
101
|
+
const install = answers.install ?? true;
|
|
102
|
+
|
|
103
|
+
// --force over existing files: list them and ask first (in a terminal).
|
|
104
|
+
const plan = planScaffold(targetDir, { title, specs });
|
|
105
|
+
const existing = plan.files.filter((file) => fs.existsSync(file.path));
|
|
106
|
+
if (values.force && existing.length && canAsk()) {
|
|
107
|
+
info(`\nThese ${existing.length} file(s) exist and would be replaced:`);
|
|
108
|
+
for (const file of existing) info(` • ${slash(path.relative(targetDir, file.path))}`);
|
|
109
|
+
const ok = await confirm({ message: "Overwrite them?", initialValue: false });
|
|
110
|
+
if (!ok) throw new CancelledError("Cancelled; nothing was written.");
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
info(`\n${icon("🚀")}Scaffolding a RapiDoc Developer Portal in: ${targetDir}`);
|
|
114
|
+
if (specs.length) info(` Using ${specs.length} OpenAPI file(s): ${specs.join(", ")}`);
|
|
115
|
+
|
|
116
|
+
let result;
|
|
117
|
+
try {
|
|
118
|
+
result = scaffoldProject(targetDir, { title, overwrite: values.force, specs });
|
|
119
|
+
} catch (err) {
|
|
120
|
+
throw new ProblemError(`Failed to scaffold the portal: ${err.message}`);
|
|
121
|
+
}
|
|
122
|
+
|
|
123
|
+
info(`\n${icon("✨")}Created ${result.filesCreated.length} file(s) for "${result.siteTitle}"`);
|
|
124
|
+
if (result.filesSkipped.length) {
|
|
125
|
+
info(` Kept ${result.filesSkipped.length} existing file(s) (use --force to overwrite):`);
|
|
126
|
+
for (const file of result.filesSkipped) info(` • ${path.relative(targetDir, file)}`);
|
|
127
|
+
}
|
|
128
|
+
|
|
129
|
+
const packageJsonPath = path.join(targetDir, "package.json");
|
|
130
|
+
const ownPackageJson = result.filesCreated.includes(packageJsonPath);
|
|
131
|
+
const relDir = path.relative(process.cwd(), targetDir) || ".";
|
|
132
|
+
if (!ownPackageJson) {
|
|
133
|
+
info(`\nAdd the CLI and the portal engine to your existing package.json:`);
|
|
134
|
+
info(` npm install -D @rapidoc/cli @rapidoc/portal`);
|
|
135
|
+
} else if (install) {
|
|
136
|
+
info(`\n${icon("📦")}Installing dependencies...`);
|
|
137
|
+
const npm = spawnSync("npm", ["install"], {
|
|
138
|
+
cwd: targetDir,
|
|
139
|
+
stdio: "inherit",
|
|
140
|
+
shell: process.platform === "win32",
|
|
141
|
+
});
|
|
142
|
+
if (npm.status !== 0) warn(`npm install failed; run it yourself in ${relDir}.`, "\n");
|
|
143
|
+
}
|
|
144
|
+
|
|
145
|
+
if (asked) {
|
|
146
|
+
const starter =
|
|
147
|
+
answers.specs !== undefined && answers.specs.length === 0 && foundSpecs.length > 0;
|
|
148
|
+
const chosen =
|
|
149
|
+
answers.specs?.length && answers.specs.length !== foundSpecs.length
|
|
150
|
+
? answers.specs
|
|
151
|
+
: undefined;
|
|
152
|
+
info(`\nThe same without questions:`);
|
|
153
|
+
info(
|
|
154
|
+
` ${equivalentCommand({ targetDir, title, specs: chosen, starter, install: ownPackageJson ? install : undefined })}`,
|
|
155
|
+
);
|
|
156
|
+
}
|
|
157
|
+
|
|
158
|
+
info(`\nNext steps:`);
|
|
159
|
+
if (relDir !== ".") info(` cd ${relDir}`);
|
|
160
|
+
if (ownPackageJson && !install) info(` npm install`);
|
|
161
|
+
info(` ${ownPackageJson ? "npm run dev" : "npx rapidoc dev"}\n`);
|
|
162
|
+
},
|
|
163
|
+
};
|
|
@@ -0,0 +1,160 @@
|
|
|
1
|
+
import fs from "node:fs";
|
|
2
|
+
import path from "node:path";
|
|
3
|
+
import pkg from "../../package.json" with { type: "json" };
|
|
4
|
+
import { loadPortal } from "../lib/engines.js";
|
|
5
|
+
import { ProblemError } from "../lib/errors.js";
|
|
6
|
+
import { info, setQuiet, success, warn } from "../lib/output.js";
|
|
7
|
+
|
|
8
|
+
/*
|
|
9
|
+
* rapidoc lint [spec|dir]: what a spec needs to make a good portal, beyond being valid OpenAPI. One spec
|
|
10
|
+
* (a file or URL), or every spec of the portal in a folder (its rapidoc.config.*), or every OpenAPI file
|
|
11
|
+
* found in a folder without one. validate's check runs first; an invalid spec is not linted further.
|
|
12
|
+
* Severities: --rule name=severity › lint: in rapidoc.config.* (per API under lint.apis) › the defaults.
|
|
13
|
+
*/
|
|
14
|
+
|
|
15
|
+
const isUrl = (target) => /^https?:\/\//i.test(target);
|
|
16
|
+
|
|
17
|
+
export default {
|
|
18
|
+
name: "lint",
|
|
19
|
+
usage: "lint [spec|dir]",
|
|
20
|
+
summary:
|
|
21
|
+
"Checks what a spec needs to make a good portal: operationIds, summaries, examples, security",
|
|
22
|
+
description:
|
|
23
|
+
"Runs validate's check, then rules for what the portal, Try, the mock server and MCP tools need:\noperationIds (stable URLs), summaries, declared tags, success responses, security on write\noperations, examples on bodies, no unused components. Same output as validate, with the rule name.\nSeverities: --rule name=error|warn|off, or lint.rules / lint.apis.<id> in rapidoc.config.*.",
|
|
24
|
+
positionals: { name: "spec|dir", max: 1 },
|
|
25
|
+
options: {
|
|
26
|
+
format: {
|
|
27
|
+
type: "string",
|
|
28
|
+
value: "format",
|
|
29
|
+
choices: ["pretty", "json", "sarif"],
|
|
30
|
+
default: "pretty",
|
|
31
|
+
description: "Output format: json for scripts, sarif for GitHub code scanning",
|
|
32
|
+
},
|
|
33
|
+
strict: { type: "boolean", description: "Fail on warnings too" },
|
|
34
|
+
rule: {
|
|
35
|
+
type: "string",
|
|
36
|
+
multiple: true,
|
|
37
|
+
value: "name=severity",
|
|
38
|
+
description: "Set a rule's severity (error, warn, off); repeat for more. See --rules",
|
|
39
|
+
},
|
|
40
|
+
rules: { type: "boolean", description: "List the rules, their defaults and what they check" },
|
|
41
|
+
remote: {
|
|
42
|
+
type: "boolean",
|
|
43
|
+
description: "Also fetch and lint remote specs and remote $refs (skipped by default)",
|
|
44
|
+
},
|
|
45
|
+
},
|
|
46
|
+
examples: [
|
|
47
|
+
"rapidoc lint openapi.yaml",
|
|
48
|
+
"rapidoc lint",
|
|
49
|
+
"rapidoc lint openapi.yaml --rule operation-description=warn --rule no-unused-components=off",
|
|
50
|
+
"rapidoc lint --strict --format sarif > rapidoc.sarif",
|
|
51
|
+
],
|
|
52
|
+
|
|
53
|
+
async run({ values, positionals }) {
|
|
54
|
+
const { format, strict, remote } = values;
|
|
55
|
+
const { RULES } = await import("../lint/rules/index.js");
|
|
56
|
+
if (values.rules) {
|
|
57
|
+
const width = Math.max(...RULES.map((rule) => rule.name.length)) + 2;
|
|
58
|
+
info("\nRules (default severity):\n");
|
|
59
|
+
for (const rule of RULES)
|
|
60
|
+
info(` ${rule.name.padEnd(width)}${rule.default.padEnd(7)}${rule.description}`);
|
|
61
|
+
info("");
|
|
62
|
+
return;
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
const pretty = format === "pretty";
|
|
66
|
+
if (!pretty) setQuiet(true);
|
|
67
|
+
const { parseRuleOptions, readLintConfig, severitiesFor } = await import("../lint/config.js");
|
|
68
|
+
const { lintSpec } = await import("../lint/run.js");
|
|
69
|
+
const { printItem, counts, toJson, toSarif } = await import("../validate/report.js");
|
|
70
|
+
const overrides = parseRuleOptions(values.rule);
|
|
71
|
+
|
|
72
|
+
const items = [];
|
|
73
|
+
const done = (item) => {
|
|
74
|
+
items.push(item);
|
|
75
|
+
if (pretty) printItem(item, { ok: "No problems" });
|
|
76
|
+
};
|
|
77
|
+
const lintOne = async (id, location, severities) => {
|
|
78
|
+
const result = await lintSpec(location, { remote, severities });
|
|
79
|
+
const problems = [...result.problems];
|
|
80
|
+
for (const skipped of result.skipped)
|
|
81
|
+
problems.push({
|
|
82
|
+
severity: "warning",
|
|
83
|
+
rule: "ref",
|
|
84
|
+
message: `$ref to ${skipped} not checked (remote; use --remote)`,
|
|
85
|
+
location,
|
|
86
|
+
});
|
|
87
|
+
done({ kind: "spec", id, location, problems, linted: result.linted });
|
|
88
|
+
};
|
|
89
|
+
|
|
90
|
+
const target = positionals[0] || ".";
|
|
91
|
+
if (isUrl(target)) {
|
|
92
|
+
info(`\nLinting ${target}...`);
|
|
93
|
+
await lintOne(target, target, severitiesFor({ overrides }));
|
|
94
|
+
} else {
|
|
95
|
+
const fullPath = path.resolve(target);
|
|
96
|
+
if (!fs.existsSync(fullPath)) throw new ProblemError(`File not found: ${fullPath}`);
|
|
97
|
+
// A single file takes the settings of the portal it's run from (the current folder).
|
|
98
|
+
const dir = fs.statSync(fullPath).isFile() ? process.cwd() : fullPath;
|
|
99
|
+
const { config, warning } = await readLintConfig(dir);
|
|
100
|
+
if (warning) warn(warning);
|
|
101
|
+
|
|
102
|
+
if (fs.statSync(fullPath).isFile()) {
|
|
103
|
+
info(`\nLinting ${path.basename(fullPath)}...`);
|
|
104
|
+
await lintOne(path.basename(fullPath), fullPath, severitiesFor({ config, overrides }));
|
|
105
|
+
} else if (
|
|
106
|
+
fs
|
|
107
|
+
.readdirSync(fullPath)
|
|
108
|
+
.some((name) => /^rapidoc\.config\.(ya?ml|json|m?js|ts)$/.test(name))
|
|
109
|
+
) {
|
|
110
|
+
const portal = await loadPortal("lint");
|
|
111
|
+
let loaded;
|
|
112
|
+
try {
|
|
113
|
+
loaded = (await portal.loadConfig(fullPath)).config;
|
|
114
|
+
} catch (err) {
|
|
115
|
+
throw new ProblemError(err.message);
|
|
116
|
+
}
|
|
117
|
+
info(`\nLinting the specs in ${fullPath}...`);
|
|
118
|
+
for (const api of loaded.apis || []) {
|
|
119
|
+
const severities = severitiesFor({ config, api: api.id, overrides });
|
|
120
|
+
for (const version of api.versions) {
|
|
121
|
+
const id = api.versioned ? `${api.id} ${version.version}` : api.id;
|
|
122
|
+
if (version.isRemote && !remote)
|
|
123
|
+
done({ kind: "spec", id, location: version.spec, skipped: true, problems: [] });
|
|
124
|
+
else await lintOne(id, version.isRemote ? version.spec : version.fullPath, severities);
|
|
125
|
+
}
|
|
126
|
+
}
|
|
127
|
+
} else {
|
|
128
|
+
const { findOpenApiSpecs } = await import("create-rapidoc/scaffold");
|
|
129
|
+
const files = findOpenApiSpecs(fullPath);
|
|
130
|
+
if (!files.length) throw new ProblemError(`No OpenAPI files found in ${fullPath}`);
|
|
131
|
+
info(`\nLinting ${files.length} spec(s) in ${fullPath}...`);
|
|
132
|
+
for (const file of files)
|
|
133
|
+
await lintOne(file, path.join(fullPath, file), severitiesFor({ config, overrides }));
|
|
134
|
+
}
|
|
135
|
+
}
|
|
136
|
+
|
|
137
|
+
const { errors, warnings } = counts(items);
|
|
138
|
+
const specs = items.filter((item) => item.kind === "spec" && !item.skipped).length;
|
|
139
|
+
const failed = errors > 0 || (strict && warnings > 0);
|
|
140
|
+
if (format === "json")
|
|
141
|
+
process.stdout.write(`${JSON.stringify(toJson(items, { strict }), null, 2)}\n`);
|
|
142
|
+
if (format === "sarif") {
|
|
143
|
+
const rules = Object.fromEntries(RULES.map((rule) => [rule.name, rule.description]));
|
|
144
|
+
process.stdout.write(
|
|
145
|
+
`${JSON.stringify(toSarif(items, { version: pkg.version, tool: "rapidoc lint", rules }), null, 2)}\n`,
|
|
146
|
+
);
|
|
147
|
+
}
|
|
148
|
+
|
|
149
|
+
const summary = `${specs} spec(s) linted: ${errors} error(s), ${warnings} warning(s)`;
|
|
150
|
+
if (!failed) {
|
|
151
|
+
success(`${summary}.\n`, "\n");
|
|
152
|
+
return;
|
|
153
|
+
}
|
|
154
|
+
if (!pretty) {
|
|
155
|
+
process.exitCode = 1;
|
|
156
|
+
return;
|
|
157
|
+
}
|
|
158
|
+
throw new ProblemError(errors ? `${summary}.` : `${summary}; --strict fails on warnings.`);
|
|
159
|
+
},
|
|
160
|
+
};
|