diff --git a/README.md b/README.md index eba89d5f..9651f689 100644 --- a/README.md +++ b/README.md @@ -758,16 +758,19 @@ const stringify = fastJson(schema, { objectMechanism: 'native' }) The projection covers schemas made only of: -- `object` with `properties` (no `additionalProperties`, `patternProperties`, - `nullable`, `dependencies`, combinators or `$ref`), with at least one property; -- `string` (optionally with `format: date-time`, `date` or `time`), `number`, - `integer`, `boolean`, without `nullable`, `const`, `enum`, combinators or `$ref`; +- `object` with `properties` (no `patternProperties`, `dependencies`, + combinators or `$ref`; `additionalProperties` absent or `false`), with at + least one property; +- `string` (with any `format` except `unsafe`), `number`, `integer`, `boolean`, + without `const`, combinators or `$ref`; - the two-element forms `['string', 'null']`, `['number', 'null']` and `['boolean', 'null']` (in either order), with the same strict type dispatch as the default mechanism; - `array` whose `items` is one such schema (no tuples), nested to any depth; every array element gets its own scratch objects. +Each of them can be `nullable: true` and can have an `enum`. + 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/lib/projection.js b/lib/projection.js index e51945e1..c48b6f6d 100644 --- a/lib/projection.js +++ b/lib/projection.js @@ -10,16 +10,19 @@ // 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 additionalProperties, patternProperties, -// nullable, combinators, $ref, dependencies; at least one property; -// - string / number / integer / boolean without nullable, const, enum, -// combinators, $ref; string may have format date-time / date / time; +// - object with `properties` only: no patternProperties, combinators, $ref, +// dependencies, and additionalProperties absent or false; at least one +// property; +// - string / number / integer / boolean without const, combinators, $ref; +// 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; // ['integer', 'null'] is left to the codegen (its null handling depends // on the type order); // - array whose `items` is a single projectable schema (not a tuple); array // 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. // Anything else makes buildProjection return null and the caller falls back to // the string codegen, so the option never changes output for unsupported // schemas. @@ -30,23 +33,21 @@ // numbers via the asNumber/asInteger rules, booleans via truthiness. const PRIMITIVES = new Set(['string', 'number', 'integer', 'boolean']) -const STRING_FORMATS = new Set([undefined, 'date-time', 'date', 'time']) // ['string'|'number'|'boolean', 'null'] in either order -> the non-null type; -// anything else -> null. Also requires the format rules of the base type. +// anything else -> null. A format only matters for a string. function nullableMultiType (schema) { const t = schema.type if (!Array.isArray(t) || t.length !== 2 || !t.includes('null')) return null const base = t[0] === 'null' ? t[1] : t[0] if (base !== 'string' && base !== 'number' && base !== 'boolean') return null - if (base === 'string' ? !STRING_FORMATS.has(schema.format) : schema.format !== undefined) return null + if (base === 'string' && schema.format === 'unsafe') return null return base } function hasDispatchKeyword (s) { - return s.nullable === true || s.const !== undefined || s.enum !== undefined || - s.allOf !== undefined || s.anyOf !== undefined || s.oneOf !== undefined || - s.if !== undefined || s.$ref !== undefined + return s.const !== undefined || s.allOf !== undefined || s.anyOf !== undefined || + s.oneOf !== undefined || s.if !== undefined || s.$ref !== undefined } function isProjectable (schema, depth = 0) { @@ -55,7 +56,8 @@ function isProjectable (schema, depth = 0) { if (Array.isArray(schema.type)) return nullableMultiType(schema) !== null if (schema.type === 'object') { - if (schema.additionalProperties !== undefined || schema.patternProperties !== undefined || + if ((schema.additionalProperties !== undefined && schema.additionalProperties !== false) || + schema.patternProperties !== undefined || schema.dependencies !== undefined || typeof schema.properties !== 'object' || schema.properties === null) { return false @@ -74,8 +76,8 @@ function isProjectable (schema, depth = 0) { } if (!PRIMITIVES.has(schema.type)) return false - if (schema.type === 'string') return STRING_FORMATS.has(schema.format) - return schema.format === undefined + // the codegen reads `format` only for a string + return schema.type !== 'string' || schema.format !== 'unsafe' } function primitiveExpr (schema, src, pointerIdx) { @@ -85,7 +87,7 @@ function primitiveExpr (schema, src, pointerIdx) { // null passes through; a matching primitive goes through the single-type // conversion; anything else is a TypeError. No coercion across types. const err = `typeMismatch(${pointerIdx})` - const single = primitiveExpr({ ...schema, type: base }, src, pointerIdx) + const single = primitiveExpr({ ...schema, type: base, nullable: false }, src, pointerIdx) if (base === 'string') { return `(${src} === null ? null : (typeof ${src} === 'string' || ${src} instanceof Date || ${src} instanceof RegExp || (typeof ${src} === 'object' && typeof ${src}.toString === 'function' && ${src}.toString !== Object.prototype.toString)) ? ${single} : ${err})` } @@ -94,6 +96,9 @@ function primitiveExpr (schema, src, pointerIdx) { } return `(${src} === null ? null : typeof ${src} === 'boolean' ? ${src} : ${err})` } + if (schema.nullable === true) { + return `(${src} === null ? null : ${primitiveExpr({ ...schema, nullable: false }, src, pointerIdx)})` + } switch (schema.type) { case 'string': if (schema.format === 'date-time') return `asDateTimeValue(${src})` @@ -179,9 +184,14 @@ class Emitter { const required = new Set(requiredList) const keys = orderedKeys(schema) const o = this.id('o') + const result = this.resultOf(schema, dst, out, indent) out.push(`${indent}const ${o} = (${src} !== null && typeof ${src} === 'object' && typeof ${src}.toJSON === 'function') ? ${src}.toJSON() : ${src}`) out.push(`${indent}if (${o} === null) {`) - for (const k of keys) out.push(`${indent} ${dst}[${JSON.stringify(k)}] = undefined`) + if (result !== dst) { + out.push(`${indent} ${result} = null`) + } else { + for (const k of keys) out.push(`${indent} ${dst}[${JSON.stringify(k)}] = undefined`) + } out.push(`${indent}} else {`) for (const k of requiredList) { if (props[k] === undefined) { @@ -207,6 +217,17 @@ class Emitter { out.push(`${indent} }`) } out.push(`${indent}}`) + return result + } + + // What a filled object or array is projected to: its scratch, or, for a + // nullable schema, a variable holding the scratch that is set to null when + // the input is null. + resultOf (schema, scratch, out, indent) { + if (schema.nullable !== true) return scratch + const result = this.id('r') + out.push(`${indent}let ${result} = ${scratch}`) + return result } // Returns an expression for the projected value of `src`; may push @@ -214,13 +235,11 @@ class Emitter { valueExpr (schema, src, out, indent, pointer, holder, slotFields) { if (schema.type === 'object') { const scratch = this.allocScratch(schema, holder, slotFields) - this.fillObject(schema, src, scratch, out, indent, pointer, holder, slotFields) - return scratch + return this.fillObject(schema, src, scratch, out, indent, pointer, holder, slotFields) } if (schema.type === 'array') { const pool = this.allocArray(holder, slotFields) - this.fillArray(schema, src, pool, out, indent, pointer, holder, slotFields) - return pool + return this.fillArray(schema, src, pool, out, indent, pointer, holder, slotFields) } return primitiveExpr(schema, src, this.pointerIndex(pointer)) } @@ -229,8 +248,9 @@ class Emitter { const items = schema.items const n = this.id('n') const i = this.id('i') + const result = this.resultOf(schema, pool, out, indent) out.push(`${indent}if (${src} === null) {`) - out.push(`${indent} ${pool}.length = 0`) + 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} const ${n} = ${src}.length`) @@ -262,6 +282,7 @@ class Emitter { out.push(`${indent} }`) } out.push(`${indent}}`) + return result } } diff --git a/test/object-mechanism-native.test.js b/test/object-mechanism-native.test.js index a94d4459..518f9684 100644 --- a/test/object-mechanism-native.test.js +++ b/test/object-mechanism-native.test.js @@ -149,21 +149,31 @@ test('native mechanism generates projection code only for projectable schemas', { type: 'array', items: { type: 'object', properties: { a: { type: 'string' } } } }, { type: 'object', properties: { a: { type: 'array', items: { type: 'array', items: { type: 'string' } } } } }, { type: 'object', properties: { a: { type: 'array', items: { type: 'object', properties: { b: { type: 'object', properties: { c: { type: 'string' } } } } } } } }, - { type: 'object', properties: { a: { type: ['string', 'null'] } } } + { type: 'object', properties: { a: { type: ['string', 'null'] } } }, + { type: 'object', properties: { a: { type: 'string' } }, additionalProperties: false }, + { type: 'object', nullable: true, properties: { a: { type: 'string' } } }, + { type: 'object', properties: { a: { type: 'string', nullable: true } } }, + { type: 'object', properties: { a: { type: 'string', enum: ['x'] } } }, + { type: 'object', properties: { a: { type: 'string', format: 'email' } } }, + { type: 'object', properties: { a: { type: 'integer', format: 'int64' } } }, + { type: 'object', properties: { a: { type: ['string', 'null'], format: 'email' } } }, + { type: 'object', properties: { a: { type: ['number', 'null'], format: 'float' } } }, + { type: 'object', properties: { a: { type: 'array', nullable: true, items: { type: 'string' } } } } ] const notProjectable = [ { type: 'string' }, { type: 'object', properties: {} }, { type: 'object', properties: { a: { type: 'string' } }, additionalProperties: true }, { type: 'object', properties: { a: { type: 'string' } }, patternProperties: { '^x': { type: 'string' } } }, - { type: 'object', nullable: true, properties: { a: { type: 'string' } } }, - { type: 'object', properties: { a: { type: 'string', nullable: true } } }, + { type: 'object', properties: { a: { type: 'string' } }, additionalProperties: { type: 'string' } }, { type: 'object', properties: { a: { type: ['string', 'number'] } } }, { type: 'object', properties: { a: { type: ['integer', 'null'] } } }, { type: 'object', properties: { a: { const: 'x' } } }, - { type: 'object', properties: { a: { type: 'string', enum: ['x'] } } }, + { type: 'object', properties: { a: { enum: ['x'] } } }, + { type: 'object', properties: { a: { nullable: true } } }, { type: 'object', properties: { a: { anyOf: [{ type: 'string' }] } } }, - { type: 'object', properties: { a: { type: 'string', format: 'email' } } }, + { 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' } } }, @@ -181,14 +191,94 @@ test('native mechanism generates projection code only for projectable schemas', test('native mechanism: unsupported schemas keep the default output', t => { const schema = { type: 'object', - properties: { a: { type: 'string' }, b: { type: 'string', nullable: true } }, + properties: { a: { type: 'string' }, b: { type: 'string', format: 'unsafe' } }, additionalProperties: { type: 'number' } } - const data = { a: 'x', b: null, c: 1, d: 2 } + const data = { a: 'x', b: 'y', c: 1, d: 2 } t.plan(1) t.assert.equal(build(schema, { objectMechanism: 'native' })(data), build(schema)(data)) }) +test('native mechanism: nullable, enum, format and additionalProperties false match the default mechanism', t => { + class Entity { + constructor (value) { this.value = value } + toJSON () { return this.value } + } + const valuesByType = { + string: ['x', 'needs "escaping"\n', '', 5, true, new Date(0), /re/, { toString () { return 'custom' } }], + number: [1.5, 0, -0, '3', Infinity, NaN, 10n, true], + integer: [1, 1.5, '3', 10n, 2n ** 64n, NaN, true], + boolean: [true, false, 0, 'y', ''], + object: [{ a: 'x' }, { a: null }, {}, { a: 'x', extra: 1 }, new Entity({ a: 'x' }), new Entity(null), 'text', 5], + array: [['x'], [], [null, 'y'], 'text', 5, {}] + } + const keywordsByType = { + string: [{}, { format: 'email' }, { format: 'uuid' }, { format: 'date-time' }, { format: 'date' }, { format: 'time' }, { enum: ['x', 'y'] }, { default: 'd' }], + number: [{}, { format: 'float' }, { enum: [1, 2] }, { default: 7 }], + integer: [{}, { format: 'int64' }, { enum: [1, 2] }], + boolean: [{}, { enum: [true] }, { format: 'ignored' }], + object: [{ properties: { a: { type: 'string', nullable: true } } }, { properties: { a: { type: 'string' } }, additionalProperties: false, required: ['a'] }], + array: [{ items: { type: 'string', nullable: true } }, { items: { type: 'object', nullable: true, additionalProperties: false, properties: { a: { type: 'string' } } } }] + } + const multiTypes = [ + [{ type: ['string', 'null'] }, valuesByType.string], + [{ type: ['null', 'string'], format: 'email' }, valuesByType.string], + [{ type: ['number', 'null'], format: 'float' }, valuesByType.number], + [{ type: ['boolean', 'null'], enum: [true, null] }, valuesByType.boolean] + ] + const label = (v) => JSON.stringify(v, (k, x) => typeof x === 'bigint' ? `${x}n` : x instanceof RegExp ? String(x) : x) + + const variants = [] + for (const type of Object.keys(valuesByType)) { + for (const keywords of keywordsByType[type]) { + for (const nullable of [true, false]) { + const schema = nullable ? { type, nullable, ...keywords } : { type, ...keywords } + variants.push([schema, valuesByType[type]]) + } + } + } + for (const [schema, values] of multiTypes) { + variants.push([schema, values], [{ ...schema, nullable: true }, values]) + } + + let checks = 0 + for (const [schema, values] of variants) { + const wrappers = [ + { type: 'object', additionalProperties: false, properties: { p: schema, last: { type: 'boolean' } } }, + { type: 'object', required: ['p'], properties: { p: schema } }, + { type: 'object', nullable: true, properties: { list: { type: 'array', nullable: true, items: schema } } } + ] + for (const wrapper of wrappers) { + const nat = build(wrapper, { objectMechanism: 'native' }) + const def = build(wrapper) + t.assert.ok(build(wrapper, { objectMechanism: 'native', mode: 'debug' }).code.includes('asStringValue'), `projected: ${label(wrapper)}`) + checks++ + const inputs = [null, {}, { p: null, list: null }, { p: undefined, list: [] }, new Entity(null)] + for (const value of [null, ...values]) { + inputs.push({ p: value, last: 1, extra: 'dropped', list: [value, null, value] }) + inputs.push(new Entity({ p: value, list: [value] })) + } + for (const input of inputs) { + const twice = [run(nat, input), run(nat, input)] + const expected = run(def, input) + t.assert.deepStrictEqual(twice, [expected, expected], `${label(wrapper)} <- ${label(input)}`) + checks++ + } + } + } + t.assert.ok(checks > 3000) + + // a nullable root, after a call that filled the scratch + const root = build({ type: 'object', nullable: true, properties: { a: { type: 'string' } } }, { objectMechanism: 'native' }) + t.assert.equal(root({ a: 'x' }), '{"a":"x"}') + t.assert.equal(root(null), 'null') + t.assert.equal(root({ a: 'y' }), '{"a":"y"}') + const list = build({ type: 'array', nullable: true, items: { type: 'string', nullable: true } }, { objectMechanism: 'native' }) + t.assert.equal(list(['x', null]), '["x",null]') + t.assert.equal(list(null), 'null') + t.assert.equal(list([]), '[]') +}) + test('objectMechanism option validation', t => { t.plan(3) t.assert.doesNotThrow(() => build({ type: 'object', properties: { a: { type: 'string' } } }, { objectMechanism: 'default' })) @@ -276,7 +366,7 @@ test('native mechanism: [primitive, null] multi-type properties keep the strict t.assert.ok(build(schema, { objectMechanism: 'native', mode: 'debug' }).code.includes('asStringValue'), 'schema is projected') for (const c of cases) t.assert.deepStrictEqual(run(nat, c), run(def, c), JSON.stringify(c, (k, v) => typeof v === 'bigint' ? 'bigint' : v)) // ['integer', 'null'] and non-null multi-types are not projected - const notProjected = [{ type: ['integer', 'null'] }, { type: ['string', 'number'] }, { type: ['string', 'null', 'number'] }, { type: ['string', 'null'], format: 'email' }] + const notProjected = [{ type: ['integer', 'null'] }, { type: ['string', 'number'] }, { type: ['string', 'null', 'number'] }, { type: ['string', 'null'], format: 'unsafe' }] t.assert.ok(notProjected.every((p) => !build({ type: 'object', properties: { a: p } }, { objectMechanism: 'native', mode: 'debug' }).code.includes('asStringValue'))) })