All files / packages/fds-uif/core/src/validate variant-conflicts.ts

90.19% Statements 92/102
83.33% Branches 65/78
100% Functions 15/15
97.67% Lines 84/86

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                                                                  16x 16x 16x   16x 4x 4x     12x 4x 4x 4x 4x   4x         8x                 8x     8x                                                                                 23x   8x   8x 8x   8x 8x 5x 5x     8x 8x 8x 8x     8x         12x   12x 21x 21x 23x       12x                 3x   2x         1x                     2x         1x                         12x 5x 5x 8x     5x 8x 3x                         12x 12x 21x 21x 23x 12x 12x 12x 12x   12x                 12x               6x 3x                     6x 3x                         12x         12x   12x 12x 6x 6x 6x                                                   26x   26x       26x 26x   26x 14x     12x   12x 12x   12x 8x                         6x   6x   6x 2x 2x                      
/**
 * @fds-uif/core - Variant Conflict Validation
 *
 * Detects when two variants make incompatible structural changes that
 * cannot be merged at runtime:
 *
 * - Two variants modify the same child with conflicting `restrict` (Error)
 *   or `slots` (Warning) values.
 * - Two variants make conflicting changes at the root structure level.
 *
 * Variants within the same variant group are mutually exclusive (only one
 * option applies at a time), so this validator never flags within-group
 * combinations against each other.
 *
 * The deep-equality helper used to compare values is co-located here
 * because variant conflicts are its only consumer; promoting it to
 * `shared.ts` would mislead readers about its scope.
 */
 
import { UifVariantConflictError } from '../errors.js';
import type { PlainObject, Variant, VariantChildChange } from '../types.js';
 
// ============================================================================
// Helpers
// ============================================================================
 
/**
 * Deep equality check for arbitrary values. More reliable than
 * `JSON.stringify` (which would falsely distinguish `{a:1,b:2}` from
 * `{b:2,a:1}` if iteration order ever differed) and avoids the cost of
 * stringifying large variant payloads on every comparison.
 */
function deepEqual(a: unknown, b: unknown): boolean {
  Iif (a === b) return true;
  Iif (a === null || b === null) return false;
  Iif (typeof a !== typeof b) return false;
 
  if (Array.isArray(a) && Array.isArray(b)) {
    Iif (a.length !== b.length) return false;
    return a.every((val, i) => deepEqual(val, b[i]));
  }
 
  if (typeof a === 'object' && typeof b === 'object') {
    const aKeys = Object.keys(a);
    const bKeys = Object.keys(b);
    Iif (aKeys.length !== bKeys.length) return false;
    return aKeys.every(
      (key) =>
        Object.hasOwn(b, key) &&
        deepEqual((a as Record<string, unknown>)[key], (b as Record<string, unknown>)[key]),
    );
  }
 
  return false;
}
 
/**
 * Check if two values conflict (are different). Returns `false` if either
 * value is `undefined`: absence is never a conflict, only differing
 * present values are.
 */
function valuesConflict(val1: unknown, val2: unknown): boolean {
  Iif (val1 === undefined || val2 === undefined) {
    return false;
  }
  return !deepEqual(val1, val2);
}
 
// ============================================================================
// Result type
// ============================================================================
 
/**
 * Result of variant conflict validation.
 */
export interface VariantConflictResult {
  /** Whether there are no conflicts */
  valid: boolean;
  /** Detected conflicts */
  errors: Array<{
    variant1: string;
    variant2: string;
    childName: string;
    property: string;
    value1: unknown;
    value2: unknown;
    severity: 'error' | 'warning';
  }>;
}
 
// ============================================================================
// Child-change conflict detection
// ============================================================================
 
type ChildChangeMap = Map<
  string,
  Map<string, Array<{ variant: string; option: string; changes: VariantChildChange }>>
>;
 
type ChildModification = { variant: string; option: string; changes: VariantChildChange };
 
function recordOptionChildChanges(
  variantName: string,
  option: { value: string; children?: VariantChildChange[] },
  childChanges: ChildChangeMap,
): void {
  if (!option.children) return;
 
  const key = `${variantName}:${option.value}`;
 
  for (const child of option.children) {
    Iif (!child.name) continue;
 
    let childMap = childChanges.get(child.name);
    if (!childMap) {
      childMap = new Map();
      childChanges.set(child.name, childMap);
    }
 
    let entries = childMap.get(key);
    Eif (!entries) {
      entries = [];
      childMap.set(key, entries);
    }
 
    entries.push({ variant: variantName, option: option.value, changes: child });
  }
}
 
function extractVariantChildChanges(variants: Variant[]): ChildChangeMap {
  const childChanges: ChildChangeMap = new Map();
 
  for (const variant of variants) {
    Iif (!variant.options) continue;
    for (const option of variant.options) {
      recordOptionChildChanges(variant.name, option, childChanges);
    }
  }
 
  return childChanges;
}
 
function checkChildModConflict(
  mod1: ChildModification,
  mod2: ChildModification,
  childName: string,
  errors: VariantConflictResult['errors'],
): void {
  if (mod1.variant === mod2.variant) return;
 
  if (
    mod1.changes.restrict !== undefined &&
    mod2.changes.restrict !== undefined &&
    valuesConflict(mod1.changes.restrict, mod2.changes.restrict)
  ) {
    errors.push({
      variant1: `${mod1.variant}:${mod1.option}`,
      variant2: `${mod2.variant}:${mod2.option}`,
      childName,
      property: 'restrict',
      value1: mod1.changes.restrict,
      value2: mod2.changes.restrict,
      severity: 'error',
    });
  }
 
  if (
    mod1.changes.slots !== undefined &&
    mod2.changes.slots !== undefined &&
    valuesConflict(mod1.changes.slots, mod2.changes.slots)
  ) {
    errors.push({
      variant1: `${mod1.variant}:${mod1.option}`,
      variant2: `${mod2.variant}:${mod2.option}`,
      childName,
      property: 'slots',
      value1: mod1.changes.slots,
      value2: mod2.changes.slots,
      severity: 'warning',
    });
  }
}
 
