All files / packages/sds-customization-compliance/src/cli build.ts

43.66% Statements 93/213
35.57% Branches 37/104
53.33% Functions 16/30
46.03% Lines 87/189

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                                                                                                                                                                                                                      4x 4x                 4x 4x                         4x 4x 140x   4x                           12x 12x 8x   4x                                       4x 4x                         4x 4x       8x 8x       8x 16x 16x 16x 4x 12x 12x 12x 12x 12x                 4x 4x                   4x 4x 4x 4x 4x               4x               4x 4x 4x 4x 4x 5x   4x           4x 4x 4x 4x   4x               4x   4x   8x 4x     4x                         4x 4x 4x 4x         3x 4x   3x 3x                   3x 4x 4x       4x 4x                 4x 4x 4x 4x 4x 4x 4x     3x             3x 3x 3x         4x 4x 4x 4x 1x   3x 4x   3x 3x     3x                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                            
/**
 * `sds-compliance build` — generate per-component compliance reports.
 *
 * For each component under `<ds2-root>/src/slds2/<name>/`:
 *   1. Build the legacy + effective-new CSS models.
 *   2. Run the audit `diff` to produce `flags` + `summary` (cached in
 *      `ThemeRegressionReport` shape, same as the historical
 *      `theme-regression.json` artifact).
 *   3. Project the effective-new model into themeData shape in-process —
 *      no dependency on design-system-2's `build/themeData/*.json` output.
 *   4. Run the 29 compliance checks against `{ regression, themeData }`.
 *   5. Write `<outDir>/<name>.json` with both the raw audit and the rows.
 *
 * Finally, write `<outDir>/index.json` as an aggregate summary the
 * Storybook addon and sandbox API route can read directly without loading
 * every component file.
 */
 
import fs from 'node:fs';
import fsp from 'node:fs/promises';
import path from 'node:path';
import { buildLegacyModel, buildEffectiveNewModel } from '../audit/models.js';
import { diff, summarize } from '../audit/diff.js';
import { flattenCss, flattenCssString } from '../audit/extract.js';
import { projectThemeData } from '../audit/themeData.js';
import { runChecks } from '../checks/index.js';
import type { Flag, FlagSummary, FileModel } from '../audit/types.js';
import type {
  BaseDeclsBySelector,
  ComplianceRow,
  ComponentSourceFile,
  ComponentSourceFileRole,
  ThemeRegressionReport,
} from '../types.js';
import {
  componentForCssPath,
  listComponents,
  resolvePaths,
  resolveStructuralPaths,
  type PathOverrides,
  type ResolvedPaths,
  type ResolvedStructuralPaths,
  type StructuralPathOverrides,
} from './paths.js';
 
/** Public options matching the CLI flags. */
export interface BuildOptions extends PathOverrides {
  /** Limit the run to a single component. */
  component?: string;
  /** Suppress stdout summary (used in watch loop). */
  quiet?: boolean;
}
 
/**
 * Shape written to `<outDir>/<component>.json`. Keeps the raw audit
 * (`regression`) alongside the compliance rows so downstream consumers
 * (sandbox plan generator, Storybook addon, docs) can derive whatever
 * they need without reading a second file.
 */
export interface ComponentReportFile {
  componentName: string;
  generatedAt: string;
  inputs: {
    legacy: string | null;
    base: string | null;
    themes: string[];
  };
  regression: {
    flags: Flag[];
    summary: FlagSummary;
    needsReview: number;
  };
  rows: ComplianceRow[];
  summary: {
    pass: number;
    fail: number;
    review: number;
    info: number;
  };
}
 
/** Shape written to `<outDir>/index.json`. */
export interface ComplianceIndexFile {
  generatedAt: string;
  ds2Root: string;
  components: Array<{
    componentName: string;
    passCount: number;
    failCount: number;
    reviewCount: number;
    infoCount: number;
    breakingFlags: number;
    warningFlags: number;
  }>;
  totals: {
    components: number;
    pass: number;
    fail: number;
    review: number;
    info: number;
    breakingFlags: number;
    warningFlags: number;
  };
}
 
async function readJson<T>(filePath: string): Promise<T | null> {
  let raw: string;
  try {
    raw = await fsp.readFile(filePath, 'utf-8');
  } catch (err) {
    // ENOENT is the expected "no data yet" case the caller treats as
    // null. Any other read error (permission denied, IO error) is
    // unexpected and should be visible.
    if ((err as NodeJS.ErrnoException).code === 'ENOENT') return null;
    console.warn(`[sds-compliance] failed to read ${filePath}:`, err);
    return null;
  }
  try {
    return JSON.parse(raw) as T;
  } catch (err) {
    console.warn(`[sds-compliance] failed to parse JSON at ${filePath}:`, err);
    return null;
  }
}
 
