2 AddedKeywordDefinition,
8 import type {SchemaCxt, SchemaObjCxt} from ".."
9 import type {InstanceOptions} from "../../core"
10 import {boolOrEmptySchema, topBoolOrEmptySchema} from "./boolSchema"
11 import {coerceAndCheckDataType, getSchemaTypes} from "./dataType"
12 import {shouldUseGroup, shouldUseRule} from "./applicability"
13 import {checkDataType, checkDataTypes, reportTypeError, DataType} from "./dataType"
14 import {assignDefaults} from "./defaults"
15 import {funcKeywordCode, macroKeywordCode, validateKeywordUsage, validSchemaType} from "./keyword"
16 import {getSubschema, extendSubschemaData, SubschemaArgs, extendSubschemaMode} from "./subschema"
17 import {_, nil, str, or, not, getProperty, Block, Code, Name, CodeGen} from "../codegen"
18 import N from "../names"
19 import {resolveUrl} from "../resolve"
28 import type {JSONType, Rule, RuleGroup} from "../rules"
37 // schema compilation - generates validation function, subschemaCode (below) is used for subschemas
38 export function validateFunctionCode(it: SchemaCxt): void {
39 if (isSchemaObj(it)) {
41 if (schemaCxtHasRules(it)) {
46 validateFunction(it, () => topBoolOrEmptySchema(it))
49 function validateFunction(
50 {gen, validateName, schema, schemaEnv, opts}: SchemaCxt,
54 gen.func(validateName, _`${N.data}, ${N.valCxt}`, schemaEnv.$async, () => {
55 gen.code(_`"use strict"; ${funcSourceUrl(schema, opts)}`)
56 destructureValCxtES5(gen, opts)
60 gen.func(validateName, _`${N.data}, ${destructureValCxt(opts)}`, schemaEnv.$async, () =>
61 gen.code(funcSourceUrl(schema, opts)).code(body)
66 function destructureValCxt(opts: InstanceOptions): Code {
67 return _`{${N.instancePath}="", ${N.parentData}, ${N.parentDataProperty}, ${N.rootData}=${
69 }${opts.dynamicRef ? _`, ${N.dynamicAnchors}={}` : nil}}={}`
72 function destructureValCxtES5(gen: CodeGen, opts: InstanceOptions): void {
76 gen.var(N.instancePath, _`${N.valCxt}.${N.instancePath}`)
77 gen.var(N.parentData, _`${N.valCxt}.${N.parentData}`)
78 gen.var(N.parentDataProperty, _`${N.valCxt}.${N.parentDataProperty}`)
79 gen.var(N.rootData, _`${N.valCxt}.${N.rootData}`)
80 if (opts.dynamicRef) gen.var(N.dynamicAnchors, _`${N.valCxt}.${N.dynamicAnchors}`)
83 gen.var(N.instancePath, _`""`)
84 gen.var(N.parentData, _`undefined`)
85 gen.var(N.parentDataProperty, _`undefined`)
86 gen.var(N.rootData, N.data)
87 if (opts.dynamicRef) gen.var(N.dynamicAnchors, _`{}`)
92 function topSchemaObjCode(it: SchemaObjCxt): void {
93 const {schema, opts, gen} = it
94 validateFunction(it, () => {
95 if (opts.$comment && schema.$comment) commentKeyword(it)
97 gen.let(N.vErrors, null)
99 if (opts.unevaluated) resetEvaluated(it)
106 function resetEvaluated(it: SchemaObjCxt): void {
107 // TODO maybe some hook to execute it in the end to check whether props/items are Name, as in assignEvaluated
108 const {gen, validateName} = it
109 it.evaluated = gen.const("evaluated", _`${validateName}.evaluated`)
110 gen.if(_`${it.evaluated}.dynamicProps`, () => gen.assign(_`${it.evaluated}.props`, _`undefined`))
111 gen.if(_`${it.evaluated}.dynamicItems`, () => gen.assign(_`${it.evaluated}.items`, _`undefined`))
114 function funcSourceUrl(schema: AnySchema, opts: InstanceOptions): Code {
115 const schId = typeof schema == "object" && schema[opts.schemaId]
116 return schId && (opts.code.source || opts.code.process) ? _`/*# sourceURL=${schId} */` : nil
119 // schema compilation - this function is used recursively to generate code for sub-schemas
120 function subschemaCode(it: SchemaCxt, valid: Name): void {
121 if (isSchemaObj(it)) {
123 if (schemaCxtHasRules(it)) {
124 subSchemaObjCode(it, valid)
128 boolOrEmptySchema(it, valid)
131 function schemaCxtHasRules({schema, self}: SchemaCxt): boolean {
132 if (typeof schema == "boolean") return !schema
133 for (const key in schema) if (self.RULES.all[key]) return true
137 function isSchemaObj(it: SchemaCxt): it is SchemaObjCxt {
138 return typeof it.schema != "boolean"
141 function subSchemaObjCode(it: SchemaObjCxt, valid: Name): void {
142 const {schema, gen, opts} = it
143 if (opts.$comment && schema.$comment) commentKeyword(it)
146 const errsCount = gen.const("_errs", N.errors)
147 typeAndKeywords(it, errsCount)
149 gen.var(valid, _`${errsCount} === ${N.errors}`)
152 function checkKeywords(it: SchemaObjCxt): void {
153 checkUnknownRules(it)
154 checkRefsAndKeywords(it)
157 function typeAndKeywords(it: SchemaObjCxt, errsCount?: Name): void {
158 if (it.opts.jtd) return schemaKeywords(it, [], false, errsCount)
159 const types = getSchemaTypes(it.schema)
160 const checkedTypes = coerceAndCheckDataType(it, types)
161 schemaKeywords(it, types, !checkedTypes, errsCount)
164 function checkRefsAndKeywords(it: SchemaObjCxt): void {
165 const {schema, errSchemaPath, opts, self} = it
166 if (schema.$ref && opts.ignoreKeywordsWithRef && schemaHasRulesButRef(schema, self.RULES)) {
167 self.logger.warn(`$ref: keywords ignored in schema at path "${errSchemaPath}"`)
171 function checkNoDefault(it: SchemaObjCxt): void {
172 const {schema, opts} = it
173 if (schema.default !== undefined && opts.useDefaults && opts.strictSchema) {
174 checkStrictMode(it, "default is ignored in the schema root")
178 function updateContext(it: SchemaObjCxt): void {
179 const schId = it.schema[it.opts.schemaId]
180 if (schId) it.baseId = resolveUrl(it.baseId, schId)
183 function checkAsyncSchema(it: SchemaObjCxt): void {
184 if (it.schema.$async && !it.schemaEnv.$async) throw new Error("async schema in sync schema")
187 function commentKeyword({gen, schemaEnv, schema, errSchemaPath, opts}: SchemaObjCxt): void {
188 const msg = schema.$comment
189 if (opts.$comment === true) {
190 gen.code(_`${N.self}.logger.log(${msg})`)
191 } else if (typeof opts.$comment == "function") {
192 const schemaPath = str`${errSchemaPath}/$comment`
193 const rootName = gen.scopeValue("root", {ref: schemaEnv.root})
194 gen.code(_`${N.self}.opts.$comment(${msg}, ${schemaPath}, ${rootName}.schema)`)
198 function returnResults(it: SchemaCxt): void {
199 const {gen, schemaEnv, validateName, ValidationError, opts} = it
200 if (schemaEnv.$async) {
201 // TODO assign unevaluated
203 _`${N.errors} === 0`,
204 () => gen.return(N.data),
205 () => gen.throw(_`new ${ValidationError as Name}(${N.vErrors})`)
208 gen.assign(_`${validateName}.errors`, N.vErrors)
209 if (opts.unevaluated) assignEvaluated(it)
210 gen.return(_`${N.errors} === 0`)
214 function assignEvaluated({gen, evaluated, props, items}: SchemaCxt): void {
215 if (props instanceof Name) gen.assign(_`${evaluated}.props`, props)
216 if (items instanceof Name) gen.assign(_`${evaluated}.items`, items)
219 function schemaKeywords(
225 const {gen, schema, data, allErrors, opts, self} = it
227 if (schema.$ref && (opts.ignoreKeywordsWithRef || !schemaHasRulesButRef(schema, RULES))) {
228 gen.block(() => keywordCode(it, "$ref", (RULES.all.$ref as Rule).definition)) // TODO typecast
231 if (!opts.jtd) checkStrictTypes(it, types)
233 for (const group of RULES.rules) groupKeywords(group)
234 groupKeywords(RULES.post)
237 function groupKeywords(group: RuleGroup): void {
238 if (!shouldUseGroup(schema, group)) return
240 gen.if(checkDataType(group.type, data, opts.strictNumbers))
241 iterateKeywords(it, group)
242 if (types.length === 1 && types[0] === group.type && typeErrors) {
248 iterateKeywords(it, group)
250 // TODO make it "ok" call?
251 if (!allErrors) gen.if(_`${N.errors} === ${errsCount || 0}`)
255 function iterateKeywords(it: SchemaObjCxt, group: RuleGroup): void {
261 if (useDefaults) assignDefaults(it, group.type)
263 for (const rule of group.rules) {
264 if (shouldUseRule(schema, rule)) {
265 keywordCode(it, rule.keyword, rule.definition, group.type)
271 function checkStrictTypes(it: SchemaObjCxt, types: JSONType[]): void {
272 if (it.schemaEnv.meta || !it.opts.strictTypes) return
273 checkContextTypes(it, types)
274 if (!it.opts.allowUnionTypes) checkMultipleTypes(it, types)
275 checkKeywordTypes(it, it.dataTypes)
278 function checkContextTypes(it: SchemaObjCxt, types: JSONType[]): void {
279 if (!types.length) return
280 if (!it.dataTypes.length) {
284 types.forEach((t) => {
285 if (!includesType(it.dataTypes, t)) {
286 strictTypesError(it, `type "${t}" not allowed by context "${it.dataTypes.join(",")}"`)
289 it.dataTypes = it.dataTypes.filter((t) => includesType(types, t))
292 function checkMultipleTypes(it: SchemaObjCxt, ts: JSONType[]): void {
293 if (ts.length > 1 && !(ts.length === 2 && ts.includes("null"))) {
294 strictTypesError(it, "use allowUnionTypes to allow union type keyword")
298 function checkKeywordTypes(it: SchemaObjCxt, ts: JSONType[]): void {
299 const rules = it.self.RULES.all
300 for (const keyword in rules) {
301 const rule = rules[keyword]
302 if (typeof rule == "object" && shouldUseRule(it.schema, rule)) {
303 const {type} = rule.definition
304 if (type.length && !type.some((t) => hasApplicableType(ts, t))) {
305 strictTypesError(it, `missing type "${type.join(",")}" for keyword "${keyword}"`)
311 function hasApplicableType(schTs: JSONType[], kwdT: JSONType): boolean {
312 return schTs.includes(kwdT) || (kwdT === "number" && schTs.includes("integer"))
315 function includesType(ts: JSONType[], t: JSONType): boolean {
316 return ts.includes(t) || (t === "integer" && ts.includes("number"))
319 function strictTypesError(it: SchemaObjCxt, msg: string): void {
320 const schemaPath = it.schemaEnv.baseId + it.errSchemaPath
321 msg += ` at "${schemaPath}" (strictTypes)`
322 checkStrictMode(it, msg, it.opts.strictTypes)
325 export class KeywordCxt implements KeywordErrorCxt {
326 readonly gen: CodeGen
327 readonly allErrors?: boolean
328 readonly keyword: string
329 readonly data: Name // Name referencing the current level of the data instance
330 readonly $data?: string | false
331 schema: any // keyword value in the schema
332 readonly schemaValue: Code | number | boolean // Code reference to keyword schema value or primitive value
333 readonly schemaCode: Code | number | boolean // Code reference to resolved schema value (different if schema is $data)
334 readonly schemaType: JSONType[] // allowed type(s) of keyword value in the schema
335 readonly parentSchema: AnySchemaObject
336 readonly errsCount?: Name // Name reference to the number of validation errors collected before this keyword,
337 // requires option trackErrors in keyword definition
338 params: KeywordCxtParams // object to pass parameters to error messages from keyword code
339 readonly it: SchemaObjCxt // schema compilation context (schema is guaranteed to be an object, not boolean)
340 readonly def: AddedKeywordDefinition
342 constructor(it: SchemaObjCxt, def: AddedKeywordDefinition, keyword: string) {
343 validateKeywordUsage(it, def, keyword)
345 this.allErrors = it.allErrors
346 this.keyword = keyword
348 this.schema = it.schema[keyword]
349 this.$data = def.$data && it.opts.$data && this.schema && this.schema.$data
350 this.schemaValue = schemaRefOrVal(it, this.schema, keyword, this.$data)
351 this.schemaType = def.schemaType
352 this.parentSchema = it.schema
358 this.schemaCode = it.gen.const("vSchema", getData(this.$data, it))
360 this.schemaCode = this.schemaValue
361 if (!validSchemaType(this.schema, def.schemaType, def.allowUndefined)) {
362 throw new Error(`${keyword} value must be ${JSON.stringify(def.schemaType)}`)
366 if ("code" in def ? def.trackErrors : def.errors !== false) {
367 this.errsCount = it.gen.const("_errs", N.errors)
371 result(condition: Code, successAction?: () => void, failAction?: () => void): void {
372 this.failResult(not(condition), successAction, failAction)
375 failResult(condition: Code, successAction?: () => void, failAction?: () => void): void {
376 this.gen.if(condition)
377 if (failAction) failAction()
382 if (this.allErrors) this.gen.endIf()
384 if (this.allErrors) this.gen.endIf()
389 pass(condition: Code, failAction?: () => void): void {
390 this.failResult(not(condition), undefined, failAction)
393 fail(condition?: Code): void {
394 if (condition === undefined) {
396 if (!this.allErrors) this.gen.if(false) // this branch will be removed by gen.optimize
399 this.gen.if(condition)
401 if (this.allErrors) this.gen.endIf()
405 fail$data(condition: Code): void {
406 if (!this.$data) return this.fail(condition)
407 const {schemaCode} = this
408 this.fail(_`${schemaCode} !== undefined && (${or(this.invalid$data(), condition)})`)
411 error(append?: boolean, errorParams?: KeywordCxtParams, errorPaths?: ErrorPaths): void {
413 this.setParams(errorParams)
414 this._error(append, errorPaths)
418 this._error(append, errorPaths)
421 private _error(append?: boolean, errorPaths?: ErrorPaths): void {
422 ;(append ? reportExtraError : reportError)(this, this.def.error, errorPaths)
426 reportError(this, this.def.$dataError || keyword$DataError)
430 if (this.errsCount === undefined) throw new Error('add "trackErrors" to keyword definition')
431 resetErrorsCount(this.gen, this.errsCount)
434 ok(cond: Code | boolean): void {
435 if (!this.allErrors) this.gen.if(cond)
438 setParams(obj: KeywordCxtParams, assign?: true): void {
439 if (assign) Object.assign(this.params, obj)
440 else this.params = obj
443 block$data(valid: Name, codeBlock: () => void, $dataValid: Code = nil): void {
444 this.gen.block(() => {
445 this.check$data(valid, $dataValid)
450 check$data(valid: Name = nil, $dataValid: Code = nil): void {
451 if (!this.$data) return
452 const {gen, schemaCode, schemaType, def} = this
453 gen.if(or(_`${schemaCode} === undefined`, $dataValid))
454 if (valid !== nil) gen.assign(valid, true)
455 if (schemaType.length || def.validateSchema) {
456 gen.elseIf(this.invalid$data())
458 if (valid !== nil) gen.assign(valid, false)
463 invalid$data(): Code {
464 const {gen, schemaCode, schemaType, def, it} = this
465 return or(wrong$DataType(), invalid$DataSchema())
467 function wrong$DataType(): Code {
468 if (schemaType.length) {
469 /* istanbul ignore if */
470 if (!(schemaCode instanceof Name)) throw new Error("ajv implementation error")
471 const st = Array.isArray(schemaType) ? schemaType : [schemaType]
472 return _`${checkDataTypes(st, schemaCode, it.opts.strictNumbers, DataType.Wrong)}`
477 function invalid$DataSchema(): Code {
478 if (def.validateSchema) {
479 const validateSchemaRef = gen.scopeValue("validate$data", {ref: def.validateSchema}) // TODO value.code for standalone
480 return _`!${validateSchemaRef}(${schemaCode})`
486 subschema(appl: SubschemaArgs, valid: Name): SchemaCxt {
487 const subschema = getSubschema(this.it, appl)
488 extendSubschemaData(subschema, this.it, appl)
489 extendSubschemaMode(subschema, appl)
490 const nextContext = {...this.it, ...subschema, items: undefined, props: undefined}
491 subschemaCode(nextContext, valid)
495 mergeEvaluated(schemaCxt: SchemaCxt, toName?: typeof Name): void {
496 const {it, gen} = this
497 if (!it.opts.unevaluated) return
498 if (it.props !== true && schemaCxt.props !== undefined) {
499 it.props = mergeEvaluated.props(gen, schemaCxt.props, it.props, toName)
501 if (it.items !== true && schemaCxt.items !== undefined) {
502 it.items = mergeEvaluated.items(gen, schemaCxt.items, it.items, toName)
506 mergeValidEvaluated(schemaCxt: SchemaCxt, valid: Name): boolean | void {
507 const {it, gen} = this
508 if (it.opts.unevaluated && (it.props !== true || it.items !== true)) {
509 gen.if(valid, () => this.mergeEvaluated(schemaCxt, Name))
515 function keywordCode(
518 def: AddedKeywordDefinition,
521 const cxt = new KeywordCxt(it, def, keyword)
523 def.code(cxt, ruleType)
524 } else if (cxt.$data && def.validate) {
525 funcKeywordCode(cxt, def)
526 } else if ("macro" in def) {
527 macroKeywordCode(cxt, def)
528 } else if (def.compile || def.validate) {
529 funcKeywordCode(cxt, def)
533 const JSON_POINTER = /^\/(?:[^~]|~0|~1)*$/
534 const RELATIVE_JSON_POINTER = /^([0-9]+)(#|\/(?:[^~]|~0|~1)*)?$/
535 export function getData(
537 {dataLevel, dataNames, dataPathArr}: SchemaCxt
541 if ($data === "") return N.rootData
542 if ($data[0] === "/") {
543 if (!JSON_POINTER.test($data)) throw new Error(`Invalid JSON-pointer: ${$data}`)
547 const matches = RELATIVE_JSON_POINTER.exec($data)
548 if (!matches) throw new Error(`Invalid JSON-pointer: ${$data}`)
549 const up: number = +matches[1]
550 jsonPointer = matches[2]
551 if (jsonPointer === "#") {
552 if (up >= dataLevel) throw new Error(errorMsg("property/index", up))
553 return dataPathArr[dataLevel - up]
555 if (up > dataLevel) throw new Error(errorMsg("data", up))
556 data = dataNames[dataLevel - up]
557 if (!jsonPointer) return data
561 const segments = jsonPointer.split("/")
562 for (const segment of segments) {
564 data = _`${data}${getProperty(unescapeJsonPointer(segment))}`
565 expr = _`${expr} && ${data}`
570 function errorMsg(pointerType: string, up: number): string {
571 return `Cannot access ${pointerType} ${up} levels up, current level is ${dataLevel}`