All files / packages/design-system-2/scripts/vrt-core diff.ts

15.21% Statements 28/184
12.39% Branches 15/121
38.09% Functions 8/21
14.77% Lines 26/176

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                            2x       1x                             5x         2x         2x     2x     2x 3x     17x 1x               2x 2x 2x     2x 2x           2x 2x                                                                                                   1x     1x                 2x 4x 4x                 1x                                                                                                                                                             1x                                                                                                                                                                                                                                                                                                                                                                                                                     1x 1x                
import * as fs from 'fs';
import * as path from 'path';
import { fileURLToPath } from 'url';
import { execFileSync } from 'child_process';
import * as dotenv from 'dotenv';
 
import { Flow, RunnerConfig, DiffScreenshotResult } from './flow';
import { diffCssBundles, changedSelectors, changedRuleProps, sameCss } from './css-diff';
import { buildReportHtml, buildCommentMarkdown, buildOrgUnavailableMarkdown } from './report';
import { FlowRunner, OrgUnavailableError, redact } from './flow-runner';
 
// --- Flow loading (formerly flow-loader.ts) ---------------------------------
export function substituteEnvVars(content: string): string {
  // Values land inside JSON strings, so escape them (a `"` or `\` in a password must not break the flow).
  return content.replace(/\$\{(\w+)\}/g, (_, name) => JSON.stringify(process.env[name] || '').slice(1, -1));
}
 
// The key each Step variant is discriminated on; an unknown key is an unrunnable step.
const STEP_KEYS = [
  'goto',
  'click',
  'blur',
  'retry',
  'type',
  'wait',
  'waitForSelector',
  'screenshot',
  'style',
  'cssFile',
  'dismiss',
];
 
function isObject(value: unknown): value is Record<string, unknown> {
  return typeof value === 'object' && value !== null && !Array.isArray(value);
}
 
// Validate shape at load time so a malformed flow fails here (naming the file) rather than later inside the runner.
function assertFlow(value: unknown, filePath: string): asserts value is Flow {
  Iif (!isObject(value)) {
    throw new Error(
      `Invalid flow ${filePath}: expected a JSON object, got ${Array.isArray(value) ? 'array' : typeof value}.`,
    );
  }
  Iif (typeof value.name !== 'string' || value.name.length === 0) {
    throw new Error(`Invalid flow ${filePath}: "name" must be a non-empty string.`);
  }
  Iif (!Array.isArray(value.steps)) {
    throw new Error(`Invalid flow ${filePath}: "steps" must be an array.`);
  }
  value.steps.forEach((step: unknown, i: number) => {
    Iif (!isObject(step)) {
      throw new Error(`Invalid flow ${filePath}: step ${i} must be an object.`);
    }
    if (!STEP_KEYS.some((key) => key in step)) {
      throw new Error(
        `Invalid flow ${filePath}: step ${i} has no recognized action (expected one of ${STEP_KEYS.join(', ')}).`,
      );
    }
  });
}
 
export function loadFlow(filePath: string): Flow {
  const absolutePath = path.resolve(filePath);
  const content = fs.readFileSync(absolutePath, 'utf-8');
  const substituted = substituteEnvVars(content);
 
  let parsed: unknown;
  try {
    parsed = JSON.parse(substituted);
  } catch (e) {
    const detail = e instanceof Error ? e.message : String(e);
    throw new Error(`Invalid flow ${absolutePath}: not valid JSON (${detail}).`);
  }
 
  assertFlow(parsed, absolutePath);
  return parsed;
}
// ----------------------------------------------------------------------------
 
// Differential VRT: injects bundle A (baseline) then B (candidate) into the SAME page
// load, so anything that isn't the CSS cancels out and every remaining pixel diff is
// CSS-attributable. See --ref/--pr/--css-a/--css-b/--build handling below for options.
 
// Target repo config — the runner is repo-agnostic, so what/where to build comes from
// the environment (CI has no UI): VRT_REPO_ROOT is the checkout to build in (default cwd),
// VRT_BUILD_CMD builds the CSS bundle, VRT_BUNDLE_REL is the built bundle path relative to
// the repo root, VRT_INSTALL_CMD (optional) installs deps in the ref worktree.
interface TargetConfig {
  repoRoot: string;
  buildCmd: [string, string[]];
  bundleRel: string;
  installCmd?: [string, string[]];
}
 
// execFileSync runs without a shell, so a command string is split into argv on whitespace
// (no shell operators / quoted spaces).
function splitCommand(cmd: string): [string, string[]] {
  const parts = cmd.trim().split(/\s+/);
  return [parts[0], parts.slice(1)];
}
 
function resolveTarget(): TargetConfig {
  const repoRoot = (process.env.VRT_REPO_ROOT || process.cwd()).trim();
  const build = process.env.VRT_BUILD_CMD?.trim();
  if (!build) {
    throw new Error(
      'VRT_BUILD_CMD not set — the command that builds your CSS bundle (e.g. "yarn build:css").',
    );
  }
  const bundleRel = process.env.VRT_BUNDLE_REL?.trim();
  if (!bundleRel) {
    throw new Error('VRT_BUNDLE_REL not set — the built CSS bundle path, relative to VRT_REPO_ROOT.');
  }
  const install = process.env.VRT_INSTALL_CMD?.trim();
  return {
    repoRoot,
    buildCmd: splitCommand(build),
    bundleRel,
    installCmd: install ? splitCommand(install) : undefined,
  };
}
 
// Resolved lazily + memoized: a run with explicit --css-a and --css-b never builds, so it
// needs no target config (and must not fail when it's unset).
let _target: TargetConfig | undefined;
const target = (): TargetConfig => (_target ??= resolveTarget());
 
// Base name for traceable temp bundle files, derived from the configured bundle path.
const bundleBase = (): string => path.basename(target().bundleRel).replace(/\.css$/i, '') || 'bundle';
 
function run(cmd: string, args: string[], cwd: string): void {
  console.log(`$ ${cmd} ${args.join(' ')}  (cwd: ${cwd})`);
  execFileSync(cmd, args, { cwd, stdio: 'inherit' });
}
 
// PR checkouts have only `origin/<base>` (no local branch), so fall back to the remote-tracking ref.
export function resolveRefSha(ref: string, cwd: string): string {
  for (const candidate of [ref, `origin/${ref}`]) {
    try {
      return execFileSync('git', ['rev-parse', '--verify', '--quiet', `${candidate}^{commit}`], {
        cwd,
        encoding: 'utf8',
        stdio: ['ignore', 'pipe', 'ignore'],
      }).trim();
    } catch {
      /* not found under this name; try the next */
    }
  }
  throw new Error(`Baseline ref "${ref}" not found locally or as origin/${ref}. Fetch it first.`);
}
 
// Builds the bundle from a commit in an isolated worktree (always cleaned up), then copies it to outPath.
function buildBundleFromRef(ref: string, sha: string, outPath: string, cfg: TargetConfig): void {
  const worktree = path.join(cfg.repoRoot, `.vrt-worktree-${ref.replace(/[^\w.-]/g, '_')}`);
 
  // Clean any stale worktree from a previous interrupted run.
  try {
    run('git', ['worktree', 'remove', '--force', worktree], cfg.repoRoot);
  } catch {
    /* no-op: nothing to remove */
  }
 
  try {
    // Detached at the resolved commit, so it works whether or not a local branch exists.
    run('git', ['worktree', 'add', '--force', '--detach', worktree, sha], cfg.repoRoot);
    // Install (if configured) + build inside the worktree so its deps match that ref.
    if (cfg.installCmd) {
      run(cfg.installCmd[0], cfg.installCmd[1], worktree);
    } else {
      console.log('No VRT_INSTALL_CMD set — assuming the worktree builds without a fresh install.');
    }
    run(cfg.buildCmd[0], cfg.buildCmd[1], worktree);
 
    const built = path.join(worktree, cfg.bundleRel);
    if (!fs.existsSync(built)) {
      throw new Error(`Bundle not produced in worktree: ${built}`);
    }
    fs.mkdirSync(path.dirname(outPath), { recursive: true });
    fs.copyFileSync(built, outPath);
    console.log(`Built ${ref} bundle → ${outPath}`);
  } finally {
    try {
      run('git', ['worktree', 'remove', '--force', worktree], cfg.repoRoot);
    } catch {
      /* no-op: best-effort cleanup */
    }
  }
}
 
