All files schema.js

98.7% Statements 153/155
91.66% Branches 44/48
100% Functions 31/31
98.69% Lines 151/153

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    1x   1x 1x 1x 1x 1x   1x             1x   1x 1x 1x 1x 1x 1x 1x 1x 1x       21x                                 3x                   1x                   3x                       30073x                   70667x                   2x                   1x                   70648x                   2x           5924x                     2316x               10x             5x           5917x 5917x 5917x 1339x 4567x                           176929x 176929x 176929x       1x 1x 1x       7x 7x       14x                             9x 9x 9x 15x   15x 2x   13x       13x 3x         10x 10x     3x         6x 1x   5x         12x               21x 9x   21x                   4x 4x   4x     4x 136x     136x 136x   4x                 2x 2x 2x 4x   2x                   6x 6x   6x     6x 210x     210x 210x 210x     210x   210x 198x         198x     6x                     12x 12x 10x   2x                                 1340x 1323x 17x 16x   1x           1339x     1339x   13x   1326x 1326x 1326x 4567x                           1340x 1340x 2x   1340x 1340x 1340x 1340x 1x   1339x 1339x                         7x 7x 7x 12x 12x 12x       12x   9x   3x 3x 2x       3x   12x   7x                                         8x 8x   8x 8x 8x 8x 8x 1x   7x     7x     7x 7x 7x 7x           7x 7x 7x 7x   7x         1x   1x                        
'use strict';
 
const Ajv = require( 'ajv' ).default;
 
const fs = require( 'fs' );
const path = require( 'path' );
const { createZObjectKey, findTypeDefinition, findTypeIdentity, getError, isMemberOfDangerTrio, isVoid, isBuiltInType, convertZListToItemArray } = require( './utils.js' );
const { readYaml } = require( './fileUtils.js' );
const { ValidationStatus } = require( './validationStatus.js' );
 
const SCHEMA_NAME_REGEX = '(Z[1-9]\\d*(K[1-9]\\d*)?|LIST|RESOLVER|GENERIC)';
 
let Z1Validator, Z4Validator, Z5Validator, Z6Validator, Z7Validator,
	Z9Validator, Z18Validator, Z40Validator, Z99Validator;
 
function initializeValidators() {
	// eslint-disable-next-line no-use-before-define
	const defaultFactory = SchemaFactory.NORMAL();
 
	Z1Validator = defaultFactory.create( 'Z1' );
	Z4Validator = defaultFactory.create( 'Z4_literal' );
	Z5Validator = defaultFactory.create( 'Z5_literal' );
	Z6Validator = defaultFactory.create( 'Z6_literal' );
	Z7Validator = defaultFactory.create( 'Z7_literal' );
	Z9Validator = defaultFactory.create( 'Z9_literal' );
	Z18Validator = defaultFactory.create( 'Z18_literal' );
	Z40Validator = defaultFactory.create( 'Z40_literal' );
	Z99Validator = defaultFactory.create( 'Z99_literal' );
}
 
function newAjv() {
	return new Ajv( {
		allowMatchingProperties: true,
		verbose: true,
		strictTuples: false,
		strictTypes: false } );
}
 
// TODO (T296659): Migrate validatesAs* functions to utils. Somehow avoid
// incurring circular import problem in the process.
 
/**
 * Determines whether argument is a valid ZObject.
 *
 * @param {Object} Z1 object to be validated
 * @return {ValidationStatus} Status is only valid if Z1 validates as a Z1
 */
function validatesAsZObject( Z1 ) {
	return Z1Validator.validateStatus( Z1 );
}
 
/**
 * Determines whether argument is a Z4.
 *
 * @param {Object} Z1 a ZObject
 * @return {ValidationStatus} Status is only valid if Z1 validates as Z4
 */
function validatesAsType( Z1 ) {
	return Z4Validator.validateStatus( Z1 );
}
 
/**
 * Determines whether argument is a Z5.
 *
 * @param {Object} Z1 a ZObject
 * @return {ValidationStatus} Status is only valid if Z1 validates as Z5
 */
