Skip to content

const is validated by fjs, add strict mode #579

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
wants to merge 11 commits into from
Closed
Show file tree
Hide file tree
Changes from 3 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
65 changes: 48 additions & 17 deletions index.js
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ const Serializer = require('./lib/serializer')
const Validator = require('./lib/validator')
const RefResolver = require('./lib/ref-resolver')
const Location = require('./lib/location')
const constValidator = require('./lib/const-validator')

let largeArraySize = 2e4
let largeArrayMechanism = 'default'
Expand Down Expand Up @@ -785,26 +786,56 @@ function buildSingleTypeSerializer (location, input) {

function buildConstSerializer (location, input) {
const schema = location.schema
const type = schema.type

const hasNullType = Array.isArray(type) && type.includes('null')

let schemaRef = location.getSchemaRef()
if (schemaRef.startsWith(rootSchemaId)) {
schemaRef = schemaRef.replace(rootSchemaId, '')
}
let code = ''

if (hasNullType) {
code += `
if (${input} === null) {
json += 'null'
switch (typeof schema.const) {
case 'bigint':
code += `
if (${input} === ${schema.const}n) {
json += '${Number(schema.const)}'
} else {
`
}

code += `json += '${JSON.stringify(schema.const)}'`

if (hasNullType) {
code += `
throw new Error(\`The value of '${schemaRef}' does not match schema definition.\`)
}`
break
case 'number':
case 'boolean':
code += `
if (${input} === ${schema.const}) {
json += ${JSON.stringify(JSON.stringify(schema.const))}
} else {
throw new Error(\`The value of '${schemaRef}' does not match schema definition.\`)
}`
break
case 'object':
if (schema.const === null) {
code += `
if (${input} === null) {
json += 'null'
} else {
throw new Error(\`The value of '${schemaRef}' does not match schema definition.\`)
}`
} else {
code += `
if (${constValidator(schema.const, input, 'integration')}) {
json += ${JSON.stringify(JSON.stringify(schema.const))}
} else {
throw new Error(\`The value of '${schemaRef}' does not match schema definition.\`)
}`
}
`
break
case 'string':
case 'undefined':
code += `
if (${input} === '${schema.const}') {
json += ${JSON.stringify(JSON.stringify(schema.const))}
} else {
throw new Error(\`The value of '${schemaRef}' does not match schema definition.\`)
}`
break
}

return code
Expand Down Expand Up @@ -869,7 +900,7 @@ function buildValue (location, input) {
return code
}

const nullable = schema.nullable === true
const nullable = schema.nullable === true && !('const' in schema)
if (nullable) {
code += `
if (${input} === null) {
Expand Down
120 changes: 120 additions & 0 deletions lib/const-validator.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,120 @@
'use strict'

function constValidator (input, accessPath = 'value', mode = 'function') {
if (mode === 'integration') {
return `${_const(input, accessPath)} true\n`
} else {
return new Function('value', `return (\n${_const(input, accessPath)} true\n)`) // eslint-disable-line no-new-func
}
}

function _const (input, accessPath) {
let functionCode = ''
switch (typeof input) {
case 'undefined':
functionCode += _constUndefined(input, accessPath)
break
case 'bigint':
functionCode += _constBigInt(input, accessPath)
break
case 'boolean':
functionCode += _constBoolean(input, accessPath)
break
case 'number':
functionCode += _constNumber(input, accessPath)
break
case 'string':
functionCode += _constString(input, accessPath)
break
case 'object':
functionCode += _constObject(input, accessPath)
break
}
return functionCode
}

function _constUndefined (input, accessPath) {
return `typeof ${accessPath} === 'undefined' &&\n`
}

function _constBigInt (input, accessPath) {
return `typeof ${accessPath} === 'bigint' && ${accessPath} === ${input.toString()}n &&\n`
}

function _constNumber (input, accessPath) {
if (input !== input) { // eslint-disable-line no-self-compare
return `typeof ${accessPath} === 'number' && ${accessPath} !== ${accessPath} &&\n`
} else {
return `typeof ${accessPath} === 'number' && ${accessPath} === ${input.toString()} &&\n`
}
}

function _constBoolean (input, accessPath) {
return `typeof ${accessPath} === 'boolean' && ${accessPath} === ${input ? 'true' : 'false'} &&\n`
}

function _constString (input, accessPath) {
return `typeof ${accessPath} === 'string' && ${accessPath} === ${JSON.stringify(input)} &&\n`
}

function _constNull (input, accessPath) {
return `typeof ${accessPath} === 'object' && ${accessPath} === null &&\n`
}

function _constArray (input, accessPath) {
let functionCode = `Array.isArray(${accessPath}) && ${accessPath}.length === ${input.length} &&\n`
for (let i = 0; i < input.length; ++i) {
functionCode += _const(input[i], `${accessPath}[${i}]`)
}
return functionCode
}

function _constPOJO (input, accessPath) {
const keys = Object.keys(input)

let functionCode = `typeof ${accessPath} === 'object' && ${accessPath} !== null &&\n`

functionCode += `Object.keys(${accessPath}).length === ${keys.length} &&\n`

if (typeof input.valueOf === 'function') {
functionCode += `(${accessPath}.valueOf === Object.prototype.valueOf || ${accessPath}.valueOf() === ${JSON.stringify(input.valueOf())}) &&\n`
}

if (typeof input.toString === 'function') {
functionCode += `(${accessPath}.toString === Object.prototype.toString || ${accessPath}.toString() === ${JSON.stringify(input.toString())}) &&\n`
}
// check keys
for (const key of keys) {
functionCode += `${JSON.stringify(key)} in ${accessPath} &&\n`
}
// check values
for (const key of keys) {
functionCode += `${_const(input[key], `${accessPath}[${JSON.stringify(key)}]`)}`
}

return functionCode
}

function _constRegExp (input, accessPath) {
return `typeof ${accessPath} === 'object' && ${accessPath} !== null && ${accessPath}.constructor === RegExp && ${accessPath}.source === ${JSON.stringify(input.source)} && ${accessPath}.flags === ${JSON.stringify(input.flags)} &&\n`
}

function _constDate (input, accessPath) {
return `typeof ${accessPath} === 'object' && ${accessPath} !== null && ${accessPath}.constructor === Date && ${accessPath}.getTime() === ${input.getTime()} &&\n`
}

function _constObject (input, accessPath) {
if (input === null) {
return _constNull(input, accessPath)
} else if (Array.isArray(input)) {
return _constArray(input, accessPath)
} else if (input.constructor === RegExp) {
return _constRegExp(input, accessPath)
} else if (input.constructor === Date) {
return _constDate(input, accessPath)
} else {
return _constPOJO(input, accessPath)
}
}

module.exports = constValidator
152 changes: 152 additions & 0 deletions test/const-validator.test.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,152 @@
'use strict'

const test = require('tap').test
const constValidator = require('../lib/const-validator')

test('string', (t) => {
t.plan(2)

const validateConst = constValidator('stringValue')

t.equal(validateConst('stringValue'), true)
t.equal(validateConst('b'), false)
})

test('number', (t) => {
t.plan(2)

const validateConst = constValidator(42)

t.equal(validateConst(42), true)
t.equal(validateConst(43), false)
})

test('bigint', (t) => {
t.plan(2)

const validateConst = constValidator(42n)

t.equal(validateConst(42n), true)
t.equal(validateConst(43n), false)
})

test('boolean', (t) => {
t.plan(2)

const validateConst = constValidator(true)

t.equal(validateConst(true), true)
t.equal(validateConst(false), false)
})

test('null', (t) => {
t.plan(2)

const validateConst = constValidator(null)

t.equal(validateConst(null), true)
t.equal(validateConst('null'), false)
})

test('array, basic', (t) => {
t.plan(3)

const validateConst = constValidator([1, 2, 3])

t.equal(validateConst([1, 2, 3]), true)
t.equal(validateConst([1, 2]), false)
t.equal(validateConst([1, 2, 3, 4]), false)
})

test('array, only numbers', (t) => {
t.plan(2)

const validateConst = constValidator([1, 2, 3])

t.equal(validateConst([1, 2, 3]), true)
t.equal(validateConst([1, 2, 4]), false)
})

test('array, sub arrays with numbers', (t) => {
t.plan(3)

const validateConst = constValidator([[1, 2], 3])

t.equal(validateConst([[1, 2], 3]), true)
t.equal(validateConst([[1, 2], 4]), false)
t.equal(validateConst([[1, 3], 4]), false)
})

test('object, two properties', (t) => {
t.plan(3)

const validateConst = constValidator({ a: 1, b: 2 })

t.equal(validateConst({ a: 1, b: 2 }), true)
t.equal(validateConst({ b: 2, a: 1 }), true)
t.equal(validateConst({ a: 1, b: 3 }), false)
})

test('NaN', (t) => {
t.plan(2)

const validateConst = constValidator(NaN)

t.equal(validateConst(NaN), true)
t.equal(validateConst(Infinity), false)
})

test('Infinity', (t) => {
t.plan(2)

const validateConst = constValidator(Infinity)

t.equal(validateConst(Infinity), true)
t.equal(validateConst(-Infinity), false)
})

test('Infinity', (t) => {
t.plan(2)

const validateConst = constValidator(Infinity)

t.equal(validateConst(Infinity), true)
t.equal(validateConst(-Infinity), false)
})

test('RegExp', (t) => {
t.plan(3)

const validateConst = constValidator(/a-z/g)

t.equal(validateConst(/a-z/g), true)
t.equal(validateConst(/a-z/gm), false)
t.equal(validateConst(/a-Z/gm), false)
})

test('Date', (t) => {
t.plan(2)

const validateConst = constValidator(new Date(123))

t.equal(validateConst(new Date(123)), true)
t.equal(validateConst(new Date(124)), false)
})

const spec = require('./spec/fast-deep-equal.spec')

spec.forEach(function (suite) {
test(suite.description, function (t) {
t.plan(suite.tests.length * 2)
suite.tests.forEach(function (testCase) {
t.test(testCase.description, function (t) {
t.plan(1)
t.equal(constValidator(testCase.value1)(testCase.value2), testCase.equal)
})
t.test(testCase.description + ' (reverse arguments)', function (t) {
t.plan(1)
t.equal(constValidator(testCase.value2)(testCase.value1), testCase.equal)
})
})
})
})
Loading