// Normalize VRT_BASE_URL to an ORIGIN (scheme + host). A path or trailing slash would mis-join with
// a page's leading-slash path (`.com//lightning/...`), which Lightning silently ignores, so it's trimmed.
function normalizeBaseUrl(raw: string): string {
  const trimmed = raw.trim();
  let parsed: URL;
  try {
    parsed = new URL(trimmed);
  } catch {
    console.error(
      `VRT_BASE_URL is not a valid URL. It must be an origin including the scheme, ` +
        `e.g. https://my-org.my.salesforce.com (no path, no trailing slash). Page paths live in the flow JSON.`,
    );
    process.exit(1);
  }
  if (parsed.protocol !== 'http:' && parsed.protocol !== 'https:') {
    console.error(`VRT_BASE_URL must start with http:// or https://.`);
    process.exit(1);
  }
  if ((parsed.pathname && parsed.pathname !== '/') || parsed.search || parsed.hash) {
    console.warn(`VRT_BASE_URL had a path; using its origin. Page paths belong in the flow JSON.`);
  }
  return parsed.origin;
}
 
// Preflight before opening a browser. Any HTTP response (even 4xx / redirect) counts as reachable;
// only connection/DNS/timeout errors abort. Mirrors the runtime message in flow-runner's goto.
async function assertReachable(baseUrl: string): Promise<void> {
  try {
    await fetch(baseUrl, { method: 'HEAD', redirect: 'manual', signal: AbortSignal.timeout(10_000) });
  } catch (e) {
    const detail = e instanceof Error ? e.message : String(e);
    throw new OrgUnavailableError(
      `Org unreachable at ${redact(baseUrl)}. If running locally, check VRT_BASE_URL (it defaults to localhost). (${redact(detail)})`,
      { cause: e },
    );
  }
}
 
const ORG_DOC = 'packages/design-system-2/scripts/vrt-core/README.md#the-test-org';
 
