All files / packages/sds-customization-compliance/src/checks/helpers propertyMetadata.ts

92.26% Statements 155/168
79.02% Branches 113/143
100% Functions 21/21
93.57% Lines 131/140

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 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632                                                                                    6x                                                                                                                                                                         6x               76x 76x 75x     6x                       76x 76x 75x 75x 75x     10x     65x 65x 65x                                         68x 67x 6x 3x   61x 7x       54x                         68x       68x 68x 68x 55x 55x   13x 12x 12x         13x               6x                                                                                                                       6x 20x                                 73x 73x 70x 57x 49x 40x               8x 8x 8x 8x 8x 4x               4x 2x               2x                             9x 9x 9x 9x 3x 3x                                       6x 6x 2x                     4x 6x 2x                                 36x 36x   36x 36x 49x 49x 38x           36x 23x 23x 47x 47x 47x 39x 38x 38x     47x   47x 23x               36x                                           14x 13x                       13x 13x 14x 14x 14x 14x                                           13x 13x 13x 13x 14x 14x 11x 11x 11x 11x   11x   3x   13x                         25x 19x 19x 19x 19x 19x 19x                                         25x 25x 25x 26x                               25x 25x 19x 19x 19x     25x               38x 38x 13x 13x               25x 25x 25x 25x 25x 25x                 40x    
/**
 * Property-level risk + demand metadata for the Theme Layer.
 *
 * Mirrors the tables in:
 *   rfcs/text/1157-theme-layer/theme-layer-property-risk.md
 *   rfcs/text/1157-theme-layer/theme-layer-property-demand.md
 *
 * This is the single source of truth: both the compliance checks
 * (`hook-high-risk-*`, `hook-medium-risk-*`) and the storybook
 * Component Hook API doc block read tiering and recommendations from
 * here. Keep it aligned with the RFC docs; when you change a tier,
 * update the docs in the same PR.
 *
 * Risk tiers: 'low' | 'medium' | 'high' (per property-risk.md).
 * Demand tiers: 'high' | 'medium' | 'low' | 'none' (per property-demand.md).
 *
 * The classifier resolves `(category, property-axis)` keys —
 * `category` from `categorizeHook` (audit package), axis from
 * `parseHookPropertyAxis`.
 */
 
import { categorizeHook } from '../../audit/categorize.js';
 
export type RiskTier = 'low' | 'medium' | 'high' | 'unknown';
export type DemandTier = 'low' | 'medium' | 'high' | 'none' | 'unknown';
 
export interface HookMetadata {
  risk: RiskTier;
  demand: DemandTier;
  /** Human-readable CSS property label, used in tooltips and recommendation prose. */
  property: string | null;
  /** How the metadata was resolved — useful for debugging mismatches. */
  source: 'override' | 'metadata' | 'fallback' | 'unknown';
}
 
type Tuple = [RiskTier, DemandTier, string | null];
 
/**
 * Risk + demand for each `(category, property-axis)` pair. Categories
 * that don't appear here, or appear without the specific axis, fall
 * through to a `<category>/default` lookup, then to an unknown tier.
 */
