All files / coherent.js/packages/core/src/state state-validation.js

87.89% Statements 632/719
83.42% Branches 146/175
95.83% Functions 23/24
87.89% Lines 632/719

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 8041x 1x 1x 1x 1x   1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x   1x 1x 1x 1x 1x 1x   1x 1x 1x 1x 1x 1x 1x 1x   1x 1x 1x 1x 1x 24x 24x 24x 24x 24x 24x 24x   1x 1x 1x 1x 1x 1x 1x 1x 92x 92x   92x 92x 92x 92x 5x 5x 4x 4x 5x 88x 88x   88x 92x 2x 2x 1x 1x 2x   88x 92x 21x 21x 4x 4x 21x   88x 92x 19x 19x 3x 3x 19x   88x 92x 4x 4x 2x 2x 4x 4x   88x 92x 40x 40x 18x 18x 40x 40x   88x 92x 2x 2x 1x 1x 1x 1x 1x 1x 1x 2x   88x 88x 88x 88x 88x 92x   1x 92x 92x 92x   92x 92x   92x 94x 94x 94x 88x 92x   92x 11x 7x 7x 7x 7x 2x 7x 3x 3x 1x 1x 1x 1x 1x 1x 1x 1x 5x 2x 2x                       7x                 11x 4x 4x 4x 4x 4x 4x 4x 4x 11x   92x 92x 92x 92x 92x 92x   1x 2x 2x 1x 1x 1x 1x 1x 1x 1x 1x 2x 2x   1x 21x   21x 1x 1x 1x 1x 1x 1x 1x   21x                 21x 2x 2x 1x 1x 1x 1x 1x 1x 1x 2x   21x 6x 6x 2x 2x 6x   21x 21x   1x 6x 6x 6x 6x 6x 6x 6x 6x   6x 2x 2x 2x 2x 2x 2x 2x 2x   6x 6x   1x 19x   19x 1x 1x 1x 1x 1x 1x 1x   19x 1x 1x 1x 1x 1x 1x 1x   19x                 19x                 19x 1x 1x 1x 1x 1x 1x 1x   19x 19x   1x 4x 4x   4x 1x 1x 1x 1x 1x 1x 1x   4x                 4x 2x 2x 2x 6x 6x 1x 1x 6x 2x 2x 1x 1x 1x 1x 1x 1x 1x 2x   4x 4x 4x 8x 8x 8x     8x     4x 4x   4x 4x 4x 4x 4x 4x   1x 40x 40x   40x 40x 2x 2x 1x 1x 1x 1x 1x 1x 1x 2x 2x   40x 40x 40x 45x 44x 44x 44x 16x 16x 44x 7x 7x 44x 40x 40x   40x 40x 1x 1x 2x 1x 1x 1x 1x 1x 1x 1x 1x 1x   40x 40x 40x                 40x                 40x 40x 40x 40x 40x 40x 1x   1x 1x 1x 1x 1x 1x 1x 30x 30x 30x 30x 30x 30x 30x 30x 30x 30x 30x 30x   30x 24x 24x 30x   30x 30x 30x   30x 30x 30x 30x 30x 30x 30x 47x 47x   47x 47x 40x 40x 40x   40x 40x 18x 18x 40x 40x   47x 47x                     47x 45x 45x 2x 2x 2x 1x 1x 1x 1x 1x 1x 1x 2x 45x 45x   47x 47x 1x 2x 1x 1x 1x 1x 1x 1x 1x 1x 1x   47x 47x 47x 47x 47x 47x   30x 30x 30x 30x 30x 30x 25x   25x                   25x 25x   30x 30x 30x 30x 30x 30x 43x   43x       43x 43x   43x 43x 43x   43x 18x   18x 1x 1x   18x 1x 1x 1x 1x   17x 17x 17x   25x 43x 5x 5x 5x 6x 6x 6x 5x 5x 5x   25x 25x 25x   25x   25x 25x 2x 2x 2x     25x 43x   30x 30x 30x 30x 30x 30x 2x 2x 2x   30x 30x 30x 30x 30x 30x 17x 17x   30x 30x 30x 30x 30x 2x 2x 1x 1x 2x 2x   30x 30x 30x 30x 30x 30x 30x 2x 2x   30x 30x 30x 30x 30x 30x 30x 30x 30x 30x   1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 3x 3x 1x 1x   1x 1x 1x 1x 1x 1x 2x 2x 2x 2x 2x 1x 1x 1x   1x 1x 1x 1x 1x 1x 1x 3x 3x 1x 1x   1x 1x 1x 1x 1x 1x 1x 2x 2x 1x 1x 1x 1x   1x 1x 1x 1x 1x 1x 2x 2x 2x 1x 1x   1x 1x 1x 1x 1x 1x 4x 3x 3x 1x 4x 1x   1x 1x 1x 1x 1x  
/**
 * @fileoverview State Validation for Coherent.js
 * Provides JSON Schema validation and custom validators for state management
 * @module @coherentjs/core/state/state-validation
 */
 
/**
 * @typedef {Object} ValidationOptions
 * @property {Object} [schema] - JSON Schema for validation
 * @property {Object<string, Function>} [validators] - Custom validator functions
 * @property {boolean} [strict=false] - Strict mode (throw on validation errors)
 * @property {boolean} [coerce=false] - Coerce types to match schema
 * @property {Function} [onError] - Validation error callback
 * @property {boolean} [validateOnSet=true] - Validate on state updates
 * @property {boolean} [validateOnGet=false] - Validate on state reads
 * @property {Array<string>} [required] - Required fields
 * @property {boolean} [allowUnknown=true] - Allow unknown properties
 */
 
/**
 * @typedef {Object} ValidationResult
 * @property {boolean} valid - Whether validation passed
 * @property {Array<ValidationError>} errors - Array of validation errors
 * @property {*} value - Validated/coerced value
 */
 
/**
 * @typedef {Object} ValidationError
 * @property {string} path - Property path that failed validation
 * @property {string} message - Error message
 * @property {string} type - Error type
 * @property {*} value - The invalid value
 * @property {*} expected - Expected value/type
 */
 
/**
 * Simple JSON Schema validator
 */
class SchemaValidator {
  constructor(schema, options = {}) {
    this.schema = schema;
    this.options = {
      coerce: false,
      allowUnknown: true,
      ...options
    };
  }
 
  /**
   * Validate value against schema
   * @param {*} value - Value to validate
   * @param {Object} schema - Schema to validate against
   * @param {string} path - Current path in object
   * @returns {ValidationResult} Validation result
   */
  validate(value, schema = this.schema, path = '') {
    const errors = [];
    let coercedValue = value;
 
    // Type validation
    if (schema.type) {
      const typeResult = this.validateType(value, schema.type, path);
      if (!typeResult.valid) {
        errors.push(...typeResult.errors);
        if (!this.options.coerce) {
          return { valid: false, errors, value };
        }
      }
      coercedValue = typeResult.value;
    }
 
    // Enum validation
    if (schema.enum) {
      const enumResult = this.validateEnum(coercedValue, schema.enum, path);
      if (!enumResult.valid) {
        errors.push(...enumResult.errors);
      }
    }
 
    // String validations
    if (schema.type === 'string') {
      const stringResult = this.validateString(coercedValue, schema, path);
      if (!stringResult.valid) {
        errors.push(...stringResult.errors);
      }
    }
 
    // Number validations
    if (schema.type === 'number' || schema.type === 'integer') {
      const numberResult = this.validateNumber(coercedValue, schema, path);
      if (!numberResult.valid) {
        errors.push(...numberResult.errors);
      }
    }
 
    // Array validations
    if (schema.type === 'array') {
      const arrayResult = this.validateArray(coercedValue, schema, path);
      if (!arrayResult.valid) {
        errors.push(...arrayResult.errors);
      }
      coercedValue = arrayResult.value;
    }
 
    // Object validations
    if (schema.type === 'object') {
      const objectResult = this.validateObject(coercedValue, schema, path);
      if (!objectResult.valid) {
        errors.push(...objectResult.errors);
      }
      coercedValue = objectResult.value;
    }
 
    // Custom validation function
    if (schema.validate && typeof schema.validate === 'function') {
      const customResult = schema.validate(coercedValue);
      if (customResult !== true) {
        errors.push({
          path,
          message: typeof customResult === 'string' ? customResult : 'Custom validation failed',
          type: 'custom',
          value: coercedValue
        });
      }
    }
 
    return {
      valid: errors.length === 0,
      errors,
      value: coercedValue
    };
  }
 
