All files / packages/icons/scripts validate.ts

82.75% Statements 120/145
75.55% Branches 68/90
88.23% Functions 15/17
82.63% Lines 119/144

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                                        2x               2x                           15x 15x     15x     15x 1x               14x     14x     14x 14x 14x     14x     14x     14x       14x 9x 5x 1x   4x     14x             15x 15x   15x     15x 15x 1x       15x             14x 14x   14x         14x 2x     14x 2x     14x 3x     14x             14x   14x 15x 1x       14x                   14x 14x 14x 14x   14x 1x     14x 1x 1x 1x       14x                 14x             14x 14x 14x 14x   14x 1x   14x 1x       1x 1x     13x 1x       14x             14x   14x 1x     13x   13x 13x   13x       13x 13x   13x             13x 13x 13x   14x 1x           12x             14x 14x 14x 14x 14x   14x 1x   14x 1x 1x   1x       1x       13x   13x 1x       14x                                                                             2x 2x   2x 4x     4x 4x 1x 1x   3x     4x     2x               1910x             1910x   1910x       1910x 11x     1910x       1910x       1910x    
/**
 * Icon validation module
 * Pure validation logic with no I/O side effects
 * Shared by test suite (Step 6) and workflow UI layer (Step 9)
 */
 
import type { ParsedIcon, IconType } from './csv-parser.js';
import { JSDOM } from 'jsdom';
 
export interface ValidationResult {
  errors: string[];
  warnings: string[];
  validation: 'Success ✅' | 'Warning ⚠️' | 'Error ❌';
  lineFailures?: Array<{ line: number; message: string }>;
}
 
export interface SvgStructureValidationResult {
  errors: string[];
}
 
const ICON_SIZE: Record<IconType, number> = {
  utility: 52,
  standard: 100,
  action: 52,
  doctype: 100,
  custom: 100,
};
 
const SUPPORTED_ICON_TYPES: IconType[] = ['standard', 'utility', 'action', 'doctype', 'custom'];
 
/**
 * Validate a parsed icon
 * @param icon - Parsed icon object to validate
 * @param colorPalette - Color palette for color validation
 * @param existingIconPaths - Optional set of existing icon paths in repo (e.g., 'svg/standard/common/account.svg')
 * @returns Validation result with errors and warnings
 */
export function validateIcon(
  icon: ParsedIcon,
  colorPalette: Record<string, string>,
  existingIconPaths: Set<string> = new Set(),
): ValidationResult {
  let errors: string[] = [];
  let warnings: string[] = [];
 
  // Validate icon type
  errors = [...errors, ...validateIconType(icon.icon_type)];
 
  // If icon type has errors, return early
  if (errors.length > 0) {
    return {
      errors,
      warnings,
      validation: 'Error ❌',
    };
  }
 
  // Validate icon name
  errors = [...errors, ...validateIconName(icon.icon_name)];
 
  // Validate synonyms
  errors = [...errors, ...validateSynonyms(icon.synonyms)];
 
  // Validate color
  const colorValidation = validateColor(icon, colorPalette);
  errors = [...errors, ...colorValidation.errors];
  warnings = [...warnings, ...colorValidation.warnings];
 
  // Validate SVG presence
  errors = [...errors, ...validateSvgPresence(icon)];
 
  // Validate icon size
  errors = [...errors, ...validateIconSize(icon)];
 
  // Check if icon already exists in repo
  errors = [...errors, ...checkIconExists(icon, existingIconPaths)];
 
  // Determine validation status
  let validation: ValidationResult['validation'];
  if (errors.length > 0) {
    validation = 'Error ❌';
  } else if (warnings.length > 0) {
    validation = 'Warning ⚠️';
  } else {
    validation = 'Success ✅';
  }
 
  return { errors, warnings, validation };
}
 
/**
 * Validate icon type is supported
 */
function validateIconType(iconType: string): string[] {
  const errors: string[] = [];
  const trimmed = iconType.trim().toLowerCase();
 
  Iif (!trimmed) {
    errors.push('Icon Type is empty');
  } else {
    const isSupported = SUPPORTED_ICON_TYPES.includes(trimmed as IconType);
    if (!isSupported) {
      errors.push(`Supported Icon types: ${SUPPORTED_ICON_TYPES.join(' | ')}`);
    }
  }
 
  return errors;
}
 
/**
 * Validate icon name follows naming conventions
 */
