All files / packages/sds-customization-compliance/src/checks hook-mechanism-fit.ts

100% Statements 43/43
85% Branches 17/20
100% Functions 8/8
100% Lines 40/40

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194                                                                          4x                                                                                                     24x               9x       6x 6x                         35x 35x 35x 24x   35x   35x       27x 27x 27x 27x 27x             27x 8x 8x 8x 8x   8x   35x       24x 24x 65x 65x 30x               35x 35x 65x 29x               6x 6x                     4x 4x 4x 4x     4x     4x  
/**
 * Six compliance checks that operationalize the property-risk and
 * property-demand RFC docs. Each check filters the recommendation
 * engine in `helpers/propertyMetadata.ts` to a single `caseId` and
 * emits an offender per hook that triggers it.
 *
 * The split into six checks (rather than one mixed-severity check)
 * matches the existing scorecard convention: each compliance row
 * covers a single, named gap so authors can act on it without
 * decoding a multi-case detail string.
 */
 
import type { ComplianceCheck, ComplianceRow, Offender } from '../types.js';
import { resolveHookPrefix } from './helpers/resolveHookPrefix.js';
import { classifyHook } from './helpers/classifyHook.js';
import {
  MECHANISM_PATHS,
  computeHookCoverageMap,
  fallbackEmptyCoverage,
  listAllPublicHooks,
  recommendForHook,
  resolveHookMetadata,
  type Recommendation,
  type MechanismPathKey,
} from './helpers/propertyMetadata.js';
import { NOT_MIGRATED_DETAIL } from './helpers/themeDataAccess.js';
 
interface CaseDescriptor {
  id: string;
  label: string;
  caseId: Recommendation['caseId'];
  /** Severity to surface on the row. `fail` → customer-reach, `review` → cascade-hygiene. */
  severity: 'fail' | 'review';
  /** One-line explanation of the case for the row's `detail` text. */
  caseRationale: string;
}
 
const CASES: CaseDescriptor[] = [
  {
    id: 'hook-high-risk-partial-coverage',
    label: 'High-risk hooks must not have partial theme coverage',
    caseId: 'high-risk-partial',
    severity: 'fail',
    caseRationale:
      'A high-risk property exposed as a base-contract hook with only some themes assigning it. Customers or future themes that set the hook get inconsistent rendering across themes.',
  },
  {
    id: 'hook-high-risk-empty-coverage',
    label: 'High-risk hooks must not be exposed with no theme coverage',
    caseId: 'high-risk-empty',
    severity: 'fail',
    caseRationale:
      "A high-risk property exposed as a per-component hook with no theme assignments. The hook surface invites customers to override a property that shouldn't vary per component.",
  },
  {
    id: 'hook-high-risk-base-contract-shape',
    label: 'High-risk hooks should not live in the base contract',
    caseId: 'high-risk-full',
    severity: 'review',
    caseRationale:
      "A high-risk property fully covered across themes, but the property's effect (layout, stacking, rendering surprises) makes it a poor customer-customization surface even when every theme assigns it.",
  },
  {
    id: 'hook-medium-risk-partial-low-demand',
    label: 'Medium-risk hooks with partial coverage and low demand should be demoted',
    caseId: 'medium-risk-partial-low-demand',
    severity: 'fail',
    caseRationale:
      "A medium-risk property exposed as a base-contract hook with partial theme coverage AND low customer demand. The hook surface invites customers to set a value the missing theme can't render, with little customer benefit to justify it.",
  },
  {
    id: 'hook-medium-risk-partial-coverage',
    label: 'Medium-risk hooks must not have partial theme coverage',
    caseId: 'medium-risk-partial-mid-demand',
    severity: 'fail',
    caseRationale:
      'A medium-risk property exposed as a base-contract hook with partial theme coverage. Customers who set it get inconsistent rendering across themes; either every theme assigns it or it moves out of the base contract.',
  },
  {
    id: 'hook-medium-risk-empty-coverage',
    label: 'Medium-risk hooks with no theme coverage should consider direct paint',
    caseId: 'medium-risk-empty',
    severity: 'review',
    caseRationale:
      'A medium-risk property exposed as a per-component hook with no theme assignments. The property might be better served by direct global-token paint rather than a per-component hook customers can override.',
  },
];
 
