@mintlify/cli 4.0.1739 → 4.0.1741

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.
@@ -7,19 +7,31 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, ge
7
7
  step((generator = generator.apply(thisArg, _arguments || [])).next());
8
8
  });
9
9
  };
10
+ var __rest = (this && this.__rest) || function (s, e) {
11
+ var t = {};
12
+ for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)
13
+ t[p] = s[p];
14
+ if (s != null && typeof Object.getOwnPropertySymbols === "function")
15
+ for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {
16
+ if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))
17
+ t[p[i]] = s[p[i]];
18
+ }
19
+ return t;
20
+ };
10
21
  import { jsx as _jsx } from "react/jsx-runtime";
11
- import { addLog, clearLogs, ErrorLog, SpinnerLog } from '@mintlify/previewing';
22
+ import { addLog, checkBuild, clearLogs, ErrorLog, SpinnerLog } from '@mintlify/previewing';
12
23
  import path from 'node:path';
13
- import { CMD_EXEC_PATH, terminate } from '../helpers.js';
14
- import { NoMatchingFilesError, resolveExplicitFiles } from '../resolveFiles.js';
15
- import { checkSite, selectRules, UsageError } from './engine.js';
16
- import { logDiagnostics } from './output.js';
24
+ import { CMD_EXEC_PATH, errorMessage, getVersions, terminate } from '../helpers.js';
25
+ import { resolveExplicitFiles } from '../resolveFiles.js';
26
+ import { sendPublishPrompt } from '../signup.js';
27
+ import { checkSite, runBuildChecks, selectRules } from './engine.js';
28
+ import { logReport } from './output.js';
29
+ import { toReport } from './report.js';
17
30
  export const EXIT = { passed: 0, failed: 1, crashed: 2 };
18
31
  export const splitList = (values) => values.flatMap((value) => value
19
32
  .split(',')
20
33
  .map((item) => item.trim())
21
34
  .filter(Boolean));
