@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.
- package/CHANGELOG.md +55 -19
- package/README.md +103 -35
- package/docs/README.md +2 -0
- package/docs/agent-hook.md +80 -0
- package/docs/ci-integration.md +16 -0
- package/docs/configuration.md +60 -3
- package/docs/dashboard.md +7 -0
- package/docs/output-formats.md +11 -1
- package/docs/philosophy.md +21 -0
- package/docs/releasing.md +12 -11
- package/docs/reports-and-ci.md +5 -2
- package/docs/rules.md +24 -15
- package/package.json +5 -5
- package/scripts/bump-version.sh +20 -4
- package/scripts/preflight-checks.sh +4 -41
- package/src/analyser.ts +47 -34
- package/src/blocks.ts +82 -75
- package/src/changed-regions.ts +390 -0
- package/src/check-ignore.ts +49 -0
- package/src/class-rules.ts +80 -33
- package/src/cli-program.ts +209 -51
- package/src/comment-rules.ts +4 -0
- package/src/config-load-error.ts +18 -0
- package/src/config-parse.ts +458 -0
- package/src/config-preservation.ts +64 -0
- package/src/config.ts +311 -428
- package/src/constants.ts +10 -2
- package/src/context-doc-rules.ts +2 -4
- package/src/dashboard.ts +8 -5
- package/src/dead-code-rules.ts +60 -14
- package/src/discovery.ts +88 -32
- package/src/doc-rules.ts +3 -3
- package/src/findings-helpers.ts +58 -5
- package/src/fixtures/rule-catalogue-security-doctrine.ts +28 -0
- package/src/init-config.ts +94 -31
- package/src/line-rules.ts +58 -4
- package/src/naming-pushers.ts +42 -7
- package/src/pillar-summary.ts +129 -0
- package/src/profiles.ts +232 -0
- package/src/project-config-rules.ts +5 -5
- package/src/project-rules.ts +2 -1
- package/src/report-html.ts +404 -0
- package/src/report-renderers.ts +210 -397
- package/src/rule-list.ts +85 -1
- package/src/rules.ts +28 -27
- package/src/safety-rules.ts +22 -7
- package/src/scoring.ts +78 -8
- package/src/security-flow-rules.ts +533 -0
- package/src/sensitive-data-rules.ts +138 -2
- package/src/test-block-rules.ts +140 -7
- package/src/test-fixtures.ts +59 -13
- package/src/types.ts +108 -5
package/src/config.ts
CHANGED
|
@@ -1,42 +1,34 @@
|
|
|
1
|
-
// Config loading
|
|
2
|
-
|
|
3
|
-
import {
|
|
4
|
-
import
|
|
1
|
+
// Config loading, defaults, validation, merging, and profile resolution. The zero-dependency
|
|
2
|
+
// YAML-subset parser, the file reader, and the value-narrowing helpers live in `config-parse.ts`.
|
|
3
|
+
import { existsSync } from "node:fs";
|
|
4
|
+
import { dirname, isAbsolute, join } from "node:path";
|
|
5
|
+
import { arrayValue, isString, objectValue, parseConfigFile, SUGGEST_EDIT_CONFIG, SUGGEST_INIT_FORCE } from "./config-parse.ts";
|
|
6
|
+
import { ConfigLoadError } from "./config-load-error.ts";
|
|
7
|
+
import { BUILT_IN_PROFILES, builtInProfileNames, DEFAULT_PROFILE_NAME, isKnownRuleId } from "./profiles.ts";
|
|
8
|
+
import type { AnalysisOptions, Config, FailThreshold, InlineProfileSpec, MinimumSeverityCommand, ProfileDefinition, ProfileRuleSetting, ProfileSpec, Severity } from "./types.ts";
|
|
5
9
|
|
|
6
10
|
type RuleOverride = Config["rules"] extends Map<string, infer RuleOverrideValue> ? RuleOverrideValue : never;
|
|
7
11
|
|
|
8
12
|
const DEFAULT_CONFIG_FILES = [".gruff-ts.yaml", ".gruff.json", ".gruff.yaml", ".gruff.yml"] as const;
|
|
9
|
-
const YAML_KEYWORD_SCALARS = new Map<string, boolean | null>([
|
|
10
|
-
["true", true],
|
|
11
|
-
["false", false],
|
|
12
|
-
["null", null],
|
|
13
|
-
["~", null],
|
|
14
|
-
]);
|
|
15
|
-
const YAML_NUMBER_SCALAR = /^-?(?:0|[1-9]\d*)(?:\.\d+)?$/;
|
|
16
|
-
|
|
17
|
-
// Result of one scalar parser attempt. `isMatched: false` lets the dispatcher fall through to the
|
|
18
|
-
// next parser instead of mistaking `undefined` for a successfully parsed null value.
|
|
19
|
-
interface ParsedYamlScalar {
|
|
20
|
-
isMatched: boolean;
|
|
21
|
-
value: unknown;
|
|
22
|
-
}
|
|
23
|
-
|
|
24
|
-
const UNMATCHED_YAML_SCALAR: ParsedYamlScalar = { isMatched: false, value: undefined };
|
|
25
13
|
|
|
26
14
|
// Built-in defaults applied before any user config overlays. The string lists here (accepted
|
|
27
15
|
// abbreviations, banned generic names, boolean prefixes, …) are the stable rule contract - they
|
|
28
16
|
// shape what every gruff scan emits by default and changing them shifts the public rule surface.
|
|
17
|
+
// schemaVersion is fixed at `gruff-ts.config.v0.1` as the schema invariant for this release.
|
|
29
18
|
function defaultConfig(): Config {
|
|
30
19
|
return {
|
|
20
|
+
schemaVersion: "gruff-ts.config.v0.1",
|
|
31
21
|
ignoredPaths: [],
|
|
32
|
-
acceptedAbbreviations: new Set(["
|
|
22
|
+
acceptedAbbreviations: new Set(["age", "app", "cb", "db", "fn", "fs", "id", "io", "key", "log", "max", "min", "now", "raw", "rx", "tx", "ui", "url"]),
|
|
33
23
|
secretPreviews: new Set(),
|
|
34
24
|
bannedGenericNames: new Set(["process", "handle", "doit", "run", "execute", "manage"]),
|
|
35
|
-
|
|
25
|
+
acceptedBooleanNames: new Set(["all", "apply", "check", "dev", "enabled", "force", "fresh", "harness", "json", "ok", "verbose", "yes"]),
|
|
26
|
+
booleanPrefixes: new Set(["is", "has", "can", "should", "does", "did", "was", "will", "may", "in", "scan", "supports", "requires", "allow", "check", "enable", "exclude", "include", "omit", "skip", "with", "without"]),
|
|
36
27
|
hungarianPrefixes: new Set(["str", "obj", "arr", "bool", "int", "num"]),
|
|
37
28
|
placeholderNames: new Set(["foo", "bar", "baz", "tmp", "temp", "thing", "stuff", "data", "value", "item"]),
|
|
38
29
|
negativeBooleanAllowed: new Set(["nostore", "nofollow", "noreferrer", "noscript", "noindex"]),
|
|
39
30
|
knownAcronyms: new Set(["url", "http", "https", "id", "xml", "json", "html", "css", "api", "sql", "db", "io", "ui", "uuid", "ip", "tcp", "udp", "ast", "cli", "npm"]),
|
|
31
|
+
minimumSeverity: new Map(),
|
|
40
32
|
rules: new Map(),
|
|
41
33
|
};
|
|
42
34
|
}
|
|
@@ -51,16 +43,213 @@ function absolutize(projectRoot: string, path: string): string {
|
|
|
51
43
|
// `.gruff-ts.yaml` work zero-config. Throws on malformed YAML - the caller surfaces it as a fatal CLI error.
|
|
52
44
|
function loadConfig(projectRoot: string, options: AnalysisOptions): Config {
|
|
53
45
|
const config = defaultConfig();
|
|
54
|
-
|
|
55
|
-
|
|
46
|
+
const path = options.shouldSkipConfig ? undefined : selectedConfigPath(projectRoot, options);
|
|
47
|
+
const raw: Record<string, unknown> = path ? parseConfigFile(path) : {};
|
|
48
|
+
if (path) {
|
|
49
|
+
applyConfigValues(config, raw);
|
|
56
50
|
}
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
|
|
51
|
+
applyProfile(config, options, raw, projectRoot);
|
|
52
|
+
return config;
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
/*
|
|
56
|
+
* Applies the profile layer UNDER the top-level config sections. Precedence (highest first): the CLI
|
|
57
|
+
* `--profile` flag, then a config-file `profile:` block, then the profile's own `extends:` chain, then
|
|
58
|
+
* the built-in default `gruff.recommended`. The flattened profile only fills rules the top-level
|
|
59
|
+
* `rules:` block did not already set, so an explicit per-rule override always wins over the profile.
|
|
60
|
+
* When neither the flag nor the config names a profile this is a no-op, because the implicit default
|
|
61
|
+
* `recommended` flattens to an empty delta - the contract that keeps `--profile recommended` and a
|
|
62
|
+
* zero-config scan byte-identical. `--no-config` skips the file but the CLI `--profile` still applies.
|
|
63
|
+
*/
|
|
64
|
+
function applyProfile(config: Config, options: AnalysisOptions, raw: Record<string, unknown>, projectRoot: string): void {
|
|
65
|
+
const rawSpec = options.profile !== undefined ? options.profile : raw.profile;
|
|
66
|
+
if (rawSpec === undefined) {
|
|
67
|
+
return;
|
|
60
68
|
}
|
|
69
|
+
applyProfileUnderlay(config, resolveProfile(parseProfileSpec(rawSpec), projectRoot));
|
|
70
|
+
}
|
|
61
71
|
|
|
62
|
-
|
|
63
|
-
|
|
72
|
+
// Lays a flattened profile under the already-applied top-level config: each rule the top-level
|
|
73
|
+
// `rules:` block did not set takes the profile's value; profile ignored paths union with `paths.ignore`.
|
|
74
|
+
function applyProfileUnderlay(config: Config, definition: ProfileDefinition): void {
|
|
75
|
+
for (const [ruleId, setting] of definition.rules) {
|
|
76
|
+
if (!config.rules.has(ruleId)) {
|
|
77
|
+
config.rules.set(ruleId, profileRuleToConfig(setting));
|
|
78
|
+
}
|
|
79
|
+
}
|
|
80
|
+
if (definition.ignoredPaths.length > 0) {
|
|
81
|
+
config.ignoredPaths = [...new Set([...config.ignoredPaths, ...definition.ignoredPaths])];
|
|
82
|
+
}
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
// Converts a profile rule setting into the loaded-config rule shape. `options` is always a map in the
|
|
86
|
+
// config value, so an absent profile options field becomes an empty map. Conditional spreads keep the
|
|
87
|
+
// absent-vs-undefined distinction required under exactOptionalPropertyTypes.
|
|
88
|
+
function profileRuleToConfig(setting: ProfileRuleSetting): RuleOverride {
|
|
89
|
+
return {
|
|
90
|
+
...(setting.enabled !== undefined ? { enabled: setting.enabled } : {}),
|
|
91
|
+
...(setting.threshold !== undefined ? { threshold: setting.threshold } : {}),
|
|
92
|
+
...(setting.severity !== undefined ? { severity: setting.severity } : {}),
|
|
93
|
+
options: setting.options ?? new Map(),
|
|
94
|
+
};
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
/*
|
|
98
|
+
* Resolves a profile spec into a flattened ProfileDefinition (a delta from the descriptor defaults).
|
|
99
|
+
* Documented precedence the callers depend on, highest first: the CLI `--profile` flag, the config
|
|
100
|
+
* `profile:` block, the `extends:` base chain, and the built-in default `gruff.recommended`. This
|
|
101
|
+
* function owns only the `extends:` flattening; `loadConfig` applies the result under the top-level
|
|
102
|
+
* config sections via `applyProfileUnderlay`.
|
|
103
|
+
*
|
|
104
|
+
* Flattening is child-wins and deterministic: a child profile's per-rule fields override the parent's
|
|
105
|
+
* same-rule fields (last assignment wins for a repeated key), and a child `ignoredPaths` array
|
|
106
|
+
* replaces - does not concatenate - the parent's. `chain` carries the ordered, already-visited file
|
|
107
|
+
* paths so a cycle (A extends B extends A) is rejected with a message naming both in order, instead of
|
|
108
|
+
* recursing until the stack overflows.
|
|
109
|
+
*
|
|
110
|
+
* Throws ConfigLoadError on: a missing `extends:` file, a rule id not in RULE_DESCRIPTORS, or an
|
|
111
|
+
* inheritance cycle. Every failure surfaces at config-load time, never at scan time. File paths only:
|
|
112
|
+
* `extends:` never fetches a remote URL or runs a shell.
|
|
113
|
+
*/
|
|
114
|
+
function resolveProfile(spec: ProfileSpec, projectRoot: string, chain: string[] = []): ProfileDefinition {
|
|
115
|
+
if (typeof spec === "string") {
|
|
116
|
+
return resolveProfileRef(spec, projectRoot, chain);
|
|
117
|
+
}
|
|
118
|
+
return resolveInlineProfile(spec, projectRoot, chain);
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
// Resolves a string ref: a built-in name returns its bundled definition (terminal, no extends); any
|
|
122
|
+
// other string is treated as a relative profile file path (no built-in match, no network, no shell).
|
|
123
|
+
// The canonical built-in names are `gruff.minimal` / `gruff.recommended` / `gruff.strict`; the bare
|
|
124
|
+
// short forms (`minimal`, `recommended`, `strict`) are accepted as aliases for CLI ergonomics, so a
|
|
125
|
+
// built-in always wins over a same-named extensionless file - point `--profile` at `./name` for a file.
|
|
126
|
+
function resolveProfileRef(ref: string, projectRoot: string, chain: string[]): ProfileDefinition {
|
|
127
|
+
const builtIn = BUILT_IN_PROFILES.get(ref) ?? BUILT_IN_PROFILES.get(`gruff.${ref}`);
|
|
128
|
+
if (builtIn) {
|
|
129
|
+
return cloneProfileDefinition(builtIn);
|
|
130
|
+
}
|
|
131
|
+
return resolveProfileFile(ref, projectRoot, chain);
|
|
132
|
+
}
|
|
133
|
+
|
|
134
|
+
// Loads and resolves a profile file, treating its parsed top-level mapping as an inline profile
|
|
135
|
+
// spec. A missing file or a cycle caught by the chain guard throws ConfigLoadError at load time.
|
|
136
|
+
function resolveProfileFile(ref: string, projectRoot: string, chain: string[]): ProfileDefinition {
|
|
137
|
+
const path = absolutize(projectRoot, ref);
|
|
138
|
+
assertNoProfileCycle(path, chain);
|
|
139
|
+
if (!existsSync(path)) {
|
|
140
|
+
throw new ConfigLoadError(
|
|
141
|
+
`Profile extends file not found: ${path}.`,
|
|
142
|
+
`Point \`extends:\` (or --profile) at an existing .yaml/.yml/.json profile file, or use a built-in name: ${builtInProfileNames().join(", ")}.`,
|
|
143
|
+
);
|
|
144
|
+
}
|
|
145
|
+
return resolveInlineProfile(inlineSpecFromObject(parseConfigFile(path)), dirname(path), [...chain, path]);
|
|
146
|
+
}
|
|
147
|
+
|
|
148
|
+
// Resolves the base (the `extends:` target, defaulting to gruff.recommended) and overlays this spec's
|
|
149
|
+
// rule and path overrides on top with child-wins semantics.
|
|
150
|
+
function resolveInlineProfile(spec: InlineProfileSpec, projectRoot: string, chain: string[]): ProfileDefinition {
|
|
151
|
+
const base = resolveProfileRef(spec.extends ?? DEFAULT_PROFILE_NAME, projectRoot, chain);
|
|
152
|
+
return overlayProfile(base, spec);
|
|
153
|
+
}
|
|
154
|
+
|
|
155
|
+
// Overlays a child inline spec on a resolved base. Per-rule fields merge (child wins field-by-field);
|
|
156
|
+
// the child `ignoredPaths` array replaces the base's when present, else the base's is inherited.
|
|
157
|
+
function overlayProfile(base: ProfileDefinition, spec: InlineProfileSpec): ProfileDefinition {
|
|
158
|
+
const rules = new Map(base.rules);
|
|
159
|
+
for (const [ruleId, setting] of Object.entries(spec.rules ?? {})) {
|
|
160
|
+
assertKnownProfileRule(ruleId);
|
|
161
|
+
rules.set(ruleId, mergeRuleSetting(rules.get(ruleId), setting));
|
|
162
|
+
}
|
|
163
|
+
const ignoredPaths = spec.ignoredPaths !== undefined ? [...spec.ignoredPaths] : [...base.ignoredPaths];
|
|
164
|
+
return { name: base.name, rules, ignoredPaths };
|
|
165
|
+
}
|
|
166
|
+
|
|
167
|
+
// Field-level child-wins merge for one rule's settings: spread the parent then the child so every key
|
|
168
|
+
// the child sets (including `enabled: false`) overrides the parent while unset child keys inherit. Both
|
|
169
|
+
// inputs are built with conditional spreads upstream, so neither carries explicit-undefined keys that
|
|
170
|
+
// would clobber an inherited value.
|
|
171
|
+
function mergeRuleSetting(parent: ProfileRuleSetting | undefined, child: ProfileRuleSetting): ProfileRuleSetting {
|
|
172
|
+
return { ...parent, ...child };
|
|
173
|
+
}
|
|
174
|
+
|
|
175
|
+
// Defensive copy so overlays never mutate a shared built-in definition's rule map or ignore list.
|
|
176
|
+
function cloneProfileDefinition(definition: ProfileDefinition): ProfileDefinition {
|
|
177
|
+
return { name: definition.name, rules: new Map(definition.rules), ignoredPaths: [...definition.ignoredPaths] };
|
|
178
|
+
}
|
|
179
|
+
|
|
180
|
+
// Guards the `extends:` chain against cycles, naming the whole chain in visit order so the user can
|
|
181
|
+
// see both ends of the loop. A revisited `key` throws ConfigLoadError before the recursion repeats.
|
|
182
|
+
function assertNoProfileCycle(key: string, chain: string[]): void {
|
|
183
|
+
if (chain.includes(key)) {
|
|
184
|
+
throw new ConfigLoadError(
|
|
185
|
+
`Profile inheritance cycle detected: ${[...chain, key].join(" -> ")}.`,
|
|
186
|
+
"Break the `extends:` cycle so each profile in the chain is reached only once.",
|
|
187
|
+
);
|
|
188
|
+
}
|
|
189
|
+
}
|
|
190
|
+
|
|
191
|
+
// Validates a user profile rule id against the catalogue so a typo never silently no-ops at scan
|
|
192
|
+
// time: an id outside RULE_DESCRIPTORS throws ConfigLoadError at load time.
|
|
193
|
+
function assertKnownProfileRule(ruleId: string): void {
|
|
194
|
+
if (!isKnownRuleId(ruleId)) {
|
|
195
|
+
throw new ConfigLoadError(
|
|
196
|
+
`Unknown rule id in profile: ${JSON.stringify(ruleId)}.`,
|
|
197
|
+
"Use a rule id from `gruff-ts list-rules`; profile `rules:` keys must match the catalogue exactly.",
|
|
198
|
+
);
|
|
199
|
+
}
|
|
200
|
+
}
|
|
201
|
+
|
|
202
|
+
/*
|
|
203
|
+
* Parses the raw `profile:` value (from YAML/JSON or the CLI flag) into a typed ProfileSpec. A string
|
|
204
|
+
* is a built-in name or file path; a mapping is an inline spec. Throws ConfigLoadError on any other
|
|
205
|
+
* shape so a malformed `profile:` block surfaces as a clean config error, not a downstream crash.
|
|
206
|
+
*/
|
|
207
|
+
function parseProfileSpec(rawSpec: unknown): ProfileSpec {
|
|
208
|
+
if (typeof rawSpec === "string") {
|
|
209
|
+
return rawSpec;
|
|
210
|
+
}
|
|
211
|
+
const block = objectValue(rawSpec);
|
|
212
|
+
if (!block) {
|
|
213
|
+
throw new ConfigLoadError(
|
|
214
|
+
"`profile:` must be a built-in name, a profile file path, or a mapping with `extends:` and overrides.",
|
|
215
|
+
SUGGEST_EDIT_CONFIG,
|
|
216
|
+
);
|
|
217
|
+
}
|
|
218
|
+
return inlineSpecFromObject(block);
|
|
219
|
+
}
|
|
220
|
+
|
|
221
|
+
// Extracts the supported inline-profile keys (`extends`, `rules`, `ignoredPaths`) from a parsed
|
|
222
|
+
// mapping; other keys such as a `schemaVersion` on a shared profile file are ignored so it reads the
|
|
223
|
+
// same as an embedded block. A bad `extends` type or malformed override throws ConfigLoadError here.
|
|
224
|
+
function inlineSpecFromObject(block: Record<string, unknown>): InlineProfileSpec {
|
|
225
|
+
const spec: InlineProfileSpec = {};
|
|
226
|
+
if ("extends" in block) {
|
|
227
|
+
if (!isString(block.extends)) {
|
|
228
|
+
throw new ConfigLoadError("`profile.extends` must be a string: a built-in name or a relative profile file path.", SUGGEST_EDIT_CONFIG);
|
|
229
|
+
}
|
|
230
|
+
spec.extends = block.extends;
|
|
231
|
+
}
|
|
232
|
+
const rulesBlock = objectValue(block.rules);
|
|
233
|
+
if (rulesBlock) {
|
|
234
|
+
spec.rules = profileRulesFromBlock(rulesBlock);
|
|
235
|
+
}
|
|
236
|
+
if ("ignoredPaths" in block) {
|
|
237
|
+
spec.ignoredPaths = arrayValue(block.ignoredPaths).filter(isString);
|
|
238
|
+
}
|
|
239
|
+
return spec;
|
|
240
|
+
}
|
|
241
|
+
|
|
242
|
+
// Builds the per-rule settings map for an inline profile, reusing the same validation as the
|
|
243
|
+
// top-level `rules:` block (`ruleConfigValue` throws on a non-numeric threshold or bad severity).
|
|
244
|
+
function profileRulesFromBlock(rulesBlock: Record<string, unknown>): Record<string, ProfileRuleSetting> {
|
|
245
|
+
const rules: Record<string, ProfileRuleSetting> = {};
|
|
246
|
+
for (const [ruleId, value] of Object.entries(rulesBlock)) {
|
|
247
|
+
const rule = objectValue(value);
|
|
248
|
+
if (rule) {
|
|
249
|
+
rules[ruleId] = ruleConfigValue(rule);
|
|
250
|
+
}
|
|
251
|
+
}
|
|
252
|
+
return rules;
|
|
64
253
|
}
|
|
65
254
|
|
|
66
255
|
// Explicit `--config` wins; otherwise look for the first supported config at the project root. Returning
|
|
@@ -69,15 +258,87 @@ function selectedConfigPath(projectRoot: string, options: AnalysisOptions): stri
|
|
|
69
258
|
return options.config ? absolutize(projectRoot, options.config) : defaultConfigPath(projectRoot);
|
|
70
259
|
}
|
|
71
260
|
|
|
72
|
-
//
|
|
73
|
-
// rules.
|
|
74
|
-
//
|
|
261
|
+
// Top-level sections applied in a fixed order: schemaVersion → minimumSeverity → paths → allowlists
|
|
262
|
+
// → rules. schemaVersion runs first because every later parse depends on the contract version it
|
|
263
|
+
// declares, and minimumSeverity runs next so CLI consumers reading it during normalizeOptions see
|
|
264
|
+
// a populated map. Order does not affect correctness today but the stable application order keeps
|
|
265
|
+
// later overrides predictable if interdependencies are added.
|
|
75
266
|
function applyConfigValues(config: Config, raw: Record<string, unknown>): void {
|
|
267
|
+
applySchemaVersionConfig(raw);
|
|
268
|
+
applyMinimumSeverityConfig(config, raw);
|
|
76
269
|
applyPathConfig(config, raw);
|
|
77
270
|
applyAllowlistConfig(config, raw);
|
|
78
271
|
applyRuleConfig(config, raw);
|
|
79
272
|
}
|
|
80
273
|
|
|
274
|
+
/*
|
|
275
|
+
* Validates the required `schemaVersion` top-level field. Pre-1.0 break: configs missing the field
|
|
276
|
+
* or carrying any other version string are rejected (throws with a documented error listing the
|
|
277
|
+
* supported version) because there is no migration shim under the no-legacy-compat contract. The
|
|
278
|
+
* function does not mutate the loaded config because the only supported value matches
|
|
279
|
+
* `defaultConfig().schemaVersion` already; future versions would extend the union and require a
|
|
280
|
+
* write here. The schema invariant is fixed at `gruff-ts.config.v0.1`.
|
|
281
|
+
*/
|
|
282
|
+
function applySchemaVersionConfig(raw: Record<string, unknown>): void {
|
|
283
|
+
const schemaVersion = raw.schemaVersion;
|
|
284
|
+
if (schemaVersion === undefined) {
|
|
285
|
+
throw new ConfigLoadError('Config must include `schemaVersion: gruff-ts.config.v0.1` at the top.', SUGGEST_INIT_FORCE);
|
|
286
|
+
}
|
|
287
|
+
if (schemaVersion !== "gruff-ts.config.v0.1") {
|
|
288
|
+
throw new ConfigLoadError(`Unsupported schemaVersion: ${JSON.stringify(schemaVersion)}. Supported: "gruff-ts.config.v0.1".`, SUGGEST_INIT_FORCE);
|
|
289
|
+
}
|
|
290
|
+
}
|
|
291
|
+
|
|
292
|
+
// Parses the `minimumSeverity:` block into a Map keyed by command name. Validation throws on
|
|
293
|
+
// `dashboard` specifically (no `--fail-on` flag exists for it), on unknown command keys, and on
|
|
294
|
+
// every non-canonical value. Missing block is allowed - it just leaves the map empty so CLI
|
|
295
|
+
// consumers fall through to the binary default.
|
|
296
|
+
function applyMinimumSeverityConfig(config: Config, raw: Record<string, unknown>): void {
|
|
297
|
+
const block = objectValue(raw.minimumSeverity);
|
|
298
|
+
if (!block) {
|
|
299
|
+
return;
|
|
300
|
+
}
|
|
301
|
+
for (const [commandName, value] of Object.entries(block)) {
|
|
302
|
+
config.minimumSeverity.set(assertMinimumSeverityCommand(commandName), parseFailThresholdConfig(value));
|
|
303
|
+
}
|
|
304
|
+
}
|
|
305
|
+
|
|
306
|
+
/*
|
|
307
|
+
* Validates one `minimumSeverity:` map key. Throws on `dashboard` specifically because the
|
|
308
|
+
* dashboard subcommand has no `--fail-on` flag; accepting the key would silently no-op and
|
|
309
|
+
* operators would expect a gate that never fires. Throws on unknown commands so typos surface at
|
|
310
|
+
* load time instead of as silent CI footguns.
|
|
311
|
+
*/
|
|
312
|
+
function assertMinimumSeverityCommand(commandName: string): MinimumSeverityCommand {
|
|
313
|
+
if (commandName === "dashboard") {
|
|
314
|
+
throw new ConfigLoadError('Unknown command in minimumSeverity: "dashboard". The dashboard subcommand does not currently expose a --fail-on flag; configuring its threshold is not supported.', "Remove the `dashboard:` line from `minimumSeverity:` in `.gruff-ts.yaml`, or open an issue if dashboard should gate.");
|
|
315
|
+
}
|
|
316
|
+
if (commandName === "analyse" || commandName === "summary" || commandName === "report") {
|
|
317
|
+
return commandName;
|
|
318
|
+
}
|
|
319
|
+
throw new ConfigLoadError(`Unknown command in minimumSeverity: ${JSON.stringify(commandName)}. Valid keys: analyse, summary, report.`, SUGGEST_EDIT_CONFIG);
|
|
320
|
+
}
|
|
321
|
+
|
|
322
|
+
/*
|
|
323
|
+
* Validates one `FailThreshold` value coming from YAML. Throws on every non-canonical value with a
|
|
324
|
+
* clear error listing the four supported strings. `never` is rejected explicitly because earlier
|
|
325
|
+
* cross-port drafts considered it as the off-switch value before the family converged on `none`;
|
|
326
|
+
* guarding against drift back to `never` keeps the cross-port vocabulary aligned.
|
|
327
|
+
*/
|
|
328
|
+
function parseFailThresholdConfig(rawValue: unknown): FailThreshold {
|
|
329
|
+
if (rawValue === "none" || rawValue === "advisory" || rawValue === "warning" || rawValue === "error") {
|
|
330
|
+
return rawValue;
|
|
331
|
+
}
|
|
332
|
+
throw new ConfigLoadError(`FailThreshold must be one of: advisory, warning, error, none. Got: ${JSON.stringify(rawValue)}.`, SUGGEST_EDIT_CONFIG);
|
|
333
|
+
}
|
|
334
|
+
|
|
335
|
+
// Per-command lookup used by the CLI precedence chain (CLI flag > config > binary default).
|
|
336
|
+
// Returns undefined when the user did not configure that command so the caller can fall through
|
|
337
|
+
// to the binary default. Exported so the CLI consumers in `cli-program.ts` can consult it.
|
|
338
|
+
function minimumSeverityFor(config: Config, command: MinimumSeverityCommand): FailThreshold | undefined {
|
|
339
|
+
return config.minimumSeverity.get(command);
|
|
340
|
+
}
|
|
341
|
+
|
|
81
342
|
// Replaces `ignoredPaths` with the user list. Non-string entries are silently dropped - invalid
|
|
82
343
|
// YAML shapes should not abort the analysis run.
|
|
83
344
|
function applyPathConfig(config: Config, raw: Record<string, unknown>): void {
|
|
@@ -96,6 +357,7 @@ function applyAllowlistConfig(config: Config, raw: Record<string, unknown>): voi
|
|
|
96
357
|
}
|
|
97
358
|
config.secretPreviews = new Set(arrayValue(allowlists?.secretPreviews).filter(isString));
|
|
98
359
|
applyNamingAllowlist(config, allowlists, "bannedGenericNames");
|
|
360
|
+
applyNamingAllowlist(config, allowlists, "acceptedBooleanNames");
|
|
99
361
|
applyNamingAllowlist(config, allowlists, "booleanPrefixes");
|
|
100
362
|
applyNamingAllowlist(config, allowlists, "hungarianPrefixes");
|
|
101
363
|
applyNamingAllowlist(config, allowlists, "placeholderNames");
|
|
@@ -105,7 +367,7 @@ function applyAllowlistConfig(config: Config, raw: Record<string, unknown>): voi
|
|
|
105
367
|
|
|
106
368
|
// Replaces the entire list when the user provides that key - there is no merge with defaults.
|
|
107
369
|
// The "set the whole list" semantic is intentional so users can deliberately empty a list.
|
|
108
|
-
function applyNamingAllowlist(config: Config, allowlists: Record<string, unknown> | undefined, key: "bannedGenericNames" | "booleanPrefixes" | "hungarianPrefixes" | "placeholderNames" | "negativeBooleanAllowed" | "knownAcronyms"): void {
|
|
370
|
+
function applyNamingAllowlist(config: Config, allowlists: Record<string, unknown> | undefined, key: "bannedGenericNames" | "acceptedBooleanNames" | "booleanPrefixes" | "hungarianPrefixes" | "placeholderNames" | "negativeBooleanAllowed" | "knownAcronyms"): void {
|
|
109
371
|
if (!allowlists || !(key in allowlists)) {
|
|
110
372
|
return;
|
|
111
373
|
}
|
|
@@ -139,18 +401,23 @@ function ruleConfigValue(rule: Record<string, unknown>): RuleOverride {
|
|
|
139
401
|
return ruleOverride;
|
|
140
402
|
}
|
|
141
403
|
|
|
142
|
-
|
|
404
|
+
/*
|
|
405
|
+
* Validates individual `threshold` and `severity` types. Either, neither, or both may be present:
|
|
406
|
+
* many rules have no `threshold` knob at all (security.eval-call, waste.any-type, etc.), so a
|
|
407
|
+
* "must be configured together" gate would block any severity-only override on those rules even
|
|
408
|
+
* though `gruff-ts list-rules <id>` advertises `rules.<id>.severity` as a public knob. Each field
|
|
409
|
+
* is independently optional and falls through to the descriptor default when absent.
|
|
410
|
+
*
|
|
411
|
+
* Throws ConfigLoadError when `threshold` is present but non-numeric, or when `severity` is
|
|
412
|
+
* present but not one of `advisory|warning|error`. Returns silently when both fields are absent
|
|
413
|
+
* (the common case for `enabled`-only or options-only overrides).
|
|
414
|
+
*/
|
|
143
415
|
function assertRuleThresholdConfig(rule: Record<string, unknown>): void {
|
|
144
|
-
|
|
145
|
-
|
|
146
|
-
if (hasThreshold && typeof rule.threshold !== "number") {
|
|
147
|
-
throw new Error('Rule config key "threshold" must be numeric.');
|
|
416
|
+
if ("threshold" in rule && typeof rule.threshold !== "number") {
|
|
417
|
+
throw new ConfigLoadError('Rule config key "threshold" must be numeric.', SUGGEST_EDIT_CONFIG);
|
|
148
418
|
}
|
|
149
|
-
if (
|
|
150
|
-
throw new
|
|
151
|
-
}
|
|
152
|
-
if (hasThreshold !== hasSeverity) {
|
|
153
|
-
throw new Error('Rule config keys "threshold" and "severity" must be configured together.');
|
|
419
|
+
if ("severity" in rule && !isSeverity(rule.severity)) {
|
|
420
|
+
throw new ConfigLoadError('Rule config key "severity" must be "advisory", "warning", or "error".', SUGGEST_EDIT_CONFIG);
|
|
154
421
|
}
|
|
155
422
|
}
|
|
156
423
|
|
|
@@ -203,373 +470,6 @@ function defaultConfigPath(projectRoot: string): string | undefined {
|
|
|
203
470
|
return undefined;
|
|
204
471
|
}
|
|
205
472
|
|
|
206
|
-
/*
|
|
207
|
-
* Reads YAML or JSON config and rejects unknown extensions. Throws on malformed input so the user
|
|
208
|
-
* sees a concrete error rather than a silently-empty config.
|
|
209
|
-
*/
|
|
210
|
-
function parseConfigFile(path: string): Record<string, unknown> {
|
|
211
|
-
const source = readFileSync(path, "utf8").replace(/^\uFEFF/, "");
|
|
212
|
-
const extension = extname(path).toLowerCase();
|
|
213
|
-
const parsed = extension === ".yaml" || extension === ".yml" ? parseYamlConfig(source) : extension === ".json" ? (JSON.parse(source) as unknown) : undefined;
|
|
214
|
-
const config = objectValue(parsed);
|
|
215
|
-
if (!config) {
|
|
216
|
-
throw new Error(`Config file must contain an object with .yaml, .yml, or .json extension: ${path}`);
|
|
217
|
-
}
|
|
218
|
-
return config;
|
|
219
|
-
}
|
|
220
|
-
|
|
221
|
-
// One non-blank, comment-stripped YAML line. `indent` is the column count (spaces only - tabs are
|
|
222
|
-
// rejected upstream) and is the sole signal used to nest blocks. `content` is whitespace-trimmed.
|
|
223
|
-
interface YamlLine {
|
|
224
|
-
indent: number;
|
|
225
|
-
content: string;
|
|
226
|
-
}
|
|
227
|
-
|
|
228
|
-
// Mutable cursor through `lines`. Stored on the heap so recursive `parseYamlBlock` calls share
|
|
229
|
-
// position state instead of threading an index argument.
|
|
230
|
-
interface YamlParser {
|
|
231
|
-
lines: YamlLine[];
|
|
232
|
-
index: number;
|
|
233
|
-
}
|
|
234
|
-
|
|
235
|
-
/*
|
|
236
|
-
* Custom YAML parser that intentionally supports only a documented subset (mappings, arrays,
|
|
237
|
-
* scalars, inline `[]`/`{}`) - keeps gruff free of a yaml dependency. Throws on malformed input
|
|
238
|
-
* because silently misparsing config would produce wrong findings and a stable but broken baseline.
|
|
239
|
-
*/
|
|
240
|
-
function parseYamlConfig(source: string): Record<string, unknown> {
|
|
241
|
-
const parser = { lines: yamlLines(source), index: 0 };
|
|
242
|
-
const parsedDocument = parser.lines.length === 0 ? {} : parseYamlBlock(parser, parser.lines[0]?.indent ?? 0);
|
|
243
|
-
const config = objectValue(parsedDocument);
|
|
244
|
-
if (!config) {
|
|
245
|
-
throw new Error("Config YAML must contain a mapping object.");
|
|
246
|
-
}
|
|
247
|
-
return config;
|
|
248
|
-
}
|
|
249
|
-
|
|
250
|
-
// Dispatch entry for a block. Empty (no lines at this indent) returns `{}`; sequence lines lead
|
|
251
|
-
// into the array parser; everything else is an object/mapping.
|
|
252
|
-
function parseYamlBlock(parser: YamlParser, indent: number): unknown {
|
|
253
|
-
const line = parser.lines[parser.index];
|
|
254
|
-
if (!line || line.indent < indent) {
|
|
255
|
-
return {};
|
|
256
|
-
}
|
|
257
|
-
return isYamlArrayLine(line) ? parseYamlArray(parser, line.indent) : parseYamlObject(parser, line.indent);
|
|
258
|
-
}
|
|
259
|
-
|
|
260
|
-
// Walks mapping entries at one indent level, stopping when the next line dedents or switches to
|
|
261
|
-
// sequence form. Throws on unexpected indent so a missed key isn't silently swallowed.
|
|
262
|
-
function parseYamlObject(parser: YamlParser, indent: number): Record<string, unknown> {
|
|
263
|
-
const result: Record<string, unknown> = {};
|
|
264
|
-
while (parser.index < parser.lines.length) {
|
|
265
|
-
const line = parser.lines[parser.index];
|
|
266
|
-
if (!line || line.indent < indent || isYamlArrayLine(line)) {
|
|
267
|
-
break;
|
|
268
|
-
}
|
|
269
|
-
assertYamlIndent(line, indent);
|
|
270
|
-
addYamlObjectEntry(parser, indent, line, result);
|
|
271
|
-
}
|
|
272
|
-
return result;
|
|
273
|
-
}
|
|
274
|
-
|
|
275
|
-
// Inline scalar after the colon → leaf value; bare key → recurse into nested block. Keys are
|
|
276
|
-
// unquoted so `"foo"` and `foo` produce the same result key.
|
|
277
|
-
function addYamlObjectEntry(parser: YamlParser, indent: number, line: YamlLine, result: Record<string, unknown>): void {
|
|
278
|
-
const [rawKey, rawValue] = yamlKeyValuePair(line.content);
|
|
279
|
-
const scalarText = rawValue.trim();
|
|
280
|
-
parser.index += 1;
|
|
281
|
-
result[unquoteYaml(rawKey.trim())] = scalarText.length > 0 ? parseYamlScalar(scalarText) : parseNestedYamlValue(parser, indent, {});
|
|
282
|
-
}
|
|
283
|
-
|
|
284
|
-
// Block-style YAML sequence. Inline `[...]` arrays are handled by `parseYamlCollectionScalar`;
|
|
285
|
-
// this walks the `- item` lines and recurses into nested values for empty `-` openers.
|
|
286
|
-
function parseYamlArray(parser: YamlParser, indent: number): unknown[] {
|
|
287
|
-
const result: unknown[] = [];
|
|
288
|
-
while (parser.index < parser.lines.length) {
|
|
289
|
-
const line = parser.lines[parser.index];
|
|
290
|
-
if (!line || line.indent < indent || !isYamlArrayLine(line)) {
|
|
291
|
-
break;
|
|
292
|
-
}
|
|
293
|
-
assertYamlIndent(line, indent);
|
|
294
|
-
result.push(parseYamlArrayItem(parser, indent, line));
|
|
295
|
-
}
|
|
296
|
-
return result;
|
|
297
|
-
}
|
|
298
|
-
|
|
299
|
-
// Three branches: bare `-` (recurse for nested), `- key: value` (mapping item), `- scalar`.
|
|
300
|
-
// Bare-dash items return null when the nested block is empty so the array entry isn't elided.
|
|
301
|
-
function parseYamlArrayItem(parser: YamlParser, indent: number, line: YamlLine): unknown {
|
|
302
|
-
const itemText = line.content === "-" ? "" : line.content.slice(2).trim();
|
|
303
|
-
parser.index += 1;
|
|
304
|
-
if (itemText.length === 0) {
|
|
305
|
-
return parseNestedYamlValue(parser, indent, null);
|
|
306
|
-
}
|
|
307
|
-
|
|
308
|
-
const pair = splitYamlKeyValue(itemText);
|
|
309
|
-
return pair ? parseYamlArrayMappingItem(parser, indent, pair) : parseYamlScalar(itemText);
|
|
310
|
-
}
|
|
311
|
-
|
|
312
|
-
// `- key: value` form: the first key is on the dash line, subsequent keys live as a nested object.
|
|
313
|
-
// Mirrors the inline-vs-nested split of `addYamlObjectEntry`.
|
|
314
|
-
function parseYamlArrayMappingItem(parser: YamlParser, indent: number, pair: [string, string]): Record<string, unknown> {
|
|
315
|
-
const [rawKey, rawValue] = pair;
|
|
316
|
-
const scalarText = rawValue.trim();
|
|
317
|
-
return {
|
|
318
|
-
[unquoteYaml(rawKey.trim())]: scalarText.length > 0 ? parseYamlScalar(scalarText) : parseNestedYamlValue(parser, indent, {}),
|
|
319
|
-
};
|
|
320
|
-
}
|
|
321
|
-
|
|
322
|
-
// Returns the nested block if the next line indents further, otherwise the caller's `fallback`.
|
|
323
|
-
// `fallback` is `{}` for mappings (empty value → empty object) and `null` for sequences.
|
|
324
|
-
function parseNestedYamlValue(parser: YamlParser, indent: number, fallback: unknown): unknown {
|
|
325
|
-
const nestedIndent = parser.lines[parser.index]?.indent;
|
|
326
|
-
return nestedIndent !== undefined && nestedIndent > indent ? parseYamlBlock(parser, nestedIndent) : fallback;
|
|
327
|
-
}
|
|
328
|
-
|
|
329
|
-
/*
|
|
330
|
-
* Throws when a mapping line has no `:` separator - the parser cannot recover, and a silent skip
|
|
331
|
-
* would hide a real config typo from the user.
|
|
332
|
-
*/
|
|
333
|
-
function yamlKeyValuePair(content: string): [string, string] {
|
|
334
|
-
const pair = splitYamlKeyValue(content);
|
|
335
|
-
if (!pair) {
|
|
336
|
-
throw new Error(`Invalid YAML mapping line: "${content}".`);
|
|
337
|
-
}
|
|
338
|
-
return pair;
|
|
339
|
-
}
|
|
340
|
-
|
|
341
|
-
// `- ` or bare `-` only - two-dash openers and ambiguous variants are not sequence entries.
|
|
342
|
-
function isYamlArrayLine(line: YamlLine): boolean {
|
|
343
|
-
return line.content.startsWith("- ") || line.content === "-";
|
|
344
|
-
}
|
|
345
|
-
|
|
346
|
-
/*
|
|
347
|
-
* Throws when a line is indented more than expected at this scope. Without this guard, a stray
|
|
348
|
-
* indent would silently produce a sub-mapping and the user's config would mean something different.
|
|
349
|
-
*/
|
|
350
|
-
function assertYamlIndent(line: YamlLine, indent: number): void {
|
|
351
|
-
if (line.indent > indent) {
|
|
352
|
-
throw new Error(`Invalid YAML indentation near "${line.content}".`);
|
|
353
|
-
}
|
|
354
|
-
}
|
|
355
|
-
|
|
356
|
-
/*
|
|
357
|
-
* Pre-pass that drops blank/comment lines and rejects tab-indented input. Tabs are forbidden
|
|
358
|
-
* because mixing them with spaces is the canonical YAML footgun, so the parser throws rather than
|
|
359
|
-
* guess at the user's intent.
|
|
360
|
-
*/
|
|
361
|
-
function yamlLines(source: string): YamlLine[] {
|
|
362
|
-
const lines: YamlLine[] = [];
|
|
363
|
-
for (const rawLine of source.replace(/\r\n/g, "\n").split("\n")) {
|
|
364
|
-
const withoutComment = stripYamlComment(rawLine).trimEnd();
|
|
365
|
-
if (withoutComment.trim().length === 0) {
|
|
366
|
-
continue;
|
|
367
|
-
}
|
|
368
|
-
const indentText = withoutComment.match(/^\s*/)?.[0] ?? "";
|
|
369
|
-
if (indentText.includes("\t")) {
|
|
370
|
-
throw new Error("Tabs are not supported in gruff YAML config indentation.");
|
|
371
|
-
}
|
|
372
|
-
lines.push({ indent: indentText.length, content: withoutComment.trimStart() });
|
|
373
|
-
}
|
|
374
|
-
return lines;
|
|
375
|
-
}
|
|
376
|
-
|
|
377
|
-
// Drops `# comment` text but only when the `#` is not inside quotes - `foo: "a # b"` keeps the
|
|
378
|
-
// comment-like substring as part of the string value, matching YAML semantics.
|
|
379
|
-
function stripYamlComment(line: string): string {
|
|
380
|
-
const commentIndex = firstUnquotedIndex(line, (character, index) => character === "#" && (index === 0 || /\s/.test(line[index - 1] ?? "")));
|
|
381
|
-
return commentIndex === undefined ? line : line.slice(0, commentIndex);
|
|
382
|
-
}
|
|
383
|
-
|
|
384
|
-
// Finds the first `:<space>` outside quotes. Required because a quoted value can legitimately
|
|
385
|
-
// contain `:` (`url: "https://..."`) and the parser must not split at the first occurrence.
|
|
386
|
-
function splitYamlKeyValue(mappingText: string): [string, string] | undefined {
|
|
387
|
-
const separatorIndex = firstUnquotedIndex(mappingText, (character, index) => {
|
|
388
|
-
const next = mappingText[index + 1];
|
|
389
|
-
return character === ":" && (!next || /\s/.test(next));
|
|
390
|
-
});
|
|
391
|
-
return separatorIndex === undefined ? undefined : [mappingText.slice(0, separatorIndex), mappingText.slice(separatorIndex + 1)];
|
|
392
|
-
}
|
|
393
|
-
|
|
394
|
-
// Tries each scalar parser in order; the first to claim a match wins. Bare strings are the
|
|
395
|
-
// fallback so callers never end up with `undefined` for a non-empty scalar.
|
|
396
|
-
function parseYamlScalar(scalarText: string): unknown {
|
|
397
|
-
const trimmed = scalarText.trim();
|
|
398
|
-
for (const parser of [parseYamlCollectionScalar, parseYamlQuotedScalar, parseYamlKeywordScalar, parseYamlNumberScalar]) {
|
|
399
|
-
const parsedScalar = parser(trimmed);
|
|
400
|
-
if (parsedScalar.isMatched) {
|
|
401
|
-
return parsedScalar.value;
|
|
402
|
-
}
|
|
403
|
-
}
|
|
404
|
-
return trimmed;
|
|
405
|
-
}
|
|
406
|
-
|
|
407
|
-
// Parses YAML collection scalar from source text.
|
|
408
|
-
function parseYamlCollectionScalar(trimmed: string): ParsedYamlScalar {
|
|
409
|
-
if (trimmed === "[]") {
|
|
410
|
-
return matchedYamlScalar([]);
|
|
411
|
-
}
|
|
412
|
-
if (trimmed === "{}") {
|
|
413
|
-
return matchedYamlScalar({});
|
|
414
|
-
}
|
|
415
|
-
if (trimmed.startsWith("[") && trimmed.endsWith("]")) {
|
|
416
|
-
return matchedYamlScalar(parseYamlInlineArray(trimmed));
|
|
417
|
-
}
|
|
418
|
-
return UNMATCHED_YAML_SCALAR;
|
|
419
|
-
}
|
|
420
|
-
|
|
421
|
-
// `"..."` or `'...'` wrapped. Calls `unquoteYaml` so the resulting value matches what a real YAML
|
|
422
|
-
// engine would produce; matched-state flag separates "empty quoted string" from "not a quoted scalar".
|
|
423
|
-
function parseYamlQuotedScalar(trimmed: string): ParsedYamlScalar {
|
|
424
|
-
if (isQuotedYaml(trimmed)) {
|
|
425
|
-
return matchedYamlScalar(unquoteYaml(trimmed));
|
|
426
|
-
}
|
|
427
|
-
return UNMATCHED_YAML_SCALAR;
|
|
428
|
-
}
|
|
429
|
-
|
|
430
|
-
// Recognises `true`/`false`/`null`/`~` (case-insensitive). The keyword table is shared so the
|
|
431
|
-
// parser produces consistent JS values (`null` instead of the string "null").
|
|
432
|
-
function parseYamlKeywordScalar(trimmed: string): ParsedYamlScalar {
|
|
433
|
-
const normalized = trimmed.toLowerCase();
|
|
434
|
-
if (YAML_KEYWORD_SCALARS.has(normalized)) {
|
|
435
|
-
return matchedYamlScalar(YAML_KEYWORD_SCALARS.get(normalized) ?? null);
|
|
436
|
-
}
|
|
437
|
-
return UNMATCHED_YAML_SCALAR;
|
|
438
|
-
}
|
|
439
|
-
|
|
440
|
-
// Strict numeric pattern - no octals, no special floats. Numbers that don't fit fall through to
|
|
441
|
-
// bare-string handling, so `0xFF` or `1e10` stay as strings rather than producing surprising values.
|
|
442
|
-
function parseYamlNumberScalar(trimmed: string): ParsedYamlScalar {
|
|
443
|
-
if (YAML_NUMBER_SCALAR.test(trimmed)) {
|
|
444
|
-
return matchedYamlScalar(Number(trimmed));
|
|
445
|
-
}
|
|
446
|
-
return UNMATCHED_YAML_SCALAR;
|
|
447
|
-
}
|
|
448
|
-
|
|
449
|
-
// Returns a "matched" result with the parsed value, distinguishing real matches from the shared
|
|
450
|
-
// `UNMATCHED_YAML_SCALAR` sentinel used by every parser that failed.
|
|
451
|
-
function matchedYamlScalar(scalarValue: unknown): ParsedYamlScalar {
|
|
452
|
-
return { isMatched: true, value: scalarValue };
|
|
453
|
-
}
|
|
454
|
-
|
|
455
|
-
// Inline `[a, b, c]` arrays. Items are split on unquoted commas and each item recurses through
|
|
456
|
-
// `parseYamlScalar` so nested types resolve correctly.
|
|
457
|
-
function parseYamlInlineArray(arrayText: string): unknown[] {
|
|
458
|
-
const inner = arrayText.slice(1, -1).trim();
|
|
459
|
-
if (inner.length === 0) {
|
|
460
|
-
return [];
|
|
461
|
-
}
|
|
462
|
-
return splitYamlInlineItems(inner).map((item) => parseYamlScalar(item));
|
|
463
|
-
}
|
|
464
|
-
|
|
465
|
-
// Quote-aware split on commas. Treating a quoted comma as a separator would corrupt entries like
|
|
466
|
-
// `["a, b", "c"]` - same reason `splitYamlKeyValue` is also quote-aware.
|
|
467
|
-
function splitYamlInlineItems(itemsText: string): string[] {
|
|
468
|
-
const items: string[] = [];
|
|
469
|
-
let start = 0;
|
|
470
|
-
for (const index of unquotedIndexes(itemsText, ",")) {
|
|
471
|
-
items.push(itemsText.slice(start, index).trim());
|
|
472
|
-
start = index + 1;
|
|
473
|
-
}
|
|
474
|
-
items.push(itemsText.slice(start).trim());
|
|
475
|
-
return items;
|
|
476
|
-
}
|
|
477
|
-
|
|
478
|
-
// Lexer state for the YAML quote walkers. `isEscaped` only matters inside `"..."` quotes because
|
|
479
|
-
// single-quoted YAML strings use `''` doubling rather than backslash escapes.
|
|
480
|
-
interface QuoteScanState {
|
|
481
|
-
quote: string | undefined;
|
|
482
|
-
isEscaped: boolean;
|
|
483
|
-
}
|
|
484
|
-
|
|
485
|
-
// Walks `value` calling `predicate` only at quote-free positions. Used by both the comment
|
|
486
|
-
// stripper and the colon splitter to keep quoted text inert.
|
|
487
|
-
function firstUnquotedIndex(sourceText: string, predicate: (character: string, index: number) => boolean): number | undefined {
|
|
488
|
-
for (const index of unquotedIndexes(sourceText)) {
|
|
489
|
-
const character = sourceText[index] ?? "";
|
|
490
|
-
if (predicate(character, index)) {
|
|
491
|
-
return index;
|
|
492
|
-
}
|
|
493
|
-
}
|
|
494
|
-
return undefined;
|
|
495
|
-
}
|
|
496
|
-
|
|
497
|
-
// All quote-free positions in `value`, optionally filtered by a specific character. The two-mode
|
|
498
|
-
// shape lets the same lexer feed both `firstUnquotedIndex` and the inline-array splitter.
|
|
499
|
-
function unquotedIndexes(sourceText: string, expectedCharacter?: string): number[] {
|
|
500
|
-
const indexes: number[] = [];
|
|
501
|
-
const state: QuoteScanState = { quote: undefined, isEscaped: false };
|
|
502
|
-
for (let index = 0; index < sourceText.length; index += 1) {
|
|
503
|
-
const character = sourceText[index] ?? "";
|
|
504
|
-
if (consumeQuotedCharacter(character, state)) {
|
|
505
|
-
continue;
|
|
506
|
-
}
|
|
507
|
-
if (isYamlQuote(character)) {
|
|
508
|
-
state.quote = character;
|
|
509
|
-
continue;
|
|
510
|
-
}
|
|
511
|
-
if (!expectedCharacter || character === expectedCharacter) {
|
|
512
|
-
indexes.push(index);
|
|
513
|
-
}
|
|
514
|
-
}
|
|
515
|
-
return indexes;
|
|
516
|
-
}
|
|
517
|
-
|
|
518
|
-
// Returns true and mutates `state` when the character was inside a quoted region. The escape
|
|
519
|
-
// handling is double-quote-only because YAML single-quote strings have no `\` escapes.
|
|
520
|
-
function consumeQuotedCharacter(character: string, state: QuoteScanState): boolean {
|
|
521
|
-
if (!state.quote) {
|
|
522
|
-
return false;
|
|
523
|
-
}
|
|
524
|
-
if (state.quote === "\"" && character === "\\" && !state.isEscaped) {
|
|
525
|
-
state.isEscaped = true;
|
|
526
|
-
return true;
|
|
527
|
-
}
|
|
528
|
-
if (character === state.quote && !state.isEscaped) {
|
|
529
|
-
state.quote = undefined;
|
|
530
|
-
}
|
|
531
|
-
state.isEscaped = false;
|
|
532
|
-
return true;
|
|
533
|
-
}
|
|
534
|
-
|
|
535
|
-
// Single and double quotes only - YAML allows backticks elsewhere but they're not part of the
|
|
536
|
-
// supported subset here, and the parser would have to reject them anyway.
|
|
537
|
-
function isYamlQuote(character: string): boolean {
|
|
538
|
-
return character === "\"" || character === "'";
|
|
539
|
-
}
|
|
540
|
-
|
|
541
|
-
// Both endpoints must use the same quote character; mismatched openers/closers are treated as
|
|
542
|
-
// plain text rather than a parse error so a single stray quote in user prose doesn't fail the config.
|
|
543
|
-
function isQuotedYaml(scalarText: string): boolean {
|
|
544
|
-
return scalarText.length >= 2 && ((scalarText.startsWith("\"") && scalarText.endsWith("\"")) || (scalarText.startsWith("'") && scalarText.endsWith("'")));
|
|
545
|
-
}
|
|
546
|
-
|
|
547
|
-
// Removes quotes and decodes the supported escapes: `''` doubling for single quotes, and `\n`,
|
|
548
|
-
// `\r`, `\t`, `\"`, `\\` for double quotes. Anything else passes through unchanged so the parser
|
|
549
|
-
// reports the user's exact intent rather than mangling unknown escape sequences.
|
|
550
|
-
function unquoteYaml(scalarText: string): string {
|
|
551
|
-
if (!isQuotedYaml(scalarText)) {
|
|
552
|
-
return scalarText;
|
|
553
|
-
}
|
|
554
|
-
const quote = scalarText[0];
|
|
555
|
-
const body = scalarText.slice(1, -1);
|
|
556
|
-
if (quote === "'") {
|
|
557
|
-
return body.replace(/''/g, "'");
|
|
558
|
-
}
|
|
559
|
-
return body.replace(/\\(["\\nrt])/g, (_match, escaped: string) => {
|
|
560
|
-
if (escaped === "n") {
|
|
561
|
-
return "\n";
|
|
562
|
-
}
|
|
563
|
-
if (escaped === "r") {
|
|
564
|
-
return "\r";
|
|
565
|
-
}
|
|
566
|
-
if (escaped === "t") {
|
|
567
|
-
return "\t";
|
|
568
|
-
}
|
|
569
|
-
return escaped;
|
|
570
|
-
});
|
|
571
|
-
}
|
|
572
|
-
|
|
573
473
|
// Rules are enabled by default - the absence of a config entry means "use the descriptor default",
|
|
574
474
|
// which is the documented contract for how unset rules behave.
|
|
575
475
|
function ruleEnabled(config: Config, ruleId: string): boolean {
|
|
@@ -594,27 +494,10 @@ function optionNumber(config: Config, ruleId: string, name: string, defaultValue
|
|
|
594
494
|
return config.rules.get(ruleId)?.options.get(name) ?? defaultValue;
|
|
595
495
|
}
|
|
596
496
|
|
|
597
|
-
// Type narrowing for `Record<string, unknown>`. Returns undefined (not null) for non-objects so
|
|
598
|
-
// the caller can use the standard optional-chaining pattern through the rest of the config layer.
|
|
599
|
-
function objectValue(configValue: unknown): Record<string, unknown> | undefined {
|
|
600
|
-
return typeof configValue === "object" && configValue !== null && !Array.isArray(configValue) ? (configValue as Record<string, unknown>) : undefined;
|
|
601
|
-
}
|
|
602
|
-
|
|
603
|
-
// Returns the array or an empty array - never undefined - so callers can iterate without a guard.
|
|
604
|
-
function arrayValue(configValue: unknown): unknown[] {
|
|
605
|
-
return Array.isArray(configValue) ? configValue : [];
|
|
606
|
-
}
|
|
607
|
-
|
|
608
|
-
// String type narrowing. Exported so other modules can share a single string-test that matches
|
|
609
|
-
// the config-side semantics (rejects non-string truthy values like numbers).
|
|
610
|
-
function isString(configValue: unknown): configValue is string {
|
|
611
|
-
return typeof configValue === "string";
|
|
612
|
-
}
|
|
613
|
-
|
|
614
497
|
// Whitelist check used both by config validation (throws on bad values) and by `applyRuleSeverityConfig`.
|
|
615
498
|
// The set of accepted strings is the public severity vocabulary; adding entries is a schema change.
|
|
616
499
|
function isSeverity(configValue: unknown): configValue is Severity {
|
|
617
500
|
return configValue === "advisory" || configValue === "warning" || configValue === "error";
|
|
618
501
|
}
|
|
619
502
|
|
|
620
|
-
export { defaultConfigPath,
|
|
503
|
+
export { defaultConfigPath, loadConfig, minimumSeverityFor, optionNumber, resolveProfile, ruleEnabled, ruleSeverity, threshold };
|