  validateType(value, type, path) {
    const actualType = Array.isArray(value) ? 'array' : typeof value;
    const errors = [];
    let coercedValue = value;
 
    // Support array of types
    const types = Array.isArray(type) ? type : [type];
 
    const isValid = types.some(t => {
      if (t === 'array') return Array.isArray(value);
      if (t === 'null') return value === null;
      if (t === 'integer') return typeof value === 'number' && Number.isInteger(value);
      return typeof value === t;
    });
 
    if (!isValid) {
      if (this.options.coerce) {
        // Try to coerce
        const primaryType = types[0];
        try {
          if (primaryType === 'string') {
            coercedValue = String(value);
          } else if (primaryType === 'number') {
            coercedValue = Number(value);
            if (isNaN(coercedValue)) {
              errors.push({
                path,
                message: `Cannot coerce "${value}" to number`,
                type: 'type',
                value,
                expected: primaryType
              });
            }
          } else if (primaryType === 'boolean') {
            coercedValue = Boolean(value);
          } else if (primaryType === 'integer') {
            coercedValue = parseInt(value, 10);
            if (isNaN(coercedValue)) {
              errors.push({
                path,
                message: `Cannot coerce "${value}" to integer`,
                type: 'type',
                value,
                expected: primaryType
              });
            }
          }
        } catch {
          errors.push({
            path,
            message: `Cannot coerce value to ${primaryType}`,
            type: 'type',
            value,
            expected: primaryType
          });
        }
      } else {
        errors.push({
          path,
          message: `Expected type ${types.join(' or ')}, got ${actualType}`,
          type: 'type',
          value,
          expected: type
        });
      }
    }
 
    return {
      valid: errors.length === 0,
      errors,
      value: coercedValue
    };
  }
 
  validateEnum(value, enumValues, path) {
    const errors = [];
    if (!enumValues.includes(value)) {
      errors.push({
        path,
        message: `Value must be one of: ${enumValues.join(', ')}`,
        type: 'enum',
        value,
        expected: enumValues
      });
    }
    return { valid: errors.length === 0, errors };
  }
 
  validateString(value, schema, path) {
    const errors = [];
 
    if (schema.minLength !== undefined && value.length < schema.minLength) {
      errors.push({
        path,
        message: `String length must be >= ${schema.minLength}`,
        type: 'minLength',
        value
      });
    }
 
    if (schema.maxLength !== undefined && value.length > schema.maxLength) {
      errors.push({
        path,
        message: `String length must be <= ${schema.maxLength}`,
        type: 'maxLength',
        value
      });
    }
 
    if (schema.pattern) {
      const regex = new RegExp(schema.pattern);
      if (!regex.test(value)) {
        errors.push({
          path,
          message: `String does not match pattern: ${schema.pattern}`,
          type: 'pattern',
          value
        });
      }
    }
 
    if (schema.format) {
      const formatResult = this.validateFormat(value, schema.format, path);
      if (!formatResult.valid) {
        errors.push(...formatResult.errors);
      }
    }
 
    return { valid: errors.length === 0, errors };
  }
 
  validateFormat(value, format, path) {
    const errors = [];
    const formats = {
      email: /^[^\s@]+@[^\s@]+\.[^\s@]+$/,
      url: /^https?:\/\/.+/,
      uuid: /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i,
      date: /^\d{4}-\d{2}-\d{2}$/,
      'date-time': /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}/
    };
 
    if (formats[format] && !formats[format].test(value)) {
      errors.push({
        path,
        message: `String does not match format: ${format}`,
        type: 'format',
        value,
        expected: format
      });
    }
 