function countRowsByStatus(rows: ComplianceRow[]): {
  pass: number;
  fail: number;
  review: number;
  info: number;
} {
  const counts = { pass: 0, fail: 0, review: 0, info: 0 };
  for (const r of rows) {
    counts[r.status] += 1;
  }
  return counts;
}
 
/**
 * Infer the role a CSS file plays inside a component directory from
 * its path relative to the component root. Drives Rule 2 (layer
 * placement) and any future role-aware structural rule.
 *
 *   - `themes/base.css`       → 'theme-base'
 *   - `themes/<other>.css`    → 'theme'
 *   - `<component>.css`       → 'base' (the top-level paint file)
 *   - everything else (.css)  → 'aux'
 */
function roleForRelPath(relPath: string): ComponentSourceFileRole {
  const parts = relPath.split(path.sep);
  if (parts[0] === 'themes') {
    return parts[1] === 'base.css' ? 'theme-base' : 'theme';
  }
  Eif (parts.length === 1 && parts[0].endsWith('.css')) return 'base';
  return 'aux';
}
 
/**
 * Walk a component directory and return one {@link ComponentSourceFile}
 * per `.css` file, flattened via the audit pipeline so structural
 * checks can walk a real PostCSS root. Skips test fixtures
 * (`__tests__`), examples (`__examples__`), and any nested non-CSS
 * directories.
 */
/**
 * Load `<componentDir>/<componentName>.system.slds.uif.json` as a
 * plain object. Returns `null` when the file is absent or unparseable
 * — checks that need it report `info` rather than crashing the build.
 */
async function loadComponentSystemUif(
  componentDir: string,
  componentName: string,
): Promise<Record<string, unknown> | null> {
  const uifPath = path.join(componentDir, `${componentName}.system.slds.uif.json`);
  Eif (!fs.existsSync(uifPath)) return null;
  try {
    const raw = await fsp.readFile(uifPath, 'utf-8');
    return JSON.parse(raw) as Record<string, unknown>;
  } catch {
    return null;
  }
}
 
async function loadComponentSourceFiles(
  componentDir: string,
  ds2Root: string,
): Promise<ComponentSourceFile[]> {
  const files: ComponentSourceFile[] = [];
  Iif (!fs.existsSync(componentDir)) return files;
 
  async function walk(dir: string): Promise<void> {
    let entries: import('node:fs').Dirent[];
    try {
      entries = await fsp.readdir(dir, { withFileTypes: true, encoding: 'utf-8' });
    } catch {
      return;
    }
    for (const entry of entries) {
      Iif (entry.name.startsWith('__')) continue;
      const full = path.join(dir, entry.name);
      if (entry.isDirectory()) {
        await walk(full);
      } else Eif (entry.isFile() && entry.name.endsWith('.css')) {
        const css = await fsp.readFile(full, 'utf-8');
        const root = await flattenCss(css, full);
        const componentRel = path.relative(componentDir, full);
        files.push({
          path: path.relative(ds2Root, full),
          role: roleForRelPath(componentRel),
          root,
        });
      }
    }
  }
 
  await walk(componentDir);
  return files;
}
 
/**
 * Project the postcss-flavored `FileModel.declsBySelector` Map into a
 * plain `Record<selector, BaseDecl[]>` so checks can consume it without
 * a postcss runtime dependency. `FlagSide.rawValue`-style detail stays
 * in the audit, here we only keep the fields compliance checks need.
 */
function projectBaseDecls(base: FileModel | null, ds2Root: string): BaseDeclsBySelector | null {
  Iif (!base) return null;
  const sourceRel = base.source ? path.relative(ds2Root, base.source) : undefined;
  const out: BaseDeclsBySelector = {};
  for (const [selector, decls] of base.declsBySelector) {
    out[selector] = decls.map((d) => ({
      prop: d.prop,
      rawValue: d.rawValue,
      terminalFallback: d.terminalFallback,
      source: sourceRel,
      line: d.line,
    }));
  }
  return out;
}
 
