All files / packages/design-tokens/src/validators validator-runner-utils.ts

89.51% Statements 111/124
74.07% Branches 60/81
92.85% Functions 26/28
90.65% Lines 97/107

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              5x 5x   13x           12x       27x                                       20x 20x 20x 20x 20x 20x   20x 20x   20x 20x 20x 20x 20x                             6x 6x   5x 6x 6x 6x 6x   6x 6x   6x 5x 5x             5x 5x 5x 5x 5x     6x               13x       16x 28x             13x 13x 13x   13x 6x 6x 3x 3x 3x   3x 3x 3x     10x     28x 28x 28x   13x 13x 13x     5x   10x 5x   3x     2x 1x 1x 1x 1x                                                                 7x 7x 7x     16x                     7x   7x 7x             7x 7x 7x 7x   15x 7x 1x 1x 2x 2x     1x 1x     7x         7x   7x 16x 16x     7x   7x 7x         7x 7x         4x                
/**
 * Shared utilities for validator runners
 */
import { spawn } from 'child_process';
import readline from 'readline';
import chalk from 'chalk';
 
const SEPARATOR = '='.repeat(80);
const DASH_SEP = '─'.repeat(80);
 
export const parseArgs = (argv: string[] = process.argv) => ({
  isVerbose: argv.includes('--verbose') || argv.includes('-v'),
  isInteractive: argv.includes('--interactive') || argv.includes('-i'),
});
 
/** Create a validator config object */
export const v = (name: string, script: string, description: string, extraArgs: string[] = []) => ({
  name,
  command: process.execPath,
  args: (verboseFlag: string) =>
    ['--import', 'tsx', `src/validators/${script}`, ...extraArgs, verboseFlag].filter(Boolean),
  description,
});
 
export function runValidator(
  validator: {
    name: string;
    description: string;
    category?: string;
    command: string;
    args: string[] | ((verboseFlag: string) => string[]);
  },
  spawnFn: typeof spawn = spawn,
): Promise<{
  name: string;
  status: string;
  code: number | null;
  duration: string;
  category?: string;
}> {
  return new Promise((resolve) => {
    console.log(chalk.bold.blue(`\n${SEPARATOR}`));
    console.log(chalk.bold.blue(`Running: ${validator.name}`));
    console.log(chalk.bold.blue(`Description: ${validator.description}`));
    if (validator.category) console.log(chalk.bold.blue(`Category: ${validator.category}`));
    console.log(chalk.bold.blue(SEPARATOR));
 
    const startTime = Date.now();
    const args = typeof validator.args === 'function' ? validator.args('') : validator.args;
 
    spawnFn(validator.command, args, { stdio: 'inherit', shell: false }).on('close', (code) => {
      const duration = ((Date.now() - startTime) / 1000).toFixed(2);
      const status = code === 0 ? 'PASS' : 'FAIL';
      console.log((code === 0 ? chalk.green : chalk.red)(`\n${status}: ${validator.name} (${duration}s)`));
      resolve({
        name: validator.name,
        status,
        code,
        duration,
        ...(validator.category && { category: validator.category }),
      });
    });
  });
}
 
export function promptContinue(
  nextValidator: { name: string; category?: string },
  { isRlClosed = false } = {},
) {
  return new Promise((resolve) => {
    if (isRlClosed) return resolve(true);
 
    const categoryInfo = nextValidator.category ? ` (${nextValidator.category})` : '';
    console.log(chalk.bold.yellow(`\n${DASH_SEP}`));
    console.log(chalk.bold.yellow(`Next: ${nextValidator.name}${categoryInfo}`));
    console.log(chalk.yellow('Press Enter or Space to continue (or Ctrl+C to exit)...'));
    console.log(chalk.bold.yellow(DASH_SEP));
 
    process.stdin.setRawMode(true);
    process.stdin.resume();
 
    const onKeyPress = (chunk: Buffer | string) => {
      const key = chunk.toString();
      Eif (
        key === '\r' ||
        key === '\n' ||
        key === ' ' ||
        key.charCodeAt(0) === 13 ||
        key.charCodeAt(0) === 32
      ) {
        process.stdin.setRawMode(false);
        process.stdin.pause();
        process.stdin.removeListener('data', onKeyPress);
        console.log('');
        resolve(true);
      }
    };
    process.stdin.on('data', onKeyPress);
  });
}
 
