@mizchi/vlmkit-core 0.9.1 → 0.11.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (57) hide show
  1. package/dist/apng.d.mts +42 -0
  2. package/dist/apng.mjs +199 -0
  3. package/dist/auth-state.d.mts +14 -3
  4. package/dist/auth-state.mjs +30 -6
  5. package/dist/bitmap-font.d.mts +48 -0
  6. package/dist/bitmap-font.mjs +945 -0
  7. package/dist/browser-launch.d.mts +65 -0
  8. package/dist/browser-launch.mjs +194 -0
  9. package/dist/cli-error.d.mts +73 -1
  10. package/dist/cli-error.mjs +164 -32
  11. package/dist/element-compare.mjs +8 -11
  12. package/dist/filmstrip.d.mts +121 -0
  13. package/dist/filmstrip.mjs +181 -0
  14. package/dist/gate-config.d.mts +107 -22
  15. package/dist/gate-config.mjs +138 -9
  16. package/dist/heatmap.d.mts +48 -4
  17. package/dist/heatmap.mjs +157 -12
  18. package/dist/index.d.mts +6 -4
  19. package/dist/index.mjs +4 -2
  20. package/dist/mask.d.mts +66 -2
  21. package/dist/mask.mjs +91 -4
  22. package/dist/page-load.d.mts +83 -0
  23. package/dist/page-load.mjs +116 -0
  24. package/dist/page-open.d.mts +123 -2
  25. package/dist/page-open.mjs +176 -6
  26. package/dist/plugin/args.d.mts +86 -0
  27. package/dist/plugin/args.mjs +162 -0
  28. package/dist/plugin/browser.d.mts +6 -0
  29. package/dist/plugin/browser.mjs +6 -0
  30. package/dist/plugin/cli-entry.d.mts +11 -0
  31. package/dist/plugin/cli-entry.mjs +69 -0
  32. package/dist/plugin/contract.d.mts +270 -0
  33. package/dist/plugin/contract.mjs +51 -0
  34. package/dist/plugin/index.d.mts +82 -0
  35. package/dist/plugin/index.mjs +81 -0
  36. package/dist/plugin/load.d.mts +36 -0
  37. package/dist/plugin/load.mjs +98 -0
  38. package/dist/plugin/registry.d.mts +60 -0
  39. package/dist/plugin/registry.mjs +160 -0
  40. package/dist/plugin/rule-tier.d.mts +65 -0
  41. package/dist/plugin/rule-tier.mjs +77 -0
  42. package/dist/plugin/rules.d.mts +112 -0
  43. package/dist/plugin/rules.mjs +188 -0
  44. package/dist/plugin/runner.d.mts +198 -0
  45. package/dist/plugin/runner.mjs +440 -0
  46. package/dist/png-utils.d.mts +31 -1
  47. package/dist/png-utils.mjs +24 -1
  48. package/dist/rect-overlap.d.mts +41 -0
  49. package/dist/rect-overlap.mjs +28 -0
  50. package/dist/run-ledger.d.mts +56 -2
  51. package/dist/run-ledger.mjs +102 -11
  52. package/dist/types.d.mts +60 -1
  53. package/dist/version.d.mts +20 -0
  54. package/dist/version.mjs +20 -0
  55. package/dist/webp.d.mts +31 -0
  56. package/dist/webp.mjs +105 -0
  57. package/package.json +17 -3