function detectChildConflicts(childChanges: ChildChangeMap, errors: VariantConflictResult['errors']): void {
  for (const [childName, modifications] of childChanges) {
    const allMods: ChildModification[] = [];
    for (const mods of modifications.values()) {
      allMods.push(...mods);
    }
 
    for (let i = 0; i < allMods.length; i++) {
      for (let j = i + 1; j < allMods.length; j++) {
        checkChildModConflict(allMods[i], allMods[j], childName, errors);
      }
    }
  }
}
 
// ============================================================================
// Root-change conflict detection
// ============================================================================
 
type RootChange = { variant: string; option: string; restrict?: string[]; slots?: Record<string, boolean> };
 
function extractRootChanges(variants: Variant[]): Map<string, RootChange[]> {
  const changes = new Map<string, RootChange[]>();
  for (const variant of variants) {
    Iif (!variant.options) continue;
    for (const option of variant.options) {
      if (option.restrict || option.slots) {
        let list = changes.get(variant.name);
        Eif (!list) {
          list = [];
          changes.set(variant.name, list);
        }
        list.push({
          variant: variant.name,
          option: option.value,
          restrict: option.restrict,
          slots: option.slots,
        });
      }
    }
  }
  return changes;
}
 
function checkRootChangeConflict(
  c1: RootChange,
  c2: RootChange,
  errors: VariantConflictResult['errors'],
): void {
  if (c1.restrict && c2.restrict && valuesConflict(c1.restrict, c2.restrict)) {
    errors.push({
      variant1: `${c1.variant}:${c1.option}`,
      variant2: `${c2.variant}:${c2.option}`,
      childName: '(root)',
      property: 'restrict',
      value1: c1.restrict,
      value2: c2.restrict,
      severity: 'error',
    });
  }
 
  if (c1.slots && c2.slots && valuesConflict(c1.slots, c2.slots)) {
    errors.push({
      variant1: `${c1.variant}:${c1.option}`,
      variant2: `${c2.variant}:${c2.option}`,
      childName: '(root)',
      property: 'slots',
      value1: c1.slots,
      value2: c2.slots,
      severity: 'warning',
    });
  }
}
 
function detectRootConflicts(variants: Variant[], errors: VariantConflictResult['errors']): void {
  const rootChanges = extractRootChanges(variants);
  // Materialize the entry list once so each pair (groupA, groupB) walks
  // the map without round-tripping through `.get(name)!` (which Sonar
  // flags as a meaningless non-null assertion since `Map.get` is
  // `V | undefined`).
  const groups = Array.from(rootChanges.values());
 
  for (let i = 0; i < groups.length; i++) {
    for (let j = i + 1; j < groups.length; j++) {
      for (const c1 of groups[i]) {
        for (const c2 of groups[j]) {
          checkRootChangeConflict(c1, c2, errors);
        }
      }
    }
  }
}
 
// ============================================================================
// Public API
// ============================================================================
 
/**
 * Validate variants for conflicting structural changes.
 *
 * According to the RFC, conflicts occur when:
 * - Two variants modify the same child with incompatible values (Error)
 * - Variant disables a slot that another variant requires (Warning)
 * - Variants specify incompatible element types (Error)
 *
 * Note: Variants within the same variant group are mutually exclusive
 * and won't trigger conflicts against each other.
 *
 * @param uif - The UIF definition to validate
 * @returns Validation result with detected conflicts
 */
export function validateVariantConflicts(uif: unknown): VariantConflictResult {
  const errors: VariantConflictResult['errors'] = [];
 
  Iif (typeof uif !== 'object' || uif === null) {
    return { valid: true, errors: [] };
  }
 
  const record = uif as PlainObject;
  const structure = record.structure as PlainObject | undefined;
 
  if (!structure || !Array.isArray(structure.variants)) {
    return { valid: true, errors: [] };
  }
 
  const variants: Variant[] = structure.variants;
 
  detectChildConflicts(extractVariantChildChanges(variants), errors);
  detectRootConflicts(variants, errors);
 
  return {
    valid: errors.filter((e) => e.severity === 'error').length === 0,
    errors,
  };
}
 
/**
 * Validate variant conflicts and throw if errors are found. Warnings do
 * not throw: they're advisory and reported via {@link validateUif}.
 *
 * @param uif - The UIF definition to validate
 * @throws {UifVariantConflictError} If error-severity variant conflicts are found
 */
export function validateVariantConflictsOrThrow(uif: unknown): void {
  const result = validateVariantConflicts(uif);
 
  const errorConflicts = result.errors.filter((e) => e.severity === 'error');
 
  if (errorConflicts.length > 0) {
    const firstError = errorConflicts[0];
    throw new UifVariantConflictError(
      'structure.variants',
      firstError.variant1,
      firstError.variant2,
      firstError.property,
      firstError.childName === '(root)' ? undefined : firstError.childName,
      firstError.value1,
      firstError.value2,
    );
  }
}