Skip to content

Support scalar nullable anyOf in the native object mechanism #942

Backlog

Description

@rvitaliy

Current behavior

On Node.js 26, a closed response object can use objectMechanism: 'native' until a single property uses anyOf for a nullable scalar. The compiler then uses the ordinary serializer for the whole response. Schema generators emit this shape for string | null, including string branches with constraints.

Minimal reproduction

Tested with fast-json-stringify 7.3.10 on main at a06b3a4 and Node.js 26.13.1.

const assert = require('node:assert/strict')
const fjs = require('fast-json-stringify')

const schema = {
  type: 'object',
  additionalProperties: false,
  required: ['id', 'name'],
  properties: {
    id: { type: 'integer' },
    name: {
      anyOf: [
        { type: 'string', pattern: '^[A-Z]+$' },
        { type: 'null' }
      ]
    }
  }
}
const options = { objectMechanism: 'native' }
const input = { id: 1, name: 'ADA', extra: true }
const debug = fjs(schema, { ...options, mode: 'debug' })
console.log('Uses projection:', debug.code.includes('const asStringValue'))
const stringify = fjs.restore(debug)
assert.equal(stringify(input), '{"id":1,"name":"ADA"}')
assert.equal(stringify({ id: 2, name: null }), '{"id":2,"name":null}')
assert.throws(() => stringify({ id: 3, name: 'ada' }), TypeError)

The script prints Uses projection: false and the assertions pass.

Proposed behavior

Allow a supported scalar branch and a null branch to participate in projection. Reuse the existing ordered Ajv checks on the original value and preserve the output and errors of the ordinary serializer. A rewrite to type: ['string', 'null'] would drop the branch validation in this example.

This extends the eligible shapes from #936. General object and multi-branch unions can continue to fall back.

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions