@blundergoat/gruff-ts 0.1.1 → 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.
Files changed (52) hide show
  1. package/CHANGELOG.md +55 -19
  2. package/README.md +103 -35
  3. package/docs/README.md +2 -0
  4. package/docs/agent-hook.md +80 -0
  5. package/docs/ci-integration.md +16 -0
  6. package/docs/configuration.md +60 -3
  7. package/docs/dashboard.md +7 -0
  8. package/docs/output-formats.md +11 -1
  9. package/docs/philosophy.md +21 -0
  10. package/docs/releasing.md +12 -11
  11. package/docs/reports-and-ci.md +5 -2
  12. package/docs/rules.md +24 -15
  13. package/package.json +5 -5
  14. package/scripts/bump-version.sh +20 -4
  15. package/scripts/preflight-checks.sh +4 -41
  16. package/src/analyser.ts +47 -34
  17. package/src/blocks.ts +82 -75
  18. package/src/changed-regions.ts +390 -0
  19. package/src/check-ignore.ts +49 -0
  20. package/src/class-rules.ts +80 -33
  21. package/src/cli-program.ts +209 -51
  22. package/src/comment-rules.ts +4 -0
  23. package/src/config-load-error.ts +18 -0
  24. package/src/config-parse.ts +458 -0
  25. package/src/config-preservation.ts +64 -0
  26. package/src/config.ts +311 -428
  27. package/src/constants.ts +10 -2
  28. package/src/context-doc-rules.ts +2 -4
  29. package/src/dashboard.ts +8 -5
  30. package/src/dead-code-rules.ts +60 -14
  31. package/src/discovery.ts +88 -32
  32. package/src/doc-rules.ts +3 -3
  33. package/src/findings-helpers.ts +58 -5
  34. package/src/fixtures/rule-catalogue-security-doctrine.ts +28 -0
  35. package/src/init-config.ts +94 -31
  36. package/src/line-rules.ts +58 -4
  37. package/src/naming-pushers.ts +42 -7
  38. package/src/pillar-summary.ts +129 -0
  39. package/src/profiles.ts +232 -0
  40. package/src/project-config-rules.ts +5 -5
  41. package/src/project-rules.ts +2 -1
  42. package/src/report-html.ts +404 -0
  43. package/src/report-renderers.ts +210 -397
  44. package/src/rule-list.ts +85 -1
  45. package/src/rules.ts +28 -27
  46. package/src/safety-rules.ts +22 -7
  47. package/src/scoring.ts +78 -8
  48. package/src/security-flow-rules.ts +533 -0
  49. package/src/sensitive-data-rules.ts +138 -2
  50. package/src/test-block-rules.ts +140 -7
  51. package/src/test-fixtures.ts +59 -13
  52. package/src/types.ts +108 -5