function validatesAsError( Z1 ) {
	return Z5Validator.validateStatus( Z1 );
}
 
/**
 * Determines whether argument is a Z6 or Z9. These two types' Z1K1s are
 * strings instead of Z9s, so some checks below need to special-case their
 * logic.
 *
 * @param {Object} Z1 a ZObject
 * @return {ValidationStatus} Status is only valid if Z1 validates as either Z6 or Z7
 */
function validatesAsString( Z1 ) {
	return Z6Validator.validateStatus( Z1 );
}
 
/**
 * Determines whether argument is a Z9.
 *
 * @param {Object} Z1 a ZObject
 * @return {ValidationStatus} Status is only valid if Z1 validates as Z9
 */
function validatesAsReference( Z1 ) {
	return Z9Validator.validateStatus( Z1 );
}
 
/**
 * Validates a ZObject against the Function Call schema.
 *
 * @param {Object} Z1 object to be validated
 * @return {ValidationStatus} whether Z1 can validated as a Function Call
 */
function validatesAsFunctionCall( Z1 ) {
	return Z7Validator.validateStatus( Z1 );
}
 
/**
 * Validates a ZObject against the Argument Reference schema.
 *
 * @param {Object} Z1 object to be validated
 * @return {ValidationStatus} whether Z1 can validated as an Argument Reference
 */
function validatesAsArgumentReference( Z1 ) {
	return Z18Validator.validateStatus( Z1 );
}
 
/**
 * Validates a ZObject against the Quote schema.
 *
 * @param {Object} Z1 object to be validated
 * @return {ValidationStatus} whether Z1 can validated as a Quote
 */
function validatesAsQuote( Z1 ) {
	return Z99Validator.validateStatus( Z1 );
}
 
/**
 * Validates a ZObject against the Boolean schema.
 *
 * @param {Object} Z1 object to be validated
 * @return {ValidationStatus} whether Z1 can validated as a Boolean
 */
function validatesAsBoolean( Z1 ) {
	return Z40Validator.validateStatus( Z1 );
}
 
class BaseSchema {
 
	constructor() {
		this.keyMap_ = new Map();
	}
 
	/**
	 * Validate a JSON object using validateStatus method; return only whether
	 * the result was valid without surfacing errors.
	 *
	 * @param {Object} maybeValid a JSON object
	 * @return {ValidationStatus} whether the object is valid
	 */
	validate( maybeValid ) {
		return this.validateStatus( maybeValid ).isValid();
	}
 
	/**
	 * @param {string} key
	 * @return {Schema} a schema for a sub part of the main schema.
	 */
	subValidator( key ) {
		return this.keyMap_.get( key );
	}
 
	/**
	 * @return {Array<string>} All the available subvalidators' keys.
	 */
	subValidatorKeys() {
		return Array.from( this.keyMap_.keys() );
	}
}
 
class Schema extends BaseSchema {
	constructor( validate, subValidators = null ) {
		super();
		this.validate_ = validate;
		if ( subValidators !== null ) {
			for ( const key of subValidators.keys() ) {
				this.keyMap_.set( key, new Schema( subValidators.get( key ) ) );
			}
		}
	}
 
	/**
	 * Try to validate a JSON object against the internal JSON schema validator.
	 * The results are used to instantiate a ValidationStatus object that is
	 * returned.
	 *
	 * @param {Object} maybeValid a JSON object
	 * @return {ValidationStatus} a validation status instance
	 */
	validateStatus( maybeValid ) {
		const result = this.validate_( maybeValid );
		const validationStatus = new ValidationStatus( this.validate_, result );
		return validationStatus;
	}
}
 
const noSchema_ = { not: {} };
const noAjv_ = new Ajv();
const justNo_ = new Schema( noAjv_.compile( noSchema_ ) );
 
class GenericSchema extends BaseSchema {
	constructor( keyMap ) {
		super();
		this.updateKeyMap( keyMap );
	}
 
	updateKeyMap( keyMap ) {
		this.keyMap_ = keyMap;
	}
 
