@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,110 @@
1
+ /*
2
+ * The shape of an OpenAPI document, for walks that need to know what a node is: which children of a
3
+ * node of one kind are schemas, parameters, responses, ... `rapidoc bundle` uses it to pick a component's
4
+ * container, `rapidoc lint` to hand each rule the nodes of the kinds it asked for.
5
+ *
6
+ * Kinds: root, components, pathItem, operation, parameter, header, requestBody, response, mediaType,
7
+ * encoding, callback, schema, example, link, securityScheme (the last three have no $ref-able children).
8
+ */
9
+
10
+ export const METHODS = [
11
+ "get",
12
+ "put",
13
+ "post",
14
+ "delete",
15
+ "options",
16
+ "head",
17
+ "patch",
18
+ "trace",
19
+ "query",
20
+ ];
21
+ const SCHEMA_ONE = [
22
+ "items",
23
+ "not",
24
+ "additionalProperties",
25
+ "additionalItems",
26
+ "unevaluatedProperties",
27
+ "unevaluatedItems",
28
+ "propertyNames",
29
+ "contains",
30
+ "if",
31
+ "then",
32
+ "else",
33
+ ];
34
+ const SCHEMA_MAP = ["properties", "patternProperties", "dependentSchemas", "$defs", "definitions"];
35
+ const SCHEMA_LIST = ["allOf", "anyOf", "oneOf", "prefixItems"];
36
+
37
+ /**
38
+ * The kind of `key`'s value inside a node of kind `kind`, as ["one", kind], ["map", kind] or
39
+ * ["list", kind]; undefined when it holds no $ref-able OpenAPI object (or the kind is unknown).
40
+ * @param {string | undefined} kind
41
+ * @param {string} key
42
+ * @param {boolean} v2 Swagger 2.0 document
43
+ */
44
+ export function childKind(kind, key, v2) {
45
+ switch (kind) {
46
+ case "root":
47
+ if (key === "paths" || key === "webhooks") return ["map", "pathItem"];
48
+ if (key === "components") return ["one", "components"];
49
+ if (v2 && key === "definitions") return ["map", "schema"];
50
+ if (v2 && key === "parameters") return ["map", "parameter"];
51
+ if (v2 && key === "responses") return ["map", "response"];
52
+ return undefined;
53
+ case "components":
54
+ return CONTAINERS[key] ? ["map", CONTAINERS[key]] : undefined;
55
+ case "pathItem":
56
+ if (key === "parameters") return ["list", "parameter"];
57
+ if (METHODS.includes(key)) return ["one", "operation"];
58
+ return undefined;
59
+ case "operation":
60
+ if (key === "parameters") return ["list", "parameter"];
61
+ if (key === "requestBody") return ["one", "requestBody"];
62
+ if (key === "responses") return ["map", "response"];
63
+ if (key === "callbacks") return ["map", "callback"];
64
+ return undefined;
65
+ case "parameter":
66
+ case "header":
67
+ if (key === "schema" || (v2 && key === "items")) return ["one", "schema"];
68
+ if (key === "examples") return ["map", "example"];
69
+ if (key === "content") return ["map", "mediaType"];
70
+ return undefined;
71
+ case "requestBody":
72
+ return key === "content" ? ["map", "mediaType"] : undefined;
73
+ case "response":
74
+ if (key === "headers") return ["map", "header"];
75
+ if (key === "content") return ["map", "mediaType"];
76
+ if (key === "links") return ["map", "link"];
77
+ if (v2 && key === "schema") return ["one", "schema"];
78
+ return undefined;
79
+ case "mediaType":
80
+ if (key === "schema") return ["one", "schema"];
81
+ if (key === "examples") return ["map", "example"];
82
+ if (key === "encoding") return ["map", "encoding"];
83
+ return undefined;
84
+ case "encoding":
85
+ return key === "headers" ? ["map", "header"] : undefined;
86
+ case "callback":
87
+ return ["one", "pathItem"];
88
+ case "schema":
89
+ if (SCHEMA_ONE.includes(key)) return ["one", "schema"];
90
+ if (SCHEMA_MAP.includes(key)) return ["map", "schema"];
91
+ if (SCHEMA_LIST.includes(key)) return ["list", "schema"];
92
+ return undefined;
93
+ default:
94
+ return undefined;
95
+ }
96
+ }
97
+
98
+ /** components/<container> → kind (OpenAPI 3.x). */
99
+ export const CONTAINERS = {
100
+ schemas: "schema",
101
+ parameters: "parameter",
102
+ responses: "response",
103
+ requestBodies: "requestBody",
104
+ headers: "header",
105
+ examples: "example",
106
+ links: "link",
107
+ callbacks: "callback",
108
+ pathItems: "pathItem",
109
+ securitySchemes: "securityScheme",
110
+ };
@@ -0,0 +1,38 @@
1
+ /**
2
+ * Terminal output. Icons only when the stream is a terminal and NO_COLOR is unset (TERM=dumb counts as
3
+ * no terminal); piped or in CI, plain text with "error:" / "warning:" prefixes. --quiet keeps errors
4
+ * and warnings only. Results and progress go to stdout, warnings and errors to stderr.
5
+ */
6
+
7
+ const decorated = (stream) =>
8
+ Boolean(stream.isTTY) && !("NO_COLOR" in process.env) && process.env.TERM !== "dumb";
9
+
10
+ let quiet = false;
11
+
12
+ /** Applies the global --quiet option. */
13
+ export function setQuiet(value) {
14
+ quiet = Boolean(value);
15
+ }
16
+
17
+ /** `icon` followed by a space on a terminal; `plain` (default: nothing) otherwise. */
18
+ export function icon(emoji, plain = "", stream = process.stdout) {
19
+ return decorated(stream) ? `${emoji} ` : plain;
20
+ }
21
+
22
+ /** Progress and results: hidden by --quiet. */
23
+ export function info(text = "") {
24
+ if (!quiet) process.stdout.write(`${text}\n`);
25
+ }
26
+
27
+ /** A line that reports success: hidden by --quiet. */
28
+ export function success(text, indent = "") {
29
+ info(`${indent}${icon("✅")}${text}`);
30
+ }
31
+
32
+ export function warn(text, indent = "") {
33
+ process.stderr.write(`${indent}${icon("⚠️ ", "warning: ", process.stderr)}${text}\n`);
34
+ }
35
+
36
+ export function error(text, indent = "") {
37
+ process.stderr.write(`${indent}${icon("❌", "error: ", process.stderr)}${text}\n`);
38
+ }
@@ -0,0 +1,65 @@
1
+ import net from "node:net";
2
+ import { CancelledError, ProblemError } from "./errors.js";
3
+ import { assumingYes, canAsk, confirm } from "./prompt.js";
4
+
5
+ /** Whether `port` can be listened on at `host` right now. */
6
+ export function isPortFree(port, host) {
7
+ return new Promise((resolve) => {
8
+ const server = net.createServer();
9
+ server.once("error", () => resolve(false));
10
+ server.listen({ port, host }, () => server.close(() => resolve(true)));
11
+ });
12
+ }
13
+
14
+ /** The first free port after `port` (up to 50 further), or 0 (let the system pick). */
15
+ async function nextFreePort(port, host) {
16
+ for (let candidate = port + 1; candidate <= Math.min(port + 50, 65535); candidate++)
17
+ if (await isPortFree(candidate, host)) return candidate;
18
+ return 0;
19
+ }
20
+
21
+ /**
22
+ * `port` is taken: in a terminal, offer the next free one (no: CancelledError); with --yes, take it;
23
+ * otherwise null (the caller decides: fail, or keep the port).
24
+ */
25
+ async function replacementPort(port, host) {
26
+ const next = await nextFreePort(port, host);
27
+ if (canAsk()) {
28
+ const ok = await confirm({
29
+ message: `Port ${port} is in use. Use ${next || "a free one"} instead?`,
30
+ initialValue: true,
31
+ });
32
+ if (!ok) throw new CancelledError();
33
+ return next;
34
+ }
35
+ return assumingYes() ? next : null;
36
+ }
37
+
38
+ const inUse = (err) => err?.code === "EADDRINUSE" || /EADDRINUSE/.test(err?.message ?? "");
39
+
40
+ /**
41
+ * Starts a server with `start(port)`; when its port is taken, offers the next free one (see
42
+ * replacementPort) and starts it there, else fails naming --port. Starting first (not checking the
43
+ * port first) keeps the server's own checks in their order: a missing build is reported before a busy
44
+ * port. Used by serve and mock.
45
+ */
46
+ export async function startOnFreePort(start, port, { host } = {}) {
47
+ try {
48
+ return await start(port);
49
+ } catch (err) {
50
+ if (!inUse(err) || !port) throw err;
51
+ const next = await replacementPort(port, host);
52
+ if (next === null)
53
+ throw new ProblemError(`Port ${port} is in use. Pass --port <number> (0 picks a free one).`);
54
+ return start(next);
55
+ }
56
+ }
57
+
58
+ /**
59
+ * For the dev server, which moves to a free port by itself (Astro): in a terminal or with --yes, settle
60
+ * the port first so the choice is the user's; otherwise leave `port` to the server.
61
+ */
62
+ export async function choosePort(port, { host } = {}) {
63
+ if (!port || (await isPortFree(port, host))) return port;
64
+ return (await replacementPort(port, host)) ?? port;
65
+ }
@@ -0,0 +1,73 @@
1
+ import { CancelledError } from "./errors.js";
2
+
3
+ /*
4
+ * Questions, through @clack/prompts (imported only when the CLI asks something). The rules:
5
+ * - canAsk(): only when stdin and stdout are terminals, CI is unset, and --yes wasn't given. Otherwise
6
+ * commands use their defaults (assumingYes(): --yes accepts them) or fail naming the option to pass.
7
+ * - Every question is also an option, so anything a question sets can be scripted.
8
+ * - Ctrl+C (or Esc) on a question throws CancelledError: "Cancelled.", exit 130.
9
+ * Tests: RAPIDOC_PROMPT_ANSWERS, a JSON array, answers the questions in order without a terminal
10
+ * (like RAPIDOC_PORTAL_MODULE, a hook for tests only). `null` in it answers like Ctrl+C.
11
+ */
12
+
13
+ let assumeYes = false;
14
+ let scripted;
15
+
16
+ /** Applies the global --yes option. */
17
+ export function setAssumeYes(value) {
18
+ assumeYes = Boolean(value);
19
+ }
20
+
21
+ /** --yes was given: questions take their default answer. */
22
+ export const assumingYes = () => assumeYes;
23
+
24
+ function scriptedAnswers() {
25
+ if (scripted === undefined) {
26
+ const raw = process.env.RAPIDOC_PROMPT_ANSWERS;
27
+ scripted = raw ? JSON.parse(raw) : null;
28
+ }
29
+ return scripted;
30
+ }
31
+
32
+ export function canAsk() {
33
+ if (assumeYes) return false;
34
+ if (scriptedAnswers()) return true;
35
+ return Boolean(process.stdin.isTTY && process.stdout.isTTY) && !process.env.CI;
36
+ }
37
+
38
+ async function ask(kind, options) {
39
+ const answers = scriptedAnswers();
40
+ if (answers) {
41
+ if (!answers.length) throw new Error(`No scripted answer left for "${options.message}"`);
42
+ const answer = answers.shift();
43
+ if (answer === null) throw new CancelledError();
44
+ if (kind === "text" && answer === "" && options.defaultValue !== undefined)
45
+ return options.defaultValue;
46
+ return answer;
47
+ }
48
+ const clack = await import("@clack/prompts");
49
+ const answer = await clack[kind](options);
50
+ if (clack.isCancel(answer)) throw new CancelledError();
51
+ return answer;
52
+ }
53
+
54
+ /** A line of text; empty input gives `defaultValue`. */
55
+ export const text = (options) => ask("text", options);
56
+ /** Yes or no. */
57
+ export const confirm = (options) => ask("confirm", options);
58
+ /** One of `options: [{ value, label, hint? }]`. */
59
+ export const select = (options) => ask("select", options);
60
+ /** Any of `options`, `initialValues` checked. */
61
+ export const multiselect = (options) => ask("multiselect", options);
62
+
63
+ /** A heading before a series of questions (terminal only). */
64
+ export async function intro(title) {
65
+ if (scriptedAnswers()) return;
66
+ (await import("@clack/prompts")).intro(title);
67
+ }
68
+
69
+ /** Closes a series of questions (terminal only). */
70
+ export async function outro(message) {
71
+ if (scriptedAnswers()) return;
72
+ (await import("@clack/prompts")).outro(message);
73
+ }
@@ -0,0 +1,36 @@
1
+ /** Edit distance (insertions, deletions, substitutions, swaps of two neighbours). */
2
+ function distance(a, b) {
3
+ const rows = Array.from({ length: a.length + 1 }, (_, i) => [i]);
4
+ for (let j = 1; j <= b.length; j++) rows[0][j] = j;
5
+ for (let i = 1; i <= a.length; i++) {
6
+ for (let j = 1; j <= b.length; j++) {
7
+ const cost = a[i - 1] === b[j - 1] ? 0 : 1;
8
+ rows[i][j] = Math.min(rows[i - 1][j] + 1, rows[i][j - 1] + 1, rows[i - 1][j - 1] + cost);
9
+ if (i > 1 && j > 1 && a[i - 1] === b[j - 2] && a[i - 2] === b[j - 1])
10
+ rows[i][j] = Math.min(rows[i][j], rows[i - 2][j - 2] + 1);
11
+ }
12
+ }
13
+ return rows[a.length][b.length];
14
+ }
15
+
16
+ /**
17
+ * The candidate closest to `input` (case-insensitive), or undefined when none is close enough: the only
18
+ * candidate starting with an input of 3+ letters, else the nearest within 1 edit (2 for 5+ letters).
19
+ */
20
+ export function closest(input, candidates) {
21
+ const needle = input.toLowerCase();
22
+ if (needle.length >= 3) {
23
+ const prefixed = candidates.filter((candidate) => candidate.toLowerCase().startsWith(needle));
24
+ if (prefixed.length === 1) return prefixed[0];
25
+ }
26
+ let best;
27
+ let bestDistance = Infinity;
28
+ for (const candidate of candidates) {
29
+ const hay = candidate.toLowerCase();
30
+ const d = distance(needle, hay);
31
+ if (d < bestDistance) [best, bestDistance] = [candidate, d];
32
+ }
33
+ if (best === undefined) return undefined;
34
+ const limit = needle.length >= 5 ? 2 : 1;
35
+ return bestDistance <= limit ? best : undefined;
36
+ }
@@ -0,0 +1,112 @@
1
+ import fs from "node:fs";
2
+ import path from "node:path";
3
+ import { UsageError, ProblemError } from "../lib/errors.js";
4
+ import { closest } from "../lib/suggest.js";
5
+ import { RULE_NAMES, RULES } from "./rules/index.js";
6
+
7
+ /*
8
+ * Which rules run and how hard they fail. Most specific wins: --rule name=severity › the API's entry
9
+ * under lint.apis in rapidoc.config.* › lint.rules there › each rule's default.
10
+ *
11
+ * lint:
12
+ * rules: { operation-description: warn, no-unused-components: off }
13
+ * apis: { legacy: { operation-operationId: off } }
14
+ *
15
+ * The config is read as a plain file (yaml or json) so that `rapidoc lint` needs no portal engine; a
16
+ * rapidoc.config.js/.mjs is imported; a .ts file can't be read here and is reported.
17
+ */
18
+
19
+ /** @import { Severity } from "./types.js" */
20
+
21
+ const SEVERITIES = ["error", "warn", "off"];
22
+
23
+ /** @typedef {{ rules?: Record<string, Severity>, apis?: Record<string, Record<string, Severity>> }} LintConfig */
24
+
25
+ function checkRuleName(name, where) {
26
+ if (RULE_NAMES.includes(name)) return;
27
+ const suggestion = closest(name, RULE_NAMES);
28
+ throw new UsageError(
29
+ `${where}: unknown rule "${name}".${suggestion ? ` Did you mean ${suggestion}?` : ""}`,
30
+ { command: "lint" },
31
+ );
32
+ }
33
+
34
+ function checkSeverity(name, severity, where) {
35
+ if (SEVERITIES.includes(severity)) return;
36
+ throw new UsageError(
37
+ `${where}: rule ${name} must be one of ${SEVERITIES.join(", ")}, got "${severity}"`,
38
+ { command: "lint" },
39
+ );
40
+ }
41
+
42
+ /** `--rule name=severity` values → { name: severity }. */
43
+ export function parseRuleOptions(values = []) {
44
+ const out = {};
45
+ for (const value of values) {
46
+ const [name, severity, ...rest] = String(value).split("=");
47
+ if (!severity || rest.length)
48
+ throw new UsageError(`--rule needs <name>=<error|warn|off>, got "${value}"`, {
49
+ command: "lint",
50
+ });
51
+ checkRuleName(name, "--rule");
52
+ checkSeverity(name, severity, "--rule");
53
+ out[name] = severity;
54
+ }
55
+ return out;
56
+ }
57
+
58
+ /**
59
+ * The `lint:` section of the portal config in `dir`, or {} when there is none.
60
+ * @returns {Promise<{ config: LintConfig, file?: string, warning?: string }>}
61
+ */
62
+ export async function readLintConfig(dir) {
63
+ const names = fs.existsSync(dir) ? fs.readdirSync(dir) : [];
64
+ const name = names.find((entry) => /^rapidoc\.config\.(ya?ml|json|m?js|ts)$/.test(entry));
65
+ if (!name) return { config: {} };
66
+ const file = path.join(dir, name);
67
+ let raw;
68
+ if (/\.ya?ml$/.test(name)) {
69
+ const { parse } = await import("yaml");
70
+ raw = parse(fs.readFileSync(file, "utf8"));
71
+ } else if (name.endsWith(".json")) {
72
+ raw = JSON.parse(fs.readFileSync(file, "utf8"));
73
+ } else if (name.endsWith(".ts")) {
74
+ return {
75
+ config: {},
76
+ file,
77
+ warning: `${name}: lint settings in a .ts config aren't read; pass --rule instead`,
78
+ };
79
+ } else {
80
+ raw = (await import(file)).default;
81
+ }
82
+ const config = raw?.lint ?? {};
83
+ if (typeof config !== "object" || config === null || Array.isArray(config))
84
+ throw new ProblemError(`${name}: lint must be a map (rules:, apis:)`);
85
+ for (const [ruleName, severity] of Object.entries(config.rules ?? {})) {
86
+ checkRuleName(ruleName, `${name}: lint.rules`);
87
+ checkSeverity(ruleName, severity, `${name}: lint.rules`);
88
+ }
89
+ for (const [api, rules] of Object.entries(config.apis ?? {}))
90
+ for (const [ruleName, severity] of Object.entries(rules ?? {})) {
91
+ checkRuleName(ruleName, `${name}: lint.apis.${api}`);
92
+ checkSeverity(ruleName, severity, `${name}: lint.apis.${api}`);
93
+ }
94
+ return { config, file };
95
+ }
96
+
97
+ /**
98
+ * The severity of every rule for one spec.
99
+ * @param {{ config?: LintConfig, api?: string, overrides?: Record<string, Severity> }} layers
100
+ * @returns {Record<string, Severity>}
101
+ */
102
+ export function severitiesFor({ config = {}, api, overrides = {} } = {}) {
103
+ return Object.fromEntries(
104
+ RULES.map((rule) => [
105
+ rule.name,
106
+ overrides[rule.name] ??
107
+ (api && config.apis?.[api]?.[rule.name]) ??
108
+ config.rules?.[rule.name] ??
109
+ rule.default,
110
+ ]),
111
+ );
112
+ }
@@ -0,0 +1,40 @@
1
+ import infoContact from "./info-contact.js";
2
+ import infoLicense from "./info-license.js";
3
+ import mediaExample from "./media-example.js";
4
+ import noServerExampleCom from "./no-server-example-com.js";
5
+ import noUnusedComponents from "./no-unused-components.js";
6
+ import operation2xxResponse from "./operation-2xx-response.js";
7
+ import operation4xxResponse from "./operation-4xx-response.js";
8
+ import operationDescription from "./operation-description.js";
9
+ import operationOperationId from "./operation-operationId.js";
10
+ import operationOperationIdUnique from "./operation-operationId-unique.js";
11
+ import operationOperationIdUrlSafe from "./operation-operationId-url-safe.js";
12
+ import operationSummary from "./operation-summary.js";
13
+ import operationTagDefined from "./operation-tag-defined.js";
14
+ import pathKebabCase from "./path-kebab-case.js";
15
+ import securityDefined from "./security-defined.js";
16
+ import securitySchemeDefined from "./security-scheme-defined.js";
17
+ import tagDescription from "./tag-description.js";
18
+
19
+ /** Every rule, in the order they are listed in help and reports. @type {import("../types.js").Rule[]} */
20
+ export const RULES = [
21
+ operationOperationId,
22
+ operationOperationIdUnique,
23
+ operationOperationIdUrlSafe,
24
+ operationSummary,
25
+ operationDescription,
26
+ operationTagDefined,
27
+ tagDescription,
28
+ operation2xxResponse,
29
+ operation4xxResponse,
30
+ securityDefined,
31
+ securitySchemeDefined,
32
+ noUnusedComponents,
33
+ mediaExample,
34
+ pathKebabCase,
35
+ noServerExampleCom,
36
+ infoContact,
37
+ infoLicense,
38
+ ];
39
+
40
+ export const RULE_NAMES = RULES.map((rule) => rule.name);
@@ -0,0 +1,12 @@
1
+ /** @type {import("../types.js").Rule} */
2
+ export default {
3
+ name: "info-contact",
4
+ description:
5
+ "info has a contact (name, url or email): the portal shows it in the API page header.",
6
+ default: "off",
7
+ on: ["info"],
8
+ check: (info, { pointer }) =>
9
+ info.contact && typeof info.contact === "object" && Object.keys(info.contact).length
10
+ ? []
11
+ : [{ pointer, message: "info has no contact" }],
12
+ };
@@ -0,0 +1,11 @@
1
+ /** @type {import("../types.js").Rule} */
2
+ export default {
3
+ name: "info-license",
4
+ description: "info has a license: the portal shows it in the API page header.",
5
+ default: "off",
6
+ on: ["info"],
7
+ check: (info, { pointer }) =>
8
+ info.license && typeof info.license === "object" && info.license.name
9
+ ? []
10
+ : [{ pointer, message: "info has no license" }],
11
+ };
@@ -0,0 +1,35 @@
1
+ const hasExample = (node) =>
2
+ node !== null &&
3
+ typeof node === "object" &&
4
+ (node.example !== undefined ||
5
+ (node.examples !== null &&
6
+ typeof node.examples === "object" &&
7
+ Object.keys(node.examples).length > 0) ||
8
+ node.default !== undefined);
9
+
10
+ /** @type {import("../types.js").Rule} */
11
+ export default {
12
+ name: "media-example",
13
+ description:
14
+ "Request and response bodies have an example (on the media type or its schema): Try fills the request with it and the mock server answers with it.",
15
+ default: "warn",
16
+ on: ["mediaType"],
17
+ check: (media, { pointer, parents, resolve }) => {
18
+ const parent = parents.at(-1);
19
+ if (parent !== "requestBody" && parent !== "response") return [];
20
+ if (hasExample(media)) return [];
21
+ const schema = resolve(media.schema);
22
+ if (hasExample(schema)) return [];
23
+ // A schema whose properties all carry examples is enough: a sample is built from them.
24
+ if (schema && typeof schema === "object" && schema.properties) {
25
+ const props = Object.values(schema.properties).map(resolve);
26
+ if (props.length && props.every(hasExample)) return [];
27
+ }
28
+ return [
29
+ {
30
+ pointer,
31
+ message: `${pointer.at(-1)} ${parent === "response" ? "response" : "request body"} has no example`,
32
+ },
33
+ ];
34
+ },
35
+ };
@@ -0,0 +1,30 @@
1
+ const PLACEHOLDER = /^(.*\.)?example\.(com|org|net)$|^localhost$|^127\.0\.0\.1$/i;
2
+
3
+ const hostOf = (url) => {
4
+ try {
5
+ return new URL(String(url).replace(/\{[^}]*\}/g, "x")).hostname;
6
+ } catch {
7
+ return undefined;
8
+ }
9
+ };
10
+
11
+ /** @type {import("../types.js").Rule} */
12
+ export default {
13
+ name: "no-server-example-com",
14
+ description: "Servers are real addresses, not example.com or localhost: Try would call nowhere.",
15
+ default: "warn",
16
+ on: ["server", "document"],
17
+ check: (node, { pointer, v2, parents }) => {
18
+ if (parents.length === 0) {
19
+ // the document: Swagger 2.0 keeps the host on the root
20
+ if (!v2 || typeof node.host !== "string") return [];
21
+ return PLACEHOLDER.test(node.host.split(":")[0])
22
+ ? [{ pointer: ["host"], message: `host "${node.host}" is a placeholder` }]
23
+ : [];
24
+ }
25
+ const host = hostOf(node.url);
26
+ return host && PLACEHOLDER.test(host)
27
+ ? [{ pointer: [...pointer, "url"], message: `Server "${node.url}" is a placeholder` }]
28
+ : [];
29
+ },
30
+ };
@@ -0,0 +1,41 @@
1
+ import { CONTAINERS } from "../../lib/openapi-shape.js";
2
+ import { encodePointer } from "../../validate/bundle.js";
3
+
4
+ /** Every $ref string in a value. */
5
+ const refsIn = (value, found = new Set()) => {
6
+ if (Array.isArray(value)) for (const item of value) refsIn(item, found);
7
+ else if (value && typeof value === "object") {
8
+ if (typeof value.$ref === "string") found.add(value.$ref);
9
+ for (const child of Object.values(value)) refsIn(child, found);
10
+ }
11
+ return found;
12
+ };
13
+
14
+ /** @type {import("../types.js").Rule} */
15
+ export default {
16
+ name: "no-unused-components",
17
+ description:
18
+ "Every component is referenced somewhere: an unused one is documentation of nothing.",
19
+ default: "warn",
20
+ on: ["document"],
21
+ check: (doc, { v2 }) => {
22
+ const containers = v2
23
+ ? [["definitions"], ["parameters"], ["responses"]]
24
+ : Object.keys(CONTAINERS)
25
+ .filter((key) => key !== "securitySchemes")
26
+ .map((key) => ["components", key]);
27
+ const used = refsIn(doc);
28
+ const findings = [];
29
+ for (const container of containers) {
30
+ let node = doc;
31
+ for (const segment of container) node = node?.[segment];
32
+ if (!node || typeof node !== "object") continue;
33
+ for (const name of Object.keys(node)) {
34
+ const pointer = [...container, name];
35
+ if (!used.has(encodePointer(pointer)))
36
+ findings.push({ pointer, message: `${encodePointer(pointer)} is never referenced` });
37
+ }
38
+ }
39
+ return findings;
40
+ },
41
+ };
@@ -0,0 +1,17 @@
1
+ /** @type {import("../types.js").Rule} */
2
+ export default {
3
+ name: "operation-2xx-response",
4
+ description:
5
+ "Every operation documents a success response (2xx or 3xx): without one, Try has nothing to show as the expected result.",
6
+ default: "warn",
7
+ on: ["operation"],
8
+ check: (op, { pointer, method, path }) =>
9
+ Object.keys(op.responses ?? {}).some((code) => /^[23]/.test(code))
10
+ ? []
11
+ : [
12
+ {
13
+ pointer: [...pointer, "responses"],
14
+ message: `${method.toUpperCase()} ${path} has no 2xx or 3xx response`,
15
+ },
16
+ ],
17
+ };
@@ -0,0 +1,17 @@
1
+ /** @type {import("../types.js").Rule} */
2
+ export default {
3
+ name: "operation-4xx-response",
4
+ description:
5
+ "Every operation documents at least one 4xx response, so readers see the error shapes.",
6
+ default: "off",
7
+ on: ["operation"],
8
+ check: (op, { pointer, method, path }) =>
9
+ Object.keys(op.responses ?? {}).some((code) => code.startsWith("4"))
10
+ ? []
11
+ : [
12
+ {
13
+ pointer: [...pointer, "responses"],
14
+ message: `${method.toUpperCase()} ${path} has no 4xx response`,
15
+ },
16
+ ],
17
+ };
@@ -0,0 +1,12 @@
1
+ /** @type {import("../types.js").Rule} */
2
+ export default {
3
+ name: "operation-description",
4
+ description:
5
+ "Every operation has a description: readers and AI agents (the MCP tool's description) rely on it.",
6
+ default: "off",
7
+ on: ["operation"],
8
+ check: (op, { pointer, method, path }) =>
9
+ typeof op.description === "string" && op.description.trim()
10
+ ? []
11
+ : [{ pointer, message: `${method.toUpperCase()} ${path} has no description` }],
12
+ };