4 KeywordErrorDefinition,
7 import type {SchemaObjCxt} from "../../compile"
8 import type {KeywordCxt} from "../../compile/validate"
9 import {_, str, not, Name} from "../../compile/codegen"
10 import {alwaysValidSchema, checkStrictMode} from "../../compile/util"
12 export type IfKeywordError = ErrorObject<"if", {failingKeyword: string}, AnySchema>
14 const error: KeywordErrorDefinition = {
15 message: ({params}) => str`must match "${params.ifClause}" schema`,
16 params: ({params}) => _`{failingKeyword: ${params.ifClause}}`,
19 const def: CodeKeywordDefinition = {
21 schemaType: ["object", "boolean"],
24 code(cxt: KeywordCxt) {
25 const {gen, parentSchema, it} = cxt
26 if (parentSchema.then === undefined && parentSchema.else === undefined) {
27 checkStrictMode(it, '"if" without "then" and "else" is ignored')
29 const hasThen = hasSchema(it, "then")
30 const hasElse = hasSchema(it, "else")
31 if (!hasThen && !hasElse) return
33 const valid = gen.let("valid", true)
34 const schValid = gen.name("_valid")
38 if (hasThen && hasElse) {
39 const ifClause = gen.let("ifClause")
40 cxt.setParams({ifClause})
41 gen.if(schValid, validateClause("then", ifClause), validateClause("else", ifClause))
43 gen.if(schValid, validateClause("then"))
45 gen.if(not(schValid), validateClause("else"))
48 cxt.pass(valid, () => cxt.error(true))
50 function validateIf(): void {
51 const schCxt = cxt.subschema(
60 cxt.mergeEvaluated(schCxt)
63 function validateClause(keyword: string, ifClause?: Name): () => void {
65 const schCxt = cxt.subschema({keyword}, schValid)
66 gen.assign(valid, schValid)
67 cxt.mergeValidEvaluated(schCxt, valid)
68 if (ifClause) gen.assign(ifClause, _`${keyword}`)
69 else cxt.setParams({ifClause: keyword})
75 function hasSchema(it: SchemaObjCxt, keyword: string): boolean {
76 const schema = it.schema[keyword]
77 return schema !== undefined && !alwaysValidSchema(it, schema)