22
- const errorMessage = (error) => (error instanceof Error ? error.message : String(error));
23
35
  const resolveSelection = (baseDir, values) => __awaiter(void 0, void 0, void 0, function* () {
24
36
  const args = (values !== null && values !== void 0 ? values : []).map(String).filter(Boolean);
25
37
  if (args.length === 0)
@@ -27,7 +39,8 @@ const resolveSelection = (baseDir, values) => __awaiter(void 0, void 0, void 0,
27
39
  const files = yield resolveExplicitFiles(CMD_EXEC_PATH, args);
28
40
  return new Set(files.map((file) => path.relative(baseDir, path.resolve(CMD_EXEC_PATH, file)).split(path.sep).join('/')));
29
41
  });
30
- export const runLintStep = (argv_1, ...args_1) => __awaiter(void 0, [argv_1, ...args_1], void 0, function* (argv, baseDir = CMD_EXEC_PATH) {
42
+ /** mint validate: one pass over every selected rule, then the strict build when nothing failed. */
43
+ export const validateHandler = (argv_1, packageName_1, ...args_1) => __awaiter(void 0, [argv_1, packageName_1, ...args_1], void 0, function* (argv, packageName, baseDir = CMD_EXEC_PATH) {
31
44
  var _a;
32
45
  try {
33
46
  const rules = selectRules({
@@ -36,23 +49,42 @@ export const runLintStep = (argv_1, ...args_1) => __awaiter(void 0, [argv_1, ...
36
49
  });
37
50
  const selected = yield resolveSelection(baseDir, argv.files);
38
51
  addLog(_jsx(SpinnerLog, { message: "validating..." }));
39
- const { diagnostics } = yield checkSite(baseDir, rules, {
52
+ const _b = yield checkSite(baseDir, rules, {
40
53
  selected,
41
54
  localSchema: argv['local-schema'],
42
- });
43
- clearLogs();
44
- const failed = logDiagnostics(diagnostics);
45
- if (failed) {
46
- yield terminate(EXIT.failed);
47
- return false;
55
+ fix: argv.fix,
56
+ }), { site, fixed } = _b, checked = __rest(_b, ["site", "fixed"]);
57
+ let { diagnostics } = checked;
58
+ const buildRules = rules.some(({ needsBuild }) => needsBuild);
59
+ let build;
60
+ if (!argv.build) {
61
+ build = { ran: false, reason: 'disabled' };
48
62
  }
49
- return true;
63
+ else if (!buildRules) {
64
+ build = { ran: false, reason: 'no build rules' };
65
+ }
66
+ else if (diagnostics.some(({ severity }) => severity === 'error')) {
67
+ build = { ran: false, reason: 'errors found' };
68
+ }
69
+ else {
70
+ addLog(_jsx(SpinnerLog, { message: "building..." }));
71
+ const { cli: cliVersion } = getVersions(packageName);
72
+ site.build = yield checkBuild(Object.assign(Object.assign({}, argv), { _: [], $0: packageName, packageName,
73
+ cliVersion, disableOpenapi: !rules.some(({ group }) => group === 'openapi') }));
74
+ diagnostics = yield runBuildChecks(site, rules, diagnostics);
75
+ build = { ran: true, passed: site.build.passed };
76
+ }
77
+ const report = toReport(diagnostics, build, argv.fix ? fixed : undefined);
78
+ clearLogs();
79
+ logReport(report);
80
+ if (report.passed && build.ran && build.passed)
81
+ yield sendPublishPrompt();
82
+ yield terminate(report.passed ? EXIT.passed : EXIT.failed);
50
83
  }
51
84
  catch (error) {
52
- const usage = error instanceof UsageError || error instanceof NoMatchingFilesError;
85
+ // Bad arguments and crashes alike mean validate could not run
53
86
  clearLogs();
54
87
  addLog(_jsx(ErrorLog, { message: errorMessage(error) }));
55
- yield terminate(usage ? EXIT.failed : EXIT.crashed);
56
- return false;
88
+ yield terminate(EXIT.crashed);
57
89
  }
58
90
  });
@@ -7,7 +7,12 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, ge
7
7
  step((generator = generator.apply(thisArg, _arguments || [])).next());
8
8
  });
9
9
  };
10
- import { checkFiles } from './files.js';
10
+ import { replaceVariables } from '@mintlify/common';
11
+ import fs from 'node:fs/promises';
12
+ import path from 'node:path';
13
+ import { checkFiles, parseFile } from './files.js';
14
+ import { applyEdits, selectEdits, toPosition } from './mdx.js';
15
+ import { buildFindings } from './rules/build.js';
11
16
  import { RULES } from './rules/index.js';
12
17
  import { PARSE_ERROR } from './rules/parseError.js';
13
18
  import { loadSite } from './site.js';
@@ -52,25 +57,105 @@ const sortDiagnostics = (diagnostics) => diagnostics.sort((a, b) => {
52
57
  ((_c = a.column) !== null && _c !== void 0 ? _c : 0) - ((_d = b.column) !== null && _d !== void 0 ? _d : 0) ||
53
58
  ((_e = RULE_ORDER.get(a.rule)) !== null && _e !== void 0 ? _e : 0) - ((_f = RULE_ORDER.get(b.rule)) !== null && _f !== void 0 ? _f : 0);
54
59
  });
55
- /** Runs every selected rule that doesn't need the build. */
56
- export const runChecks = (site, rules) => __awaiter(void 0, void 0, void 0, function* () {
57
- const fileRules = rules.filter((rule) => rule.scope === 'file');
58
- const diagnostics = yield checkFiles(site, fileRules);
60
+ /** Adds findings for a rule unless a diagnostic of that rule already has the same key. */
61
+ const merge = (diagnostics, source, extra, key) => {
62
+ const reported = new Set(diagnostics.filter((item) => item.rule === source.id).map(key));
63
+ for (const finding of extra) {
64
+ if (reported.has(key(finding)))
65
+ continue;
66
+ reported.add(key(finding));
67
+ diagnostics.push(toDiagnostic(source, finding));
68
+ }
69
+ };
70
+ const addParseErrors = (site, diagnostics, extra) => merge(diagnostics, PARSE_ERROR, extra.filter(({ file }) => !site.selected || site.selected.has(file)), ({ file }) => file);
71
+ const fileRulesOf = (rules) => rules.filter((rule) => rule.scope === 'file');
72
+ const runSiteRules = (site, rules, needsBuild, diagnostics) => __awaiter(void 0, void 0, void 0, function* () {
59
73
  for (const rule of rules) {
60
- if (rule.scope !== 'site' || rule.needsBuild)
74
+ if (rule.scope !== 'site' || Boolean(rule.needsBuild) !== needsBuild)
61
75
  continue;
62
76
  for (const finding of yield rule.check(site))
63
77
  diagnostics.push(toDiagnostic(rule, finding));
64
78
  }
79
+ });
80
+ /** Runs every selected rule that doesn't need the build. */
81
+ export const runChecks = (site, rules) => __awaiter(void 0, void 0, void 0, function* () {
82
+ const diagnostics = yield checkFiles(site, fileRulesOf(rules));
83
+ yield runSiteRules(site, rules, false, diagnostics);
84
+ return sortDiagnostics(diagnostics);
85
+ });
86
+ /** Adds the build's findings to a site whose build has run. */
87
+ export const runBuildChecks = (site, rules, diagnostics) => __awaiter(void 0, void 0, void 0, function* () {
88
+ yield runSiteRules(site, rules, true, diagnostics);
89
+ // The file pass already reported files it couldn't parse; the build adds the rest
90
+ addParseErrors(site, diagnostics, buildFindings(site, 'parse-error'));
65
91
  return sortDiagnostics(diagnostics);
66
92
  });
67
- /** Loads the site and runs the selected rules. */
93
+ const parseLevel = (file, content, baseDir) => {
94
+ const parsed = parseFile(file, content, baseDir);
95
+ return 'error' in parsed ? 0 : parsed.approximate ? 1 : 2;
96
+ };
97
+ /** Applies every fix that doesn't overlap an earlier fix in the same file, writing each Markdown file only when its fixed content parses at least as well as before. */
98
+ export const applyFixes = (site, diagnostics) => __awaiter(void 0, void 0, void 0, function* () {
99
+ var _a;
100
+ const contents = new Map();
101
+ const read = (file) => __awaiter(void 0, void 0, void 0, function* () {
102
+ var _a;
103
+ if (!contents.has(file)) {
104
+ contents.set(file, yield fs.readFile(path.join(site.baseDir, file), 'utf-8'));
105
+ }
106
+ return (_a = contents.get(file)) !== null && _a !== void 0 ? _a : '';
107
+ });
108
+ const chosen = new Map();
109
+ const overlaps = ({ file, start, end }) => { var _a; return ((_a = chosen.get(file)) !== null && _a !== void 0 ? _a : []).some(({ fix }) => start < fix.end && fix.start < end); };
110
+ for (const { rule, fix } of diagnostics) {
111
+ if (!fix || overlaps(fix))
112
+ continue;
113
+ const content = yield read(fix.file);
114
+ const change = Object.assign(Object.assign({ rule, file: fix.file }, toPosition(content, fix.start)), { before: content.slice(fix.start, fix.end), after: fix.text });
115
+ chosen.set(fix.file, [...((_a = chosen.get(fix.file)) !== null && _a !== void 0 ? _a : []), { fix, change }]);
116
+ }
117
+ const snippets = new Set(site.files.filter(({ kind }) => kind === 'snippet').map(({ file }) => file));
118
+ const level = (file, content) => parseLevel(file, snippets.has(file) ? replaceVariables(content, site.variables) : content, site.baseDir);
119
+ const applied = [];
120
+ for (const [file, picks] of chosen) {
121
+ const content = yield read(file);
122
+ const updated = applyEdits(content, selectEdits(picks.map(({ fix }) => fix)));
123
+ if (/\.mdx?$/.test(file) && level(file, updated) < level(file, content)) {
124
+ continue;
125
+ }
126
+ yield fs.writeFile(path.join(site.baseDir, file), updated);
127
+ applied.push(...picks.map(({ change }) => change));
128
+ }
129
+ return applied;
130
+ });
131
+ // Fixes can unlock others (a self-closed <br> lets a page parse), so --fix runs a few passes
132
+ const MAX_FIX_PASSES = 5;
133
+ /**
134
+ * Loads the site and runs the selected rules. With fix, applies the fixes, rechecks only the
135
+ * files that changed for further fixes, then runs every rule once more for the final report.
136
+ */
68
137
  export const checkSite = (baseDir, rules, options) => __awaiter(void 0, void 0, void 0, function* () {
138
+ const fixed = [];
69
139
  const site = yield loadSite(baseDir, options);
70
140
  const { selected } = options;
71
141
  if (selected && !site.files.some(({ file }) => selected.has(file))) {
72
142
  throw new UsageError(`none of the given files are pages or snippets of this site: ${[...selected].join(', ')}`);
73
143
  }
74
144
  const diagnostics = yield runChecks(site, rules);
75
- return { site, diagnostics };
145
+ if (!options.fix)
146
+ return { site, diagnostics, fixed };
147
+ // Only file rules offer fixes, so passes after the first recheck just the files that changed
148
+ let pending = diagnostics;
149
+ for (let pass = 0; pass < MAX_FIX_PASSES; pass++) {
150
+ const changes = yield applyFixes(site, pending);
151
+ if (changes.length === 0)
152
+ break;
153
+ fixed.push(...changes);
154
+ const changed = new Set(changes.map(({ file }) => file));
155
+ pending = sortDiagnostics(yield checkFiles(Object.assign(Object.assign({}, site), { selected: changed }), fileRulesOf(rules)));
156
+ }
157
+ if (fixed.length === 0)
158
+ return { site, diagnostics, fixed };
159
+ const fixedSite = yield loadSite(baseDir, options);
160
+ return { site: fixedSite, diagnostics: yield runChecks(fixedSite, rules), fixed };
76
161
  });
@@ -74,7 +74,7 @@ const tryParseContent = (content) => {
74
74
  return undefined;
75
75
  }
76
76
  };
77
- const parseFile = (file, content, baseDir) => {
77
+ export const parseFile = (file, content, baseDir) => {
78
78
  const context = { file, content, baseDir, frontmatter: readFrontmatter(content) };
79
79
  const tree = tryParseContent(content);
80
80
  if (tree)
@@ -1,28 +1,44 @@
1
1
  import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
2
- import { addLog, ErrorLog } from '@mintlify/previewing';
2
+ import { addLog, ErrorLog, InfoLog, SuccessLog } from '@mintlify/previewing';
3
3
  import { Box, Text } from 'ink';
4
+ const preview = (value) => {
5
+ const text = JSON.stringify(value);
6
+ return text.length > 60 ? `${text.slice(0, 57)}..."` : text;
7
+ };
4
8
  const location = ({ line, column }) => line ? `${line}${column ? `:${column}` : ''}` : '';
5
9
  const DiagnosticLine = ({ diagnostic }) => {
6
10
  const at = location(diagnostic);
7
11
  return (_jsxs(Text, { children: [' ', diagnostic.severity === 'error' ? (_jsx(Text, { color: "red", children: "\u2717" })) : (_jsx(Text, { color: "yellow", children: "!" })), ' ', at && _jsxs(Text, { dimColor: true, children: [at, " "] }), _jsx(Text, { dimColor: true, children: diagnostic.rule }), " ", diagnostic.message, diagnostic.fix && _jsx(Text, { dimColor: true, children: " (fixable)" })] }));
8
12
  };
9
13
  const plural = (count, word) => `${count} ${word}${count === 1 ? '' : 's'}`;
10
- export const logDiagnostics = (all) => {
11
- var _a, _b;
14
+ export const logReport = (report) => {
15
+ var _a, _b, _c;
16
+ for (const change of (_a = report.fixed) !== null && _a !== void 0 ? _a : []) {
17
+ addLog(_jsx(SuccessLog, { message: `fixed ${change.file}${change.line ? `:${change.line}` : ''} ${change.rule}: ${preview(change.before)} → ${preview(change.after)}` }));
18
+ }
12
19
  const byFile = new Map();
13
- for (const diagnostic of all) {
14
- (_b = (_a = byFile.get(diagnostic.file)) === null || _a === void 0 ? void 0 : _a.push(diagnostic)) !== null && _b !== void 0 ? _b : byFile.set(diagnostic.file, [diagnostic]);
20
+ for (const diagnostic of report.diagnostics) {
21
+ (_c = (_b = byFile.get(diagnostic.file)) === null || _b === void 0 ? void 0 : _b.push(diagnostic)) !== null && _c !== void 0 ? _c : byFile.set(diagnostic.file, [diagnostic]);
15
22
  }
16
23
  for (const [file, diagnostics] of byFile) {
17
24
  addLog(_jsxs(Box, { flexDirection: "column", children: [_jsx(Text, { bold: true, children: file }), diagnostics.map((diagnostic, index) => (_jsx(DiagnosticLine, { diagnostic: diagnostic }, index)))] }));
18
25
  }
19
- const errors = all.filter(({ severity }) => severity === 'error').length;
20
- const warnings = all.length - errors;
21
- if (errors > 0) {
22
- addLog(_jsx(ErrorLog, { message: `${plural(errors, 'error')}${warnings > 0 ? `, ${plural(warnings, 'warning')}` : ''}` }));
23
- }
24
- else if (warnings > 0) {
25
- addLog(_jsx(Text, { dimColor: true, children: plural(warnings, 'warning') }));
26
+ const fixable = report.diagnostics.filter(({ fix }) => fix).length;
27
+ if (fixable > 0 && !report.fixed) {
28
+ addLog(_jsx(InfoLog, { message: `\`--fix\` would fix ${plural(fixable, 'issue')}.` }));
26
29
  }
27
- return errors > 0;
30
+ const { build } = report;
31
+ if (build.ran && build.passed)
32
+ addLog(_jsx(SuccessLog, { message: "build passed" }));
33
+ else if (build.ran && report.passed)
34
+ addLog(_jsx(InfoLog, { message: "build failed only on disabled rules" }));
35
+ else if (build.ran)
36
+ addLog(_jsx(ErrorLog, { message: "build failed" }));
37
+ else if (build.reason === 'errors found')
38
+ addLog(_jsx(InfoLog, { message: "build skipped until the errors above are fixed" }));
39
+ const { errors, warnings } = report.summary;
40
+ const warned = plural(warnings, 'warning');
41
+ const passed = warnings > 0 ? `passed with ${warned}` : 'validation passed';
42
+ const failed = `${plural(errors, 'error')}${warnings > 0 ? `, ${warned}` : ''}`;
43
+ addLog(report.passed ? _jsx(SuccessLog, { message: passed }) : _jsx(ErrorLog, { message: failed }));
28
44
  };
@@ -0,0 +1,11 @@
1
+ export const toReport = (diagnostics, build, fixed) => {
2
+ var _a;
3
+ const byRule = {};
4
+ for (const { rule } of diagnostics)
5
+ byRule[rule] = ((_a = byRule[rule]) !== null && _a !== void 0 ? _a : 0) + 1;
6
+ const errors = diagnostics.filter(({ severity }) => severity === 'error').length;
7
+ return Object.assign({ passed: errors === 0, summary: { errors, warnings: diagnostics.length - errors, byRule }, diagnostics: diagnostics.map(({ rule, group, severity, file, line, column, message, fix }) => (Object.assign(Object.assign(Object.assign(Object.assign({ rule,
8
+ group,
9
+ severity,
10
+ file }, (line !== undefined && { line })), (column !== undefined && { column })), { message }), (fix && { fix })))), build }, (fixed && { fixed }));
11
+ };
@@ -0,0 +1,94 @@
1
+ import { normalizeRelativePath, toPosixPath } from '@mintlify/common';
2
+ import { stripVTControlCharacters } from 'node:util';
3
+ const FILE = String.raw `[\w@.\\/-]+\.(?:mdx?|jsx?|tsx?|json|ya?ml)\b`;
4
+ const FILE_IN_MESSAGE = new RegExp(FILE);
5
+ const IMPORTERS = [
6
+ new RegExp(String.raw `\(in (${FILE}),`),
7
+ new RegExp(String.raw `(?:\bin|imported from) (${FILE})`),
8
+ ];
9
+ const IMPORT_TYPES = new Set([
10
+ 'missing-file',
11
+ 'invalid-import-path',
12
+ 'import-resolution-error',
13
+ 'default-import-no-default-export',
14
+ 'export-collision',
15
+ 'undeclared-package',
16
+ 'package-import-conflict',
17
+ ]);
18
+ const POSITION = /^:(\d+)(?::(\d+))?/;
19
+ const QUOTED = /"([^"]+)"/;
20
+ const toFinding = (site, { type, message }) => {
21
+ var _a;
22
+ const clean = stripVTControlCharacters(message).trim();
23
+ const importer = IMPORT_TYPES.has(type)
24
+ ? IMPORTERS.map((pattern) => { var _a; return (_a = pattern.exec(clean)) === null || _a === void 0 ? void 0 : _a[1]; }).find(Boolean)
25
+ : undefined;
26
+ // Missing nav pages are always about the config, even when the page looks like a file
27
+ const match = importer || type === 'missing-nav-page' ? null : FILE_IN_MESSAGE.exec(clean);
28
+ const found = importer !== null && importer !== void 0 ? importer : match === null || match === void 0 ? void 0 : match[0];
29
+ const file = found ? normalizeRelativePath(toPosixPath(found)) : site.configFile;
30
+ const position = match ? POSITION.exec(clean.slice(match.index + match[0].length)) : null;
31
+ // Config warnings quote the entry they're about, such as a navigation page
32
+ const quoted = file === site.configFile ? (_a = QUOTED.exec(clean)) === null || _a === void 0 ? void 0 : _a[0] : undefined;
33
+ return Object.assign(Object.assign(Object.assign({ file }, (position && Object.assign({ line: Number(position[1]) }, (position[2] && { column: Number(position[2]) })))), (quoted && site.locate(file, quoted))), { message: clean });
34
+ };
35
+ /** Warning types some rule turns into diagnostics, so a strict-build failure is explained. */
36
+ const COVERED_TYPES = new Set(['parse-error']);
37
+ const buildRule = (id, group, types, description) => {
38
+ for (const type of types)
39
+ COVERED_TYPES.add(type);
40
+ return {
41
+ id,
42
+ group,
43
+ severity: 'error',
44
+ needsBuild: true,
45
+ scope: 'site',
46
+ description,
47
+ check: (site) => {
48
+ var _a, _b;
49
+ return ((_b = (_a = site.build) === null || _a === void 0 ? void 0 : _a.warnings) !== null && _b !== void 0 ? _b : [])
50
+ .filter(({ type }) => types.includes(type))
51
+ .map((warning) => toFinding(site, warning));
52
+ },
53
+ };
54
+ };
55
+ export const BUILD_RULES = [
56
+ buildRule('missing-nav-page', 'nav', ['missing-nav-page'], 'pages in the navigation that have no file'),
57
+ buildRule('missing-file', 'content', ['missing-file'], "imported files that don't exist"),
58
+ buildRule('import-error', 'content', [
59
+ 'invalid-import-path',
60
+ 'import-resolution-error',
61
+ 'default-import-no-default-export',
62
+ 'export-collision',
63
+ ], "imports in pages and snippets that don't resolve"),
64
+ buildRule('package-import', 'config', ['undeclared-package', 'package-import-conflict'], 'npm package imports that are undeclared or conflict'),
65
+ buildRule('openapi-build', 'openapi', ['openapi'], 'OpenAPI pages the build could not generate'),
66
+ {
67
+ id: 'build-failed',
68
+ group: 'config',
69
+ severity: 'error',
70
+ needsBuild: true,
71
+ scope: 'site',
72
+ description: 'the strict build failed for a reason no rule reports',
73
+ check: (site) => {
74
+ if (!site.build || site.build.passed)
75
+ return [];
76
+ const unreported = (warning) => warning.type === 'parse-error' &&
77
+ site.selected !== undefined &&
78
+ !site.selected.has(toFinding(site, warning).file);
79
+ const uncovered = site.build.warnings.filter((warning) => !COVERED_TYPES.has(warning.type) || unreported(warning));
80
+ const findings = uncovered.map((warning) => toFinding(site, warning));
81
+ // Covered warnings are the selected rules' to report; disabled ones are meant to pass
82
+ return site.build.strict
83
+ ? findings
84
+ : [...findings, { file: site.configFile, message: site.build.error }];
85
+ },
86
+ },
87
+ ];
88
+ /** Build warnings of one type, which the engine merges into the static rule that covers them. */
89
+ export const buildFindings = (site, type) => {
90
+ var _a, _b;
91
+ return ((_b = (_a = site.build) === null || _a === void 0 ? void 0 : _a.warnings) !== null && _b !== void 0 ? _b : [])
92
+ .filter((warning) => warning.type === type)
93
+ .map((warning) => toFinding(site, warning));
94
+ };
@@ -1,3 +1,5 @@
1
+ import { BUILD_RULES } from './build.js';
1
2
  import { voidTags } from './content/voidTags.js';
3
+ import { openApiSpec } from './openapi.js';
2
4
  /** Every check mint validate runs, in report order. */
3
- export const RULES = [voidTags];
5
+ export const RULES = [voidTags, openApiSpec, ...BUILD_RULES];
@@ -0,0 +1,50 @@
1
+ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
2
+ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
3
+ return new (P || (P = Promise))(function (resolve, reject) {
4
+ function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
5
+ function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
6
+ function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
7
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
8
+ });
9
+ };
10
+ import fs from 'node:fs/promises';
11
+ import path from 'node:path';
12
+ import { errorMessage } from '../../helpers.js';
13
+ import { buildOverlayRegistryForCheck, checkOpenApiFile, getOpenApiFilenamesFromDocsConfig, } from '../../openApiCheck.js';
14
+ export const openApiSpec = {
15
+ id: 'openapi-spec',
16
+ group: 'openapi',
17
+ severity: 'error',
18
+ scope: 'site',
19
+ description: "OpenAPI specs in docs.json or mint.json that don't parse or validate, with overlays applied",
20
+ check: (site) => __awaiter(void 0, void 0, void 0, function* () {
21
+ let filenames = [];
22
+ try {
23
+ const config = JSON.parse(yield fs.readFile(path.join(site.baseDir, site.configFile), 'utf-8'));
24
+ // mint.json lists its specs under a top-level openapi key
25
+ filenames = getOpenApiFilenamesFromDocsConfig(site.configFile === 'mint.json' ? { api: { openapi: config.openapi } } : config);
26
+ }
27
+ catch (_a) {
28
+ // A missing or invalid config file is the build's to report
29
+ }
30
+ if (filenames.length === 0)
31
+ return [];
32
+ let overlayRegistry;
33
+ try {
34
+ overlayRegistry = yield buildOverlayRegistryForCheck(site.localSchema);
35
+ }
36
+ catch (error) {
37
+ return [{ file: site.configFile, message: `OpenAPI overlays: ${errorMessage(error)}` }];
38
+ }
39
+ const perFile = yield Promise.all(filenames.map((file) => __awaiter(void 0, void 0, void 0, function* () {
40
+ const messages = [];
41
+ yield checkOpenApiFile(file, site.localSchema, overlayRegistry, (message) => messages.push(message));
42
+ return messages.flatMap(({ level, message }) => level === 'error'
43
+ ? [{ file, message }]
44
+ : level === 'warning'
45
+ ? [{ file, message, severity: 'warning' }]
46
+ : []);
47
+ })));
48
+ return perFile.flat();
49
+ }),
50
+ };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@mintlify/cli",
3
- "version": "4.0.1739",
3
+ "version": "4.0.1741",
4
4
  "description": "The Mintlify CLI",
5
5
  "engines": {
6
6
  "node": ">=18.0.0"
@@ -46,11 +46,11 @@
46
46
  "dependencies": {
47
47
  "@inquirer/prompts": "7.9.0",
48
48
  "@mintlify/common": "1.0.1307",
49
- "@mintlify/link-rot": "3.0.1536",
49
+ "@mintlify/link-rot": "3.0.1537",
50
50
  "@mintlify/models": "0.0.379",
51
51
  "@mintlify/og": "0.0.106",
52
- "@mintlify/prebuild": "1.0.1473",
53
- "@mintlify/previewing": "4.0.1554",
52
+ "@mintlify/prebuild": "1.0.1474",
53
+ "@mintlify/previewing": "4.0.1555",
54
54
  "@mintlify/validation": "0.1.944",
55
55
  "adm-zip": "0.6.0",
56
56
  "chalk": "5.2.0",
@@ -101,5 +101,5 @@
101
101
  "vitest": "2.1.9",
102
102
  "vitest-mock-process": "1.0.4"
103
103
  },
104
- "gitHead": "bc5883bc2e0ace9696ffa286bf8cb2b2c32c2c81"
104
+ "gitHead": "4e0cdb6a51f1b140f02f0579f9e4c32592220434"
105
105
  }
package/src/cli.tsx CHANGED
@@ -2,7 +2,6 @@ import {
2
2
  addLog,
3
3
  dev,
4
4
  exportSite,
5
- validateBuild,
6
5
  ErrorLog,
7
6
  SuccessLog,
8
7
  Logs,
@@ -10,8 +9,6 @@ import {
10
9
  } from '@mintlify/previewing';
11
10
  import { thumbnailOverrideSchema } from '@mintlify/validation';
12
11
  import { render, Text } from 'ink';
13
- import fs from 'node:fs/promises';
14
- import path from 'path';
15
12
  import yargs, { type Argv } from 'yargs';
16
13
  import { hideBin } from 'yargs/helpers';
17
14
 
@@ -30,7 +27,6 @@ import { DEPLOY_HELP, deploymentInstructions } from './deploy-instructions.js';
30
27
  import { formatDeployment, prepareAgentDeployment } from './deploy.js';
31
28
  import { formatHandler } from './format.js';
32
29
  import {
33
- CMD_EXEC_PATH,
34
30
  checkPort,
35
31
  checkNodeVersion,
36
32
  autoUpgradeIfNeeded,
@@ -46,17 +42,16 @@ import { logout } from './logout.js';
46
42
  import { mdxLinter } from './mdxLinter.js';
47
43
  import { createTelemetryMiddleware } from './middlewares/telemetryMiddleware.js';
48
44
  import { ogCommand } from './og.js';
49
- import {
50
- buildOverlayRegistryForCheck,
51
- checkOpenApiFile,
52
- getOpenApiFilenamesFromDocsConfig,
53
- } from './openApiCheck.js';
45
+ import { buildOverlayRegistryForCheck, checkOpenApiFile } from './openApiCheck.js';
54
46
  import { scoreHandler } from './score/index.js';
55
- import { sendPublishPrompt, signup } from './signup.js';
47
+ import { signup } from './signup.js';
56
48
  import { status, getCliSubdomains } from './status.js';
57
49
  import { trackTelemetryPreferenceChange } from './telemetry/track.js';
58
50
  import { update } from './update.js';
59
- import { runLintStep, splitList } from './validate/command.js';
51
+ import { splitList, validateHandler } from './validate/command.js';
52
+ import { RULES } from './validate/rules/index.js';
53
+ import { PARSE_ERROR } from './validate/rules/parseError.js';
54
+ import { GROUPS } from './validate/types.js';
60
55
  import { renderWelcome } from './welcome.js';
61
56
  import { workflowsBuilder } from './workflows/index.js';
62
57
 
@@ -362,7 +357,7 @@ export const cli = ({ packageName = 'mint' }: { packageName?: string }) => {
362
357
  )
363
358
  .command(
364
359
  'validate',
365
- 'Validate the documentation build (strict mode, exits on warnings or errors)',
360
+ 'Check the docs: content, OpenAPI specs, then a strict build. Exits 0 with no errors, 1 with errors, 2 when validate itself could not run',
366
361
  (yargs) =>
367
362
  yargs
368
363
  .option('local-schema', {
@@ -380,17 +375,18 @@ export const cli = ({ packageName = 'mint' }: { packageName?: string }) => {
380
375
  type: 'array',
381
376
  description: 'Mock user groups for validation',
382
377
  })
383
- .option('disable-openapi', {
384
- type: 'boolean',
385
- default: false,
386
- description: 'Disable OpenAPI file generation',
387
- })
388
378
  .option('files', {
389
379
  type: 'string',
390
380
  array: true,
391
381
  description:
392
382
  'Limit page checks to these files or globs; site-wide checks and the build still cover the whole site',
393
383
  })
384
+ .option('build', {
385
+ type: 'boolean',
386
+ default: true,
387
+ description:
388
+ 'Run the strict build after the other checks pass; --no-build skips it, so no client download is needed. Remote OpenAPI specs are still fetched unless openapi rules are disabled',
389
+ })
394
390
  .option('enable', {
395
391
  type: 'string',
396
392
  array: true,
@@ -405,50 +401,30 @@ export const cli = ({ packageName = 'mint' }: { packageName?: string }) => {
405
401
  description:
406
402
  'Turn off rules or groups (comma-separated), or all; parse errors are still reported',
407
403
  })
408
- .usage('usage: mintlify validate [options]')
409
- .example('mintlify validate', 'validate the build'),
410
- async (argv) => {
411
- const lintPassed = await runLintStep(argv);
412
- if (!lintPassed) return;
413
-
414
- if (!argv['disable-openapi']) {
415
- let openApiFilenames: string[] = [];
416
-
417
- try {
418
- const docsJson = await fs.readFile(path.join(CMD_EXEC_PATH, 'docs.json'), 'utf-8');
419
- openApiFilenames = getOpenApiFilenamesFromDocsConfig(JSON.parse(docsJson));
420
- } catch {}
421
-
422
- let overlayRegistry;
423
- try {
424
- overlayRegistry = await buildOverlayRegistryForCheck(argv['local-schema']);
425
- } catch (error) {
426
- addLog(<ErrorLog message={error instanceof Error ? error.message : String(error)} />);
427
- await terminate(1);
428
- return;
429
- }
430
- const results = await Promise.all(
431
- openApiFilenames.map((file) =>
432
- checkOpenApiFile(file, argv['local-schema'], overlayRegistry)
433
- )
434
- );
435
-
436
- if (results.some((valid) => !valid)) {
437
- await terminate(1);
438
- return;
439
- }
440
- }
441
-
442
- const { cli: cliVersion } = getVersions(packageName);
443
- await validateBuild(
444
- {
445
- ...argv,
446
- packageName,
447
- cliVersion,
448
- },
449
- sendPublishPrompt
450
- );
451
- }
404
+ .option('fix', {
405
+ type: 'boolean',
406
+ default: false,
407
+ description: 'Apply the fixes and check again',
408
+ })
409
+ .usage('usage: mint validate [options]')
410
+ .epilogue(
411
+ [
412
+ `Groups: ${GROUPS.join(', ')}. Rules:`,
413
+ ...RULES.map(({ id, description }) => ` ${id} — ${description}`),
414
+ ` parse-error — ${PARSE_ERROR.description} (always runs)`,
415
+ ].join('\n')
416
+ )
417
+ .example('mint validate', 'run every check and the build')
418
+ .example(
419
+ 'mint validate --files "guides/**/*.mdx" --fix',
420
+ 'check some pages and apply fixes'
421
+ )
422
+ .example(
423
+ 'mint validate --disable all --enable content',
424
+ 'run the content rules only; missing-file and import-error still run the build'
425
+ )
426
+ .strict(),
427
+ (argv) => validateHandler(argv, packageName)
452
428
  )
453
429
  .command(
454
430
  'export',