@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.
package/src/helpers.tsx CHANGED
@@ -248,6 +248,9 @@ export const readLocalOpenApiFile = async (
248
248
  return document;
249
249
  };
250
250
 
251
+ export const errorMessage = (error: unknown) =>
252
+ error instanceof Error ? error.message : String(error);
253
+
251
254
  export const terminate = async (code: number) => {
252
255
  // Wait for the logs to be fully rendered before exiting
253
256
  await new Promise((resolve) => setTimeout(resolve, 50));
@@ -1,18 +1,22 @@
1
- import { addLog, clearLogs, ErrorLog, SpinnerLog } from '@mintlify/previewing';
1
+ import { addLog, checkBuild, clearLogs, ErrorLog, SpinnerLog } from '@mintlify/previewing';
2
2
  import path from 'node:path';
3
3
 
4
- import { CMD_EXEC_PATH, terminate } from '../helpers.js';
5
- import { NoMatchingFilesError, resolveExplicitFiles } from '../resolveFiles.js';
6
- import { checkSite, selectRules, UsageError } from './engine.js';
7
- import { logDiagnostics } from './output.js';
4
+ import { CMD_EXEC_PATH, errorMessage, getVersions, terminate } from '../helpers.js';
5
+ import { resolveExplicitFiles } from '../resolveFiles.js';
6
+ import { sendPublishPrompt } from '../signup.js';
7
+ import { checkSite, runBuildChecks, selectRules } from './engine.js';
8
+ import { logReport } from './output.js';
9
+ import { toReport, type BuildStatus } from './report.js';
8
10
 
9
11
  export type ValidateArgs = {
10
12
  'local-schema': boolean;
11
13
  'client-version'?: string;
12
14
  groups?: (string | number)[];
13
15
  files?: (string | number)[];
16
+ build: boolean;
14
17
  enable?: string[];
15
18
  disable?: string[];
19
+ fix: boolean;
16
20
  };
17
21
 
18
22
  export const EXIT = { passed: 0, failed: 1, crashed: 2 } as const;
@@ -25,8 +29,6 @@ export const splitList = (values: string[]) =>
25
29
  .filter(Boolean)
26
30
  );
27
31
 
28
- const errorMessage = (error: unknown) => (error instanceof Error ? error.message : String(error));
29
-
30
32
  const resolveSelection = async (baseDir: string, values: (string | number)[] | undefined) => {
31
33
  const args = (values ?? []).map(String).filter(Boolean);
32
34
  if (args.length === 0) return undefined;
@@ -38,10 +40,12 @@ const resolveSelection = async (baseDir: string, values: (string | number)[] | u
38
40
  );
39
41
  };
40
42
 