function printResults(
  results: Array<{ status: string; name: string; duration: string; category?: string }>,
  grouped = false,
) {
  const print = (
    items: Array<{ status: string; name: string; duration: string; category?: string }>,
    indent = '',
  ) =>
    items.forEach((r) => {
      console.log(
        (r.status === 'PASS' ? chalk.green : chalk.red)(
          `${indent}${r.status.padEnd(6)} ${r.name.padEnd(50 - indent.length)} ${r.duration}s`,
        ),
      );
    });
 
  console.log(chalk.bold.blue(`\n\n${SEPARATOR}`));
  console.log(chalk.bold.blue('SUMMARY'));
  console.log(chalk.bold.blue(SEPARATOR));
 
  if (grouped) {
    const permanent = results.filter((r) => r.category === 'permanent');
    const temporary = results.filter((r) => r.category === 'temporary');
    Eif (permanent.length) {
      console.log(chalk.bold.cyan('\nPermanent Validators:'));
      print(permanent, '  ');
    }
    Eif (temporary.length) {
      console.log(chalk.bold.cyan('\nTemporary Validators:'));
      print(temporary, '  ');
    }
  } else {
    print(results);
  }
 
  const passed = results.filter((r) => r.status === 'PASS').length;
  const failed = results.filter((r) => r.status === 'FAIL').length;
  const totalTime = results.reduce((sum, r) => sum + parseFloat(r.duration), 0).toFixed(2);
 
  console.log(chalk.bold.blue(`\n${SEPARATOR}`));
  console.log(chalk.bold(`Total: ${passed} passed, ${failed} failed (${totalTime}s)`));
  return { passed, failed, totalTime };
}
 
export const printBasicSummary = (
  results: Array<{ status: string; name: string; duration: string; category?: string }>,
) => printResults(results, false);
export const printCategorizedSummary = (
  results: Array<{ status: string; name: string; duration: string; category?: string }>,
) => printResults(results, true);
 
export function setupSigintHandler(exitFn: typeof process.exit = process.exit) {
  process.on('SIGINT', () => {
    console.log(chalk.yellow('\n\n⚠️  Interrupted by user'));
    Iif ('isRaw' in process.stdin && process.stdin.isRaw) process.stdin.setRawMode(false);
    process.stdin.pause();
    exitFn(130);
  });
}
 
export type RunnerConfig = {
  title: string;
  description: string;
  getValidators: (verboseFlag: string) => Array<{
    name: string;
    description: string;
    category?: string;
    command: string;
    args: string[] | ((verboseFlag: string) => string[]);
  }>;
  printSummary?: (results: Array<{ status: string; name: string; duration: string; category?: string }>) => {
    passed: number;
    failed: number;
    totalTime: string;
  };
  argv?: string[];
  spawnFn?: typeof spawn;
  exitFn?: typeof process.exit;
};
 
export async function createRunner(config: RunnerConfig) {
  const {
    title,
    description,
    getValidators,
    printSummary = printBasicSummary,
    argv = process.argv,
    spawnFn = spawn,
    exitFn = process.exit,
  } = config;
  const { isVerbose, isInteractive } = parseArgs(argv);
  const verboseFlag = isVerbose ? '--verbose' : '';
 
  // Resolve validator args with verboseFlag
  const validators = getValidators(verboseFlag).map((val) => ({
    ...val,
    args: typeof val.args === 'function' ? val.args(verboseFlag) : val.args,
  }));
 
  const results: Array<{
    name: string;
    status: string;
    code: number | null;
    duration: string;
    category?: string;
  }> = [];
  let rl: readline.Interface | undefined,
    isRlClosed = false;
  const closeReadline = () => {
    if (rl && !isRlClosed) {
      rl.close();
      isRlClosed = true;
    }
  };
 
  console.log(chalk.bold.blue(`\n🔍 ${title}`));
  console.log(SEPARATOR);
  console.log(chalk.gray(`${description}\n`));
  console.log(`Total validators to run: ${validators.length}`);
 
  const hasCategories = validators.some((val) => val.category);
  if (hasCategories) {
    const counts = { permanent: 0, temporary: 0 };
    validators.forEach((val) => {
      Eif (val.category === 'permanent' || val.category === 'temporary') {
        counts[val.category]++;
      }
    });
    Eif (counts.permanent) console.log(`  - Permanent: ${counts.permanent}`);
    Eif (counts.temporary) console.log(`  - Temporary: ${counts.temporary}`);
  }
 
  Iif (isInteractive) {
    console.log(chalk.gray('\nInteractive mode: Press Enter or Space to continue between validators'));
    console.log(chalk.gray('Press Ctrl+C at any time to exit'));
    rl = readline.createInterface({ input: process.stdin, output: process.stdout });
  }
  console.log('');
 
  for (let i = 0; i < validators.length; i++) {
    results.push(await runValidator(validators[i], spawnFn));
    Iif (isInteractive && i < validators.length - 1) await promptContinue(validators[i + 1], { isRlClosed });
  }
 
  Iif (isInteractive) closeReadline();
 
  const { passed, failed } = printSummary(results);
  console.log(
    failed === 0
      ? chalk.green('\n✅ All validators passed!\n')
      : chalk.red(`\n❌ ${failed} validator(s) failed\n`),
  );
  exitFn(failed === 0 ? 0 : 1);
  return { passed, failed };
}
 
/** Standard entry point for runner scripts - call with import.meta.url */
export function runMain(main: () => Promise<unknown>, importMetaUrl: string) {
  Iif (importMetaUrl === `file://${process.argv[1]}`) {
    setupSigintHandler();
    main().catch((err) => {
      console.error('\n❌ Error running validators:', err);
      process.exit(1);
    });
  }
}