@blundergoat/gruff-ts 0.2.0 → 0.3.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +24 -0
- package/README.md +80 -12
- package/docs/README.md +2 -0
- package/docs/agent-hook.md +80 -0
- package/docs/ci-integration.md +16 -0
- package/docs/configuration.md +21 -2
- package/docs/output-formats.md +10 -0
- package/docs/philosophy.md +21 -0
- package/docs/releasing.md +5 -5
- package/docs/rules.md +24 -15
- package/package.json +5 -5
- package/scripts/bump-version.sh +1 -1
- package/src/analyser.ts +43 -30
- package/src/blocks.ts +20 -67
- 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 +105 -11
- package/src/comment-rules.ts +4 -0
- package/src/config-parse.ts +458 -0
- package/src/config-preservation.ts +1 -1
- package/src/config.ts +215 -460
- package/src/constants.ts +1 -1
- package/src/context-doc-rules.ts +2 -4
- package/src/dashboard.ts +7 -4
- package/src/discovery.ts +88 -32
- package/src/findings-helpers.ts +41 -5
- package/src/fixtures/rule-catalogue-security-doctrine.ts +28 -0
- package/src/init-config.ts +3 -0
- package/src/naming-pushers.ts +35 -6
- 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 +1 -1
- package/src/report-renderers.ts +58 -0
- package/src/rule-list.ts +22 -1
- package/src/rules.ts +10 -10
- package/src/safety-rules.ts +16 -6
- package/src/scoring.ts +43 -5
- package/src/security-flow-rules.ts +533 -0
- package/src/sensitive-data-rules.ts +138 -2
- package/src/test-block-rules.ts +106 -15
- package/src/test-fixtures.ts +46 -8
- package/src/types.ts +78 -2
package/src/config.ts
CHANGED
|
@@ -1,33 +1,15 @@
|
|
|
1
|
-
// Config loading
|
|
2
|
-
|
|
3
|
-
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";
|
|
4
6
|
import { ConfigLoadError } from "./config-load-error.ts";
|
|
5
|
-
import
|
|
6
|
-
|
|
7
|
-
// Two common suggestion strings reused across the validators. Hoisted out so a future doc-link
|
|
8
|
-
// or wording tweak lands in one place instead of N throw sites.
|
|
9
|
-
const SUGGEST_INIT_FORCE = "Run `gruff-ts init --force` to regenerate the config from current defaults (preserves your `paths.ignore` and `minimumSeverity:` entries).";
|
|
10
|
-
const SUGGEST_EDIT_CONFIG = "Edit `.gruff-ts.yaml` to use a valid value, or run `gruff-ts init --force` to regenerate from defaults.";
|
|
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";
|
|
11
9
|
|
|
12
10
|
type RuleOverride = Config["rules"] extends Map<string, infer RuleOverrideValue> ? RuleOverrideValue : never;
|
|
13
11
|
|
|
14
12
|
const DEFAULT_CONFIG_FILES = [".gruff-ts.yaml", ".gruff.json", ".gruff.yaml", ".gruff.yml"] as const;
|
|
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
13
|
|
|
32
14
|
// Built-in defaults applied before any user config overlays. The string lists here (accepted
|
|
33
15
|
// abbreviations, banned generic names, boolean prefixes, …) are the stable rule contract - they
|
|
@@ -40,6 +22,7 @@ function defaultConfig(): Config {
|
|
|
40
22
|
acceptedAbbreviations: new Set(["age", "app", "cb", "db", "fn", "fs", "id", "io", "key", "log", "max", "min", "now", "raw", "rx", "tx", "ui", "url"]),
|
|
41
23
|
secretPreviews: new Set(),
|
|
42
24
|
bannedGenericNames: new Set(["process", "handle", "doit", "run", "execute", "manage"]),
|
|
25
|
+
acceptedBooleanNames: new Set(["all", "apply", "check", "dev", "enabled", "force", "fresh", "harness", "json", "ok", "verbose", "yes"]),
|
|
43
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"]),
|
|
44
27
|
hungarianPrefixes: new Set(["str", "obj", "arr", "bool", "int", "num"]),
|
|
45
28
|
placeholderNames: new Set(["foo", "bar", "baz", "tmp", "temp", "thing", "stuff", "data", "value", "item"]),
|
|
@@ -60,16 +43,213 @@ function absolutize(projectRoot: string, path: string): string {
|
|
|
60
43
|
// `.gruff-ts.yaml` work zero-config. Throws on malformed YAML - the caller surfaces it as a fatal CLI error.
|
|
61
44
|
function loadConfig(projectRoot: string, options: AnalysisOptions): Config {
|
|
62
45
|
const config = defaultConfig();
|
|
63
|
-
|
|
64
|
-
|
|
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);
|
|
65
50
|
}
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
|
|
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;
|
|
69
68
|
}
|
|
69
|
+
applyProfileUnderlay(config, resolveProfile(parseProfileSpec(rawSpec), projectRoot));
|
|
70
|
+
}
|
|
70
71
|
|
|
71
|
-
|
|
72
|
-
|
|
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;
|
|
73
253
|
}
|
|
74
254
|
|
|
75
255
|
// Explicit `--config` wins; otherwise look for the first supported config at the project root. Returning
|
|
@@ -177,6 +357,7 @@ function applyAllowlistConfig(config: Config, raw: Record<string, unknown>): voi
|
|
|
177
357
|
}
|
|
178
358
|
config.secretPreviews = new Set(arrayValue(allowlists?.secretPreviews).filter(isString));
|
|
179
359
|
applyNamingAllowlist(config, allowlists, "bannedGenericNames");
|
|
360
|
+
applyNamingAllowlist(config, allowlists, "acceptedBooleanNames");
|
|
180
361
|
applyNamingAllowlist(config, allowlists, "booleanPrefixes");
|
|
181
362
|
applyNamingAllowlist(config, allowlists, "hungarianPrefixes");
|
|
182
363
|
applyNamingAllowlist(config, allowlists, "placeholderNames");
|
|
@@ -186,7 +367,7 @@ function applyAllowlistConfig(config: Config, raw: Record<string, unknown>): voi
|
|
|
186
367
|
|
|
187
368
|
// Replaces the entire list when the user provides that key - there is no merge with defaults.
|
|
188
369
|
// The "set the whole list" semantic is intentional so users can deliberately empty a list.
|
|
189
|
-
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 {
|
|
190
371
|
if (!allowlists || !(key in allowlists)) {
|
|
191
372
|
return;
|
|
192
373
|
}
|
|
@@ -289,415 +470,6 @@ function defaultConfigPath(projectRoot: string): string | undefined {
|
|
|
289
470
|
return undefined;
|
|
290
471
|
}
|
|
291
472
|
|
|
292
|
-
/*
|
|
293
|
-
* Reads YAML or JSON config and rejects unknown extensions. Raw IO failures (e.g. `--config <path>`
|
|
294
|
-
* pointing at a missing file) and JSON parse failures are rewrapped as ConfigLoadError so the CLI
|
|
295
|
-
* surface stays uniform - a bare ENOENT or SyntaxError would otherwise bypass the formatted
|
|
296
|
-
* "gruff-ts: config error" stderr path in `runWithConfigErrorHandling`.
|
|
297
|
-
*
|
|
298
|
-
* Throws ConfigLoadError when: the file is missing (ENOENT), the contents are not valid JSON, the
|
|
299
|
-
* YAML subset rejects the file (see parseYamlConfig), or the top-level value is not a mapping.
|
|
300
|
-
*/
|
|
301
|
-
function parseConfigFile(path: string): Record<string, unknown> {
|
|
302
|
-
const source = readConfigSource(path);
|
|
303
|
-
const extension = extname(path).toLowerCase();
|
|
304
|
-
const parsed = parseConfigSource(source, extension, path);
|
|
305
|
-
const config = objectValue(parsed);
|
|
306
|
-
if (!config) {
|
|
307
|
-
throw new ConfigLoadError(`Config file must contain an object with .yaml, .yml, or .json extension: ${path}`, SUGGEST_INIT_FORCE);
|
|
308
|
-
}
|
|
309
|
-
return config;
|
|
310
|
-
}
|
|
311
|
-
|
|
312
|
-
/*
|
|
313
|
-
* Reads the raw config bytes. Explicit `--config <path>` skips the `defaultConfigPath` existence
|
|
314
|
-
* check, so a typo here would otherwise dump a raw Node stack. Throws ConfigLoadError on ENOENT
|
|
315
|
-
* with a user-actionable suggestion; rethrows every other filesystem error unchanged so an
|
|
316
|
-
* unexpected IO failure still surfaces its native stack for debugging.
|
|
317
|
-
*/
|
|
318
|
-
function readConfigSource(path: string): string {
|
|
319
|
-
try {
|
|
320
|
-
return readFileSync(path, "utf8").replace(/^\uFEFF/, "");
|
|
321
|
-
} catch (error) {
|
|
322
|
-
if ((error as NodeJS.ErrnoException | null)?.code === "ENOENT") {
|
|
323
|
-
throw new ConfigLoadError(`Config file not found: ${path}.`, "Pass --config with an existing path, or omit the flag to use the default lookup.");
|
|
324
|
-
}
|
|
325
|
-
throw error;
|
|
326
|
-
}
|
|
327
|
-
}
|
|
328
|
-
|
|
329
|
-
// Routes to the YAML subset parser or the native JSON parser. Wraps `JSON.parse`'s SyntaxError so
|
|
330
|
-
// a malformed `.gruff.json` surfaces through the same ConfigLoadError channel as YAML failures
|
|
331
|
-
// (parseYamlConfig already throws ConfigLoadError on its own malformed inputs).
|
|
332
|
-
function parseConfigSource(source: string, extension: string, path: string): unknown {
|
|
333
|
-
if (extension === ".yaml" || extension === ".yml") {
|
|
334
|
-
return parseYamlConfig(source);
|
|
335
|
-
}
|
|
336
|
-
if (extension !== ".json") {
|
|
337
|
-
return undefined;
|
|
338
|
-
}
|
|
339
|
-
try {
|
|
340
|
-
return JSON.parse(source) as unknown;
|
|
341
|
-
} catch (error) {
|
|
342
|
-
if (error instanceof SyntaxError) {
|
|
343
|
-
throw new ConfigLoadError(`Config file is not valid JSON: ${error.message} (${path}).`, SUGGEST_EDIT_CONFIG);
|
|
344
|
-
}
|
|
345
|
-
throw error;
|
|
346
|
-
}
|
|
347
|
-
}
|
|
348
|
-
|
|
349
|
-
// One non-blank, comment-stripped YAML line. `indent` is the column count (spaces only - tabs are
|
|
350
|
-
// rejected upstream) and is the sole signal used to nest blocks. `content` is whitespace-trimmed.
|
|
351
|
-
interface YamlLine {
|
|
352
|
-
indent: number;
|
|
353
|
-
content: string;
|
|
354
|
-
}
|
|
355
|
-
|
|
356
|
-
// Mutable cursor through `lines`. Stored on the heap so recursive `parseYamlBlock` calls share
|
|
357
|
-
// position state instead of threading an index argument.
|
|
358
|
-
interface YamlParser {
|
|
359
|
-
lines: YamlLine[];
|
|
360
|
-
index: number;
|
|
361
|
-
}
|
|
362
|
-
|
|
363
|
-
/*
|
|
364
|
-
* Custom YAML parser that intentionally supports only a documented subset (mappings, arrays,
|
|
365
|
-
* scalars, inline `[]`/`{}`) - keeps gruff free of a yaml dependency. Throws on malformed input
|
|
366
|
-
* because silently misparsing config would produce wrong findings and a stable but broken baseline.
|
|
367
|
-
*/
|
|
368
|
-
function parseYamlConfig(source: string): Record<string, unknown> {
|
|
369
|
-
const parser = { lines: yamlLines(source), index: 0 };
|
|
370
|
-
const parsedDocument = parser.lines.length === 0 ? {} : parseYamlBlock(parser, parser.lines[0]?.indent ?? 0);
|
|
371
|
-
const config = objectValue(parsedDocument);
|
|
372
|
-
if (!config) {
|
|
373
|
-
throw new ConfigLoadError("Config YAML must contain a mapping object.", SUGGEST_INIT_FORCE);
|
|
374
|
-
}
|
|
375
|
-
return config;
|
|
376
|
-
}
|
|
377
|
-
|
|
378
|
-
// Dispatch entry for a block. Empty (no lines at this indent) returns `{}`; sequence lines lead
|
|
379
|
-
// into the array parser; everything else is an object/mapping.
|
|
380
|
-
function parseYamlBlock(parser: YamlParser, indent: number): unknown {
|
|
381
|
-
const line = parser.lines[parser.index];
|
|
382
|
-
if (!line || line.indent < indent) {
|
|
383
|
-
return {};
|
|
384
|
-
}
|
|
385
|
-
return isYamlArrayLine(line) ? parseYamlArray(parser, line.indent) : parseYamlObject(parser, line.indent);
|
|
386
|
-
}
|
|
387
|
-
|
|
388
|
-
// Walks mapping entries at one indent level, stopping when the next line dedents or switches to
|
|
389
|
-
// sequence form. Throws on unexpected indent so a missed key isn't silently swallowed.
|
|
390
|
-
function parseYamlObject(parser: YamlParser, indent: number): Record<string, unknown> {
|
|
391
|
-
const result: Record<string, unknown> = {};
|
|
392
|
-
while (parser.index < parser.lines.length) {
|
|
393
|
-
const line = parser.lines[parser.index];
|
|
394
|
-
if (!line || line.indent < indent || isYamlArrayLine(line)) {
|
|
395
|
-
break;
|
|
396
|
-
}
|
|
397
|
-
assertYamlIndent(line, indent);
|
|
398
|
-
addYamlObjectEntry(parser, indent, line, result);
|
|
399
|
-
}
|
|
400
|
-
return result;
|
|
401
|
-
}
|
|
402
|
-
|
|
403
|
-
// Inline scalar after the colon → leaf value; bare key → recurse into nested block. Keys are
|
|
404
|
-
// unquoted so `"foo"` and `foo` produce the same result key.
|
|
405
|
-
function addYamlObjectEntry(parser: YamlParser, indent: number, line: YamlLine, result: Record<string, unknown>): void {
|
|
406
|
-
const [rawKey, rawValue] = yamlKeyValuePair(line.content);
|
|
407
|
-
const scalarText = rawValue.trim();
|
|
408
|
-
parser.index += 1;
|
|
409
|
-
result[unquoteYaml(rawKey.trim())] = scalarText.length > 0 ? parseYamlScalar(scalarText) : parseNestedYamlValue(parser, indent, {});
|
|
410
|
-
}
|
|
411
|
-
|
|
412
|
-
// Block-style YAML sequence. Inline `[...]` arrays are handled by `parseYamlCollectionScalar`;
|
|
413
|
-
// this walks the `- item` lines and recurses into nested values for empty `-` openers.
|
|
414
|
-
function parseYamlArray(parser: YamlParser, indent: number): unknown[] {
|
|
415
|
-
const result: unknown[] = [];
|
|
416
|
-
while (parser.index < parser.lines.length) {
|
|
417
|
-
const line = parser.lines[parser.index];
|
|
418
|
-
if (!line || line.indent < indent || !isYamlArrayLine(line)) {
|
|
419
|
-
break;
|
|
420
|
-
}
|
|
421
|
-
assertYamlIndent(line, indent);
|
|
422
|
-
result.push(parseYamlArrayItem(parser, indent, line));
|
|
423
|
-
}
|
|
424
|
-
return result;
|
|
425
|
-
}
|
|
426
|
-
|
|
427
|
-
// Three branches: bare `-` (recurse for nested), `- key: value` (mapping item), `- scalar`.
|
|
428
|
-
// Bare-dash items return null when the nested block is empty so the array entry isn't elided.
|
|
429
|
-
function parseYamlArrayItem(parser: YamlParser, indent: number, line: YamlLine): unknown {
|
|
430
|
-
const itemText = line.content === "-" ? "" : line.content.slice(2).trim();
|
|
431
|
-
parser.index += 1;
|
|
432
|
-
if (itemText.length === 0) {
|
|
433
|
-
return parseNestedYamlValue(parser, indent, null);
|
|
434
|
-
}
|
|
435
|
-
|
|
436
|
-
const pair = splitYamlKeyValue(itemText);
|
|
437
|
-
return pair ? parseYamlArrayMappingItem(parser, indent, pair) : parseYamlScalar(itemText);
|
|
438
|
-
}
|
|
439
|
-
|
|
440
|
-
// `- key: value` form: the first key is on the dash line, subsequent keys live as a nested object.
|
|
441
|
-
// Mirrors the inline-vs-nested split of `addYamlObjectEntry`.
|
|
442
|
-
function parseYamlArrayMappingItem(parser: YamlParser, indent: number, pair: [string, string]): Record<string, unknown> {
|
|
443
|
-
const [rawKey, rawValue] = pair;
|
|
444
|
-
const scalarText = rawValue.trim();
|
|
445
|
-
return {
|
|
446
|
-
[unquoteYaml(rawKey.trim())]: scalarText.length > 0 ? parseYamlScalar(scalarText) : parseNestedYamlValue(parser, indent, {}),
|
|
447
|
-
};
|
|
448
|
-
}
|
|
449
|
-
|
|
450
|
-
// Returns the nested block if the next line indents further, otherwise the caller's `fallback`.
|
|
451
|
-
// `fallback` is `{}` for mappings (empty value → empty object) and `null` for sequences.
|
|
452
|
-
function parseNestedYamlValue(parser: YamlParser, indent: number, fallback: unknown): unknown {
|
|
453
|
-
const nestedIndent = parser.lines[parser.index]?.indent;
|
|
454
|
-
return nestedIndent !== undefined && nestedIndent > indent ? parseYamlBlock(parser, nestedIndent) : fallback;
|
|
455
|
-
}
|
|
456
|
-
|
|
457
|
-
/*
|
|
458
|
-
* Throws when a mapping line has no `:` separator - the parser cannot recover, and a silent skip
|
|
459
|
-
* would hide a real config typo from the user.
|
|
460
|
-
*/
|
|
461
|
-
function yamlKeyValuePair(content: string): [string, string] {
|
|
462
|
-
const pair = splitYamlKeyValue(content);
|
|
463
|
-
if (!pair) {
|
|
464
|
-
throw new ConfigLoadError(`Invalid YAML mapping line: "${content}".`, SUGGEST_INIT_FORCE);
|
|
465
|
-
}
|
|
466
|
-
return pair;
|
|
467
|
-
}
|
|
468
|
-
|
|
469
|
-
// `- ` or bare `-` only - two-dash openers and ambiguous variants are not sequence entries.
|
|
470
|
-
function isYamlArrayLine(line: YamlLine): boolean {
|
|
471
|
-
return line.content.startsWith("- ") || line.content === "-";
|
|
472
|
-
}
|
|
473
|
-
|
|
474
|
-
/*
|
|
475
|
-
* Throws when a line is indented more than expected at this scope. Without this guard, a stray
|
|
476
|
-
* indent would silently produce a sub-mapping and the user's config would mean something different.
|
|
477
|
-
*/
|
|
478
|
-
function assertYamlIndent(line: YamlLine, indent: number): void {
|
|
479
|
-
if (line.indent > indent) {
|
|
480
|
-
throw new ConfigLoadError(`Invalid YAML indentation near "${line.content}".`, SUGGEST_INIT_FORCE);
|
|
481
|
-
}
|
|
482
|
-
}
|
|
483
|
-
|
|
484
|
-
/*
|
|
485
|
-
* Pre-pass that drops blank/comment lines and rejects tab-indented input. Tabs are forbidden
|
|
486
|
-
* because mixing them with spaces is the canonical YAML footgun, so the parser throws rather than
|
|
487
|
-
* guess at the user's intent.
|
|
488
|
-
*/
|
|
489
|
-
function yamlLines(source: string): YamlLine[] {
|
|
490
|
-
const lines: YamlLine[] = [];
|
|
491
|
-
for (const rawLine of source.replace(/\r\n/g, "\n").split("\n")) {
|
|
492
|
-
const withoutComment = stripYamlComment(rawLine).trimEnd();
|
|
493
|
-
if (withoutComment.trim().length === 0) {
|
|
494
|
-
continue;
|
|
495
|
-
}
|
|
496
|
-
const indentText = withoutComment.match(/^\s*/)?.[0] ?? "";
|
|
497
|
-
if (indentText.includes("\t")) {
|
|
498
|
-
throw new ConfigLoadError("Tabs are not supported in gruff YAML config indentation.", SUGGEST_INIT_FORCE);
|
|
499
|
-
}
|
|
500
|
-
lines.push({ indent: indentText.length, content: withoutComment.trimStart() });
|
|
501
|
-
}
|
|
502
|
-
return lines;
|
|
503
|
-
}
|
|
504
|
-
|
|
505
|
-
// Drops `# comment` text but only when the `#` is not inside quotes - `foo: "a # b"` keeps the
|
|
506
|
-
// comment-like substring as part of the string value, matching YAML semantics.
|
|
507
|
-
function stripYamlComment(line: string): string {
|
|
508
|
-
const commentIndex = firstUnquotedIndex(line, (character, index) => character === "#" && (index === 0 || /\s/.test(line[index - 1] ?? "")));
|
|
509
|
-
return commentIndex === undefined ? line : line.slice(0, commentIndex);
|
|
510
|
-
}
|
|
511
|
-
|
|
512
|
-
// Finds the first `:<space>` outside quotes. Required because a quoted value can legitimately
|
|
513
|
-
// contain `:` (`url: "https://..."`) and the parser must not split at the first occurrence.
|
|
514
|
-
function splitYamlKeyValue(mappingText: string): [string, string] | undefined {
|
|
515
|
-
const separatorIndex = firstUnquotedIndex(mappingText, (character, index) => {
|
|
516
|
-
const next = mappingText[index + 1];
|
|
517
|
-
return character === ":" && (!next || /\s/.test(next));
|
|
518
|
-
});
|
|
519
|
-
return separatorIndex === undefined ? undefined : [mappingText.slice(0, separatorIndex), mappingText.slice(separatorIndex + 1)];
|
|
520
|
-
}
|
|
521
|
-
|
|
522
|
-
// Tries each scalar parser in order; the first to claim a match wins. Bare strings are the
|
|
523
|
-
// fallback so callers never end up with `undefined` for a non-empty scalar.
|
|
524
|
-
function parseYamlScalar(scalarText: string): unknown {
|
|
525
|
-
const trimmed = scalarText.trim();
|
|
526
|
-
for (const parser of [parseYamlCollectionScalar, parseYamlQuotedScalar, parseYamlKeywordScalar, parseYamlNumberScalar]) {
|
|
527
|
-
const parsedScalar = parser(trimmed);
|
|
528
|
-
if (parsedScalar.isMatched) {
|
|
529
|
-
return parsedScalar.value;
|
|
530
|
-
}
|
|
531
|
-
}
|
|
532
|
-
return trimmed;
|
|
533
|
-
}
|
|
534
|
-
|
|
535
|
-
// Parses YAML collection scalar from source text.
|
|
536
|
-
function parseYamlCollectionScalar(trimmed: string): ParsedYamlScalar {
|
|
537
|
-
if (trimmed === "[]") {
|
|
538
|
-
return matchedYamlScalar([]);
|
|
539
|
-
}
|
|
540
|
-
if (trimmed === "{}") {
|
|
541
|
-
return matchedYamlScalar({});
|
|
542
|
-
}
|
|
543
|
-
if (trimmed.startsWith("[") && trimmed.endsWith("]")) {
|
|
544
|
-
return matchedYamlScalar(parseYamlInlineArray(trimmed));
|
|
545
|
-
}
|
|
546
|
-
return UNMATCHED_YAML_SCALAR;
|
|
547
|
-
}
|
|
548
|
-
|
|
549
|
-
// `"..."` or `'...'` wrapped. Calls `unquoteYaml` so the resulting value matches what a real YAML
|
|
550
|
-
// engine would produce; matched-state flag separates "empty quoted string" from "not a quoted scalar".
|
|
551
|
-
function parseYamlQuotedScalar(trimmed: string): ParsedYamlScalar {
|
|
552
|
-
if (isQuotedYaml(trimmed)) {
|
|
553
|
-
return matchedYamlScalar(unquoteYaml(trimmed));
|
|
554
|
-
}
|
|
555
|
-
return UNMATCHED_YAML_SCALAR;
|
|
556
|
-
}
|
|
557
|
-
|
|
558
|
-
// Recognises `true`/`false`/`null`/`~` (case-insensitive). The keyword table is shared so the
|
|
559
|
-
// parser produces consistent JS values (`null` instead of the string "null").
|
|
560
|
-
function parseYamlKeywordScalar(trimmed: string): ParsedYamlScalar {
|
|
561
|
-
const normalized = trimmed.toLowerCase();
|
|
562
|
-
if (YAML_KEYWORD_SCALARS.has(normalized)) {
|
|
563
|
-
return matchedYamlScalar(YAML_KEYWORD_SCALARS.get(normalized) ?? null);
|
|
564
|
-
}
|
|
565
|
-
return UNMATCHED_YAML_SCALAR;
|
|
566
|
-
}
|
|
567
|
-
|
|
568
|
-
// Strict numeric pattern - no octals, no special floats. Numbers that don't fit fall through to
|
|
569
|
-
// bare-string handling, so `0xFF` or `1e10` stay as strings rather than producing surprising values.
|
|
570
|
-
function parseYamlNumberScalar(trimmed: string): ParsedYamlScalar {
|
|
571
|
-
if (YAML_NUMBER_SCALAR.test(trimmed)) {
|
|
572
|
-
return matchedYamlScalar(Number(trimmed));
|
|
573
|
-
}
|
|
574
|
-
return UNMATCHED_YAML_SCALAR;
|
|
575
|
-
}
|
|
576
|
-
|
|
577
|
-
// Returns a "matched" result with the parsed value, distinguishing real matches from the shared
|
|
578
|
-
// `UNMATCHED_YAML_SCALAR` sentinel used by every parser that failed.
|
|
579
|
-
function matchedYamlScalar(scalarValue: unknown): ParsedYamlScalar {
|
|
580
|
-
return { isMatched: true, value: scalarValue };
|
|
581
|
-
}
|
|
582
|
-
|
|
583
|
-
// Inline `[a, b, c]` arrays. Items are split on unquoted commas and each item recurses through
|
|
584
|
-
// `parseYamlScalar` so nested types resolve correctly.
|
|
585
|
-
function parseYamlInlineArray(arrayText: string): unknown[] {
|
|
586
|
-
const inner = arrayText.slice(1, -1).trim();
|
|
587
|
-
if (inner.length === 0) {
|
|
588
|
-
return [];
|
|
589
|
-
}
|
|
590
|
-
return splitYamlInlineItems(inner).map((item) => parseYamlScalar(item));
|
|
591
|
-
}
|
|
592
|
-
|
|
593
|
-
// Quote-aware split on commas. Treating a quoted comma as a separator would corrupt entries like
|
|
594
|
-
// `["a, b", "c"]` - same reason `splitYamlKeyValue` is also quote-aware.
|
|
595
|
-
function splitYamlInlineItems(itemsText: string): string[] {
|
|
596
|
-
const items: string[] = [];
|
|
597
|
-
let start = 0;
|
|
598
|
-
for (const index of unquotedIndexes(itemsText, ",")) {
|
|
599
|
-
items.push(itemsText.slice(start, index).trim());
|
|
600
|
-
start = index + 1;
|
|
601
|
-
}
|
|
602
|
-
items.push(itemsText.slice(start).trim());
|
|
603
|
-
return items;
|
|
604
|
-
}
|
|
605
|
-
|
|
606
|
-
// Lexer state for the YAML quote walkers. `isEscaped` only matters inside `"..."` quotes because
|
|
607
|
-
// single-quoted YAML strings use `''` doubling rather than backslash escapes.
|
|
608
|
-
interface QuoteScanState {
|
|
609
|
-
quote: string | undefined;
|
|
610
|
-
isEscaped: boolean;
|
|
611
|
-
}
|
|
612
|
-
|
|
613
|
-
// Walks `value` calling `predicate` only at quote-free positions. Used by both the comment
|
|
614
|
-
// stripper and the colon splitter to keep quoted text inert.
|
|
615
|
-
function firstUnquotedIndex(sourceText: string, predicate: (character: string, index: number) => boolean): number | undefined {
|
|
616
|
-
for (const index of unquotedIndexes(sourceText)) {
|
|
617
|
-
const character = sourceText[index] ?? "";
|
|
618
|
-
if (predicate(character, index)) {
|
|
619
|
-
return index;
|
|
620
|
-
}
|
|
621
|
-
}
|
|
622
|
-
return undefined;
|
|
623
|
-
}
|
|
624
|
-
|
|
625
|
-
// All quote-free positions in `value`, optionally filtered by a specific character. The two-mode
|
|
626
|
-
// shape lets the same lexer feed both `firstUnquotedIndex` and the inline-array splitter.
|
|
627
|
-
function unquotedIndexes(sourceText: string, expectedCharacter?: string): number[] {
|
|
628
|
-
const indexes: number[] = [];
|
|
629
|
-
const state: QuoteScanState = { quote: undefined, isEscaped: false };
|
|
630
|
-
for (let index = 0; index < sourceText.length; index += 1) {
|
|
631
|
-
const character = sourceText[index] ?? "";
|
|
632
|
-
if (consumeQuotedCharacter(character, state)) {
|
|
633
|
-
continue;
|
|
634
|
-
}
|
|
635
|
-
if (isYamlQuote(character)) {
|
|
636
|
-
state.quote = character;
|
|
637
|
-
continue;
|
|
638
|
-
}
|
|
639
|
-
if (!expectedCharacter || character === expectedCharacter) {
|
|
640
|
-
indexes.push(index);
|
|
641
|
-
}
|
|
642
|
-
}
|
|
643
|
-
return indexes;
|
|
644
|
-
}
|
|
645
|
-
|
|
646
|
-
// Returns true and mutates `state` when the character was inside a quoted region. The escape
|
|
647
|
-
// handling is double-quote-only because YAML single-quote strings have no `\` escapes.
|
|
648
|
-
function consumeQuotedCharacter(character: string, state: QuoteScanState): boolean {
|
|
649
|
-
if (!state.quote) {
|
|
650
|
-
return false;
|
|
651
|
-
}
|
|
652
|
-
if (state.quote === "\"" && character === "\\" && !state.isEscaped) {
|
|
653
|
-
state.isEscaped = true;
|
|
654
|
-
return true;
|
|
655
|
-
}
|
|
656
|
-
if (character === state.quote && !state.isEscaped) {
|
|
657
|
-
state.quote = undefined;
|
|
658
|
-
}
|
|
659
|
-
state.isEscaped = false;
|
|
660
|
-
return true;
|
|
661
|
-
}
|
|
662
|
-
|
|
663
|
-
// Single and double quotes only - YAML allows backticks elsewhere but they're not part of the
|
|
664
|
-
// supported subset here, and the parser would have to reject them anyway.
|
|
665
|
-
function isYamlQuote(character: string): boolean {
|
|
666
|
-
return character === "\"" || character === "'";
|
|
667
|
-
}
|
|
668
|
-
|
|
669
|
-
// Both endpoints must use the same quote character; mismatched openers/closers are treated as
|
|
670
|
-
// plain text rather than a parse error so a single stray quote in user prose doesn't fail the config.
|
|
671
|
-
function isQuotedYaml(scalarText: string): boolean {
|
|
672
|
-
return scalarText.length >= 2 && ((scalarText.startsWith("\"") && scalarText.endsWith("\"")) || (scalarText.startsWith("'") && scalarText.endsWith("'")));
|
|
673
|
-
}
|
|
674
|
-
|
|
675
|
-
// Removes quotes and decodes the supported escapes: `''` doubling for single quotes, and `\n`,
|
|
676
|
-
// `\r`, `\t`, `\"`, `\\` for double quotes. Anything else passes through unchanged so the parser
|
|
677
|
-
// reports the user's exact intent rather than mangling unknown escape sequences.
|
|
678
|
-
function unquoteYaml(scalarText: string): string {
|
|
679
|
-
if (!isQuotedYaml(scalarText)) {
|
|
680
|
-
return scalarText;
|
|
681
|
-
}
|
|
682
|
-
const quote = scalarText[0];
|
|
683
|
-
const body = scalarText.slice(1, -1);
|
|
684
|
-
if (quote === "'") {
|
|
685
|
-
return body.replace(/''/g, "'");
|
|
686
|
-
}
|
|
687
|
-
return body.replace(/\\(["\\nrt])/g, (_match, escaped: string) => {
|
|
688
|
-
if (escaped === "n") {
|
|
689
|
-
return "\n";
|
|
690
|
-
}
|
|
691
|
-
if (escaped === "r") {
|
|
692
|
-
return "\r";
|
|
693
|
-
}
|
|
694
|
-
if (escaped === "t") {
|
|
695
|
-
return "\t";
|
|
696
|
-
}
|
|
697
|
-
return escaped;
|
|
698
|
-
});
|
|
699
|
-
}
|
|
700
|
-
|
|
701
473
|
// Rules are enabled by default - the absence of a config entry means "use the descriptor default",
|
|
702
474
|
// which is the documented contract for how unset rules behave.
|
|
703
475
|
function ruleEnabled(config: Config, ruleId: string): boolean {
|
|
@@ -722,27 +494,10 @@ function optionNumber(config: Config, ruleId: string, name: string, defaultValue
|
|
|
722
494
|
return config.rules.get(ruleId)?.options.get(name) ?? defaultValue;
|
|
723
495
|
}
|
|
724
496
|
|
|
725
|
-
// Type narrowing for `Record<string, unknown>`. Returns undefined (not null) for non-objects so
|
|
726
|
-
// the caller can use the standard optional-chaining pattern through the rest of the config layer.
|
|
727
|
-
function objectValue(configValue: unknown): Record<string, unknown> | undefined {
|
|
728
|
-
return typeof configValue === "object" && configValue !== null && !Array.isArray(configValue) ? (configValue as Record<string, unknown>) : undefined;
|
|
729
|
-
}
|
|
730
|
-
|
|
731
|
-
// Returns the array or an empty array - never undefined - so callers can iterate without a guard.
|
|
732
|
-
function arrayValue(configValue: unknown): unknown[] {
|
|
733
|
-
return Array.isArray(configValue) ? configValue : [];
|
|
734
|
-
}
|
|
735
|
-
|
|
736
|
-
// String type narrowing. Exported so other modules can share a single string-test that matches
|
|
737
|
-
// the config-side semantics (rejects non-string truthy values like numbers).
|
|
738
|
-
function isString(configValue: unknown): configValue is string {
|
|
739
|
-
return typeof configValue === "string";
|
|
740
|
-
}
|
|
741
|
-
|
|
742
497
|
// Whitelist check used both by config validation (throws on bad values) and by `applyRuleSeverityConfig`.
|
|
743
498
|
// The set of accepted strings is the public severity vocabulary; adding entries is a schema change.
|
|
744
499
|
function isSeverity(configValue: unknown): configValue is Severity {
|
|
745
500
|
return configValue === "advisory" || configValue === "warning" || configValue === "error";
|
|
746
501
|
}
|
|
747
502
|
|
|
748
|
-
export { defaultConfigPath,
|
|
503
|
+
export { defaultConfigPath, loadConfig, minimumSeverityFor, optionNumber, resolveProfile, ruleEnabled, ruleSeverity, threshold };
|