    return { valid: errors.length === 0, errors };
  }
 
  validateNumber(value, schema, path) {
    const errors = [];
 
    if (schema.minimum !== undefined && value < schema.minimum) {
      errors.push({
        path,
        message: `Number must be >= ${schema.minimum}`,
        type: 'minimum',
        value
      });
    }
 
    if (schema.maximum !== undefined && value > schema.maximum) {
      errors.push({
        path,
        message: `Number must be <= ${schema.maximum}`,
        type: 'maximum',
        value
      });
    }
 
    if (schema.exclusiveMinimum !== undefined && value <= schema.exclusiveMinimum) {
      errors.push({
        path,
        message: `Number must be > ${schema.exclusiveMinimum}`,
        type: 'exclusiveMinimum',
        value
      });
    }
 
    if (schema.exclusiveMaximum !== undefined && value >= schema.exclusiveMaximum) {
      errors.push({
        path,
        message: `Number must be < ${schema.exclusiveMaximum}`,
        type: 'exclusiveMaximum',
        value
      });
    }
 
    if (schema.multipleOf !== undefined && value % schema.multipleOf !== 0) {
      errors.push({
        path,
        message: `Number must be multiple of ${schema.multipleOf}`,
        type: 'multipleOf',
        value
      });
    }
 
    return { valid: errors.length === 0, errors };
  }
 
  validateArray(value, schema, path) {
    const errors = [];
    const coercedValue = [...value];
 
    if (schema.minItems !== undefined && value.length < schema.minItems) {
      errors.push({
        path,
        message: `Array must have at least ${schema.minItems} items`,
        type: 'minItems',
        value
      });
    }
 
    if (schema.maxItems !== undefined && value.length > schema.maxItems) {
      errors.push({
        path,
        message: `Array must have at most ${schema.maxItems} items`,
        type: 'maxItems',
        value
      });
    }
 
    if (schema.uniqueItems) {
      const seen = new Set();
      const duplicates = [];
      value.forEach((item, index) => {
        const key = JSON.stringify(item);
        if (seen.has(key)) {
          duplicates.push(index);
        }
        seen.add(key);
      });
      if (duplicates.length > 0) {
        errors.push({
          path,
          message: 'Array items must be unique',
          type: 'uniqueItems',
          value
        });
      }
    }
 
    // Validate items
    if (schema.items) {
      value.forEach((item, index) => {
        const itemPath = `${path}[${index}]`;
        const itemResult = this.validate(item, schema.items, itemPath);
        if (!itemResult.valid) {
          errors.push(...itemResult.errors);
        }
        if (this.options.coerce) {
          coercedValue[index] = itemResult.value;
        }
      });
    }
 
    return {
      valid: errors.length === 0,
      errors,
      value: coercedValue
    };
  }
 
  validateObject(value, schema, path) {
    const errors = [];
    const coercedValue = { ...value };
 
    // Required properties
    if (schema.required) {
      schema.required.forEach(prop => {
        if (!(prop in value)) {
          errors.push({
            path: path ? `${path}.${prop}` : prop,
            message: `Required property "${prop}" is missing`,
            type: 'required',
            value: undefined
          });
        }
      });
    }
 
    // Validate properties
    if (schema.properties) {
      Object.entries(schema.properties).forEach(([prop, propSchema]) => {
        if (prop in value) {
          const propPath = path ? `${path}.${prop}` : prop;
          const propResult = this.validate(value[prop], propSchema, propPath);
          if (!propResult.valid) {
            errors.push(...propResult.errors);
          }
          if (this.options.coerce) {
            coercedValue[prop] = propResult.value;
          }
        }
      });
    }
 
    // Additional properties
    if (schema.additionalProperties === false && !this.options.allowUnknown) {
      const allowedProps = new Set(Object.keys(schema.properties || {}));
      Object.keys(value).forEach(prop => {
        if (!allowedProps.has(prop)) {
          errors.push({
            path: path ? `${path}.${prop}` : prop,
            message: `Unknown property "${prop}"`,
            type: 'additionalProperties',
            value: value[prop]
          });
        }
      });
    }
 
    // Min/max properties
    const propCount = Object.keys(value).length;
    if (schema.minProperties !== undefined && propCount < schema.minProperties) {
      errors.push({
        path,
        message: `Object must have at least ${schema.minProperties} properties`,
        type: 'minProperties',
        value
      });
    }
 
    if (schema.maxProperties !== undefined && propCount > schema.maxProperties) {
      errors.push({
        path,
        message: `Object must have at most ${schema.maxProperties} properties`,
        type: 'maxProperties',
        value
      });
    }
 
    return {
      valid: errors.length === 0,
      errors,
      value: coercedValue
    };
  }
}
 