/** Run the audit + checks for a single component and write its report. */
export async function buildComponent(
  componentName: string,
  paths: ResolvedPaths,
): Promise<ComponentReportFile> {
  const componentDir = path.join(paths.slds2Dir, componentName);
  const legacy = await buildLegacyModel(componentDir);
  const effective = await buildEffectiveNewModel(componentDir);
  const flags = diff(legacy, effective);
  const summary = summarize(flags);
  const needsReview = flags.filter((f) => f.needsReview).length;
 
  const regression: ThemeRegressionReport = {
    name: componentName,
    flags,
    summary,
  };
 
  const themeData = projectThemeData(effective);
  const baseDeclsBySelector = projectBaseDecls(effective?.base ?? null, paths.ds2Root);
  const componentSourceFiles = await loadComponentSourceFiles(componentDir, paths.ds2Root);
  const componentSystemUif = await loadComponentSystemUif(componentDir, componentName);
 
  const rows = runChecks({
    componentName,
    regression,
    themeData,
    baseDeclsBySelector,
    componentSourceFiles,
    componentSystemUif,
  });
  const rowCounts = countRowsByStatus(rows);
 
  const themesFound = effective
    ? Object.entries(effective.themes ?? {})
        .filter(([, v]) => v !== null && v !== undefined)
        .map(([k]) => k)
    : [];
 
  const report: ComponentReportFile = {
    componentName,
    generatedAt: new Date().toISOString(),
    inputs: {
      legacy: legacy?.source ? path.relative(paths.ds2Root, legacy.source) : null,
      base: effective?.base?.source ? path.relative(paths.ds2Root, effective.base.source) : null,
      themes: themesFound,
    },
    regression: { flags, summary, needsReview },
    rows,
    summary: rowCounts,
  };
 
  await fsp.mkdir(paths.outDir, { recursive: true });
  const outPath = path.join(paths.outDir, `${componentName}.json`);
  await fsp.writeFile(outPath, JSON.stringify(report, null, 2) + '\n');
  return report;
}
 
/** Rebuild the aggregate `index.json` from whatever component reports exist on disk. */
export async function writeIndex(paths: ResolvedPaths): Promise<ComplianceIndexFile> {
  const entries = fs.existsSync(paths.outDir) ? await fsp.readdir(paths.outDir) : [];
  const componentFiles = entries.filter((f) => f.endsWith('.json') && f !== 'index.json').sort();
 
  const components: ComplianceIndexFile['components'] = [];
  const totals = {
    components: 0,
    pass: 0,
    fail: 0,
    review: 0,
    info: 0,
    breakingFlags: 0,
    warningFlags: 0,
  };
 
  for (const file of componentFiles) {
    const report = await readJson<ComponentReportFile>(path.join(paths.outDir, file));
    Iif (!report) continue;
    // `review` was added after the original on-disk format shipped. Older
    // reports lacked it entirely; fall back to 0 so a partial rebuild
    // doesn't crash the index aggregator.
    const reviewCount = report.summary.review ?? 0;
    components.push({
      componentName: report.componentName,
      passCount: report.summary.pass,
      failCount: report.summary.fail,
      reviewCount,
      infoCount: report.summary.info,
      breakingFlags: report.regression.summary.breaking,
      warningFlags: report.regression.summary.warning,
    });
    totals.components += 1;
    totals.pass += report.summary.pass;
    totals.fail += report.summary.fail;
    totals.review += reviewCount;
    totals.info += report.summary.info;
    totals.breakingFlags += report.regression.summary.breaking;
    totals.warningFlags += report.regression.summary.warning;
  }
 
  const index: ComplianceIndexFile = {
    generatedAt: new Date().toISOString(),
    ds2Root: paths.ds2Root,
    components,
    totals,
  };
 
  await fsp.mkdir(paths.outDir, { recursive: true });
  await fsp.writeFile(path.join(paths.outDir, 'index.json'), JSON.stringify(index, null, 2) + '\n');
  return index;
}
 
/** Run a full build. Returns the aggregate index for inspection/testing. */
export async function build(opts: BuildOptions = {}): Promise<ComplianceIndexFile> {
  const paths = resolvePaths(opts);
  const all = listComponents(paths.slds2Dir);
  const components = opts.component ? all.filter((n) => n === opts.component) : all;
  if (opts.component && components.length === 0) {
    throw new Error(`Component not found under ${paths.slds2Dir}: ${opts.component}`);
  }
  for (const name of components) {
    await buildComponent(name, paths);
  }
  const index = await writeIndex(paths);
  Iif (!opts.quiet) {
    logBuildSummary(index, paths);
  }
  return index;
}
 
function logBuildSummary(index: ComplianceIndexFile, paths: ResolvedPaths): void {
  // eslint-disable-next-line no-console
  console.info(
    `[sds-compliance] built ${index.totals.components} component report${
      index.totals.components === 1 ? '' : 's'
    } — pass ${index.totals.pass}, fail ${index.totals.fail}, review ${index.totals.review}, info ${index.totals.info}; ` +
      `${index.totals.breakingFlags} breaking, ${index.totals.warningFlags} warning.`,
  );
  // eslint-disable-next-line no-console
  console.info(`[sds-compliance]   out: ${paths.outDir}`);
}
 