41
- export const runLintStep = async (
43
+ /** mint validate: one pass over every selected rule, then the strict build when nothing failed. */
44
+ export const validateHandler = async (
42
45
  argv: ValidateArgs,
46
+ packageName: string,
43
47
  baseDir = CMD_EXEC_PATH
44
- ): Promise<boolean> => {
48
+ ) => {
45
49
  try {
46
50
  const rules = selectRules({
47
51
  enable: argv.enable,
@@ -50,22 +54,45 @@ export const runLintStep = async (
50
54
  const selected = await resolveSelection(baseDir, argv.files);
51
55
  addLog(<SpinnerLog message="validating..." />);
52
56
 
53
- const { diagnostics } = await checkSite(baseDir, rules, {
57
+ const { site, fixed, ...checked } = await checkSite(baseDir, rules, {
54
58
  selected,
55
59
  localSchema: argv['local-schema'],
60
+ fix: argv.fix,
56
61
  });
57
- clearLogs();
58
- const failed = logDiagnostics(diagnostics);
59
- if (failed) {
60
- await terminate(EXIT.failed);
61
- return false;
62
+ let { diagnostics } = checked;
63
+
64
+ const buildRules = rules.some(({ needsBuild }) => needsBuild);
65
+ let build: BuildStatus;
66
+ if (!argv.build) {
67
+ build = { ran: false, reason: 'disabled' };
68
+ } else if (!buildRules) {
69
+ build = { ran: false, reason: 'no build rules' };
70
+ } else if (diagnostics.some(({ severity }) => severity === 'error')) {
71
+ build = { ran: false, reason: 'errors found' };
72
+ } else {
73
+ addLog(<SpinnerLog message="building..." />);
74
+ const { cli: cliVersion } = getVersions(packageName);
75
+ site.build = await checkBuild({
76
+ ...argv,
77
+ _: [],
78
+ $0: packageName,
79
+ packageName,
80
+ cliVersion,
81
+ disableOpenapi: !rules.some(({ group }) => group === 'openapi'),
82
+ });
83
+ diagnostics = await runBuildChecks(site, rules, diagnostics);
84
+ build = { ran: true, passed: site.build.passed };
62
85
  }
63
- return true;
86
+
87
+ const report = toReport(diagnostics, build, argv.fix ? fixed : undefined);
88
+ clearLogs();
89
+ logReport(report);
90
+ if (report.passed && build.ran && build.passed) await sendPublishPrompt();
91
+ await terminate(report.passed ? EXIT.passed : EXIT.failed);
64
92
  } catch (error) {
65
- const usage = error instanceof UsageError || error instanceof NoMatchingFilesError;
93
+ // Bad arguments and crashes alike mean validate could not run
66
94
  clearLogs();
67
95
  addLog(<ErrorLog message={errorMessage(error)} />);
68
- await terminate(usage ? EXIT.failed : EXIT.crashed);
69
- return false;
96
+ await terminate(EXIT.crashed);
70
97
  }
71
98
  };
@@ -1,11 +1,19 @@
1
- import { checkFiles } from './files.js';
1
+ import { replaceVariables } from '@mintlify/common';
2
+ import fs from 'node:fs/promises';
3
+ import path from 'node:path';
4
+
5
+ import { checkFiles, parseFile } from './files.js';
6
+ import { applyEdits, selectEdits, toPosition } from './mdx.js';
7
+ import { buildFindings } from './rules/build.js';
2
8
  import { RULES } from './rules/index.js';
3
9
  import { PARSE_ERROR } from './rules/parseError.js';
4
10
  import { loadSite } from './site.js';
5
11
  import {
6
12
  GROUPS,
13
+ type Change,
7
14
  type Diagnostic,
8
15
  type DiagnosticSource,
16
+ type FileEdit,
9
17
  type FileRule,
10
18
  type Finding,
11
19
  type Rule,
@@ -63,24 +71,126 @@ const sortDiagnostics = (diagnostics: Diagnostic[]) =>
63
71
  (RULE_ORDER.get(a.rule) ?? 0) - (RULE_ORDER.get(b.rule) ?? 0)
64
72
  );
65
73
 
66
- /** Runs every selected rule that doesn't need the build. */
67
- export const runChecks = async (site: Site, rules: Rule[]) => {
68
- const fileRules = rules.filter((rule): rule is FileRule => rule.scope === 'file');
69
- const diagnostics = await checkFiles(site, fileRules);
74
+ /** Adds findings for a rule unless a diagnostic of that rule already has the same key. */
75
+ const merge = (
76
+ diagnostics: Diagnostic[],
77
+ source: DiagnosticSource,
78
+ extra: Finding[],
79
+ key: (item: Pick<Diagnostic, 'file' | 'message'>) => string
80
+ ) => {
81
+ const reported = new Set(diagnostics.filter((item) => item.rule === source.id).map(key));
82
+ for (const finding of extra) {
83
+ if (reported.has(key(finding))) continue;
84
+ reported.add(key(finding));
85
+ diagnostics.push(toDiagnostic(source, finding));
86
+ }
87
+ };
88
+
89
+ const addParseErrors = (site: Site, diagnostics: Diagnostic[], extra: Finding[]) =>
90
+ merge(
91
+ diagnostics,
92
+ PARSE_ERROR,
93
+ extra.filter(({ file }) => !site.selected || site.selected.has(file)),
94
+ ({ file }) => file
95
+ );
70
96
 
97
+ const fileRulesOf = (rules: Rule[]) =>
98
+ rules.filter((rule): rule is FileRule => rule.scope === 'file');
99
+
100
+ const runSiteRules = async (
101
+ site: Site,
102
+ rules: Rule[],
103
+ needsBuild: boolean,
104
+ diagnostics: Diagnostic[]
105
+ ) => {
71
106
  for (const rule of rules) {
72
- if (rule.scope !== 'site' || rule.needsBuild) continue;
107
+ if (rule.scope !== 'site' || Boolean(rule.needsBuild) !== needsBuild) continue;
73
108
  for (const finding of await rule.check(site)) diagnostics.push(toDiagnostic(rule, finding));
74
109
  }
110
+ };
111
+
112
+ /** Runs every selected rule that doesn't need the build. */
113
+ export const runChecks = async (site: Site, rules: Rule[]) => {
114
+ const diagnostics = await checkFiles(site, fileRulesOf(rules));
115
+ await runSiteRules(site, rules, false, diagnostics);
116
+ return sortDiagnostics(diagnostics);
117
+ };
118
+
119
+ /** Adds the build's findings to a site whose build has run. */
120
+ export const runBuildChecks = async (site: Site, rules: Rule[], diagnostics: Diagnostic[]) => {
121
+ await runSiteRules(site, rules, true, diagnostics);
122
+ // The file pass already reported files it couldn't parse; the build adds the rest
123
+ addParseErrors(site, diagnostics, buildFindings(site, 'parse-error'));
75
124
  return sortDiagnostics(diagnostics);
76
125
  };
77
126
 
78
- /** Loads the site and runs the selected rules. */
127
+ const parseLevel = (file: string, content: string, baseDir: string) => {
128
+ const parsed = parseFile(file, content, baseDir);
129
+ return 'error' in parsed ? 0 : parsed.approximate ? 1 : 2;
130
+ };
131
+
132
+ /** 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. */
133
+ export const applyFixes = async (site: Site, diagnostics: Diagnostic[]): Promise<Change[]> => {
134
+ const contents = new Map<string, string>();
135
+ const read = async (file: string) => {
136
+ if (!contents.has(file)) {
137
+ contents.set(file, await fs.readFile(path.join(site.baseDir, file), 'utf-8'));
138
+ }
139
+ return contents.get(file) ?? '';
140
+ };
141
+ const chosen = new Map<string, { fix: FileEdit; change: Change }[]>();
142
+ const overlaps = ({ file, start, end }: FileEdit) =>
143
+ (chosen.get(file) ?? []).some(({ fix }) => start < fix.end && fix.start < end);
144
+
145
+ for (const { rule, fix } of diagnostics) {
146
+ if (!fix || overlaps(fix)) continue;
147
+ const content = await read(fix.file);
148
+ const change = {
149
+ rule,
150
+ file: fix.file,
151
+ ...toPosition(content, fix.start),
152
+ before: content.slice(fix.start, fix.end),
153
+ after: fix.text,
154
+ };
155
+ chosen.set(fix.file, [...(chosen.get(fix.file) ?? []), { fix, change }]);
156
+ }
157
+
158
+ const snippets = new Set(
159
+ site.files.filter(({ kind }) => kind === 'snippet').map(({ file }) => file)
160
+ );
161
+ const level = (file: string, content: string) =>
162
+ parseLevel(
163
+ file,
164
+ snippets.has(file) ? replaceVariables(content, site.variables) : content,
165
+ site.baseDir
166
+ );
167
+
168
+ const applied: Change[] = [];
169
+ for (const [file, picks] of chosen) {
170
+ const content = await read(file);
171
+ const updated = applyEdits(content, selectEdits(picks.map(({ fix }) => fix)));
172
+ if (/\.mdx?$/.test(file) && level(file, updated) < level(file, content)) {
173
+ continue;
174
+ }
175
+ await fs.writeFile(path.join(site.baseDir, file), updated);
176
+ applied.push(...picks.map(({ change }) => change));
177
+ }
178
+ return applied;
179
+ };
180
+
181
+ // Fixes can unlock others (a self-closed <br> lets a page parse), so --fix runs a few passes
182
+ const MAX_FIX_PASSES = 5;
183
+
184
+ /**
185
+ * Loads the site and runs the selected rules. With fix, applies the fixes, rechecks only the
186
+ * files that changed for further fixes, then runs every rule once more for the final report.
187
+ */
79
188
  export const checkSite = async (
80
189
  baseDir: string,
81
190
  rules: Rule[],
82
- options: { selected?: ReadonlySet<string>; localSchema: boolean }
191
+ options: { selected?: ReadonlySet<string>; localSchema: boolean; fix: boolean }
83
192
  ) => {
193
+ const fixed: Change[] = [];
84
194
  const site = await loadSite(baseDir, options);
85
195
  const { selected } = options;
86
196
  if (selected && !site.files.some(({ file }) => selected.has(file))) {
@@ -89,5 +199,18 @@ export const checkSite = async (
89
199
  );
90
200
  }
91
201
  const diagnostics = await runChecks(site, rules);
92
- return { site, diagnostics };
202
+ if (!options.fix) return { site, diagnostics, fixed };
203
+
204
+ // Only file rules offer fixes, so passes after the first recheck just the files that changed
205
+ let pending = diagnostics;
206
+ for (let pass = 0; pass < MAX_FIX_PASSES; pass++) {
207
+ const changes = await applyFixes(site, pending);
208
+ if (changes.length === 0) break;
209
+ fixed.push(...changes);
210
+ const changed = new Set(changes.map(({ file }) => file));
211
+ pending = sortDiagnostics(await checkFiles({ ...site, selected: changed }, fileRulesOf(rules)));
212
+ }
213
+ if (fixed.length === 0) return { site, diagnostics, fixed };
214
+ const fixedSite = await loadSite(baseDir, options);
215
+ return { site: fixedSite, diagnostics: await runChecks(fixedSite, rules), fixed };
93
216
  };
@@ -99,7 +99,7 @@ const tryParseContent = (content: string): Root | undefined => {
99
99
  }
100
100
  };
101
101
 
102
- const parseFile = (file: string, content: string, baseDir: string): Parsed => {
102
+ export const parseFile = (file: string, content: string, baseDir: string): Parsed => {
103
103
  const context = { file, content, baseDir, frontmatter: readFrontmatter(content) };
104
104
  const tree = tryParseContent(content);
105
105
  if (tree) return { context: { ...context, tree }, approximate: false };
@@ -1,8 +1,14 @@
1
- import { addLog, ErrorLog } from '@mintlify/previewing';
1
+ import { addLog, ErrorLog, InfoLog, SuccessLog } from '@mintlify/previewing';
2
2
  import { Box, Text } from 'ink';
3
3
 
4
+ import type { Report } from './report.js';
4
5
  import type { Diagnostic } from './types.js';
5
6
 
7
+ const preview = (value: string) => {
8
+ const text = JSON.stringify(value);
9
+ return text.length > 60 ? `${text.slice(0, 57)}..."` : text;
10
+ };
11
+
6
12
  const location = ({ line, column }: Pick<Diagnostic, 'line' | 'column'>) =>
7
13
  line ? `${line}${column ? `:${column}` : ''}` : '';
8
14
 
@@ -25,9 +31,17 @@ const DiagnosticLine = ({ diagnostic }: { diagnostic: Diagnostic }) => {
25
31
 
26
32
  const plural = (count: number, word: string) => `${count} ${word}${count === 1 ? '' : 's'}`;
27
33
 
28
- export const logDiagnostics = (all: Diagnostic[]) => {
34
+ export const logReport = (report: Report) => {
35
+ for (const change of report.fixed ?? []) {
36
+ addLog(
37
+ <SuccessLog
38
+ message={`fixed ${change.file}${change.line ? `:${change.line}` : ''} ${change.rule}: ${preview(change.before)} → ${preview(change.after)}`}
39
+ />
40
+ );
41
+ }
42
+
29
43
  const byFile = new Map<string, Diagnostic[]>();
30
- for (const diagnostic of all) {
44
+ for (const diagnostic of report.diagnostics) {
31
45
  byFile.get(diagnostic.file)?.push(diagnostic) ?? byFile.set(diagnostic.file, [diagnostic]);
32
46
  }
33
47
  for (const [file, diagnostics] of byFile) {
@@ -41,16 +55,22 @@ export const logDiagnostics = (all: Diagnostic[]) => {
41
55
  );
42
56
  }
43
57
 
44
- const errors = all.filter(({ severity }) => severity === 'error').length;
45
- const warnings = all.length - errors;
46
- if (errors > 0) {
47
- addLog(
48
- <ErrorLog
49
- message={`${plural(errors, 'error')}${warnings > 0 ? `, ${plural(warnings, 'warning')}` : ''}`}
50
- />
51
- );
52
- } else if (warnings > 0) {
53
- addLog(<Text dimColor>{plural(warnings, 'warning')}</Text>);
58
+ const fixable = report.diagnostics.filter(({ fix }) => fix).length;
59
+ if (fixable > 0 && !report.fixed) {
60
+ addLog(<InfoLog message={`\`--fix\` would fix ${plural(fixable, 'issue')}.`} />);
54
61
  }
55
- return errors > 0;
62
+
63
+ const { build } = report;
64
+ if (build.ran && build.passed) addLog(<SuccessLog message="build passed" />);
65
+ else if (build.ran && report.passed)
66
+ addLog(<InfoLog message="build failed only on disabled rules" />);
67
+ else if (build.ran) addLog(<ErrorLog message="build failed" />);
68
+ else if (build.reason === 'errors found')
69
+ addLog(<InfoLog message="build skipped until the errors above are fixed" />);
70
+
71
+ const { errors, warnings } = report.summary;
72
+ const warned = plural(warnings, 'warning');
73
+ const passed = warnings > 0 ? `passed with ${warned}` : 'validation passed';
74
+ const failed = `${plural(errors, 'error')}${warnings > 0 ? `, ${warned}` : ''}`;
75
+ addLog(report.passed ? <SuccessLog message={passed} /> : <ErrorLog message={failed} />);
56
76
  };
@@ -0,0 +1,40 @@
1
+ import type { Change, Diagnostic } from './types.js';
2
+
3
+ export type BuildStatus =
4
+ | { ran: true; passed: boolean }
5
+ | { ran: false; reason: 'disabled' | 'errors found' | 'no build rules' };
6
+
7
+ export type Report = {
8
+ passed: boolean;
9
+ summary: { errors: number; warnings: number; byRule: Record<string, number> };
10
+ diagnostics: Diagnostic[];
11
+ build: BuildStatus;
12
+ /** With --fix: the edits that were applied. */
13
+ fixed?: Change[];
14
+ };
15
+
16
+ export const toReport = (
17
+ diagnostics: Diagnostic[],
18
+ build: BuildStatus,
19
+ fixed?: Change[]
20
+ ): Report => {
21
+ const byRule: Record<string, number> = {};
22
+ for (const { rule } of diagnostics) byRule[rule] = (byRule[rule] ?? 0) + 1;
23
+ const errors = diagnostics.filter(({ severity }) => severity === 'error').length;
24
+ return {
25
+ passed: errors === 0,
26
+ summary: { errors, warnings: diagnostics.length - errors, byRule },
27
+ diagnostics: diagnostics.map(({ rule, group, severity, file, line, column, message, fix }) => ({
28
+ rule,
29
+ group,
30
+ severity,
31
+ file,
32
+ ...(line !== undefined && { line }),
33
+ ...(column !== undefined && { column }),
34
+ message,
35
+ ...(fix && { fix }),
36
+ })),
37
+ build,
38
+ ...(fixed && { fixed }),
39
+ };
40
+ };
@@ -0,0 +1,132 @@
1
+ import { normalizeRelativePath, toPosixPath } from '@mintlify/common';
2
+ import type { Warning } from '@mintlify/prebuild';
3
+ import { stripVTControlCharacters } from 'node:util';
4
+
5
+ import type { Finding, Group, Site, SiteRule } from '../types.js';
6
+
7
+ const FILE = String.raw`[\w@.\\/-]+\.(?:mdx?|jsx?|tsx?|json|ya?ml)\b`;
8
+
9
+ const FILE_IN_MESSAGE = new RegExp(FILE);
10
+
11
+ const IMPORTERS = [
12
+ new RegExp(String.raw`\(in (${FILE}),`),
13
+ new RegExp(String.raw`(?:\bin|imported from) (${FILE})`),
14
+ ];
15
+
16
+ const IMPORT_TYPES = new Set<Warning['type']>([
17
+ 'missing-file',
18
+ 'invalid-import-path',
19
+ 'import-resolution-error',
20
+ 'default-import-no-default-export',
21
+ 'export-collision',
22
+ 'undeclared-package',
23
+ 'package-import-conflict',
24
+ ]);
25
+
26
+ const POSITION = /^:(\d+)(?::(\d+))?/;
27
+
28
+ const QUOTED = /"([^"]+)"/;
29
+
30
+ const toFinding = (site: Site, { type, message }: Warning): Finding => {
31
+ const clean = stripVTControlCharacters(message).trim();
32
+ const importer = IMPORT_TYPES.has(type)
33
+ ? IMPORTERS.map((pattern) => pattern.exec(clean)?.[1]).find(Boolean)
34
+ : undefined;
35
+ // Missing nav pages are always about the config, even when the page looks like a file
36
+ const match = importer || type === 'missing-nav-page' ? null : FILE_IN_MESSAGE.exec(clean);
37
+ const found = importer ?? match?.[0];
38
+ const file = found ? normalizeRelativePath(toPosixPath(found)) : site.configFile;
39
+ const position = match ? POSITION.exec(clean.slice(match.index + match[0].length)) : null;
40
+ // Config warnings quote the entry they're about, such as a navigation page
41
+ const quoted = file === site.configFile ? QUOTED.exec(clean)?.[0] : undefined;
42
+ return {
43
+ file,
44
+ ...(position && {
45
+ line: Number(position[1]),
46
+ ...(position[2] && { column: Number(position[2]) }),
47
+ }),
48
+ ...(quoted && site.locate(file, quoted)),
49
+ message: clean,
50
+ };
51
+ };
52
+
53
+ /** Warning types some rule turns into diagnostics, so a strict-build failure is explained. */
54
+ const COVERED_TYPES = new Set<Warning['type']>(['parse-error']);
55
+
56
+ const buildRule = (
57
+ id: string,
58
+ group: Group,
59
+ types: Warning['type'][],
60
+ description: string
61
+ ): SiteRule => {
62
+ for (const type of types) COVERED_TYPES.add(type);
63
+ return {
64
+ id,
65
+ group,
66
+ severity: 'error',
67
+ needsBuild: true,
68
+ scope: 'site',
69
+ description,
70
+ check: (site) =>
71
+ (site.build?.warnings ?? [])
72
+ .filter(({ type }) => types.includes(type))
73
+ .map((warning) => toFinding(site, warning)),
74
+ };
75
+ };
76
+
77
+ export const BUILD_RULES: SiteRule[] = [
78
+ buildRule(
79
+ 'missing-nav-page',
80
+ 'nav',
81
+ ['missing-nav-page'],
82
+ 'pages in the navigation that have no file'
83
+ ),
84
+ buildRule('missing-file', 'content', ['missing-file'], "imported files that don't exist"),
85
+ buildRule(
86
+ 'import-error',
87
+ 'content',
88
+ [
89
+ 'invalid-import-path',
90
+ 'import-resolution-error',
91
+ 'default-import-no-default-export',
92
+ 'export-collision',
93
+ ],
94
+ "imports in pages and snippets that don't resolve"
95
+ ),
96
+ buildRule(
97
+ 'package-import',
98
+ 'config',
99
+ ['undeclared-package', 'package-import-conflict'],
100
+ 'npm package imports that are undeclared or conflict'
101
+ ),
102
+ buildRule('openapi-build', 'openapi', ['openapi'], 'OpenAPI pages the build could not generate'),
103
+ {
104
+ id: 'build-failed',
105
+ group: 'config',
106
+ severity: 'error',
107
+ needsBuild: true,
108
+ scope: 'site',
109
+ description: 'the strict build failed for a reason no rule reports',
110
+ check: (site) => {
111
+ if (!site.build || site.build.passed) return [];
112
+ const unreported = (warning: Warning) =>
113
+ warning.type === 'parse-error' &&
114
+ site.selected !== undefined &&
115
+ !site.selected.has(toFinding(site, warning).file);
116
+ const uncovered = site.build.warnings.filter(
117
+ (warning) => !COVERED_TYPES.has(warning.type) || unreported(warning)
118
+ );
119
+ const findings = uncovered.map((warning) => toFinding(site, warning));
120
+ // Covered warnings are the selected rules' to report; disabled ones are meant to pass
121
+ return site.build.strict
122
+ ? findings
123
+ : [...findings, { file: site.configFile, message: site.build.error }];
124
+ },
125
+ },
126
+ ];
127
+
128
+ /** Build warnings of one type, which the engine merges into the static rule that covers them. */
129
+ export const buildFindings = (site: Site, type: Warning['type']): Finding[] =>
130
+ (site.build?.warnings ?? [])
131
+ .filter((warning) => warning.type === type)
132
+ .map((warning) => toFinding(site, warning));
@@ -1,5 +1,7 @@
1
1
  import type { Rule } from '../types.js';
2
+ import { BUILD_RULES } from './build.js';
2
3
  import { voidTags } from './content/voidTags.js';
4
+ import { openApiSpec } from './openapi.js';
3
5
 
4
6
  /** Every check mint validate runs, in report order. */
5
- export const RULES: Rule[] = [voidTags];
7
+ export const RULES: Rule[] = [voidTags, openApiSpec, ...BUILD_RULES];
@@ -0,0 +1,59 @@
1
+ import fs from 'node:fs/promises';
2
+ import path from 'node:path';
3
+
4
+ import { errorMessage } from '../../helpers.js';
5
+ import {
6
+ buildOverlayRegistryForCheck,
7
+ checkOpenApiFile,
8
+ getOpenApiFilenamesFromDocsConfig,
9
+ type OpenApiCheckMessage,
10
+ } from '../../openApiCheck.js';
11
+ import type { Finding, SiteRule } from '../types.js';
12
+
13
+ export const openApiSpec: SiteRule = {
14
+ id: 'openapi-spec',
15
+ group: 'openapi',
16
+ severity: 'error',
17
+ scope: 'site',
18
+ description:
19
+ "OpenAPI specs in docs.json or mint.json that don't parse or validate, with overlays applied",
20
+ check: async (site) => {
21
+ let filenames: string[] = [];
22
+ try {
23
+ const config = JSON.parse(
24
+ await fs.readFile(path.join(site.baseDir, site.configFile), 'utf-8')
25
+ );
26
+ // mint.json lists its specs under a top-level openapi key
27
+ filenames = getOpenApiFilenamesFromDocsConfig(
28
+ site.configFile === 'mint.json' ? { api: { openapi: config.openapi } } : config
29
+ );
30
+ } catch {
31
+ // A missing or invalid config file is the build's to report
32
+ }
33
+ if (filenames.length === 0) return [];
34
+
35
+ let overlayRegistry;
36
+ try {
37
+ overlayRegistry = await buildOverlayRegistryForCheck(site.localSchema);
38
+ } catch (error) {
39
+ return [{ file: site.configFile, message: `OpenAPI overlays: ${errorMessage(error)}` }];
40
+ }
41
+
42
+ const perFile = await Promise.all(
43
+ filenames.map(async (file) => {
44
+ const messages: OpenApiCheckMessage[] = [];
45
+ await checkOpenApiFile(file, site.localSchema, overlayRegistry, (message) =>
46
+ messages.push(message)
47
+ );
48
+ return messages.flatMap(({ level, message }): Finding[] =>
49
+ level === 'error'
50
+ ? [{ file, message }]
51
+ : level === 'warning'
52
+ ? [{ file, message, severity: 'warning' }]
53
+ : []
54
+ );
55
+ })
56
+ );
57
+ return perFile.flat();
58
+ },
59
+ };
@@ -11,6 +11,16 @@ export type Edit = { start: number; end: number; text: string };
11
11
 
12
12
  export type FileEdit = Edit & { file: string };
13
13
 
14
+ /** A fix --fix applied: where it was and the text it replaced. */
15
+ export type Change = {
16
+ rule: string;
17
+ file: string;
18
+ line?: number;
19
+ column?: number;
20
+ before: string;
21
+ after: string;
22
+ };
23
+
14
24
  export type Diagnostic = {
15
25
  rule: string;
16
26
  group: Group;