/**
 * Create validated state manager
 * @param {Object} initialState - Initial state
 * @param {ValidationOptions} options - Validation options
 * @returns {Object} Validated state manager
 */
export function createValidatedState(initialState = {}, options = {}) {
  const opts = {
    schema: null,
    validators: {},
    strict: false,
    coerce: false,
    onError: null,
    validateOnSet: true,
    validateOnGet: false,
    required: [],
    allowUnknown: true,
    ...options
  };
 
  const schemaValidator = opts.schema ? new SchemaValidator(opts.schema, {
    coerce: opts.coerce,
    allowUnknown: opts.allowUnknown
  }) : null;
 
  let state = { ...initialState };
  const listeners = new Set();
  const validationErrors = new Map();
 
  /**
   * Validate state
   * @param {Object} value - State to validate
   * @param {string} key - State key (for partial validation)
   * @returns {ValidationResult} Validation result
   */
  function validateState(value, key = null) {
    const errors = [];
    let validatedValue = value;
 
    // JSON Schema validation
    if (schemaValidator) {
      const schema = key && opts.schema.properties
        ? opts.schema.properties[key]
        : opts.schema;
 
      const result = schemaValidator.validate(value, schema, key || '');
      if (!result.valid) {
        errors.push(...result.errors);
      }
      validatedValue = result.value;
    }
 
    // Custom validators
    if (key && opts.validators[key]) {
      const validator = opts.validators[key];
      const result = validator(value);
      if (result !== true) {
        errors.push({
          path: key,
          message: typeof result === 'string' ? result : 'Validation failed',
          type: 'custom',
          value
        });
      }
    } else if (!key) {
      // Run custom validators for all fields when validating full state
      Object.entries(opts.validators).forEach(([fieldKey, validator]) => {
        if (fieldKey in value) {
          const result = validator(value[fieldKey]);
          if (result !== true) {
            errors.push({
              path: fieldKey,
              message: typeof result === 'string' ? result : 'Validation failed',
              type: 'custom',
              value: value[fieldKey]
            });
          }
        }
      });
    }
 
    // Required fields
    if (opts.required.length > 0 && !key) {
      opts.required.forEach(field => {
        if (!(field in value)) {
          errors.push({
            path: field,
            message: `Required field "${field}" is missing`,
            type: 'required',
            value: undefined
          });
        }
      });
    }
 
    return {
      valid: errors.length === 0,
      errors,
      value: validatedValue
    };
  }
 
  /**
   * Get state
   * @param {string} key - State key
   * @returns {*} State value
   */
  function getState(key) {
    const value = key ? state[key] : { ...state };
 
    if (opts.validateOnGet) {
      const result = validateState(value, key);
      if (!result.valid) {
        validationErrors.set(key || '__root__', result.errors);
        if (opts.onError) {
          opts.onError(result.errors);
        }
      }
    }
 
    return value;
  }
 
  /**
   * Set state
   * @param {Object|Function} updates - State updates
   * @throws {Error} If validation fails in strict mode
   */
  function setState(updates) {
    const oldState = { ...state };
 
    if (typeof updates === 'function') {
      updates = updates(oldState);
    }
 
    // Create the new full state for validation
    const newState = { ...state, ...updates };
 
    // Validate before setting
    if (opts.validateOnSet) {
      const result = validateState(newState);
 
      if (!result.valid) {
        validationErrors.set('__root__', result.errors);
 
        if (opts.onError) {
          opts.onError(result.errors);
        }
 
        if (opts.strict) {
          const error = new Error('Validation failed');
          error.validationErrors = result.errors;
          throw error;
        }
 
        // Don't update state if validation fails in non-strict mode
        return;
      }
 
      // Use coerced value if coercion is enabled
      if (opts.coerce) {
        const updatedKeys = Object.keys(updates);
        const newUpdates = {};
        updatedKeys.forEach(key => {
          if (result.value[key] !== state[key]) {
            newUpdates[key] = result.value[key];
          }
        });
        updates = newUpdates;
      }
 
      // Clear errors on successful validation
      validationErrors.clear();
    }
 
    state = { ...state, ...updates };
 
    // Notify listeners
    listeners.forEach(listener => {
      try {
        listener(state, oldState);
      } catch (error) {
        console.error('Listener error:', error);
      }
    });
  }
 
  /**
   * Subscribe to state changes
   * @param {Function} listener - Change listener
   * @returns {Function} Unsubscribe function
   */
  function subscribe(listener) {
    listeners.add(listener);
    return () => listeners.delete(listener);
  }
 
  /**
   * Get validation errors
   * @param {string} key - State key
   * @returns {Array<ValidationError>} Validation errors
   */
  function getErrors(key = '__root__') {
    return validationErrors.get(key) || [];
  }
 
  /**
   * Check if state is valid
   * @returns {boolean} Whether state is valid
   */
  function isValid() {
    const result = validateState(state);
    if (!result.valid) {
      validationErrors.set('__root__', result.errors);
    }
    return result.valid;
  }
 
  /**
   * Validate specific field
   * @param {string} key - Field key
   * @param {*} value - Field value
   * @returns {ValidationResult} Validation result
   */
  function validateField(key, value) {
    return validateState(value, key);
  }
 
  return {
    getState,
    setState,
    subscribe,
    getErrors,
    isValid,
    validateField,
    validate: () => validateState(state)
  };
}
 
