@svelte-vitals/core 0.47.0 → 0.47.2

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.
@@ -1,1283 +0,0 @@
1
- /**
2
- * Component-body facts for the Correctness category — the source-analysis boundary
3
- * (mirrors images.ts / headings.ts). Collected by the static (CLI) provider only;
4
- * the rendered provider can't see reactivity, so correctness rules no-op there.
5
- */
6
- /** An `{#each}` block in a component template. */
7
- interface EachBlockFact {
8
- /** True when the block has a key, e.g. `{#each items as item (item.id)}`. */
9
- hasKey: boolean;
10
- /** 1-based source line, or 0 if unknown. */
11
- line: number;
12
- /** Set when the block's key expression is its index binding or a trivial coercion of it — `(i)`, `(String(i))`, `(Number(i))`, `` (`${i}`) ``, `(i.toString())`, `(i + '')` — correctness/each-index-key. */
13
- indexKey?: boolean;
14
- }
15
- /** An `$effect(...)` / `$effect.pre(...)` call in a component's instance script. */
16
- interface EffectFact {
17
- /** 1-based source line, or 0 if unknown. */
18
- line: number;
19
- /** True when the effect body only assigns to `$state` variables (the "use $derived" smell). */
20
- assignsOnlyState: boolean;
21
- /** True when this $effect has a NON-EMPTY body that reads no reactive value and makes no bare call — it never re-runs, so it should be onMount (correctness/effect-as-onmount). */
22
- mountOnly: boolean;
23
- }
24
- /** A `$effect` guaranteed to run outside component initialisation — it throws `effect_orphan` at runtime (correctness/orphan-effect). */
25
- interface OrphanEffectFact {
26
- /** 1-based source line, or 0 if unknown. For 'constructor-instantiated', the module-scope `new` site. */
27
- line: number;
28
- /** 'top-level' = runs at module evaluation; 'constructor-instantiated' = module-scope `new` of a same-file class whose constructor creates a bare effect. */
29
- kind: 'top-level' | 'constructor-instantiated';
30
- /** Class name when kind is 'constructor-instantiated' (used in the finding message). */
31
- className?: string;
32
- }
33
- /** A svelte lifecycle/context call guaranteed to run outside component initialisation — it throws `lifecycle_outside_component` at runtime (correctness/orphan-lifecycle). */
34
- interface OrphanLifecycleCallFact {
35
- /** Canonical svelte export name (alias-resolved), e.g. 'onMount'. */
36
- name: string;
37
- /** 1-based source line, or 0 if unknown. For 'constructor-instantiated', the module-scope `new` site. */
38
- line: number;
39
- /** 'top-level' = runs at module evaluation; 'constructor-instantiated' = module-scope `new` of a same-file class whose constructor calls a tracked function. */
40
- kind: 'top-level' | 'constructor-instantiated';
41
- /** Class name when kind is 'constructor-instantiated' (used in the finding message). */
42
- className?: string;
43
- }
44
- /** A browser-only global read in code that runs on the server — SSR crashes with "<name> is not defined" (correctness/server-browser-global, correctness/instance-browser-global). */
45
- interface BrowserGlobalRefFact {
46
- /** The global's name, e.g. 'window'. */
47
- name: string;
48
- /** 1-based source line, or 0 if unknown. */
49
- line: number;
50
- /** 'module' = module evaluation (script module / runes module — correctness/server-browser-global); 'instance' = component-init top level (runs on the server during SSR — correctness/instance-browser-global). */
51
- context: 'module' | 'instance';
52
- }
53
- /** A flagged source position in a component (e.g. an `{@html}` tag or a `javascript:` URL). */
54
- interface SourceSpan {
55
- /** 1-based source line, or 0 if unknown. */
56
- line: number;
57
- }
58
- /** An inline `svelte-vitals-disable-next-line` directive found in the component's source (issue #92). */
59
- interface SuppressionDirective {
60
- /** 1-based line the directive suppresses (the line immediately after the comment). */
61
- line: number;
62
- /** Rule ids suppressed on that line; undefined = suppress every rule on that line. */
63
- ruleIds?: string[];
64
- }
65
- /** An `<input type="checkbox">` / `<input type="radio">` element carrying a `bind:value`
66
- * directive — `bind:value` observes the DOM `value` property, which checkbox/radio
67
- * interaction never changes, so the bound state silently never updates
68
- * (correctness/checkable-bind-value). */
69
- interface CheckableBindValueFact {
70
- /** Which checkable input type was flagged — selects the message wording. */
71
- kind: 'checkbox' | 'radio';
72
- /** 1-based source line, or 0 if unknown. */
73
- line: number;
74
- }
75
- /** A root-relative navigation literal — broken when the app is served under `kit.paths.base`
76
- * (correctness/base-path-navigation). Shared by the component and Kit-module channels. */
77
- interface BasePathLinkFact {
78
- /** Which navigation surface it was written on — selects the message wording. */
79
- kind: 'href' | 'goto' | 'redirect';
80
- /** The literal path as written, e.g. '/about'. */
81
- path: string;
82
- /** 1-based source line, or 0 if unknown. */
83
- line: number;
84
- }
85
- /** An interactive element (e.g. `<button>`) found nested inside another interactive
86
- * container (e.g. `<a href>`) (a11y/interactive-nesting). */
87
- interface InteractiveNestingFact {
88
- containerTag: string;
89
- /** The container's literal `role`, when that is what made it a container rather than its tag. */
90
- containerRole?: string;
91
- descendantTag: string;
92
- /** 1-based source line of the descendant, or 0 if unknown. */
93
- line: number;
94
- }
95
- /** A `button`/`a href`/`input type="image"` with no computable accessible name (a11y/accessible-name). */
96
- interface UnnamedInteractiveFact {
97
- tag: string;
98
- /** 1-based source line, or 0 if unknown. */
99
- line: number;
100
- }
101
- /** An element carrying a `role` and/or `aria-*` attribute(s) (a11y ARIA rules). */
102
- interface AriaElementFact {
103
- tag: string;
104
- /** 1-based source line, or 0 if unknown. */
105
- line: number;
106
- /** literal role value; undefined = no role attr; { expression: true } = dynamic */
107
- role?: {
108
- literal?: string;
109
- expression?: boolean;
110
- };
111
- /** every aria-* attribute on the element */
112
- aria: {
113
- name: string;
114
- literal?: string;
115
- expression?: boolean;
116
- line: number;
117
- }[];
118
- /** literal `type` of an `<input>`, lowercased; undefined for non-inputs or a dynamic type */
119
- inputType?: string;
120
- /** an `<input>` carrying a `list` attribute — its implicit role is `combobox` and the host supplies `aria-expanded` */
121
- hasList?: true;
122
- /**
123
- * A `<select>`'s native role: `combobox` with no `multiple` and no `size` above 1, `listbox`
124
- * otherwise; absent for a non-select or when a dynamic `size` leaves it unknowable.
125
- */
126
- selectKind?: 'combobox' | 'listbox';
127
- /** Set when the element also carries a spread attribute — its full attribute set is
128
- * unknowable, so required-prop presence checks must treat it as satisfied (a11y/required-aria-props). */
129
- hasSpread?: true;
130
- }
131
- /**
132
- * Every element in a component with its literal attribute names — the input for the rules that
133
- * judge against the HTML spec data (a11y/deprecated-element, a11y/deprecated-attr, and the rest of
134
- * that family). Tag and attribute names are lowercased, matching how HTML parses them.
135
- */
136
- interface ElementFact {
137
- tag: string;
138
- /** 1-based source line, or 0 if unknown. */
139
- line: number;
140
- /**
141
- * Literal attribute names on the element (directives, spreads and expression-only names excluded).
142
- * The per-attribute line is not what the deprecation rules anchor to — they anchor at the start
143
- * tag so a `disable-next-line` directive can reach a multi-line element — but a value-level rule
144
- * (`invalid-attr`) may want it for its message.
145
- */
146
- attrs: {
147
- name: string;
148
- line: number;
149
- value?: string;
150
- }[];
151
- /**
152
- * Inside an `<svg>` subtree, or in a component declaring `<svelte:options namespace="svg" />`.
153
- * `<foreignObject>` returns to HTML. Names collide across the two namespaces (`a`, `script`,
154
- * `style`, `title`), so HTML-only rules must skip these.
155
- */
156
- inSvg?: true;
157
- /**
158
- * Index of the nearest literal ancestor element in the same array (push-before-children DFS
159
- * keeps it sound), looking through `{#if}`/`{#each}`/`{#await}`/`{#key}`. Absent at template
160
- * root and after every construct whose rendering position is not lexical — a component,
161
- * `<svelte:element>`, `<slot>`, `{@render}`, `{@html}`, a custom element or unknown tag,
162
- * a `{#snippet}` body root, `<svelte:head>` children — so `a11y/permitted-contents` never
163
- * judges across one.
164
- */
165
- parent?: number;
166
- /** A spread attribute is present — every attribute test on this element is unknowable. */
167
- hasSpread?: true;
168
- /**
169
- * A direct child the static walk cannot see through (component, `{@html}`, `{@render}`,
170
- * `<slot />`, `<svelte:element>`, a custom element or unknown tag) — `:has(...)` over this
171
- * element's subtree is unknowable.
172
- */
173
- unknownContent?: true;
174
- }
175
- /** Reactivity/correctness + security + architecture facts parsed from one `.svelte` component. */
176
- interface ComponentFacts {
177
- /** Source file the component came from. */
178
- file: string;
179
- eachBlocks: EachBlockFact[];
180
- effects: EffectFact[];
181
- /** `{@html …}` occurrences — raw-HTML render surfaces (security/raw-html). */
182
- htmlTags: SourceSpan[];
183
- /** Element attributes with a literal `javascript:` URL (security/javascript-url). */
184
- javascriptUrls: SourceSpan[];
185
- /** Source line count of the component file (architecture/component-size). */
186
- loc: number;
187
- /** Named props destructured from `$props()`; 0 when unknowable (rest / non-destructured) (architecture/prop-count). */
188
- propCount: number;
189
- /** Module specifiers of every `import` in the instance + module scripts (performance/heavy-import). */
190
- imports: string[];
191
- /**
192
- * Module specifiers of every `import`, each with its source line (performance/heavy-import,
193
- * architecture/route-component-import). `type` marks a declaration that contributes **no runtime
194
- * value binding** — either `import type …`, or one whose every specifier is inline-typed
195
- * (`import { type A } from …`). A specifier-less side-effect import is not marked: it still loads
196
- * the module. Optional, so existing external constructors of `ComponentFacts` are unaffected.
197
- */
198
- importSpans: {
199
- source: string;
200
- line: number;
201
- type?: true;
202
- }[];
203
- /** Value `import * as X from '<bare pkg>'` namespace imports (type-only excluded) — performance/namespace-import. */
204
- namespaceImports: {
205
- source: string;
206
- line: number;
207
- }[];
208
- /** `$state` declarations never written or escaped anywhere in the component — candidates for const (correctness/unmutated-state). */
209
- constableStates: {
210
- name: string;
211
- line: number;
212
- }[];
213
- /** Mutations of a non-`$bindable` prop from `$props()`, or a legacy `export let` prop — member writes, `delete`, or a mutating method call (correctness/prop-mutation). `legacy` distinguishes which mode the prop was declared in (absent/false: `$props()`), since the fix differs — optional so existing external constructors of `ComponentFacts` are unaffected. */
214
- mutatedProps: {
215
- name: string;
216
- line: number;
217
- legacy?: boolean;
218
- }[];
219
- /** Top-level const/let bindings computed from a $props() or legacy `export let` prop without $derived (or `$:`), never reassigned or escaped, and referenced (eagerly) in the template — frozen at init (correctness/stale-prop-derivation). `legacy` distinguishes which mode the prop was declared in, since the fix differs — optional so existing external constructors of `ComponentFacts` are unaffected. */
220
- stalePropDerivations: {
221
- name: string;
222
- line: number;
223
- legacy?: boolean;
224
- }[];
225
- /** Object/array-literal $state bindings reassigned at least once but never mutated, escaped, aliased, or item-edited — $state.raw candidates (performance/state-raw). */
226
- rawableStates: {
227
- name: string;
228
- line: number;
229
- }[];
230
- /** Plain built-in instances (Map/Set/Date/URL/URLSearchParams) in $state whose type-specific mutations were observed inside functions, with no exempting reassignment — untracked by reactivity (correctness/nonreactive-builtin-state). */
231
- nonreactiveBuiltinStates: {
232
- name: string;
233
- type: string;
234
- line: number;
235
- }[];
236
- /** `<input type="checkbox">` / `<input type="radio">` elements bound with `bind:value`
237
- * instead of `bind:checked`/`bind:group` (correctness/checkable-bind-value). */
238
- checkableBindValues: CheckableBindValueFact[];
239
- /** Root-relative `<a href>` and `goto()` literals in this component (correctness/base-path-navigation). */
240
- basePathLinks: BasePathLinkFact[];
241
- /** `$effect` calls guaranteed to run outside component initialisation — module scope in `.svelte.ts`/`.svelte.js` or `<script module>` (correctness/orphan-effect). */
242
- orphanEffects: OrphanEffectFact[];
243
- /** Svelte lifecycle/context calls guaranteed to run outside component initialisation — module scope in `.svelte.ts`/`.svelte.js` or `<script module>` (correctness/orphan-lifecycle). */
244
- orphanLifecycleCalls: OrphanLifecycleCallFact[];
245
- /** Browser-global reads in server-executed positions of this file (correctness/server-browser-global, correctness/instance-browser-global). */
246
- browserGlobalRefs: BrowserGlobalRefFact[];
247
- /** Module-scope `$state` declarations in a `.svelte.ts`/`.svelte.js` runes module — on a server, one instance shared by every request (security/shared-state-import). Always empty for `.svelte` files. */
248
- moduleStateDecls: {
249
- name: string;
250
- line: number;
251
- }[];
252
- /** Inline `svelte-vitals-disable-next-line` directives found in this file's source — component-rule escape hatch (issue #92). Optional: absent is equivalent to no directives, so existing external constructors of `ComponentFacts` are unaffected. */
253
- suppressions?: SuppressionDirective[];
254
- /** Markdown links `[label](url)` appearing inside a comment (architecture/doc-link-target). */
255
- commentLinks: {
256
- url: string;
257
- line: number;
258
- }[];
259
- /** Elements carrying a role or any aria-* attribute (a11y ARIA rules). */
260
- ariaElements?: AriaElementFact[];
261
- /** Every element with its attribute names and SVG-namespace flag (the HTML spec-data rules). */
262
- elements?: ElementFact[];
263
- /** Interactive elements nested inside another interactive container (a11y/interactive-nesting). */
264
- interactiveNestings?: InteractiveNestingFact[];
265
- /** `button`/`a href`/`input type="image"` elements with no computable accessible name (a11y/accessible-name). */
266
- unnamedInteractive?: UnnamedInteractiveFact[];
267
- /** `<label>` elements with neither a `for` attribute nor a wrapped labelable descendant (a11y/label-has-control). */
268
- unassociatedLabels?: {
269
- line: number;
270
- }[];
271
- /** Text nodes whose trimmed content opens with a bullet character followed by whitespace, outside any `li` (a11y/use-list). */
272
- bulletTexts?: {
273
- line: number;
274
- char: string;
275
- }[];
276
- /** `<select required>` (no `multiple`, display size absent or ≤ 1) whose first `option` element
277
- * child is not a placeholder label option (a11y/placeholder-label-option). */
278
- selectsMissingPlaceholder?: {
279
- line: number;
280
- }[];
281
- /** `<time>` with no `datetime` attribute whose literal text content is not machine-readable (a11y/require-datetime). */
282
- timesMissingDatetime?: {
283
- line: number;
284
- text: string;
285
- }[];
286
- /** Set when the file failed to read or parse and these facts are the empty fallback — the file was NOT analyzed. */
287
- parseFailed?: true;
288
- /** Set when the file could not be READ — an environment problem (permissions, a descriptor
289
- * limit), not a malformed component. Reported separately so one does not masquerade as the other. */
290
- readFailed?: true;
291
- }
292
- /**
293
- * Warnings for files a collector could not read or parse: the file contributes empty facts, so any
294
- * findings it would have produced are simply missing rather than reported as fixed. The two causes
295
- * are reported separately — an unreadable file is an environment problem (permissions, a descriptor
296
- * limit) and a malformed one is the author's, and sharing a message is how a descriptor limit once
297
- * read as hundreds of broken components. Capped at 10 inline paths so one badly-broken directory
298
- * cannot flood the terminal.
299
- */
300
- declare function skippedFileWarnings(facts: readonly {
301
- file: string;
302
- parseFailed?: true;
303
- readFailed?: true;
304
- }[]): string[];
305
-
306
- /**
307
- * Core type definitions shared across modes. This module is pure: no I/O, no
308
- * `node:` imports, no runtime-specific globals (design §8).
309
- */
310
-
311
- type Severity = 'critical' | 'warning' | 'info';
312
- /** Where a head tag is set, relative to the route being evaluated (design §4). */
313
- type Presence = 'own' | 'inherited' | 'none';
314
- /** How a tag's value is determined (design §4). */
315
- type Value = 'static' | 'dynamic' | 'absent';
316
- /**
317
- * Two-axis detection result. Kept independent so combinations such as
318
- * "inherited + dynamic" remain expressible (design §4).
319
- */
320
- interface Detection {
321
- presence: Presence;
322
- value: Value;
323
- }
324
- /**
325
- * One compiled SvelteKit alias entry, in the order Kit builds them (`get_config_aliases` in
326
- * `@sveltejs/kit/src/exports/vite/utils.js`): `$lib` first, then `kit.alias` in declaration
327
- * order. Resolution takes the FIRST matching entry, exactly as Vite's alias plugin does, so
328
- * **position is precedence** — the list is never sorted and a longer `find` never wins on
329
- * length alone.
330
- */
331
- interface KitAlias {
332
- /** The alias key, with any trailing `/*` removed. */
333
- find: string;
334
- /**
335
- * The project-relative target: posixified, with any trailing `/*` and any trailing slashes
336
- * removed. `null` when the config's value is not a string literal — such an entry still
337
- * matches (holding its position and its mode) but resolves to undefined, so a specifier we
338
- * cannot resolve stays unresolved instead of falling through to a later entry.
339
- */
340
- replacement: string | null;
341
- /**
342
- * How `find` matches a specifier, mirroring Kit's three compiled entry shapes:
343
- * - `prefix` — `spec === find` or `spec.startsWith(find + '/')`; a plain key.
344
- * - `contents` — `spec.startsWith(find + '/')` only; from a `key/*` key, which Kit
345
- * documents as matching "the contents of a directory, not the directory itself".
346
- * - `exact` — `spec === find` only; a plain key whose `key/*` form is ALSO declared, which
347
- * is how Kit stops the plain key from swallowing the nested specifiers.
348
- */
349
- match: 'prefix' | 'contents' | 'exact';
350
- }
351
- /** Project-wide facts precomputed by the runtime layer for project-scope rules (design §10). */
352
- interface Project {
353
- hasRobotsTxt: boolean;
354
- hasSitemap: boolean;
355
- /** <html lang> from app.html: presence 'own' when the attribute exists ('none' otherwise); value 'static' if non-empty, 'absent' if empty. */
356
- htmlLang: Detection;
357
- /** Whether the static static/robots.txt references a sitemap (`Sitemap:` line). Undefined for a +server endpoint / absent / unreadable. */
358
- robotsReferencesSitemap?: boolean;
359
- /**
360
- * Set when the Vite config disables minification for production builds (performance/minify-disabled).
361
- * `file` is the config path relative to the analyzed root (posix, may start with `../`
362
- * in monorepos); unset for inline programmatic configs. `line` is 1-based and set only
363
- * when the literal `minify: false` was located in that file; unset when the value was
364
- * resolved at build time (plugin/conditional config). `suppressions` carries the config file's
365
- * own inline directives, so a line-anchored finding in it can be silenced like any other.
366
- */
367
- viteMinifyDisabled?: {
368
- file?: string;
369
- line?: number;
370
- suppressions?: SuppressionDirective[];
371
- };
372
- /**
373
- * Set when the project configures a non-empty `kit.paths.base` — read from the `sveltekit()`
374
- * Vite plugin config, else `svelte.config.{js,ts}` (correctness/base-path-navigation).
375
- * `value` is the literal base when statically resolvable, unset when the config computes it
376
- * (e.g. `dev ? '' : '/repo'`). `file` is the config path relative to the analyzed root (posix).
377
- * Absent means the app is served at the root — the rule stays silent.
378
- */
379
- kitPathsBase?: {
380
- value?: string;
381
- file: string;
382
- };
383
- /**
384
- * The project's compiled SvelteKit alias entries, in Kit's own order (`$lib` first), read from
385
- * `svelte.config.{js,ts}`. Absent means no config was read — resolution then falls back to
386
- * `$lib` → `src/lib`, which is what this analyzer assumed unconditionally before. A collected
387
- * list is never empty: `$lib` is always prepended.
388
- */
389
- kitAliases?: KitAlias[];
390
- /**
391
- * Whether `src/app.html` opens with `<!doctype html>` (a11y/doctype). Set from the same read
392
- * as `htmlLang`; absent when the file wasn't read (missing or unreadable) — the rule stays
393
- * silent then, like `viteMinifyDisabled`'s absent convention.
394
- */
395
- appHtmlDoctype?: boolean;
396
- /** Literal ids in src/app.html with the line each first appears on — shell content present on every rendered route. Absent when the file wasn't read. */
397
- appHtmlIds?: {
398
- id: string;
399
- line: number;
400
- }[];
401
- /** Distinct lowercased tag names inside `app.html`'s `<body>` (a11y/required-element's presence set; static mode). */
402
- appHtmlBodyTags?: string[];
403
- }
404
- declare const defaultProject: Project;
405
- /** A concrete, agent-actionable remediation for a finding (design §10, issue #18). */
406
- interface Fix {
407
- /** One-line imperative instruction, e.g. 'Add a <meta name="description"> inside <svelte:head>.' */
408
- description: string;
409
- /** Concrete code to insert or a file's contents to create. */
410
- snippet?: string;
411
- /** Markdown fenced-code language for `snippet` (default 'svelte'). */
412
- lang?: string;
413
- }
414
- /** A single rule finding for one route (or the whole project). */
415
- interface Result {
416
- /** Rule id, e.g. 'seo/title-presence'. */
417
- id: string;
418
- severity: Severity;
419
- detection: Detection;
420
- /** Route path, e.g. '/blog/[slug]'. Omitted for project-scoped rules. */
421
- route?: string;
422
- /** Source location, e.g. 'src/routes/blog/[slug]/+page.svelte'. */
423
- location?: string;
424
- message: string;
425
- recommendation?: string;
426
- docsUrl?: string;
427
- /** Agent-actionable remediation (issue #18). */
428
- fix?: Fix;
429
- /** Vitals category this finding belongs to (default 'seo' when absent). */
430
- category?: Category;
431
- /** 1-based source line for element-level findings (e.g. a specific <img>). */
432
- line?: number;
433
- }
434
- type Scope = 'route' | 'project' | 'component';
435
- type Category = 'seo' | 'performance' | 'correctness' | 'security' | 'architecture' | 'a11y';
436
- /**
437
- * Every category, as a runtime list — for validating a user-supplied category
438
- * name and naming the known ones in the error. One definition so a category
439
- * added to `Category` can't be accepted by one validator and rejected by
440
- * another. Not an ordering: reporters keep their own display order.
441
- */
442
- declare const CATEGORIES: readonly Category[];
443
- /** How dynamic (`{data.title}`) values are treated by scoring (design §4, §12). */
444
- type TreatDynamicAs = 'pass' | 'warn' | 'fail';
445
- /** Resolved option values handed to a rule at check time. */
446
- type RuleOptions = Record<string, unknown>;
447
- /**
448
- * Object form of a rule setting. `severity` omitted keeps the rule's built-in
449
- * severity — the common case when only a threshold is being moved.
450
- * `{ severity: 'off', … }` disables the rule and any `options` beside it are
451
- * inert (equivalent to the bare `'off'` string, not an error).
452
- */
453
- interface RuleSettingObject {
454
- severity?: Severity | 'off';
455
- options?: RuleOptions;
456
- }
457
- /** Per-rule override: disable, change severity, and/or set options. */
458
- type RuleSetting = 'off' | Severity | RuleSettingObject;
459
- /**
460
- * Scoped rule override (design 2026-07-18), applied to results after analysis.
461
- * An entry matches a finding when any `route` glob matches its route id or any
462
- * `files` glob matches its source location; at least one of the two must be
463
- * set. Glob syntax: `*` matches within a segment, `**` across segments, a
464
- * trailing `/**` also matches the bare prefix, and all other characters
465
- * (including SvelteKit's `(`, `)`, `[`, `]`) are literal.
466
- */
467
- interface RuleOverride {
468
- /**
469
- * Route-id glob(s), e.g. '/admin/**'. Note route ids drop `(group)` segments
470
- * (`src/routes/(app)/dashboard` reports as '/dashboard') — target a group
471
- * via `files` instead.
472
- */
473
- route?: string | string[];
474
- /** Source-path glob(s) matched against a finding's location, e.g. 'src/routes/(app)/**'. */
475
- files?: string | string[];
476
- /** Keys are rule ids ('seo/title-presence') or category names ('seo'). Rule id beats category within an entry. */
477
- rules: Record<string, RuleSetting>;
478
- }
479
- interface Config {
480
- treatDynamicAs: TreatDynamicAs;
481
- /** Component names treated as meta sources of unknown content (design §11 layer 4). */
482
- metaComponents: string[];
483
- /** Per-rule overrides keyed by rule id (design §6). */
484
- rules: Record<string, RuleSetting>;
485
- /** Minimum severity that fails the run / CI (design §6). */
486
- failOn: Severity;
487
- /** Per-category weights for the combined Health score (default: equal, 1 each) (#10). */
488
- weights?: Partial<Record<Category, number>>;
489
- /** Route-/file-scoped rule overrides, applied to results after analysis (later entries win). */
490
- overrides?: RuleOverride[];
491
- }
492
- declare const defaultConfig: Config;
493
- /** Merge user config over defaults. Identity helper for config files (design §6). */
494
- declare function defineConfig(config?: Partial<Config>): Config;
495
-
496
- interface Summary {
497
- critical: number;
498
- warning: number;
499
- info: number;
500
- /** Passed (not penalized), including dynamic. */
501
- passed: number;
502
- /** Subset of passed that resolved dynamically (↯). */
503
- dynamic: number;
504
- }
505
- /** Classify a single result for display/scoring (design §7, §12). */
506
- type Classification = 'fail' | 'pass' | 'dynamic';
507
- declare function classify(result: Result, config: Config): Classification;
508
- /** A penalized dynamic finding is a warning under treatDynamicAs 'warn'; otherwise the rule's severity. */
509
- declare function effectiveSeverity(result: Result, config: Config): Severity;
510
- declare function summarize(results: Result[], config: Config): Summary;
511
- /** Whether the run should fail the build/CI per the minimum failing severity. */
512
- declare function hasFailureAtOrAbove(summary: Summary, min: Severity): boolean;
513
-
514
- /**
515
- * Render penalized findings as GitHub Actions workflow commands (issue #18, design slice 5).
516
- * GitHub turns these into inline PR annotations and run-annotation entries. Returns '' when clean.
517
- */
518
- declare function formatGithubReport(results: Result[], config: Config): string;
519
-
520
- /**
521
- * Render a compact Markdown summary — Health score, per-category table, severity counts, and
522
- * a findings table — suitable for a GitHub Actions job summary or a sticky PR comment
523
- * (`svelte-vitals ci install`). Delegates all aggregation to `buildJsonReport` so the numbers
524
- * never drift from the JSON/console reporters.
525
- */
526
- declare function formatMarkdownReport(results: Result[], config: Config, meta: {
527
- version: string;
528
- }): string;
529
-
530
- /**
531
- * Runtime abstraction (design §8). Core defines only the interface; concrete
532
- * adapters (Node / Deno / Bun) live in the CLI package and are the only place
533
- * allowed to touch runtime-specific I/O APIs. Providers and rules use this
534
- * interface exclusively, which keeps them runtime-agnostic and lets tests inject
535
- * an in-memory implementation.
536
- */
537
- interface Runtime {
538
- /** Read a UTF-8 text file. Rejects if the file does not exist. */
539
- readFile(path: string): Promise<string>;
540
- /** Whether a path exists. */
541
- exists(path: string): Promise<boolean>;
542
- /**
543
- * Paths matching `pattern`, relative to `cwd`.
544
- *
545
- * **Dot files and dot directories are excluded**, and an adapter must keep it that way: the
546
- * directory-shaped Architecture rules derive their directory set from these paths, and one of them
547
- * enumerates a parent's children exhaustively, so a `.server/` appearing here would be reported as
548
- * an undeclared name. Both shipped adapters pass `dot: false`.
549
- *
550
- * **Every returned path is a file, never a directory**, and an adapter must keep that true too:
551
- * `architecture/reserved-directory-names`' unit test takes a directory's immediate children from
552
- * this same inventory and asks whether one of them is a file named after the directory, so an
553
- * adapter that let a directory through here would let a bare `Card/Card` satisfy that test as if it
554
- * were an entry file. Both shipped adapters get this for free from their glob library's default,
555
- * which returns files only unless asked to include directories.
556
- */
557
- glob(pattern: string, cwd: string): Promise<string[]>;
558
- /** Join path segments without depending on `node:path`. */
559
- join(...parts: string[]): string;
560
- }
561
- /**
562
- * How many file reads may be in flight at once. Analysis reads every `.svelte` file in a project
563
- * in parallel, which on a large project opens more descriptors than the process is allowed: at
564
- * `ulimit -n 1024` — a common container default — a 1 681-route project raised `EMFILE`, and
565
- * because a failed read lands in the same `catch` as a malformed component, 682 files were dropped
566
- * and the run still reported a normal score. The cap is what keeps the analysis whole.
567
- *
568
- * 64 is chosen to sit well under the stock 256 on macOS while leaving descriptors for everything
569
- * else the process holds open. It is not a throughput knob: reads are a few percent of the work.
570
- */
571
- declare const READ_CONCURRENCY = 64;
572
- /**
573
- * `readFile` with at most `limit` reads in flight. A plain counter plus a queue of waiters —
574
- * deliberately not a dependency, and pure enough to live in core.
575
- */
576
- declare function withReadLimit(readFile: (path: string) => Promise<string>, limit?: number): (path: string) => Promise<string>;
577
-
578
- /**
579
- * A normalized head tag. The mode-independent boundary (design §8): the static
580
- * SourceHeadProvider (CLI, via the runtime-abstracted `HeadProvider` below) and
581
- * the rendered collector (`@svelte-vitals/vite`, build-time Node) both emit
582
- * these, so rules never need to know which mode produced them.
583
- */
584
- interface HeadTag {
585
- kind: 'title' | 'meta' | 'link' | 'jsonld' | 'script';
586
- /** <meta name="...">. */
587
- name?: string;
588
- /** <meta property="..."> (e.g. og:image). */
589
- property?: string;
590
- /** <link rel="...">. */
591
- rel?: string;
592
- /** <link as="..."> keyword (e.g. 'font') when statically literal; undefined when absent or dynamically bound. */
593
- as?: string;
594
- /** True when a <link> has an `as` attribute at all (literal or dynamic). Distinguishes "no as" from "dynamic as". */
595
- hasAs?: boolean;
596
- /** True when a <link> has a `crossorigin` attribute (presence only; value is irrelevant to the checks). */
597
- hasCrossorigin?: boolean;
598
- /** True when a <meta name="robots"> literal content contains `noindex`/`none`. Undefined when dynamic or absent. */
599
- noindex?: boolean;
600
- /** Literal `<script type="application/ld+json">` content, set only when the script is static. Undefined when dynamic. */
601
- jsonld?: string;
602
- /** Literal visible text of a static <title> or <meta name="description"> content, set only when static. Undefined when dynamic. */
603
- text?: string;
604
- /** Literal `hreflang` of a `<link rel="alternate">` (e.g. 'en', 'en-US', 'x-default'). Undefined when dynamic/absent. */
605
- hreflang?: string;
606
- /** Literal href (link) / src (script) URL when static — used for third-party origin analysis (performance/preconnect). */
607
- href?: string;
608
- /** True for a render-blocking `<script src>` in <head> (no defer/async/module) (performance/render-blocking-script). */
609
- blocking?: boolean;
610
- /** Where this tag was set relative to the route. Never 'none' (absence = no tag). */
611
- presence: Exclude<Presence, 'none'>;
612
- /** Whether the tag's value is static/dynamic/absent (design §4). */
613
- value: Value;
614
- /** Source file the tag came from (static mode); unset on a rendered head. */
615
- file?: string;
616
- }
617
- /** Resolved effective head for a single route (design §8). */
618
- interface ResolvedHead {
619
- /** Route path, e.g. '/blog/[slug]'. */
620
- route: string;
621
- /** Which provider produced this. */
622
- source: 'static' | 'rendered';
623
- /** Effective head tags after layout-chain composition. */
624
- tags: HeadTag[];
625
- /** Representative source file for the route (used for issue locations). */
626
- file: string;
627
- }
628
- /**
629
- * Supplies ResolvedHead[] for a project through the runtime abstraction. The
630
- * static (CLI) mode implements this; rendered mode reads prerendered HTML at
631
- * build time and emits the same ResolvedHead[] without the runtime indirection.
632
- */
633
- interface HeadProvider {
634
- mode: 'static' | 'rendered';
635
- collect(rt: Runtime, cwd: string, config?: Config): Promise<ResolvedHead[]>;
636
- }
637
-
638
- /**
639
- * A normalized <img> occurrence — the mode-independent boundary for Performance
640
- * rules (mirrors head.ts). Attribute presence only: a dynamically-bound attribute
641
- * (width={w}) still counts as present, so dynamic values are never flagged.
642
- */
643
- interface ImageInfo {
644
- hasWidth: boolean;
645
- hasHeight: boolean;
646
- hasLoading: boolean;
647
- /** True when the <img> has an `alt` attribute at all (incl. empty `alt=""` decorative; seo/image-alt). */
648
- hasAlt: boolean;
649
- /** True when the <img> has a literal `loading="lazy"` (performance/lcp-image). Dynamic/spread → false. */
650
- lazy: boolean;
651
- /** True when the <img> has a `srcset` attribute (performance/responsive-image). */
652
- hasSrcset: boolean;
653
- /** 1-based source line, or 0 if unknown. */
654
- line: number;
655
- /** Source file the <img> came from. */
656
- file: string;
657
- }
658
- /** Resolved <img> elements for a single route (page + layout chain). */
659
- interface ResolvedImages {
660
- route: string;
661
- images: ImageInfo[];
662
- }
663
-
664
- /**
665
- * A normalized page-body heading occurrence — the mode-independent boundary for
666
- * the heading-hierarchy rule (mirrors images.ts). Both providers collect these
667
- * so seo/single-h1 never needs to know which mode produced them.
668
- */
669
- interface HeadingInfo {
670
- /** Heading level 1–6 (the `n` in <hn>). */
671
- level: number;
672
- /** 1-based source line, or 0 if unknown (rendered mode does not track lines). */
673
- line: number;
674
- /** Source file the heading came from. */
675
- file: string;
676
- }
677
- /** Resolved page-body headings for a single route (page + layout chain). */
678
- interface ResolvedHeadings {
679
- route: string;
680
- headings: HeadingInfo[];
681
- /**
682
- * Headings found in child components rendered (transitively) by this route's
683
- * chain files — source mode only; absent in rendered mode. Kept separate from
684
- * `headings` because their position in document order is unknown: safe for
685
- * counting (seo/single-h1), unusable for outline order (seo/heading-level-skip).
686
- */
687
- componentHeadings?: HeadingInfo[];
688
- }
689
-
690
- /** One step of a template branch address: which exclusive block, and which arm of it. */
691
- interface BranchStep {
692
- /** index of the {#if}/{#await} block among its file's blocks (document order) */
693
- group: number;
694
- /** branch index within the group (if: 0..n consequent→else; await: 0=pending,1=then,2=catch) */
695
- branch: number;
696
- }
697
- /** Where a folded occurrence sits, for the finding location. */
698
- interface A11yOccurrenceInfo {
699
- file: string;
700
- line: number;
701
- }
702
- /** One reason a route's closed world failed to hold, with the first offending location. */
703
- interface A11ySkipCause {
704
- kind: 'component' | 'spread' | 'html' | 'dynamic-id';
705
- file: string;
706
- line: number;
707
- /** for kind 'component': the unresolvable component's name as written */
708
- detail?: string;
709
- }
710
- /**
711
- * Route-scoped a11y facts, the mode-independent boundary for the landmark/id rules
712
- * (mirrors headings.ts). Source mode composes the layout chain plus its resolved
713
- * components; rendered mode reads the prerendered document.
714
- */
715
- interface ResolvedA11y {
716
- route: string;
717
- /** representatives per landmark kind after the branch-aware fold ('main' | 'banner' | 'contentinfo' | 'complementary') */
718
- landmarks: Record<string, A11yOccurrenceInfo[]>;
719
- /** landmark occurrences nested inside another landmark after composition */
720
- nestedLandmarks: {
721
- kind: string;
722
- within: string;
723
- file: string;
724
- line: number;
725
- }[];
726
- /** representatives per literal id */
727
- ids: Record<string, A11yOccurrenceInfo[]>;
728
- /** literal id references */
729
- idRefs: {
730
- id: string;
731
- attr: string;
732
- file: string;
733
- line: number;
734
- }[];
735
- /** optimistic candidates: every literal id anywhere (all branches, each/snippet bodies, components, app.html) */
736
- idCandidates: string[];
737
- /** closed world holds: every component resolved, no depth truncation, no {@html}/spread, no dynamic id */
738
- fullyResolved: boolean;
739
- /** Why `fullyResolved` is false — deduped by (kind, file, detail), first occurrence's line kept. Present exactly when `fullyResolved` is false. */
740
- unresolvedCauses?: A11ySkipCause[];
741
- /**
742
- * Distinct tag names in the route's body subtree — layout chain, page, every resolved component,
743
- * and `app.html`'s `<body>` (static), or the prerendered `<body>` (rendered); optimistic across
744
- * `{#if}` arms and `{#each}`/snippet bodies. Never `<svelte:head>` content, `<template>` children,
745
- * or `<svelte:element>`. Absent where a provider does not collect it (a11y/required-element).
746
- */
747
- elementTags?: string[];
748
- /**
749
- * The closed world for elements: every component descended into (an unresolved, depth-truncated,
750
- * or — conservatively — cycle-cut one clears it), no `{@html}`, no `<svelte:element>`. Incomparable with `fullyResolved` — a spread or `id={expr}` clears that flag
751
- * and not this one, since neither can hide an element; a `<svelte:element>` clears this and not
752
- * that. "Missing" is only reportable when this holds; presence is sound regardless.
753
- */
754
- elementsClosed?: boolean;
755
- /** The file a route-level finding is anchored to: the page file (static) or the prerendered HTML path (rendered). */
756
- file?: string;
757
- }
758
- type Foldable = {
759
- key: string;
760
- path: BranchStep[];
761
- repeatable: boolean;
762
- };
763
- /**
764
- * Branch-aware occurrence fold (design "Control-flow semantics"): within a branch
765
- * occurrences sum, across the arms of one exclusive block the arm with the most
766
- * occurrences wins (tie → lowest branch index) and ITS occurrences are the group's
767
- * representatives — so a caller's count is always `list.length`, with a location per
768
- * representative. `{#each}`/`{#snippet}` occurrences render 0..N times and drop out.
769
- * The max is per key: there is no scalar total to maximize.
770
- */
771
- declare function foldOccurrences<T extends Foldable>(nodes: T[]): Map<string, T[]>;
772
- /**
773
- * Decode a fragment identifier the way navigation does before matching an element id
774
- * (`href="#caf%C3%A9"` targets `id="café"`). Malformed escapes are kept verbatim —
775
- * the browser would also fail to decode them, so the raw text is the comparable form.
776
- */
777
- declare function decodeFragmentId(fragment: string): string;
778
- /** Whitespace-split tokens of a (possibly undefined) literal attribute value. */
779
- declare function splitTokens(value: string | undefined): string[];
780
- /** Explicit `role` values that map to the landmark kinds the route rules inspect. */
781
- declare const LANDMARK_ROLES: ReadonlySet<string>;
782
- /**
783
- * Attributes whose (whitespace-tokenized) values reference element ids: the ARIA id-reference and
784
- * id-reference-list properties, and HTML's own (`for`, `list`, `headers`, `form`, the popover and
785
- * command targets). `href="#…"` is handled separately — its value is a URL, not a token list.
786
- */
787
- declare const IDREF_ATTRS: readonly string[];
788
- /**
789
- * Whether a decoded URL fragment is HTML's "top of the document" indicator: `#top` (ASCII
790
- * case-insensitive) scrolls to the top when no element has that id, so it is never a missing
791
- * reference. Compare AFTER percent-decoding — `#%74op` navigates identically to `#top`.
792
- */
793
- declare function isTopFragment(id: string): boolean;
794
- /**
795
- * A fragment with its text directive removed. Everything from the first `:~:` on is user-agent
796
- * instructions for finding text and names no element, while anything before it is still an
797
- * ordinary element fragment — `#section:~:text=hi` targets `id="section"`, `#:~:text=hi` targets
798
- * nothing. Returns an empty string when the fragment is a directive and nothing else.
799
- */
800
- declare function stripTextDirective(fragment: string): string;
801
-
802
- /**
803
- * Facts parsed from one SvelteKit route/hooks file for the SSR shared-state rules
804
- * (the security kit-module rules). Collected by `collectKitModuleFacts` (static/CLI + vite build mode).
805
- */
806
- interface KitModuleFacts {
807
- /** Repo-relative source file. */
808
- file: string;
809
- /** 'server' = runs only on the server (+*.server, +server, hooks.server); 'universal' = +page.ts/+layout.ts (still runs on the server during SSR). */
810
- kind: 'server' | 'universal';
811
- /** Module-scope let/var reassigned from inside a function (security/server-module-state). */
812
- moduleStateReassignments: {
813
- name: string;
814
- line: number;
815
- inHandler: boolean;
816
- }[];
817
- /** Writes to an imported binding from inside an exported handler (security/handler-state-write). */
818
- importedStateWrites: {
819
- name: string;
820
- line: number;
821
- via: 'assignment' | 'set-call';
822
- }[];
823
- /** Writes to an imported binding outside handlers — top level or helper functions (security/shared-state-import's write flavour). */
824
- importedStateWritesOutsideHandlers: {
825
- name: string;
826
- line: number;
827
- }[];
828
- /**
829
- * `.set()`/`.update()` in a handler on an import resolving under the `$lib` server root.
830
- * The call shape alone cannot tell a persistence client (`db.set(…)`) from a hand-rolled
831
- * in-memory store, so the decision needs the target module — which this pure parse cannot
832
- * read. `collectKitModuleFacts` resolves each one and promotes the in-memory ones into
833
- * `importedStateWrites`; a consumer that ignores this field sees the pre-arbitration
834
- * behaviour, i.e. every one of these exempt.
835
- */
836
- pendingServerStoreWrites: {
837
- name: string;
838
- imported: string;
839
- resolved: string;
840
- line: number;
841
- }[];
842
- /** Value imports whose specifier resolves to a repo-local `.svelte.ts`/`.svelte.js` runes module (security/shared-state-import). */
843
- runesModuleImports: {
844
- source: string;
845
- resolved: string;
846
- names: string[];
847
- line: number;
848
- }[];
849
- /** Svelte lifecycle/context calls that run outside component initialisation — top level, handler bodies, or the `init` hook (correctness/orphan-lifecycle). */
850
- lifecycleCalls: {
851
- name: string;
852
- line: number;
853
- inHandler: boolean;
854
- }[];
855
- /** Browser-global reads in server-executed positions — top level, handler bodies, the `init` hook (correctness/server-browser-global). Empty when the file itself exports `ssr = false`. */
856
- browserGlobalRefs: {
857
- name: string;
858
- line: number;
859
- inHandler: boolean;
860
- }[];
861
- /** Root-relative `redirect()` literals in this Kit module (correctness/base-path-navigation). */
862
- basePathLinks: BasePathLinkFact[];
863
- /** Set when this file disables SSR via `export const ssr = false` (inline or same-file alias export) — the declaration's line (seo/ssr-disabled). */
864
- ssrDisabled?: {
865
- line: number;
866
- };
867
- /** Set when this file disables client-side rendering via `export const csr = false` (inline or same-file alias export). With no client runtime, a universal load only runs during SSR — performance/load-waterfall's browser-waterfall premise doesn't hold. */
868
- csrDisabled?: {
869
- line: number;
870
- };
871
- /** Sequential-await analysis of the exported `load` function (performance/load-waterfall, performance/sequential-awaits): 1-based lines of await sites that depend on an earlier await's result, and of sites independent of all earlier awaits. Set only when at least one list is non-empty. */
872
- loadWaterfalls?: {
873
- dependentLines: number[];
874
- independentLines: number[];
875
- };
876
- /** Inline `svelte-vitals-disable-next-line` directives in this file. */
877
- suppressions: SuppressionDirective[];
878
- /** Set when the file failed to read or parse and these facts are the empty fallback — the file was NOT analyzed. */
879
- parseFailed?: true;
880
- /** Set when the file could not be READ — an environment problem, not a malformed module. */
881
- readFailed?: true;
882
- }
883
-
884
- /** The severity a setting selects: `'off'`, an explicit severity, or undefined (leave the built-in). */
885
- declare function settingSeverity(setting: RuleSetting | undefined): Severity | 'off' | undefined;
886
- /** The options a setting carries, or undefined for the string forms. */
887
- declare function settingOptions(setting: RuleSetting | undefined): RuleOptions | undefined;
888
- /** Drop rules disabled via config (design §6), including a `defaultOff` rule with no entry. */
889
- declare function selectRules(rules: Rule[], config: Config): Rule[];
890
- /**
891
- * `config` with `failedRuleIds` (from `runRules`' `failedRules`) forced `'off'`: a rule that threw
892
- * examined nothing, so leaving it in the inventory would score it as if it had run clean, silently
893
- * inflating Health. Reuses the exact mechanism a `rules: { id: 'off' }` config entry already gets —
894
- * `selectRules`/`buildInventory` both drop an `'off'` id from the denominator — rather than adding a
895
- * second, parallel notion of "not counted" for callers to keep in sync.
896
- */
897
- declare function withFailedRulesOff(config: Config, failedRuleIds: readonly string[]): Config;
898
- /** One-line "rule failed and was skipped" warning; capped to the message's first line so a stack trace can't flood a terminal. */
899
- declare function formatFailedRuleWarning(f: {
900
- id: string;
901
- message: string;
902
- }): string;
903
- /** Apply per-rule severity overrides to results (design §6). */
904
- declare function applyRuleSeverities(results: Result[], config: Config): Result[];
905
- /** An override entry with its globs compiled once. Build with `compileOverrides`. */
906
- interface CompiledOverride {
907
- routes: RegExp[];
908
- files: RegExp[];
909
- rules: Record<string, RuleSetting>;
910
- }
911
- /**
912
- * Compile every override entry's globs to RegExp, once. Callers that match many
913
- * targets (every component, every route) must hoist this out of their loop.
914
- */
915
- declare function compileOverrides(config: Config): CompiledOverride[];
916
- /**
917
- * Whether an override entry applies to a target. THE single definition of that
918
- * question — the result post-pass and in-run option resolution both call it.
919
- * Sharing this matcher is necessary but not sufficient for a severity override
920
- * and an option override to select the same files: each caller must also pass
921
- * the same `target` (route and, critically, `file`) the other path effectively
922
- * matches against. See Finding 1, docs/superpowers/specs/2026-07-26-rule-options-design.md.
923
- */
924
- declare function overrideMatches(o: CompiledOverride, target: {
925
- route?: string;
926
- file?: string;
927
- }): boolean;
928
- /**
929
- * Apply route-/file-scoped overrides to results (design 2026-07-18). An entry
930
- * matches when any `route` glob matches the finding's route id or any `files`
931
- * glob matches its location (OR). `'off'` removes a matched result entirely —
932
- * passing seeds included, so scoring and "checks passed" counts behave as if
933
- * the rule never ran there. A severity value rewrites the result's severity.
934
- * Entries are evaluated in order (later entries win); within one entry, a
935
- * rule-id key beats a category key only when it specifies a `severity` — an
936
- * options-only rule-id key (no `severity`) contributes its options but leaves
937
- * the category key's severity in force, rather than shadowing it (design
938
- * 2026-07-26, Finding 2 / second review Finding E).
939
- */
940
- declare function applyOverrides(results: Result[], config: Config): Result[];
941
-
942
- /**
943
- * Per-rule options: their declaration, resolution, and validation (design
944
- * 2026-07-26). Deliberately does not import `rule.ts` — `rule.ts` imports
945
- * `RuleOptionsSpec` from here, so taking `Rule` as a parameter would cycle.
946
- * Callers pass the id and the spec instead.
947
- */
948
-
949
- /**
950
- * One configurable option. `kind` decides the merge semantics, so no rule
951
- * writes merge code of its own: `integer` replaces, and the two collection
952
- * kinds ADD to the built-in default (never replace — see the design doc).
953
- */
954
- type RuleOptionSpec = {
955
- kind: 'integer';
956
- default: number;
957
- min?: number;
958
- max?: number;
959
- } | {
960
- kind: 'string-list';
961
- default: readonly string[];
962
- /**
963
- * Grammar every entry must match, checked at config load. A declaration-driven rule reserves
964
- * its grammar with this so a value the rule does not interpret today (`'input[type=file]'`
965
- * for a tag-name list) is rejected rather than accepted-and-ignored — accepting it would make
966
- * giving it meaning later a reinterpretation of a value the frozen schema already took.
967
- */
968
- pattern?: {
969
- regex: RegExp;
970
- describe: string;
971
- };
972
- } | {
973
- kind: 'string-map';
974
- default: Readonly<Record<string, string>>;
975
- };
976
- /** A rule's configurable options, keyed by option name. */
977
- type RuleOptionsSpec = Record<string, RuleOptionSpec>;
978
- /**
979
- * Typed reads of a resolved options object. `RuleOptions` values are `unknown`
980
- * (the map is open-ended by design), so without these every rule would carry
981
- * its own `o.max as number` cast and the "resolution guarantees the declared
982
- * kind" invariant would live in a dozen places instead of one. `resolveRuleOptions`
983
- * always seeds every declared key from the spec default and validation rejects a
984
- * wrongly-typed value up front, so a mismatch here means a rule read a key it
985
- * never declared — the `fallback` keeps that a wrong number rather than a crash.
986
- */
987
- declare function intOption(options: RuleOptions, key: string, fallback?: number): number;
988
- /** As `intOption`, for a `string-list` option. */
989
- declare function listOption(options: RuleOptions, key: string): string[];
990
- /** As `intOption`, for a `string-map` option. */
991
- declare function mapOption(options: RuleOptions, key: string): Record<string, string>;
992
- /**
993
- * Whether any config layer so much as mentions `ruleId` — its `rules` entry, or any `overrides`
994
- * entry's.
995
- *
996
- * A rule that is inert until declared can return early on `false` instead of resolving options once
997
- * per target and discarding the result. That waste is not hypothetical: the three directory-shaped
998
- * Architecture rules resolve per directory, so an unconfigured project pays it for every directory
999
- * under `src/` three times over, on every dev-server save. Measured 2026-07-30 over a synthetic tree
1000
- * of 1,523 directories: 5.4 ms per analysis, for rules that are off by default and therefore produce
1001
- * nothing.
1002
- *
1003
- * Deliberately conservative. It asks only whether the rule is *mentioned*, not whether the mention
1004
- * resolves to a non-empty value, so a `'off'` severity with no options still answers `true` and the
1005
- * caller does its normal work. A cheaper-but-wrong version of this would make a rule skip work it
1006
- * owed; this one can only ever fail to save time.
1007
- */
1008
- declare function isMentionedAnywhere(config: Config, ruleId: string): boolean;
1009
- /**
1010
- * Effective options for a rule at a target: built-in defaults, then
1011
- * `config.rules[ruleId].options`, then every matching `config.overrides` entry
1012
- * in order. Integers take the last value; lists and maps accumulate.
1013
- *
1014
- * `target` omitted skips overrides entirely (project-scoped rules). Callers
1015
- * resolving many targets should hoist `compileOverrides(config)` and pass it as
1016
- * `compiled` — otherwise every call recompiles the globs.
1017
- */
1018
- declare function resolveRuleOptions(ruleId: string, spec: RuleOptionsSpec | undefined, config: Config, target?: {
1019
- route?: string;
1020
- file?: string;
1021
- }, compiled?: CompiledOverride[]): RuleOptions;
1022
- /**
1023
- * Problems with a user-supplied options object, as human-readable sentences
1024
- * (empty = valid). Callers treat any result as fatal: a typo that silently
1025
- * leaves the config inert is the failure this exists to prevent.
1026
- *
1027
- * `baseline`, when given, is the already-resolved value this `options` layer
1028
- * is being merged onto — built-in defaults merged with any earlier layer(s)
1029
- * (e.g. the global `config.rules[id].options`, when `options` is an
1030
- * `overrides[]` entry). The min/max cross-check below compares against it
1031
- * instead of the spec's own default, so a layer that only sets one side of a
1032
- * range is checked against what it actually inherits (design 2026-07-26
1033
- * review, Finding A). Omit it to check `options` against the spec defaults
1034
- * alone, as when validating the global layer itself. A `baseline` that is
1035
- * only partially resolved (missing `min` or `max`) is treated as "can't
1036
- * determine that side" rather than silently comparing against `undefined` —
1037
- * see the `typeof` guard below.
1038
- *
1039
- * `skipRangeCheck`, when true, skips the min/max cross-check entirely
1040
- * regardless of `baseline`. A caller sets this when it statically cannot
1041
- * rule out that some *other* config layer narrows the opposite side of the
1042
- * range at the same target — see the CLI's and the Vite plugin's
1043
- * `overrides[]` validation (design 2026-07-26 review, Finding A, third
1044
- * pass).
1045
- */
1046
- declare function validateRuleOptions(ruleId: string, spec: RuleOptionsSpec | undefined, options: RuleOptions, baseline?: RuleOptions, skipRangeCheck?: boolean): string[];
1047
- /**
1048
- * Whether `validateRuleOptions` should skip the min/max cross-check for
1049
- * `overrides[selfIndex].rules[key]` — the whole decision, so the CLI's
1050
- * config-file loader and the Vite plugin can't drift apart on it (they held
1051
- * line-for-line copies of it before).
1052
- *
1053
- * An entry that sets both sides, or neither, is judged against its baseline as
1054
- * usual. An entry that sets only one side is skipped when some *other* entry
1055
- * sets the opposite side, since the two may co-apply at a shared target and be
1056
- * valid there — see `otherOverrideNarrowsOppositeSide` for why that is
1057
- * conservative by necessity and what it lets through.
1058
- */
1059
- declare function shouldSkipRangeCheck(overrides: readonly unknown[], selfIndex: number, key: string, setting: unknown): boolean;
1060
- /**
1061
- * Problems with one user-supplied rule setting — the bare severity string or the
1062
- * object form — as human-readable sentences prefixed with `label` (empty = valid).
1063
- * THE single definition of what a setting may look like: the CLI's config-file
1064
- * loader and the Vite plugin both funnel through it, so a config file and the
1065
- * equivalent plugin option are accepted or rejected identically. Callers treat any
1066
- * result as fatal, on the same reasoning as an unknown rule id — a typo that
1067
- * silently leaves the config inert is the failure being prevented.
1068
- *
1069
- * `label` names the setting in the message (e.g. `rules.seo/title-length`,
1070
- * `overrides[0].rules.architecture`); `ruleId` is the key options messages quote.
1071
- * `allowOptions` is false for a category key: a category may carry a severity, but
1072
- * options are rule-specific and meaningless there. `baseline` and `skipRangeCheck`
1073
- * are passed through to `validateRuleOptions`.
1074
- */
1075
- declare function validateRuleSetting(label: string, ruleId: string, setting: unknown, spec: RuleOptionsSpec | undefined, opts: {
1076
- allowOptions: boolean;
1077
- baseline?: RuleOptions;
1078
- skipRangeCheck?: boolean;
1079
- }): string[];
1080
-
1081
- /** Input given to every rule. Mode-independent: rules see only ResolvedHead[] (design §8, §10). */
1082
- interface RuleContext {
1083
- heads: ResolvedHead[];
1084
- /** Per-route <img> elements for Performance rules (absent in modes that don't collect them). */
1085
- images?: ResolvedImages[];
1086
- /** Per-route page-body headings for seo/single-h1 (absent in modes that don't collect them). */
1087
- headings?: ResolvedHeadings[];
1088
- /** Per-route composed landmark/id occurrences for the route-scoped a11y rules (absent in modes that don't collect them). */
1089
- a11y?: ResolvedA11y[];
1090
- /** Per-file component-body facts for the component-scoped rules (absent in the dev handle's rendered pass). */
1091
- components?: ComponentFacts[];
1092
- /** Per-file SvelteKit route/hooks facts for the kit-module rules (absent in the dev handle's rendered pass). */
1093
- kitModules?: KitModuleFacts[];
1094
- /**
1095
- * Every file under `src/`, as project-relative paths, for directory-shaped Architecture rules
1096
- * (static/CLI + vite build mode only). Sorted — see `collectSourceFiles`, which is what both
1097
- * adapters use to build it.
1098
- */
1099
- sourceFiles?: string[];
1100
- project: Project;
1101
- config: Config;
1102
- /**
1103
- * Report per-declaration counts of places this rule examined. The engine supplies it and keys the
1104
- * result by rule id; a rule that does not call it gets no entry, which is distinct from an entry of
1105
- * zeros. Absent in contexts a caller builds directly. Silent last-write-wins: calling it more than
1106
- * once keeps only the most recent map, with no merge and no error — call it once, with the complete
1107
- * counts, at the end of `check()`.
1108
- */
1109
- recordExamined?: (counts: Record<string, number>) => void;
1110
- }
1111
- interface Rule {
1112
- id: string;
1113
- title: string;
1114
- category: Category;
1115
- /** Default severity (overridable by config in later slices). */
1116
- severity: Severity;
1117
- /** 'route' = evaluated per route, 'project' = site-wide, 'component' = evaluated per source file (design §10, §12). */
1118
- scope: Scope;
1119
- /** Why this rule matters — one or two sentences, surfaced by `svelte-vitals explain` (issue #24). */
1120
- rationale: string;
1121
- /** Canonical remediation template, shared by findings and `svelte-vitals explain` (issue #24). */
1122
- fix?: Fix;
1123
- /** Configurable options for this rule; absent means the rule takes none. */
1124
- options?: RuleOptionsSpec;
1125
- /**
1126
- * The message this rule puts on a PASS result. Declared so a PASS synthesised elsewhere — the
1127
- * central inline-suppression pass, which turns a fully-suppressed rule+route into a pass — reads
1128
- * the same as one the rule emitted itself. Rules built through `componentRule` and the a11y
1129
- * route factory supply it; the rest fall back to `title`, which is a cosmetic difference visible
1130
- * only in `--verbose`'s passed listing.
1131
- */
1132
- passLabel?: string;
1133
- /** Off unless config.rules names the rule explicitly — the opt-in class (design 2026-08-21). */
1134
- defaultOff?: true;
1135
- /**
1136
- * The rule compares routes against each other (`seo/duplicate-title`), so it cannot be judged
1137
- * from one route's rendered HTML — the dev dashboard's live layer leaves it to the static pass.
1138
- */
1139
- crossRoute?: true;
1140
- /**
1141
- * Evaluate the resolved heads. A single rule may return one Result per route,
1142
- * so it always returns an array. Project-scoped rules return a single element.
1143
- */
1144
- check(ctx: RuleContext): Promise<Result[]>;
1145
- }
1146
- /** Documentation URL for a rule id. Single source so no per-rule URL can drift (issue #24). */
1147
- declare function docsUrlFor(id: string): string;
1148
- /**
1149
- * Whether a detection should be penalized by scoring (design §12). Shared by the
1150
- * future Scorer and by the Slice 0 reporter so pass/fail is decided in one place.
1151
- *
1152
- * presence 'none' → penalized (nothing set anywhere)
1153
- * value 'absent' → penalized (tag present but empty)
1154
- * value 'dynamic' → penalized when treatDynamicAs is not 'pass' (warn or fail)
1155
- * otherwise (static/inherited) → not penalized
1156
- */
1157
- declare function isPenalized(detection: Detection, treatDynamicAs: TreatDynamicAs): boolean;
1158
-
1159
- interface ScoreModel {
1160
- routeAverage: number;
1161
- sitePenalty: number;
1162
- /** Headline cap value when it actually lowered the score, else null. */
1163
- criticalCap: number | null;
1164
- }
1165
- interface ScoreResult {
1166
- /** The score as displayed: `Math.floor(rawScore)`, so 100 means the deduction was exactly zero. */
1167
- score: number;
1168
- /**
1169
- * The same score before flooring, after `sitePenalty` and the cap, clamped to `[0, 100]`. Exposed so
1170
- * `computeHealth` can average unrounded values and floor once — averaging the displayed scores would
1171
- * compose two roundings and move Health by up to two points.
1172
- */
1173
- rawScore: number;
1174
- scoreModel: ScoreModel;
1175
- /** Keys this result set touched. */
1176
- keys: number;
1177
- /** Keys carrying at least one penalized finding. */
1178
- affectedKeys: number;
1179
- }
1180
- interface ScoreOptions {
1181
- applyCriticalCap?: boolean;
1182
- /** The rules that ran. Defaults to the selected registry; supplied by tests and custom rule sets. */
1183
- rules?: readonly Rule[];
1184
- }
1185
- /** Compute the headline score and its breakdown (design §12). */
1186
- declare function computeScore(results: Result[], config: Config, options?: ScoreOptions): ScoreResult;
1187
- /** Compute an independent score per category present in `results` (issue #10). */
1188
- declare function scoresByCategory(results: Result[], config: Config, options?: ScoreOptions): Partial<Record<Category, ScoreResult>>;
1189
- interface HealthResult {
1190
- /** Weighted overall score across present categories (0–100). */
1191
- health: number;
1192
- categories: Partial<Record<Category, ScoreResult>>;
1193
- /** Effective weight used per present category. */
1194
- weights: Partial<Record<Category, number>>;
1195
- }
1196
- /** Combined weighted Health score over the categories present in `results` (#10). */
1197
- declare function computeHealth(results: Result[], config: Config): HealthResult;
1198
-
1199
- declare function issueOf(result: Result): {
1200
- fix?: Fix | undefined;
1201
- docsUrl?: string | undefined;
1202
- recommendation: string | undefined;
1203
- line?: number | undefined;
1204
- id: string;
1205
- category: Category;
1206
- title: string;
1207
- detection: Detection;
1208
- location: string | undefined;
1209
- };
1210
- type JsonIssue = ReturnType<typeof issueOf> & {
1211
- severity: ReturnType<typeof effectiveSeverity>;
1212
- };
1213
- /**
1214
- * Per-rule counts. A rule present with `findings: 0` ran and reported nothing, and an absent rule was not
1215
- * selected — but only when the caller supplied `ruleIds`. Without it the map is seeded from results alone,
1216
- * so absence means "produced nothing" rather than "not selected".
1217
- */
1218
- interface RuleEvidence {
1219
- findings: number;
1220
- passed: number;
1221
- }
1222
- interface JsonReport {
1223
- version: string;
1224
- score: number;
1225
- weights: Partial<Record<Category, number>>;
1226
- categories: Record<string, {
1227
- score: number;
1228
- scoreModel: ScoreModel;
1229
- keys: number;
1230
- affectedKeys: number;
1231
- }>;
1232
- summary: Summary;
1233
- rules: Record<string, RuleEvidence>;
1234
- routes: Array<{
1235
- route: string;
1236
- score: number;
1237
- categories: Record<string, number>;
1238
- issues: JsonIssue[];
1239
- }>;
1240
- siteIssues: JsonIssue[];
1241
- /**
1242
- * Floored severity weight per `"<category>::<scope>"` pair. Reproduces a `routes[].categories` entry
1243
- * (`100 - 100 * failed / inventories[pair]`): a key is either a route id or a source file path, and
1244
- * those two key spaces never overlap, so a category's results on one key always draw on a single scope.
1245
- * It does not reproduce `routes[].score`: a route spanning more than one pair sums their *raw* weights
1246
- * and floors that sum once, so adding this map's already-floored entries and re-dividing can disagree.
1247
- */
1248
- inventories: Record<string, number>;
1249
- /**
1250
- * Per-rule, per-declaration counts of places examined. Unlike `rules`, this describes the analysis
1251
- * rather than the report: `--diff`, `--baseline` and suppressions do not narrow it. Three states: a
1252
- * rule that reports no counts has no entry; a rule that counts but whose configuration declares
1253
- * nothing has an empty entry; a declaration that judged nothing has an entry of `0`.
1254
- */
1255
- examined?: Record<string, Record<string, number>>;
1256
- /**
1257
- * Routes a closed-world rule skipped, keyed by rule id. Like `examined`, this describes the
1258
- * analysis rather than the report: `--diff`, `--baseline` and suppressions do not narrow it.
1259
- * `refs` is the route's literal id-reference count — a skipped route with `refs: 0` would
1260
- * produce nothing even if unlocked. Only source-mode analysis populates it; absent when no
1261
- * analyzed route was skipped.
1262
- */
1263
- skipped?: Record<string, Array<{
1264
- route: string;
1265
- refs: number;
1266
- causes: Array<{
1267
- kind: string;
1268
- file: string;
1269
- line: number;
1270
- detail?: string;
1271
- }>;
1272
- }>>;
1273
- }
1274
- /** Build the structured JSON report object (design §7). The shape the `json` reporter emits (issue #24). */
1275
- declare function buildJsonReport(results: Result[], config: Config, meta: {
1276
- version: string;
1277
- }, ruleIds?: readonly string[], examined?: Record<string, Record<string, number>>, skipped?: JsonReport['skipped']): JsonReport;
1278
- /** Render results as the documented JSON report string (design §7). */
1279
- declare function formatJsonReport(results: Result[], config: Config, meta: {
1280
- version: string;
1281
- }, ruleIds?: readonly string[], examined?: Record<string, Record<string, number>>, skipped?: JsonReport['skipped']): string;
1282
-
1283
- export { foldOccurrences as $, type A11yOccurrenceInfo as A, type BranchStep as B, type ComponentFacts as C, applyOverrides as D, type EachBlockFact as E, type Fix as F, applyRuleSeverities as G, type HeadTag as H, type ImageInfo as I, type JsonReport as J, type KitAlias as K, LANDMARK_ROLES as L, buildJsonReport as M, classify as N, type OrphanEffectFact as O, type Project as P, compileOverrides as Q, type Result as R, type SuppressionDirective as S, computeHealth as T, computeScore as U, type Value as V, decodeFragmentId as W, defaultConfig as X, defaultProject as Y, docsUrlFor as Z, effectiveSeverity as _, type Rule as a, formatFailedRuleWarning as a0, formatGithubReport as a1, formatJsonReport as a2, formatMarkdownReport as a3, hasFailureAtOrAbove as a4, intOption as a5, isMentionedAnywhere as a6, isPenalized as a7, isTopFragment as a8, listOption as a9, type TreatDynamicAs as aA, defineConfig as aB, mapOption as aa, overrideMatches as ab, resolveRuleOptions as ac, scoresByCategory as ad, selectRules as ae, settingOptions as af, settingSeverity as ag, shouldSkipRangeCheck as ah, skippedFileWarnings as ai, splitTokens as aj, stripTextDirective as ak, summarize as al, validateRuleOptions as am, validateRuleSetting as an, withFailedRulesOff as ao, withReadLimit as ap, CATEGORIES as aq, type Detection as ar, type Presence as as, type RuleEvidence as at, type RuleOptions as au, type RuleOverride as av, type RuleSetting as aw, type RuleSettingObject as ax, type ScoreModel as ay, type Summary as az, type Config as b, type Runtime as c, type KitModuleFacts as d, type RuleContext as e, type Category as f, type Severity as g, type RuleOptionSpec as h, type ResolvedHead as i, type A11ySkipCause as j, type Classification as k, type CompiledOverride as l, type EffectFact as m, type HeadProvider as n, type HeadingInfo as o, type HealthResult as p, IDREF_ATTRS as q, READ_CONCURRENCY as r, type ResolvedA11y as s, type ResolvedHeadings as t, type ResolvedImages as u, type RuleOptionsSpec as v, type Scope as w, type ScoreOptions as x, type ScoreResult as y, type SourceSpan as z };