async function main() {
  const args = process.argv.slice(2);
  const flowPath = args.find((a) => !a.startsWith('--'));
  if (!flowPath) {
    console.error(
      'Usage: tsx core/diff.ts <flow.json> [--ref <gitref>] [--css-a p] [--css-b p] [--build]\n' +
        'Env (unless both --css-a and --css-b are given): VRT_REPO_ROOT (default cwd),\n' +
        'VRT_BUILD_CMD (required), VRT_BUNDLE_REL (required), VRT_INSTALL_CMD (optional).',
    );
    process.exit(1);
  }
 
  const getOpt = (name: string): string | undefined => {
    const i = args.indexOf(name);
    return i >= 0 ? args[i + 1] : undefined;
  };
 
  // Baseline defaults to develop since PRs always target it (main is never a PR base).
  const ref = getOpt('--ref') ?? 'develop';
  const prOpt = getOpt('--pr');
  const cssAOpt = getOpt('--css-a');
  const cssBOpt = getOpt('--css-b');
  const forceBuild = args.includes('--build');
 
  // candidateLabel names the on-disk bundle file; displayLabel is the human-readable form for the report.
  const candidateLabel = prOpt ? `pr${prOpt}` : 'working';
  const displayLabel = prOpt ? `PR #${prOpt}` : 'working tree';
 
  // Normalize + validate to a clean origin (fails loudly on a bad URL). Reachability is checked
  // only after the CSS compare, so a PR with no CSS changes passes even when the org is down.
  const baseUrl = normalizeBaseUrl(process.env.VRT_BASE_URL || 'http://localhost:3000');
 
  const screenshotDir = process.env.VRT_SCREENSHOT_DIR || 'core/screenshots';
  const tmpDir = path.join(screenshotDir, 'diff-bundles');
  fs.mkdirSync(tmpDir, { recursive: true });
 
  // Resolve bundle B (candidate); copy the working-tree artifact to a source-named file for traceability.
  let cssBPath: string;
  let labelB: string;
  if (cssBOpt) {
    cssBPath = path.resolve(cssBOpt);
    labelB = path.basename(cssBPath);
  } else {
    const workingBundle = path.join(target().repoRoot, target().bundleRel);
    if (forceBuild || !fs.existsSync(workingBundle)) {
      run(target().buildCmd[0], target().buildCmd[1], target().repoRoot);
    }
    cssBPath = path.join(tmpDir, `${bundleBase()}.${candidateLabel}.css`);
    fs.copyFileSync(workingBundle, cssBPath);
    labelB = candidateLabel;
  }
 
  // Resolve bundle A (baseline = built from --ref, unless overridden).
  let cssAPath: string;
  let labelA: string;
  if (cssAOpt) {
    cssAPath = path.resolve(cssAOpt);
    labelA = path.basename(cssAPath);
  } else {
    // Keyed by the ref's commit, so the worktree install + build only reruns when the ref moves.
    const sha = resolveRefSha(ref, target().repoRoot);
    cssAPath = path.join(tmpDir, `${bundleBase()}.${ref.replace(/[^\w.-]/g, '_')}.${sha.slice(0, 12)}.css`);
    if (fs.existsSync(cssAPath)) {
      console.log(`Reusing cached ${ref} bundle (${sha.slice(0, 12)}) → ${cssAPath}`);
    } else {
      buildBundleFromRef(ref, sha, cssAPath, target());
    }
    labelA = ref;
  }
 
  // Tier-1 CSS attribution: exact declarations changed; feeds Tier-2 per-page DOM matching in the runner.
  const cssA = fs.readFileSync(cssAPath, 'utf8');
  const cssB = fs.readFileSync(cssBPath, 'utf8');
  const cssChanges = diffCssBundles(cssA, cssB);
  const changedSels = changedSelectors(cssChanges);
 
  console.log('Differential VRT');
  console.log(`  bundle A (baseline):  ${cssAPath}  [${labelA}]`);
  console.log(`  bundle B (candidate): ${cssBPath}  [${labelB}]`);
  console.log(`  flow:                 ${flowPath}`);
  console.log(
    `  CSS changes:          ${cssChanges.length} declaration(s) across ${changedSels.length} selector(s)`,
  );
  console.log('---');
 
  // Build the CI run URL from GitHub Actions env vars so the PR comment can link to it; undefined locally.
  const { GITHUB_SERVER_URL, GITHUB_REPOSITORY, GITHUB_RUN_ID } = process.env;
  const runUrl =
    GITHUB_SERVER_URL && GITHUB_REPOSITORY && GITHUB_RUN_ID
      ? `${GITHUB_SERVER_URL}/${GITHUB_REPOSITORY}/actions/runs/${GITHUB_RUN_ID}`
      : undefined;
 
  // The PR's web URL for the report header to link to; falls back to plain text if server/repo/PR are missing.
  const prUrl =
    GITHUB_SERVER_URL && GITHUB_REPOSITORY && prOpt
      ? `${GITHUB_SERVER_URL}/${GITHUB_REPOSITORY}/pull/${prOpt}`
      : undefined;
 
  const prLabel = cssBOpt ? labelB : displayLabel;
  const commentMd = path.join(screenshotDir, 'pr-comment.md');
 
  // Identical CSS can't change a page: pass without touching the org.
  if (sameCss(cssA, cssB)) {
    fs.writeFileSync(
      commentMd,
      buildCommentMarkdown({ prLabel, baselineLabel: labelA, results: [], changes: [], runUrl, prUrl }),
    );
    console.log(`No SLDS CSS changes between ${labelA} and ${labelB}; no pages tested.`);
    console.log(`Wrote ${commentMd}`);
    return;
  }
 
  const config: RunnerConfig = {
    baseUrl,
    headless: process.env.VRT_HEADLESS !== 'false',
    screenshotDir,
  };
 
  const runner = new FlowRunner(config);
  const flow = loadFlow(flowPath);
 
  let results: DiffScreenshotResult[] = [];
  try {
    await assertReachable(baseUrl);
    await runner.init();
    results = await runner.runFlowDifferential(flow, {
      cssAPath,
      cssBPath,
      labelA,
      labelB,
      changedSelectors: changedSels,
      changedRules: changedRuleProps(cssChanges),
    });
  } catch (e) {
    // Say so on the PR; the job still fails.
    if (e instanceof OrgUnavailableError) {
      const docUrl =
        GITHUB_SERVER_URL && GITHUB_REPOSITORY
          ? `${GITHUB_SERVER_URL}/${GITHUB_REPOSITORY}/blob/develop/${ORG_DOC}`
          : undefined;
      fs.writeFileSync(
        commentMd,
        buildOrgUnavailableMarkdown({ prLabel, baselineLabel: labelA, reason: e.message, docUrl }),
      );
    }
    throw e;
  } finally {
    await runner.close();
  }
 
  console.log('---');
  console.log('Differential results:');
  let anyChange = false;
  for (const r of results) {
    if (r.missed) {
      console.log(
        `  ⛔ ${r.name}: ${r.missed.error ? `NOT CAPTURED (${r.missed.error})` : `skipped (depends on ${r.missed.dependsOn})`}`,
      );
    } else if (r.dimensionMismatch) {
      console.log(
        `  ⚠ ${r.name}: REFLOW (A=${r.dimensionMismatch.a.join('x')} B=${r.dimensionMismatch.b.join('x')}) — review ${r.diffPath ?? r.shotBPath}`,
      );
      anyChange = true;
    } else {
      const pct = (r.ratio * 100).toFixed(3);
      const flag = r.noise ? '≈ noise (ignored)' : r.changedPixels > 0 ? '✗ CHANGED' : '✓ identical';
      console.log(
        `  ${flag}  ${r.name}: ${r.changedPixels}/${r.totalPixels} px (${pct}%)  → ${r.diffPath ?? '(no diff img)'}`,
      );
      if (r.changedPixels > 0 && !r.noise) anyChange = true;
    }
  }
 
  // Emit machine-readable results for CI surfacing (PR comment / summary).
  const outJson = path.join(config.screenshotDir!, 'diff-results.json');
  fs.writeFileSync(outJson, JSON.stringify(results, null, 2));
  console.log(`\nWrote ${outJson}`);
 
  const reportInput = {
    prLabel,
    baselineLabel: labelA,
    results,
    changes: cssChanges,
    runUrl,
    prUrl,
  };
  const reportHtml = path.join(config.screenshotDir!, 'visual-report.html');
  fs.writeFileSync(reportHtml, buildReportHtml(reportInput));
  fs.writeFileSync(commentMd, buildCommentMarkdown(reportInput));
  console.log(`Wrote ${reportHtml}`);
  console.log(`Wrote ${commentMd}`);
 
  console.log(
    anyChange ? '\nDifferences found (see visual-report.html).' : '\nNo CSS-attributable differences.',
  );
  // Job stays green; the report and PR comment carry the "incomplete" status.
  const missedCount = results.filter((r) => r.missed).length;
  if (missedCount) console.log(`Incomplete: ${missedCount} of ${results.length} page(s) not captured.`);
}
 
// Run only as the entrypoint, so tests can import the helpers above without starting a run.
const self = fileURLToPath(import.meta.url);
Iif (process.argv[1] && path.resolve(process.argv[1]) === self) {
  // Load local .env (gitignored; no-op in CI).
  dotenv.config({ path: path.resolve(path.dirname(self), '.env') });
  main().catch((err) => {
    console.error(redact(err instanceof Error ? (err.stack ?? err.message) : String(err)));
    process.exitCode = 1;
  });
}