const PROPERTY_METADATA: Record<string, Tuple> = {
  // Color
  'color/foreground': ['low', 'high', 'color'],
  'color/background': ['low', 'high', 'background-color'],
  'color/border': ['low', 'high', 'border-color'],
 
  // Spacing — padding axes plus gap/general
  'spacing/block': ['low', 'high', 'padding-block'],
  'spacing/inline': ['low', 'high', 'padding-inline'],
  'spacing/gap': ['low', 'medium', 'gap'],
  'spacing/default': ['low', 'medium', 'spacing'],
 
  // Margin
  'margin/block': ['low', 'medium', 'margin-block'],
  'margin/inline': ['low', 'medium', 'margin-inline'],
  'margin/default': ['low', 'medium', 'margin'],
 
  // Sizing — width / height (and the `size` shorthand for square
  // sizing) live on compositional / atomic children (icons,
  // thumbnails, swatches) where intentional dimensional control is
  // both common and load-bearing for the customer surface. Treating
  // them as low risk lets components expose them as configurable
  // hooks without the mechanism-fit checks pushing toward path 2/3.
  'sizing/border': ['low', 'high', 'border-width'],
  'sizing/size': ['low', 'high', 'width / height'],
  'sizing/height': ['low', 'medium', 'height'],
  'sizing/width': ['low', 'medium', 'width'],
  'sizing/min': ['medium', 'medium', 'min-height / min-width'],
  'sizing/max': ['medium', 'low', 'max-height / max-width'],
  'sizing/default': ['low', 'medium', 'sizing'],
 
  // Radius
  'radius/border': ['low', 'high', 'border-radius'],
  'radius/default': ['low', 'high', 'border-radius'],
 
  // Font
  'font/size': ['low', 'high', 'font-size'],
  'font/weight': ['low', 'high', 'font-weight'],
  'font/line-height': ['low', 'medium', 'line-height'],
  'font/family': ['medium', 'low', 'font-family'],
  'font/style': ['low', 'low', 'font-style'],
  'font/default': ['low', 'medium', 'font'],
 
  // Shadow
  'shadow/default': ['medium', 'low', 'box-shadow (idle / decorative)'],
  // Synthetic key applied when the hook ends with a state suffix.
  'shadow/state': ['medium', 'medium', 'box-shadow (per-state)'],
 
  // Transform — two-tier:
  // - idle: compositional setup (e.g. avatarGroup `scale()` on stacked
  //   initials). Static, no accessibility load. Medium risk because
  //   transforms still affect layout flow if mis-tuned, but low demand.
  // - state: hover lift, focus shift, active press. Now accessibility-
  //   load-bearing (defeats `prefers-reduced-motion`, can move focus
  //   ring off-screen, partial coverage is a UX inconsistency trap).
  //   High risk; demand stays low because most themes won't drive it.
  'transform/default': ['medium', 'low', 'transform (idle / compositional)'],
  // Synthetic key applied when the hook ends with a state suffix.
  'transform/state': ['high', 'low', 'transform (per-state)'],
 
  // Image
  'image/default': ['medium', 'medium', 'background-image'],
 
  // Position
  'position/default': ['high', 'none', 'position / top / left / etc.'],
 
  // Gap (legacy category bucket, still used by buildThemeData)
  'gap/default': ['low', 'medium', 'gap'],
 
  // Opacity
  'opacity/default': ['medium', 'medium', 'opacity'],
 
  // Display
  'display/default': ['high', 'none', 'display'],
 
  // Other (catch-all)
  'other/default': ['low', 'low', null],
};
 
/**
 * Per-hook overrides for canonical "wrong path" cases the property
 * tables can't reach via the normal lookup. Use sparingly: a needed
 * override usually signals the property tables should grow a new
 * row (or a synthetic-key rule should grow in `derivePropertyKey`).
 */
const HOOK_OVERRIDES: Record<string, Tuple> = {};
 
/**
 * Strip the `--slds-c-<componentPrefix>-` prefix and return the body
 * for further parsing. Returns `null` if the hook doesn't start with
 * the expected prefix shape.
 */
function hookBody(hookName: string, componentPrefix: string): string | null {
  const prefix = `--slds-c-${componentPrefix}-`;
  if (!hookName.startsWith(prefix)) return null;
  return hookName.slice(prefix.length);
}
 
const STATE_SUFFIXES = new Set(['hover', 'focus', 'active', 'disabled']);
 
/**
 * Parse a hook name into the property axis (the segment after the
 * `<category>` token, with state suffixes stripped). For
 * `--slds-c-button-color-background-hover` returns `'background'`;
 * for `--slds-c-pill-spacing-inline-end` returns `'inline'`; for
 * `--slds-c-button-icon-size` returns `'size'` (sizing-shorthand
 * rule). Returns `'default'` when no specific axis can be resolved
 * (callers fall through to `<category>/default`).
 */
