
Validating Slds
- 932 installs
- 787 repo stars
- Updated August 5, 2026
- forcedotcom/sf-skills
validating-slds is a Salesforce Lightning Web Component skill that audits SLDS compliance, accessibility attributes, and CSS theming hooks to produce a scored quality report for developers who need component readiness ch
About
validating-slds is a Salesforce-focused agent skill that audits Lightning Web Components for SLDS compliance and returns a scored quality report. The skill runs the SLDS linter, analyzes CSS for theming hook usage and pairing, checks HTML for accessibility attributes, and aggregates findings into category scores with an overall grade. Developers reach for validating-slds when asked to score a component, produce an SLDS scorecard, audit compliance, or evaluate whether an LWC is ready to ship. Trigger phrases include "rate my component", "audit SLDS compliance", and "review my component before code review". Output includes a structured quality report suitable for manual review gating before submission.
- Runs the official SLDS linter plus supplementary static analysis for CSS theming hooks, HTML accessibility attributes, a
- Produces a scored quality report with category breakdowns and an overall production-readiness grade.
- Serves as a required manual review gate before code submission.
- Valid for single components, full projects, or before/after change comparisons.
- Explicitly not for fixing violations or building new components.
Validating Slds by the numbers
- 932 all-time installs (skills.sh)
- Ranked #145 of 1,352 Code Review & Quality skills by installs in the Skillselion catalog
- Data as of Aug 5, 2026 (Skillselion catalog sync)
npx skills add https://github.com/forcedotcom/sf-skills --skill validating-sldsAdd your badge
Show developers this skill is listed on Skillselion. Paste this into your README.
| Installs | 932 |
|---|---|
| repo stars | ★ 787 |
| Last updated | August 5, 2026 |
| Repository | forcedotcom/sf-skills ↗ |
How do you score SLDS compliance in Lightning Web Components?
Automatically audit Lightning Web Components for SLDS compliance and receive a scored quality report with a manual review gate.
Who is it for?
Salesforce developers shipping Lightning Web Components who need a structured SLDS audit before code review or AppExchange submission.
Skip if: Teams building non-Salesforce frontends or backends where SLDS rules and LWC file structures do not apply.
When should I use this skill?
A developer asks to score, rate, audit, or evaluate SLDS compliance or component quality on an LWC before review or submission.
What you get
Scored SLDS quality report with category grades, linter findings, CSS theming analysis, and accessibility checks.
- scored SLDS quality report
- categorized linter findings
Files
SLDS Quality Audit
Audit Lightning Web Components for SLDS compliance and produce an automated scorecard plus a required manual review gate. Combines SLDS linter output with supplementary static analysis to catch what the linter misses.
Scope
Also valid for: auditing SLDS compliance across a project or component set, and before/after quality comparison after making changes.
Not for:
- Fixing linter violations — use
uplifting-components-to-slds2instead - Building new components — use
applying-sldsinstead - Just running the linter — run
npx @salesforce-ux/slds-linter@latest lint .directly - Full WCAG accessibility audit — this skill checks attribute presence only (labels, alt text, focus indicators), not contrast ratios, keyboard flows, or screen reader behavior
- Framework-specific template auditing beyond
.css,.html, and.jsfiles — JSX/TSX/Vue/Svelte outputs need additional manual review
---
Quality Validation Process
1. Run SLDS Linter → Collect violation counts (linter's job)
2. Run Analyze Script → Check what linter doesn't cover (supplementary)
3. Agent Review → Required manual review gate
4. Score & Grade → Compute automated score + final recommendation
5. Generate Report → Produce formatted scorecardStep 1: Run SLDS Linter
Run the linter to collect baseline violation data:
npx @salesforce-ux/slds-linter@latest lint <component-path> 2>&1Count violations by rule. These feed directly into the Linter Compliance score:
| Rule | Impact |
|---|---|
slds/class-override | Breaks theming, dark mode |
slds/lwc-token-to-slds-hook | SLDS 1 technical debt |
slds/no-hardcoded-values | Breaks theming, accessibility |
Linter Compliance Score = 100 - (total_violations × 10), minimum 0.
If the linter is unavailable (no Node.js, no network access, CI sandbox restrictions): skip this step, note "Linter not run" in the report header, mark Linter Compliance as N/A, and compute the Overall score using the remaining 4 categories renormalized to 100%:
Overall (linter unavailable) = (Theming × 0.29) + (Accessibility × 0.29)
+ (CodeQuality × 0.21) + (ComponentUsage × 0.21)Step 2: Run Supplementary Analysis
Run the analyze script to catch issues the linter doesn't cover. The bundled analyzer scans .css, .html, and .js files only:
node scripts/analyze-quality.cjs <component-path>The script outputs JSON with findings organized by severity. It checks:
CSS Checks (linter-complementary)
| Check | What It Catches | Severity |
|---|---|---|
| Missing fallbacks | var(--slds-g-*) without a fallback value | Critical |
| Invented hooks (T051) | --slds-g-* tokens not found in hooks-index.json (requires --hooks-index) | Critical |
| Hook pairing | Background hooks without matching foreground hooks | Warning |
!important | Specificity overrides | Warning |
| Magic pixel values | Hardcoded px not using spacing hooks | Warning |
| High z-index | z-index values > 99 | Warning |
| Outline removal | outline: none without alternative focus style | Warning |
JS Checks
| Check | What It Catches | Severity |
|---|---|---|
| Inline style assignment | .style.*= direct property assignment | Warning |
| SLDS class manipulation | Dynamic .classList.add('slds-*') manipulation | Warning |
HTML Checks
| Check | What It Catches | Severity |
|---|---|---|
| LBC input labels | <lightning-input> without label attribute | Critical |
| Icon alt text | <lightning-icon> without alternative-text | Critical |
| Image alt text | <img> without alt | Critical |
| Heading hierarchy | Skipped heading levels (h2 to h4) | Warning |
| Positive tabindex | tabindex values other than 0 or -1 | Warning |
| Clickable divs | <div onclick> instead of <button> | Warning |
| Inline styles | style="..." attributes | Warning |
| Native elements | <input>, <button>, <select> where LBC alternatives exist | Warning |
Hook Pairing Validation
The script checks that background/foreground hooks are semantically paired:
surface-* backgrounds → on-surface-* text
surface-container-* bg → on-surface-* text
accent-* backgrounds → on-accent-* text
accent-container-* bg → on-accent-* textLimitation: Hook pairing is checked at the file level, not per-selector. A file withsurface-1in.classAandon-accent-1in.classBwould pass because both surface and accent families are present. Review pairing correctness per-selector during manual review (Step 3).
Invented Hook Detection (T051)
The script cross-references every --slds-g-* token in CSS against hooks-index.json. Any hook not found in metadata is flagged as critical — this catches the most common agent mistake of inventing hooks from naming patterns.
Step 3: Agent Manual Review
These checks require understanding the component's purpose and cannot be automated reliably. Review each and classify findings as either:
- Blocking — incorrect blueprint structure, missing required states, or semantic/interaction issues that make the component not production-ready
- Advisory — worthwhile improvements that do not block shipping on their own
| Review Area | What to Look For |
|---|---|
| Loading states | Does the component show a spinner or skeleton when fetching data? |
| Error states | Are errors surfaced to the user with actionable messages? |
| Empty states | Is there a meaningful empty state when no data exists? |
| Disabled states | Do interactive elements visually and functionally handle disabled? |
| Semantic HTML | Are <nav>, <article>, <section> used where appropriate? |
| SLDS blueprint compliance | Do cards, modals, forms follow SLDS blueprint structure? |
Manual review findings are not automated, but they do affect the final recommendation. Do not report an automated grade as the only verdict.
Step 4: Calculate Automated Scores and Final Recommendation
Component Complexity
Before scoring, classify the component to give the score context:
| Complexity | Criteria | Report Note |
|---|---|---|
| Small | 1-2 files, < 100 total lines | Score is high-confidence (small surface area) |
| Medium | 3-6 files, 100-500 total lines | Score reflects typical component |
| Large | 7+ files, 500+ total lines | Score reflects absolute issue count — even well-built large components may score lower |
Include the complexity classification in the report header. This prevents misreading a "B" on a 1000-line component vs. a "B" on a 20-line component.
Automated Scoring Formula
Category Score = 100 - (critical_issues × 10) - (warnings × 3) - (info × 1)
Minimum score: 0Categories and Weights
| Category | Weight | Source |
|---|---|---|
| Linter Compliance | 30% | SLDS linter output (Step 1) |
| Theming | 20% | Script: fallbacks, hook pairing (Step 2) |
| Accessibility | 20% | Script: labels, alt text, focus (Step 2) |
| Code Quality | 15% | Script: !important, inline styles, z-index (Step 2) |
| Component Usage | 15% | Script: native elements (Step 2) plus manual semantic/blueprint review (Step 3) |
Automated Overall Score
Overall = (Linter × 0.30) + (Theming × 0.20) + (Accessibility × 0.20)
+ (CodeQuality × 0.15) + (ComponentUsage × 0.15)Automated Grade Thresholds
| Score | Grade | Meaning |
|---|---|---|
| 90-100 | A | Excellent automated score |
| 80-89 | B | Good automated score |
| 70-79 | C | Acceptable automated score |
| 60-69 | D | Weak automated score |
| 0-59 | F | Failing automated score |
Manual Review Gate
After computing the automated score, apply the manual review outcome:
| Gate | When to use it | Effect on final recommendation |
|---|---|---|
| Pass | No manual findings | Final recommendation can follow the automated score |
| Advisory | Only non-blocking manual findings | Final recommendation can be "Ready with follow-ups" at best |
| Blocking | One or more blocking manual findings | Final recommendation is not ready for production, regardless of automated grade |
Final Recommendation Rules
Use both the automated score and the manual review gate:
| Final Recommendation | Conditions |
|---|---|
| Ready for production | Automated grade A/B, no critical findings, manual gate = Pass |
| Ready with follow-ups | Automated grade A/B, no critical findings, manual gate = Advisory |
| Needs work | Any critical findings, automated grade C/D, or manual gate = Blocking |
| Failing | Automated grade F |
Step 5: Generate Quality Report
Use the template in [report-format.md](references/report-format.md) to produce the final report. Default to the compact format for initial output and expand sections on request.
The report includes:
- Executive summary with automated grade and final recommendation
- Manual review gate outcome (
Pass,Advisory, orBlocking) - Scores by category with visual indicators
- Detailed findings organized by severity
- Specific code locations and recommendations
- Checklist of required actions
---
Quick Validation Mode
For a rapid quality check without full analysis:
1. Run linter: npx @salesforce-ux/slds-linter@latest lint <path> 2. Count violations by type 3. Report summary only
Quick Quality Check: <component-name>
─────────────────────────────────────
Linter Violations:
• Class Override: 0
• Deprecated Tokens: 3
• Hardcoded Values: 5
Quick Automated Grade: C (estimated)
Run full validation for detailed report.---
Edge Cases and False Positives
| Situation | Guidance |
|---|---|
| Headless components (JS-only, no HTML) | Skip HTML checks; score only CSS + linter categories |
| Wrapper/container components | May legitimately have minimal CSS; don't penalize low hook usage |
| Intentional native elements | <button> inside custom SLDS blueprints is correct; suppress C002 if inside an slds-* blueprint structure |
| Components outside LEX | LWR/Experience Cloud components may not use Lightning Base Components; note context in report |
| Test/demo components | Lower the bar — note in report but don't block on warnings |
If a check produces a false positive, note it in the report as "suppressed" with justification rather than silently dropping it.
---
References
- [Quality Checks](references/quality-checks.md) - Complete list of all quality checks with detection patterns
- [Report Format](references/report-format.md) - Quality report template and formatting guide
- [Analyze Script](scripts/analyze-quality.cjs) - Automated analysis for linter-complementary checks
- uplifting-components-to-slds2 skill - How to fix linter violations
- applying-slds skill - Guide for building new components with correct patterns
SLDS Quality Checks Reference
Complete catalog of quality checks performed during SLDS component validation.
Scope note: The SLDS linter already catches class overrides (slds/class-override), deprecated tokens (slds/lwc-token-to-slds-hook), and hardcoded values (slds/no-hardcoded-values). The checks below cover what the linter does not catch. Linter violation counts are incorporated into the final score separately — see Step 1 in SKILL.md.
Detection Legend
| Symbol | Meaning |
|---|---|
| Script | Automated by analyze-quality.cjs |
| Linter | Caught by the SLDS linter |
| Manual | Requires agent review (Step 3) |
---
Table of Contents
- Theming and Styling Checks
- Accessibility Checks
- Code Quality Checks
- Component Usage Checks
- Detection Patterns
---
Theming and Styling Checks
Hook Fallbacks (not caught by linter)
| ID | Check | Severity | Detection | Pass Criteria |
|---|---|---|---|---|
| T002 | Fallback values present | Critical | Script | All var(--slds-g-*) include a fallback value |
Hook Family Pairing
| ID | Check | Severity | Detection | Pass Criteria |
|---|---|---|---|---|
| T010 | File-level hook family pairing | Warning | Script | Each background hook family present in a file has a matching on-* family present somewhere in the same file |
| T011 | Surface/container pairing correctness | Warning | Manual | surface-* and surface-container-* backgrounds are paired with appropriate on-surface-* text in the same selector/context |
| T012 | Accent pairing correctness | Warning | Manual | accent-* and accent-container-* backgrounds are paired with appropriate on-accent-* text in the same selector/context |
| T013 | Feedback pairing correctness | Warning | Manual | Feedback colors are paired with the correct on-error-*, on-warning-*, on-success-*, or on-info-* text hooks in the same selector/context |
Spacing Hook Usage
| ID | Check | Severity | Detection | Pass Criteria |
|---|---|---|---|---|
| T020 | Spacing uses hooks | Warning | Manual | Spacing uses var(--slds-g-spacing-*) or utilities |
| T021 | No magic pixel values | Warning | Script | No arbitrary px values for spacing |
| T022 | Base-8 alignment | Info | Manual | Spacing values align to 4, 8, 12, 16, 24, 32, 48px |
Typography Hook Usage
| ID | Check | Severity | Detection | Pass Criteria |
|---|---|---|---|---|
| T030 | Font family hooks | Warning | Manual | font-family uses var(--slds-g-font-family-*) |
| T031 | Font size hooks | Warning | Manual | font-size uses var(--slds-g-font-scale-*) or var(--slds-g-font-size-base) — NOT var(--slds-g-font-size-N) |
| T032 | Font weight hooks | Warning | Manual | font-weight uses var(--slds-g-font-weight-*) |
| T033 | Line height hooks | Info | Manual | line-height uses var(--slds-g-font-line-height-*) |
Other Styling Hooks
| ID | Check | Severity | Detection | Pass Criteria |
|---|---|---|---|---|
| T040 | Shadow hooks | Warning | Manual | Shadows use var(--slds-g-shadow-*) |
| T041 | Border radius hooks | Warning | Manual | Border radius uses var(--slds-g-radius-*) |
| T042 | Border width hooks | Info | Manual | Border width uses var(--slds-g-border-width-*) |
Hook Validity
| ID | Check | Severity | Detection | Pass Criteria |
|---|---|---|---|---|
| T050 | Color hooks numbered | Warning | Manual | Every --slds-g-color-* hook ends in a number (no bare on-surface, on-accent, etc.) |
| T051 | No invented hooks | Critical | Script | Every --slds-g-* hook referenced actually exists in metadata/hooks-index.json |
---
Accessibility Checks
Labels and Names
| ID | Check | Severity | Detection | Pass Criteria |
|---|---|---|---|---|
| A001 | Input labels | Critical | Script | All <lightning-input> have label attribute |
| A002 | Button names | Critical | Manual | All <button>, <lightning-button> have accessible names |
| A003 | Link names | Critical | Manual | All <a> have descriptive text content |
| A004 | Icon alt text | Critical | Script | All icons have alternative-text or empty for decorative |
| A005 | Image alt text | Critical | Script | All <img> have alt attribute |
ARIA and Semantics
| ID | Check | Severity | Detection | Pass Criteria |
|---|---|---|---|---|
| A010 | Heading hierarchy | Warning | Script | H1 → H2 → H3 without skipping |
| A011 | ARIA roles | Warning | Manual | role attributes used correctly |
| A012 | ARIA labels | Warning | Manual | aria-label, aria-labelledby used appropriately |
| A013 | ARIA live | Info | Manual | Dynamic content uses aria-live regions |
| A014 | ARIA invalid | Warning | Manual | Invalid form fields have aria-invalid="true" |
Keyboard and Focus
| ID | Check | Severity | Detection | Pass Criteria |
|---|---|---|---|---|
| A020 | Tab order | Warning | Script | tabindex values are 0 or -1 only |
| A021 | Focus visible | Warning | Script | No outline: none without alternative focus style |
| A022 | Interactive elements | Warning | Script | Clickable elements are <button> or <a> |
| A023 | Focus management | Info | Manual | Modals trap focus, return focus on close |
Visual Accessibility
| ID | Check | Severity | Detection | Pass Criteria |
|---|---|---|---|---|
| A030 | Color not sole indicator | Warning | Manual | Status/errors use icon or text, not just color |
| A031 | Touch targets | Info | Manual | Interactive elements >= 44x44px on mobile |
| A032 | Text sizing | Info | Manual | Text can scale without breaking layout |
---
Code Quality Checks
CSS Anti-patterns
| ID | Check | Severity | Detection | Pass Criteria |
|---|---|---|---|---|
| Q001 | No !important | Warning | Script | No !important declarations |
| Q002 | No inline styles (HTML) | Warning | Script | No style="..." attributes in HTML |
| Q025 | No inline styles (JS) | Warning | Script | No .style.*= direct property assignment in JS |
| Q003 | No deep nesting | Info | Manual | Selectors <= 3 levels deep |
| Q004 | No ID selectors | Info | Manual | No #id in CSS selectors |
| Q005 | No universal selectors | Info | Manual | No * in CSS selectors |
Naming Conventions
| ID | Check | Severity | Detection | Pass Criteria |
|---|---|---|---|---|
| Q010 | Component prefix | Warning | Manual | Custom classes use component prefix |
| Q011 | CamelCase prefix | Warning | Manual | Prefix follows camelCase convention |
| Q012 | Avoid dynamic SLDS class manipulation | Warning | Script | Avoid .classList.add/remove/toggle('slds-*') patterns in JS |
| Q013 | BEM consistency | Info | Manual | Class names follow consistent BEM pattern |
Maintainability
| ID | Check | Severity | Detection | Pass Criteria |
|---|---|---|---|---|
| Q020 | No magic numbers | Warning | Manual | All numeric values have clear purpose |
| Q021 | Z-index scale | Warning | Script | Z-index values follow defined scale |
| Q022 | No fixed dimensions | Warning | Manual | Avoid fixed width/height in px |
| Q023 | CSS file size | Info | Manual | CSS file < 500 lines |
---
Component Usage Checks
Lightning Base Components
| ID | Check | Severity | Detection | Pass Criteria |
|---|---|---|---|---|
| C001 | Use LBC inputs | Warning | Script | Use <lightning-input> not <input> |
| C002 | Use LBC buttons | Warning | Script | Use <lightning-button> not <button> |
| C003 | Use LBC icons | Warning | Manual | Use <lightning-icon> not custom SVG |
| C004 | Use LBC combobox | Warning | Script | Use <lightning-combobox> not <select> |
| C005 | Use LBC datatable | Info | Manual | Use <lightning-datatable> for tables |
SLDS Blueprint Compliance
| ID | Check | Severity | Detection | Pass Criteria |
|---|---|---|---|---|
| C010 | Card structure | Warning | Manual | Cards use slds-card class structure |
| C011 | Modal structure | Warning | Manual | Modals use slds-modal class structure |
| C012 | Form structure | Warning | Manual | Forms use slds-form or slds-form-element |
| C013 | Button variants | Info | Manual | Buttons use slds-button_* variants |
Semantic HTML
| ID | Check | Severity | Detection | Pass Criteria |
|---|---|---|---|---|
| C020 | Use button element | Warning | Manual | Clickable elements use <button> |
| C021 | Use nav element | Info | Manual | Navigation uses <nav> |
| C022 | Use article element | Info | Manual | Self-contained content uses <article> |
| C023 | Use section element | Info | Manual | Thematic grouping uses <section> |
| C024 | No div soup | Info | Manual | Meaningful elements used over nested <div> |
---
Detection Patterns
Regex Patterns for CSS Analysis
Hardcoded colors, SLDS class overrides, and deprecated LWC tokens are already caught by the SLDS linter. These patterns cover supplementary checks only.
// Missing fallback — matches var(--slds-g-*) with NO comma before closing paren
const MISSING_FALLBACK = /var\(--slds-g-[^,)]+\)/g;
// !important usage
const IMPORTANT = /!important/g;
// Magic pixel spacing values (not inside a var() fallback)
const MAGIC_PX = /\b(?:margin(?:-[a-z-]+)?|padding(?:-[a-z-]+)?|gap|row-gap|column-gap)\s*:\s*\d+px\b(?![^;]*var\()/g;
// High z-index (3+ digits)
const HIGH_ZINDEX = /z-index\s*:\s*(\d{3,})/g;
// Focus outline removed
const OUTLINE_NONE = /outline\s*:\s*none/g;Regex Patterns for HTML Analysis
Native<input>labeling via<label for="">requires cross-element analysis that regex cannot handle reliably. The checks below focus on Lightning Base Component attributes and structural issues.
// Lightning input without label attribute
const LBC_INPUT_NO_LABEL = /<lightning-input(?![^>]*\blabel\b)[^>]*>/gi;
// Icon without alternative-text
const ICON_NO_ALT = /<lightning-icon(?![^>]*alternative-text)[^>]*>/gi;
// Image without alt
const IMG_NO_ALT = /<img(?![^>]*\balt\b)[^>]*>/gi;
// Inline styles
const INLINE_STYLE = /style\s*=\s*["'][^"']+["']/gi;
// Positive tabindex (should be 0 or -1 only)
const TABINDEX_POSITIVE = /tabindex\s*=\s*["']([1-9]\d*)["']/gi;
// Heading hierarchy (track sequence to detect skipped levels)
const HEADINGS = /<h([1-6])[^>]*>/gi;
// Div with click handler (should be button)
const CLICKABLE_DIV = /<div[^>]*onclick[^>]*>/gi;
// Native elements where LBC alternatives exist (info-level)
const NATIVE_INPUT = /<input\s/gi;
const NATIVE_BUTTON = /<button\s/gi;
const NATIVE_SELECT = /<select\s/gi;File Analysis Strategy
1. CSS Files: Parse with regex, track line numbers, categorize findings; cross-reference hooks against hooks-index.json (T051) 2. HTML Files: Parse with regex, validate structure, check attributes 3. JS Files: Check for inline style assignment (.style.*=) and dynamic SLDS class manipulation (.classList.add('slds-*')) 4. Cross-file/manual: Review relationships between files that regex cannot validate reliably
---
Severity Levels
| Level | Weight | Action Required |
|---|---|---|
| Critical | -10 pts | Must fix before deployment |
| Warning | -3 pts | Should fix, review if acceptable |
| Info | -1 pt | Nice to fix, no blocking |
---
Category Scoring
The script outputs individual category scores. It does not produce a combined overall grade — the agent computes that using the formula in SKILL.md Step 4:
Overall = (Linter × 0.30) + (Theming × 0.20) + (Accessibility × 0.20)
+ (CodeQuality × 0.15) + (ComponentUsage × 0.15)Linter Compliance is scored separately from linter output (count violations × 10, min 0).
Automation Coverage
The script automates 17 of 53 checks listed above (marked Script in the Detection column). The remaining 36 require agent manual review (Step 3 in SKILL.md). Categories with fewer automated checks — especially Code Quality (4 of 13) and Component Usage (3 of 14) — will tend toward 100 when no automated findings exist. Treat the automated score as provisional: manual review findings must be reported separately and can block a production recommendation even when the score is high.
Theming
Score = 100 - (critical issues in category × 10)
- (warnings in category × 3)
- (info in category × 1)
Min: 0Accessibility
Score = 100 - (critical issues in category × 10)
- (warnings in category × 3)
- (info in category × 1)
Min: 0Code Quality
Score = 100 - (critical issues in category × 10)
- (warnings in category × 3)
- (info in category × 1)
Min: 0Component Usage
Score = 100 - (critical issues in category × 10)
- (warnings in category × 3)
- (info in category × 1)
Min: 0SLDS Quality Report Format
Guidelines for generating quality reports. Default to the compact format and expand sections when the user requests detail.
---
Default: Compact Report
Always start with this format. It gives the user the full picture in a glanceable summary.
````markdown
SLDS Quality Scorecard: {component-name}
Path: {component-path} | Complexity: {small|medium|large} ({n} files, {n} lines) Generated: {date}
Automated Grade: {grade} ({score}/100)
{grade-description}
Manual Review Gate: {Pass|Advisory|Blocking} Final Recommendation: {Ready for production|Ready with follow-ups|Needs work|Failing}
| Category | Score | Grade |
|---|---|---|
| Linter Compliance | {score}/100 | {status-emoji} {grade} |
| Theming | {score}/100 | {status-emoji} {grade} |
| Accessibility | {score}/100 | {status-emoji} {grade} |
| Code Quality | {score}/100 | {status-emoji} {grade} |
| Component Usage | {score}/100 | {status-emoji} {grade} |
Issues: {n} critical | {n} warnings | {n} info
Top Issues
1. {issue} — {file}:{line} — {recommendation} 2. {issue} — {file}:{line} — {recommendation} 3. {issue} — {file}:{line} — {recommendation}
Automated score reflects linter + script findings only. Manual review can still block ship.
>
{accessibility-disclaimer-if-scored}
Ask for the full report to see all findings, code examples, and action items. ````
When to Show Compact
- First response to a quality audit request
- Quick validation mode
- Auditing multiple components (show compact for each)
---
Expanded: Full Report
Show this when the user asks to "expand", "show details", "full report", or "show all findings". Build on top of the compact report — don't repeat the summary, just add the detail sections below it.
````markdown ---
Critical Issues ({count})
Issues that must be fixed before deployment.
{issue-category}
| # | File | Line | Issue | Recommendation |
|---|---|---|---|---|
| 1 | {file} | {line} | {description} | {fix} |
| 2 | {file} | {line} | {description} | {fix} |
Example fix:
/* Before */
{problematic-code}
/* After */
{fixed-code}---
Warnings ({count})
Issues that should be fixed but are not blocking.
| # | File | Line | Issue | Impact |
|---|---|---|---|---|
| 1 | {file} | {line} | {description} | {impact} |
---
Info ({count})
Suggestions for improvement.
| # | Category | Finding | Suggestion |
|---|---|---|---|
| 1 | {category} | {finding} | {suggestion} |
---
Detailed Findings
Manual Review Gate
Gate: {Pass|Advisory|Blocking}
| Review Area | Outcome | Notes |
|---|---|---|
| Loading states | {Pass | Advisory |
| Error states | {Pass | Advisory |
| Empty states | {Pass | Advisory |
| Disabled states | {Pass | Advisory |
| Semantic HTML | {Pass | Advisory |
| Blueprint compliance | {Pass | Advisory |
---
Linter Compliance
Violations Found: {count}
| Rule | Count | Files Affected |
|---|---|---|
slds/class-override | {count} | {files} |
slds/lwc-token-to-slds-hook | {count} | {files} |
slds/no-hardcoded-values | {count} | {files} |
<details> <summary>Full Linter Output</summary>
{linter-output}</details>
---
Theming
Hooks Usage Summary:
| Hook Type | Used | Missing Fallback | Issues |
|---|---|---|---|
| Color Hooks | {count} | {count} | {count} |
| Spacing Hooks | {count} | {count} | {count} |
| Typography Hooks | {count} | {count} | {count} |
Hook Pairing Analysis:
| Background Hook | Paired Text Hook | Status |
|---|---|---|
--slds-g-color-surface-1 | --slds-g-color-on-surface-2 | {status} |
---
Accessibility
This section checks attribute presence only. It does not validate contrast ratios, keyboard flows, or screen reader behavior. Passing here does not guarantee WCAG compliance.
| Check | Status | Details |
|---|---|---|
| Lightning input labels | {status} | {count} inputs, {count} labeled |
| Icon alternative text | {status} | {count} icons, {count} with alt |
| Image alt attributes | {status} | {count} images, {count} with alt |
| Heading hierarchy | {status} | {sequence} |
| Focus indicators | {status} | {findings} |
---
Code Quality
| Metric | Value | Status |
|---|---|---|
| Total CSS lines | {count} | {status} |
| !important usage | {count} | {status} |
| Inline styles | {count} | {status} |
| High z-index values | {count} | {status} |
---
Component Usage
| Element Type | Native Count | LBC Alternative | Recommendation |
|---|---|---|---|
| Inputs | {count} | <lightning-input> | {recommendation} |
| Buttons | {count} | <lightning-button> | {recommendation} |
| Selects | {count} | <lightning-combobox> | {recommendation} |
---
Action Items
Must Fix (Critical)
- [ ] {action-item}
Should Fix (Warnings)
- [ ] {action-item}
Nice to Have (Info)
- [ ] {action-item}
---
Next Steps
1. Address all {count} critical issues immediately 2. Review and fix {count} warnings before code review 3. Consider {count} suggestions for future improvements 4. Re-run validation to confirm fixes
Estimated Effort: {estimate} ````
---
JSON Output
For programmatic consumption (e.g., CI integration or tracking over time). Produce this only when explicitly requested or when auditing multiple components for comparison.
{
"component": "{component-name}",
"path": "{component-path}",
"timestamp": "{iso-date}",
"complexity": {
"classification": "medium",
"totalFiles": 4,
"totalLines": 280
},
"scores": {
"automatedOverall": 85,
"automatedGrade": "B",
"categories": {
"linter": { "score": 100, "grade": "A" },
"theming": { "score": 80, "grade": "B" },
"accessibility": { "score": 75, "grade": "C" },
"codeQuality": { "score": 90, "grade": "A" },
"componentUsage": { "score": 85, "grade": "B" }
}
},
"manualReview": {
"gate": "Advisory",
"findings": []
},
"finalRecommendation": "Ready with follow-ups",
"findings": {
"critical": [],
"warnings": [],
"info": []
},
"summary": {
"filesAnalyzed": 4,
"totalLines": 280,
"critical": 0,
"warnings": 2,
"info": 3
}
}---
Status Indicators
| Score Range | Emoji | Meaning |
|---|---|---|
| 90-100 | ✅ | Excellent |
| 80-89 | 🟢 | Good |
| 70-79 | 🟡 | Acceptable |
| 60-69 | 🟠 | Needs Work |
| 0-59 | 🔴 | Critical |
---
Grade Descriptions
| Grade | Description |
|---|---|
| A | Excellent - Strong automated result. Requires a passing manual review gate before calling it production-ready. |
| B | Good - Solid automated result. Requires manual review before a production recommendation. |
| C | Acceptable - Automated issues should be addressed before production. |
| D | Needs Work - Significant automated issues require attention before code review. |
| F | Critical - Automated checks found blocking issues. Not suitable for deployment. |
---
Report Delivery Guidelines
1. Always default to compact — show the scorecard first, expand on request 2. Separate automated grade from final recommendation — manual review can override ship readiness 3. Group by severity — critical issues first, then warnings, then info 4. Include actionable recommendations — every finding should have a clear fix 5. Provide code examples — show before/after for complex fixes in the expanded report 6. Note complexity — a "B" on a large component means something different than a "B" on a small one 7. Add accessibility disclaimer — when the accessibility score is included, note it checks attribute presence only
#!/usr/bin/env node
/**
* SLDS Quality Analyzer
*
* Analyzes CSS and HTML files for SLDS quality issues beyond what the linter catches.
*
* Usage: node analyze-quality.cjs <component-path> [--hooks-index <path>]
*
* Output: JSON with findings categorized by severity
*/
const fs = require('fs');
const path = require('path');
function resolveHooksIndexPath(args) {
const idx = args.indexOf('--hooks-index');
if (idx !== -1 && idx + 1 < args.length) {
return path.resolve(args[idx + 1]);
}
return null;
}
let HOOKS_INDEX_PATH = null;
// Severity levels
const CRITICAL = 'critical';
const WARNING = 'warning';
const INFO = 'info';
// Detection patterns
// NOTE: Checks that the SLDS linter already handles are excluded here to avoid
// double-counting. The linter covers: slds/class-override (L001),
// slds/lwc-token-to-slds-hook (L002), slds/no-hardcoded-values (L003).
// This script focuses on what the linter does NOT catch.
const PATTERNS = {
// CSS patterns (linter-complementary only)
css: {
missingFallback: {
pattern: /var\(--slds-g-[^,)]+\)/g,
severity: CRITICAL,
id: 'T002',
message: 'SLDS hook without fallback value',
recommendation: 'Add fallback: var(--slds-g-color-surface-1, #fff)'
},
important: {
pattern: /!important/g,
severity: WARNING,
id: 'Q001',
message: '!important declaration found',
recommendation: 'Remove !important, use proper specificity'
},
magicPixels: {
pattern: /\b(?:margin(?:-[a-z-]+)?|padding(?:-[a-z-]+)?|gap|row-gap|column-gap)\s*:\s*(\d+)px\b(?![^;]*var\()/g,
severity: WARNING,
id: 'T021',
message: 'Magic pixel value not using spacing hook',
recommendation: 'Use var(--slds-g-spacing-*) or utility class'
},
highZindex: {
pattern: /z-index\s*:\s*(\d{3,})/g,
severity: WARNING,
id: 'Q021',
message: 'High z-index value',
recommendation: 'Use defined z-index scale'
},
outlineNone: {
pattern: /outline\s*:\s*none/g,
severity: WARNING,
id: 'A021',
message: 'Focus outline removed without alternative',
recommendation: 'Provide alternative focus indicator'
}
},
// JS patterns (inline styles and dynamic class manipulation)
js: {
inlineStyleJS: {
pattern: /\.style\.\w+\s*=/g,
severity: WARNING,
id: 'Q025',
message: 'Inline style manipulation in JavaScript',
recommendation: 'Use CSS classes instead of direct style property assignment'
},
classListManipulation: {
pattern: /\.classList\.(add|remove|toggle)\(\s*['"]slds-/g,
severity: WARNING,
id: 'Q012',
message: 'Dynamic SLDS class manipulation in JavaScript',
recommendation: 'Prefer declarative class bindings; avoid manipulating slds-* classes directly'
}
},
// HTML patterns
html: {
inlineStyle: {
pattern: /style\s*=\s*["'][^"']+["']/gi,
severity: WARNING,
id: 'Q002',
message: 'Inline style attribute',
recommendation: 'Move styles to CSS file'
},
lightningInputNoLabel: {
pattern: /<lightning-input(?![^>]*\blabel\b)[^>]*>/gi,
severity: CRITICAL,
id: 'A001',
message: 'Lightning input without label attribute',
recommendation: 'Add label attribute to lightning-input'
},
iconNoAlt: {
pattern: /<lightning-icon(?![^>]*alternative-text)[^>]*>/gi,
severity: CRITICAL,
id: 'A004',
message: 'Icon without alternative-text',
recommendation: 'Add alternative-text (or empty string for decorative)'
},
imgNoAlt: {
pattern: /<img(?![^>]*\balt\b)[^>]*>/gi,
severity: CRITICAL,
id: 'A005',
message: 'Image without alt attribute',
recommendation: 'Add alt attribute'
},
positiveTabindex: {
pattern: /tabindex\s*=\s*["']([1-9]\d*)["']/gi,
severity: WARNING,
id: 'A020',
message: 'Positive tabindex value',
recommendation: 'Use tabindex="0" or "-1" only'
},
clickableDiv: {
pattern: /<div[^>]*onclick[^>]*>/gi,
severity: WARNING,
id: 'A022',
message: 'Div with click handler instead of button',
recommendation: 'Use <button> or <lightning-button> for interactive elements'
},
nativeInput: {
pattern: /<input\s/gi,
severity: WARNING,
id: 'C001',
message: 'Native input element',
recommendation: 'Consider <lightning-input> for built-in labeling and validation'
},
nativeButton: {
pattern: /<button\s(?![^>]*class\s*=\s*["'][^"']*slds-button)/gi,
severity: WARNING,
id: 'C002',
message: 'Native button element',
recommendation: 'Consider <lightning-button> for SLDS styling consistency (suppressed if slds-button class present)'
},
nativeSelect: {
pattern: /<select\s/gi,
severity: WARNING,
id: 'C004',
message: 'Native select element',
recommendation: 'Consider <lightning-combobox> for consistency'
}
}
};
/**
* Find all files with given extensions in directory
*/
function findFiles(dir, extensions) {
const files = [];
function walk(currentDir) {
try {
const items = fs.readdirSync(currentDir);
for (const item of items) {
const fullPath = path.join(currentDir, item);
const stat = fs.statSync(fullPath);
if (stat.isDirectory() && !item.startsWith('.') && item !== 'node_modules') {
walk(fullPath);
} else if (stat.isFile()) {
const ext = path.extname(item).toLowerCase();
if (extensions.includes(ext)) {
files.push(fullPath);
}
}
}
} catch (err) {
// Skip directories we can't read
}
}
walk(dir);
return files;
}
/**
* Analyze a single file
*/
function analyzeFile(filePath, patterns) {
const findings = [];
const content = fs.readFileSync(filePath, 'utf-8');
const lines = content.split('\n');
for (const [name, config] of Object.entries(patterns)) {
const regex = new RegExp(config.pattern.source, config.pattern.flags);
let match;
while ((match = regex.exec(content)) !== null) {
// Find line number
const beforeMatch = content.substring(0, match.index);
const lineNumber = beforeMatch.split('\n').length;
const lineContent = lines[lineNumber - 1] || '';
findings.push({
id: config.id,
severity: config.severity,
file: filePath,
line: lineNumber,
column: match.index - beforeMatch.lastIndexOf('\n'),
match: match[0].substring(0, 50),
message: config.message,
recommendation: config.recommendation,
context: lineContent.trim().substring(0, 80)
});
}
}
return findings;
}
/**
* Analyze heading hierarchy in HTML
*/
function analyzeHeadings(filePath) {
const findings = [];
const content = fs.readFileSync(filePath, 'utf-8');
const headingRegex = /<h([1-6])[^>]*>/gi;
const headings = [];
let match;
while ((match = headingRegex.exec(content)) !== null) {
headings.push({
level: parseInt(match[1]),
index: match.index
});
}
// Check for skipped levels
for (let i = 1; i < headings.length; i++) {
const prev = headings[i - 1].level;
const curr = headings[i].level;
if (curr > prev + 1) {
const beforeMatch = content.substring(0, headings[i].index);
const lineNumber = beforeMatch.split('\n').length;
findings.push({
id: 'A010',
severity: WARNING,
file: filePath,
line: lineNumber,
message: `Skipped heading level: h${prev} to h${curr}`,
recommendation: `Use h${prev + 1} instead of h${curr}`
});
}
}
return findings;
}
/**
* Load valid hook tokens from hooks-index.json
*/
let _validHooks = null;
function loadValidHooks() {
if (_validHooks) return _validHooks;
if (!HOOKS_INDEX_PATH) return null;
try {
const data = JSON.parse(fs.readFileSync(HOOKS_INDEX_PATH, 'utf-8'));
_validHooks = new Set(data.hooks.map(h => h.token));
} catch {
console.error(`WARNING: Could not load hooks-index.json at ${HOOKS_INDEX_PATH}`);
console.error('Invented-hook detection (T051) will be skipped.');
_validHooks = null;
}
return _validHooks;
}
/**
* Check for invented hooks (T051) — hooks referenced in CSS that don't exist in metadata
*/
function analyzeInventedHooks(filePath) {
const findings = [];
const validHooks = loadValidHooks();
if (!validHooks) return findings; // skip if metadata unavailable
const content = fs.readFileSync(filePath, 'utf-8');
const lines = content.split('\n');
const hookRef = /var\((--slds-g-[^,)]+)/g;
let match;
while ((match = hookRef.exec(content)) !== null) {
const hookName = match[1].trim();
if (!validHooks.has(hookName)) {
const beforeMatch = content.substring(0, match.index);
const lineNumber = beforeMatch.split('\n').length;
const lineContent = lines[lineNumber - 1] || '';
findings.push({
id: 'T051',
severity: CRITICAL,
file: filePath,
line: lineNumber,
match: hookName,
message: `Invented hook — "${hookName}" does not exist in hooks-index.json`,
recommendation: 'Verify the hook exists via: node scripts/search-hooks.cjs --prefix "' + hookName + '"',
context: lineContent.trim().substring(0, 80)
});
}
}
return findings;
}
/**
* Check for hook pairing issues
*/
function analyzeHookPairing(filePath) {
const findings = [];
const content = fs.readFileSync(filePath, 'utf-8');
// Find all background hooks
const bgHookRegex = /--slds-g-color-(surface|accent|success|warning|error|info)(?:-container)?-\d/g;
const textHookRegex = /--slds-g-color-on-(surface|accent|success|warning|error|info)(?:-container)?-\d/g;
const bgHooks = content.match(bgHookRegex) || [];
const textHooks = content.match(textHookRegex) || [];
// Extract families
const bgFamilies = new Set(bgHooks.map(h => {
const match = h.match(/--slds-g-color-(\w+(?:-container)?)-\d/);
return match ? match[1] : null;
}).filter(Boolean));
const textFamilies = new Set(textHooks.map(h => {
const match = h.match(/--slds-g-color-on-(\w+(?:-container)?)-\d/);
return match ? match[1] : null;
}).filter(Boolean));
// Check for mismatches
for (const bgFamily of bgFamilies) {
const expectedTextFamily = bgFamily.replace('-container', '');
if (!textFamilies.has(expectedTextFamily) && !textFamilies.has(bgFamily)) {
findings.push({
id: 'T010',
severity: WARNING,
file: filePath,
message: `Background hook family '${bgFamily}' may lack matching text hook`,
recommendation: `Pair with --slds-g-color-on-${expectedTextFamily}-*`
});
}
}
return findings;
}
/**
* Calculate scores from findings
*/
function calculateScores(findings) {
const weights = {
[CRITICAL]: 10,
[WARNING]: 3,
[INFO]: 1
};
// NOTE: Linter findings (L001, L002, L003) come from the SLDS linter output,
// not from this script. They should be merged in by the calling agent.
// This script only produces findings for the other categories.
const categories = {
theming: { issues: 0, ids: ['T002', 'T010', 'T011', 'T021', 'T051'] },
accessibility: { issues: 0, ids: ['A001', 'A004', 'A005', 'A010', 'A020', 'A021', 'A022'] },
codeQuality: { issues: 0, ids: ['Q001', 'Q002', 'Q012', 'Q021', 'Q025'] },
componentUsage: { issues: 0, ids: ['C001', 'C002', 'C004'] }
};
// Count weighted issues per category
for (const finding of findings) {
const weight = weights[finding.severity];
for (const [category, config] of Object.entries(categories)) {
if (config.ids.includes(finding.id)) {
config.issues += weight;
break;
}
}
}
// Calculate scores
const scores = {};
for (const [category, config] of Object.entries(categories)) {
scores[category] = Math.max(0, 100 - config.issues);
}
return scores;
}
/**
* Get grade from score
*/
function getGrade(score) {
if (score >= 90) return 'A';
if (score >= 80) return 'B';
if (score >= 70) return 'C';
if (score >= 60) return 'D';
return 'F';
}
/**
* Main analysis function
*/
function analyze(componentPath) {
const resolvedPath = path.resolve(componentPath);
if (!fs.existsSync(resolvedPath)) {
console.error(`Error: Path does not exist: ${resolvedPath}`);
process.exit(1);
}
const findings = [];
// Find and analyze CSS files
const cssFiles = findFiles(resolvedPath, ['.css']);
for (const file of cssFiles) {
findings.push(...analyzeFile(file, PATTERNS.css));
findings.push(...analyzeHookPairing(file));
findings.push(...analyzeInventedHooks(file));
}
// Find and analyze HTML files
const htmlFiles = findFiles(resolvedPath, ['.html']);
for (const file of htmlFiles) {
findings.push(...analyzeFile(file, PATTERNS.html));
findings.push(...analyzeHeadings(file));
}
// Find and analyze JS files
const jsFiles = findFiles(resolvedPath, ['.js']);
for (const file of jsFiles) {
findings.push(...analyzeFile(file, PATTERNS.js));
}
// Calculate scores
const scores = calculateScores(findings);
// Organize findings by severity
const organized = {
critical: findings.filter(f => f.severity === CRITICAL),
warning: findings.filter(f => f.severity === WARNING),
info: findings.filter(f => f.severity === INFO)
};
// Calculate total lines for complexity classification
let totalLines = 0;
for (const file of [...cssFiles, ...htmlFiles, ...jsFiles]) {
totalLines += fs.readFileSync(file, 'utf-8').split('\n').length;
}
const totalFiles = cssFiles.length + htmlFiles.length + jsFiles.length;
let complexity = 'small';
if (totalFiles >= 7 || totalLines >= 500) complexity = 'large';
else if (totalFiles >= 3 || totalLines >= 100) complexity = 'medium';
// Build result
const result = {
component: path.basename(resolvedPath),
path: resolvedPath,
timestamp: new Date().toISOString(),
complexity: {
classification: complexity,
totalFiles,
totalLines
},
note: "These are automated category scores only. Combine them with SLDS linter results and the required Step 3 manual review gate in SKILL.md before making a final ship recommendation.",
scores: {
theming: { score: scores.theming, grade: getGrade(scores.theming) },
accessibility: { score: scores.accessibility, grade: getGrade(scores.accessibility) },
codeQuality: { score: scores.codeQuality, grade: getGrade(scores.codeQuality) },
componentUsage: { score: scores.componentUsage, grade: getGrade(scores.componentUsage) }
},
findings: organized,
summary: {
filesAnalyzed: totalFiles,
cssFiles: cssFiles.length,
htmlFiles: htmlFiles.length,
jsFiles: jsFiles.length,
totalLines,
critical: organized.critical.length,
warnings: organized.warning.length,
info: organized.info.length
}
};
return result;
}
// CLI entry point
if (require.main === module) {
const args = process.argv.slice(2);
const positionalArgs = args.filter((a, i) => !a.startsWith('--') && (i === 0 || !args[i - 1].startsWith('--')));
if (positionalArgs.length === 0) {
console.log('SLDS Quality Analyzer');
console.log('Usage: node analyze-quality.cjs <component-path> [--hooks-index <path>]');
console.log('');
console.log('Options:');
console.log(' --hooks-index <path> Path to hooks-index.json (optional; enables T051 invented-hook detection)');
console.log('');
console.log('Output: JSON analysis of SLDS quality issues');
process.exit(0);
}
HOOKS_INDEX_PATH = resolveHooksIndexPath(args);
const result = analyze(positionalArgs[0]);
console.log(JSON.stringify(result, null, 2));
}
module.exports = { analyze, PATTERNS };
Related skills
How it compares
Choose validating-slds over generic frontend linters when the target is Salesforce LWC with SLDS-specific theming hooks and scorecard-style grading.
FAQ
What does validating-slds check in an LWC?
validating-slds runs the SLDS linter, reviews CSS for theming hook usage and pairing, inspects HTML accessibility attributes, and rolls findings into category scores plus an overall grade for manual review.
When should developers run validating-slds?
validating-slds fits pre-code-review and pre-submission checks when a developer wants an SLDS scorecard, quality report, or readiness audit on a Lightning Web Component.