@@ -0,0 +1,60 @@
1
+ import { AnyGateDefinition, GateCategory, VlmkitPlugin } from "./contract.mjs";
2
+ import { RuleSettings } from "./rules.mjs";
3
+
4
+ //#region src/plugin/registry.d.ts
5
+ interface RegisteredGate {
6
+ gate: AnyGateDefinition;
7
+ /** Plugin that supplied it — named in conflict errors and `--plugins` listings. */
8
+ plugin: string;
9
+ }
10
+ interface GateResolution {
11
+ gate: AnyGateDefinition;
12
+ /** Argv remaining after the matched command tokens. */
13
+ rest: string[];
14
+ }
15
+ interface GateRegistry {
16
+ readonly plugins: readonly VlmkitPlugin[];
17
+ /** Every gate, in registration order. */
18
+ list(): readonly RegisteredGate[];
19
+ byId(id: string): AnyGateDefinition | undefined;
20
+ /** Exact command lookup: `"check integrity"` or `["check", "integrity"]`. */
21
+ byCommand(command: string | readonly string[]): AnyGateDefinition | undefined;
22
+ /**
23
+ * Longest-prefix match against argv, so `["check","copy","--manifest","x"]`
24
+ * resolves to `check copy` with the flags left in `rest`.
25
+ */
26
+ resolve(argv: readonly string[]): GateResolution | undefined;
27
+ /** Command tokens grouped by first token, for help output. */
28
+ groups(): ReadonlyMap<string, readonly RegisteredGate[]>;
29
+ /**
30
+ * Gates grouped by what KIND of question they answer, in adoption order,
31
+ * with uncategorized gates last under `other`.
32
+ *
33
+ * Separate from `groups()`, which groups by CLI verb. A reader choosing what
34
+ * to run wants the former; a reader typing a command wants the latter.
35
+ */
36
+ categories(): ReadonlyMap<GateCategory | "other", readonly RegisteredGate[]>;
37
+ /** Near-miss command strings for a "did you mean" line. */
38
+ suggest(command: string | readonly string[], limit?: number): string[];
39
+ }
40
+ declare function createGateRegistry(plugins: readonly VlmkitPlugin[]): GateRegistry;
41
+ /** Levenshtein, iterative single-row — only ever run on a failed lookup. */
42
+ declare function editDistance(a: string, b: string): number;
43
+ interface GateCommandProblem {
44
+ command: string;
45
+ message: string;
46
+ }
47
+ /**
48
+ * Validate the gate strings a config declares. Returns one problem per bad
49
+ * entry rather than throwing on the first, so a reviewer fixes the whole
50
+ * config in one pass.
51
+ */
52
+ declare function validateGateCommands(registry: GateRegistry, commands: readonly string[]): GateCommandProblem[];
53
+ /**
54
+ * Validate rule references. A bare `<ruleId>` key is only resolvable inside
55
+ * a gate-scoped block, so this checks the qualified forms and reports a bare
56
+ * key as needing a scope rather than guessing which gate it meant.
57
+ */
58
+ declare function validateRuleSettings(registry: GateRegistry, settings: RuleSettings, scope?: AnyGateDefinition): string[];
59
+ //#endregion
60
+ export { GateCommandProblem, GateRegistry, GateResolution, RegisteredGate, createGateRegistry, editDistance, validateGateCommands, validateRuleSettings };
@@ -0,0 +1,160 @@
1
+ import { GATE_CATEGORY_ORDER, gateCommandString } from "./contract.mjs";
2
+ import { validateGateDefinition } from "./rules.mjs";
3
+ //#region src/plugin/registry.ts
4
+ var Registry = class {
5
+ plugins;
6
+ gates = [];
7
+ byIdMap = /* @__PURE__ */ new Map();
8
+ byCommandMap = /* @__PURE__ */ new Map();
9
+ /** Longest command first, so `resolve` prefers `check a11y contrast` over `check a11y`. */
10
+ ordered = [];
11
+ constructor(plugins) {
12
+ this.plugins = plugins;
13
+ const problems = [];
14
+ for (const plugin of plugins) {
15
+ if (!plugin.name.trim()) problems.push("a plugin has no name");
16
+ for (const gate of plugin.gates) {
17
+ problems.push(...validateGateDefinition(gate).map((p) => `${plugin.name}: ${p}`));
18
+ const command = gateCommandString(gate);
19
+ const clashId = this.gates.find((g) => g.gate.id === gate.id);
20
+ if (clashId) {
21
+ problems.push(`gate id "${gate.id}" is registered by both ${clashId.plugin} and ${plugin.name} — ids address rule settings and ledger entries, so they must be unique`);
22
+ continue;
23
+ }
24
+ const clashCommand = this.gates.find((g) => gateCommandString(g.gate) === command);
25
+ if (clashCommand) {
26
+ problems.push(`command "${command}" is registered by both ${clashCommand.plugin} and ${plugin.name}`);
27
+ continue;
28
+ }
29
+ this.gates.push({
30
+ gate,
31
+ plugin: plugin.name
32
+ });
33
+ this.byIdMap.set(gate.id, gate);
34
+ this.byCommandMap.set(command, gate);
35
+ this.ordered.push({
36
+ tokens: gate.command,
37
+ gate
38
+ });
39
+ }
40
+ }
41
+ if (problems.length > 0) throw new Error(`Invalid gate plugin(s):\n${problems.map((p) => ` - ${p}`).join("\n")}`);
42
+ this.ordered.sort((a, b) => b.tokens.length - a.tokens.length);
43
+ }
44
+ list() {
45
+ return this.gates;
46
+ }
47
+ byId(id) {
48
+ return this.byIdMap.get(id);
49
+ }
50
+ byCommand(command) {
51
+ const key = typeof command === "string" ? command.trim().split(/\s+/).filter(Boolean).join(" ") : command.join(" ");
52
+ return this.byCommandMap.get(key);
53
+ }
54
+ resolve(argv) {
55
+ for (const { tokens, gate } of this.ordered) {
56
+ if (tokens.length > argv.length) continue;
57
+ if (tokens.every((token, i) => token === argv[i])) return {
58
+ gate,
59
+ rest: argv.slice(tokens.length)
60
+ };
61
+ }
62
+ }
63
+ groups() {
64
+ const out = /* @__PURE__ */ new Map();
65
+ for (const entry of this.gates) {
66
+ const group = entry.gate.command[0];
67
+ const bucket = out.get(group);
68
+ if (bucket) bucket.push(entry);
69
+ else out.set(group, [entry]);
70
+ }
71
+ return out;
72
+ }
73
+ categories() {
74
+ const out = /* @__PURE__ */ new Map();
75
+ for (const category of GATE_CATEGORY_ORDER) {
76
+ const members = this.gates.filter((entry) => entry.gate.category === category);
77
+ if (members.length > 0) out.set(category, members);
78
+ }
79
+ const uncategorized = this.gates.filter((entry) => entry.gate.category === void 0);
80
+ if (uncategorized.length > 0) out.set("other", uncategorized);
81
+ return out;
82
+ }
83
+ suggest(command, limit = 3) {
84
+ const query = (typeof command === "string" ? command.trim().split(/\s+/) : [...command]).filter((t) => Boolean(t) && !t.startsWith("-")).join(" ");
85
+ if (!query) return [];
86
+ return [...this.byCommandMap.keys()].map((candidate) => ({
87
+ candidate,
88
+ distance: editDistance(query, candidate)
89
+ })).filter(({ distance }) => distance <= 2).sort((a, b) => a.distance - b.distance || a.candidate.localeCompare(b.candidate)).slice(0, limit).map(({ candidate }) => candidate);
90
+ }
91
+ };
92
+ function createGateRegistry(plugins) {
93
+ return new Registry(plugins);
94
+ }
95
+ /** Levenshtein, iterative single-row — only ever run on a failed lookup. */
96
+ function editDistance(a, b) {
97
+ if (a === b) return 0;
98
+ let row = Array.from({ length: b.length + 1 }, (_, i) => i);
99
+ for (let i = 1; i <= a.length; i++) {
100
+ const next = [i];
101
+ for (let j = 1; j <= b.length; j++) next[j] = Math.min(row[j] + 1, next[j - 1] + 1, row[j - 1] + (a[i - 1] === b[j - 1] ? 0 : 1));
102
+ row = next;
103
+ }
104
+ return row[b.length];
105
+ }
106
+ /**
107
+ * Validate the gate strings a config declares. Returns one problem per bad
108
+ * entry rather than throwing on the first, so a reviewer fixes the whole
109
+ * config in one pass.
110
+ */
111
+ function validateGateCommands(registry, commands) {
112
+ const problems = [];
113
+ for (const command of commands) {
114
+ const tokens = command.trim().split(/\s+/).filter(Boolean);
115
+ if (tokens.length === 0) {
116
+ problems.push({
117
+ command,
118
+ message: "empty gate command"
119
+ });
120
+ continue;
121
+ }
122
+ if (registry.resolve(tokens)) continue;
123
+ const suggestions = registry.suggest(tokens);
124
+ problems.push({
125
+ command,
126
+ message: `unknown gate "${command}"` + (suggestions.length > 0 ? ` — did you mean ${suggestions.map((s) => `"${s}"`).join(", ")}?` : "")
127
+ });
128
+ }
129
+ return problems;
130
+ }
131
+ /**
132
+ * Validate rule references. A bare `<ruleId>` key is only resolvable inside
133
+ * a gate-scoped block, so this checks the qualified forms and reports a bare
134
+ * key as needing a scope rather than guessing which gate it meant.
135
+ */
136
+ function validateRuleSettings(registry, settings, scope) {
137
+ const problems = [];
138
+ for (const key of Object.keys(settings)) {
139
+ if (!key.includes("/")) {
140
+ if (scope) {
141
+ if (!scope.rules.some((r) => r.id === key)) problems.push(`"${key}" is not a rule of ${scope.id} (known: ${scope.rules.map((r) => r.id).join(", ")})`);
142
+ continue;
143
+ }
144
+ if (registry.byId(key)) continue;
145
+ problems.push(`"${key}" is neither a gate id nor a rule reference (<gateId>/<ruleId>)`);
146
+ continue;
147
+ }
148
+ const [gateId, ruleId] = [key.slice(0, key.indexOf("/")), key.slice(key.indexOf("/") + 1)];
149
+ const gate = registry.byId(gateId);
150
+ if (!gate) {
151
+ problems.push(`"${key}": unknown gate id "${gateId}"`);
152
+ continue;
153
+ }
154
+ if (ruleId === "*") continue;
155
+ if (!gate.rules.some((r) => r.id === ruleId)) problems.push(`"${key}": ${gateId} has no rule "${ruleId}" (known: ${gate.rules.map((r) => r.id).join(", ")})`);
156
+ }
157
+ return problems;
158
+ }
159
+ //#endregion
160
+ export { createGateRegistry, editDistance, validateGateCommands, validateRuleSettings };
@@ -0,0 +1,65 @@
1
+ import { FindingSeverity, RuleView } from "./contract.mjs";
2
+
3
+ //#region src/plugin/rule-tier.d.ts
4
+ /** A rule's effective setting: a severity, or `off` when the project turned it off. */
5
+ type RuleTier = "off" | FindingSeverity;
6
+ /**
7
+ * What to print a row as: the explicit project setting, or the severity the finding was
8
+ * emitted at.
9
+ *
10
+ * `emitted` — not the gate's declared table severity — because that is exactly what
11
+ * `applyRuleSettings` keeps: "only an explicit setting re-tunes. A gate is free to emit a
12
+ * severity that differs from its rule default, and that judgment must survive." Reading
13
+ * `rules.effective()` here instead looks equivalent and is not: it falls back to the table, so
14
+ * a finding emitted `warn` under a rule declared `suspect` renders as a failure over an exit 0.
15
+ * That is not hypothetical — `check integrity` printed `DEFECTS (1 fail, 0 warn)` directly
16
+ * above `exits 0 — 1 warn(s)` for a post-load `js-error`, which is the bug that produced this
17
+ * function.
18
+ *
19
+ * `rules` is optional in `format`, and undefined means nobody applied settings — a direct
20
+ * library call or a test. The emitted severity is the honest answer there too.
21
+ */
22
+ declare function ruleTier(rules: RuleView | undefined, ruleId: string, emitted: FindingSeverity): RuleTier;
23
+ /**
24
+ * A `RuleView` from a plain map of explicit settings — for tests, and for anything else that
25
+ * needs to render prose under a hypothetical configuration.
26
+ *
27
+ * It exists so a stub cannot get the `effective` / `setting` split wrong. Hand-written stubs
28
+ * supplied only `effective`, which is the lossy half: a formatter under such a stub reads a
29
+ * severity for EVERY rule and can never see "nobody set this one", so a test built on it
30
+ * cannot reproduce the case the real runner hits most often — no settings at all.
31
+ */
32
+ declare function ruleViewFrom(settings: Readonly<Record<string, RuleTier>>, fallback?: FindingSeverity): RuleView;
33
+ interface TieredRow<T> {
34
+ row: T;
35
+ tier: FindingSeverity;
36
+ }
37
+ interface TieredRows<T> {
38
+ /** Rows whose rule is still on, each carrying its effective severity. */
39
+ shown: TieredRow<T>[];
40
+ /** Rows dropped because their rule is `off`, keyed by rule id for the disclosure line. */
41
+ hiddenByRule: Map<string, number>;
42
+ }
43
+ /**
44
+ * Split rows into "still worth printing" and "turned off", by rule id.
45
+ *
46
+ * The hidden rows are returned counted rather than discarded because a formatter that
47
+ * silently prints fewer lines is a report that quietly measures less than it did yesterday.
48
+ * The runner already prints `N finding(s) suppressed by rule settings`; a migrated formatter
49
+ * uses this to keep its own body and counts consistent with that line instead of contradicting
50
+ * it.
51
+ */
52
+ declare function applyRuleTiers<T>(rows: readonly T[], ruleOf: (row: T) => {
53
+ rule: string;
54
+ emitted: FindingSeverity;
55
+ }, rules?: RuleView): TieredRows<T>;
56
+ /**
57
+ * One line naming what the settings removed, or `undefined` when nothing was.
58
+ *
59
+ * Deliberately not styled with colour codes: the callers are eight formatters with their own
60
+ * palettes, and they wrap this in their own `DIM`. Deliberately not silent when the count is
61
+ * zero either — it returns `undefined` so a formatter cannot print an empty bullet.
62
+ */
63
+ declare function hiddenByRuleNote(hiddenByRule: Map<string, number>): string | undefined;
64
+ //#endregion
65
+ export { RuleTier, TieredRow, TieredRows, applyRuleTiers, hiddenByRuleNote, ruleTier, ruleViewFrom };
@@ -0,0 +1,77 @@
1
+ //#region src/plugin/rule-tier.ts
2
+ /**
3
+ * What to print a row as: the explicit project setting, or the severity the finding was
4
+ * emitted at.
5
+ *
6
+ * `emitted` — not the gate's declared table severity — because that is exactly what
7
+ * `applyRuleSettings` keeps: "only an explicit setting re-tunes. A gate is free to emit a
8
+ * severity that differs from its rule default, and that judgment must survive." Reading
9
+ * `rules.effective()` here instead looks equivalent and is not: it falls back to the table, so
10
+ * a finding emitted `warn` under a rule declared `suspect` renders as a failure over an exit 0.
11
+ * That is not hypothetical — `check integrity` printed `DEFECTS (1 fail, 0 warn)` directly
12
+ * above `exits 0 — 1 warn(s)` for a post-load `js-error`, which is the bug that produced this
13
+ * function.
14
+ *
15
+ * `rules` is optional in `format`, and undefined means nobody applied settings — a direct
16
+ * library call or a test. The emitted severity is the honest answer there too.
17
+ */
18
+ function ruleTier(rules, ruleId, emitted) {
19
+ return rules?.setting(ruleId) ?? emitted;
20
+ }
21
+ /**
22
+ * A `RuleView` from a plain map of explicit settings — for tests, and for anything else that
23
+ * needs to render prose under a hypothetical configuration.
24
+ *
25
+ * It exists so a stub cannot get the `effective` / `setting` split wrong. Hand-written stubs
26
+ * supplied only `effective`, which is the lossy half: a formatter under such a stub reads a
27
+ * severity for EVERY rule and can never see "nobody set this one", so a test built on it
28
+ * cannot reproduce the case the real runner hits most often — no settings at all.
29
+ */
30
+ function ruleViewFrom(settings, fallback = "warn") {
31
+ return {
32
+ setting: (ruleId) => settings[ruleId],
33
+ effective: (ruleId) => settings[ruleId] ?? fallback
34
+ };
35
+ }
36
+ /**
37
+ * Split rows into "still worth printing" and "turned off", by rule id.
38
+ *
39
+ * The hidden rows are returned counted rather than discarded because a formatter that
40
+ * silently prints fewer lines is a report that quietly measures less than it did yesterday.
41
+ * The runner already prints `N finding(s) suppressed by rule settings`; a migrated formatter
42
+ * uses this to keep its own body and counts consistent with that line instead of contradicting
43
+ * it.
44
+ */
45
+ function applyRuleTiers(rows, ruleOf, rules) {
46
+ const shown = [];
47
+ const hiddenByRule = /* @__PURE__ */ new Map();
48
+ for (const row of rows) {
49
+ const { rule, emitted } = ruleOf(row);
50
+ const tier = ruleTier(rules, rule, emitted);
51
+ if (tier === "off") {
52
+ hiddenByRule.set(rule, (hiddenByRule.get(rule) ?? 0) + 1);
53
+ continue;
54
+ }
55
+ shown.push({
56
+ row,
57
+ tier
58
+ });
59
+ }
60
+ return {
61
+ shown,
62
+ hiddenByRule
63
+ };
64
+ }
65
+ /**
66
+ * One line naming what the settings removed, or `undefined` when nothing was.
67
+ *
68
+ * Deliberately not styled with colour codes: the callers are eight formatters with their own
69
+ * palettes, and they wrap this in their own `DIM`. Deliberately not silent when the count is
70
+ * zero either — it returns `undefined` so a formatter cannot print an empty bullet.
71
+ */
72
+ function hiddenByRuleNote(hiddenByRule) {
73
+ if (hiddenByRule.size === 0) return void 0;
74
+ return `${[...hiddenByRule.values()].reduce((a, b) => a + b, 0)} finding(s) not shown — rule turned off (${[...hiddenByRule].map(([rule, n]) => `${rule} x${n}`).join(", ")})`;
75
+ }
76
+ //#endregion
77
+ export { applyRuleTiers, hiddenByRuleNote, ruleTier, ruleViewFrom };
@@ -0,0 +1,112 @@
1
+ import { AnyGateDefinition, Finding, FindingSeverity } from "./contract.mjs";
2
+
3
+ //#region src/plugin/rules.d.ts
4
+ /** `"off"` drops the finding; a severity re-tunes it (usually `suspect` → `warn`). */
5
+ type RuleSetting = "off" | FindingSeverity;
6
+ declare const RULE_SETTINGS: readonly RuleSetting[];
7
+ /**
8
+ * Keys are `<gateId>/<ruleId>`, `<gateId>` (every rule of that gate), or a
9
+ * bare `<ruleId>` when the settings block is already scoped to one gate.
10
+ */
11
+ type RuleSettings = Readonly<Record<string, RuleSetting>>;
12
+ /**
13
+ * The long form of a rule setting: the setting plus why it is there.
14
+ *
15
+ * `suppressions` has carried `reason` / `owner` / `expires` from the start, and
16
+ * an expired one stops being applied. `rules` had none of that, which v6's
17
+ * adopting agent named as the sharpest edge in the config:
18
+ *
19
+ * "`suppressions` have `reason` / `owner` / `expires` and an expired one
20
+ * re-fails the build. `rules` has none of that. […] So the only mechanism for
21
+ * 'the tool is wrong about this rule' is the one mechanism with no audit
22
+ * trail and no expiry."
23
+ *
24
+ * A `//`-prefixed comment key was the first answer and is not enough: a comment
25
+ * cannot expire, and nothing enumerates it. This form goes through the same
26
+ * inventory and the same expiry rule as a suppression.
27
+ *
28
+ * The short form (`"rule": "off"`) stays valid — `--rule` on the command line
29
+ * cannot carry a reason, so requiring one everywhere would make the config
30
+ * unable to express what the CLI does.
31
+ */
32
+ interface RuleSettingEntry {
33
+ setting: RuleSetting;
34
+ /** Why the tool is wrong here. Required in this form — that is the point of it. */
35
+ reason: string;
36
+ /** Who signed off. Reported, so an unowned entry is visible. */
37
+ owner?: string;
38
+ /** `YYYY-MM-DD`. Past it, the setting is dropped and the rule bites again. */
39
+ expires?: string;
40
+ }
41
+ type RuleSettingValue = RuleSetting | RuleSettingEntry;
42
+ /** Rule settings with their annotations kept, for the inventory and expiry. */
43
+ interface AnnotatedRuleSettings {
44
+ settings: RuleSettings;
45
+ /** Keyed by rule reference; only the entries written in the long form. */
46
+ annotations: Readonly<Record<string, RuleSettingEntry>>;
47
+ }
48
+ interface RuleDecision {
49
+ ruleId: string;
50
+ /** Effective severity, or `"off"`. */
51
+ effective: RuleSetting;
52
+ /** The gate's declared default, for reporting what changed. */
53
+ declared: FindingSeverity;
54
+ /** The settings key that decided this, when a setting applied. */
55
+ via?: string;
56
+ }
57
+ interface ResolvedRules {
58
+ gateId: string;
59
+ decisions: ReadonlyMap<string, RuleDecision>;
60
+ /** Settings keys that matched no rule of this gate — typos, or stale entries. */
61
+ unmatched: readonly string[];
62
+ }
63
+ interface SuppressedFinding {
64
+ finding: Finding;
65
+ /** Settings key that silenced it. */
66
+ via: string;
67
+ }
68
+ interface RetunedFinding {
69
+ finding: Finding;
70
+ from: FindingSeverity;
71
+ to: FindingSeverity;
72
+ via: string;
73
+ }
74
+ interface AppliedRules {
75
+ /** Findings that survived, with severities re-tuned in place. */
76
+ findings: readonly Finding[];
77
+ suppressed: readonly SuppressedFinding[];
78
+ retuned: readonly RetunedFinding[];
79
+ /**
80
+ * Rule ids a gate emitted that are absent from its own rule table. A gate
81
+ * bug, not a user error: an undeclared rule cannot be documented or
82
+ * configured, which is the drift this whole layer exists to prevent.
83
+ */
84
+ undeclared: readonly string[];
85
+ }
86
+ /**
87
+ * Parse and validate a settings object, keeping any annotations.
88
+ *
89
+ * Errors name the JSON path, matching `parseGateConfig`'s convention so a bad
90
+ * rules block reads like any other config defect.
91
+ */
92
+ declare function parseAnnotatedRuleSettings(raw: unknown, path: string): AnnotatedRuleSettings;
93
+ /** The settings alone, for the many callers that never needed the annotations. */
94
+ declare function parseRuleSettings(raw: unknown, path: string): RuleSettings;
95
+ declare function resolveRules(gate: AnyGateDefinition, settings?: RuleSettings): ResolvedRules;
96
+ /** Apply resolved settings to a gate's findings. */
97
+ declare function applyRuleSettings(gate: AnyGateDefinition, findings: readonly Finding[], settings?: RuleSettings): AppliedRules;
98
+ interface FindingCounts {
99
+ suspect: number;
100
+ warn: number;
101
+ info: number;
102
+ }
103
+ declare function countFindings(findings: readonly Finding[]): FindingCounts;
104
+ /**
105
+ * Validate a definition before it is registered. Cheap invariants, but each
106
+ * one is a defect that used to be discoverable only by running the gate:
107
+ * duplicate rule ids make a setting ambiguous, a non-slug id breaks config
108
+ * keys, and an empty command cannot be dispatched.
109
+ */
110
+ declare function validateGateDefinition(gate: AnyGateDefinition): string[];
111
+ //#endregion
112
+ export { AnnotatedRuleSettings, AppliedRules, FindingCounts, RULE_SETTINGS, ResolvedRules, RetunedFinding, RuleDecision, RuleSetting, RuleSettingEntry, RuleSettingValue, RuleSettings, SuppressedFinding, applyRuleSettings, countFindings, parseAnnotatedRuleSettings, parseRuleSettings, resolveRules, validateGateDefinition };
@@ -0,0 +1,188 @@
1
+ import { UsageError } from "../cli-error.mjs";
2
+ import { FINDING_SEVERITIES, ruleRef } from "./contract.mjs";
3
+ //#region src/plugin/rules.ts
4
+ /**
5
+ * Rule settings — the eslint-shaped layer that lets a project re-tune or
6
+ * switch off one rule instead of one whole gate.
7
+ *
8
+ * `vlmkit.gates.json` could previously only silence at gate granularity:
9
+ * drop `check integrity` from a page's list, or append a flag the gate
10
+ * happened to implement (`--allow-invisible`, `--allow`). A project that
11
+ * accepts one intentional `text-collision` pattern on one page had to
12
+ * choose between an ad-hoc per-gate flag, if the gate author had thought to
13
+ * add one, and turning the entire eighteen-rule gate off. Rule settings
14
+ * make the narrow choice available for every gate uniformly, and — because
15
+ * the rule table is declared — a typo is a config error rather than a
16
+ * silently ineffective line.
17
+ *
18
+ * The two decisions inherited from `gate-config.ts` still hold: a
19
+ * suppression must be enumerable, and a silenced finding is *reported as
20
+ * silenced* rather than dropped. `applyRuleSettings` returns what it
21
+ * suppressed and what it re-tuned, so the runner can print both.
22
+ */
23
+ const RULE_SETTINGS = ["off", ...FINDING_SEVERITIES];
24
+ function isRuleSetting(value) {
25
+ return typeof value === "string" && RULE_SETTINGS.includes(value);
26
+ }
27
+ /**
28
+ * Parse and validate a settings object, keeping any annotations.
29
+ *
30
+ * Errors name the JSON path, matching `parseGateConfig`'s convention so a bad
31
+ * rules block reads like any other config defect.
32
+ */
33
+ function parseAnnotatedRuleSettings(raw, path) {
34
+ if (typeof raw !== "object" || raw === null || Array.isArray(raw)) throw new UsageError(`${path}: must be an object mapping rule references to settings`);
35
+ const settings = {};
36
+ const annotations = {};
37
+ for (const [rawKey, value] of Object.entries(raw)) {
38
+ const key = rawKey.trim();
39
+ if (!key) throw new UsageError(`${path}: rule reference must be a non-empty string`);
40
+ if (key.startsWith("//")) continue;
41
+ if (isRuleSetting(value)) {
42
+ settings[key] = value;
43
+ continue;
44
+ }
45
+ if (typeof value !== "object" || value === null || Array.isArray(value)) throw new UsageError(`${path}["${key}"]: must be one of ${RULE_SETTINGS.join(", ")}, or { "setting": ..., "reason": ... }, got ${JSON.stringify(value)}`);
46
+ const entry = value;
47
+ if (!isRuleSetting(entry.setting)) throw new UsageError(`${path}["${key}"].setting: must be one of ${RULE_SETTINGS.join(", ")}, got ${JSON.stringify(entry.setting)}`);
48
+ if (typeof entry.reason !== "string" || !entry.reason.trim()) throw new UsageError(`${path}["${key}"].reason: required — say why the tool is wrong about this rule. Use the short form ("${key}": "${entry.setting}") only when there is nothing to record.`);
49
+ if (entry.owner !== void 0 && typeof entry.owner !== "string") throw new UsageError(`${path}["${key}"].owner: must be a string`);
50
+ if (entry.expires !== void 0) {
51
+ if (typeof entry.expires !== "string" || !/^\d{4}-\d{2}-\d{2}$/.test(entry.expires)) throw new UsageError(`${path}["${key}"].expires: must be YYYY-MM-DD, got ${JSON.stringify(entry.expires)}`);
52
+ if (Number.isNaN(Date.parse(`${entry.expires}T00:00:00Z`))) throw new UsageError(`${path}["${key}"].expires: not a real date: ${entry.expires}`);
53
+ }
54
+ settings[key] = entry.setting;
55
+ annotations[key] = {
56
+ setting: entry.setting,
57
+ reason: entry.reason.trim(),
58
+ ...entry.owner ? { owner: entry.owner.trim() } : {},
59
+ ...entry.expires ? { expires: entry.expires } : {}
60
+ };
61
+ }
62
+ return {
63
+ settings,
64
+ annotations
65
+ };
66
+ }
67
+ /** The settings alone, for the many callers that never needed the annotations. */
68
+ function parseRuleSettings(raw, path) {
69
+ return parseAnnotatedRuleSettings(raw, path).settings;
70
+ }
71
+ /**
72
+ * Which settings key applies to a rule, most specific first.
73
+ *
74
+ * Specificity beats declaration order deliberately: a config that turns a
75
+ * whole gate down to `warn` and then names one rule `suspect` means the
76
+ * narrow line, regardless of which key JSON happened to list first.
77
+ */
78
+ function candidateKeys(gateId, ruleId) {
79
+ return [
80
+ ruleRef(gateId, ruleId),
81
+ ruleId,
82
+ `${gateId}/*`,
83
+ gateId
84
+ ];
85
+ }
86
+ function resolveRules(gate, settings = {}) {
87
+ const decisions = /* @__PURE__ */ new Map();
88
+ const used = /* @__PURE__ */ new Set();
89
+ for (const rule of gate.rules) {
90
+ let decision = {
91
+ ruleId: rule.id,
92
+ effective: rule.severity,
93
+ declared: rule.severity
94
+ };
95
+ for (const key of candidateKeys(gate.id, rule.id)) {
96
+ const setting = settings[key];
97
+ if (setting === void 0) continue;
98
+ used.add(key);
99
+ decision = {
100
+ ruleId: rule.id,
101
+ effective: setting,
102
+ declared: rule.severity,
103
+ via: key
104
+ };
105
+ break;
106
+ }
107
+ decisions.set(rule.id, decision);
108
+ }
109
+ const unmatched = Object.keys(settings).filter((key) => !used.has(key)).filter((key) => key === gate.id || key === `${gate.id}/*` || key.startsWith(`${gate.id}/`) || !key.includes("/"));
110
+ return {
111
+ gateId: gate.id,
112
+ decisions,
113
+ unmatched
114
+ };
115
+ }
116
+ /** Apply resolved settings to a gate's findings. */
117
+ function applyRuleSettings(gate, findings, settings = {}) {
118
+ const resolved = resolveRules(gate, settings);
119
+ const kept = [];
120
+ const suppressed = [];
121
+ const retuned = [];
122
+ const undeclared = [];
123
+ for (const finding of findings) {
124
+ const decision = resolved.decisions.get(finding.rule);
125
+ if (!decision) {
126
+ if (!undeclared.includes(finding.rule)) undeclared.push(finding.rule);
127
+ kept.push(finding);
128
+ continue;
129
+ }
130
+ if (decision.effective === "off") {
131
+ suppressed.push({
132
+ finding,
133
+ via: decision.via ?? gate.id
134
+ });
135
+ continue;
136
+ }
137
+ if (decision.via && decision.effective !== finding.severity) {
138
+ retuned.push({
139
+ finding,
140
+ from: finding.severity,
141
+ to: decision.effective,
142
+ via: decision.via
143
+ });
144
+ kept.push({
145
+ ...finding,
146
+ severity: decision.effective
147
+ });
148
+ continue;
149
+ }
150
+ kept.push(finding);
151
+ }
152
+ return {
153
+ findings: kept,
154
+ suppressed,
155
+ retuned,
156
+ undeclared
157
+ };
158
+ }
159
+ function countFindings(findings) {
160
+ return {
161
+ suspect: findings.filter((f) => f.severity === "suspect").length,
162
+ warn: findings.filter((f) => f.severity === "warn").length,
163
+ info: findings.filter((f) => f.severity === "info").length
164
+ };
165
+ }
166
+ /**
167
+ * Validate a definition before it is registered. Cheap invariants, but each
168
+ * one is a defect that used to be discoverable only by running the gate:
169
+ * duplicate rule ids make a setting ambiguous, a non-slug id breaks config
170
+ * keys, and an empty command cannot be dispatched.
171
+ */
172
+ function validateGateDefinition(gate) {
173
+ const problems = [];
174
+ if (!/^[a-z0-9]+(?:[.-][a-z0-9]+)*$/.test(gate.id)) problems.push(`id "${gate.id}" must be lowercase dot/dash-separated (e.g. check.integrity)`);
175
+ if (gate.command.length === 0) problems.push(`${gate.id}: command must have at least one token`);
176
+ for (const token of gate.command) if (!/^[a-z0-9-]+$/.test(token)) problems.push(`${gate.id}: command token "${token}" must be a lowercase slug`);
177
+ if (gate.rules.length === 0) problems.push(`${gate.id}: rules table is empty — a gate with no declared rules cannot be tuned or documented`);
178
+ const seen = /* @__PURE__ */ new Set();
179
+ for (const rule of gate.rules) {
180
+ if (!/^[a-z0-9]+(?:-[a-z0-9]+)*$/.test(rule.id)) problems.push(`${gate.id}: rule id "${rule.id}" must be a lowercase slug`);
181
+ if (seen.has(rule.id)) problems.push(`${gate.id}: duplicate rule id "${rule.id}"`);
182
+ seen.add(rule.id);
183
+ if (!rule.title.trim()) problems.push(`${gate.id}/${rule.id}: title is required`);
184
+ }
185
+ return problems;
186
+ }
187
+ //#endregion
188
+ export { RULE_SETTINGS, applyRuleSettings, countFindings, parseAnnotatedRuleSettings, parseRuleSettings, resolveRules, validateGateDefinition };