export function parseHookPropertyAxis(hookName: string, componentPrefix: string, category: string): string {
  const body = hookBody(hookName, componentPrefix);
  if (!body) return 'default';
  const parts = body.split('-');
  const catIdx = parts.indexOf(category);
  if (catIdx === -1) {
    // No category token — likely a sizing-shorthand hook like
    // `-size`, `-height`, `-width`. Return the tail.
    Eif (parts.length >= 2) return parts.at(-1) ?? 'default';
    return parts[0] ?? 'default';
  }
  const afterCategory = parts.slice(catIdx + 1);
  const axis = afterCategory.find((p) => !STATE_SUFFIXES.has(p));
  return axis ?? 'default';
}
 
/**
 * Map a hook name into a `category/axis` lookup key.
 *
 * Two synthetic-key special cases live here, both bumping risk/demand
 * for state-suffixed forms of properties whose idle form is benign:
 *   - `shadow/state` (state-suffixed shadow hooks): demand bumps low →
 *     medium because focus shadows are accessibility-load-bearing.
 *   - `transform/state` (state-suffixed transform hooks): risk bumps
 *     medium → high because hover lifts / focus shifts run in
 *     response to interaction, defeat `prefers-reduced-motion`, and
 *     can move the focus ring off-screen on partial-coverage themes.
 *
 * Transform routes regardless of nominal `category`. The hook name
 * `--slds-c-button-transform-hover` categorizes as `other` (no
 * canonical category token in the name), so we recognize it here by
 * the `-transform` suffix on the property segment instead.
 */
function derivePropertyKey(hookName: string, category: string, propertyAxis: string): string | null {
  if (!category || !propertyAxis) return null;
  if (category === 'shadow') {
    if (/-shadow-(hover|focus|active|disabled)$/.test(hookName)) return 'shadow/state';
    return 'shadow/default';
  }
  if (/-transform(-(hover|focus|active|disabled))?$/.test(hookName)) {
    return /-transform-(hover|focus|active|disabled)$/.test(hookName)
      ? 'transform/state'
      : 'transform/default';
  }
  return `${category}/${propertyAxis}`;
}
 
/**
 * Resolve risk + demand for a hook. Always returns a result —
 * `source: 'unknown'` indicates the property tables had no entry,
 * not that the lookup failed.
 */
export function resolveHookMetadata(
  hookName: string,
  componentPrefix: string,
  category: string,
): HookMetadata {
  Iif (HOOK_OVERRIDES[hookName]) {
    const [risk, demand, property] = HOOK_OVERRIDES[hookName];
    return { risk, demand, property, source: 'override' };
  }
  const propertyAxis = parseHookPropertyAxis(hookName, componentPrefix, category);
  const key = derivePropertyKey(hookName, category, propertyAxis);
  if (key && PROPERTY_METADATA[key]) {
    const [risk, demand, property] = PROPERTY_METADATA[key];
    return { risk, demand, property, source: 'metadata' };
  }
  if (category) {
    const fallback = PROPERTY_METADATA[`${category}/default`];
    Iif (fallback) {
      const [risk, demand, property] = fallback;
      return { risk, demand, property, source: 'fallback' };
    }
  }
  return { risk: 'unknown', demand: 'unknown', property: null, source: 'unknown' };
}
 
/**
 * The three mechanism paths the property-risk doc defines.
 * Recommendations name them by `key`; consumers (compliance + the
 * docs panel) resolve them to display titles + summaries.
 */
