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 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 | 13x 9x 9x 9x 1x 71x 8x 58x 58x 457x 457x 457x 457x 58x 8x 9x 9x 9x 3x 3x 3x 9x 255x 255x 255x 105x 335x 150x 4x 4x 14x 14x 14x 3x 3x 4x 4x 4x 4x 4x 7x 13x 44x 44x 68x 68x 68x 13x 55x 1x 29x 29x 29x 29x 29x 29x 29x 7x 12x 12x 12x 12x 12x 30x 1x 29x 174x 31x 29x 4x 2x 2x 4x 4x 20x 20x 20x 20x 20x 20x 20x 12x 16x 16x 9x 9x 20x 5x 2x 2x 19x 34x 34x 34x 34x 7x 7x 1x 20x 20x 20x 18x 20x 4x 1x 1x 11x 19x 21x 8x 5x 8x 8x 8x 8x 11x 7x 20x 20x 20x 9x 11x 11x 5x 8x 5x 8x 3x 3x 1x 1x 1x 11x 19x 10x 10x 11x 11x 10x 5x 5x 2x 3x 11x 7x 5x 5x 1x 1x 9x 9x 9x 8x 1x 8x 2x 1x 1x 2x 2x 9x 1x 1x 8x 2x 2x 2x 1x 9x 3x 2x 2x 2x 2x | /**
* @fds-uif/core - Validation Utilities
*
* Utilities for validating UIF definitions beyond schema validation.
* These checks ensure semantic correctness after merging.
*/
import {
UifConflictingMarkersError,
UifDuplicateIdentifierError,
UifInvalidStateReferenceError,
UifVariantConflictError,
} from './errors.js';
import {
IDENTIFIED_ARRAYS,
MARKER_AFTER,
MARKER_BEFORE,
} from './constants.js';
import type {
PlainObject,
ValidationError,
ValidationOptions,
ValidationResult,
Variant,
VariantChildChange,
VariantOption,
} from './types.js';
// ============================================================================
// Constants
// ============================================================================
/** Error codes for validation errors */
export const ValidationErrorCode = {
DUPLICATE_IDENTIFIER: 'UIF_DUPLICATE_IDENTIFIER',
INVALID_STATE_REFERENCE: 'UIF_INVALID_STATE_REFERENCE',
CONFLICTING_MARKERS: 'UIF_CONFLICTING_MARKERS',
VARIANT_CONFLICT: 'UIF_VARIANT_CONFLICT',
} as const;
// ============================================================================
// Utility Functions
// ============================================================================
/**
* Calculate Levenshtein distance between two strings.
* Used for "did you mean?" suggestions.
*
* Optimized with early termination when distance exceeds threshold.
*/
function levenshteinDistance(a: string, b: string, maxDistance?: number): number {
// Early termination for identical strings
Iif (a === b) return 0;
const aLen = a.length;
const bLen = b.length;
// Early termination if length difference exceeds max distance
if (maxDistance !== undefined && Math.abs(aLen - bLen) > maxDistance) {
return maxDistance + 1;
}
// Use single array instead of matrix for memory efficiency
const row: number[] = Array.from({ length: bLen + 1 }, (_, i) => i);
for (let i = 1; i <= aLen; i++) {
let prev = i;
for (let j = 1; j <= bLen; j++) {
const cost = a[i - 1] === b[j - 1] ? 0 : 1;
const current = Math.min(
row[j] + 1, // deletion
prev + 1, // insertion
row[j - 1] + cost // substitution
);
row[j - 1] = prev;
prev = current;
}
row[bLen] = prev;
}
return row[bLen];
}
/**
* Find the closest match for a string from a list of candidates.
* Returns undefined if no close match is found.
*/
function findClosestMatch(target: string, candidates: string[], maxDistance = 2): string | undefined {
const targetLower = target.toLowerCase();
let bestMatch: string | undefined;
let bestDistance = maxDistance + 1;
for (const candidate of candidates) {
const distance = levenshteinDistance(targetLower, candidate.toLowerCase(), bestDistance);
if (distance < bestDistance) {
bestDistance = distance;
bestMatch = candidate;
// Early exit if we found an exact match
Iif (distance === 0) break;
}
}
return bestDistance <= maxDistance ? bestMatch : undefined;
}
/**
* Get a value from a nested object using a dot-notation path.
*/
function getByPath(obj: unknown, path: string): unknown {
Iif (!path) return obj;
const parts = path.split('.');
let current: unknown = obj;
for (const part of parts) {
if (current === null || current === undefined) {
return undefined;
}
if (typeof current !== 'object') {
return undefined;
}
current = (current as Record<string, unknown>)[part];
}
return current;
}
/**
* Format a path for user-friendly display.
* Converts "structure.children[0].name" to "structure > children[0] > name"
*/
function formatPathForDisplay(path: string): string {
return path.replace(/\./g, ' > ').replace(/\[(\d+)\]/g, '[$1]');
}
/**
* Format the path line for error messages.
* Notes that this is a path in the merged UIF, not a source file location.
*/
function formatPathLine(path: string): string {
return `Path (in merged UIF): ${formatPathForDisplay(path)}`;
}
/**
* Deep equality check for values (more reliable than JSON.stringify).
*/
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.prototype.hasOwnProperty.call(b, key) &&
deepEqual((a as Record<string, unknown>)[key], (b as Record<string, unknown>)[key])
);
}
return false;
}
// ============================================================================
// Identifier Validation
// ============================================================================
/**
* Configuration for identifier validation.
*/
interface IdentifierConfig {
/** JSON path pattern to the array */
path: string;
/** The field used as identifier */
field: string;
/** Whether to validate recursively (for nested children) */
recursive?: boolean;
}
/**
* All identified arrays in UIF and their configuration.
*/
const IDENTIFIER_CONFIGS: IdentifierConfig[] = [
{ path: 'states', field: IDENTIFIED_ARRAYS.states },
{ path: 'structure.modifiers', field: IDENTIFIED_ARRAYS.modifiers },
{ path: 'structure.variants', field: IDENTIFIED_ARRAYS.variants },
{ path: 'structure.variants.*.options', field: IDENTIFIED_ARRAYS.options },
{ path: 'stateClasses', field: IDENTIFIED_ARRAYS.stateClasses },
{ path: 'structure.children', field: IDENTIFIED_ARRAYS.children, recursive: true },
{ path: 'accessibility.requirements', field: IDENTIFIED_ARRAYS.requirements },
];
/**
* Result of identifier validation.
*/
export interface IdentifierValidationResult {
/** Whether all identifiers are valid (no duplicates) */
valid: boolean;
/** List of duplicate identifier errors */
errors: Array<{
path: string;
field: string;
duplicate: string;
}>;
}
/**
* Check an array for duplicate identifiers.
*/
function checkArrayDuplicates(
arr: unknown[],
field: string,
path: string,
errors: IdentifierValidationResult['errors'],
recursive: boolean = false,
childrenField: string = 'children',
): void {
const seen = new Set<string>();
for (let i = 0; i < arr.length; i++) {
const item = arr[i];
if (typeof item !== 'object' || item === null) {
continue;
}
const record = item as Record<string, unknown>;
const identifier = record[field];
if (typeof identifier === 'string') {
if (seen.has(identifier)) {
errors.push({
path: `${path}[${i}]`,
field,
duplicate: identifier,
});
} else {
seen.add(identifier);
}
}
// Recursively check children if configured
if (recursive && Array.isArray(record[childrenField])) {
checkArrayDuplicates(
record[childrenField] as unknown[],
field,
`${path}[${i}].${childrenField}`,
errors,
recursive,
childrenField,
);
}
}
}
/**
* Validate paths containing wildcards.
*/
function validateWildcardPath(
uif: unknown,
config: IdentifierConfig,
errors: IdentifierValidationResult['errors'],
): void {
const parts = config.path.split('.');
const wildcardIndex = parts.indexOf('*');
Iif (wildcardIndex === -1) return;
// Get path up to wildcard
const prePath = parts.slice(0, wildcardIndex).join('.');
const postPath = parts.slice(wildcardIndex + 1).join('.');
const preValue = prePath ? getByPath(uif, prePath) : uif;
if (!Array.isArray(preValue)) return;
// Iterate over array items
for (let i = 0; i < preValue.length; i++) {
const item = preValue[i];
const itemPath = prePath ? `${prePath}[${i}]` : `[${i}]`;
const targetArr = postPath ? getByPath(item, postPath) : item;
if (Array.isArray(targetArr)) {
const fullPath = postPath ? `${itemPath}.${postPath}` : itemPath;
checkArrayDuplicates(targetArr, config.field, fullPath, errors, config.recursive);
}
}
}
/**
* Validate that all identified arrays in a UIF have unique identifiers.
*
* @param uif - The UIF definition to validate
* @returns Validation result with any duplicate errors
*
* @example
* ```ts
* import { validateIdentifiers } from '@fds-uif/core';
*
* const result = validateIdentifiers(myUif);
* if (!result.valid) {
* console.error('Duplicate identifiers found:', result.errors);
* }
* ```
*/
export function validateIdentifiers(uif: unknown): IdentifierValidationResult {
const errors: IdentifierValidationResult['errors'] = [];
if (typeof uif !== 'object' || uif === null) {
return { valid: true, errors: [] };
}
for (const config of IDENTIFIER_CONFIGS) {
// Handle paths with wildcards (e.g., 'structure.variants.*.options')
if (config.path.includes('*')) {
validateWildcardPath(uif, config, errors);
} else {
const arr = getByPath(uif, config.path);
if (Array.isArray(arr)) {
checkArrayDuplicates(arr, config.field, config.path, errors, config.recursive);
}
}
}
return {
valid: errors.length === 0,
errors,
};
}
/**
* Validate identifiers and throw if duplicates are found.
*
* @param uif - The UIF definition to validate
* @throws {UifDuplicateIdentifierError} If duplicate identifiers are found
*
* @example
* ```ts
* import { validateIdentifiersOrThrow } from '@fds-uif/core';
*
* try {
* validateIdentifiersOrThrow(myUif);
* } catch (error) {
* if (error instanceof UifDuplicateIdentifierError) {
* console.error('Duplicate found:', error.duplicateValue);
* }
* }
* ```
*/
export function validateIdentifiersOrThrow(uif: unknown): void {
const result = validateIdentifiers(uif);
if (!result.valid && result.errors.length > 0) {
const firstError = result.errors[0];
throw new UifDuplicateIdentifierError(firstError.path, firstError.field, firstError.duplicate);
}
}
// ============================================================================
// State Reference Validation
// ============================================================================
/**
* Result of state reference validation.
*/
export interface StateReferenceValidationResult {
/** Whether all state references are valid */
valid: boolean;
/** Invalid state references with suggestions */
errors: Array<{
state: string;
path: string;
suggestion?: string;
}>;
/** Available states for reference */
availableStates: string[];
}
/**
* Validate that stateClasses reference valid states.
*
* @param uif - The UIF definition to validate
* @returns Array of invalid state references (for backwards compatibility)
*/
export function validateStateReferences(uif: unknown): string[] {
const result = validateStateReferencesDetailed(uif);
return result.errors.map((e) => e.state);
}
/**
* Validate state references with detailed results.
*
* @param uif - The UIF definition to validate
* @returns Detailed validation result with suggestions
*/
export function validateStateReferencesDetailed(uif: unknown): StateReferenceValidationResult {
if (typeof uif !== 'object' || uif === null) {
return { valid: true, errors: [], availableStates: [] };
}
const record = uif as Record<string, unknown>;
const errors: StateReferenceValidationResult['errors'] = [];
// Get available state names
const states = record.states;
const stateNames: string[] = [];
if (Array.isArray(states)) {
for (const state of states) {
if (typeof state === 'object' && state !== null) {
const name = (state as Record<string, unknown>).name;
if (typeof name === 'string') {
stateNames.push(name);
}
}
}
}
// Check stateClasses references
const stateClasses = record.stateClasses;
if (Array.isArray(stateClasses)) {
for (let i = 0; i < stateClasses.length; i++) {
const sc = stateClasses[i];
if (typeof sc === 'object' && sc !== null) {
const stateRef = (sc as Record<string, unknown>).state;
if (typeof stateRef === 'string' && !stateNames.includes(stateRef)) {
const suggestion = findClosestMatch(stateRef, stateNames);
errors.push({
state: stateRef,
path: `stateClasses[${i}]`,
suggestion,
});
}
}
}
}
return {
valid: errors.length === 0,
errors,
availableStates: stateNames,
};
}
/**
* Validate state references and throw if invalid.
*
* @param uif - The UIF definition to validate
* @throws {UifInvalidStateReferenceError} If invalid state references are found
*/
export function validateStateReferencesOrThrow(uif: unknown): void {
const result = validateStateReferencesDetailed(uif);
if (!result.valid && result.errors.length > 0) {
const firstError = result.errors[0];
throw new UifInvalidStateReferenceError(
firstError.path,
firstError.state,
result.availableStates,
firstError.suggestion,
);
}
}
// ============================================================================
// Marker Validation
// ============================================================================
/**
* Result of marker validation.
*/
export interface MarkerValidationResult {
/** Whether all markers are valid */
valid: boolean;
/** Items with conflicting markers */
errors: Array<{
path: string;
identifier?: string;
beforeValue: string;
afterValue: string;
}>;
}
/**
* Validate an array for items with conflicting $before/$after markers.
*/
function checkArrayMarkers(
arr: unknown[],
path: string,
identifierField: string | undefined,
errors: MarkerValidationResult['errors'],
): void {
for (let i = 0; i < arr.length; i++) {
const item = arr[i];
if (typeof item !== 'object' || item === null) {
continue;
}
const record = item as Record<string, unknown>;
const hasBefore = typeof record[MARKER_BEFORE] === 'string';
const hasAfter = typeof record[MARKER_AFTER] === 'string';
if (hasBefore && hasAfter) {
const identifier = identifierField ? (record[identifierField] as string) : undefined;
errors.push({
path: `${path}[${i}]`,
identifier,
beforeValue: record[MARKER_BEFORE] as string,
afterValue: record[MARKER_AFTER] as string,
});
}
// Recursively check children
if (Array.isArray(record.children)) {
checkArrayMarkers(
record.children as unknown[],
`${path}[${i}].children`,
'name',
errors,
);
}
}
}
/**
* Validate that no items have both $before and $after markers.
*
* @param uif - The UIF definition to validate
* @returns Validation result
*/
export function validateMarkers(uif: unknown): MarkerValidationResult {
const errors: MarkerValidationResult['errors'] = [];
if (typeof uif !== 'object' || uif === null) {
return { valid: true, errors: [] };
}
const record = uif as Record<string, unknown>;
// Check all identified arrays that can have markers
const arraysToCheck = [
{ path: 'states', arr: record.states, field: 'name' },
{ path: 'structure.modifiers', arr: getByPath(record, 'structure.modifiers'), field: 'name' },
{ path: 'structure.children', arr: getByPath(record, 'structure.children'), field: 'name' },
{ path: 'stateClasses', arr: record.stateClasses, field: 'state' },
];
for (const { path, arr, field } of arraysToCheck) {
if (Array.isArray(arr)) {
checkArrayMarkers(arr, path, field, errors);
}
}
return {
valid: errors.length === 0,
errors,
};
}
/**
* Validate markers and throw if conflicts are found.
*
* @param uif - The UIF definition to validate
* @throws {UifConflictingMarkersError} If conflicting markers are found
*/
export function validateMarkersOrThrow(uif: unknown): void {
const result = validateMarkers(uif);
if (!result.valid && result.errors.length > 0) {
const firstError = result.errors[0];
throw new UifConflictingMarkersError(
firstError.path,
firstError.identifier,
firstError.beforeValue,
firstError.afterValue,
);
}
}
// ============================================================================
// Variant Conflict Detection
// ============================================================================
/**
* 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';
}>;
}
/**
* Extract child modifications from variant options.
*/
function extractVariantChildChanges(
variants: Variant[],
): Map<string, Map<string, Array<{ variant: string; option: string; changes: VariantChildChange }>>> {
const childChanges = new Map<
string,
Map<string, Array<{ variant: string; option: string; changes: VariantChildChange }>>
>();
for (const variant of variants) {
Iif (!variant.options) continue;
for (const option of variant.options as VariantOption[]) {
if (!option.children) continue;
for (const child of option.children) {
Iif (!child.name) continue;
if (!childChanges.has(child.name)) {
childChanges.set(child.name, new Map());
}
const childMap = childChanges.get(child.name)!;
const key = `${variant.name}:${option.value}`;
if (!childMap.has(key)) {
childMap.set(key, []);
}
childMap.get(key)!.push({
variant: variant.name,
option: option.value,
changes: child,
});
}
}
}
return childChanges;
}
/**
* Check if two values conflict (are different).
* Returns false if either value is undefined (no conflict with absence).
*/
function valuesConflict(val1: unknown, val2: unknown): boolean {
if (val1 === undefined || val2 === undefined) {
return false;
}
return !deepEqual(val1, val2);
}
/**
* 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'] = [];
if (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 = structure.variants as Variant[];
const childChanges = extractVariantChildChanges(variants);
// Check for conflicts between different variant groups
for (const [childName, modifications] of childChanges) {
const allModifications: Array<{ variant: string; option: string; changes: VariantChildChange }> = [];
// Flatten all modifications for this child
for (const mods of modifications.values()) {
allModifications.push(...mods);
}
// Compare modifications from different variant groups
for (let i = 0; i < allModifications.length; i++) {
for (let j = i + 1; j < allModifications.length; j++) {
const mod1 = allModifications[i];
const mod2 = allModifications[j];
// Skip if same variant group (mutually exclusive by definition)
if (mod1.variant === mod2.variant) {
continue;
}
// Check restrict conflict
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',
});
}
// Check slots conflict (warning - may be intentional)
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',
});
}
}
}
}
// Also check for root-level variant conflicts (restrict, slots)
const variantRootChanges = new Map<
string,
Array<{ variant: string; option: string; restrict?: string[]; slots?: Record<string, boolean> }>
>();
for (const variant of variants) {
Iif (!variant.options) continue;
for (const option of variant.options as VariantOption[]) {
if (option.restrict || option.slots) {
if (!variantRootChanges.has(variant.name)) {
variantRootChanges.set(variant.name, []);
}
variantRootChanges.get(variant.name)!.push({
variant: variant.name,
option: option.value,
restrict: option.restrict,
slots: option.slots,
});
}
}
}
// Compare root-level changes across different variant groups
const variantNames = Array.from(variantRootChanges.keys());
for (let i = 0; i < variantNames.length; i++) {
for (let j = i + 1; j < variantNames.length; j++) {
const changes1 = variantRootChanges.get(variantNames[i])!;
const changes2 = variantRootChanges.get(variantNames[j])!;
for (const c1 of changes1) {
for (const c2 of changes2) {
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',
});
}
}
}
}
}
return {
valid: errors.filter((e) => e.severity === 'error').length === 0,
errors,
};
}
/**
* Validate variant conflicts and throw if errors are found.
*
* @param uif - The UIF definition to validate
* @throws {UifVariantConflictError} If variant conflicts are found
*/
export function validateVariantConflictsOrThrow(uif: unknown): void {
const result = validateVariantConflicts(uif);
// Only throw for errors, not warnings
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)' ? firstError.childName : undefined,
firstError.value1,
firstError.value2,
);
}
}
// ============================================================================
// Comprehensive Validation
// ============================================================================
/**
* Comprehensive UIF validation combining all checks.
*
* @param uif - The UIF definition to validate
* @param options - Validation options
* @returns Combined validation result
*
* @example
* ```ts
* import { validateUif } from '@fds-uif/core';
*
* const result = validateUif(myUif);
*
* if (!result.valid) {
* console.error('Validation errors:', result.errors);
* }
*
* if (result.warnings.length > 0) {
* console.warn('Validation warnings:', result.warnings);
* }
* ```
*/
export function validateUif(uif: unknown, options: ValidationOptions = {}): ValidationResult {
const {
checkIdentifiers = true,
checkStateReferences = true,
checkVariantConflicts = true,
includeWarnings = true,
} = options;
const errors: ValidationError[] = [];
const warnings: ValidationError[] = [];
// Identifier validation
if (checkIdentifiers) {
const identifierResult = validateIdentifiers(uif);
for (const error of identifierResult.errors) {
errors.push({
code: ValidationErrorCode.DUPLICATE_IDENTIFIER,
message: `Duplicate ${error.field} "${error.duplicate}"\n\n ${formatPathLine(error.path)}`,
path: error.path,
severity: 'error',
details: { field: error.field, duplicate: error.duplicate },
});
}
}
// State reference validation
if (checkStateReferences) {
const stateResult = validateStateReferencesDetailed(uif);
for (const error of stateResult.errors) {
let message = `Unknown state "${error.state}"`;
if (error.suggestion) {
message += `. Did you mean "${error.suggestion}"?`;
} else if (stateResult.availableStates.length > 0) {
message += `\n\n Available states: ${stateResult.availableStates.join(', ')}`;
}
message += `\n\n ${formatPathLine(error.path)}`;
errors.push({
code: ValidationErrorCode.INVALID_STATE_REFERENCE,
message,
path: error.path,
severity: 'error',
suggestion: error.suggestion,
details: {
invalidState: error.state,
availableStates: stateResult.availableStates,
},
});
}
}
// Marker validation
const markerResult = validateMarkers(uif);
for (const error of markerResult.errors) {
const identifier = error.identifier ? ` (${error.identifier})` : '';
errors.push({
code: ValidationErrorCode.CONFLICTING_MARKERS,
message: `Item${identifier} has both $before and $after markers\n\n $before: "${error.beforeValue}"\n $after: "${error.afterValue}"\n\n ${formatPathLine(error.path)}`,
path: error.path,
severity: 'error',
details: {
identifier: error.identifier,
beforeValue: error.beforeValue,
afterValue: error.afterValue,
},
});
}
// Variant conflict validation
if (checkVariantConflicts) {
const variantResult = validateVariantConflicts(uif);
for (const conflict of variantResult.errors) {
const isRoot = conflict.childName === '(root)';
const location = isRoot ? 'root structure' : `child "${conflict.childName}"`;
const item: ValidationError = {
code: ValidationErrorCode.VARIANT_CONFLICT,
message: `Variant conflict on "${conflict.property}"\n\n ${conflict.variant1}: ${JSON.stringify(conflict.value1)}\n ${conflict.variant2}: ${JSON.stringify(conflict.value2)}\n\n Location: ${location}`,
path: 'structure.variants',
severity: conflict.severity,
details: {
variant1: conflict.variant1,
variant2: conflict.variant2,
childName: conflict.childName,
property: conflict.property,
value1: conflict.value1,
value2: conflict.value2,
},
};
if (conflict.severity === 'error') {
errors.push(item);
} else if (includeWarnings) {
warnings.push(item);
}
}
}
return {
valid: errors.length === 0,
errors,
warnings,
};
}
/**
* Validate UIF and throw if errors are found.
*
* @param uif - The UIF definition to validate
* @param options - Validation options
* @throws {UifDuplicateIdentifierError} If duplicate identifiers are found
* @throws {UifInvalidStateReferenceError} If invalid state references are found
* @throws {UifConflictingMarkersError} If conflicting markers are found
* @throws {UifVariantConflictError} If variant conflicts are found
*
* @example
* ```ts
* import { validateUifOrThrow, UifError } from '@fds-uif/core';
*
* try {
* validateUifOrThrow(myUif);
* console.log('UIF is valid!');
* } catch (error) {
* if (error instanceof UifError) {
* console.error(`Validation failed: ${error.code}`);
* }
* }
* ```
*/
export function validateUifOrThrow(uif: unknown, options: ValidationOptions = {}): void {
const {
checkIdentifiers = true,
checkStateReferences = true,
checkVariantConflicts = true,
} = options;
// Run each validation in order, throwing on first error
if (checkIdentifiers) {
validateIdentifiersOrThrow(uif);
}
if (checkStateReferences) {
validateStateReferencesOrThrow(uif);
}
validateMarkersOrThrow(uif);
if (checkVariantConflicts) {
validateVariantConflictsOrThrow(uif);
}
}
|