	/**
	 * Try to validate a JSON object against the internal validators. For each
	 * key in maybeValid, the corresponding value will be validated against the
	 * appropriate validator in this.keyMap_.
	 *
	 * The results are used to instantiate a ValidationStatus object that is
	 * returned.
	 *
	 * @param {Object} maybeValid a JSON object
	 * @return {ValidationStatus} a validation status instance
	 */
	validateStatus( maybeValid ) {
		const allKeys = new Set( Object.keys( maybeValid ) );
		allKeys.delete( 'Z1K1' );
		for ( const key of this.keyMap_.keys() ) {
			const toValidate = maybeValid[ key ];
			// TODO (T290996): How to signal non-optional keys?
			if ( toValidate === undefined ) {
				continue;
			}
			allKeys.delete( key );
 
			// Allow unresolved Z7, Z9, or Z18 to pass validation. This is a stopgap
			// measure that will be phased out pending a massive validator overhaul.
			if ( isMemberOfDangerTrio( toValidate ) ) {
				continue;
			}
 
			// If key is not present, maybeValid[ key ] is undefined, which will
			// not validate well.
			const howsIt = this.keyMap_.get( key ).validateStatus( toValidate );
			if ( !howsIt.isValid() ) {
				// TODO (T296842): Somehow include key.
				// TODO (T296842): Consider conjunction of all errors?
				return howsIt;
			}
		}
 
		// TODO (T296842): Better errors for stray keys; allow non-local keys?
		if ( allKeys.size > 0 ) {
			return justNo_.validateStatus( maybeValid );
		}
		return new ValidationStatus( null, true );
	}
}
 
function dataDir( ...pathComponents ) {
	return path.join(
		path.dirname( path.dirname( path.dirname( __filename ) ) ),
		'data', ...pathComponents );
}
 
class SchemaFactory {
 
	constructor( ajv = null ) {
		if ( ajv === null ) {
			ajv = newAjv();
		}
		this.ajv_ = ajv;
	}
 
	/**
	 * Initializes a SchemaFactory linking schemata for canonical ZObjects.
	 *
	 * @return {SchemaFactory} factory with all canonical schemata included
	 */
	static CANONICAL() {
		// Add all schemata for normal ZObjects to ajv's parsing context.
		const ajv = newAjv();
		const directory = dataDir( 'CANONICAL' );
		// eslint-disable-next-line security/detect-unsafe-regex
		const fileRegex = /((Z[1-9]\d*(K[1-9]\d*)?)|(LIST)|(RESOLVER))\.yaml/;
 
		// eslint-disable-next-line security/detect-non-literal-fs-filename
		for ( const fileName of fs.readdirSync( directory ) ) {
			Iif ( fileName.match( fileRegex ) === null ) {
				throw new Error( "Schema not found: '" + fileName + "'" );
			}
			const fullFile = path.join( directory, fileName );
			ajv.addSchema( readYaml( fullFile ) );
		}
		return new SchemaFactory( ajv );
	}
 
	/**
	 * Initializes a SchemaFactory for mixed form Z1.
	 *
	 * @return {SchemaFactory} factory with lonely mixed form schema
	 */
	static MIXED() {
		const ajv = newAjv();
		const directory = dataDir( 'MIXED' );
		for ( const filename of [ 'Z1.yaml', 'Z99.yaml' ] ) {
			ajv.addSchema( readYaml( path.join( directory, filename ) ) );
		}
		return new SchemaFactory( ajv );
	}
 
