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 all 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
67 changes: 26 additions & 41 deletions index.js
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,11 @@ const Validator = require('./lib/validator')
const RefResolver = require('./lib/ref-resolver')
const Location = require('./lib/location')

/**
* Keywords
*/
const constKeyword = require('./lib/keywords/const').keyword

let largeArraySize = 2e4
let largeArrayMechanism = 'default'

Expand Down Expand Up @@ -78,6 +83,7 @@ function build (schema, options) {
options,
refResolver: new RefResolver(),
rootSchemaId: schema.$id || randomUUID(),
strict: false,
validatorSchemasIds: new Set()
}

Expand Down Expand Up @@ -116,6 +122,13 @@ function build (schema, options) {
}
}

if (options.strict) {
if (typeof options.strict !== 'boolean') {
throw new Error('Strict-mode must be a boolean value')
}
context.strict = options.strict
}

const location = new Location(schema, context.rootSchemaId)
const code = buildValue(context, location, 'input')

Expand Down Expand Up @@ -321,27 +334,26 @@ function buildInnerObject (context, location) {
if (obj[${sanitized}] !== undefined) {
${addComma}
json += ${JSON.stringify(sanitized + ':')}
${buildValue(context, propertyLocation, `obj[${sanitized}]`)}
}
`

code += buildValue(context, propertyLocation, `obj[${sanitized}]`)

const defaultValue = propertyLocation.schema.default
if (defaultValue !== undefined) {
if (propertyLocation.schema.default !== undefined) {
code += `
} else {
else {
${addComma}
json += ${JSON.stringify(sanitized + ':' + JSON.stringify(defaultValue))}
json += ${JSON.stringify(sanitized + ':' + JSON.stringify(propertyLocation.schema.default))}
}
`
} else if (required.includes(key)) {
}

if (propertyLocation.schema.default === undefined && required.includes(key)) {
code += `
} else {
else {
throw new Error('${sanitized} is required!')
}
`
}

code += `
}
`
})

for (const requiredProperty of required) {
Expand Down Expand Up @@ -782,33 +794,6 @@ function buildSingleTypeSerializer (context, location, input) {
}
}

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

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

let code = ''

if (hasNullType) {
code += `
if (${input} === null) {
json += 'null'
} else {
`
}

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

if (hasNullType) {
code += `
}
`
}

return code
}

function buildValue (context, location, input) {
let schema = location.schema

Expand Down Expand Up @@ -868,7 +853,7 @@ function buildValue (context, location, input) {
return code
}

const nullable = schema.nullable === true
const nullable = schema.nullable === true && !('const' in schema)
if (nullable) {
code += `
if (${input} === null) {
Expand All @@ -878,7 +863,7 @@ function buildValue (context, location, input) {
}

if (schema.const !== undefined) {
code += buildConstSerializer(location, input)
code += constKeyword(context, location, input)
} else if (Array.isArray(type)) {
code += buildMultiTypeSerializer(context, location, input)
} else {
Expand Down
141 changes: 141 additions & 0 deletions lib/keywords/const.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,141 @@
'use strict'

function validator (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)
}
}

function keyword (context, location, input) {
const schema = location.schema
let schemaRef = location.getSchemaRef()
if (schemaRef.startsWith(context.rootSchemaId)) {
schemaRef = schemaRef.replace(context.rootSchemaId, '')
}

if (context.strict) {
return `
if (${validator(schema.const, input, 'integration')}) {
json += ${JSON.stringify(JSON.stringify(schema.const))}
} else {
throw new Error(\`The value of '${schemaRef}' does not match schema definition.\`)
}
`
} else {
return `json += JSON.stringify(${input})`
}
}

module.exports.validator = validator
module.exports.keyword = keyword
Loading