2 KeywordErrorDefinition,
7 import type {SchemaObjCxt} from ".."
8 import {isJSONType, JSONType} from "../rules"
9 import {schemaHasRulesForType} from "./applicability"
10 import {reportError} from "../errors"
11 import {_, nil, and, not, operators, Code, Name} from "../codegen"
12 import {toHash, schemaRefOrVal} from "../util"
14 export enum DataType {
19 export function getSchemaTypes(schema: AnySchemaObject): JSONType[] {
20 const types = getJSONTypes(schema.type)
21 const hasNull = types.includes("null")
23 if (schema.nullable === false) throw new Error("type: null contradicts nullable: false")
25 if (!types.length && schema.nullable !== undefined) {
26 throw new Error('"nullable" cannot be used without "type"')
28 if (schema.nullable === true) types.push("null")
33 export function getJSONTypes(ts: unknown | unknown[]): JSONType[] {
34 const types: unknown[] = Array.isArray(ts) ? ts : ts ? [ts] : []
35 if (types.every(isJSONType)) return types
36 throw new Error("type must be JSONType or JSONType[]: " + types.join(","))
39 export function coerceAndCheckDataType(it: SchemaObjCxt, types: JSONType[]): boolean {
40 const {gen, data, opts} = it
41 const coerceTo = coerceToTypes(types, opts.coerceTypes)
44 !(coerceTo.length === 0 && types.length === 1 && schemaHasRulesForType(it, types[0]))
46 const wrongType = checkDataTypes(types, data, opts.strictNumbers, DataType.Wrong)
47 gen.if(wrongType, () => {
48 if (coerceTo.length) coerceData(it, types, coerceTo)
49 else reportTypeError(it)
55 const COERCIBLE: Set<JSONType> = new Set(["string", "number", "integer", "boolean", "null"])
56 function coerceToTypes(types: JSONType[], coerceTypes?: boolean | "array"): JSONType[] {
58 ? types.filter((t) => COERCIBLE.has(t) || (coerceTypes === "array" && t === "array"))
62 function coerceData(it: SchemaObjCxt, types: JSONType[], coerceTo: JSONType[]): void {
63 const {gen, data, opts} = it
64 const dataType = gen.let("dataType", _`typeof ${data}`)
65 const coerced = gen.let("coerced", _`undefined`)
66 if (opts.coerceTypes === "array") {
67 gen.if(_`${dataType} == 'object' && Array.isArray(${data}) && ${data}.length == 1`, () =>
69 .assign(data, _`${data}[0]`)
70 .assign(dataType, _`typeof ${data}`)
71 .if(checkDataTypes(types, data, opts.strictNumbers), () => gen.assign(coerced, data))
74 gen.if(_`${coerced} !== undefined`)
75 for (const t of coerceTo) {
76 if (COERCIBLE.has(t) || (t === "array" && opts.coerceTypes === "array")) {
84 gen.if(_`${coerced} !== undefined`, () => {
85 gen.assign(data, coerced)
86 assignParentData(it, coerced)
89 function coerceSpecificType(t: string): void {
93 .elseIf(_`${dataType} == "number" || ${dataType} == "boolean"`)
94 .assign(coerced, _`"" + ${data}`)
95 .elseIf(_`${data} === null`)
96 .assign(coerced, _`""`)
101 _`${dataType} == "boolean" || ${data} === null
102 || (${dataType} == "string" && ${data} && ${data} == +${data})`
104 .assign(coerced, _`+${data}`)
109 _`${dataType} === "boolean" || ${data} === null
110 || (${dataType} === "string" && ${data} && ${data} == +${data} && !(${data} % 1))`
112 .assign(coerced, _`+${data}`)
116 .elseIf(_`${data} === "false" || ${data} === 0 || ${data} === null`)
117 .assign(coerced, false)
118 .elseIf(_`${data} === "true" || ${data} === 1`)
119 .assign(coerced, true)
122 gen.elseIf(_`${data} === "" || ${data} === 0 || ${data} === false`)
123 gen.assign(coerced, null)
129 _`${dataType} === "string" || ${dataType} === "number"
130 || ${dataType} === "boolean" || ${data} === null`
132 .assign(coerced, _`[${data}]`)
137 function assignParentData({gen, parentData, parentDataProperty}: SchemaObjCxt, expr: Name): void {
138 // TODO use gen.property
139 gen.if(_`${parentData} !== undefined`, () =>
140 gen.assign(_`${parentData}[${parentDataProperty}]`, expr)
144 export function checkDataType(
147 strictNums?: boolean | "log",
148 correct = DataType.Correct
150 const EQ = correct === DataType.Correct ? operators.EQ : operators.NEQ
154 return _`${data} ${EQ} null`
156 cond = _`Array.isArray(${data})`
159 cond = _`${data} && typeof ${data} == "object" && !Array.isArray(${data})`
162 cond = numCond(_`!(${data} % 1) && !isNaN(${data})`)
168 return _`typeof ${data} ${EQ} ${dataType}`
170 return correct === DataType.Correct ? cond : not(cond)
172 function numCond(_cond: Code = nil): Code {
173 return and(_`typeof ${data} == "number"`, _cond, strictNums ? _`isFinite(${data})` : nil)
177 export function checkDataTypes(
178 dataTypes: JSONType[],
180 strictNums?: boolean | "log",
183 if (dataTypes.length === 1) {
184 return checkDataType(dataTypes[0], data, strictNums, correct)
187 const types = toHash(dataTypes)
188 if (types.array && types.object) {
189 const notObj = _`typeof ${data} != "object"`
190 cond = types.null ? notObj : _`!${data} || ${notObj}`
197 if (types.number) delete types.integer
198 for (const t in types) cond = and(cond, checkDataType(t as JSONType, data, strictNums, correct))
202 export type TypeError = ErrorObject<"type", {type: string}>
204 const typeError: KeywordErrorDefinition = {
205 message: ({schema}) => `must be ${schema}`,
206 params: ({schema, schemaValue}) =>
207 typeof schema == "string" ? _`{type: ${schema}}` : _`{type: ${schemaValue}}`,
210 export function reportTypeError(it: SchemaObjCxt): void {
211 const cxt = getTypeErrorContext(it)
212 reportError(cxt, typeError)
215 function getTypeErrorContext(it: SchemaObjCxt): KeywordErrorCxt {
216 const {gen, data, schema} = it
217 const schemaCode = schemaRefOrVal(it, schema, "type")
224 schemaValue: schemaCode,
225 parentSchema: schema,