export const MECHANISM_PATHS = {
  configurableHook: {
    name: 'Configurable component hook',
    summary:
      'Open as a base-contract hook. Every theme assigns it; customers can override it on the component root.',
  },
  globalTokenPaint: {
    name: 'Direct global-token paint',
    summary:
      'Paint directly in themes/base.css against a global token (--slds-g-*). No per-component hook; customers retheme via the global token, which propagates everywhere.',
  },
  themeScoped: {
    name: 'Scope to a single theme',
    summary:
      'Declare the rule and the hook reference inside one theme file only. The base contract stays clean; other themes never paint the property.',
  },
} as const;
 
export type MechanismPathKey = keyof typeof MECHANISM_PATHS;
 
/**
 * Coverage shape passed into `recommendForHook`. Mirrors what the
 * docs panel computes from themeData and what the compliance checks
 * compute from the in-memory themeData walk.
 */
export interface HookCoverage {
  have: number;
  total: number;
  themes: string[];
  present: string[];
  missing: string[];
}
 
export interface Recommendation {
  /** `'critical'` → fail in compliance; `'advisory'` → review. */
  severity: 'critical' | 'advisory';
  /** The recommendation's discriminator id, used to pick the compliance check. */
  caseId:
    | 'high-risk-partial'
    | 'high-risk-empty'
    | 'high-risk-full'
    | 'medium-risk-partial-low-demand'
    | 'medium-risk-partial-mid-demand'
    | 'medium-risk-empty';
  headline: string;
  rationale: string;
  suggestedPaths: MechanismPathKey[];
}
 
/**
 * Recommendation engine. Returns `null` when the current shape
 * matches guidance.
 */
/**
 * Inline phrase used in headlines / rationale when we know the
 * underlying CSS property the hook controls. `property` is the
 * human-readable label from the property tables (e.g.
 * `"box-shadow (idle / decorative)"`, `"padding-block"`). When
 * unknown we drop back to "the property" so the prose still scans.
 */
const propertyPhrase = (property: string | null | undefined): string =>
  property ? `the \`${property}\` property` : 'the property';
 
export function recommendForHook(args: {
  risk: RiskTier;
  demand: DemandTier;
  coverage: HookCoverage;
  hookName: string;
  /** Human-readable CSS property label from `resolveHookMetadata`. */
  property?: string | null;
  /**
   * `true` when the hook is already declared and read inside a single
   * theme file with no base-contract reach (path 3, theme-scoped).
   * Theme-scoped hooks are by definition in the right shape — they
   * have nothing to recommend, so the engine short-circuits to `null`.
   */
  isThemeScoped?: boolean;
}): Recommendation | null {
  const { risk, demand, coverage, hookName, property, isThemeScoped } = args;
  if (isThemeScoped) return null;
  if (risk === 'unknown' || demand === 'unknown') return null;
  if (risk === 'high') return recommendHighRisk(hookName, property, coverage);
  if (risk === 'medium') return recommendMediumRisk(hookName, property, demand, coverage);
  return null;
}
 
function recommendHighRisk(
  hookName: string,
  property: string | null | undefined,
  coverage: HookCoverage,
): Recommendation | null {
  const { have, total, present } = coverage;
  const partial = total > 0 && have > 0 && have < total;
  const empty = total > 0 && have === 0;
  const prop = propertyPhrase(property);
  if (partial) {
    return {
      severity: 'critical',
      caseId: 'high-risk-partial',
      headline: `Move ${hookName} into the assigning theme only.`,
      rationale: `High-risk property (${prop}) with partial coverage (${present.join(', ')} only). High-risk properties shouldn't be exposed as configurable component hooks; customers or future themes that set this hook get inconsistent rendering across themes.`,
      suggestedPaths: ['themeScoped'],
    };
  }
  if (empty) {
    return {
      severity: 'critical',
      caseId: 'high-risk-empty',
      headline: `Remove ${hookName} from the base contract.`,
      rationale: `High-risk property (${prop}) exposed as a per-component hook with no theme coverage. High-risk properties shouldn't be exposed as configurable component hooks; the hook surface invites customers to override a property that can't vary safely per component.`,
      suggestedPaths: ['globalTokenPaint', 'themeScoped'],
    };
  }
  return {
    severity: 'advisory',
    caseId: 'high-risk-full',
    headline: `Reconsider whether ${hookName} belongs on the customer surface.`,
    rationale: `High-risk property (${prop}) fully covered across themes, but the property's effect (layout, stacking, or rendering surprises) makes it a poor customer-customization surface. High-risk properties shouldn't be exposed as configurable component hooks.`,
    suggestedPaths: ['globalTokenPaint', 'themeScoped'],
  };
}
 