function validateIconName(iconName: string): string[] {
  const errors: string[] = [];
  const trimmed = iconName.trim();
 
  Iif (!trimmed) {
    errors.push('Icon Name is empty');
    return errors;
  }
 
  if (trimmed !== trimmed.toLowerCase()) {
    errors.push('Icon Name should be in lowercase.');
  }
 
  if (trimmed.includes(' ')) {
    errors.push('Icon Name should not contain space.');
  }
 
  if (!/^[a-z_]+$/.test(trimmed)) {
    errors.push('Only underscores are allowed as special characters in Icon Name.');
  }
 
  return errors;
}
 
/**
 * Validate synonyms follow naming conventions
 */
function validateSynonyms(synonyms: string[]): string[] {
  const errors: string[] = [];
 
  synonyms.forEach((syn) => {
    if (!/^[a-z\s]+$/.test(syn)) {
      errors.push(`${syn} synonym should be in lowercase & without special characters.`);
    }
  });
 
  return errors;
}
 
/**
 * Validate icon color
 */
function validateColor(
  icon: ParsedIcon,
  colorPalette: Record<string, string>,
): { errors: string[]; warnings: string[] } {
  const errors: string[] = [];
  const warnings: string[] = [];
  const iconColor = icon.color;
  const isUtilityOrDocType = icon.icon_type === 'utility' || icon.icon_type === 'doctype';
 
  if (isUtilityOrDocType && iconColor.length !== 0) {
    warnings.push('Color is present for Utility/Doctype icon but will be ignored.');
  }
 
  if (!isUtilityOrDocType) {
    const isStandardOrAction = icon.icon_type === 'standard' || icon.icon_type === 'action';
    Eif (isStandardOrAction && iconColor.length === 0) {
      errors.push('Color is required for Standard or Action icons.');
    }
  }
 
  Iif (iconColor && !isUtilityOrDocType) {
    const paletteKey = `PALETTE_${iconColor.toUpperCase().replaceAll('-', '_')}`;
    const iconPaletteColor = colorPalette[paletteKey];
 
    if (!iconPaletteColor) {
      errors.push('Color reference not found in color palette.');
    }
  }
 
  return { errors, warnings };
}
 
/**
 * Validate SVG files are present in icon object
 */
function validateSvgPresence(icon: ParsedIcon): string[] {
  const errors: string[] = [];
  const hasLtrRtl = icon.has_ltr_rtl === 'yes';
  const iconType = icon.icon_type;
  const fileName = icon.file_name;
 
  const prepareSvgMissingErrMsg = (iconType: string, subPath: string): string =>
    `${fileName} is missing in ${iconType}/${subPath} directory.`;
 
  if (hasLtrRtl) {
    Iif (!icon.ltr_svg) {
      errors.push(prepareSvgMissingErrMsg(iconType, 'ltr'));
    }
 
    Eif (!icon.rtl_svg) {
      errors.push(prepareSvgMissingErrMsg(iconType, 'rtl'));
    }
  } else {
    if (!icon.common_svg) {
      errors.push(`${fileName} is missing in ${iconType}/common/ or ${iconType}/ directory.`);
    }
  }
 
  return errors;
}
 
/**
 * Validate icon SVG dimensions match expected size for icon type
 */
function validateIconSize(icon: ParsedIcon): string[] {
  const svgHTML = icon.ltr_svg || icon.rtl_svg || icon.common_svg || '';
 
  if (!svgHTML || icon.icon_type === 'doctype') {
    return [];
  }
 
  const iconType = icon.icon_type.toLowerCase().trim() as IconType;
 
  try {
    const wrapper = new JSDOM(svgHTML).window.document.querySelector('svg');
 
    Iif (!wrapper) {
      return ['SVG element not found in SVG content.'];
    }
 
    let width = wrapper.getAttribute('width');
    let height = wrapper.getAttribute('height');
 
    Iif (!width || !height) {
      const viewBox = wrapper.getAttribute('viewBox');
      if (viewBox) {
        [width, height] = viewBox.split(' ').slice(-2);
      }
    }
 
    const w = Number(width);
    const h = Number(height);
    const expectedSize = ICON_SIZE[iconType];
 
    if ([w, h].every((d) => d !== expectedSize)) {
      return [`${iconType} icon type must have size ${expectedSize}x${expectedSize}`];
    }
  } catch (error) {
    return [`Failed to parse SVG: ${error instanceof Error ? error.message : String(error)}`];
  }
 
  return [];
}
 
