diff --git a/README.md b/README.md index 9651f689..77fe97ab 100644 --- a/README.md +++ b/README.md @@ -758,11 +758,11 @@ const stringify = fastJson(schema, { objectMechanism: 'native' }) The projection covers schemas made only of: -- `object` with `properties` (no `patternProperties`, `dependencies`, - combinators or `$ref`; `additionalProperties` absent or `false`), with at - least one property; +- `object` with `properties` (no `patternProperties`, `dependencies` or + combinators; `additionalProperties` absent or `false`), with at least one + property; - `string` (with any `format` except `unsafe`), `number`, `integer`, `boolean`, - without `const`, combinators or `$ref`; + without `const` or combinators; - the two-element forms `['string', 'null']`, `['number', 'null']` and `['boolean', 'null']` (in either order), with the same strict type dispatch as the default mechanism; @@ -771,6 +771,13 @@ The projection covers schemas made only of: Each of them can be `nullable: true` and can have an `enum`. +Each of them can also be reached through a `$ref`, to a definition of the same +schema or to an external schema. Two kinds of `$ref` keep the default +mechanism: a recursive one, and one with other keywords next to it (a +`nullable` or a `default`, for instance; `title`, `description` and the other +annotations are fine). The same holds for a root schema that is itself a +`$ref` with its `definitions` next to it. + Any other schema silently uses the default mechanism, so the option is always safe to enable. The projection only pays off where V8 has the fast path, so on Node.js 24 and older the option is a no-op and the default mechanism is used. diff --git a/index.js b/index.js index 0360dd8d..3f147b9f 100644 --- a/index.js +++ b/index.js @@ -554,7 +554,11 @@ function build (schema, options) { // `forceProjection` is an internal, undocumented escape hatch used by the // test suite to exercise the projection on runtimes where it is gated off. if (context.objectMechanism === 'native' && (options.forceProjection === true || PROJECTION_SUPPORTED)) { - projection = buildProjection(schema) + projection = buildProjection(location, { + resolve: (location) => resolveRef(context, location), + pointer: (location) => getSafeSchemaRef(context, location), + ignoredSiblings: IGNORED_REF_SIBLING_KEYWORDS + }) } if (projection === null) { code = buildValue(context, location, 'input') diff --git a/lib/projection.js b/lib/projection.js index 842f3149..3f0e999b 100644 --- a/lib/projection.js +++ b/lib/projection.js @@ -10,10 +10,10 @@ // always taken, even when the user's input would have bailed out of it. // // Projectable schemas (every node must be one of these): -// - object with `properties` only: no patternProperties, combinators, $ref, +// - object with `properties` only: no patternProperties, combinators, // dependencies, and additionalProperties absent or false; at least one // property; -// - string / number / integer / boolean without const, combinators, $ref; +// - 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), // with the strict no-coercion dispatch of the multi-type codegen; @@ -23,6 +23,9 @@ // elements get their own scratch tree from a per-element slot pool. // Any of them may be `nullable: true` (null is then written as null) and may // carry an `enum`, which the codegen does not use once the type is known. +// Any of them may be reached through a $ref, to the same schema or to an +// external one, as long as the $ref has no keyword next to it that the codegen +// would merge and the target is not recursive. // Anything else makes buildProjection return null and the caller falls back to // the string codegen, so the option never changes output for unsupported // schemas. @@ -47,37 +50,78 @@ function nullableMultiType (schema) { function hasDispatchKeyword (s) { return s.const !== undefined || s.allOf !== undefined || s.anyOf !== undefined || - s.oneOf !== undefined || s.if !== undefined || s.$ref !== undefined + s.oneOf !== undefined || s.if !== undefined } -function isProjectable (schema, depth = 0) { - if (typeof schema !== 'object' || schema === null || depth > 32) return false - if (hasDispatchKeyword(schema)) return false - if (Array.isArray(schema.type)) return nullableMultiType(schema) !== null +// The JSON pointer of a projected node, as the codegen writes it in its errors. +const POINTER = Symbol('pointer') + +// A $ref is projected by expanding its target in place, so a schema that is +// used many times is also copied many times. Past this number of expanded +// nodes the schema is left to the codegen, which shares one function per schema. +const MAX_REF_NODES = 1000 + +// Returns a copy of the schema at `location`, with every $ref replaced by its +// target and every node tagged with its JSON pointer, or null when the schema +// is not projectable. +function resolveProjectable (location, refs, state, depth) { + const schema = location.schema + if (typeof schema !== 'object' || schema === null || depth > 32) return null + + // truthiness, as in the codegen: an empty $ref is not a reference + if (!schema.$ref) return resolveNode(location, refs, state, depth) + + // the codegen merges the keywords next to a $ref with its target + for (const key in schema) { + if (!refs.ignoredSiblings.has(key)) return null + } + location = refs.resolve(location) + + // a target that is already being expanded is a recursive schema + const target = location.getSchemaRef() + if (state.open.has(target)) return null + state.open.add(target) + const node = resolveNode(location, refs, state, depth) + state.open.delete(target) + return node +} + +function resolveNode (location, refs, state, depth) { + const schema = location.schema + if (state.open.size !== 0 && ++state.refNodes > MAX_REF_NODES) return null + if (hasDispatchKeyword(schema)) return null + + const node = { ...schema, [POINTER]: refs.pointer(location) } + if (Array.isArray(schema.type)) return nullableMultiType(schema) !== null ? node : null if (schema.type === 'object') { if ((schema.additionalProperties !== undefined && schema.additionalProperties !== false) || schema.patternProperties !== undefined || schema.dependencies !== undefined || typeof schema.properties !== 'object' || schema.properties === null) { - return false + return null } const keys = Object.keys(schema.properties) - if (keys.length === 0) return false + if (keys.length === 0) return null + const propertiesLocation = location.getPropertyLocation('properties') + node.properties = Object.create(null) for (const key of keys) { - if (!isProjectable(schema.properties[key], depth + 1)) return false + const property = resolveProjectable(propertiesLocation.getPropertyLocation(key), refs, state, depth + 1) + if (property === null) return null + node.properties[key] = property } - return true + return node } if (schema.type === 'array') { - if (schema.items === undefined || Array.isArray(schema.items) || schema.additionalItems !== undefined) return false - return isProjectable(schema.items, depth + 1) + if (schema.items === undefined || Array.isArray(schema.items) || schema.additionalItems !== undefined) return null + node.items = resolveProjectable(location.getPropertyLocation('items'), refs, state, depth + 1) + return node.items !== null ? node : null } - if (!PRIMITIVES.has(schema.type)) return false + if (!PRIMITIVES.has(schema.type)) return null // the codegen reads `format` only for a string - return schema.type !== 'string' || schema.format !== 'unsafe' + return schema.type !== 'string' || schema.format !== 'unsafe' ? node : null } function primitiveExpr (schema, src, pointerIdx) { @@ -178,7 +222,7 @@ class Emitter { return `${holder}.${field}` } - fillObject (schema, src, dst, out, indent, pointer, holder, slotFields) { + fillObject (schema, src, dst, out, indent, holder, slotFields) { const props = schema.properties const requiredList = schema.required || [] const required = new Set(requiredList) @@ -213,7 +257,7 @@ class Emitter { out.push(`${indent} ${dst}[${ks}] = undefined`) } out.push(`${indent} } else {`) - out.push(`${indent} ${dst}[${ks}] = ${this.valueExpr(p, v, out, indent + ' ', `${pointer}/properties/${k}`, holder, slotFields)}`) + out.push(`${indent} ${dst}[${ks}] = ${this.valueExpr(p, v, out, indent + ' ', holder, slotFields)}`) out.push(`${indent} }`) } out.push(`${indent}}`) @@ -232,19 +276,19 @@ class Emitter { // Returns an expression for the projected value of `src`; may push // preparatory statements to `out` (filling a nested scratch) first. - valueExpr (schema, src, out, indent, pointer, holder, slotFields) { + valueExpr (schema, src, out, indent, holder, slotFields) { if (schema.type === 'object') { const scratch = this.allocScratch(schema, holder, slotFields) - return this.fillObject(schema, src, scratch, out, indent, pointer, holder, slotFields) + return this.fillObject(schema, src, scratch, out, indent, holder, slotFields) } if (schema.type === 'array') { const pool = this.allocArray(holder, slotFields) - return this.fillArray(schema, src, pool, out, indent, pointer, holder, slotFields) + return this.fillArray(schema, src, pool, out, indent, holder, slotFields) } - return primitiveExpr(schema, src, this.pointerIndex(pointer)) + return primitiveExpr(schema, src, this.pointerIndex(schema[POINTER])) } - fillArray (schema, src, pool, out, indent, pointer, holder, slotFields) { + fillArray (schema, src, pool, out, indent, holder, slotFields) { const items = schema.items const n = this.id('n') const i = this.id('i') @@ -252,7 +296,7 @@ class Emitter { out.push(`${indent}if (${src} === null) {`) out.push(`${indent} ${result !== pool ? `${result} = null` : `${pool}.length = 0`}`) out.push(`${indent}} else {`) - out.push(`${indent} if (!Array.isArray(${src})) typeMismatch(${this.pointerIndex(pointer)})`) + out.push(`${indent} if (!Array.isArray(${src})) typeMismatch(${this.pointerIndex(schema[POINTER])})`) out.push(`${indent} const ${n} = ${src}.length`) // Assigning to `length` is not a plain store: it goes through the array // length setter even when the value does not change, and that costs more @@ -272,7 +316,7 @@ class Emitter { const innerHolder = this.id('slot') const innerFields = [] const inner = [] - const expr = this.valueExpr(items, el, inner, indent + ' ', `${pointer}/items`, innerHolder, innerFields) + const expr = this.valueExpr(items, el, inner, indent + ' ', innerHolder, innerFields) this.decls.push(`function ${factory} () { return { ${innerFields.map(([f, lit]) => `${f}: ${lit}`).join(', ')} } }`) out.push(`${indent} for (let ${i} = ${slots}.length; ${i} < ${n}; ${i}++) ${slots}[${i}] = ${factory}()`) out.push(`${indent} for (let ${i} = 0; ${i} < ${n}; ${i}++) {`) @@ -283,7 +327,7 @@ class Emitter { out.push(`${indent} }`) } else { out.push(`${indent} for (let ${i} = 0; ${i} < ${n}; ${i}++) {`) - out.push(`${indent} ${pool}[${i}] = ${primitiveExpr(items, `${src}[${i}]`, this.pointerIndex(`${pointer}/items`))}`) + out.push(`${indent} ${pool}[${i}] = ${primitiveExpr(items, `${src}[${i}]`, this.pointerIndex(items[POINTER]))}`) out.push(`${indent} }`) } out.push(`${indent}}`) @@ -292,14 +336,18 @@ class Emitter { } // Returns the full body of the context function (declarations + main) or null -// when the schema is not projectable. -function buildProjection (schema) { - if (!isProjectable(schema)) return null +// when the schema at `location` is not projectable. `refs` is how the codegen +// reads a $ref: `resolve(location)` gives the location of its target, +// `pointer(location)` the JSON pointer used in the errors, `ignoredSiblings` +// the keywords that may stand next to a $ref without changing its target. +function buildProjection (location, refs) { + const schema = resolveProjectable(location, refs, { open: new Set(), refNodes: 0 }, 0) + if (schema === null) return null if (schema.type !== 'object' && schema.type !== 'array') return null // primitive roots gain nothing const em = new Emitter() const body = [] // root object: a null input serializes as {} (same as the codegen) - const rootExpr = em.valueExpr(schema, 'input', body, ' ', '#', null, null) + const rootExpr = em.valueExpr(schema, 'input', body, ' ', null, null) // The scratch objects are shared by every call of a serializer, so a call // that starts while another one is filling them (a getter or a toJSON() of // the input serializing with the same function) would overwrite the values @@ -400,4 +448,4 @@ const projectionHelpers = ` } ` -module.exports = { buildProjection, isProjectable } +module.exports = { buildProjection } diff --git a/test/object-mechanism-native.test.js b/test/object-mechanism-native.test.js index 055dba53..55b7af05 100644 --- a/test/object-mechanism-native.test.js +++ b/test/object-mechanism-native.test.js @@ -249,7 +249,6 @@ test('native mechanism generates projection code only for projectable schemas', { type: 'object', properties: { a: { anyOf: [{ type: 'string' }] } } }, { type: 'object', properties: { a: { type: 'string', format: 'unsafe' } } }, { type: 'object', properties: { a: { type: ['string', 'null'], format: 'unsafe' } } }, - { type: 'object', properties: { a: { $ref: '#/definitions/s' } }, definitions: { s: { type: 'string' } } }, { type: 'object', properties: { a: { type: 'array', items: [{ type: 'string' }] } } }, { type: 'object', properties: { a: { type: 'array' } } }, { type: 'object', properties: { a: { type: 'null' } } } @@ -263,6 +262,186 @@ test('native mechanism generates projection code only for projectable schemas', } }) +test('native mechanism: $ref is projected and matches the default mechanism', t => { + const user = { + type: 'object', + required: ['id'], + properties: { + id: { type: 'integer' }, + name: { type: ['string', 'null'] }, + 'a/b': { type: ['number', 'null'] }, + tags: { type: 'array', items: { type: 'string' } } + } + } + const external = { + $id: 'external', + type: 'object', + properties: { street: { type: 'string' }, city: { $ref: '#/definitions/city' } }, + definitions: { + city: { type: 'object', nullable: true, properties: { name: { type: ['string', 'null'] } } }, + zip: { type: 'string' } + } + } + const list = { $id: 'list', type: 'array', items: { $ref: 'external#/definitions/city' } } + const options = { schema: { external, list } } + const schemas = [ + // the same definition used twice and inside an array + { + type: 'object', + definitions: { user }, + properties: { + owner: { $ref: '#/definitions/user' }, + editor: { $ref: '#/definitions/user', description: 'a keyword that does not change the target' }, + members: { type: 'array', items: { $ref: '#/definitions/user' } } + } + }, + // a $ref to a $ref, and a $ref inside a definition + { + type: 'object', + definitions: { a: { $ref: '#/definitions/b' }, b: { type: 'object', properties: { owner: { $ref: '#/definitions/user' } } }, user }, + properties: { owner: { $ref: '#/definitions/a' }, members: { type: 'array', items: { $ref: '#/definitions/a' } } } + }, + // external schemas, with a $ref relative to them, a sub-schema and an anchor + { + $id: 'http://example.com/root.json', + type: 'object', + definitions: { anchored: { $id: '#anchor', type: 'object', properties: { name: { type: ['string', 'null'] } } } }, + properties: { + owner: { $ref: 'external#' }, + editor: { $ref: 'external' }, + members: { $ref: 'list' }, + tags: { $ref: 'external#/definitions/zip' }, + id: { $ref: 'external#/properties/street' }, + name: { $ref: '#anchor' } + } + } + ] + const noPrototype = Object.assign(Object.create(null), { id: 1 }) + const values = [ + { id: 1, name: 'x', 'a/b': 1.5, tags: ['a', 'b'], street: 's', city: { name: 'c' }, extra: 'dropped' }, + { id: 2, name: null, 'a/b': null, tags: [], city: null }, + { id: 3, name: 5 }, + { id: 4, 'a/b': 'text' }, + { id: 5, tags: 'text' }, + { id: 6, city: { name: 5 } }, + { name: 'no id' }, + { toJSON () { return { id: 7, name: 'from toJSON' } } }, + {}, + null, + 'text', + [{ name: 'in a list' }, null, { name: 5 }] + ] + let checks = 0 + for (const schema of schemas) { + t.assert.ok(build(schema, { ...options, objectMechanism: 'native', mode: 'debug' }).code.includes('asStringValue'), `projected: ${JSON.stringify(schema)}`) + const nat = build(schema, { ...options, objectMechanism: 'native' }) + const def = build(schema, options) + const inputs = [null, {}, ...values] + for (const a of values) { + for (const b of values) { + inputs.push({ owner: a, editor: b, members: [a, b, a], tags: a, id: b, name: a }) + } + } + for (const input of inputs) { + const expected = run(def, input) + t.assert.deepStrictEqual([run(nat, input), run(nat, input)], [expected, expected]) + checks++ + } + } + t.assert.ok(checks > 400) + + // each use of a definition has its own scratch + const twice = build(schemas[0], { objectMechanism: 'native' }) + t.assert.equal( + twice({ owner: { id: 1, name: 'a' }, editor: { id: 2, tags: ['t'] }, members: [{ id: 3 }, { id: 4, name: 'd' }] }), + '{"owner":{"id":1,"name":"a"},"editor":{"id":2,"tags":["t"]},"members":[{"id":3},{"id":4,"name":"d"}]}' + ) + // the pointer in an error is the one of the target, with its escaped key + t.assert.throws(() => twice({ owner: { id: 1, 'a/b': 'text' } }), new TypeError("The value of '#/definitions/user/properties/a~1b' does not match schema definition.")) + // a required key that is not a property, on an object without a prototype + const required = { type: 'object', required: ['constructor'], properties: { id: { type: 'integer' } } } + t.assert.deepStrictEqual(run(build(required, { objectMechanism: 'native' }), noPrototype), run(build(required), noPrototype)) + t.assert.deepStrictEqual(run(build(required, { objectMechanism: 'native' }), noPrototype), { err: 'Error: "constructor" is required!' }) + // a $ref that cannot be found is the same error + const missing = { type: 'object', properties: { a: { $ref: '#/definitions/missing' } } } + t.assert.throws(() => build(missing, { objectMechanism: 'native' }), /Cannot find reference "#\/definitions\/missing"/) +}) + +test('native mechanism: an empty $ref is not a reference, as in the default mechanism', t => { + const external = { + $id: 'external', + type: 'object', + properties: { a: { type: 'string' } }, + definitions: { d: { type: 'object', properties: { x: { $ref: '' }, y: { type: 'string' } } } } + } + const cases = [ + [{ $ref: '' }, { a: 1 }], + [{ type: 'object', properties: { a: { $ref: '' }, b: { type: 'string' } } }, { a: { z: 1 }, b: 'x' }], + [{ type: 'object', properties: { a: { type: 'string', $ref: '' } } }, { a: 5 }], + [{ type: 'array', items: { $ref: '' } }, [{ z: 1 }, 2]], + [{ type: 'object', properties: { p: { $ref: 'external#/definitions/d' } } }, { p: { x: { a: 'in', other: 1 }, y: 'y' } }] + ] + t.plan(cases.length + 2) + for (const [schema, input] of cases) { + const options = { schema: { external } } + t.assert.deepStrictEqual( + run(build(schema, { ...options, objectMechanism: 'native' }), input), + run(build(schema, options), input) + ) + } + // the value under an empty $ref has no type: it is written as it is + t.assert.equal(build(cases[4][0], { schema: { external }, objectMechanism: 'native' })(cases[4][1]), '{"p":{"x":{"a":"in","other":1},"y":"y"}}') + // with a type next to it, the node is projected like any other + t.assert.ok(build(cases[2][0], { objectMechanism: 'native', mode: 'debug' }).code.includes('asStringValue')) +}) + +test('native mechanism: a $ref the projection does not cover keeps the default mechanism', t => { + const leaf = { type: 'object', properties: { a: { type: 'string' }, b: { type: 'string' }, c: { type: 'string' } } } + // 4 x 4 x 4 x 4 uses of a 4-node schema: more than 1000 nodes once expanded + const wide = (target) => ({ type: 'object', properties: { p0: { $ref: target }, p1: { $ref: target }, p2: { $ref: target }, p3: { $ref: target } } }) + const notProjectable = [ + // keywords next to a $ref are merged with its target, definitions included + { $ref: '#/definitions/o', definitions: { o: { type: 'object', properties: { a: { type: 'string' } } } } }, + { type: 'object', definitions: { s: { type: 'string' } }, properties: { a: { $ref: '#/definitions/s', nullable: true } } }, + // recursive, directly and through another definition + { type: 'object', definitions: { node: { type: 'object', properties: { value: { type: 'string' }, next: { $ref: '#/definitions/node' } } } }, properties: { head: { $ref: '#/definitions/node' } } }, + { $id: 'tree', type: 'object', properties: { children: { type: 'array', items: { $ref: 'tree#' } } } }, + { + type: 'object', + definitions: { + a: { type: 'object', properties: { b: { $ref: '#/definitions/b' } } }, + b: { type: 'object', properties: { a: { $ref: '#/definitions/a' } } } + }, + properties: { a: { $ref: '#/definitions/a' } } + }, + // the target is not projectable + { type: 'object', definitions: { s: { anyOf: [{ type: 'string' }, { type: 'number' }] } }, properties: { a: { $ref: '#/definitions/s' } } }, + { type: 'object', definitions: { s: true }, properties: { a: { $ref: '#/definitions/s' } } }, + { type: 'object', definitions: { l: { type: 'array', items: { anyOf: [{ type: 'string' }] } } }, properties: { a: { $ref: '#/definitions/l' } } }, + { type: 'object', definitions: { d0: leaf, d1: wide('#/definitions/d0'), d2: wide('#/definitions/d1'), d3: wide('#/definitions/d2'), d4: wide('#/definitions/d3') }, properties: { a: { $ref: '#/definitions/d4' } } } + ] + const inputs = [ + { a: 'x' }, + { a: null }, + { a: ['x'] }, + { head: { value: 'x', next: { value: 'y', next: null } } }, + { children: [{ children: [] }] }, + { a: { b: { a: {} } } }, + { a: { p0: { p1: { p2: { p3: { a: 'deep' } } } } } }, + {} + ] + t.plan(notProjectable.length * (inputs.length + 1) + 1) + for (const schema of notProjectable) { + t.assert.ok(!build(schema, { objectMechanism: 'native', mode: 'debug' }).code.includes('asStringValue'), JSON.stringify(schema)) + const nat = build(schema, { objectMechanism: 'native' }) + const def = build(schema) + for (const input of inputs) t.assert.deepStrictEqual(run(nat, input), run(def, input)) + } + // the same shape, one level less, is small enough to be projected + const small = { type: 'object', definitions: { d0: leaf, d1: wide('#/definitions/d0'), d2: wide('#/definitions/d1'), d3: wide('#/definitions/d2') }, properties: { a: { $ref: '#/definitions/d3' } } } + t.assert.ok(build(small, { objectMechanism: 'native', mode: 'debug' }).code.includes('asStringValue')) +}) + test('native mechanism: unsupported schemas keep the default output', t => { const schema = { type: 'object',