/* -------------------------------------------------------------------------- */
/* Structural-only build (e.g. LBC scratch trio)                              */
/* -------------------------------------------------------------------------- */
 
/**
 * Public options for the structural-only build path. Mirrors {@link BuildOptions}
 * but takes a `sourceDir` whose immediate subdirectories are treated as
 * components. Used by the LBC scratch trio (and any other "outside the
 * SLDS layout" surface) to run the 11 structural source rules without
 * the full audit pipeline.
 */
export interface BuildStructuralOptions extends StructuralPathOverrides {
  component?: string;
  quiet?: boolean;
}
 
/**
 * Infer a role for an arbitrary CSS file inside a non-SLDS component dir.
 *
 * The trio under `sds-lbc-scratch/src/lightning/<name>/` writes a few
 * environment-flavored files that we want the compliance pipeline to
 * recognize:
 *
 *   - `<name>.css`              → 'base' (the LWC-default entry file)
 *   - `<name>.lbc.native.css`   → 'aux' (native-shadow variant)
 *   - `<name>.slds.css` /
 *     `<kebab>.slds.css`        → 'aux' (light-DOM SLDS variant)
 *   - anything else (.css)      → 'aux'
 *
 * Layer placement is content with `aux`/`base` staying unlayered, which
 * matches how the LBC source ships, so this tagging keeps the rule honest
 * without forcing the scratch source to invent themes it doesn't have.
 */
function structuralRoleForRelPath(relPath: string): ComponentSourceFileRole {
  const parts = relPath.split(path.sep);
  if (parts.length !== 1 || !parts[0].endsWith('.css')) return 'aux';
  const name = parts[0];
  if (/\.(lbc\.native|slds)\.css$/i.test(name)) return 'aux';
  return 'base';
}
 
/**
 * Walk a structural-only component directory and return one
 * {@link ComponentSourceFile} per `.css` file. Uses
 * {@link flattenCssString} (no `@import` resolution) so that LBC sources
 * referencing modules like `lightning/sldsCommon` don't blow up the
 * pipeline. Each file is checked as authored, which matches what the
 * structural rules want anyway.
 */
async function loadStructuralSourceFiles(
  componentDir: string,
  baseRoot: string,
): Promise<ComponentSourceFile[]> {
  const files: ComponentSourceFile[] = [];
  if (!fs.existsSync(componentDir)) return files;
 
  async function walk(dir: string): Promise<void> {
    let entries: import('node:fs').Dirent[];
    try {
      entries = await fsp.readdir(dir, { withFileTypes: true, encoding: 'utf-8' });
    } catch {
      return;
    }
    for (const entry of entries) {
      if (entry.name.startsWith('__')) continue;
      const full = path.join(dir, entry.name);
      if (entry.isDirectory()) {
        await walk(full);
      } else if (entry.isFile() && entry.name.endsWith('.css')) {
        const css = await fsp.readFile(full, 'utf-8');
        const root = await flattenCssString(css);
        const componentRel = path.relative(componentDir, full);
        files.push({
          path: path.relative(baseRoot, full),
          role: structuralRoleForRelPath(componentRel),
          root,
        });
      }
    }
  }
 
  await walk(componentDir);
  return files;
}
 
/** Build a single structural-only component report. */
export async function buildStructuralComponent(
  componentName: string,
  paths: ResolvedStructuralPaths,
): Promise<ComponentReportFile> {
  const componentDir = path.join(paths.sourceDir, componentName);
  const componentSourceFiles = await loadStructuralSourceFiles(componentDir, paths.baseRoot);
 
  const rows = runChecks({
    componentName,
    componentSourceFiles,
  });
  const rowCounts = countRowsByStatus(rows);
 
  const report: ComponentReportFile = {
    componentName,
    generatedAt: new Date().toISOString(),
    inputs: {
      legacy: null,
      base: null,
      themes: [],
    },
    regression: {
      flags: [],
      summary: { breaking: 0, warning: 0, info: 0 },
      needsReview: 0,
    },
    rows,
    summary: rowCounts,
  };
 
  await fsp.mkdir(paths.outDir, { recursive: true });
  const outPath = path.join(paths.outDir, `${componentName}.json`);
  await fsp.writeFile(outPath, JSON.stringify(report, null, 2) + '\n');
  return report;
}
 
