From ef0540b8963febd89e60c7fefa094a53d7d9888c Mon Sep 17 00:00:00 2001 From: Tony133 Date: Mon, 23 Nov 2026 11:20:37 +0100 Subject: [PATCH 1/2] fix: objectMechanism 'native' keeps no data between calls --- README.md | 17 +- lib/projection.js | 238 ++++++++++----------------- test/object-mechanism-native.test.js | 48 ++++++ 3 files changed, 144 insertions(+), 159 deletions(-) diff --git a/README.md b/README.md index e4e1f406..a9a60551 100644 --- a/README.md +++ b/README.md @@ -197,7 +197,7 @@ are rejected before compilation. - `inlineValidators`: when using standalone mode, embed Ajv-generated validator functions in the output instead of compiling schemas at runtime. [More details](#standalone) - `largeArrayMechanism`: set the mechanism that should be used to handle large (by default `20000` or more items) arrays. [More details](#largearrays) -- `objectMechanism`: set the mechanism used to serialize objects. `'native'` projects the input into schema-shaped scratch objects and delegates to the native `JSON.stringify`, which is much faster on Node.js 25+. [More details](#objectmechanism) +- `objectMechanism`: set the mechanism used to serialize objects. `'native'` projects the input into new schema-shaped objects and delegates to the native `JSON.stringify`, which is much faster on Node.js 25+. [More details](#objectmechanism) - `compileValidators`: when `true`, the `ajv` validators used by `anyOf`, `oneOf` and `if/then/else` are compiled during `build()` instead of lazily, on the first serialization that reaches them. This makes `build()` slower but removes a potentially large one-off cost from the first `stringify()` call. Defaults to `false`. @@ -744,10 +744,9 @@ building can match, but that fast path bails out as soon as the input carries a `Date`, a `toJSON`, a class prototype or any property that is not plain data. With `objectMechanism: 'native'`, `fast-json-stringify` instead *projects* the -input into preallocated scratch objects whose keys are exactly the schema -properties, in schema order, and hands the scratch to the native -`JSON.stringify`. The scratch is plain by construction, so the fast path is -always taken, whatever the input looks like, while the schema is still applied: +input into new objects whose keys are exactly the schema properties, in schema +order, and hands them to the native `JSON.stringify`. These objects are plain +by construction, so the fast path is always taken, whatever the input looks like, while the schema is still applied: undeclared properties are dropped, `required` is enforced, `default` applied, types coerced and `format: date-time` / `date` / `time` rendered as before. The output is byte-identical to the default mechanism. @@ -766,8 +765,7 @@ The projection covers schemas made only of: - 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. +- `array` whose `items` is one such schema (no tuples), nested to any depth. Each of them can be `nullable: true` and can have an `enum`. @@ -790,9 +788,8 @@ When each object carries three undeclared properties (a string, a `Date` and an object) it is also about 4x faster than `JSON.stringify` itself. (Node.js v26.13.0, fast-json-stringify 7.3.10, Apple Silicon.) -The scratch objects are reused across calls; `JSON.stringify` is synchronous, -so this is safe, and no reference to the last input is retained beyond the -primitive values written into the scratch. +The projected objects are created by each call and dropped when it returns, so +a serializer keeps no data of the last input in memory. **When to use it** diff --git a/lib/projection.js b/lib/projection.js index 3f0e999b..ac251661 100644 --- a/lib/projection.js +++ b/lib/projection.js @@ -3,11 +3,16 @@ // Projection strategy (objectMechanism: 'native'). // // Instead of building the JSON string in generated JS, project the input into -// preallocated "scratch" objects whose keys are exactly the schema properties, -// in schema order, and hand the scratch to the native JSON.stringify. The -// scratch is clean by construction (no extra properties, no Date, no toJSON, -// standard prototypes), so V8's side-effect-free fast path (V8 13.8+) is -// always taken, even when the user's input would have bailed out of it. +// new objects whose keys are exactly the schema properties, in schema order, +// and hand them to the native JSON.stringify. The projected objects are clean +// by construction (no extra properties, no Date, no toJSON, standard +// prototypes), so V8's side-effect-free fast path (V8 13.8+) is always taken, +// even when the user's input would have bailed out of it. +// +// The projected objects are created by each call and dropped when it returns: +// a serializer keeps no data between calls, and a call that starts while +// another one is running (a getter or a toJSON() of the input serializing with +// the same function) shares nothing with it. // // Projectable schemas (every node must be one of these): // - object with `properties` only: no patternProperties, combinators, @@ -19,8 +24,7 @@ // 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. +// - array whose `items` is a single projectable schema (not a tuple). // 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 @@ -166,7 +170,6 @@ function orderedKeys (schema) { class Emitter { constructor () { - this.decls = [] this.uid = 0 // JSON pointers for error messages. The generated code only ever refers // to them by index into this table (emitted as a JSON literal), so no @@ -189,147 +192,92 @@ class Emitter { return i } - scratchLiteral (schema) { - return '{ ' + orderedKeys(schema).map((k) => `${JSON.stringify(k)}: undefined`).join(', ') + ' }' - } - - // Scratch storage for a schema node. Nodes reachable without crossing an - // array are module-level constants (one per serializer). Nodes inside array - // items live in a per-slot holder object created by a generated factory, so - // that each array element has its own scratch tree. - // - // `holder` is null at the top level (declare constants) or the expression of - // the current slot holder; `slotFields` collects the holder's fields. - allocScratch (schema, holder, slotFields) { - if (holder === null) { - const name = this.id('scratch') - this.decls.push(`const ${name} = ${this.scratchLiteral(schema)}`) - return name - } - const field = this.id('s') - slotFields.push([field, this.scratchLiteral(schema)]) - return `${holder}.${field}` - } - - allocArray (holder, slotFields) { - if (holder === null) { - const name = this.id('arr') - this.decls.push(`const ${name} = []`) - return name - } - const field = this.id('a') - slotFields.push([field, '[]']) - return `${holder}.${field}` - } - - fillObject (schema, src, dst, out, indent, holder, slotFields) { + // Pushes the statements that project `src` as an object and returns the + // variable that holds the result: a new object with every property of the + // schema, in the order of the codegen. A missing property is undefined, + // which JSON.stringify skips; keeping it gives every projected object of a + // schema the same shape. + projectObject (schema, src, out, indent) { const props = schema.properties const requiredList = schema.required || [] const required = new Set(requiredList) const keys = orderedKeys(schema) const o = this.id('o') - const result = this.resultOf(schema, dst, out, indent) + const result = this.id('r') out.push(`${indent}const ${o} = (${src} !== null && typeof ${src} === 'object' && typeof ${src}.toJSON === 'function') ? ${src}.toJSON() : ${src}`) + out.push(`${indent}let ${result}`) out.push(`${indent}if (${o} === null) {`) - if (result !== dst) { - out.push(`${indent} ${result} = null`) - } else { - for (const k of keys) out.push(`${indent} ${dst}[${JSON.stringify(k)}] = undefined`) - } + // a null input is written as {} (same as the codegen), or as null when nullable + out.push(`${indent} ${result} = ${schema.nullable === true ? 'null' : '{}'}`) out.push(`${indent}} else {`) for (const k of requiredList) { if (props[k] === undefined) { out.push(`${indent} if (${o}[${JSON.stringify(k)}] === undefined) requiredMissing(${this.keyIndex(k)})`) } } + const entries = [] for (const k of keys) { const p = props[k] const ks = JSON.stringify(k) const v = this.id('v') - out.push(`${indent} const ${v} = ${o}[${ks}]`) - out.push(`${indent} if (${v} === undefined) {`) + const value = this.id('p') // Same precedence as the codegen: a default satisfies a required key. - if (p.default !== undefined) { - out.push(`${indent} ${dst}[${ks}] = ${JSON.stringify(p.default)}`) - } else if (required.has(k)) { - out.push(`${indent} requiredMissing(${this.keyIndex(k)})`) + const missing = p.default !== undefined + ? JSON.stringify(p.default) + : required.has(k) ? `requiredMissing(${this.keyIndex(k)})` : 'undefined' + out.push(`${indent} const ${v} = ${o}[${ks}]`) + if (p.type === 'object' || p.type === 'array') { + out.push(`${indent} let ${value}`) + out.push(`${indent} if (${v} === undefined) {`) + out.push(`${indent} ${value} = ${missing}`) + out.push(`${indent} } else {`) + out.push(`${indent} ${value} = ${this.valueExpr(p, v, out, indent + ' ')}`) + out.push(`${indent} }`) } else { - out.push(`${indent} ${dst}[${ks}] = undefined`) + out.push(`${indent} const ${value} = ${v} === undefined ? ${missing} : ${this.valueExpr(p, v, out, indent + ' ')}`) } - out.push(`${indent} } else {`) - out.push(`${indent} ${dst}[${ks}] = ${this.valueExpr(p, v, out, indent + ' ', holder, slotFields)}`) - out.push(`${indent} }`) + // in an object literal "__proto__" sets the prototype: a computed key + // defines a property with that name instead + entries.push(k === '__proto__' ? `[${ks}]: ${value}` : `${ks}: ${value}`) } + out.push(`${indent} ${result} = { ${entries.join(', ')} }`) 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 - // preparatory statements to `out` (filling a nested scratch) first. - 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, holder, slotFields) - } - if (schema.type === 'array') { - const pool = this.allocArray(holder, slotFields) - return this.fillArray(schema, src, pool, out, indent, holder, slotFields) - } + // statements to `out` that must run before the expression is evaluated. + valueExpr (schema, src, out, indent) { + if (schema.type === 'object') return this.projectObject(schema, src, out, indent) + if (schema.type === 'array') return this.projectArray(schema, src, out, indent) return primitiveExpr(schema, src, this.pointerIndex(schema[POINTER])) } - fillArray (schema, src, pool, out, indent, holder, slotFields) { + // Pushes the statements that project `src` as an array and returns the + // variable that holds the result: a new array with one projected value per + // element. + projectArray (schema, src, out, indent) { const items = schema.items const n = this.id('n') const i = this.id('i') - const result = this.resultOf(schema, pool, out, indent) + const result = this.id('r') + out.push(`${indent}let ${result}`) out.push(`${indent}if (${src} === null) {`) - out.push(`${indent} ${result !== pool ? `${result} = null` : `${pool}.length = 0`}`) + // a null input is written as [] (same as the codegen), or as null when nullable + out.push(`${indent} ${result} = ${schema.nullable === true ? 'null' : '[]'}`) out.push(`${indent}} else {`) 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 - // than copying a few items. Skip it when the pool already has the right - // length, which is the case whenever two consecutive calls serialize an - // array of the same size. - out.push(`${indent} if (${pool}.length !== ${n}) ${pool}.length = ${n}`) + out.push(`${indent} ${result} = new Array(${n})`) + out.push(`${indent} for (let ${i} = 0; ${i} < ${n}; ${i}++) {`) if (items.type === 'object' || items.type === 'array') { - // Pool of per-element slot holders; each holder owns the scratch tree of - // one element (nested objects and arrays included). Grows to the longest - // array seen, never shrinks. When this array is itself inside an array - // element, its slot pool lives in the enclosing holder, so sibling - // elements never share scratch objects. - const slots = this.allocArray(holder, slotFields) - const factory = this.id('makeSlot') const el = this.id('el') - const innerHolder = this.id('slot') - const innerFields = [] - const inner = [] - 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}++) {`) out.push(`${indent} const ${el} = ${src}[${i}]`) - out.push(`${indent} const ${innerHolder} = ${slots}[${i}]`) - out.push(...inner) - out.push(`${indent} ${pool}[${i}] = ${expr}`) - out.push(`${indent} }`) + out.push(`${indent} ${result}[${i}] = ${this.valueExpr(items, el, out, indent + ' ')}`) } else { - out.push(`${indent} for (let ${i} = 0; ${i} < ${n}; ${i}++) {`) - out.push(`${indent} ${pool}[${i}] = ${primitiveExpr(items, `${src}[${i}]`, this.pointerIndex(items[POINTER]))}`) - out.push(`${indent} }`) + out.push(`${indent} ${result}[${i}] = ${primitiveExpr(items, `${src}[${i}]`, this.pointerIndex(items[POINTER]))}`) } + out.push(`${indent} }`) out.push(`${indent}}`) return result } @@ -346,19 +294,14 @@ function buildProjection (location, refs) { 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) - // 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 - // already projected. Each serializer is therefore an instance with its own - // scratch: a re-entrant call is handed to a second instance, created on - // first use, and so on for deeper nesting. - // + const rootExpr = em.valueExpr(schema, 'input', body, ' ') // A BigInt outside the safe integer range has no exact Number, so it is - // kept as a BigInt in the scratch and flagged: that scratch (never the + // kept as a BigInt in the projected value and flagged: that value (never the // input, which has already been read once) is then serialized by a small - // walker that writes the digits, as the codegen does. + // walker that writes the digits, as the codegen does. The flag is shared by + // the calls of a serializer, so a call that runs inside another one may + // clear the flag of the outer call: the outer call then finds out because + // JSON.stringify throws, and falls back to the walker. return ` ${projectionHelpers} const POINTERS = ${JSON.stringify(em.pointers)} @@ -369,36 +312,32 @@ function buildProjection (location, refs) { function requiredMissing (i) { throw new Error('"' + KEYS[i] + '" is required!') } - function createProjection () { - ${em.decls.join('\n ')} - let busy = false - let nested = null - let hasBigInt = false - const asIntegerValue = (v) => { - if (Number.isInteger(v)) return v - if (typeof v !== 'bigint') return Number(serializer.asInteger(v)) - if (v >= MIN_SAFE_BIGINT && v <= MAX_SAFE_BIGINT) return Number(v) - hasBigInt = true - return v - } - return function main (input) { - if (busy) return (nested || (nested = createProjection()))(input) - busy = true - try { + let hasBigInt = false + const asIntegerValue = (v) => { + if (Number.isInteger(v)) return v + if (typeof v !== 'bigint') return Number(serializer.asInteger(v)) + if (v >= MIN_SAFE_BIGINT && v <= MAX_SAFE_BIGINT) return Number(v) + hasBigInt = true + return v + } + function main (input) { ${body.join('\n')} - return hasBigInt ? stringifyScratchWithBigInt(${rootExpr}) : JSON.stringify(${rootExpr}) - } finally { - busy = false - hasBigInt = false - } + if (hasBigInt) { + hasBigInt = false + return stringifyWithBigInt(${rootExpr}) + } + try { + return JSON.stringify(${rootExpr}) + } catch { + return stringifyWithBigInt(${rootExpr}) } } - return createProjection() + return main ` } // Runtime helpers mirroring lib/serializer.js, returning values (not JSON text) -// to be placed into the scratch. +// to be placed into the projected objects. const projectionHelpers = ` const asStringValue = (v) => { if (typeof v === 'string') return v @@ -414,7 +353,7 @@ const projectionHelpers = ` throw new Error('The value "' + v + '" cannot be converted to a date-time.') } // serializer.asDate/asTime return JSON text: for a string input that text is - // already escaped, so the string itself goes to the scratch and is escaped + // already escaped, so the string itself is projected and is escaped // once, by JSON.stringify. const asDateValue = (v) => typeof v === 'string' ? v : serializer.asDate(v).slice(1, -1) const asTimeValue = (v) => typeof v === 'string' ? v : serializer.asTime(v).slice(1, -1) @@ -425,23 +364,24 @@ const projectionHelpers = ` } const MAX_SAFE_BIGINT = BigInt(Number.MAX_SAFE_INTEGER) const MIN_SAFE_BIGINT = -MAX_SAFE_BIGINT - // Serializes a scratch that holds a BigInt, the one value the native - // JSON.stringify rejects. A scratch is made of plain objects, arrays, strings, - // numbers, booleans, null and undefined, so nothing else needs handling. - const stringifyScratchWithBigInt = (v) => { + // Serializes a projected value that holds a BigInt, the one value the native + // JSON.stringify rejects. A projected value is made of plain objects, arrays, + // strings, numbers, booleans, null and undefined, so nothing else needs + // handling. + const stringifyWithBigInt = (v) => { if (typeof v === 'bigint') return v.toString() if (v === null || typeof v !== 'object') return JSON.stringify(v) let json = '' if (Array.isArray(v)) { for (let i = 0; i < v.length; i++) { - json += (i === 0 ? '[' : ',') + stringifyScratchWithBigInt(v[i]) + json += (i === 0 ? '[' : ',') + stringifyWithBigInt(v[i]) } return json === '' ? '[]' : json + ']' } for (const key of Object.keys(v)) { const value = v[key] if (value !== undefined) { - json += (json === '' ? '{' : ',') + JSON.stringify(key) + ':' + stringifyScratchWithBigInt(value) + json += (json === '' ? '{' : ',') + JSON.stringify(key) + ':' + stringifyWithBigInt(value) } } return json === '' ? '{}' : json + '}' diff --git a/test/object-mechanism-native.test.js b/test/object-mechanism-native.test.js index 55b7af05..cfcd12f0 100644 --- a/test/object-mechanism-native.test.js +++ b/test/object-mechanism-native.test.js @@ -549,6 +549,54 @@ test('native mechanism: scratch does not leak state between calls', t => { t.assert.equal(nat({ nested: {} }), '{"nested":{}}') }) +test('native mechanism: a serializer shares nothing between calls', t => { + const schema = { + type: 'object', + properties: { + id: { type: 'integer' }, + name: { type: 'string' }, + child: { type: 'object', properties: { id: { type: 'integer' }, name: { type: 'string' } } }, + list: { type: 'array', items: { type: 'object', properties: { id: { type: 'integer' } } } } + } + } + const nat = build(schema, { objectMechanism: 'native' }) + const def = build(schema) + t.plan(6) + + // a property missing in the second call is not left over from the first + t.assert.equal(nat({ id: 1, name: 'first', child: { id: 2, name: 'c' }, list: [{ id: 1 }, { id: 2 }, { id: 3 }] }), '{"id":1,"name":"first","child":{"id":2,"name":"c"},"list":[{"id":1},{"id":2},{"id":3}]}') + t.assert.equal(nat({ id: 2, child: {}, list: [{}] }), '{"id":2,"child":{},"list":[{}]}') + t.assert.equal(nat(null), '{}') + + // a call made while another one is running, with a BigInt beyond the safe + // range in the outer call only, in the inner call only, and in both + const big = 2n ** 70n + const reentrant = (outerId, innerId) => (fn) => fn({ + id: outerId, + get name () { return fn({ id: innerId, name: 'inner' }) }, + child: { id: outerId, name: 'c' } + }) + for (const [outerId, innerId] of [[big, 1], [1, big], [big, big]]) { + t.assert.equal(reentrant(outerId, innerId)(nat), reentrant(outerId, innerId)(def)) + } +}) + +test('native mechanism: a property named __proto__ is written as the default mechanism does', t => { + // JSON.parse defines "__proto__" as an own property, both in the schema and in the input + const schema = JSON.parse('{"type":"object","properties":{"a":{"type":"string"},"__proto__":{"type":"string"},"b":{"type":"object","properties":{"__proto__":{"type":"integer"}}}}}') + const inputs = [ + JSON.parse('{"a":"x","__proto__":"own","b":{"__proto__":5}}'), + JSON.parse('{"__proto__":"only"}'), + { a: 'x' }, + { a: 'x', b: {} } + ] + const nat = build(schema, { objectMechanism: 'native' }) + const def = build(schema) + t.plan(inputs.length + 1) + for (const input of inputs) t.assert.deepStrictEqual(run(nat, input), run(def, input)) + t.assert.equal(nat(inputs[0]), '{"a":"x","__proto__":"own","b":{"__proto__":5}}') +}) + test('native mechanism works in standalone mode', t => { const schema = { type: 'object', properties: { a: { type: 'string' }, n: { type: 'number' } } } const code = build(schema, { objectMechanism: 'native', mode: 'standalone' }) From ebc229ae6bfa59f355b2e7f123a4bea611b2120f Mon Sep 17 00:00:00 2001 From: Tony133 Date: Mon, 23 Nov 2026 11:21:22 +0100 Subject: [PATCH 2/2] perf: keep the default mechanism for objects with more than 127 properties --- README.md | 3 ++- lib/projection.js | 8 +++++++- test/object-mechanism-native.test.js | 23 +++++++++++++++++++++++ 3 files changed, 32 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index a9a60551..321921eb 100644 --- a/README.md +++ b/README.md @@ -759,7 +759,8 @@ The projection covers schemas made only of: - `object` with `properties` (no `patternProperties`, `dependencies` or combinators; `additionalProperties` absent or `false`), with at least one - property; + property and at most 127: with more, the `JSON.stringify` fast path of V8 + is not available and the default mechanism is the faster one; - `string` (with any `format` except `unsafe`), `number`, `integer`, `boolean`, without `const` or combinators; - the two-element forms `['string', 'null']`, `['number', 'null']` and diff --git a/lib/projection.js b/lib/projection.js index ac251661..5f3bd88f 100644 --- a/lib/projection.js +++ b/lib/projection.js @@ -57,6 +57,12 @@ function hasDispatchKeyword (s) { s.oneOf !== undefined || s.if !== undefined } +// The JSON.stringify fast path of V8 handles objects with up to 127 +// properties. From 128 the projected object is serialized on the slow path, +// and the projection is slower than the codegen instead of faster, so an +// object with more properties than this is left to the codegen. +const MAX_PROPERTIES = 127 + // The JSON pointer of a projected node, as the codegen writes it in its errors. const POINTER = Symbol('pointer') @@ -106,7 +112,7 @@ function resolveNode (location, refs, state, depth) { return null } const keys = Object.keys(schema.properties) - if (keys.length === 0) return null + if (keys.length === 0 || keys.length > MAX_PROPERTIES) 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 cfcd12f0..00567a22 100644 --- a/test/object-mechanism-native.test.js +++ b/test/object-mechanism-native.test.js @@ -597,6 +597,29 @@ test('native mechanism: a property named __proto__ is written as the default mec t.assert.equal(nat(inputs[0]), '{"a":"x","__proto__":"own","b":{"__proto__":5}}') }) +test('native mechanism: an object with more than 127 properties keeps the default mechanism', t => { + const wide = (count) => { + const properties = {} + const input = {} + for (let i = 0; i < count; i++) { + properties['key' + i] = i % 2 === 0 ? { type: 'string' } : { type: 'integer' } + input['key' + i] = i % 2 === 0 ? 'value ' + i : i + } + return { schema: { type: 'object', properties }, input } + } + const projected = (schema) => build(schema, { objectMechanism: 'native', mode: 'debug' }).code.includes('asStringValue') + t.plan(7) + t.assert.ok(projected(wide(127).schema)) + t.assert.ok(!projected(wide(128).schema)) + // also when the wide object is nested or is the item of an array + t.assert.ok(!projected({ type: 'object', properties: { a: { type: 'string' }, nested: wide(128).schema } })) + t.assert.ok(!projected({ type: 'array', items: wide(128).schema })) + for (const count of [127, 128, 300]) { + const { schema, input } = wide(count) + t.assert.equal(build(schema, { objectMechanism: 'native' })(input), build(schema)(input)) + } +}) + test('native mechanism works in standalone mode', t => { const schema = { type: 'object', properties: { a: { type: 'string' }, n: { type: 'number' } } } const code = build(schema, { objectMechanism: 'native', mode: 'standalone' })