# All files / lib/validation schema-validator.js

51.85% Statements 28/54
39.53% Branches 17/43
62.5% Functions 5/8
51.85% Lines 28/54

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

    2x
    2x

    2x

    2x
    2x

    2x

    2x

    14x
    14x

    14x
    5x

    7x

    9x

    7x

    7x
    3x

    4x

    4x
    4x

    7x

    7x

    7x

    19x
    19x

    19x
    57x
    2x

    19x

     /**
     * Schema Validator for rosetta.yaml
     * Validates rosetta.yaml files against the JSON Schema
     */

    import Ajv from 'ajv';
    import addFormats from 'ajv-formats';
    import fs from 'fs-extra';
    import path from 'path';
    import { fileURLToPath } from 'url';

    const __filename = fileURLToPath(import.meta.url);
    const __dirname = path.dirname(__filename);

    // Load the schema
    const schemaPath = path.join(__dirname, '../../schemas/rosetta-schema.json');
    let schema;

    try {
      schema = JSON.parse(fs.readFileSync(schemaPath, 'utf8'));
    } catch (error) {
      throw new Error(`Failed to load schema from ${schemaPath}: ${error.message}`);
    }

    // Initialize AJV with all errors for detailed reporting
    const ajv = new Ajv({
      allErrors: true,
      verbose: true,
      strict: false
    });

    addFormats(ajv);

    /**
     * Validate a YAML object against the rosetta schema
     * @param {Object} yamlObject - The parsed YAML object to validate
     * @returns {Object} Validation result with valid flag and errors array
     */
    export function validateYAML(yamlObject) {
      const validate = ajv.compile(schema);
      const valid = validate(yamlObject);

      if (!valid) {
        return {
          valid: false,
          errors: validate.errors.map(err => ({
            path: err.instancePath || '(root)',
            property: err.instancePath?.split('/').pop() || 'root',
            message: err.message,
            expected: formatExpectedValue(err),
            actual: formatActualValue(err),
            keyword: err.keyword
          }))
        };
      }

      return { valid: true };
    }

    /**
     * Format the expected value for error messages
     */
    function formatExpectedValue(error) {
      Iif (error.keyword === 'type') {
        return error.params.type;
      }
      if (error.keyword === 'enum') {
        return error.params.allowedValues.join(', ');
      }
      Iif (error.keyword === 'pattern') {
        return error.params.pattern;
      }
      Eif (error.keyword === 'minLength') {
        return `at least ${error.params.limit} characters`;
      }
      if (error.keyword === 'maxLength') {
        return `at most ${error.params.limit} characters`;
      }
      if (error.keyword === 'minimum') {
        return error.params.limit;
      }
      if (error.keyword === 'maximum') {
        return error.params.limit;
      }
      return error.params?.allowedValues || error.params?.type || 'valid value';
    }

    /**
     * Format the actual value for error messages
     */
    function formatActualValue(error) {
      Iif (error.data === undefined || error.data === null) {
        return error.keyword === 'required' ? 'missing' : String(error.data);
      }
      Iif (typeof error.data === 'object') {
        return JSON.stringify(error.data);
      }
      return String(error.data);
    }

    /**
     * Validate a rosetta.yaml file directly
     * @param {string} filePath - Path to the rosetta.yaml file
     * @returns {Promise<Object>} Validation result
     */
    export async function validateYAMLFile(filePath) {
      try {
        const yaml = await fs.readFile(filePath, 'utf8');

        // Import yaml parser
        const { parse } = await import('js-yaml');
        const yamlObject = parse(yaml);

        return validateYAML(yamlObject);
      } catch (error) {
        if (error.name === 'YAMLException') {
          return {
            valid: false,
            errors: [{
              path: '(parse)',
              property: 'parse',
              message: `YAML parsing error: ${error.message}`,
              keyword: 'parse'
            }]
          };
        }

        return {
          valid: false,
          errors: [{
            path: '(file)',
            property: 'file',
            message: error.message,
            keyword: 'file'
          }]
        };
      }
    }

    /**
     * Format validation errors as a readable string
     * @param {Array} errors - Array of error objects from validateYAML
     * @returns {string} Formatted error message
     */
    export function formatValidationErrors(errors) {
      if (!errors || errors.length === 0) {
        return 'No errors';
      }

      const lines = errors.map((err, idx) => {
        const location = err.path === '(root)' ? 'root' : err.path;
        return `  ${idx + 1}. [${err.keyword}] ${location}\n     ${err.message}`;
      });

      return `Validation errors:\n${lines.join('\n')}`;
    }

    /**
     * Check if a YAML object has required top-level fields
     * Quick check before full schema validation
     * @param {Object} yamlObject - The parsed YAML object
     * @returns {Object} Result with valid flag and missing fields
     */
    export function checkRequiredFields(yamlObject) {
      const required = ['schema_version', 'project', 'stack'];
      const missing = [];

      for (const field of required) {
        if (!yamlObject || !yamlObject[field]) {
          missing.push(field);
        }
      }

      return {
        valid: missing.length === 0,
        missing
      };
    }

    // Export the schema for use in generators
    export { schema };