function recommendMediumRisk(
  hookName: string,
  property: string | null | undefined,
  demand: DemandTier,
  coverage: HookCoverage,
): Recommendation | null {
  const { have, total, present, missing } = coverage;
  const partial = total > 0 && have > 0 && have < total;
  const empty = total > 0 && have === 0;
  if (partial) return recommendMediumRiskPartial(hookName, property, demand, present, missing, have, total);
  Eif (empty) {
    return {
      severity: 'advisory',
      caseId: 'medium-risk-empty',
      headline: `Consider direct assignment of a global token to ${propertyPhrase(property)} instead of ${hookName}.`,
      rationale: `Medium-risk property (${propertyPhrase(property)}) with no theme assignments. Assigning a global token directly to the property in themes/base.css avoids exposing a per-component hook customers can override for a value no theme is ready to drive.`,
      suggestedPaths: ['globalTokenPaint'],
    };
  }
  return null;
}
 
function recommendMediumRiskPartial(
  hookName: string,
  property: string | null | undefined,
  demand: DemandTier,
  present: string[],
  missing: string[],
  have: number,
  total: number,
): Recommendation | null {
  const prop = propertyPhrase(property);
  if (demand === 'low' || demand === 'none') {
    return {
      severity: 'critical',
      caseId: 'medium-risk-partial-low-demand',
      headline: `Demote ${hookName} to direct paint and drop the hook.`,
      rationale: `Medium-risk property (${prop}) with low customer demand and partial theme coverage (${present.join(', ')} only, missing ${missing.join(', ')}). The hook surface invites customers to set a value the missing theme can't render consistently, with little customer benefit to justify it.`,
      suggestedPaths: ['globalTokenPaint'],
    };
  }
  // Strict majority: > 50% of themes drive the hook. Configurable
  // component hook is the right path; the gap is the missing theme(s)
  // catching up. Ties (1/2, 2/4) count as minority precedent.
  const majorityPresent = total > 0 && have * 2 > total;
  if (majorityPresent) return null;
  return {
    severity: 'critical',
    caseId: 'medium-risk-partial-mid-demand',
    headline: `Move ${hookName} into the assigning theme only.`,
    rationale: `Medium-risk property (${prop}) with minority coverage (${present.join(', ')} only, missing ${missing.join(', ')}). Without a strict majority of themes driving the hook, the base contract shouldn't expose it; customers who set it get inconsistent rendering across themes.`,
    suggestedPaths: ['themeScoped', 'globalTokenPaint'],
  };
}
 
/**
 * Walk every theme's per-selector hook assignments and compute a
 * `hookName → HookCoverage` map. Used by the compliance checks to
 * feed `recommendForHook`.
 */