/**
 * Run a structural-only build across every component dir under
 * `sourceDir`. The hook-surface and theme-regression checks short-circuit
 * to `info` (no themeData / no diff loaded), and the 11 structural
 * source rules carry the verdict.
 */
export async function buildStructural(opts: BuildStructuralOptions): Promise<ComplianceIndexFile> {
  const paths = resolveStructuralPaths(opts);
  const all = listComponents(paths.sourceDir);
  const components = opts.component ? all.filter((n) => n === opts.component) : all;
  if (opts.component && components.length === 0) {
    throw new Error(`Component not found under ${paths.sourceDir}: ${opts.component}`);
  }
  for (const name of components) {
    await buildStructuralComponent(name, paths);
  }
  // Reuse the same index aggregator: the on-disk report shape is identical,
  // so `writeIndex` doesn't need to know the build came from structural-only.
  const indexPaths: ResolvedPaths = {
    ds2Root: paths.baseRoot,
    slds2Dir: paths.sourceDir,
    outDir: paths.outDir,
    packageRoot: paths.packageRoot,
  };
  const index = await writeIndex(indexPaths);
  if (!opts.quiet) {
    logStructuralSummary(index, paths);
  }
  return index;
}
 
function logStructuralSummary(index: ComplianceIndexFile, paths: ResolvedStructuralPaths): void {
  // eslint-disable-next-line no-console
  console.info(
    `[sds-compliance] built ${index.totals.components} structural-only report${
      index.totals.components === 1 ? '' : 's'
    } — pass ${index.totals.pass}, fail ${index.totals.fail}, review ${index.totals.review}, info ${index.totals.info}.`,
  );
  // eslint-disable-next-line no-console
  console.info(`[sds-compliance]   src: ${paths.sourceDir}`);
  // eslint-disable-next-line no-console
  console.info(`[sds-compliance]   out: ${paths.outDir}`);
}
 
/**
 * Watch mode. Rebuilds individual components as their CSS changes. Uses
 * dynamic `import('chokidar')` so the main library entry never pays the
 * cost of loading chokidar when only the pure API is consumed.
 *
 * themeData is synthesized in-process from the audit's effective-new model,
 * so no separate filesystem target needs watching.
 */
export async function watch(opts: BuildOptions = {}): Promise<() => Promise<void>> {
  const paths = resolvePaths(opts);
  await build({ ...opts, quiet: true });
 
  const { watch: chokidarWatch } = await import('chokidar');
  // chokidar v5 dropped glob support — watch the slds2 directory itself
  // and filter events down to the same `<component>/*.css` and
  // `<component>/themes/*.css` shape we used to express via globs.
  const watcher = chokidarWatch(paths.slds2Dir, {
    ignoreInitial: true,
    awaitWriteFinish: { stabilityThreshold: 120, pollInterval: 40 },
    ignored: (target, stats) => {
      if (!stats) return false;
      if (stats.isDirectory()) return false;
      if (!target.endsWith('.css')) return true;
      const rel = path.relative(paths.slds2Dir, target);
      const segments = rel.split(path.sep);
      // Accept `<component>/<file>.css` and `<component>/themes/<file>.css`.
      if (segments.length === 2) return false;
      if (segments.length === 3 && segments[1] === 'themes') return false;
      return true;
    },
  });
 
  const affected = new Set<string>();
  let running: Promise<void> | null = null;
  const flush = async (): Promise<void> => {
    if (running) return running;
    running = (async () => {
      while (affected.size > 0) {
        const name = [...affected][0];
        affected.delete(name);
        try {
          await buildComponent(name, paths);
          // eslint-disable-next-line no-console
          console.info(`[sds-compliance] rebuilt ${name}`);
        } catch (err) {
          // eslint-disable-next-line no-console
          console.error(`[sds-compliance] failed to rebuild ${name}:`, err);
        }
      }
      try {
        await writeIndex(paths);
      } catch (err) {
        // eslint-disable-next-line no-console
        console.error(`[sds-compliance] failed to rewrite index.json:`, err);
      }
    })();
    try {
      await running;
    } finally {
      running = null;
    }
  };
 
  const enqueue = (p: string): void => {
    const component = componentForCssPath(paths.slds2Dir, p);
    if (!component) return;
    if (opts.component && opts.component !== component) return;
    affected.add(component);
    void flush();
  };
 
  watcher.on('add', enqueue);
  watcher.on('change', enqueue);
  watcher.on('unlink', enqueue);
 
  // eslint-disable-next-line no-console
  console.info(`[sds-compliance] watching ${paths.slds2Dir}`);
  return async () => {
    await watcher.close();
  };
}