	/**
	 * Initializes a SchemaFactory linking schemata for normal-form ZObjects.
	 *
	 * @return {SchemaFactory} factory with all normal-form schemata included
	 */
	static NORMAL() {
		// Add all schemata for normal ZObjects to ajv's parsing context.
		const ajv = newAjv();
		const directory = dataDir( 'NORMAL' );
		// eslint-disable-next-line security/detect-unsafe-regex
		const fileRegex = /((Z[1-9]\d*(K[1-9]\d*)?)|(GENERIC)|(LIST)|(RESOLVER))\.yaml/;
 
		// eslint-disable-next-line security/detect-non-literal-fs-filename
		for ( const fileName of fs.readdirSync( directory ) ) {
			Iif ( fileName.match( fileRegex ) === null ) {
				throw new Error( "Schema not found: '" + fileName + "'" );
			}
			const fullFile = path.join( directory, fileName );
			const schema = readYaml( fullFile );
			ajv.addSchema( schema );
 
			// Add literal schema too
			const id = schema.$id + '_literal';
			// Checks whether a literal definition exists
			if ( schema.definitions.objects[ id ] ) {
				const literal = {
					$id: id,
					$ref: schema.$ref + '_literal',
					definitions: schema.definitions
				};
				ajv.addSchema( literal );
			}
		}
		return new SchemaFactory( ajv );
	}
 
	/**
	 * Try to compile a schema. Use the factory's internal ajv_ in order to
	 * resolve references among multiple files.
	 *
	 * @param {Object} schema a JSON object containing a JSON Schema object
	 * @return {Schema} a Schema wrapping the resulting validator or null
	 */
	parse( schema ) {
		try {
			const validate = this.ajv_.compile( schema );
			return new Schema( validate );
		} catch ( err ) {
			throw new Error( 'Could not parse schema `' + err.message + '`, schema was: ' + JSON.stringify( schema ) );
		}
	}
 
	/**
	 * Gets the AJV schemas for *all* the sub components of a schema that is defined
	 * in the ZID_literal.properties section.
	 * The returned map looks like Z1K1: AjvValidator, Z8K1: AjvValidator...
	 * If such mapping cannot be found, an empty map will be returned.
	 *
	 * @param {string} schemaName the name of the schema. It can be ZID or ZID_literal.
	 * @return {Map<string, *>} A mapping of the subcomponent keys and their AJV schema.
	 */
	getSubSchemas_( schemaName ) {
		// For both ZID schema and ZID_literal schema, the schema definition is the same.
		// This behavior is defined by the schema factory above.
		let zid;
		if ( schemaName.match( `^${ SCHEMA_NAME_REGEX }$` ) ) {
			zid = schemaName;
		} else if ( schemaName.match( `^${ SCHEMA_NAME_REGEX }_literal$` ) ) {
			zid = schemaName.split( '_' )[ 0 ];
		} else {
			throw new Error(
				`Cannot process schema name to get sub-validators: ${ schemaName }. ` +
				'Accecptable format examples: Z42 and Z42_literal.'
			);
		}
 
		const overallSchema = this.ajv_.getSchema( schemaName ).schema;
		// If this schema doesn't have a zid_literal field or the field does not
		// contain properties (like Z1), we simply return an empty map.
		if ( !overallSchema.definitions.objects[ `${ zid }_literal` ] ||
			!overallSchema.definitions.objects[ `${ zid }_literal` ].properties ) {
			return new Map();
		}
		const keys = Object.keys( overallSchema.definitions.objects[ `${ zid }_literal` ].properties );
		const keyPathPrefix = `${ zid }#/definitions/objects/${ zid }_literal/properties/`;
		return new Map(
			keys.map( ( k ) => [ k, this.ajv_.getSchema( `${ keyPathPrefix }${ k }` ) ] ) );
	}
 
	/**
	 * Create a schema for the desired native type. A schema for normalized
	 * Z11s, for example, can be created as easily as
	 *
	 *  const factory = SchemaFactory.NORMAL();
	 *  const Z11Schema = factory.create("Z11");
	 *
	 * @param {string} schemaName the name of a supported schema
	 * @return {Schema} a fully-initialized Schema or null if unsupported
	 */
	create( schemaName ) {
		let type = schemaName;
		if ( schemaName === 'Z41' || schemaName === 'Z42' ) {
			type = 'Z40';
		}
		let validate = null;
		const message = null;
		validate = this.ajv_.getSchema( type );
		if ( validate === null || validate === undefined ) {
			throw new Error( 'Could not find schema: "' + schemaName + '" – ' + message );
		}
		const subValidators = this.getSubSchemas_( type );
		return new Schema( validate, subValidators );
	}
 
