madr-lint 0.1.0 → 0.3.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/CHANGELOG.md +46 -0
- package/README.md +21 -2
- package/dist/cli.js +636 -85
- package/dist/cli.js.map +1 -1
- package/dist/index.d.ts +122 -10
- package/dist/index.js +373 -43
- package/dist/index.js.map +1 -1
- package/package.json +4 -3
package/dist/cli.js
CHANGED
|
@@ -6,14 +6,153 @@ var __export = (target, all) => {
|
|
|
6
6
|
};
|
|
7
7
|
|
|
8
8
|
// src/cli.ts
|
|
9
|
-
import { readFileSync as
|
|
9
|
+
import { existsSync as existsSync5, readFileSync as readFileSync5 } from "fs";
|
|
10
10
|
import { relative as relative2, resolve as resolve3, sep as sep2 } from "path";
|
|
11
11
|
import { defineCommand, runMain } from "citty";
|
|
12
12
|
|
|
13
|
-
// src/core/
|
|
14
|
-
import { createHash } from "crypto";
|
|
13
|
+
// src/core/baseline.ts
|
|
15
14
|
import { existsSync, mkdirSync, readFileSync, writeFileSync } from "fs";
|
|
16
15
|
import { dirname, join } from "path";
|
|
16
|
+
|
|
17
|
+
// src/core/types.ts
|
|
18
|
+
var INTERNAL_ERROR_RULE_NAME = "core/internal-error";
|
|
19
|
+
function isProjectRule(rule9) {
|
|
20
|
+
return "check" in rule9;
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
// src/core/baseline.ts
|
|
24
|
+
var BASELINE_VERSION = 1;
|
|
25
|
+
var BASELINE_DISPLAY_PATH = ".madr-lint/baseline.json";
|
|
26
|
+
function baselinePath(cwd) {
|
|
27
|
+
return join(cwd, ".madr-lint", "baseline.json");
|
|
28
|
+
}
|
|
29
|
+
function nullProtoMap() {
|
|
30
|
+
return /* @__PURE__ */ Object.create(null);
|
|
31
|
+
}
|
|
32
|
+
function buildBaseline(diagnostics) {
|
|
33
|
+
const entries = nullProtoMap();
|
|
34
|
+
for (const d of diagnostics) {
|
|
35
|
+
if (d.ruleName === INTERNAL_ERROR_RULE_NAME) continue;
|
|
36
|
+
const byRule = entries[d.path] ??= nullProtoMap();
|
|
37
|
+
const byMessage = byRule[d.ruleName] ??= nullProtoMap();
|
|
38
|
+
byMessage[d.messageId] = (byMessage[d.messageId] ?? 0) + 1;
|
|
39
|
+
}
|
|
40
|
+
return { version: BASELINE_VERSION, entries };
|
|
41
|
+
}
|
|
42
|
+
function serializeBaseline(baseline) {
|
|
43
|
+
const sortedEntries = nullProtoMap();
|
|
44
|
+
for (const path of Object.keys(baseline.entries).toSorted()) {
|
|
45
|
+
const byRule = baseline.entries[path] ?? {};
|
|
46
|
+
const sortedByRule = nullProtoMap();
|
|
47
|
+
for (const rule9 of Object.keys(byRule).toSorted()) {
|
|
48
|
+
const byMessage = byRule[rule9] ?? {};
|
|
49
|
+
const sortedByMessage = nullProtoMap();
|
|
50
|
+
for (const messageId of Object.keys(byMessage).toSorted()) {
|
|
51
|
+
sortedByMessage[messageId] = byMessage[messageId] ?? 0;
|
|
52
|
+
}
|
|
53
|
+
sortedByRule[rule9] = sortedByMessage;
|
|
54
|
+
}
|
|
55
|
+
sortedEntries[path] = sortedByRule;
|
|
56
|
+
}
|
|
57
|
+
const ordered = { version: baseline.version, entries: sortedEntries };
|
|
58
|
+
return JSON.stringify(ordered, null, 2) + "\n";
|
|
59
|
+
}
|
|
60
|
+
function loadBaseline(path) {
|
|
61
|
+
if (!existsSync(path)) return null;
|
|
62
|
+
try {
|
|
63
|
+
const data = JSON.parse(readFileSync(path, "utf8"));
|
|
64
|
+
if (typeof data.entries !== "object" || data.entries === null) return null;
|
|
65
|
+
return {
|
|
66
|
+
version: typeof data.version === "number" ? data.version : BASELINE_VERSION,
|
|
67
|
+
entries: rebuildEntries(data.entries)
|
|
68
|
+
};
|
|
69
|
+
} catch {
|
|
70
|
+
return null;
|
|
71
|
+
}
|
|
72
|
+
}
|
|
73
|
+
function rebuildEntries(raw) {
|
|
74
|
+
const entries = nullProtoMap();
|
|
75
|
+
for (const [path, rawByRule] of Object.entries(raw)) {
|
|
76
|
+
if (typeof rawByRule !== "object" || rawByRule === null) continue;
|
|
77
|
+
const byRule = nullProtoMap();
|
|
78
|
+
for (const [rule9, rawByMessage] of Object.entries(rawByRule)) {
|
|
79
|
+
if (typeof rawByMessage !== "object" || rawByMessage === null) continue;
|
|
80
|
+
const byMessage = nullProtoMap();
|
|
81
|
+
for (const [messageId, count] of Object.entries(
|
|
82
|
+
rawByMessage
|
|
83
|
+
)) {
|
|
84
|
+
if (typeof count === "number") byMessage[messageId] = count;
|
|
85
|
+
}
|
|
86
|
+
byRule[rule9] = byMessage;
|
|
87
|
+
}
|
|
88
|
+
entries[path] = byRule;
|
|
89
|
+
}
|
|
90
|
+
return entries;
|
|
91
|
+
}
|
|
92
|
+
function writeBaseline(path, baseline) {
|
|
93
|
+
mkdirSync(dirname(path), { recursive: true });
|
|
94
|
+
writeFileSync(path, serializeBaseline(baseline), "utf8");
|
|
95
|
+
}
|
|
96
|
+
var KEY_SEP = "\0";
|
|
97
|
+
function fingerprint(d) {
|
|
98
|
+
return d.path + KEY_SEP + d.ruleName + KEY_SEP + d.messageId;
|
|
99
|
+
}
|
|
100
|
+
function applyBaseline(diagnostics, baseline) {
|
|
101
|
+
const remaining = /* @__PURE__ */ new Map();
|
|
102
|
+
for (const [path, byRule] of Object.entries(baseline.entries)) {
|
|
103
|
+
for (const [rule9, byMessage] of Object.entries(byRule)) {
|
|
104
|
+
if (rule9 === INTERNAL_ERROR_RULE_NAME) continue;
|
|
105
|
+
for (const [messageId, count] of Object.entries(byMessage)) {
|
|
106
|
+
remaining.set(path + KEY_SEP + rule9 + KEY_SEP + messageId, count);
|
|
107
|
+
}
|
|
108
|
+
}
|
|
109
|
+
}
|
|
110
|
+
const kept = [];
|
|
111
|
+
let hidden = 0;
|
|
112
|
+
for (const d of diagnostics) {
|
|
113
|
+
if (d.ruleName === INTERNAL_ERROR_RULE_NAME) {
|
|
114
|
+
kept.push(d);
|
|
115
|
+
continue;
|
|
116
|
+
}
|
|
117
|
+
const key = fingerprint(d);
|
|
118
|
+
const left = remaining.get(key);
|
|
119
|
+
if (left !== void 0 && left > 0) {
|
|
120
|
+
remaining.set(key, left - 1);
|
|
121
|
+
hidden++;
|
|
122
|
+
} else {
|
|
123
|
+
kept.push(d);
|
|
124
|
+
}
|
|
125
|
+
}
|
|
126
|
+
return { kept, hidden };
|
|
127
|
+
}
|
|
128
|
+
function totalCount(baseline) {
|
|
129
|
+
let total = 0;
|
|
130
|
+
for (const byRule of Object.values(baseline.entries)) {
|
|
131
|
+
for (const byMessage of Object.values(byRule)) {
|
|
132
|
+
for (const count of Object.values(byMessage)) total += count;
|
|
133
|
+
}
|
|
134
|
+
}
|
|
135
|
+
return total;
|
|
136
|
+
}
|
|
137
|
+
function baselineWriteSummary(baseline) {
|
|
138
|
+
const violations = totalCount(baseline);
|
|
139
|
+
const files = Object.keys(baseline.entries).length;
|
|
140
|
+
const v = `${violations} ${violations === 1 ? "violation" : "violations"}`;
|
|
141
|
+
const f = `${files} ${files === 1 ? "file" : "files"}`;
|
|
142
|
+
return `Wrote ${v} across ${f} to ${BASELINE_DISPLAY_PATH}`;
|
|
143
|
+
}
|
|
144
|
+
function baselineMalformedWarning() {
|
|
145
|
+
return `madr-lint: warning: ${BASELINE_DISPLAY_PATH} is malformed; ignoring it (run --update-baseline to regenerate)`;
|
|
146
|
+
}
|
|
147
|
+
function baselineHiddenSummary(hidden) {
|
|
148
|
+
return `${hidden} ${hidden === 1 ? "problem" : "problems"} hidden by baseline (${BASELINE_DISPLAY_PATH})`;
|
|
149
|
+
}
|
|
150
|
+
|
|
151
|
+
// src/core/cache.ts
|
|
152
|
+
import { createHash } from "crypto";
|
|
153
|
+
import { existsSync as existsSync2, mkdirSync as mkdirSync2, readFileSync as readFileSync2, writeFileSync as writeFileSync2 } from "fs";
|
|
154
|
+
import { dirname as dirname2, join as join2 } from "path";
|
|
155
|
+
var CACHE_SCHEMA_VERSION = 2;
|
|
17
156
|
function computeContentHash(content) {
|
|
18
157
|
return createHash("sha1").update(content, "utf8").digest("hex");
|
|
19
158
|
}
|
|
@@ -33,13 +172,18 @@ function stableStringify(value) {
|
|
|
33
172
|
return "{" + entries.map(([k, v]) => JSON.stringify(k) + ":" + stableStringify(v)).join(",") + "}";
|
|
34
173
|
}
|
|
35
174
|
function manifestPath(cacheDir) {
|
|
36
|
-
return
|
|
175
|
+
return join2(cacheDir, "manifest.json");
|
|
37
176
|
}
|
|
38
177
|
function loadManifest(path) {
|
|
39
|
-
if (!
|
|
178
|
+
if (!existsSync2(path)) return null;
|
|
40
179
|
try {
|
|
41
|
-
const data = JSON.parse(
|
|
42
|
-
if (
|
|
180
|
+
const data = JSON.parse(readFileSync2(path, "utf8"));
|
|
181
|
+
if (
|
|
182
|
+
// Single invalidation point for schema drift: an unknown (or absent)
|
|
183
|
+
// schema version nulls here, so every consumer sees a cold cache — no
|
|
184
|
+
// scattered re-hydration of stale-shape entries downstream.
|
|
185
|
+
data.schemaVersion !== CACHE_SCHEMA_VERSION || typeof data.version !== "string" || typeof data.configHash !== "string" || typeof data.files !== "object" || data.files === null
|
|
186
|
+
) {
|
|
43
187
|
return null;
|
|
44
188
|
}
|
|
45
189
|
return data;
|
|
@@ -48,12 +192,12 @@ function loadManifest(path) {
|
|
|
48
192
|
}
|
|
49
193
|
}
|
|
50
194
|
function saveManifest(path, manifest) {
|
|
51
|
-
|
|
52
|
-
|
|
195
|
+
mkdirSync2(dirname2(path), { recursive: true });
|
|
196
|
+
writeFileSync2(path, JSON.stringify(manifest), "utf8");
|
|
53
197
|
}
|
|
54
198
|
|
|
55
199
|
// src/core/config.ts
|
|
56
|
-
import { existsSync as
|
|
200
|
+
import { existsSync as existsSync3, readFileSync as readFileSync3 } from "fs";
|
|
57
201
|
import { resolve } from "path";
|
|
58
202
|
import { createJiti } from "jiti";
|
|
59
203
|
|
|
@@ -64,7 +208,7 @@ var recommended = {
|
|
|
64
208
|
"madr/no-broken-links": "error",
|
|
65
209
|
"madr/no-duplicate-numbering": "error",
|
|
66
210
|
// Convention-only — opt in if your team treats ADR numbering as a
|
|
67
|
-
// contiguous sequence. See
|
|
211
|
+
// contiguous sequence. See https://knktkc.github.io/madr-lint/rules/no-numbering-gap/.
|
|
68
212
|
"madr/no-numbering-gap": "off",
|
|
69
213
|
"madr/required-sections": "error",
|
|
70
214
|
"madr/status-enum": "error",
|
|
@@ -85,12 +229,43 @@ var CONFIG_FILES = [
|
|
|
85
229
|
"madr-lint.config.mjs",
|
|
86
230
|
"madr-lint.config.cjs"
|
|
87
231
|
];
|
|
232
|
+
var ConfigFileNotFoundError = class extends Error {
|
|
233
|
+
constructor(message) {
|
|
234
|
+
super(message);
|
|
235
|
+
this.name = "ConfigFileNotFoundError";
|
|
236
|
+
}
|
|
237
|
+
};
|
|
238
|
+
function loadConfigFromPath(filePath) {
|
|
239
|
+
let raw;
|
|
240
|
+
try {
|
|
241
|
+
raw = readFileSync3(filePath, "utf8");
|
|
242
|
+
} catch (err) {
|
|
243
|
+
const code = err.code;
|
|
244
|
+
if (code === "ENOENT") {
|
|
245
|
+
throw new ConfigFileNotFoundError(`Config file not found: ${filePath}`);
|
|
246
|
+
}
|
|
247
|
+
if (code === "EISDIR") {
|
|
248
|
+
throw new ConfigFileNotFoundError(
|
|
249
|
+
`Config path is a directory, not a file: ${filePath}`
|
|
250
|
+
);
|
|
251
|
+
}
|
|
252
|
+
throw err;
|
|
253
|
+
}
|
|
254
|
+
if (filePath.endsWith(".json")) {
|
|
255
|
+
const parsed = JSON.parse(raw);
|
|
256
|
+
return resolveExtends(parsed);
|
|
257
|
+
}
|
|
258
|
+
const jiti = createJiti(import.meta.url, { interopDefault: true });
|
|
259
|
+
const loaded = jiti(filePath);
|
|
260
|
+
const config = typeof loaded === "object" && loaded !== null && "default" in loaded ? loaded.default : loaded;
|
|
261
|
+
return resolveExtends(config);
|
|
262
|
+
}
|
|
88
263
|
function loadConfig(cwd) {
|
|
89
264
|
for (const name of CONFIG_FILES) {
|
|
90
265
|
const path = resolve(cwd, name);
|
|
91
|
-
if (!
|
|
266
|
+
if (!existsSync3(path)) continue;
|
|
92
267
|
if (name.endsWith(".json")) {
|
|
93
|
-
const parsed = JSON.parse(
|
|
268
|
+
const parsed = JSON.parse(readFileSync3(path, "utf8"));
|
|
94
269
|
return resolveExtends(parsed);
|
|
95
270
|
}
|
|
96
271
|
const jiti = createJiti(import.meta.url, { interopDefault: true });
|
|
@@ -115,17 +290,17 @@ function resolveExtends(config) {
|
|
|
115
290
|
}
|
|
116
291
|
|
|
117
292
|
// src/core/discover.ts
|
|
118
|
-
import { existsSync as
|
|
119
|
-
import { join as
|
|
293
|
+
import { existsSync as existsSync4, readdirSync, statSync } from "fs";
|
|
294
|
+
import { join as join3 } from "path";
|
|
120
295
|
function findAdrFiles(target) {
|
|
121
|
-
if (!
|
|
296
|
+
if (!existsSync4(target)) return [];
|
|
122
297
|
const stat = statSync(target);
|
|
123
298
|
if (stat.isFile()) {
|
|
124
299
|
return target.endsWith(".md") ? [target] : [];
|
|
125
300
|
}
|
|
126
301
|
if (!stat.isDirectory()) return [];
|
|
127
302
|
const entries = readdirSync(target, { recursive: true, withFileTypes: true });
|
|
128
|
-
return entries.filter((e) => e.isFile() && e.name.endsWith(".md")).map((e) =>
|
|
303
|
+
return entries.filter((e) => e.isFile() && e.name.endsWith(".md")).map((e) => join3(e.parentPath, e.name)).toSorted();
|
|
129
304
|
}
|
|
130
305
|
|
|
131
306
|
// src/core/ignore.ts
|
|
@@ -152,12 +327,21 @@ function matchesPattern(relativePath, base, pattern) {
|
|
|
152
327
|
}
|
|
153
328
|
|
|
154
329
|
// src/core/lint.ts
|
|
155
|
-
import { readFileSync as
|
|
330
|
+
import { readFileSync as readFileSync4, statSync as statSync2 } from "fs";
|
|
156
331
|
import { isAbsolute, relative, resolve as resolve2, sep } from "path";
|
|
157
332
|
|
|
158
333
|
// src/core/runner.ts
|
|
159
334
|
import Ajv from "ajv";
|
|
160
335
|
|
|
336
|
+
// src/core/interpolate.ts
|
|
337
|
+
function interpolate(template, data) {
|
|
338
|
+
if (!template.includes("{{")) return template;
|
|
339
|
+
return template.replace(/\{\{(\w+)\}\}/g, (_, key) => {
|
|
340
|
+
const v = data[key];
|
|
341
|
+
return v !== void 0 ? String(v) : `{{${key}}}`;
|
|
342
|
+
});
|
|
343
|
+
}
|
|
344
|
+
|
|
161
345
|
// src/core/parser.ts
|
|
162
346
|
import { fromMarkdown } from "mdast-util-from-markdown";
|
|
163
347
|
import { toString } from "mdast-util-to-string";
|
|
@@ -167,20 +351,33 @@ function parseFile(content) {
|
|
|
167
351
|
const data = matter.data;
|
|
168
352
|
const frontmatter = Object.keys(data).length > 0 ? data : null;
|
|
169
353
|
const ast = fromMarkdown(matter.content);
|
|
170
|
-
const
|
|
354
|
+
const listResult = extractListMetadataWithLoc(ast);
|
|
355
|
+
const listMetadata = listResult?.values ?? null;
|
|
171
356
|
let metadata = null;
|
|
357
|
+
let metadataLoc = listResult && Object.keys(listResult.loc).length > 0 ? { ...listResult.loc } : null;
|
|
172
358
|
if (frontmatter && listMetadata) {
|
|
173
359
|
const frontmatterDefined = {};
|
|
174
360
|
for (const [k, v] of Object.entries(frontmatter)) {
|
|
175
361
|
if (v !== null && v !== void 0) frontmatterDefined[k] = v;
|
|
176
362
|
}
|
|
177
363
|
metadata = { ...listMetadata, ...frontmatterDefined };
|
|
364
|
+
if (metadataLoc) {
|
|
365
|
+
for (const k of Object.keys(frontmatterDefined)) delete metadataLoc[k];
|
|
366
|
+
if (Object.keys(metadataLoc).length === 0) metadataLoc = null;
|
|
367
|
+
}
|
|
178
368
|
} else if (frontmatter) {
|
|
179
369
|
metadata = frontmatter;
|
|
180
370
|
} else if (listMetadata) {
|
|
181
371
|
metadata = listMetadata;
|
|
182
372
|
}
|
|
183
|
-
return {
|
|
373
|
+
return {
|
|
374
|
+
frontmatter,
|
|
375
|
+
listMetadata,
|
|
376
|
+
metadata,
|
|
377
|
+
metadataLoc,
|
|
378
|
+
ast,
|
|
379
|
+
body: matter.content
|
|
380
|
+
};
|
|
184
381
|
}
|
|
185
382
|
var RECOGNIZED_METADATA_KEYS = /* @__PURE__ */ new Set([
|
|
186
383
|
"status",
|
|
@@ -190,7 +387,7 @@ var RECOGNIZED_METADATA_KEYS = /* @__PURE__ */ new Set([
|
|
|
190
387
|
"consulted",
|
|
191
388
|
"informed"
|
|
192
389
|
]);
|
|
193
|
-
function
|
|
390
|
+
function extractListMetadataWithLoc(ast) {
|
|
194
391
|
let firstList = null;
|
|
195
392
|
for (const child of ast.children) {
|
|
196
393
|
if (child.type === "heading") {
|
|
@@ -205,17 +402,20 @@ function extractListMetadata(ast) {
|
|
|
205
402
|
break;
|
|
206
403
|
}
|
|
207
404
|
if (!firstList) return null;
|
|
208
|
-
const
|
|
405
|
+
const values = {};
|
|
406
|
+
const loc = {};
|
|
209
407
|
for (const item of firstList.children) {
|
|
210
408
|
const pair = extractListItemKV(item);
|
|
211
|
-
if (pair && !(pair.key in
|
|
212
|
-
|
|
409
|
+
if (pair && !(pair.key in values)) {
|
|
410
|
+
values[pair.key] = pair.value;
|
|
411
|
+
const start = item.position?.start;
|
|
412
|
+
if (start) loc[pair.key] = { line: start.line, column: start.column };
|
|
213
413
|
}
|
|
214
414
|
}
|
|
215
|
-
const hasRecognizedKey = Object.keys(
|
|
415
|
+
const hasRecognizedKey = Object.keys(values).some(
|
|
216
416
|
(k) => RECOGNIZED_METADATA_KEYS.has(k)
|
|
217
417
|
);
|
|
218
|
-
return hasRecognizedKey ?
|
|
418
|
+
return hasRecognizedKey ? { values, loc } : null;
|
|
219
419
|
}
|
|
220
420
|
var KEY_PATTERN = /^[A-Za-z][A-Za-z0-9 \-_]*$/;
|
|
221
421
|
var SEPARATOR_PATTERN = /^\s*:\s*/;
|
|
@@ -255,6 +455,118 @@ function extractListItemKV(item) {
|
|
|
255
455
|
return null;
|
|
256
456
|
}
|
|
257
457
|
|
|
458
|
+
// src/core/suppression.ts
|
|
459
|
+
var DIRECTIVE_KINDS = /* @__PURE__ */ new Set([
|
|
460
|
+
"disable-file",
|
|
461
|
+
"disable",
|
|
462
|
+
"enable",
|
|
463
|
+
"disable-next-line"
|
|
464
|
+
]);
|
|
465
|
+
var DIRECTIVE_PREFIX = "madr-lint-";
|
|
466
|
+
function parseDirective(value, line) {
|
|
467
|
+
const trimmed = value.trim();
|
|
468
|
+
if (!trimmed.startsWith("<!--") || !trimmed.endsWith("-->")) return null;
|
|
469
|
+
const inner = trimmed.slice(4, -3).trim();
|
|
470
|
+
if (inner.includes("<!--") || inner.includes("-->")) return null;
|
|
471
|
+
if (!inner.startsWith(DIRECTIVE_PREFIX)) return null;
|
|
472
|
+
const afterPrefix = inner.slice(DIRECTIVE_PREFIX.length);
|
|
473
|
+
const wsIndex = afterPrefix.search(/\s/);
|
|
474
|
+
const keyword = wsIndex === -1 ? afterPrefix : afterPrefix.slice(0, wsIndex);
|
|
475
|
+
if (!DIRECTIVE_KINDS.has(keyword)) return null;
|
|
476
|
+
const rest = wsIndex === -1 ? "" : afterPrefix.slice(wsIndex);
|
|
477
|
+
return { kind: keyword, rules: parseRuleList(rest), line };
|
|
478
|
+
}
|
|
479
|
+
function parseRuleList(rest) {
|
|
480
|
+
const trimmed = rest.trim();
|
|
481
|
+
if (trimmed === "") return null;
|
|
482
|
+
const rules = trimmed.split(",").map((s) => s.trim()).filter((s) => s !== "");
|
|
483
|
+
return rules.length > 0 ? rules : null;
|
|
484
|
+
}
|
|
485
|
+
function walkHtml(node, out) {
|
|
486
|
+
if (node.type === "html") {
|
|
487
|
+
const line = node.position?.start.line;
|
|
488
|
+
if (typeof line === "number") {
|
|
489
|
+
const directive = parseDirective(node.value, line);
|
|
490
|
+
if (directive) out.push(directive);
|
|
491
|
+
}
|
|
492
|
+
}
|
|
493
|
+
if ("children" in node && Array.isArray(node.children)) {
|
|
494
|
+
for (const child of node.children) walkHtml(child, out);
|
|
495
|
+
}
|
|
496
|
+
}
|
|
497
|
+
function collectDirectives(ast, body) {
|
|
498
|
+
const all = [];
|
|
499
|
+
walkHtml(ast, all);
|
|
500
|
+
if (all.length === 0) return null;
|
|
501
|
+
let lines = null;
|
|
502
|
+
const nextNonBlankLine = (after) => {
|
|
503
|
+
lines ??= body.split("\n");
|
|
504
|
+
for (let ln = after + 1; ln <= lines.length; ln++) {
|
|
505
|
+
if ((lines[ln - 1] ?? "").trim() !== "") return ln;
|
|
506
|
+
}
|
|
507
|
+
return null;
|
|
508
|
+
};
|
|
509
|
+
const index = {
|
|
510
|
+
fileDisableAll: false,
|
|
511
|
+
fileDisableRules: /* @__PURE__ */ new Set(),
|
|
512
|
+
ranged: [],
|
|
513
|
+
nextLine: /* @__PURE__ */ new Map()
|
|
514
|
+
};
|
|
515
|
+
for (const directive of all) {
|
|
516
|
+
switch (directive.kind) {
|
|
517
|
+
case "disable-file": {
|
|
518
|
+
if (directive.rules === null) index.fileDisableAll = true;
|
|
519
|
+
else for (const rule9 of directive.rules) index.fileDisableRules.add(rule9);
|
|
520
|
+
break;
|
|
521
|
+
}
|
|
522
|
+
case "disable":
|
|
523
|
+
case "enable": {
|
|
524
|
+
index.ranged.push(directive);
|
|
525
|
+
break;
|
|
526
|
+
}
|
|
527
|
+
case "disable-next-line": {
|
|
528
|
+
const target = nextNonBlankLine(directive.line);
|
|
529
|
+
if (target === null) break;
|
|
530
|
+
let entry = index.nextLine.get(target);
|
|
531
|
+
if (!entry) {
|
|
532
|
+
entry = { all: false, rules: /* @__PURE__ */ new Set() };
|
|
533
|
+
index.nextLine.set(target, entry);
|
|
534
|
+
}
|
|
535
|
+
if (directive.rules === null) entry.all = true;
|
|
536
|
+
else for (const rule9 of directive.rules) entry.rules.add(rule9);
|
|
537
|
+
break;
|
|
538
|
+
}
|
|
539
|
+
}
|
|
540
|
+
}
|
|
541
|
+
index.ranged.sort((a, b) => a.line - b.line);
|
|
542
|
+
return index;
|
|
543
|
+
}
|
|
544
|
+
function directiveApplies(directive, ruleName) {
|
|
545
|
+
return directive.rules === null || directive.rules.includes(ruleName);
|
|
546
|
+
}
|
|
547
|
+
function isSuppressed(index, ruleName, line) {
|
|
548
|
+
if (index.fileDisableAll || index.fileDisableRules.has(ruleName)) return true;
|
|
549
|
+
if (line !== void 0) {
|
|
550
|
+
const next = index.nextLine.get(line);
|
|
551
|
+
if (next && (next.all || next.rules.has(ruleName))) return true;
|
|
552
|
+
}
|
|
553
|
+
const ceiling = line ?? Number.POSITIVE_INFINITY;
|
|
554
|
+
let disabled = false;
|
|
555
|
+
for (const directive of index.ranged) {
|
|
556
|
+
if (directive.line > ceiling) break;
|
|
557
|
+
if (directiveApplies(directive, ruleName)) {
|
|
558
|
+
disabled = directive.kind === "disable";
|
|
559
|
+
}
|
|
560
|
+
}
|
|
561
|
+
return disabled;
|
|
562
|
+
}
|
|
563
|
+
function filterSuppressed(diagnostics, index) {
|
|
564
|
+
return diagnostics.filter((d) => {
|
|
565
|
+
if (d.ruleName === INTERNAL_ERROR_RULE_NAME) return true;
|
|
566
|
+
return !isSuppressed(index, d.ruleName, d.loc?.line);
|
|
567
|
+
});
|
|
568
|
+
}
|
|
569
|
+
|
|
258
570
|
// src/core/runner.ts
|
|
259
571
|
var ajv = new Ajv({ strict: true, allErrors: true });
|
|
260
572
|
var validatorCache = /* @__PURE__ */ new WeakMap();
|
|
@@ -266,7 +578,7 @@ function getValidator(schema) {
|
|
|
266
578
|
}
|
|
267
579
|
return validator;
|
|
268
580
|
}
|
|
269
|
-
var
|
|
581
|
+
var INTERNAL_ERROR_DOCS_URL = "https://github.com/knktkc/madr-lint";
|
|
270
582
|
var RuleOptionsError = class extends Error {
|
|
271
583
|
constructor(ruleName, ajvErrors) {
|
|
272
584
|
super(`Invalid options for rule ${ruleName}: ${ajvErrors}`);
|
|
@@ -277,6 +589,27 @@ var RuleOptionsError = class extends Error {
|
|
|
277
589
|
ruleName;
|
|
278
590
|
ajvErrors;
|
|
279
591
|
};
|
|
592
|
+
var PerFileRuleContext = class {
|
|
593
|
+
file;
|
|
594
|
+
options;
|
|
595
|
+
report;
|
|
596
|
+
ensureParsed;
|
|
597
|
+
constructor(file, options, ensureParsed, report) {
|
|
598
|
+
this.file = file;
|
|
599
|
+
this.options = options;
|
|
600
|
+
this.ensureParsed = ensureParsed;
|
|
601
|
+
this.report = report;
|
|
602
|
+
}
|
|
603
|
+
get frontmatter() {
|
|
604
|
+
return this.ensureParsed().frontmatter;
|
|
605
|
+
}
|
|
606
|
+
get metadata() {
|
|
607
|
+
return this.ensureParsed().metadata;
|
|
608
|
+
}
|
|
609
|
+
get metadataLoc() {
|
|
610
|
+
return this.ensureParsed().metadataLoc;
|
|
611
|
+
}
|
|
612
|
+
};
|
|
280
613
|
function runRulesOnFile(rules, file, runtime = {}) {
|
|
281
614
|
const diagnostics = [];
|
|
282
615
|
const severity = runtime.severity ?? "error";
|
|
@@ -300,24 +633,25 @@ function runRulesOnFile(rules, file, runtime = {}) {
|
|
|
300
633
|
throw new RuleOptionsError(rule9.meta.name, ajv.errorsText(validator.errors));
|
|
301
634
|
}
|
|
302
635
|
}
|
|
303
|
-
const
|
|
636
|
+
const ruleName = rule9.meta.name;
|
|
637
|
+
const suggestions = rule9.meta.suggestions;
|
|
638
|
+
const docsUrl = rule9.meta.docs.url ?? "";
|
|
639
|
+
const context = new PerFileRuleContext(
|
|
304
640
|
file,
|
|
305
|
-
|
|
306
|
-
|
|
307
|
-
|
|
308
|
-
|
|
309
|
-
return ensureParsed().metadata;
|
|
310
|
-
},
|
|
311
|
-
options: mergedOptions,
|
|
312
|
-
report(d) {
|
|
641
|
+
mergedOptions,
|
|
642
|
+
ensureParsed,
|
|
643
|
+
(d) => {
|
|
644
|
+
const template = suggestions?.[d.messageId];
|
|
313
645
|
diagnostics.push({
|
|
314
|
-
ruleName
|
|
646
|
+
ruleName,
|
|
315
647
|
severity,
|
|
316
648
|
path: file.path,
|
|
649
|
+
suggestion: template === void 0 ? null : interpolate(template, d.data ?? {}),
|
|
650
|
+
docsUrl,
|
|
317
651
|
...d
|
|
318
652
|
});
|
|
319
653
|
}
|
|
320
|
-
|
|
654
|
+
);
|
|
321
655
|
let listeners;
|
|
322
656
|
try {
|
|
323
657
|
listeners = rule9.create(context);
|
|
@@ -336,7 +670,11 @@ function runRulesOnFile(rules, file, runtime = {}) {
|
|
|
336
670
|
if (hasASTRule) {
|
|
337
671
|
walk(ensureParsed().ast, enterMap, exitMap);
|
|
338
672
|
}
|
|
339
|
-
return diagnostics;
|
|
673
|
+
if (diagnostics.length === 0) return diagnostics;
|
|
674
|
+
if (!file.content.includes(DIRECTIVE_PREFIX)) return diagnostics;
|
|
675
|
+
const { ast, body } = ensureParsed();
|
|
676
|
+
const directives = collectDirectives(ast, body);
|
|
677
|
+
return directives ? filterSuppressed(diagnostics, directives) : diagnostics;
|
|
340
678
|
}
|
|
341
679
|
function internalErrorDiagnostic(ruleName, operation, err, path) {
|
|
342
680
|
return {
|
|
@@ -344,6 +682,8 @@ function internalErrorDiagnostic(ruleName, operation, err, path) {
|
|
|
344
682
|
messageId: "ruleThrew",
|
|
345
683
|
severity: "error",
|
|
346
684
|
path,
|
|
685
|
+
suggestion: null,
|
|
686
|
+
docsUrl: INTERNAL_ERROR_DOCS_URL,
|
|
347
687
|
data: {
|
|
348
688
|
rule: ruleName,
|
|
349
689
|
operation,
|
|
@@ -394,6 +734,7 @@ function buildProjectFile(file) {
|
|
|
394
734
|
return {
|
|
395
735
|
path: file.path,
|
|
396
736
|
content: file.content,
|
|
737
|
+
body: parsed.body,
|
|
397
738
|
frontmatter: parsed.frontmatter,
|
|
398
739
|
metadata: parsed.metadata,
|
|
399
740
|
ast: parsed.ast
|
|
@@ -417,14 +758,20 @@ function runRulesOnProject(rules, files, runtime = {}) {
|
|
|
417
758
|
);
|
|
418
759
|
}
|
|
419
760
|
}
|
|
761
|
+
const ruleName = rule9.meta.name;
|
|
762
|
+
const suggestions = rule9.meta.suggestions;
|
|
763
|
+
const docsUrl = rule9.meta.docs.url ?? "";
|
|
420
764
|
const context = {
|
|
421
765
|
files,
|
|
422
766
|
options: mergedOptions,
|
|
423
767
|
fileExists: runtime.fileExists,
|
|
424
768
|
report(d) {
|
|
769
|
+
const template = suggestions?.[d.messageId];
|
|
425
770
|
diagnostics.push({
|
|
426
|
-
ruleName
|
|
771
|
+
ruleName,
|
|
427
772
|
severity,
|
|
773
|
+
suggestion: template === void 0 ? null : interpolate(template, d.data ?? {}),
|
|
774
|
+
docsUrl,
|
|
428
775
|
...d
|
|
429
776
|
});
|
|
430
777
|
}
|
|
@@ -440,11 +787,6 @@ function runRulesOnProject(rules, files, runtime = {}) {
|
|
|
440
787
|
return diagnostics;
|
|
441
788
|
}
|
|
442
789
|
|
|
443
|
-
// src/core/types.ts
|
|
444
|
-
function isProjectRule(rule9) {
|
|
445
|
-
return "check" in rule9;
|
|
446
|
-
}
|
|
447
|
-
|
|
448
790
|
// src/core/lint.ts
|
|
449
791
|
function toPosix(p) {
|
|
450
792
|
if (sep === "/") return p;
|
|
@@ -454,7 +796,7 @@ function lintFiles(opts) {
|
|
|
454
796
|
const allDiagnostics = [];
|
|
455
797
|
const fileEntries = opts.files.map((absolutePath) => ({
|
|
456
798
|
relativePath: toPosix(relative(opts.cwd, absolutePath)),
|
|
457
|
-
content:
|
|
799
|
+
content: readFileSync4(absolutePath, "utf8")
|
|
458
800
|
}));
|
|
459
801
|
const perFileRules = [];
|
|
460
802
|
const projectRules = [];
|
|
@@ -472,6 +814,7 @@ function lintFiles(opts) {
|
|
|
472
814
|
manifest = loaded;
|
|
473
815
|
} else {
|
|
474
816
|
manifest = {
|
|
817
|
+
schemaVersion: CACHE_SCHEMA_VERSION,
|
|
475
818
|
version: opts.cache.pkgVersion,
|
|
476
819
|
configHash: opts.cache.configHash,
|
|
477
820
|
files: {}
|
|
@@ -545,8 +888,9 @@ function lintFiles(opts) {
|
|
|
545
888
|
if (sev === "error") errorRules.push(rule9);
|
|
546
889
|
else if (sev === "warn") warnRules.push(rule9);
|
|
547
890
|
}
|
|
891
|
+
const projectDiagnostics = [];
|
|
548
892
|
if (errorRules.length > 0) {
|
|
549
|
-
|
|
893
|
+
projectDiagnostics.push(
|
|
550
894
|
...runRulesOnProject(errorRules, projectFiles, {
|
|
551
895
|
severity: "error",
|
|
552
896
|
fileExists,
|
|
@@ -555,7 +899,7 @@ function lintFiles(opts) {
|
|
|
555
899
|
);
|
|
556
900
|
}
|
|
557
901
|
if (warnRules.length > 0) {
|
|
558
|
-
|
|
902
|
+
projectDiagnostics.push(
|
|
559
903
|
...runRulesOnProject(warnRules, projectFiles, {
|
|
560
904
|
severity: "warn",
|
|
561
905
|
fileExists,
|
|
@@ -563,14 +907,27 @@ function lintFiles(opts) {
|
|
|
563
907
|
})
|
|
564
908
|
);
|
|
565
909
|
}
|
|
910
|
+
allDiagnostics.push(
|
|
911
|
+
...filterSuppressedProjectDiagnostics(projectDiagnostics, projectFiles)
|
|
912
|
+
);
|
|
566
913
|
}
|
|
567
914
|
if (manifest && opts.cache) {
|
|
568
915
|
saveManifest(manifestPath(opts.cache.dir), manifest);
|
|
569
916
|
}
|
|
917
|
+
if (!opts.baseline) {
|
|
918
|
+
return {
|
|
919
|
+
filesChecked: opts.files.length,
|
|
920
|
+
filesFromCache,
|
|
921
|
+
diagnostics: allDiagnostics,
|
|
922
|
+
baselineHidden: 0
|
|
923
|
+
};
|
|
924
|
+
}
|
|
925
|
+
const applied = applyBaseline(allDiagnostics, opts.baseline);
|
|
570
926
|
return {
|
|
571
927
|
filesChecked: opts.files.length,
|
|
572
928
|
filesFromCache,
|
|
573
|
-
diagnostics:
|
|
929
|
+
diagnostics: applied.kept,
|
|
930
|
+
baselineHidden: applied.hidden
|
|
574
931
|
};
|
|
575
932
|
}
|
|
576
933
|
function runPerFileRulesForFile(perFileRules, ruleSeverity, optionsByRule, file) {
|
|
@@ -605,6 +962,25 @@ function runPerFileRulesForFile(perFileRules, ruleSeverity, optionsByRule, file)
|
|
|
605
962
|
}
|
|
606
963
|
return diagnostics;
|
|
607
964
|
}
|
|
965
|
+
function filterSuppressedProjectDiagnostics(diagnostics, projectFiles) {
|
|
966
|
+
if (diagnostics.length === 0) return [];
|
|
967
|
+
const fileByPath = new Map(projectFiles.map((f) => [f.path, f]));
|
|
968
|
+
const indexByPath = /* @__PURE__ */ new Map();
|
|
969
|
+
const indexFor = (path) => {
|
|
970
|
+
const cached = indexByPath.get(path);
|
|
971
|
+
if (cached !== void 0) return cached;
|
|
972
|
+
const file = fileByPath.get(path);
|
|
973
|
+
const index = file && file.content.includes(DIRECTIVE_PREFIX) ? collectDirectives(file.ast, file.body) : null;
|
|
974
|
+
indexByPath.set(path, index);
|
|
975
|
+
return index;
|
|
976
|
+
};
|
|
977
|
+
return diagnostics.filter((d) => {
|
|
978
|
+
if (d.ruleName === INTERNAL_ERROR_RULE_NAME) return true;
|
|
979
|
+
const index = indexFor(d.path);
|
|
980
|
+
if (!index) return true;
|
|
981
|
+
return !isSuppressed(index, d.ruleName, d.loc?.line);
|
|
982
|
+
});
|
|
983
|
+
}
|
|
608
984
|
function resolveSeverity(config) {
|
|
609
985
|
if (config === void 0) return "off";
|
|
610
986
|
if (typeof config === "string") return config;
|
|
@@ -621,19 +997,32 @@ function extractOptionsByRule(ruleSeverity) {
|
|
|
621
997
|
// src/core/reporter.ts
|
|
622
998
|
import pc from "picocolors";
|
|
623
999
|
var textReporter = {
|
|
1000
|
+
// Deliberately 2-param (meta unused): the CLI prints baselineHiddenSummary()
|
|
1001
|
+
// itself for text format, so the footer can outlive a suppressed banner.
|
|
624
1002
|
format(diagnostics, rulesByName) {
|
|
625
1003
|
if (diagnostics.length === 0) {
|
|
626
1004
|
return pc.green("\u2713 All clear.");
|
|
627
1005
|
}
|
|
628
1006
|
const byFile = groupByFile(diagnostics);
|
|
629
1007
|
const lines = [];
|
|
1008
|
+
const gutter = " ".repeat(9 + 28 + 2);
|
|
630
1009
|
for (const [file, fileDiagnostics] of byFile) {
|
|
631
1010
|
lines.push(pc.underline(file));
|
|
1011
|
+
const docsByRule = /* @__PURE__ */ new Map();
|
|
632
1012
|
for (const d of fileDiagnostics) {
|
|
633
1013
|
const sev = d.severity === "error" ? pc.red(" error ") : pc.yellow(" warn ");
|
|
634
1014
|
const ruleId = pc.dim(d.ruleName.padEnd(28));
|
|
635
1015
|
const message = renderMessage(d, rulesByName);
|
|
636
1016
|
lines.push(`${sev}${ruleId} ${message}`);
|
|
1017
|
+
if (d.suggestion) {
|
|
1018
|
+
lines.push(`${gutter}${pc.cyan(`\u2192 ${d.suggestion}`)}`);
|
|
1019
|
+
}
|
|
1020
|
+
if (d.docsUrl && !docsByRule.has(d.ruleName)) {
|
|
1021
|
+
docsByRule.set(d.ruleName, d.docsUrl);
|
|
1022
|
+
}
|
|
1023
|
+
}
|
|
1024
|
+
for (const [ruleName, url] of docsByRule) {
|
|
1025
|
+
lines.push(pc.dim(` ${ruleName} ${url}`));
|
|
637
1026
|
}
|
|
638
1027
|
lines.push("");
|
|
639
1028
|
}
|
|
@@ -656,12 +1045,6 @@ function renderMessage(d, rulesByName) {
|
|
|
656
1045
|
const template = rule9?.meta.messages[d.messageId] ?? d.messageId;
|
|
657
1046
|
return interpolate(template, d.data ?? {});
|
|
658
1047
|
}
|
|
659
|
-
function interpolate(template, data) {
|
|
660
|
-
return template.replace(/\{\{(\w+)\}\}/g, (_, key) => {
|
|
661
|
-
const v = data[key];
|
|
662
|
-
return v !== void 0 ? String(v) : `{{${key}}}`;
|
|
663
|
-
});
|
|
664
|
-
}
|
|
665
1048
|
function formatSummary(errors, warnings) {
|
|
666
1049
|
const parts = [];
|
|
667
1050
|
if (errors > 0) parts.push(`${errors} ${errors === 1 ? "error" : "errors"}`);
|
|
@@ -669,7 +1052,7 @@ function formatSummary(errors, warnings) {
|
|
|
669
1052
|
return parts.join(", ");
|
|
670
1053
|
}
|
|
671
1054
|
var jsonReporter = {
|
|
672
|
-
format(diagnostics, rulesByName) {
|
|
1055
|
+
format(diagnostics, rulesByName, meta) {
|
|
673
1056
|
const errors = diagnostics.filter((d) => d.severity === "error").length;
|
|
674
1057
|
const warnings = diagnostics.filter((d) => d.severity === "warn").length;
|
|
675
1058
|
const payload = {
|
|
@@ -677,7 +1060,10 @@ var jsonReporter = {
|
|
|
677
1060
|
summary: {
|
|
678
1061
|
total: diagnostics.length,
|
|
679
1062
|
errors,
|
|
680
|
-
warnings
|
|
1063
|
+
warnings,
|
|
1064
|
+
// Always present (0 when no baseline) so CI consumers can detect an
|
|
1065
|
+
// active baseline without probing for the key. SARIF stays untouched.
|
|
1066
|
+
baselineHidden: meta?.baselineHidden ?? 0
|
|
681
1067
|
},
|
|
682
1068
|
results: diagnostics.map((d) => ({
|
|
683
1069
|
path: d.path,
|
|
@@ -685,6 +1071,10 @@ var jsonReporter = {
|
|
|
685
1071
|
messageId: d.messageId,
|
|
686
1072
|
severity: d.severity,
|
|
687
1073
|
message: renderMessage(d, rulesByName),
|
|
1074
|
+
// Self-contained diagnostics (#67): always present so consumers can
|
|
1075
|
+
// rely on the keys — `suggestion` is null when the rule declares none.
|
|
1076
|
+
suggestion: d.suggestion,
|
|
1077
|
+
docsUrl: d.docsUrl,
|
|
688
1078
|
data: d.data ?? {}
|
|
689
1079
|
}))
|
|
690
1080
|
};
|
|
@@ -737,10 +1127,43 @@ var sarifReporter = {
|
|
|
737
1127
|
return JSON.stringify(sarif, null, 2);
|
|
738
1128
|
}
|
|
739
1129
|
};
|
|
1130
|
+
function escapeGhMessage(s) {
|
|
1131
|
+
return s.replace(/%/g, "%25").replace(/\r/g, "%0D").replace(/\n/g, "%0A");
|
|
1132
|
+
}
|
|
1133
|
+
function escapeGhProperty(s) {
|
|
1134
|
+
return escapeGhMessage(s).replace(/,/g, "%2C").replace(/:/g, "%3A");
|
|
1135
|
+
}
|
|
1136
|
+
var githubReporter = {
|
|
1137
|
+
format(diagnostics, rulesByName, meta) {
|
|
1138
|
+
const lines = [];
|
|
1139
|
+
for (const d of diagnostics) {
|
|
1140
|
+
const level = d.severity === "error" ? "error" : "warning";
|
|
1141
|
+
const file = escapeGhProperty(d.path);
|
|
1142
|
+
const title = escapeGhProperty(d.ruleName);
|
|
1143
|
+
const rendered = renderMessage(d, rulesByName);
|
|
1144
|
+
const message = escapeGhMessage(
|
|
1145
|
+
d.suggestion ? `${rendered} \u2014 ${d.suggestion}` : rendered
|
|
1146
|
+
);
|
|
1147
|
+
const linePart = d.loc ? `,line=${d.loc.line}` : "";
|
|
1148
|
+
lines.push(`::${level} file=${file}${linePart},title=${title}::${message}`);
|
|
1149
|
+
}
|
|
1150
|
+
const errors = diagnostics.filter((d) => d.severity === "error").length;
|
|
1151
|
+
const warnings = diagnostics.filter((d) => d.severity === "warn").length;
|
|
1152
|
+
const summaryParts = [];
|
|
1153
|
+
if (errors > 0) summaryParts.push(`${errors} ${errors === 1 ? "error" : "errors"}`);
|
|
1154
|
+
if (warnings > 0) summaryParts.push(`${warnings} ${warnings === 1 ? "warning" : "warnings"}`);
|
|
1155
|
+
if (summaryParts.length === 0) summaryParts.push("0 errors, 0 warnings");
|
|
1156
|
+
const baselineHidden = meta?.baselineHidden ?? 0;
|
|
1157
|
+
if (baselineHidden > 0) summaryParts.push(`${baselineHidden} hidden by baseline`);
|
|
1158
|
+
lines.push(summaryParts.join(", "));
|
|
1159
|
+
return lines.join("\n");
|
|
1160
|
+
}
|
|
1161
|
+
};
|
|
740
1162
|
var reporters = {
|
|
741
1163
|
text: textReporter,
|
|
742
1164
|
json: jsonReporter,
|
|
743
|
-
sarif: sarifReporter
|
|
1165
|
+
sarif: sarifReporter,
|
|
1166
|
+
github: githubReporter
|
|
744
1167
|
};
|
|
745
1168
|
|
|
746
1169
|
// src/rules/index.ts
|
|
@@ -793,13 +1216,17 @@ var rule = {
|
|
|
793
1216
|
versionCompat: ["v2", "v3", "v4"],
|
|
794
1217
|
docs: {
|
|
795
1218
|
description: "Validate that ADR `date` (frontmatter or v2 bold-list) is a valid ISO 8601 calendar date (YYYY-MM-DD)",
|
|
796
|
-
url: "https://github.
|
|
1219
|
+
url: "https://knktkc.github.io/madr-lint/rules/date-iso8601/",
|
|
797
1220
|
recommended: true
|
|
798
1221
|
},
|
|
799
1222
|
messages: {
|
|
800
1223
|
missingDate: 'Metadata does not contain a "{{field}}" field (checked frontmatter and v2 bold-list)',
|
|
801
1224
|
invalidDate: 'Date "{{date}}" is not a valid ISO 8601 calendar date (YYYY-MM-DD)'
|
|
802
1225
|
},
|
|
1226
|
+
suggestions: {
|
|
1227
|
+
missingDate: 'add a "{{field}}" field in YYYY-MM-DD format to the frontmatter (for MADR v2, a "* Date: ..." list item)',
|
|
1228
|
+
invalidDate: "use the YYYY-MM-DD calendar-date format, e.g. 2025-03-14"
|
|
1229
|
+
},
|
|
803
1230
|
defaultOptions: {
|
|
804
1231
|
field: "date"
|
|
805
1232
|
},
|
|
@@ -825,8 +1252,10 @@ var rule = {
|
|
|
825
1252
|
return;
|
|
826
1253
|
}
|
|
827
1254
|
if (!isValidIso8601Date(dateStr)) {
|
|
1255
|
+
const loc = context.metadataLoc?.[fieldName];
|
|
828
1256
|
context.report({
|
|
829
1257
|
messageId: "invalidDate",
|
|
1258
|
+
...loc ? { loc } : {},
|
|
830
1259
|
data: { date: dateStr }
|
|
831
1260
|
});
|
|
832
1261
|
}
|
|
@@ -884,12 +1313,17 @@ var rule2 = {
|
|
|
884
1313
|
versionCompat: ["v2", "v3", "v4"],
|
|
885
1314
|
docs: {
|
|
886
1315
|
description: "Enforce ADR filename convention NNNN-kebab-case.md",
|
|
887
|
-
url: "https://github.
|
|
1316
|
+
url: "https://knktkc.github.io/madr-lint/rules/filename-format/",
|
|
888
1317
|
recommended: true
|
|
889
1318
|
},
|
|
890
1319
|
messages: {
|
|
891
1320
|
invalidFilename: 'Filename "{{filename}}" does not match expected pattern "{{expected}}"'
|
|
892
1321
|
},
|
|
1322
|
+
suggestions: {
|
|
1323
|
+
// The message already states the expected pattern; the suggestion adds a
|
|
1324
|
+
// concrete, conforming example of the NNNN-kebab-case.md convention.
|
|
1325
|
+
invalidFilename: "rename the file to the NNNN-kebab-case.md convention, e.g. 0001-record-architecture-decisions.md"
|
|
1326
|
+
},
|
|
893
1327
|
defaultOptions: {
|
|
894
1328
|
pattern: "^[0-9]{4}-[a-z0-9-]+\\.md$"
|
|
895
1329
|
},
|
|
@@ -910,7 +1344,7 @@ var rule2 = {
|
|
|
910
1344
|
var filename_format_default = rule2;
|
|
911
1345
|
|
|
912
1346
|
// src/rules/no-broken-links/index.ts
|
|
913
|
-
import { dirname as
|
|
1347
|
+
import { dirname as dirname3, posix } from "path";
|
|
914
1348
|
|
|
915
1349
|
// src/rules/no-broken-links/schema.json
|
|
916
1350
|
var schema_default3 = {
|
|
@@ -963,12 +1397,15 @@ var rule3 = {
|
|
|
963
1397
|
versionCompat: ["v2", "v3", "v4"],
|
|
964
1398
|
docs: {
|
|
965
1399
|
description: "Relative-path Markdown links must resolve to an existing file in the project",
|
|
966
|
-
url: "https://github.
|
|
1400
|
+
url: "https://knktkc.github.io/madr-lint/rules/no-broken-links/",
|
|
967
1401
|
recommended: true
|
|
968
1402
|
},
|
|
969
1403
|
messages: {
|
|
970
1404
|
brokenLink: 'Link to "{{url}}" resolves to "{{resolvedPath}}", which does not exist in the project'
|
|
971
1405
|
},
|
|
1406
|
+
suggestions: {
|
|
1407
|
+
brokenLink: "fix the link target or remove the link; relative paths resolve from the ADR file's own directory"
|
|
1408
|
+
},
|
|
972
1409
|
defaultOptions: {},
|
|
973
1410
|
schema: schema_default3
|
|
974
1411
|
},
|
|
@@ -985,13 +1422,15 @@ var rule3 = {
|
|
|
985
1422
|
if (isExternalOrAnchor(url)) continue;
|
|
986
1423
|
const pathOnly = safeDecode(stripAnchorAndQuery(url));
|
|
987
1424
|
if (pathOnly === "") continue;
|
|
988
|
-
const fileDir =
|
|
1425
|
+
const fileDir = dirname3(file.path);
|
|
989
1426
|
const resolvedPath = resolveRelative(fileDir, pathOnly);
|
|
990
1427
|
const exists = knownPaths.has(resolvedPath) || (context.fileExists?.(resolvedPath) ?? false);
|
|
991
1428
|
if (!exists) {
|
|
1429
|
+
const start = link.position?.start;
|
|
992
1430
|
context.report({
|
|
993
1431
|
messageId: "brokenLink",
|
|
994
1432
|
path: file.path,
|
|
1433
|
+
...start ? { loc: { line: start.line, column: start.column } } : {},
|
|
995
1434
|
data: { url, resolvedPath }
|
|
996
1435
|
});
|
|
997
1436
|
}
|
|
@@ -1021,12 +1460,15 @@ var rule4 = {
|
|
|
1021
1460
|
versionCompat: ["v2", "v3", "v4"],
|
|
1022
1461
|
docs: {
|
|
1023
1462
|
description: "No two ADRs share the same NNNN- number prefix",
|
|
1024
|
-
url: "https://github.
|
|
1463
|
+
url: "https://knktkc.github.io/madr-lint/rules/no-duplicate-numbering/",
|
|
1025
1464
|
recommended: true
|
|
1026
1465
|
},
|
|
1027
1466
|
messages: {
|
|
1028
1467
|
duplicateNumber: "ADR number {{number}} is used by multiple files: {{paths}}"
|
|
1029
1468
|
},
|
|
1469
|
+
suggestions: {
|
|
1470
|
+
duplicateNumber: "renumber all but one of these files so each ADR has a unique NNNN- prefix"
|
|
1471
|
+
},
|
|
1030
1472
|
defaultOptions: {},
|
|
1031
1473
|
schema: schema_default4
|
|
1032
1474
|
},
|
|
@@ -1080,12 +1522,15 @@ var rule5 = {
|
|
|
1080
1522
|
versionCompat: ["v2", "v3", "v4"],
|
|
1081
1523
|
docs: {
|
|
1082
1524
|
description: "Detect gaps in ADR numbering (e.g. 0001 and 0003 exist but 0002 is missing). Convention-only; default off.",
|
|
1083
|
-
url: "https://github.
|
|
1525
|
+
url: "https://knktkc.github.io/madr-lint/rules/no-numbering-gap/",
|
|
1084
1526
|
recommended: false
|
|
1085
1527
|
},
|
|
1086
1528
|
messages: {
|
|
1087
1529
|
numberingGap: "Numbering gap: missing {{missing}} between ADR-{{from}} and ADR-{{to}}"
|
|
1088
1530
|
},
|
|
1531
|
+
// No `suggestions`: a gap can be intentional (a rejected or deleted ADR),
|
|
1532
|
+
// and closing it may mean either adding the missing ADR OR renumbering —
|
|
1533
|
+
// the right remediation is contextual, so we omit a suggestion. See #67.
|
|
1089
1534
|
defaultOptions: {},
|
|
1090
1535
|
schema: schema_default5
|
|
1091
1536
|
},
|
|
@@ -1156,12 +1601,15 @@ var rule6 = {
|
|
|
1156
1601
|
versionCompat: ["v2", "v3", "v4"],
|
|
1157
1602
|
docs: {
|
|
1158
1603
|
description: "Enforce that ADRs contain required heading sections",
|
|
1159
|
-
url: "https://github.
|
|
1604
|
+
url: "https://knktkc.github.io/madr-lint/rules/required-sections/",
|
|
1160
1605
|
recommended: true
|
|
1161
1606
|
},
|
|
1162
1607
|
messages: {
|
|
1163
1608
|
missingSection: 'Missing required section: "{{section}}"'
|
|
1164
1609
|
},
|
|
1610
|
+
suggestions: {
|
|
1611
|
+
missingSection: 'add a "## {{section}}" heading to the document body'
|
|
1612
|
+
},
|
|
1165
1613
|
defaultOptions: {
|
|
1166
1614
|
sections: [
|
|
1167
1615
|
"Context and Problem Statement",
|
|
@@ -1233,13 +1681,19 @@ var rule7 = {
|
|
|
1233
1681
|
versionCompat: ["v2", "v3", "v4"],
|
|
1234
1682
|
docs: {
|
|
1235
1683
|
description: "Validate that ADR `status` (frontmatter or v2 bold-list) is in the allowed enum",
|
|
1236
|
-
url: "https://github.
|
|
1684
|
+
url: "https://knktkc.github.io/madr-lint/rules/status-enum/",
|
|
1237
1685
|
recommended: true
|
|
1238
1686
|
},
|
|
1239
1687
|
messages: {
|
|
1240
1688
|
missingStatus: 'Metadata does not contain a "status" field (checked frontmatter and v2 bold-list)',
|
|
1241
1689
|
invalidStatus: 'Status "{{status}}" is not one of: {{allowed}}'
|
|
1242
1690
|
},
|
|
1691
|
+
// No suggestion for invalidStatus: the message already lists the allowed
|
|
1692
|
+
// values (the expected-vs-actual is self-contained), so a suggestion would
|
|
1693
|
+
// only restate it. See issue #67.
|
|
1694
|
+
suggestions: {
|
|
1695
|
+
missingStatus: 'add a "status" field to the frontmatter (for MADR v2, a "* Status: ..." list item) \u2014 allowed values: {{allowed}}'
|
|
1696
|
+
},
|
|
1243
1697
|
defaultOptions: {
|
|
1244
1698
|
values: ["proposed", "rejected", "accepted", "deprecated"],
|
|
1245
1699
|
prefixValues: ["superseded by"],
|
|
@@ -1248,12 +1702,13 @@ var rule7 = {
|
|
|
1248
1702
|
schema: schema_default7
|
|
1249
1703
|
},
|
|
1250
1704
|
create(context) {
|
|
1705
|
+
const { values, prefixValues, caseSensitive } = context.options;
|
|
1706
|
+
const allowed = [...values, ...prefixValues.map((p) => `${p} ...`)];
|
|
1251
1707
|
const meta = context.metadata;
|
|
1252
1708
|
if (!meta || typeof meta.status !== "string") {
|
|
1253
|
-
context.report({ messageId: "missingStatus", data: {} });
|
|
1709
|
+
context.report({ messageId: "missingStatus", data: { allowed } });
|
|
1254
1710
|
return;
|
|
1255
1711
|
}
|
|
1256
|
-
const { values, prefixValues, caseSensitive } = context.options;
|
|
1257
1712
|
const status = meta.status;
|
|
1258
1713
|
const compareStatus = caseSensitive ? status : status.toLowerCase();
|
|
1259
1714
|
const compareValues = caseSensitive ? values : values.map((v) => v.toLowerCase());
|
|
@@ -1263,12 +1718,10 @@ var rule7 = {
|
|
|
1263
1718
|
(p) => compareStatus.startsWith(p)
|
|
1264
1719
|
);
|
|
1265
1720
|
if (!exactMatch && !prefixMatch) {
|
|
1266
|
-
const
|
|
1267
|
-
...values,
|
|
1268
|
-
...prefixValues.map((p) => `${p} ...`)
|
|
1269
|
-
];
|
|
1721
|
+
const loc = context.metadataLoc?.status;
|
|
1270
1722
|
context.report({
|
|
1271
1723
|
messageId: "invalidStatus",
|
|
1724
|
+
...loc ? { loc } : {},
|
|
1272
1725
|
data: { status, allowed }
|
|
1273
1726
|
});
|
|
1274
1727
|
}
|
|
@@ -1309,12 +1762,20 @@ var rule8 = {
|
|
|
1309
1762
|
versionCompat: ["v3", "v4"],
|
|
1310
1763
|
docs: {
|
|
1311
1764
|
description: "Frontmatter `supersedes` and `superseded-by` must reference each other bidirectionally",
|
|
1312
|
-
url: "https://github.
|
|
1765
|
+
url: "https://knktkc.github.io/madr-lint/rules/supersedes-bidirectional/",
|
|
1313
1766
|
recommended: true
|
|
1314
1767
|
},
|
|
1315
1768
|
messages: {
|
|
1316
1769
|
unknownReference: "Frontmatter `{{direction}}: {{ref}}` references an ADR that does not exist",
|
|
1317
|
-
|
|
1770
|
+
// `declared` is the field the SOURCE file actually declares;
|
|
1771
|
+
// `direction` is the field THIS file (the diagnostic's path) must add.
|
|
1772
|
+
// They are opposites — rendering `direction` as the declared field
|
|
1773
|
+
// would mislabel the source's frontmatter in both directions.
|
|
1774
|
+
missingBackReference: "`{{source}}` declares `{{declared}}: {{ref}}`, but `{{ref}}` (this file) does not back-reference it via `{{direction}}: {{expected}}`"
|
|
1775
|
+
},
|
|
1776
|
+
suggestions: {
|
|
1777
|
+
unknownReference: 'correct "{{ref}}" to an existing ADR number, or remove "{{direction}}: {{ref}}" from the frontmatter',
|
|
1778
|
+
missingBackReference: 'add "{{direction}}: {{expected}}" to the frontmatter of this file'
|
|
1318
1779
|
},
|
|
1319
1780
|
defaultOptions: {},
|
|
1320
1781
|
schema: schema_default8
|
|
@@ -1351,6 +1812,7 @@ var rule8 = {
|
|
|
1351
1812
|
data: {
|
|
1352
1813
|
ref,
|
|
1353
1814
|
source: file.path,
|
|
1815
|
+
declared: FORWARD_FIELD,
|
|
1354
1816
|
direction: BACKWARD_FIELD,
|
|
1355
1817
|
expected: fileRef
|
|
1356
1818
|
}
|
|
@@ -1375,6 +1837,7 @@ var rule8 = {
|
|
|
1375
1837
|
data: {
|
|
1376
1838
|
ref,
|
|
1377
1839
|
source: file.path,
|
|
1840
|
+
declared: BACKWARD_FIELD,
|
|
1378
1841
|
direction: FORWARD_FIELD,
|
|
1379
1842
|
expected: fileRef
|
|
1380
1843
|
}
|
|
@@ -1392,7 +1855,7 @@ function toPosix2(p) {
|
|
|
1392
1855
|
return p.split(sep2).join("/");
|
|
1393
1856
|
}
|
|
1394
1857
|
var pkg = JSON.parse(
|
|
1395
|
-
|
|
1858
|
+
readFileSync5(new URL("../package.json", import.meta.url), "utf8")
|
|
1396
1859
|
);
|
|
1397
1860
|
var main = defineCommand({
|
|
1398
1861
|
meta: {
|
|
@@ -1418,14 +1881,71 @@ var main = defineCommand({
|
|
|
1418
1881
|
},
|
|
1419
1882
|
format: {
|
|
1420
1883
|
type: "string",
|
|
1421
|
-
description: "Reporter format: text (default), json, or
|
|
1884
|
+
description: "Reporter format: text (default), json, sarif, or github",
|
|
1422
1885
|
default: "text"
|
|
1886
|
+
},
|
|
1887
|
+
baseline: {
|
|
1888
|
+
type: "boolean",
|
|
1889
|
+
description: "Subtract .madr-lint/baseline.json when present (use --no-baseline to ignore it)",
|
|
1890
|
+
default: true
|
|
1891
|
+
},
|
|
1892
|
+
"update-baseline": {
|
|
1893
|
+
type: "boolean",
|
|
1894
|
+
description: "Rewrite .madr-lint/baseline.json from a full lint, then exit 0",
|
|
1895
|
+
default: false
|
|
1896
|
+
},
|
|
1897
|
+
quiet: {
|
|
1898
|
+
type: "boolean",
|
|
1899
|
+
description: "Report errors only; suppress warnings from output",
|
|
1900
|
+
default: false
|
|
1901
|
+
},
|
|
1902
|
+
"max-warnings": {
|
|
1903
|
+
type: "string",
|
|
1904
|
+
description: "Exit 1 when warning count exceeds n. n=0 means any warning fails. Negative = no limit.",
|
|
1905
|
+
required: false
|
|
1906
|
+
},
|
|
1907
|
+
config: {
|
|
1908
|
+
type: "string",
|
|
1909
|
+
description: "Path to config file, bypassing auto-discovery",
|
|
1910
|
+
required: false
|
|
1423
1911
|
}
|
|
1424
1912
|
},
|
|
1425
1913
|
run({ args }) {
|
|
1426
1914
|
const cwd = process.cwd();
|
|
1427
|
-
let
|
|
1428
|
-
|
|
1915
|
+
let maxWarnings = -1;
|
|
1916
|
+
const rawMaxWarnings = args["max-warnings"];
|
|
1917
|
+
if (rawMaxWarnings !== void 0) {
|
|
1918
|
+
const parsed = Number(rawMaxWarnings);
|
|
1919
|
+
if (rawMaxWarnings.trim() === "" || !Number.isInteger(parsed)) {
|
|
1920
|
+
console.error(
|
|
1921
|
+
`Invalid --max-warnings "${rawMaxWarnings}": must be an integer.`
|
|
1922
|
+
);
|
|
1923
|
+
process.exit(2);
|
|
1924
|
+
}
|
|
1925
|
+
maxWarnings = parsed;
|
|
1926
|
+
}
|
|
1927
|
+
let config;
|
|
1928
|
+
let configExplicit = false;
|
|
1929
|
+
const configArg = args.config;
|
|
1930
|
+
if (configArg) {
|
|
1931
|
+
const absConfigPath = resolve3(cwd, configArg);
|
|
1932
|
+
try {
|
|
1933
|
+
config = loadConfigFromPath(absConfigPath);
|
|
1934
|
+
configExplicit = true;
|
|
1935
|
+
} catch (err) {
|
|
1936
|
+
if (err instanceof ConfigFileNotFoundError) {
|
|
1937
|
+
console.error(err.message);
|
|
1938
|
+
} else {
|
|
1939
|
+
console.error(
|
|
1940
|
+
`Failed to load config "${configArg}": ${err instanceof Error ? err.message : String(err)}`
|
|
1941
|
+
);
|
|
1942
|
+
}
|
|
1943
|
+
process.exit(2);
|
|
1944
|
+
}
|
|
1945
|
+
} else {
|
|
1946
|
+
config = loadConfig(cwd);
|
|
1947
|
+
}
|
|
1948
|
+
if (!configExplicit && Object.keys(config.rules).length === 0) {
|
|
1429
1949
|
config = resolveExtends({ extends: ["madr-lint:recommended"] });
|
|
1430
1950
|
}
|
|
1431
1951
|
const positionals = args._ ?? [];
|
|
@@ -1461,6 +1981,13 @@ var main = defineCommand({
|
|
|
1461
1981
|
}),
|
|
1462
1982
|
pkgVersion: pkg.version
|
|
1463
1983
|
} : null;
|
|
1984
|
+
const baselineFile = baselinePath(cwd);
|
|
1985
|
+
const updateBaseline = args["update-baseline"] === true;
|
|
1986
|
+
const useBaseline = !updateBaseline && args.baseline !== false;
|
|
1987
|
+
const baseline = useBaseline ? loadBaseline(baselineFile) : null;
|
|
1988
|
+
if (useBaseline && baseline === null && existsSync5(baselineFile)) {
|
|
1989
|
+
console.error(baselineMalformedWarning());
|
|
1990
|
+
}
|
|
1464
1991
|
const allRulesArray = Object.values(rules_exports);
|
|
1465
1992
|
let result;
|
|
1466
1993
|
try {
|
|
@@ -1469,7 +1996,8 @@ var main = defineCommand({
|
|
|
1469
1996
|
ruleSeverity: config.rules,
|
|
1470
1997
|
files,
|
|
1471
1998
|
cwd,
|
|
1472
|
-
cache: cacheConfig
|
|
1999
|
+
cache: cacheConfig,
|
|
2000
|
+
baseline
|
|
1473
2001
|
});
|
|
1474
2002
|
} catch (err) {
|
|
1475
2003
|
if (err instanceof RuleOptionsError) {
|
|
@@ -1478,6 +2006,12 @@ var main = defineCommand({
|
|
|
1478
2006
|
}
|
|
1479
2007
|
throw err;
|
|
1480
2008
|
}
|
|
2009
|
+
if (updateBaseline) {
|
|
2010
|
+
const built = buildBaseline(result.diagnostics);
|
|
2011
|
+
writeBaseline(baselineFile, built);
|
|
2012
|
+
console.log(baselineWriteSummary(built));
|
|
2013
|
+
process.exit(0);
|
|
2014
|
+
}
|
|
1481
2015
|
const rulesByName = new Map(
|
|
1482
2016
|
allRulesArray.map((r) => [r.meta.name, r])
|
|
1483
2017
|
);
|
|
@@ -1489,11 +2023,28 @@ var main = defineCommand({
|
|
|
1489
2023
|
);
|
|
1490
2024
|
process.exit(2);
|
|
1491
2025
|
}
|
|
1492
|
-
|
|
1493
|
-
const
|
|
1494
|
-
|
|
1495
|
-
|
|
1496
|
-
|
|
2026
|
+
const allDiagnostics = result.diagnostics;
|
|
2027
|
+
const warningCount = allDiagnostics.filter((d) => d.severity === "warn").length;
|
|
2028
|
+
const errorCount = allDiagnostics.filter((d) => d.severity === "error").length;
|
|
2029
|
+
const overWarningLimit = maxWarnings >= 0 && warningCount > maxWarnings;
|
|
2030
|
+
const reported = args.quiet ? allDiagnostics.filter((d) => d.severity !== "warn") : allDiagnostics;
|
|
2031
|
+
const suppressAllClear = format === "text" && reported.length === 0 && overWarningLimit;
|
|
2032
|
+
if (!suppressAllClear) {
|
|
2033
|
+
console.log(
|
|
2034
|
+
reporter.format(reported, rulesByName, {
|
|
2035
|
+
baselineHidden: result.baselineHidden
|
|
2036
|
+
})
|
|
2037
|
+
);
|
|
2038
|
+
}
|
|
2039
|
+
if (format === "text" && result.baselineHidden > 0) {
|
|
2040
|
+
console.log(baselineHiddenSummary(result.baselineHidden));
|
|
2041
|
+
}
|
|
2042
|
+
if (overWarningLimit) {
|
|
2043
|
+
console.error(
|
|
2044
|
+
`madr-lint: ${warningCount} warning(s) found, exceeds --max-warnings ${maxWarnings}`
|
|
2045
|
+
);
|
|
2046
|
+
}
|
|
2047
|
+
process.exit(errorCount > 0 || overWarningLimit ? 1 : 0);
|
|
1497
2048
|
}
|
|
1498
2049
|
});
|
|
1499
2050
|
await runMain(main);
|