@voidh4x0r/slopgate 0.0.0-stage → 0.1.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (50) hide show
  1. package/CHANGELOG.md +82 -0
  2. package/LICENSE +21 -0
  3. package/README.md +304 -2
  4. package/dist/ast.d.ts +29 -0
  5. package/dist/ast.js +3 -0
  6. package/dist/baseline.d.ts +33 -0
  7. package/dist/baseline.js +104 -0
  8. package/dist/cli.d.ts +9 -0
  9. package/dist/cli.js +487 -0
  10. package/dist/config.d.ts +25 -0
  11. package/dist/config.js +91 -0
  12. package/dist/data/python-stdlib.d.ts +21 -0
  13. package/dist/data/python-stdlib.js +92 -0
  14. package/dist/deps.d.ts +8 -0
  15. package/dist/deps.js +491 -0
  16. package/dist/diff.d.ts +30 -0
  17. package/dist/diff.js +217 -0
  18. package/dist/engine.d.ts +15 -0
  19. package/dist/engine.js +169 -0
  20. package/dist/files.d.ts +33 -0
  21. package/dist/files.js +214 -0
  22. package/dist/mcp.d.ts +41 -0
  23. package/dist/mcp.js +226 -0
  24. package/dist/parser.d.ts +3 -0
  25. package/dist/parser.js +45 -0
  26. package/dist/reporters/github.d.ts +2 -0
  27. package/dist/reporters/github.js +44 -0
  28. package/dist/reporters/json.d.ts +10 -0
  29. package/dist/reporters/json.js +36 -0
  30. package/dist/reporters/pretty.d.ts +12 -0
  31. package/dist/reporters/pretty.js +103 -0
  32. package/dist/reporters/sarif.d.ts +2 -0
  33. package/dist/reporters/sarif.js +75 -0
  34. package/dist/rules/helpers.d.ts +53 -0
  35. package/dist/rules/helpers.js +178 -0
  36. package/dist/rules/index.d.ts +3 -0
  37. package/dist/rules/index.js +4 -0
  38. package/dist/rules/python.d.ts +2 -0
  39. package/dist/rules/python.js +632 -0
  40. package/dist/rules/typescript.d.ts +2 -0
  41. package/dist/rules/typescript.js +563 -0
  42. package/dist/suppress.d.ts +12 -0
  43. package/dist/suppress.js +52 -0
  44. package/dist/types.d.ts +95 -0
  45. package/dist/types.js +1 -0
  46. package/grammars/README.md +28 -0
  47. package/grammars/tree-sitter-python.wasm +0 -0
  48. package/grammars/tree-sitter-tsx.wasm +0 -0
  49. package/grammars/tree-sitter-typescript.wasm +0 -0
  50. package/package.json +61 -4