/**
 * Check if icon already exists in the repository
 */
function checkIconExists(icon: ParsedIcon, existingIconPaths: Set<string>): string[] {
  const errors: string[] = [];
  const iconName = icon.icon_name;
  const iconType = icon.icon_type;
  const fileName = icon.file_name;
  const hasLtrRtl = icon.has_ltr_rtl === 'yes';
 
  const prepareSvgErrMsg = (iconName: string, iconType: string, subPath: string, fileName: string): string =>
    `'${iconName}' is already present in ${iconType}/${subPath}/${fileName}`;
 
  if (hasLtrRtl) {
    const ltrPath = `svg/${iconType}/ltr/${fileName}`;
    const rtlPath = `svg/${iconType}/rtl/${fileName}`;
 
    Iif (existingIconPaths.has(ltrPath)) {
      errors.push(prepareSvgErrMsg(iconName, iconType, 'ltr', fileName));
    }
 
    Iif (existingIconPaths.has(rtlPath)) {
      errors.push(prepareSvgErrMsg(iconName, iconType, 'rtl', fileName));
    }
  } else {
    const commonPath = `svg/${iconType}/common/${fileName}`;
 
    if (existingIconPaths.has(commonPath)) {
      errors.push(prepareSvgErrMsg(iconName, iconType, 'common', fileName));
    }
  }
 
  return errors;
}
 
/**
 * Check for duplicate icon entries in the parsed icon list
 * @param icons - Array of parsed icons
 * @returns Updated icons array with duplicate errors added
 */
export function checkDuplicateIcons(icons: ParsedIcon[]): ParsedIcon[] {
  const iconSet = new Set<string>();
 
  return icons.map((icon) => {
    const iconNameType = `${icon.icon_name}-${icon.icon_type}`;
 
    if (iconSet.has(iconNameType)) {
      return {
        ...icon,
        // This would need to be handled externally since ParsedIcon doesn't have errors field
        // The validation result should be merged
      };
    }
 
    iconSet.add(iconNameType);
    return icon;
  });
}
 
/**
 * Validate multiple icons and check for duplicates
 * @param icons - Array of parsed icons
 * @param colorPalette - Color palette for validation
 * @param existingIconPaths - Set of existing icon paths in repo
 * @returns Map of icon IDs to validation results
 */
export function validateIcons(
  icons: ParsedIcon[],
  colorPalette: Record<string, string>,
  existingIconPaths: Set<string> = new Set(),
): Map<string, ValidationResult> {
  const results = new Map<string, ValidationResult>();
  const iconSet = new Set<string>();
 
  icons.forEach((icon) => {
    const validation = validateIcon(icon, colorPalette, existingIconPaths);
 
    // Check for duplicates
    const iconNameType = `${icon.icon_name}-${icon.icon_type}`;
    if (iconSet.has(iconNameType)) {
      validation.errors.push(`'${icon.icon_name}' icon of ${icon.icon_type} type is already listed above.`);
      validation.validation = 'Error ❌';
    } else {
      iconSet.add(iconNameType);
    }
 
    results.set(icon.id, validation);
  });
 
  return results;
}
 
/**
 * Validate structural SVG rules that must be shared by tests and UI flows.
 * These checks intentionally mirror Step 6 requirements.
 */
export function validateSvgStructure(svgContent: string): SvgStructureValidationResult {
  const errors: string[] = [];
 
  // These are flat structural checks (no <g>, no <style>, no class attribute).
  // A full JSDOM parse per file made the icon suite spin up ~1900 documents and
  // blow past the default test timeout; lightweight scanning is equivalent here
  // and orders of magnitude faster. Strip comments/CDATA first so tokens inside
  // them don't produce false positives.
  const stripped = svgContent.replace(/<!--[\s\S]*?-->/g, '').replace(/<!\[CDATA\[[\s\S]*?\]\]>/g, '');
 
  Iif (!/<svg[\s>]/i.test(stripped)) {
    return { errors: ['Missing <svg> element.'] };
  }
 
  if (/<g[\s>]/i.test(stripped)) {
    errors.push('SVG must not contain <g> groups.');
  }
 
  Iif (/<style[\s>]/i.test(stripped)) {
    errors.push('SVG must not contain <style> tags.');
  }
 
  Iif (/\sclass\s*=/i.test(stripped)) {
    errors.push('SVG must not contain class attributes.');
  }
 
  return { errors };
}