export function computeHookCoverageMap(themeData: {
  themes?: Record<string, { selectors?: Record<string, Record<string, unknown>> }>;
}): Map<string, HookCoverage> {
  const themes = Object.keys(themeData.themes ?? {}).sort((a, b) => a.localeCompare(b));
  const coverage = new Map<string, HookCoverage>();
  // First pass: collect every hook name we encounter in any theme.
  const hookSet = new Set<string>();
  for (const themeName of themes) {
    const tBlock = themeData.themes?.[themeName];
    for (const hookMap of Object.values(tBlock?.selectors ?? {})) {
      for (const hook of Object.keys(hookMap ?? {})) hookSet.add(hook);
    }
  }
  // Second pass: build coverage for every hook (including hooks the
  // base contract reads but no theme assigns — those will surface as
  // `have: 0`).
  for (const hook of hookSet) {
    const present: string[] = [];
    for (const themeName of themes) {
      const tBlock = themeData.themes?.[themeName];
      let assigned = false;
      for (const hookMap of Object.values(tBlock?.selectors ?? {})) {
        if (hookMap && hook in hookMap) {
          assigned = true;
          break;
        }
      }
      if (assigned) present.push(themeName);
    }
    const missing = themes.filter((t) => !present.includes(t));
    coverage.set(hook, {
      have: present.length,
      total: themes.length,
      themes,
      present,
      missing,
    });
  }
  return coverage;
}
 
/**
 * Hooks that a `themeData` knows about. Preferred path:
 * `editableSurfaces` (the build pipeline categorized every hook for
 * us). Fallback path (when the CLI projects themeData from raw CSS
 * and doesn't emit `editableSurfaces`): collect hooks from
 * `selectors` (base reads) + `themes[*].selectors` (theme
 * assignments) and categorize their names via the shared
 * `categorizeHook` helper from the audit package, which encodes the
 * same `(category-token, sizing-shorthand, line-height)` rules
 * `buildThemeData.js` uses when it emits `editableSurfaces`.
 */
 
type HookEntry = string | { name: string; source?: string };
type SurfaceShape = { hooks?: Record<string, Array<HookEntry>> };
 
function normalizeHookEntry(
  entry: HookEntry,
  category: string,
): { name: string; category: string; source?: string } | null {
  if (typeof entry === 'string') return { name: entry, category };
  Eif (entry?.name) return { name: entry.name, category, source: entry.source };
  return null;
}
 
/**
 * Yield `{ name, category, source }` for every entry across every
 * editable surface. Normalizes the string-or-object shape into a
 * common form so downstream classification stays simple.
 */
function* iterateSurfaceEntries(
  surfaces: Array<SurfaceShape>,
): Generator<{ name: string; category: string; source?: string }> {
  for (const surface of surfaces) {
    for (const [category, entries] of Object.entries(surface.hooks ?? {})) {
      Iif (!Array.isArray(entries)) continue;
      for (const entry of entries) {
        const normalized = normalizeHookEntry(entry, category);
        Eif (normalized) yield normalized;
      }
    }
  }
}
 
/**
 * Classify every editable-surface hook entry into public (read by
 * `themes/base.css`) or theme-private (read only inside a theme
 * file). A hook with any `source: 'base'` entry is public regardless
 * of where else it appears; a hook without a `source` field is
 * treated as public for back-compat with older themeData payloads.
 *
 * Returns the public hooks (de-duplicated, source order preserved)
 * and a flag indicating whether any theme-private hooks were
 * observed — the caller uses the flag to decide whether to fall
 * through to the legacy assignment-walking path.
 */
function classifyEditableSurfaceHooks(surfaces: Array<SurfaceShape>): {
  public: { hookName: string; category: string }[];
  sawThemePrivate: boolean;
} {
  const out: { hookName: string; category: string }[] = [];
  const seen = new Set<string>();
  const themeOnly = new Set<string>();
  for (const { name, category, source } of iterateSurfaceEntries(surfaces)) {
    const isBase = source === 'base' || source === undefined;
    if (isBase) {
      themeOnly.delete(name);
      Eif (!seen.has(name)) {
        seen.add(name);
        out.push({ hookName: name, category });
      }
      continue;
    }
    Eif (!seen.has(name)) themeOnly.add(name);
  }
  return { public: out, sawThemePrivate: themeOnly.size > 0 };
}
 
/**
 * Walk base reads grouped by category and add each unique hook to
 * `out`, mutating the `seen` set. Used by the legacy projection
 * path when `editableSurfaces` isn't present in themeData.
 */
function collectFromBaseSelectors(
  selectors: Record<string, Record<string, string[]>> | undefined,
  out: { hookName: string; category: string }[],
  seen: Set<string>,
): void {
  for (const categoryMap of Object.values(selectors ?? {})) {
    for (const [category, hooks] of Object.entries(categoryMap ?? {})) {
      Iif (!Array.isArray(hooks)) continue;
      for (const name of hooks) {
        Iif (!name || seen.has(name)) continue;
        seen.add(name);
        out.push({ hookName: name, category });
      }
    }
  }
}
 
/**
 * Walk every theme's hook *assignments* and add each unique hook
 * (categorized by parsing the hook name) to `out`. Theme-private
 * hooks — ones declared inside a theme file with no base-contract
 * read site — are skipped by checking the caller-supplied
 * `baseReads` set. Used as a last-resort source so a themeData
 * without `editableSurfaces` (CLI projection path) still yields
 * something to evaluate while still respecting path-3 scoping.
 */
function collectFromThemeAssignments(
  themes: Record<string, { selectors?: Record<string, Record<string, unknown>> }> | undefined,
  baseReads: Set<string>,
  out: { hookName: string; category: string }[],
  seen: Set<string>,
): void {
  for (const tBlock of Object.values(themes ?? {})) {
    for (const hookMap of Object.values(tBlock?.selectors ?? {})) {
      for (const name of Object.keys(hookMap ?? {})) {
        Eif (!name || seen.has(name) || !baseReads.has(name)) continue;
        seen.add(name);
        out.push({ hookName: name, category: categorizeHook(name) });
      }
    }
  }
}
 
/**
 * The set of hook names the base contract reads, as projected by
 * the CLI's `projectThemeData`. Hooks not in this set are
 * theme-private and shouldn't surface in the public-contract list.
 */
function collectBaseReadHookNames(
  selectors: Record<string, Record<string, string[]>> | undefined,
): Set<string> {
  const out = new Set<string>();
  for (const categoryMap of Object.values(selectors ?? {})) {
    for (const hooks of Object.values(categoryMap ?? {})) {
      Iif (!Array.isArray(hooks)) continue;
      for (const name of hooks) Eif (name) out.add(name);
    }
  }
  return out;
}
 
export function listAllPublicHooks(themeData: {
  editableSurfaces?: Array<SurfaceShape>;
  selectors?: Record<string, Record<string, string[]>>;
  themes?: Record<string, { selectors?: Record<string, Record<string, unknown>> }>;
}): { hookName: string; category: string }[] {
  const surfaces = themeData.editableSurfaces ?? [];
  if (surfaces.length > 0) {
    const classified = classifyEditableSurfaceHooks(surfaces);
    Eif (classified.public.length > 0 || classified.sawThemePrivate) return classified.public;
  }
  // Fallback: walk base reads + theme assignments and categorize
  // hook names by inspecting the segments. The CLI projection path
  // doesn't emit `editableSurfaces`, so without this fallback the
  // mechanism-fit checks would have no hooks to evaluate. Theme
  // assignments are filtered against `baseReads` so theme-private
  // (path-3) hooks don't surface as public-contract candidates.
  const out: { hookName: string; category: string }[] = [];
  const seen = new Set<string>();
  collectFromBaseSelectors(themeData.selectors, out, seen);
  const baseReads = collectBaseReadHookNames(themeData.selectors);
  collectFromThemeAssignments(themeData.themes, baseReads, out, seen);
  return out;
}
 
/**
 * Coverage for hooks that didn't appear in any theme's assignments
 * — return a zero-coverage shape so the recommendation engine can
 * still evaluate empty-coverage cases.
 */
export function fallbackEmptyCoverage(themes: string[]): HookCoverage {
  return { have: 0, total: themes.length, themes, present: [], missing: themes.slice() };
}