From 587822c16e3f573362fdfe291c9afc37ca31bb15 Mon Sep 17 00:00:00 2001 From: toasted-nutbread Date: Tue, 11 Aug 2020 19:21:26 -0400 Subject: More JSON schema improvements (#729) * Add support for constant values * Add contains check for arrays * Add tests * Simplify getValidValueOrDefault testing --- ext/bg/js/json-schema.js | 27 +++++++++++++++++++++++++++ 1 file changed, 27 insertions(+) (limited to 'ext') diff --git a/ext/bg/js/json-schema.js b/ext/bg/js/json-schema.js index b777ac09..7cc87bb0 100644 --- a/ext/bg/js/json-schema.js +++ b/ext/bg/js/json-schema.js @@ -326,6 +326,11 @@ class JsonSchemaValidator { throw new JsonSchemaValidationError(`Value type ${type} does not match schema type ${schemaType}`, value, schema, info); } + const schemaConst = schema.const; + if (typeof schemaConst !== 'undefined' && !this.valuesAreEqual(value, schemaConst)) { + throw new JsonSchemaValidationError('Invalid constant value', value, schema, info); + } + const schemaEnum = schema.enum; if (Array.isArray(schemaEnum) && !this.valuesAreEqualAny(value, schemaEnum)) { throw new JsonSchemaValidationError('Invalid enum value', value, schema, info); @@ -414,6 +419,8 @@ class JsonSchemaValidator { throw new JsonSchemaValidationError('Array length too long', value, schema, info); } + this.validateArrayContains(value, schema, info); + for (let i = 0, ii = value.length; i < ii; ++i) { const schemaPath = []; const propertySchema = this.getPropertySchema(schema, i, value, schemaPath); @@ -431,6 +438,26 @@ class JsonSchemaValidator { } } + validateArrayContains(value, schema, info) { + const containsSchema = schema.contains; + if (!this.isObject(containsSchema)) { return; } + + info.schemaPush('contains', containsSchema); + for (let i = 0, ii = value.length; i < ii; ++i) { + const propertyValue = value[i]; + info.valuePush(i, propertyValue); + try { + this.validate(propertyValue, containsSchema, info); + info.schemaPop(); + return; + } catch (e) { + // NOP + } + info.valuePop(); + } + throw new JsonSchemaValidationError('contains schema didn\'t match', value, schema, info); + } + validateObject(value, schema, info) { const properties = new Set(Object.getOwnPropertyNames(value)); -- cgit v1.2.3