@kirill.konshin/lint 0.5.2 → 0.5.3

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.
@@ -0,0 +1,347 @@
1
+ // @ts-check
2
+ /**
3
+ * The review file: rendered from audit findings, answered by the owner item by item, processed round by round.
4
+ * Format: references/review-format.md.
5
+ */
6
+ import fs from 'node:fs';
7
+ import path from 'node:path';
8
+
9
+ import { normalize, parseArgs } from './util.mjs';
10
+
11
+ /**
12
+ * @typedef {{
13
+ * repo: string, file: string, line: number, quote: string, ruleName?: string, criteria?: number[], layer: string,
14
+ * whatsWrong: string, proposed: string, evidence?: string[], crossRefs?: string[], needsHumanIntent?: boolean,
15
+ * reversesPastDecision?: string, area?: string, note?: string, cid?: string
16
+ * }} Finding
17
+ * @typedef {{ key?: string, title: string, whatsWrong: string, proposed: string, layer: string, criteria?: number[],
18
+ * needsHumanIntent?: boolean, members: Finding[] }} Theme
19
+ * @typedef {{ id: string, line: number, end: number, heading: string, theme: boolean,
20
+ * members: { quote: string, location: string, line: number, comments: string[] }[],
21
+ * quote: string, location: string, response: string, responseLine: number, state: string, applied: string[] }} Item
22
+ */
23
+
24
+ const RESPONSE_STATES = ['open', 'accepted', 'accepted-with-comment', 'comment', 'rejected', 'rejected-with-comment'];
25
+
26
+ /** @param {string} text */
27
+ const oneLine = (text) => normalize(String(text ?? '')).replace(/\s*\n\s*/g, ' ');
28
+ /** @param {Finding} f */
29
+ const location = (f) => `\`${f.repo} ${f.file}:${f.line}\``;
30
+ /** @param {string} q */
31
+ const quoted = (q) => `“${oneLine(q).replace(/[“”]/g, '"')}”`;
32
+
33
+ /**
34
+ * The extra context a reader needs to decide: evidence, cross references, intent, reversal.
35
+ * @param {Finding | Theme} f
36
+ */
37
+ function context(f) {
38
+ const parts = [];
39
+ if ('reversesPastDecision' in f && f.reversesPastDecision)
40
+ parts.push(`Reverses an earlier decision: ${oneLine(f.reversesPastDecision).replace(/[.\s]+$/, '')}.`);
41
+ if ('evidence' in f && f.evidence?.length)
42
+ parts.push(
43
+ `Evidence: ${f.evidence
44
+ .slice(0, 6)
45
+ .map((e) => `\`${e}\``)
46
+ .join(', ')}.`,
47
+ );
48
+ if ('crossRefs' in f && f.crossRefs?.length) parts.push(`See also: ${f.crossRefs.slice(0, 6).join(', ')}.`);
49
+ return parts.length ? ` ${parts.join(' ')}` : '';
50
+ }
51
+
52
+ /**
53
+ * One item in the mandated five-bullet shape.
54
+ * @param {string} id
55
+ * @param {Finding | Theme} item
56
+ * @param {boolean} theme
57
+ */
58
+ export function renderItem(id, item, theme) {
59
+ const crit = (item.criteria ?? []).join(', ');
60
+ const intent = item.needsHumanIntent ? ' · ❓ intent' : '';
61
+ if (!theme) {
62
+ const f = /** @type {Finding} */ (item);
63
+ return [
64
+ `### ${id} · ${f.layer} · ${f.repo} ${f.area ?? ''}`.trimEnd() + `${crit ? ` · ${crit}` : ''}${intent}`,
65
+ '',
66
+ `* Rule: ${quoted(f.quote)}`,
67
+ ` * Location: ${location(f)}`,
68
+ ` * What’s wrong: ${oneLine(f.whatsWrong)}${context(f)}`,
69
+ ` * Proposed: ${oneLine(f.proposed)}`,
70
+ ` * My response: ⬜`,
71
+ '',
72
+ ].join('\n');
73
+ }
74
+ const t = /** @type {Theme} */ (item);
75
+ return [
76
+ `### ${id} · ${t.layer} · Theme: ${oneLine(t.title)}${crit ? ` · ${crit}` : ''}${intent}`,
77
+ '',
78
+ `* Rule: ${quoted(t.title)} — ${t.members.length} rules:`,
79
+ ...t.members.map((m) => ` * ${quoted(m.quote)} — ${location(m)}${m.note ? ` — ${oneLine(m.note)}` : ''}`),
80
+ ` * Location: each member above`,
81
+ ` * What’s wrong: ${oneLine(t.whatsWrong)}`,
82
+ ` * Proposed: ${oneLine(t.proposed)}`,
83
+ ` * My response: ⬜`,
84
+ '',
85
+ ].join('\n');
86
+ }
87
+
88
+ /**
89
+ * Render audit output into review sections.
90
+ * @param {{ themes?: Theme[], findings?: Finding[] }} data
91
+ * @param {{ start?: number, sections?: { key: string, title: string, areas?: string[], intro?: string }[] }} opts
92
+ */
93
+ export function render(data, { start = 1, sections } = {}) {
94
+ let n = start;
95
+ const next = () => `R-${String(n++).padStart(3, '0')}`;
96
+ const themes = data.themes ?? [];
97
+ const findings = data.findings ?? [];
98
+ const areaOfTheme = (/** @type {Theme} */ t) => {
99
+ const counts = new Map();
100
+ for (const m of t.members) counts.set(m.area, (counts.get(m.area) ?? 0) + 1);
101
+ return [...counts.entries()].sort((a, b) => b[1] - a[1])[0]?.[0];
102
+ };
103
+ const layout =
104
+ sections ??
105
+ [...new Set([...themes.map(areaOfTheme), ...findings.map((f) => f.area)])].map((a) => ({
106
+ key: a ?? 'other',
107
+ title: a ?? 'Other',
108
+ areas: [a],
109
+ }));
110
+ const out = [];
111
+ for (const s of layout) {
112
+ const areas = new Set(s.areas ?? [s.key]);
113
+ const ts = themes.filter((t) => areas.has(areaOfTheme(t)));
114
+ const fs = findings.filter((f) => areas.has(f.area));
115
+ if (!ts.length && !fs.length) continue;
116
+ out.push(`## ${s.title}`, '');
117
+ if (s.intro) out.push(s.intro, '');
118
+ for (const t of ts) out.push(renderItem(next(), t, true));
119
+ for (const f of fs.sort(
120
+ (a, b) => a.repo.localeCompare(b.repo) || a.file.localeCompare(b.file) || a.line - b.line,
121
+ ))
122
+ out.push(renderItem(next(), f, false));
123
+ }
124
+ return { markdown: out.join('\n'), next: n };
125
+ }
126
+
127
+ const ITEM = /^###\s+(R-\d+)\b(.*)$/;
128
+ const FIELD =
129
+ /^\s*[*-]\s+(Rule|Location|What[’']s wrong|Proposed|My response|Applied|Previous response[^:]*)\s*:\s?(.*)$/;
130
+ const MEMBER = /^\s{2,}[*-]\s+“(.+?)”\s+—\s+`([^`]+)`/;
131
+
132
+ /** @param {string} response */
133
+ export function stateOf(response) {
134
+ const r = response.trim();
135
+ if (!r || r === '⬜') return 'open';
136
+ if (r.startsWith('✅')) return r.replace('✅', '').trim() ? 'accepted-with-comment' : 'accepted';
137
+ if (r.startsWith('❌')) return r.replace('❌', '').trim() ? 'rejected-with-comment' : 'rejected';
138
+ if (r.startsWith('⬜')) return r.replace('⬜', '').trim() ? 'comment' : 'open';
139
+ return 'comment';
140
+ }
141
+
142
+ /**
143
+ * Parse a review file into items.
144
+ * @param {string} text
145
+ * @returns {Item[]}
146
+ */
147
+ export function parseReview(text) {
148
+ const lines = text.split('\n');
149
+ /** @type {Item[]} */
150
+ const items = [];
151
+ /** @type {Item | null} */
152
+ let cur = null;
153
+ let field = '';
154
+ lines.forEach((line, i) => {
155
+ const h = ITEM.exec(line);
156
+ if (h || /^#{1,3}\s/.test(line)) {
157
+ if (cur) cur.end = i;
158
+ cur = null;
159
+ field = '';
160
+ if (h) {
161
+ cur = {
162
+ id: h[1],
163
+ line: i + 1,
164
+ end: lines.length,
165
+ heading: h[2],
166
+ theme: /Theme:/.test(h[2]),
167
+ members: [],
168
+ quote: '',
169
+ location: '',
170
+ response: '',
171
+ responseLine: 0,
172
+ state: 'open',
173
+ applied: [],
174
+ };
175
+ items.push(cur);
176
+ }
177
+ return;
178
+ }
179
+ if (!cur) return;
180
+ const f = FIELD.exec(line);
181
+ if (f) {
182
+ field = f[1].replace('’', "'");
183
+ if (field === 'Rule') cur.quote = f[2];
184
+ else if (field === 'Location') cur.location = f[2];
185
+ else if (field === 'My response') {
186
+ cur.response = f[2];
187
+ cur.responseLine = i + 1;
188
+ } else if (field === 'Applied') cur.applied.push(f[2]);
189
+ return;
190
+ }
191
+ const m = MEMBER.exec(line);
192
+ if (m && cur.theme && field === 'Rule') {
193
+ cur.members.push({ quote: m[1], location: m[2], line: i + 1, comments: [] });
194
+ return;
195
+ }
196
+ if (!line.trim()) return;
197
+ if (field === 'My response') cur.response += `\n${line.trim()}`;
198
+ else if (field === 'Rule' && cur.members.length) cur.members[cur.members.length - 1].comments.push(line.trim());
199
+ });
200
+ for (const it of items) it.state = stateOf(it.response);
201
+ return items;
202
+ }
203
+
204
+ /**
205
+ * Locations a review names: `NAME path:line`.
206
+ * @param {string} loc
207
+ */
208
+ const parseLocation = (loc) => {
209
+ const m = /`?([\w-]+)\s+([^`\s]+):(\d+)`?/.exec(loc);
210
+ return m ? { repo: m[1], file: m[2], line: Number(m[3]) } : null;
211
+ };
212
+
213
+ /**
214
+ * Every quote must be found, fragment by fragment in order, at its location (a window from the line on).
215
+ * @param {Item[]} items
216
+ * @param {Map<string, string>} roots NAME → absolute path
217
+ */
218
+ export function verify(items, roots) {
219
+ const problems = [];
220
+ const cache = new Map();
221
+ const check = (/** @type {string} */ id, /** @type {string} */ quote, /** @type {string} */ loc) => {
222
+ const at = parseLocation(loc);
223
+ if (!at) return problems.push(`${id}: location not understood: ${loc}`);
224
+ const root = roots.get(at.repo);
225
+ if (!root) return problems.push(`${id}: unknown repository ${at.repo} (pass --root ${at.repo}=<path>)`);
226
+ const abs = path.join(root, at.file);
227
+ if (!cache.has(abs)) cache.set(abs, fs.existsSync(abs) ? fs.readFileSync(abs, 'utf8').split('\n') : null);
228
+ const lines = cache.get(abs);
229
+ if (!lines) return problems.push(`${id}: ${at.repo} ${at.file} does not exist`);
230
+ if (at.line < 1 || at.line > lines.length)
231
+ return problems.push(`${id}: ${at.repo} ${at.file}:${at.line} is past the end (${lines.length} lines)`);
232
+ const window = normalize(lines.slice(at.line - 1, at.line + 59).join(' ')).replace(/[“”]/g, '"');
233
+ const q = quote.replace(/^“|”$/g, '').replace(/[“”]/g, '"');
234
+ let from = 0;
235
+ for (const frag of q
236
+ .split(/…|\.\.\./)
237
+ .map((x) => normalize(x))
238
+ .filter((x) => x.length > 2)) {
239
+ const idx = window.indexOf(frag, from);
240
+ if (idx < 0)
241
+ return problems.push(
242
+ `${id}: quote not found at ${at.repo} ${at.file}:${at.line}: "${frag.slice(0, 80)}"`,
243
+ );
244
+ from = idx + frag.length;
245
+ }
246
+ };
247
+ for (const it of items) {
248
+ if (it.theme) for (const m of it.members) check(it.id, m.quote, m.location);
249
+ else check(it.id, it.quote.replace(/^\s*/, ''), it.location);
250
+ }
251
+ return problems;
252
+ }
253
+
254
+ /** @param {string} text @param {Item[]} items */
255
+ export function lint(text, items) {
256
+ const problems = [];
257
+ const seen = new Set();
258
+ const lines = text.split('\n');
259
+ for (const it of items) {
260
+ if (seen.has(it.id)) problems.push(`${it.id}: duplicate id`);
261
+ seen.add(it.id);
262
+ const body = lines.slice(it.line - 1, it.end).join('\n');
263
+ for (const field of ['Rule', 'Location', "What’s wrong|What's wrong", 'Proposed', 'My response'])
264
+ if (!new RegExp(`^\\s*[*-]\\s+(?:${field})\\s*:`, 'm').test(body))
265
+ problems.push(`${it.id}: missing "${field.split('|')[0]}"`);
266
+ if (!it.theme && !/^\s*“.+”/.test(it.quote)) problems.push(`${it.id}: the rule is not quoted “…”`);
267
+ if (!it.theme && !parseLocation(it.location)) problems.push(`${it.id}: location is not \`NAME path:line\``);
268
+ if (it.theme && !it.members.length) problems.push(`${it.id}: a theme lists no members`);
269
+ if (!it.responseLine) problems.push(`${it.id}: no response line`);
270
+ }
271
+ return problems;
272
+ }
273
+
274
+ /** @param {Item[]} items */
275
+ export function status(items) {
276
+ const counts = Object.fromEntries(RESPONSE_STATES.map((s) => [s, 0]));
277
+ for (const it of items) counts[it.state]++;
278
+ const pending = items.filter((it) => it.state.startsWith('accepted') && !it.applied.length).map((it) => it.id);
279
+ const memberComments = items.filter((it) => it.members.some((m) => m.comments.length)).map((it) => it.id);
280
+ return {
281
+ total: items.length,
282
+ counts,
283
+ open: items.filter((it) => it.state === 'open').map((it) => it.id),
284
+ comments: items.filter((it) => it.state === 'comment' || it.state.endsWith('-with-comment')).map((it) => it.id),
285
+ acceptedNotApplied: pending,
286
+ rejected: items.filter((it) => it.state.startsWith('rejected')).map((it) => it.id),
287
+ memberComments,
288
+ resolved: items.every(
289
+ (it) =>
290
+ it.state !== 'open' &&
291
+ it.state !== 'comment' &&
292
+ (!it.state.startsWith('accepted') || it.applied.length),
293
+ ),
294
+ };
295
+ }
296
+
297
+ /**
298
+ * @param {string[]} argv `render <data.json> [--out f] [--append] [--sections s.json]` | `status <file>` | `verify <file>` | `lint <file>`
299
+ * @param {{ name: string, path: string }[]} roots
300
+ */
301
+ export function reviewCli(argv, roots) {
302
+ const [sub, ...rest] = argv;
303
+ const opts = parseArgs(rest, ['root']);
304
+ const file = opts._[0];
305
+ if (sub === 'render') {
306
+ const data = JSON.parse(fs.readFileSync(file, 'utf8'));
307
+ const existing = opts.out && opts.append && fs.existsSync(opts.out) ? fs.readFileSync(opts.out, 'utf8') : '';
308
+ const last = Math.max(0, ...parseReview(existing).map((it) => Number(it.id.slice(2))));
309
+ const sections = opts.sections ? JSON.parse(fs.readFileSync(opts.sections, 'utf8')) : undefined;
310
+ const { markdown } = render(data, { start: last + 1, sections });
311
+ const round = opts.round ? `## Round ${opts.round} — new\n\n` : '';
312
+ const out = existing ? `${existing.trimEnd()}\n\n${round}${markdown}` : markdown;
313
+ if (opts.out) fs.writeFileSync(opts.out, out.trimEnd() + '\n');
314
+ else process.stdout.write(out);
315
+ return 0;
316
+ }
317
+ const text = fs.readFileSync(file, 'utf8');
318
+ const items = parseReview(text);
319
+ if (sub === 'status') {
320
+ const s = status(items);
321
+ if (opts.json) process.stdout.write(JSON.stringify(s, null, 2) + '\n');
322
+ else {
323
+ process.stdout.write(
324
+ `${s.total} items — ${Object.entries(s.counts)
325
+ .map(([k, v]) => `${k} ${v}`)
326
+ .join(', ')}\n`,
327
+ );
328
+ if (s.open.length) process.stdout.write(`open: ${s.open.join(' ')}\n`);
329
+ if (s.comments.length) process.stdout.write(`with comments: ${s.comments.join(' ')}\n`);
330
+ if (s.memberComments.length)
331
+ process.stdout.write(`themes with member comments: ${s.memberComments.join(' ')}\n`);
332
+ if (s.acceptedNotApplied.length)
333
+ process.stdout.write(`accepted, not yet applied: ${s.acceptedNotApplied.join(' ')}\n`);
334
+ process.stdout.write(s.resolved ? 'resolved: every item answered and applied\n' : 'not resolved\n');
335
+ }
336
+ return s.resolved ? 0 : 1;
337
+ }
338
+ if (sub === 'verify' || sub === 'lint') {
339
+ const problems =
340
+ sub === 'lint' ? lint(text, items) : verify(items, new Map(roots.map((r) => [r.name, r.path])));
341
+ for (const p of problems) process.stdout.write(p + '\n');
342
+ process.stderr.write(`${items.length} items, ${problems.length} problem(s)\n`);
343
+ return problems.length ? 1 : 0;
344
+ }
345
+ process.stderr.write('usage: steward review render|status|verify|lint <file>\n');
346
+ return 2;
347
+ }