	/**
	 * Create a Map[ key -> BaseSchema] for a given Z4. Resultant Map indicates
	 * against which validators to test the elements of a ZObject with the
	 * corresponding keys.
	 *
	 * @param {Object} Z4 a Z4/Type
	 * @param {Map} typeCache mapping from typekeys (see createZObjectKey) to BaseSchemata
	 * @return {Map} mapping from type keys to BaseSchemata
	 */
	keyMapForUserDefined( Z4, typeCache ) {
		const keyMap = new Map();
		const Z3s = convertZListToItemArray( Z4.Z4K2 || [] );
		for ( const Z3 of Z3s ) {
			const propertyName = Z3.Z3K2.Z6K1;
			const propertyType = Z3.Z3K1;
			const identity = findTypeIdentity( propertyType ) || findTypeDefinition( propertyType );
			let subValidator;
			// TODO (T316787): Ensure that this works properly for nested user-
			// defined types.
			if ( validatesAsReference( identity ).isValid() &&
                isBuiltInType( identity.Z9K1 ) ) {
				subValidator = this.create( identity.Z9K1 );
			} else {
				const key = createZObjectKey( propertyType );
				if ( !( typeCache.has( key ) ) ) {
					typeCache.set(
						key,
						this.createUserDefined( [ propertyType ] ).get( key ) );
				}
				subValidator = typeCache.get( key );
			}
			keyMap.set( propertyName, subValidator );
		}
		return keyMap;
	}
 
	/**
	 * Create a schema for given user-defined type. The Z4 corresponding to the
	 * type must be provided.
	 *
	 * Currently only works for normal form.
	 *
	 * TODO (T296843): Maybe make this work for canonical forms, too.
	 *
	 * Usage:
	 *
	 *  // Z4 is a Z4 corresponding to a user-defined type
	 *  const factory = SchemaFactory.NORMAL();
	 *  const Z10001Schema = factory.createUserDefined([Z4]);
	 *
	 * @param {Object} Z4s the descriptor for the user-defined types
	 * @return {Schema} a fully-initialized Schema
	 */
	createUserDefined( Z4s ) {
		const typeCache = new Map();
		const normalize = require( './normalize.js' );
 
		const normalZ4s = [];
		for ( let errorIndex = 0; errorIndex < Z4s.length; ++errorIndex ) {
			const Z4 = Z4s[ errorIndex ];
			const normalizedEnvelope = normalize( Z4 );
			if ( !isVoid( getError( normalizedEnvelope ) ) ) {
				throw new Error( 'Failed to normalized Z4 at index: ' + errorIndex + '. Object: ' + JSON.stringify( Z4 ) );
			}
			normalZ4s.push( normalizedEnvelope.Z22K1 );
		}
 
		const zObjectKeys = [];
 
		// Create a GenericSchema for each of the requested Z4s.
		for ( const Z4 of normalZ4s ) {
			const key = createZObjectKey( Z4 );
			zObjectKeys.push( key );
			typeCache.set( key, new GenericSchema( new Map() ) );
		}
 
		// Populate all of the GenericSchemata with key maps.
		// We iterate twice here to avoid circular references and to ensure we
		// don't try to create schemata multiple times for any given Z4.
		for ( let i = 0; i < normalZ4s.length; ++i ) {
			const Z4 = normalZ4s[ i ];
			const key = zObjectKeys[ i ];
			typeCache.get( key ).updateKeyMap( this.keyMapForUserDefined( Z4, typeCache ) );
		}
		return typeCache;
	}
 
}
 
initializeValidators();
 
module.exports = {
	SchemaFactory,
	validatesAsZObject,
	validatesAsType,
	validatesAsError,
	validatesAsString,
	validatesAsFunctionCall,
	validatesAsReference,
	validatesAsQuote,
	validatesAsArgumentReference,
	validatesAsBoolean
};