diff --git a/lib/projection.js b/lib/projection.js index 5f3bd88f..248c96df 100644 --- a/lib/projection.js +++ b/lib/projection.js @@ -17,7 +17,7 @@ // Projectable schemas (every node must be one of these): // - object with `properties` only: no patternProperties, combinators, // dependencies, and additionalProperties absent or false; at least one -// property; +// property; no array index key placed after a required property; // - string / number / integer / boolean without const or combinators; // a string may have any format but 'unsafe', which is written unescaped; // - the two-element forms ['string'|'number'|'boolean', 'null'] (any order), @@ -113,6 +113,11 @@ function resolveNode (location, refs, state, depth) { } const keys = Object.keys(schema.properties) if (keys.length === 0 || keys.length > MAX_PROPERTIES) return null + // an object lists array index keys first, whatever the order they are + // added in, so it cannot keep them after the required properties + const ordered = orderedKeys(schema) + const objectOrder = Object.keys(Object.fromEntries(ordered.map((key) => [key, null]))) + if (ordered.some((key, i) => key !== objectOrder[i])) return null const propertiesLocation = location.getPropertyLocation('properties') node.properties = Object.create(null) for (const key of keys) { diff --git a/test/object-mechanism-native.test.js b/test/object-mechanism-native.test.js index 00567a22..13af8b96 100644 --- a/test/object-mechanism-native.test.js +++ b/test/object-mechanism-native.test.js @@ -841,3 +841,22 @@ test('native mechanism: a serializer can be called again while it is serializing // after an error the serializer is not left in the "serializing" state t.assert.equal(nat({ a: '1', b: '2', c: '3', list: [{ x: '4' }] }), '{"a":"1","b":"2","c":"3","list":[{"x":"4"}]}') }) + +test('native mechanism: array index property names keep the order of the default mechanism', t => { + // An object lists array index keys first, so a projected object cannot put + // them after the required properties as the default mechanism does + const schemas = [ + { type: 'object', required: ['a'], properties: { a: { type: 'string' }, 2: { type: 'integer' } } }, + { type: 'array', items: { type: 'object', required: ['a'], properties: { 0: { type: 'string' }, a: { type: 'string' } } } }, + { type: 'object', required: ['1'], properties: { 1: { type: 'string' }, a: { type: 'string' } } } + ] + const inputs = [{ a: 'x', 0: 'y', 1: 'z', 2: 3 }, [{ a: 'x', 0: 'y' }, { a: 'z' }]] + t.plan(schemas.length * inputs.length + 1) + for (const schema of schemas) { + const nat = build(schema, { objectMechanism: 'native' }) + const def = build(schema) + for (const input of inputs) t.assert.deepStrictEqual(run(nat, input), run(def, input), JSON.stringify(schema)) + } + // the order is the same: the schema is still projected + t.assert.ok(build(schemas[2], { objectMechanism: 'native', mode: 'debug' }).code.includes('asStringValue')) +})