/**
 * Common validators
 */
export const validators = {
  /**
   * Email validator
   * @param {string} value - Email to validate
   * @returns {boolean|string} True if valid, error message otherwise
   */
  email: (value) => {
    if (typeof value !== 'string') return 'Email must be a string';
    if (!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(value)) return 'Invalid email format';
    return true;
  },
 
  /**
   * URL validator
   * @param {string} value - URL to validate
   * @returns {boolean|string} True if valid, error message otherwise
   */
  url: (value) => {
    if (typeof value !== 'string') return 'URL must be a string';
    try {
      new URL(value);
      return true;
    } catch {
      return 'Invalid URL format';
    }
  },
 
  /**
   * Range validator
   * @param {number} min - Minimum value
   * @param {number} max - Maximum value
   * @returns {Function} Validator function
   */
  range: (min, max) => (value) => {
    if (typeof value !== 'number') return 'Value must be a number';
    if (value < min || value > max) return `Value must be between ${min} and ${max}`;
    return true;
  },
 
  /**
   * Length validator
   * @param {number} min - Minimum length
   * @param {number} max - Maximum length
   * @returns {Function} Validator function
   */
  length: (min, max) => (value) => {
    if (typeof value !== 'string') return 'Value must be a string';
    if (value.length < min || value.length > max) {
      return `Length must be between ${min} and ${max}`;
    }
    return true;
  },
 
  /**
   * Pattern validator
   * @param {RegExp|string} pattern - Pattern to match
   * @returns {Function} Validator function
   */
  pattern: (pattern) => (value) => {
    if (typeof value !== 'string') return 'Value must be a string';
    const regex = typeof pattern === 'string' ? new RegExp(pattern) : pattern;
    if (!regex.test(value)) return `Value does not match pattern: ${pattern}`;
    return true;
  },
 
  /**
   * Required validator
   * @param {*} value - Value to validate
   * @returns {boolean|string} True if valid, error message otherwise
   */
  required: (value) => {
    if (value === undefined || value === null || value === '') {
      return 'Value is required';
    }
    return true;
  }
};
 
export default {
  createValidatedState,
  validators,
  SchemaValidator
};