@@ -293,6 +293,8 @@ function knownCliFlags(): Set<string> {
293
293
  "--baseline",
294
294
  "--config",
295
295
  "--diff",
296
+ "--changed-ranges",
297
+ "--changed-scope",
296
298
  "--fail-on",
297
299
  "--force",
298
300
  "--format",
@@ -307,9 +309,11 @@ function knownCliFlags(): Set<string> {
307
309
  "--no-interaction",
308
310
  "--output",
309
311
  "--port",
312
+ "--profile",
310
313
  "--project-root",
311
314
  "--quiet",
312
315
  "--silent",
316
+ "--since",
313
317
  "--top",
314
318
  "--verbose",
315
319
  "--version",
@@ -0,0 +1,18 @@
1
+ /*
2
+ * Error class for user-facing config-load failures. CLI action handlers catch this specifically so
3
+ * a malformed `.gruff-ts.yaml` produces a clean stderr message and exit code 2, instead of a raw
4
+ * Node stack trace. The `suggestion` field carries the user-actionable next step (run init --force,
5
+ * edit a specific value, etc.) so the CLI layer can format it consistently across all throw sites.
6
+ * Reports a tagged error that the CLI layer recognises via `instanceof`.
7
+ */
8
+ export class ConfigLoadError extends Error {
9
+ readonly suggestion: string;
10
+
11
+ // Stores the suggested fix alongside the message so the CLI formatter can render both without
12
+ // re-deriving the suggestion from the error text. Throws nothing; this is a plain data wrapper.
13
+ constructor(message: string, suggestion: string) {
14
+ super(message);
15
+ this.name = "ConfigLoadError";
16
+ this.suggestion = suggestion;
17
+ }
18
+ }
@@ -0,0 +1,458 @@
1
+ // Config parsing layer: the zero-dependency YAML-subset parser, the file reader, the shared
2
+ // user-facing suggestion strings, and the value-narrowing helpers. Split out of `config.ts` so the
3
+ // config semantics module (defaults, validation, profile resolution) stays under the size budget and
4
+ // so both `config.ts` and the profile resolver can read files without a circular import. This module
5
+ // depends only on Node IO and `ConfigLoadError`; it never imports `config.ts` or `profiles.ts`.
6
+ import { readFileSync } from "node:fs";
7
+ import { extname } from "node:path";
8
+ import { ConfigLoadError } from "./config-load-error.ts";
9
+
10
+ // Two common suggestion strings reused across the validators. Hoisted out so a future doc-link
11
+ // or wording tweak lands in one place instead of N throw sites.
12
+ const SUGGEST_INIT_FORCE = "Run `gruff-ts init --force` to regenerate the config from current defaults (preserves your `paths.ignore` and `minimumSeverity:` entries).";
13
+ const SUGGEST_EDIT_CONFIG = "Edit `.gruff-ts.yaml` to use a valid value, or run `gruff-ts init --force` to regenerate from defaults.";
14
+
15
+ const YAML_KEYWORD_SCALARS = new Map<string, boolean | null>([
16
+ ["true", true],
17
+ ["false", false],
18
+ ["null", null],
19
+ ["~", null],
20
+ ]);
21
+ const YAML_NUMBER_SCALAR = /^-?(?:0|[1-9]\d*)(?:\.\d+)?$/;
22
+
23
+ // Result of one scalar parser attempt. `isMatched: false` lets the dispatcher fall through to the
24
+ // next parser instead of mistaking `undefined` for a successfully parsed null value.
25
+ interface ParsedYamlScalar {
26
+ isMatched: boolean;
27
+ value: unknown;
28
+ }
29
+
30
+ const UNMATCHED_YAML_SCALAR: ParsedYamlScalar = { isMatched: false, value: undefined };
31
+
32
+ /*
33
+ * Reads YAML or JSON config and rejects unknown extensions. Raw IO failures (e.g. `--config <path>`
34
+ * pointing at a missing file) and JSON parse failures are rewrapped as ConfigLoadError so the CLI
35
+ * surface stays uniform - a bare ENOENT or SyntaxError would otherwise bypass the formatted
36
+ * "gruff-ts: config error" stderr path in `runWithConfigErrorHandling`.
37
+ *
38
+ * Throws ConfigLoadError when: the file is missing (ENOENT), the contents are not valid JSON, the
39
+ * YAML subset rejects the file (see parseYamlConfig), or the top-level value is not a mapping.
40
+ */
41
+ function parseConfigFile(path: string): Record<string, unknown> {
42
+ const source = readConfigSource(path);
43
+ const extension = extname(path).toLowerCase();
44
+ const parsed = parseConfigSource(source, extension, path);
45
+ const config = objectValue(parsed);
46
+ if (!config) {
47
+ throw new ConfigLoadError(`Config file must contain an object with .yaml, .yml, or .json extension: ${path}`, SUGGEST_INIT_FORCE);
48
+ }
49
+ return config;
50
+ }
51
+
52
+ /*
53
+ * Reads the raw config bytes. Explicit `--config <path>` skips the `defaultConfigPath` existence
54
+ * check, so a typo here would otherwise dump a raw Node stack. Throws ConfigLoadError on ENOENT
55
+ * with a user-actionable suggestion; rethrows every other filesystem error unchanged so an
56
+ * unexpected IO failure still surfaces its native stack for debugging.
57
+ */
58
+ function readConfigSource(path: string): string {
59
+ try {
60
+ return readFileSync(path, "utf8").replace(/^\uFEFF/, "");
61
+ } catch (error) {
62
+ if ((error as NodeJS.ErrnoException | null)?.code === "ENOENT") {
63
+ throw new ConfigLoadError(`Config file not found: ${path}.`, "Pass --config with an existing path, or omit the flag to use the default lookup.");
64
+ }
65
+ throw error;
66
+ }
67
+ }
68
+
69
+ // Routes to the YAML subset parser or the native JSON parser. Wraps `JSON.parse`'s SyntaxError so
70
+ // a malformed `.gruff.json` surfaces through the same ConfigLoadError channel as YAML failures
71
+ // (parseYamlConfig already throws ConfigLoadError on its own malformed inputs).
72
+ function parseConfigSource(source: string, extension: string, path: string): unknown {
73
+ if (extension === ".yaml" || extension === ".yml") {
74
+ return parseYamlConfig(source);
75
+ }
76
+ if (extension !== ".json") {
77
+ return undefined;
78
+ }
79
+ try {
80
+ return JSON.parse(source) as unknown;
81
+ } catch (error) {
82
+ if (error instanceof SyntaxError) {
83
+ throw new ConfigLoadError(`Config file is not valid JSON: ${error.message} (${path}).`, SUGGEST_EDIT_CONFIG);
84
+ }
85
+ throw error;
86
+ }
87
+ }
88
+
89
+ // One non-blank, comment-stripped YAML line. `indent` is the column count (spaces only - tabs are
90
+ // rejected upstream) and is the sole signal used to nest blocks. `content` is whitespace-trimmed.
91
+ interface YamlLine {
92
+ indent: number;
93
+ content: string;
94
+ }
95
+
96
+ // Mutable cursor through `lines`. Stored on the heap so recursive `parseYamlBlock` calls share
97
+ // position state instead of threading an index argument.
98
+ interface YamlParser {
99
+ lines: YamlLine[];
100
+ index: number;
101
+ }
102
+
103
+ /*
104
+ * Custom YAML parser that intentionally supports only a documented subset (mappings, arrays,
105
+ * scalars, inline `[]`/`{}`) - keeps gruff free of a yaml dependency. Throws on malformed input
106
+ * because silently misparsing config would produce wrong findings and a stable but broken baseline.
107
+ */
108
+ function parseYamlConfig(source: string): Record<string, unknown> {
109
+ const parser = { lines: yamlLines(source), index: 0 };
110
+ const parsedDocument = parser.lines.length === 0 ? {} : parseYamlBlock(parser, parser.lines[0]?.indent ?? 0);
111
+ const config = objectValue(parsedDocument);
112
+ if (!config) {
113
+ throw new ConfigLoadError("Config YAML must contain a mapping object.", SUGGEST_INIT_FORCE);
114
+ }
115
+ return config;
116
+ }
117
+
118
+ // Dispatch entry for a block. Empty (no lines at this indent) returns `{}`; sequence lines lead
119
+ // into the array parser; everything else is an object/mapping.
120
+ function parseYamlBlock(parser: YamlParser, indent: number): unknown {
121
+ const line = parser.lines[parser.index];
122
+ if (!line || line.indent < indent) {
123
+ return {};
124
+ }
125
+ return isYamlArrayLine(line) ? parseYamlArray(parser, line.indent) : parseYamlObject(parser, line.indent);
126
+ }
127
+
128
+ // Walks mapping entries at one indent level, stopping when the next line dedents or switches to
129
+ // sequence form. Throws on unexpected indent so a missed key isn't silently swallowed.
130
+ function parseYamlObject(parser: YamlParser, indent: number): Record<string, unknown> {
131
+ const result: Record<string, unknown> = {};
132
+ while (parser.index < parser.lines.length) {
133
+ const line = parser.lines[parser.index];
134
+ if (!line || line.indent < indent || isYamlArrayLine(line)) {
135
+ break;
136
+ }
137
+ assertYamlIndent(line, indent);
138
+ addYamlObjectEntry(parser, indent, line, result);
139
+ }
140
+ return result;
141
+ }
142
+
143
+ // Inline scalar after the colon → leaf value; bare key → recurse into nested block. Keys are
144
+ // unquoted so `"foo"` and `foo` produce the same result key.
145
+ function addYamlObjectEntry(parser: YamlParser, indent: number, line: YamlLine, result: Record<string, unknown>): void {
146
+ const [rawKey, rawValue] = yamlKeyValuePair(line.content);
147
+ const scalarText = rawValue.trim();
148
+ parser.index += 1;
149
+ result[unquoteYaml(rawKey.trim())] = scalarText.length > 0 ? parseYamlScalar(scalarText) : parseNestedYamlValue(parser, indent, {});
150
+ }
151
+
152
+ // Block-style YAML sequence. Inline `[...]` arrays are handled by `parseYamlCollectionScalar`;
153
+ // this walks the `- item` lines and recurses into nested values for empty `-` openers.
154
+ function parseYamlArray(parser: YamlParser, indent: number): unknown[] {
155
+ const result: unknown[] = [];
156
+ while (parser.index < parser.lines.length) {
157
+ const line = parser.lines[parser.index];
158
+ if (!line || line.indent < indent || !isYamlArrayLine(line)) {
159
+ break;
160
+ }
161
+ assertYamlIndent(line, indent);
162
+ result.push(parseYamlArrayItem(parser, indent, line));
163
+ }
164
+ return result;
165
+ }
166
+
167
+ // Three branches: bare `-` (recurse for nested), `- key: value` (mapping item), `- scalar`.
168
+ // Bare-dash items return null when the nested block is empty so the array entry isn't elided.
169
+ function parseYamlArrayItem(parser: YamlParser, indent: number, line: YamlLine): unknown {
170
+ const itemText = line.content === "-" ? "" : line.content.slice(2).trim();
171
+ parser.index += 1;
172
+ if (itemText.length === 0) {
173
+ return parseNestedYamlValue(parser, indent, null);
174
+ }
175
+
176
+ const pair = splitYamlKeyValue(itemText);
177
+ return pair ? parseYamlArrayMappingItem(parser, indent, pair) : parseYamlScalar(itemText);
178
+ }
179
+
180
+ // `- key: value` form: the first key is on the dash line, subsequent keys live as a nested object.
181
+ // Mirrors the inline-vs-nested split of `addYamlObjectEntry`.
182
+ function parseYamlArrayMappingItem(parser: YamlParser, indent: number, pair: [string, string]): Record<string, unknown> {
183
+ const [rawKey, rawValue] = pair;
184
+ const scalarText = rawValue.trim();
185
+ return {
186
+ [unquoteYaml(rawKey.trim())]: scalarText.length > 0 ? parseYamlScalar(scalarText) : parseNestedYamlValue(parser, indent, {}),
187
+ };
188
+ }
189
+
190
+ // Returns the nested block if the next line indents further, otherwise the caller's `fallback`.
191
+ // `fallback` is `{}` for mappings (empty value → empty object) and `null` for sequences.
192
+ function parseNestedYamlValue(parser: YamlParser, indent: number, fallback: unknown): unknown {
193
+ const nestedIndent = parser.lines[parser.index]?.indent;
194
+ return nestedIndent !== undefined && nestedIndent > indent ? parseYamlBlock(parser, nestedIndent) : fallback;
195
+ }
196
+
197
+ /*
198
+ * Throws when a mapping line has no `:` separator - the parser cannot recover, and a silent skip
199
+ * would hide a real config typo from the user.
200
+ */
201
+ function yamlKeyValuePair(content: string): [string, string] {
202
+ const pair = splitYamlKeyValue(content);
203
+ if (!pair) {
204
+ throw new ConfigLoadError(`Invalid YAML mapping line: "${content}".`, SUGGEST_INIT_FORCE);
205
+ }
206
+ return pair;
207
+ }
208
+
209
+ // `- ` or bare `-` only - two-dash openers and ambiguous variants are not sequence entries.
210
+ function isYamlArrayLine(line: YamlLine): boolean {
211
+ return line.content.startsWith("- ") || line.content === "-";
212
+ }
213
+
214
+ /*
215
+ * Throws when a line is indented more than expected at this scope. Without this guard, a stray
216
+ * indent would silently produce a sub-mapping and the user's config would mean something different.
217
+ */
218
+ function assertYamlIndent(line: YamlLine, indent: number): void {
219
+ if (line.indent > indent) {
220
+ throw new ConfigLoadError(`Invalid YAML indentation near "${line.content}".`, SUGGEST_INIT_FORCE);
221
+ }
222
+ }
223
+
224
+ /*
225
+ * Pre-pass that drops blank/comment lines and rejects tab-indented input. Tabs are forbidden
226
+ * because mixing them with spaces is the canonical YAML footgun, so the parser throws rather than
227
+ * guess at the user's intent.
228
+ */
229
+ function yamlLines(source: string): YamlLine[] {
230
+ const lines: YamlLine[] = [];
231
+ for (const rawLine of source.replace(/\r\n/g, "\n").split("\n")) {
232
+ const withoutComment = stripYamlComment(rawLine).trimEnd();
233
+ if (withoutComment.trim().length === 0) {
234
+ continue;
235
+ }
236
+ const indentText = withoutComment.match(/^\s*/)?.[0] ?? "";
237
+ if (indentText.includes("\t")) {
238
+ throw new ConfigLoadError("Tabs are not supported in gruff YAML config indentation.", SUGGEST_INIT_FORCE);
239
+ }
240
+ lines.push({ indent: indentText.length, content: withoutComment.trimStart() });
241
+ }
242
+ return lines;
243
+ }
244
+
245
+ // Drops `# comment` text but only when the `#` is not inside quotes - `foo: "a # b"` keeps the
246
+ // comment-like substring as part of the string value, matching YAML semantics.
247
+ function stripYamlComment(line: string): string {
248
+ const commentIndex = firstUnquotedIndex(line, (character, index) => character === "#" && (index === 0 || /\s/.test(line[index - 1] ?? "")));
249
+ return commentIndex === undefined ? line : line.slice(0, commentIndex);
250
+ }
251
+
252
+ // Finds the first `:<space>` outside quotes. Required because a quoted value can legitimately
253
+ // contain `:` (`url: "https://..."`) and the parser must not split at the first occurrence.
254
+ function splitYamlKeyValue(mappingText: string): [string, string] | undefined {
255
+ const separatorIndex = firstUnquotedIndex(mappingText, (character, index) => {
256
+ const next = mappingText[index + 1];
257
+ return character === ":" && (!next || /\s/.test(next));
258
+ });
259
+ return separatorIndex === undefined ? undefined : [mappingText.slice(0, separatorIndex), mappingText.slice(separatorIndex + 1)];
260
+ }
261
+
262
+ // Tries each scalar parser in order; the first to claim a match wins. Bare strings are the
263
+ // fallback so callers never end up with `undefined` for a non-empty scalar.
264
+ function parseYamlScalar(scalarText: string): unknown {
265
+ const trimmed = scalarText.trim();
266
+ for (const parser of [parseYamlCollectionScalar, parseYamlQuotedScalar, parseYamlKeywordScalar, parseYamlNumberScalar]) {
267
+ const parsedScalar = parser(trimmed);
268
+ if (parsedScalar.isMatched) {
269
+ return parsedScalar.value;
270
+ }
271
+ }
272
+ return trimmed;
273
+ }
274
+
275
+ // Parses YAML collection scalar from source text.
276
+ function parseYamlCollectionScalar(trimmed: string): ParsedYamlScalar {
277
+ if (trimmed === "[]") {
278
+ return matchedYamlScalar([]);
279
+ }
280
+ if (trimmed === "{}") {
281
+ return matchedYamlScalar({});
282
+ }
283
+ if (trimmed.startsWith("[") && trimmed.endsWith("]")) {
284
+ return matchedYamlScalar(parseYamlInlineArray(trimmed));
285
+ }
286
+ return UNMATCHED_YAML_SCALAR;
287
+ }
288
+
289
+ // `"..."` or `'...'` wrapped. Calls `unquoteYaml` so the resulting value matches what a real YAML
290
+ // engine would produce; matched-state flag separates "empty quoted string" from "not a quoted scalar".
291
+ function parseYamlQuotedScalar(trimmed: string): ParsedYamlScalar {
292
+ if (isQuotedYaml(trimmed)) {
293
+ return matchedYamlScalar(unquoteYaml(trimmed));
294
+ }
295
+ return UNMATCHED_YAML_SCALAR;
296
+ }
297
+
298
+ // Recognises `true`/`false`/`null`/`~` (case-insensitive). The keyword table is shared so the
299
+ // parser produces consistent JS values (`null` instead of the string "null").
300
+ function parseYamlKeywordScalar(trimmed: string): ParsedYamlScalar {
301
+ const normalized = trimmed.toLowerCase();
302
+ if (YAML_KEYWORD_SCALARS.has(normalized)) {
303
+ return matchedYamlScalar(YAML_KEYWORD_SCALARS.get(normalized) ?? null);
304
+ }
305
+ return UNMATCHED_YAML_SCALAR;
306
+ }
307
+
308
+ // Strict numeric pattern - no octals, no special floats. Numbers that don't fit fall through to
309
+ // bare-string handling, so `0xFF` or `1e10` stay as strings rather than producing surprising values.
310
+ function parseYamlNumberScalar(trimmed: string): ParsedYamlScalar {
311
+ if (YAML_NUMBER_SCALAR.test(trimmed)) {
312
+ return matchedYamlScalar(Number(trimmed));
313
+ }
314
+ return UNMATCHED_YAML_SCALAR;
315
+ }
316
+
317
+ // Returns a "matched" result with the parsed value, distinguishing real matches from the shared
318
+ // `UNMATCHED_YAML_SCALAR` sentinel used by every parser that failed.
319
+ function matchedYamlScalar(scalarValue: unknown): ParsedYamlScalar {
320
+ return { isMatched: true, value: scalarValue };
321
+ }
322
+
323
+ // Inline `[a, b, c]` arrays. Items are split on unquoted commas and each item recurses through
324
+ // `parseYamlScalar` so nested types resolve correctly.
325
+ function parseYamlInlineArray(arrayText: string): unknown[] {
326
+ const inner = arrayText.slice(1, -1).trim();
327
+ if (inner.length === 0) {
328
+ return [];
329
+ }
330
+ return splitYamlInlineItems(inner).map((item) => parseYamlScalar(item));
331
+ }
332
+
333
+ // Quote-aware split on commas. Treating a quoted comma as a separator would corrupt entries like
334
+ // `["a, b", "c"]` - same reason `splitYamlKeyValue` is also quote-aware.
335
+ function splitYamlInlineItems(itemsText: string): string[] {
336
+ const items: string[] = [];
337
+ let start = 0;
338
+ for (const index of unquotedIndexes(itemsText, ",")) {
339
+ items.push(itemsText.slice(start, index).trim());
340
+ start = index + 1;
341
+ }
342
+ items.push(itemsText.slice(start).trim());
343
+ return items;
344
+ }
345
+
346
+ // Lexer state for the YAML quote walkers. `isEscaped` only matters inside `"..."` quotes because
347
+ // single-quoted YAML strings use `''` doubling rather than backslash escapes.
348
+ interface QuoteScanState {
349
+ quote: string | undefined;
350
+ isEscaped: boolean;
351
+ }
352
+
353
+ // Walks `value` calling `predicate` only at quote-free positions. Used by both the comment
354
+ // stripper and the colon splitter to keep quoted text inert.
355
+ function firstUnquotedIndex(sourceText: string, predicate: (character: string, index: number) => boolean): number | undefined {
356
+ for (const index of unquotedIndexes(sourceText)) {
357
+ const character = sourceText[index] ?? "";
358
+ if (predicate(character, index)) {
359
+ return index;
360
+ }
361
+ }
362
+ return undefined;
363
+ }
364
+
365
+ // All quote-free positions in `value`, optionally filtered by a specific character. The two-mode
366
+ // shape lets the same lexer feed both `firstUnquotedIndex` and the inline-array splitter.
367
+ function unquotedIndexes(sourceText: string, expectedCharacter?: string): number[] {
368
+ const indexes: number[] = [];
369
+ const state: QuoteScanState = { quote: undefined, isEscaped: false };
370
+ for (let index = 0; index < sourceText.length; index += 1) {
371
+ const character = sourceText[index] ?? "";
372
+ if (consumeQuotedCharacter(character, state)) {
373
+ continue;
374
+ }
375
+ if (isYamlQuote(character)) {
376
+ state.quote = character;
377
+ continue;
378
+ }
379
+ if (!expectedCharacter || character === expectedCharacter) {
380
+ indexes.push(index);
381
+ }
382
+ }
383
+ return indexes;
384
+ }
385
+
386
+ // Returns true and mutates `state` when the character was inside a quoted region. The escape
387
+ // handling is double-quote-only because YAML single-quote strings have no `\` escapes.
388
+ function consumeQuotedCharacter(character: string, state: QuoteScanState): boolean {
389
+ if (!state.quote) {
390
+ return false;
391
+ }
392
+ if (state.quote === "\"" && character === "\\" && !state.isEscaped) {
393
+ state.isEscaped = true;
394
+ return true;
395
+ }
396
+ if (character === state.quote && !state.isEscaped) {
397
+ state.quote = undefined;
398
+ }
399
+ state.isEscaped = false;
400
+ return true;
401
+ }
402
+
403
+ // Single and double quotes only - YAML allows backticks elsewhere but they're not part of the
404
+ // supported subset here, and the parser would have to reject them anyway.
405
+ function isYamlQuote(character: string): boolean {
406
+ return character === "\"" || character === "'";
407
+ }
408
+
409
+ // Both endpoints must use the same quote character; mismatched openers/closers are treated as
410
+ // plain text rather than a parse error so a single stray quote in user prose doesn't fail the config.
411
+ function isQuotedYaml(scalarText: string): boolean {
412
+ return scalarText.length >= 2 && ((scalarText.startsWith("\"") && scalarText.endsWith("\"")) || (scalarText.startsWith("'") && scalarText.endsWith("'")));
413
+ }
414
+
415
+ // Removes quotes and decodes the supported escapes: `''` doubling for single quotes, and `\n`,
416
+ // `\r`, `\t`, `\"`, `\\` for double quotes. Anything else passes through unchanged so the parser
417
+ // reports the user's exact intent rather than mangling unknown escape sequences.
418
+ function unquoteYaml(scalarText: string): string {
419
+ if (!isQuotedYaml(scalarText)) {
420
+ return scalarText;
421
+ }
422
+ const quote = scalarText[0];
423
+ const body = scalarText.slice(1, -1);
424
+ if (quote === "'") {
425
+ return body.replace(/''/g, "'");
426
+ }
427
+ return body.replace(/\\(["\\nrt])/g, (_match, escaped: string) => {
428
+ if (escaped === "n") {
429
+ return "\n";
430
+ }
431
+ if (escaped === "r") {
432
+ return "\r";
433
+ }
434
+ if (escaped === "t") {
435
+ return "\t";
436
+ }
437
+ return escaped;
438
+ });
439
+ }
440
+
441
+ // Type narrowing for `Record<string, unknown>`. Returns undefined (not null) for non-objects so
442
+ // the caller can use the standard optional-chaining pattern through the rest of the config layer.
443
+ function objectValue(configValue: unknown): Record<string, unknown> | undefined {
444
+ return typeof configValue === "object" && configValue !== null && !Array.isArray(configValue) ? (configValue as Record<string, unknown>) : undefined;
445
+ }
446
+
447
+ // Returns the array or an empty array - never undefined - so callers can iterate without a guard.
448
+ function arrayValue(configValue: unknown): unknown[] {
449
+ return Array.isArray(configValue) ? configValue : [];
450
+ }
451
+
452
+ // String type narrowing. Exported so other modules can share a single string-test that matches
453
+ // the config-side semantics (rejects non-string truthy values like numbers).
454
+ function isString(configValue: unknown): configValue is string {
455
+ return typeof configValue === "string";
456
+ }
457
+
458
+ export { arrayValue, isString, objectValue, parseConfigFile, SUGGEST_EDIT_CONFIG, SUGGEST_INIT_FORCE };
@@ -0,0 +1,64 @@
1
+ // Best-effort field extraction for `gruff-ts init --force`. The strict loader in `config.ts`
2
+ // throws on schemaVersion mismatch (deliberate: pre-1.0 break, no migration shim), but the init
3
+ // migration path needs to lift `paths.ignore` and `minimumSeverity` off whatever the user has on
4
+ // disk so regeneration does not silently clobber curated entries. This module exists because the
5
+ // strict validator is the wrong tool for that handoff - the next analyser load will run it.
6
+ import { objectValue, parseConfigFile } from "./config-parse.ts";
7
+ import type { FailThreshold, MinimumSeverityCommand } from "./types.ts";
8
+
9
+ // Carry-over bundle returned to `gruff-ts init --force`. Both fields are best-effort: empty
10
+ // values mean nothing was preserved, not that the existing config was empty.
11
+ interface PreservedConfigFields {
12
+ ignoredPaths: string[];
13
+ minimumSeverity: Map<MinimumSeverityCommand, FailThreshold>;
14
+ }
15
+
16
+ /*
17
+ * Reads the existing config and returns its `paths.ignore` and `minimumSeverity` blocks. Pre-0.2.0
18
+ * configs without `schemaVersion` succeed here (the strict gate is skipped) so the user's entries
19
+ * survive `init --force`. Individual malformed entries inside the preserved blocks are dropped
20
+ * rather than thrown - the strict validator runs at the next analyser load and surfaces errors
21
+ * in the right place. Throws `ConfigLoadError` only on IO/parse failure of the file itself; the
22
+ * caller handles that fallback to "preserve nothing" instead of blocking regeneration.
23
+ */
24
+ export function extractPreservedConfigFields(configPath: string): PreservedConfigFields {
25
+ const raw = parseConfigFile(configPath);
26
+ return {
27
+ ignoredPaths: extractIgnoredPaths(raw),
28
+ minimumSeverity: extractMinimumSeverity(raw),
29
+ };
30
+ }
31
+
32
+ // `paths.ignore` is a free-form list of glob strings. Non-string entries are dropped silently -
33
+ // the strict path enforces the same shape at the next analyser load.
34
+ function extractIgnoredPaths(raw: Record<string, unknown>): string[] {
35
+ const ignore = objectValue(raw.paths)?.ignore;
36
+ return Array.isArray(ignore) ? ignore.filter((entry): entry is string => typeof entry === "string") : [];
37
+ }
38
+
39
+ // Permissive minimumSeverity reader: each entry is filtered through the same vocabulary the strict
40
+ // validator checks (commands × thresholds). Anything off-vocabulary is dropped. The reason we
41
+ // don't throw here is so a typo in one entry does not nuke preservation of the other entries.
42
+ function extractMinimumSeverity(raw: Record<string, unknown>): Map<MinimumSeverityCommand, FailThreshold> {
43
+ const result = new Map<MinimumSeverityCommand, FailThreshold>();
44
+ const block = objectValue(raw.minimumSeverity);
45
+ if (!block) {
46
+ return result;
47
+ }
48
+ for (const [commandName, value] of Object.entries(block)) {
49
+ addPreservedSeverityEntry(result, commandName, value);
50
+ }
51
+ return result;
52
+ }
53
+
54
+ // Per-entry filter: extracted so the outer loop stays linear and the NPath budget for the file
55
+ // extractor stays small. Both gates must pass before the entry lands in the preserved map.
56
+ function addPreservedSeverityEntry(result: Map<MinimumSeverityCommand, FailThreshold>, commandName: string, rawThreshold: unknown): void {
57
+ if (commandName !== "analyse" && commandName !== "summary" && commandName !== "report") {
58
+ return;
59
+ }
60
+ if (rawThreshold !== "none" && rawThreshold !== "advisory" && rawThreshold !== "warning" && rawThreshold !== "error") {
61
+ return;
62
+ }
63
+ result.set(commandName, rawThreshold);
64
+ }