const CASE_BY_ID = new Map(CASES.map((c) => [c.caseId, c]));
 
interface Finding {
  hookName: string;
  recommendation: Recommendation;
}
 
function pathSuggestionList(paths: readonly MechanismPathKey[]): string {
  return paths.map((p) => `\`${MECHANISM_PATHS[p].name}\``).join(', ');
}
 
function offenderFromFinding(finding: Finding): Offender {
  const { hookName, recommendation } = finding;
  return {
    hook: hookName,
    note: recommendation.headline,
    fix:
      `${recommendation.rationale} Suggested mechanism${recommendation.suggestedPaths.length === 1 ? '' : 's'}: ${pathSuggestionList(recommendation.suggestedPaths)}. ` +
      `See \`rfcs/text/1157-theme-layer/theme-layer-property-risk.md\` and \`rfcs/text/1157-theme-layer/theme-layer-property-demand.md\` for the governing tier tables.`,
  };
}
 
function evaluateAllHooks(
  themeData: NonNullable<Parameters<ComplianceCheck>[0]['themeData']>,
  componentName: string,
): Map<Recommendation['caseId'], Finding[]> {
  const componentPrefix = resolveHookPrefix(componentName);
  const coverageMap = computeHookCoverageMap(themeData);
  const emptyCoverage = fallbackEmptyCoverage(
    [...new Set(Object.keys(themeData.themes ?? {}))].sort((a, b) => a.localeCompare(b)),
  );
  const findings = new Map<Recommendation['caseId'], Finding[]>();
 
  for (const { hookName, category } of listAllPublicHooks(themeData)) {
    // Skip hooks classifyHook tells us aren't `--slds-c-{prefix}-*`
    // shaped (defensive — themeData should never include them, but
    // we don't want to misreport when component prefixes diverge).
    const cls = classifyHook(hookName, componentName);
    const resolvedCategory = cls.isColor ? cls.category : category;
    const meta = resolveHookMetadata(hookName, componentPrefix, resolvedCategory);
    const coverage = coverageMap.get(hookName) ?? emptyCoverage;
    const recommendation = recommendForHook({
      risk: meta.risk,
      demand: meta.demand,
      coverage,
      hookName,
      property: meta.property,
    });
    if (!recommendation) continue;
    let bucket = findings.get(recommendation.caseId);
    Eif (!bucket) {
      bucket = [];
      findings.set(recommendation.caseId, bucket);
    }
    bucket.push({ hookName, recommendation });
  }
  return findings;
}
 
function buildCheckForCase(descriptor: CaseDescriptor): ComplianceCheck {
  const { id, label, caseId, severity, caseRationale } = descriptor;
  return (input): ComplianceRow => {
    const { componentName, themeData } = input;
    if (!themeData) {
      return {
        id,
        label,
        status: 'info',
        count: 0,
        detail: NOT_MIGRATED_DETAIL,
      };
    }
    const allFindings = evaluateAllHooks(themeData, componentName);
    const findings = allFindings.get(caseId) ?? [];
    if (findings.length === 0) {
      return {
        id,
        label,
        status: 'pass',
        count: 0,
        detail: `No hooks fall into this case. ${caseRationale.replace(/^A /, 'The case covers ')}`,
      };
    }
    const offenders: Offender[] = findings.map(offenderFromFinding);
    return {
      id,
      label,
      status: severity,
      count: offenders.length,
      detail: `${offenders.length} hook${offenders.length === 1 ? '' : 's'} match this case. ${caseRationale}`,
      offenders,
    };
  };
}
 
export const hookHighRiskPartialCoverage = buildCheckForCase(CASE_BY_ID.get('high-risk-partial')!);
export const hookHighRiskEmptyCoverage = buildCheckForCase(CASE_BY_ID.get('high-risk-empty')!);
export const hookHighRiskBaseContractShape = buildCheckForCase(CASE_BY_ID.get('high-risk-full')!);
export const hookMediumRiskPartialLowDemand = buildCheckForCase(
  CASE_BY_ID.get('medium-risk-partial-low-demand')!,
);
export const hookMediumRiskPartialCoverage = buildCheckForCase(
  CASE_BY_ID.get('medium-risk-partial-mid-demand')!,
);
export const hookMediumRiskEmptyCoverage = buildCheckForCase(CASE_BY_ID.get('medium-risk-empty')!);