package/dist/cli.js ADDED
@@ -0,0 +1,487 @@
1
+ #!/usr/bin/env node
2
+ import { mkdir, readFile, realpath, stat, writeFile } from 'node:fs/promises';
3
+ import * as path from 'node:path';
4
+ import process from 'node:process';
5
+ import { fileURLToPath } from 'node:url';
6
+ import { loadBaseline, partitionByBaseline, writeBaseline } from "./baseline.js";
7
+ import { confidenceRank, loadConfig, meetsConfidence } from "./config.js";
8
+ import { assertSafeRef, diffSince, findRepoRoot, isInDiffWithPrefix } from "./diff.js";
9
+ import { scanProject } from "./engine.js";
10
+ import { serveMcp } from "./mcp.js";
11
+ import { renderGithub } from "./reporters/github.js";
12
+ import { renderJson } from "./reporters/json.js";
13
+ import { renderPretty } from "./reporters/pretty.js";
14
+ import { renderSarif } from "./reporters/sarif.js";
15
+ import { ALL_RULES, RULE_BY_ID } from "./rules/index.js";
16
+ const FALLBACK_VERSION = '0.1.0';
17
+ const DEFAULT_BASELINE = '.slopgate-baseline.json';
18
+ const CONFIDENCES = ['high', 'medium', 'low'];
19
+ const FAIL_ON = ['high', 'medium', 'low', 'none'];
20
+ const FORMATS = ['pretty', 'json', 'sarif', 'github'];
21
+ const HELP = `slopgate ${FALLBACK_VERSION} — the slop gate for AI-written code
22
+
23
+ Usage:
24
+ slopgate [path] [options] scan a directory or file (default: .)
25
+ slopgate rules list every rule
26
+ slopgate mcp [path] run as an MCP server on stdio
27
+ slopgate init add config + GitHub Action
28
+ slopgate --version | --help
29
+
30
+ Options:
31
+ --format <pretty|json|sarif|github> output format (default: pretty)
32
+ --confidence <high|medium|low> minimum confidence to show (default: high)
33
+ --fail-on <high|medium|low|none> minimum confidence that fails the run (default: high)
34
+ --baseline [path] findings file to ignore (default: ${DEFAULT_BASELINE})
35
+ --write-baseline [path] record current findings as the baseline, then exit 0
36
+ --diff [ref] only report findings on lines changed since ref (default: HEAD)
37
+ --include <glob> extra include pattern (repeatable)
38
+ --exclude <glob> extra exclude pattern (repeatable)
39
+ --rule <id> only run this rule (repeatable)
40
+ --no-color disable ANSI colors
41
+ --quiet only print the summary
42
+ --verbose print warnings and per-file details
43
+ --force overwrite files in \`init\`
44
+ -h, --help show this help
45
+ -V, --version print the version
46
+
47
+ Exit codes:
48
+ 0 no findings at or above --fail-on
49
+ 1 findings at or above --fail-on
50
+ 2 usage or configuration error
51
+
52
+ Suppression:
53
+ # slopgate-ignore-next-line py/noop-test
54
+ // slopgate-ignore-line ts/stub-function
55
+ # slopgate-disable-file
56
+
57
+ MCP (for coding agents):
58
+ slopgate mcp
59
+ {"mcpServers":{"slopgate":{"command":"npx","args":["-y","@voidh4x0r/slopgate","mcp"]}}}
60
+
61
+ Docs: https://github.com/VoidH4x0r/slopgate
62
+ `;
63
+ function defaultOptions() {
64
+ return {
65
+ command: 'scan',
66
+ paths: [],
67
+ format: 'pretty',
68
+ confidence: undefined,
69
+ failOn: undefined,
70
+ baseline: undefined,
71
+ writeBaseline: undefined,
72
+ diff: undefined,
73
+ include: [],
74
+ exclude: [],
75
+ rules: [],
76
+ color: true,
77
+ quiet: false,
78
+ verbose: false,
79
+ force: false,
80
+ };
81
+ }
82
+ const VALUE_FLAGS = new Set([
83
+ 'format',
84
+ 'confidence',
85
+ 'fail-on',
86
+ 'baseline',
87
+ 'write-baseline',
88
+ 'diff',
89
+ 'include',
90
+ 'exclude',
91
+ 'rule',
92
+ 'paths',
93
+ ]);
94
+ /** `--diff` is the only value flag whose value is optional. */
95
+ const OPTIONAL_VALUE_FLAGS = new Set(['diff', 'baseline', 'write-baseline']);
96
+ function parseArgs(argv) {
97
+ const options = defaultOptions();
98
+ for (let index = 0; index < argv.length; index += 1) {
99
+ const token = argv[index] ?? '';
100
+ if (token === '--') {
101
+ options.paths.push(...argv.slice(index + 1));
102
+ break;
103
+ }
104
+ if (!token.startsWith('-')) {
105
+ if (options.command === 'scan' && options.paths.length === 0 && ['scan', 'rules', 'init', 'mcp', 'help'].includes(token)) {
106
+ options.command = token;
107
+ continue;
108
+ }
109
+ options.paths.push(token);
110
+ continue;
111
+ }
112
+ if (token === '-h' || token === '--help') {
113
+ options.command = 'help';
114
+ continue;
115
+ }
116
+ if (token === '-V' || token === '--version') {
117
+ options.command = 'version';
118
+ continue;
119
+ }
120
+ if (token === '--no-color') {
121
+ options.color = false;
122
+ continue;
123
+ }
124
+ if (token === '--color') {
125
+ options.color = true;
126
+ continue;
127
+ }
128
+ if (token === '--quiet') {
129
+ options.quiet = true;
130
+ continue;
131
+ }
132
+ if (token === '--verbose') {
133
+ options.verbose = true;
134
+ continue;
135
+ }
136
+ if (token === '--force') {
137
+ options.force = true;
138
+ continue;
139
+ }
140
+ const equals = token.indexOf('=');
141
+ const rawName = (equals === -1 ? token : token.slice(0, equals)).replace(/^--?/, '');
142
+ if (!VALUE_FLAGS.has(rawName))
143
+ return { options, error: `unknown option: ${token}` };
144
+ let value;
145
+ if (equals !== -1) {
146
+ value = token.slice(equals + 1);
147
+ }
148
+ else {
149
+ const next = argv[index + 1];
150
+ if (next !== undefined && !next.startsWith('-')) {
151
+ value = next;
152
+ index += 1;
153
+ }
154
+ else if (!OPTIONAL_VALUE_FLAGS.has(rawName)) {
155
+ return { options, error: `option --${rawName} needs a value` };
156
+ }
157
+ }
158
+ switch (rawName) {
159
+ case 'format':
160
+ if (!value || !FORMATS.includes(value)) {
161
+ return { options, error: `--format must be one of ${FORMATS.join(', ')}` };
162
+ }
163
+ options.format = value;
164
+ break;
165
+ case 'confidence':
166
+ if (!value || !CONFIDENCES.includes(value)) {
167
+ return { options, error: `--confidence must be one of ${CONFIDENCES.join(', ')}` };
168
+ }
169
+ options.confidence = value;
170
+ break;
171
+ case 'fail-on':
172
+ if (!value || !FAIL_ON.includes(value)) {
173
+ return { options, error: `--fail-on must be one of ${FAIL_ON.join(', ')}` };
174
+ }
175
+ options.failOn = value;
176
+ break;
177
+ case 'baseline':
178
+ options.baseline = value ?? DEFAULT_BASELINE;
179
+ break;
180
+ case 'write-baseline':
181
+ options.writeBaseline = value ?? DEFAULT_BASELINE;
182
+ break;
183
+ case 'diff':
184
+ options.diff = value ?? 'HEAD';
185
+ break;
186
+ case 'include':
187
+ if (value)
188
+ options.include.push(value);
189
+ break;
190
+ case 'exclude':
191
+ if (value)
192
+ options.exclude.push(value);
193
+ break;
194
+ case 'rule':
195
+ if (value)
196
+ options.rules.push(value);
197
+ break;
198
+ default:
199
+ break;
200
+ }
201
+ }
202
+ return { options };
203
+ }
204
+ /** Real process streams. Tests pass their own collector instead. */
205
+ export function defaultIo() {
206
+ return {
207
+ out: (text) => process.stdout.write(text),
208
+ err: (text) => process.stderr.write(text),
209
+ isTTY: process.stdout.isTTY === true,
210
+ };
211
+ }
212
+ function writeOut(io, text) {
213
+ io.out(text.endsWith('\n') ? text : text + '\n');
214
+ }
215
+ function warn(io, options, message) {
216
+ if (!options.quiet)
217
+ io.err(`slopgate: ${message}\n`);
218
+ }
219
+ async function runRules(options, io) {
220
+ const rows = ALL_RULES.map((rule) => ({
221
+ id: rule.meta.id,
222
+ severity: rule.meta.severity,
223
+ confidence: rule.meta.confidence,
224
+ languages: rule.meta.languages.join(','),
225
+ title: rule.meta.title,
226
+ }));
227
+ const idWidth = Math.max(...rows.map((row) => row.id.length), 2);
228
+ const sevWidth = Math.max(...rows.map((row) => row.severity.length), 8);
229
+ const confWidth = Math.max(...rows.map((row) => row.confidence.length), 10);
230
+ const langWidth = Math.max(...rows.map((row) => row.languages.length), 9);
231
+ writeOut(io, `\n${'id'.padEnd(idWidth)} ${'severity'.padEnd(sevWidth)} ${'confidence'.padEnd(confWidth)} ${'languages'.padEnd(langWidth)} title\n`);
232
+ for (const row of rows) {
233
+ writeOut(io, `${row.id.padEnd(idWidth)} ${row.severity.padEnd(sevWidth)} ${row.confidence.padEnd(confWidth)} ${row.languages.padEnd(langWidth)} ${row.title}\n`);
234
+ }
235
+ writeOut(io, '');
236
+ void options;
237
+ return 0;
238
+ }
239
+ async function exists(file) {
240
+ try {
241
+ await readFile(file);
242
+ return true;
243
+ }
244
+ catch {
245
+ return false;
246
+ }
247
+ }
248
+ async function readVersion() {
249
+ try {
250
+ const text = await readFile(new URL('../package.json', import.meta.url), 'utf8');
251
+ const parsed = JSON.parse(text);
252
+ return typeof parsed.version === 'string' ? parsed.version : FALLBACK_VERSION;
253
+ }
254
+ catch {
255
+ return FALLBACK_VERSION;
256
+ }
257
+ }
258
+ /**
259
+ * Deliberately minimal: everything else falls back to the defaults, and a
260
+ * short config is easier to review than a 20-line dump of glob patterns.
261
+ */
262
+ const INIT_CONFIG = {
263
+ exclude: [],
264
+ rules: {},
265
+ confidence: 'high',
266
+ failOn: 'high',
267
+ };
268
+ const INIT_WORKFLOW = (version) => `name: slopgate
269
+
270
+ on:
271
+ push:
272
+ branches: [main]
273
+ pull_request:
274
+
275
+ permissions:
276
+ contents: read
277
+
278
+ jobs:
279
+ slopgate:
280
+ name: slopgate
281
+ runs-on: ubuntu-latest
282
+ steps:
283
+ - uses: actions/checkout@v4
284
+ - uses: actions/setup-node@v4
285
+ with:
286
+ node-version: 22
287
+ - name: Scan for AI slop
288
+ run: npx --yes @voidh4x0r/slopgate@${version} . --fail-on high --format pretty
289
+ `;
290
+ async function runInit(options, io, version) {
291
+ const root = path.resolve(options.paths[0] ?? '.');
292
+ await mkdir(root, { recursive: true });
293
+ const configPath = path.join(root, '.slopgate.json');
294
+ const workflowPath = path.join(root, '.github', 'workflows', 'slopgate.yml');
295
+ if (!options.force && (await exists(configPath))) {
296
+ warn(io, options, `${path.relative(process.cwd(), configPath)} already exists (use --force to overwrite)`);
297
+ }
298
+ else {
299
+ await writeFile(configPath, JSON.stringify(INIT_CONFIG, null, 2) + '\n', 'utf8');
300
+ writeOut(io, `created ${path.relative(process.cwd(), configPath)}`);
301
+ }
302
+ if (!options.force && (await exists(workflowPath))) {
303
+ warn(io, options, `${path.relative(process.cwd(), workflowPath)} already exists (use --force to overwrite)`);
304
+ }
305
+ else {
306
+ await mkdir(path.dirname(workflowPath), { recursive: true });
307
+ await writeFile(workflowPath, INIT_WORKFLOW(version), 'utf8');
308
+ writeOut(io, `created ${path.relative(process.cwd(), workflowPath)}`);
309
+ }
310
+ writeOut(io, 'next: npx @voidh4x0r/slopgate . --write-baseline, then commit the baseline');
311
+ return 0;
312
+ }
313
+ async function runMcp(options) {
314
+ const root = path.resolve(options.paths[0] ?? '.');
315
+ const info = await stat(root).catch(() => undefined);
316
+ if (!info?.isDirectory()) {
317
+ throw new Error(`MCP root is not a directory: ${root}`);
318
+ }
319
+ await serveMcp(root, await readVersion());
320
+ return 0;
321
+ }
322
+ async function runScan(options, io) {
323
+ if (options.paths.length > 1) {
324
+ throw new Error('only one path is supported; run slopgate once per path');
325
+ }
326
+ const target = path.resolve(options.paths[0] ?? '.');
327
+ const targetInfo = await stat(target).catch(() => undefined);
328
+ if (!targetInfo) {
329
+ throw new Error(`path not found: ${target}`);
330
+ }
331
+ const projectRoot = targetInfo.isFile() ? path.dirname(target) : target;
332
+ const { config, file: configFile } = await loadConfig(projectRoot);
333
+ if (options.rules.length > 0) {
334
+ const unknown = options.rules.filter((id) => !RULE_BY_ID.has(id));
335
+ if (unknown.length > 0) {
336
+ throw new Error(`unknown rule id: ${unknown.join(', ')} (run \`slopgate rules\` to list the ${ALL_RULES.length} rule ids)`);
337
+ }
338
+ }
339
+ if (options.diff !== undefined) {
340
+ // Fail fast, before spawning git, on refs that look like options.
341
+ assertSafeRef(options.diff);
342
+ }
343
+ const merged = {
344
+ ...config,
345
+ include: [...config.include, ...options.include],
346
+ exclude: [...config.exclude, ...options.exclude],
347
+ };
348
+ if (options.confidence)
349
+ merged.confidence = options.confidence;
350
+ if (options.failOn)
351
+ merged.failOn = options.failOn;
352
+ const result = await scanProject({
353
+ root: target,
354
+ config: merged,
355
+ ...(options.rules.length > 0 ? { onlyRules: new Set(options.rules) } : {}),
356
+ });
357
+ for (const message of result.warnings)
358
+ warn(io, options, message);
359
+ if (result.stats.files === 0) {
360
+ throw new Error(`no files matched under ${path.relative(process.cwd(), target) || '.'} (check include/exclude patterns)`);
361
+ }
362
+ const baselinePath = path.resolve(projectRoot, options.baseline ?? DEFAULT_BASELINE);
363
+ const explicitWrite = options.writeBaseline;
364
+ if (explicitWrite) {
365
+ const writeTarget = path.resolve(projectRoot, explicitWrite);
366
+ // Record the current findings, not the diff-filtered subset.
367
+ await writeBaseline(writeTarget, result.findings);
368
+ writeOut(io, `wrote ${result.findings.length} findings to ${path.relative(process.cwd(), writeTarget)}`);
369
+ return 0;
370
+ }
371
+ let findings = result.findings;
372
+ let onlyDiff = 0;
373
+ if (options.diff !== undefined) {
374
+ // git paths are relative to the repository root, not to the scan target.
375
+ const repoRoot = await findRepoRoot(projectRoot);
376
+ const set = await diffSince(repoRoot, options.diff);
377
+ const prefix = path.relative(repoRoot, target);
378
+ const before = findings.length;
379
+ findings = findings.filter((finding) => isInDiffWithPrefix(finding, set, prefix));
380
+ onlyDiff = before - findings.length;
381
+ }
382
+ const baseline = (await loadBaseline(baselinePath)) ?? undefined;
383
+ if (baseline === undefined && options.baseline !== undefined) {
384
+ throw new Error(`baseline file not found: ${baselinePath}`);
385
+ }
386
+ const { fresh, known } = partitionByBaseline(findings, baseline);
387
+ // `--fail-on` below `--confidence` must lower the display threshold too,
388
+ // otherwise the setting can never fail CI (the findings are filtered out).
389
+ const displayConfidence = merged.failOn === 'none' || confidenceRank(merged.confidence) <= confidenceRank(merged.failOn)
390
+ ? merged.confidence
391
+ : merged.failOn;
392
+ const visible = fresh.filter((finding) => meetsConfidence(finding.confidence, displayConfidence));
393
+ const hidden = fresh.length - visible.length;
394
+ const run = {
395
+ visible,
396
+ stats: result.stats,
397
+ suppressed: result.suppressedCount,
398
+ baselined: known.length,
399
+ hidden,
400
+ onlyDiff,
401
+ };
402
+ const version = await readVersion();
403
+ if (options.format === 'json') {
404
+ writeOut(io, renderJson({
405
+ findings: visible,
406
+ stats: run.stats,
407
+ version,
408
+ suppressedByComment: run.suppressed,
409
+ baselined: run.baselined,
410
+ hiddenByConfidence: run.hidden,
411
+ }));
412
+ }
413
+ else if (options.format === 'sarif') {
414
+ writeOut(io, renderSarif(visible, version));
415
+ }
416
+ else if (options.format === 'github') {
417
+ writeOut(io, renderGithub(visible, run.stats));
418
+ }
419
+ else {
420
+ writeOut(io, renderPretty({
421
+ findings: visible,
422
+ stats: run.stats,
423
+ suppressedByComment: run.suppressed,
424
+ baselined: run.baselined,
425
+ hiddenByConfidence: run.hidden,
426
+ version,
427
+ color: options.color && io.isTTY && !process.env.NO_COLOR,
428
+ quiet: options.quiet,
429
+ }));
430
+ if (options.verbose) {
431
+ writeOut(io, ` config: ${configFile ?? '(none)'} baseline: ${baseline ? path.relative(process.cwd(), baselinePath) : '(none)'}` +
432
+ (onlyDiff > 0 ? ` diff-only: ${onlyDiff} finding(s) outside the diff were ignored` : '') +
433
+ '\n');
434
+ }
435
+ }
436
+ if (merged.failOn === 'none')
437
+ return 0;
438
+ const failing = visible.some((finding) => meetsConfidence(finding.confidence, merged.failOn));
439
+ return failing ? 1 : 0;
440
+ }
441
+ export async function main(argv, io = defaultIo()) {
442
+ const { options, error } = parseArgs(argv);
443
+ if (error) {
444
+ io.err(`slopgate: ${error}\n\n${HELP}`);
445
+ return 2;
446
+ }
447
+ try {
448
+ switch (options.command) {
449
+ case 'help':
450
+ writeOut(io, HELP);
451
+ return 0;
452
+ case 'version':
453
+ writeOut(io, await readVersion());
454
+ return 0;
455
+ case 'rules':
456
+ return await runRules(options, io);
457
+ case 'init':
458
+ return await runInit(options, io, await readVersion());
459
+ case 'mcp':
460
+ return await runMcp(options);
461
+ case 'scan':
462
+ return await runScan(options, io);
463
+ default:
464
+ io.err(`slopgate: unknown command\n\n${HELP}`);
465
+ return 2;
466
+ }
467
+ }
468
+ catch (caught) {
469
+ io.err(`slopgate: ${caught.message}\n`);
470
+ return 2;
471
+ }
472
+ }
473
+ const entry = process.argv[1];
474
+ if (entry !== undefined) {
475
+ try {
476
+ const [realEntry, self] = await Promise.all([realpath(entry), realpath(fileURLToPath(import.meta.url))]);
477
+ if (realEntry === self) {
478
+ process.exitCode = await main(process.argv.slice(2), defaultIo());
479
+ }
480
+ }
481
+ catch (error) {
482
+ if (process.env.SLOPGATE_DEBUG) {
483
+ process.stderr.write(`slopgate: entry-point detection failed: ${error.message}\n`);
484
+ }
485
+ // Imported from another module (or a path we cannot resolve): stay silent.
486
+ }
487
+ }
@@ -0,0 +1,25 @@
1
+ import type { Confidence, Severity } from './types.ts';
2
+ export type FailOn = 'high' | 'medium' | 'low' | 'none';
3
+ export interface Config {
4
+ include: string[];
5
+ exclude: string[];
6
+ /** Top-level module names to always treat as declared. */
7
+ ignoreModules: string[];
8
+ /** Rule id -> 'off' or an explicit severity. */
9
+ rules: Record<string, 'off' | Severity>;
10
+ /** Minimum confidence to display. */
11
+ confidence: Confidence;
12
+ /** Minimum confidence that makes the process exit non-zero. */
13
+ failOn: FailOn;
14
+ }
15
+ export interface LoadedConfig {
16
+ config: Config;
17
+ file: string | undefined;
18
+ }
19
+ export declare const CONFIG_FILENAMES: readonly [".slopgate.json", "slopgate.config.json"];
20
+ export declare const DEFAULT_CONFIG: Config;
21
+ export declare function confidenceRank(c: Confidence): number;
22
+ export declare function meetsConfidence(value: Confidence, minimum: Confidence): boolean;
23
+ /** Merge a user-supplied config object over the defaults, validating as we go. */
24
+ export declare function normalizeConfig(raw: unknown): Config;
25
+ export declare function loadConfig(root: string): Promise<LoadedConfig>;
package/dist/config.js ADDED
@@ -0,0 +1,91 @@
1
+ import { readFile } from 'node:fs/promises';
2
+ import * as path from 'node:path';
3
+ import { DEFAULT_INCLUDE } from "./files.js";
4
+ export const CONFIG_FILENAMES = ['.slopgate.json', 'slopgate.config.json'];
5
+ export const DEFAULT_CONFIG = {
6
+ include: [...DEFAULT_INCLUDE],
7
+ exclude: [],
8
+ ignoreModules: [],
9
+ rules: {},
10
+ confidence: 'high',
11
+ failOn: 'high',
12
+ };
13
+ const CONFIDENCE_RANK = { low: 0, medium: 1, high: 2 };
14
+ const SEVERITIES = ['error', 'warning', 'info'];
15
+ const FAIL_ON = ['high', 'medium', 'low', 'none'];
16
+ export function confidenceRank(c) {
17
+ return CONFIDENCE_RANK[c];
18
+ }
19
+ export function meetsConfidence(value, minimum) {
20
+ return CONFIDENCE_RANK[value] >= CONFIDENCE_RANK[minimum];
21
+ }
22
+ function asStringArray(value, field) {
23
+ if (value === undefined)
24
+ return undefined;
25
+ if (!Array.isArray(value) || value.some((item) => typeof item !== 'string')) {
26
+ throw new Error(`config field "${field}" must be an array of strings`);
27
+ }
28
+ return value;
29
+ }
30
+ /** Merge a user-supplied config object over the defaults, validating as we go. */
31
+ export function normalizeConfig(raw) {
32
+ if (raw === null || typeof raw !== 'object' || Array.isArray(raw)) {
33
+ throw new Error('config must be a JSON object');
34
+ }
35
+ const input = raw;
36
+ const config = { ...DEFAULT_CONFIG, rules: {} };
37
+ config.include = asStringArray(input.include, 'include') ?? config.include;
38
+ config.exclude = asStringArray(input.exclude, 'exclude') ?? config.exclude;
39
+ config.ignoreModules = asStringArray(input.ignoreModules, 'ignoreModules') ?? config.ignoreModules;
40
+ if (input.rules !== undefined) {
41
+ if (input.rules === null || typeof input.rules !== 'object' || Array.isArray(input.rules)) {
42
+ throw new Error('config field "rules" must be an object');
43
+ }
44
+ for (const [ruleId, value] of Object.entries(input.rules)) {
45
+ if (value === 'off') {
46
+ config.rules[ruleId] = 'off';
47
+ }
48
+ else if (typeof value === 'string' && SEVERITIES.includes(value)) {
49
+ config.rules[ruleId] = value;
50
+ }
51
+ else {
52
+ throw new Error(`rule "${ruleId}" must be "off", "error", "warning" or "info"`);
53
+ }
54
+ }
55
+ }
56
+ if (input.confidence !== undefined) {
57
+ if (typeof input.confidence !== 'string' ||
58
+ !Object.hasOwn(CONFIDENCE_RANK, input.confidence)) {
59
+ throw new Error('config field "confidence" must be "high", "medium" or "low"');
60
+ }
61
+ config.confidence = input.confidence;
62
+ }
63
+ if (input.failOn !== undefined) {
64
+ if (typeof input.failOn !== 'string' || !FAIL_ON.includes(input.failOn)) {
65
+ throw new Error('config field "failOn" must be one of high|medium|low|none');
66
+ }
67
+ config.failOn = input.failOn;
68
+ }
69
+ return config;
70
+ }
71
+ export async function loadConfig(root) {
72
+ for (const name of CONFIG_FILENAMES) {
73
+ const file = path.join(root, name);
74
+ try {
75
+ const raw = await readFile(file, 'utf8');
76
+ // Editors on Windows like to write a UTF-8 BOM; JSON.parse rejects it.
77
+ const text = raw.replace(/^\uFEFF/, '');
78
+ const parsed = JSON.parse(text);
79
+ return { config: normalizeConfig(parsed), file: name };
80
+ }
81
+ catch (error) {
82
+ if (error.code === 'ENOENT')
83
+ continue;
84
+ if (error instanceof SyntaxError) {
85
+ throw new Error(`${name} is not valid JSON (${error.message})`);
86
+ }
87
+ throw error;
88
+ }
89
+ }
90
+ return { config: { ...DEFAULT_CONFIG, rules: {} }, file: undefined };
91
+ }
@@ -0,0 +1,21 @@
1
+ /**
2
+ * Top-level modules of the Python standard library (3.9 - 3.14).
3
+ *
4
+ * Kept as a static list on purpose: we never execute the target project's
5
+ * Python interpreter, and the list is stable enough to pin. Anything missing
6
+ * can be added to `ignoreModules` in `.slopgate.json`.
7
+ */
8
+ export declare const PYTHON_STDLIB: ReadonlySet<string>;
9
+ /**
10
+ * Import path -> distribution name, for packages whose import name differs
11
+ * from the name you put in a manifest. Keys are case-sensitive and may be
12
+ * dotted; the longest matching prefix wins (`google.protobuf` before `google`).
13
+ * Without this map the dependency check would produce false positives on very
14
+ * common packages.
15
+ */
16
+ export declare const IMPORT_TO_DISTRIBUTION: Readonly<Record<string, string>>;
17
+ /**
18
+ * Modules that are importable without being declared because the toolchain
19
+ * provides them. `setuptools` ships `pkg_resources` and `_distutils_hack`.
20
+ */
21
+ export declare const IMPLICIT_MODULES: ReadonlySet<string>;