[79a0317] | 1 | import type {
|
---|
| 2 | AddedKeywordDefinition,
|
---|
| 3 | AnySchema,
|
---|
| 4 | AnySchemaObject,
|
---|
| 5 | KeywordErrorCxt,
|
---|
| 6 | KeywordCxtParams,
|
---|
| 7 | } from "../../types"
|
---|
| 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"
|
---|
| 20 | import {
|
---|
| 21 | schemaRefOrVal,
|
---|
| 22 | schemaHasRulesButRef,
|
---|
| 23 | checkUnknownRules,
|
---|
| 24 | checkStrictMode,
|
---|
| 25 | unescapeJsonPointer,
|
---|
| 26 | mergeEvaluated,
|
---|
| 27 | } from "../util"
|
---|
| 28 | import type {JSONType, Rule, RuleGroup} from "../rules"
|
---|
| 29 | import {
|
---|
| 30 | ErrorPaths,
|
---|
| 31 | reportError,
|
---|
| 32 | reportExtraError,
|
---|
| 33 | resetErrorsCount,
|
---|
| 34 | keyword$DataError,
|
---|
| 35 | } from "../errors"
|
---|
| 36 |
|
---|
| 37 | // schema compilation - generates validation function, subschemaCode (below) is used for subschemas
|
---|
| 38 | export function validateFunctionCode(it: SchemaCxt): void {
|
---|
| 39 | if (isSchemaObj(it)) {
|
---|
| 40 | checkKeywords(it)
|
---|
| 41 | if (schemaCxtHasRules(it)) {
|
---|
| 42 | topSchemaObjCode(it)
|
---|
| 43 | return
|
---|
| 44 | }
|
---|
| 45 | }
|
---|
| 46 | validateFunction(it, () => topBoolOrEmptySchema(it))
|
---|
| 47 | }
|
---|
| 48 |
|
---|
| 49 | function validateFunction(
|
---|
| 50 | {gen, validateName, schema, schemaEnv, opts}: SchemaCxt,
|
---|
| 51 | body: Block
|
---|
| 52 | ): void {
|
---|
| 53 | if (opts.code.es5) {
|
---|
| 54 | gen.func(validateName, _`${N.data}, ${N.valCxt}`, schemaEnv.$async, () => {
|
---|
| 55 | gen.code(_`"use strict"; ${funcSourceUrl(schema, opts)}`)
|
---|
| 56 | destructureValCxtES5(gen, opts)
|
---|
| 57 | gen.code(body)
|
---|
| 58 | })
|
---|
| 59 | } else {
|
---|
| 60 | gen.func(validateName, _`${N.data}, ${destructureValCxt(opts)}`, schemaEnv.$async, () =>
|
---|
| 61 | gen.code(funcSourceUrl(schema, opts)).code(body)
|
---|
| 62 | )
|
---|
| 63 | }
|
---|
| 64 | }
|
---|
| 65 |
|
---|
| 66 | function destructureValCxt(opts: InstanceOptions): Code {
|
---|
| 67 | return _`{${N.instancePath}="", ${N.parentData}, ${N.parentDataProperty}, ${N.rootData}=${
|
---|
| 68 | N.data
|
---|
| 69 | }${opts.dynamicRef ? _`, ${N.dynamicAnchors}={}` : nil}}={}`
|
---|
| 70 | }
|
---|
| 71 |
|
---|
| 72 | function destructureValCxtES5(gen: CodeGen, opts: InstanceOptions): void {
|
---|
| 73 | gen.if(
|
---|
| 74 | N.valCxt,
|
---|
| 75 | () => {
|
---|
| 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}`)
|
---|
| 81 | },
|
---|
| 82 | () => {
|
---|
| 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, _`{}`)
|
---|
| 88 | }
|
---|
| 89 | )
|
---|
| 90 | }
|
---|
| 91 |
|
---|
| 92 | function topSchemaObjCode(it: SchemaObjCxt): void {
|
---|
| 93 | const {schema, opts, gen} = it
|
---|
| 94 | validateFunction(it, () => {
|
---|
| 95 | if (opts.$comment && schema.$comment) commentKeyword(it)
|
---|
| 96 | checkNoDefault(it)
|
---|
| 97 | gen.let(N.vErrors, null)
|
---|
| 98 | gen.let(N.errors, 0)
|
---|
| 99 | if (opts.unevaluated) resetEvaluated(it)
|
---|
| 100 | typeAndKeywords(it)
|
---|
| 101 | returnResults(it)
|
---|
| 102 | })
|
---|
| 103 | return
|
---|
| 104 | }
|
---|
| 105 |
|
---|
| 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`))
|
---|
| 112 | }
|
---|
| 113 |
|
---|
| 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
|
---|
| 117 | }
|
---|
| 118 |
|
---|
| 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)) {
|
---|
| 122 | checkKeywords(it)
|
---|
| 123 | if (schemaCxtHasRules(it)) {
|
---|
| 124 | subSchemaObjCode(it, valid)
|
---|
| 125 | return
|
---|
| 126 | }
|
---|
| 127 | }
|
---|
| 128 | boolOrEmptySchema(it, valid)
|
---|
| 129 | }
|
---|
| 130 |
|
---|
| 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
|
---|
| 134 | return false
|
---|
| 135 | }
|
---|
| 136 |
|
---|
| 137 | function isSchemaObj(it: SchemaCxt): it is SchemaObjCxt {
|
---|
| 138 | return typeof it.schema != "boolean"
|
---|
| 139 | }
|
---|
| 140 |
|
---|
| 141 | function subSchemaObjCode(it: SchemaObjCxt, valid: Name): void {
|
---|
| 142 | const {schema, gen, opts} = it
|
---|
| 143 | if (opts.$comment && schema.$comment) commentKeyword(it)
|
---|
| 144 | updateContext(it)
|
---|
| 145 | checkAsyncSchema(it)
|
---|
| 146 | const errsCount = gen.const("_errs", N.errors)
|
---|
| 147 | typeAndKeywords(it, errsCount)
|
---|
| 148 | // TODO var
|
---|
| 149 | gen.var(valid, _`${errsCount} === ${N.errors}`)
|
---|
| 150 | }
|
---|
| 151 |
|
---|
| 152 | function checkKeywords(it: SchemaObjCxt): void {
|
---|
| 153 | checkUnknownRules(it)
|
---|
| 154 | checkRefsAndKeywords(it)
|
---|
| 155 | }
|
---|
| 156 |
|
---|
| 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)
|
---|
| 162 | }
|
---|
| 163 |
|
---|
| 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}"`)
|
---|
| 168 | }
|
---|
| 169 | }
|
---|
| 170 |
|
---|
| 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")
|
---|
| 175 | }
|
---|
| 176 | }
|
---|
| 177 |
|
---|
| 178 | function updateContext(it: SchemaObjCxt): void {
|
---|
| 179 | const schId = it.schema[it.opts.schemaId]
|
---|
| 180 | if (schId) it.baseId = resolveUrl(it.opts.uriResolver, it.baseId, schId)
|
---|
| 181 | }
|
---|
| 182 |
|
---|
| 183 | function checkAsyncSchema(it: SchemaObjCxt): void {
|
---|
| 184 | if (it.schema.$async && !it.schemaEnv.$async) throw new Error("async schema in sync schema")
|
---|
| 185 | }
|
---|
| 186 |
|
---|
| 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)`)
|
---|
| 195 | }
|
---|
| 196 | }
|
---|
| 197 |
|
---|
| 198 | function returnResults(it: SchemaCxt): void {
|
---|
| 199 | const {gen, schemaEnv, validateName, ValidationError, opts} = it
|
---|
| 200 | if (schemaEnv.$async) {
|
---|
| 201 | // TODO assign unevaluated
|
---|
| 202 | gen.if(
|
---|
| 203 | _`${N.errors} === 0`,
|
---|
| 204 | () => gen.return(N.data),
|
---|
| 205 | () => gen.throw(_`new ${ValidationError as Name}(${N.vErrors})`)
|
---|
| 206 | )
|
---|
| 207 | } else {
|
---|
| 208 | gen.assign(_`${validateName}.errors`, N.vErrors)
|
---|
| 209 | if (opts.unevaluated) assignEvaluated(it)
|
---|
| 210 | gen.return(_`${N.errors} === 0`)
|
---|
| 211 | }
|
---|
| 212 | }
|
---|
| 213 |
|
---|
| 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)
|
---|
| 217 | }
|
---|
| 218 |
|
---|
| 219 | function schemaKeywords(
|
---|
| 220 | it: SchemaObjCxt,
|
---|
| 221 | types: JSONType[],
|
---|
| 222 | typeErrors: boolean,
|
---|
| 223 | errsCount?: Name
|
---|
| 224 | ): void {
|
---|
| 225 | const {gen, schema, data, allErrors, opts, self} = it
|
---|
| 226 | const {RULES} = self
|
---|
| 227 | if (schema.$ref && (opts.ignoreKeywordsWithRef || !schemaHasRulesButRef(schema, RULES))) {
|
---|
| 228 | gen.block(() => keywordCode(it, "$ref", (RULES.all.$ref as Rule).definition)) // TODO typecast
|
---|
| 229 | return
|
---|
| 230 | }
|
---|
| 231 | if (!opts.jtd) checkStrictTypes(it, types)
|
---|
| 232 | gen.block(() => {
|
---|
| 233 | for (const group of RULES.rules) groupKeywords(group)
|
---|
| 234 | groupKeywords(RULES.post)
|
---|
| 235 | })
|
---|
| 236 |
|
---|
| 237 | function groupKeywords(group: RuleGroup): void {
|
---|
| 238 | if (!shouldUseGroup(schema, group)) return
|
---|
| 239 | if (group.type) {
|
---|
| 240 | gen.if(checkDataType(group.type, data, opts.strictNumbers))
|
---|
| 241 | iterateKeywords(it, group)
|
---|
| 242 | if (types.length === 1 && types[0] === group.type && typeErrors) {
|
---|
| 243 | gen.else()
|
---|
| 244 | reportTypeError(it)
|
---|
| 245 | }
|
---|
| 246 | gen.endIf()
|
---|
| 247 | } else {
|
---|
| 248 | iterateKeywords(it, group)
|
---|
| 249 | }
|
---|
| 250 | // TODO make it "ok" call?
|
---|
| 251 | if (!allErrors) gen.if(_`${N.errors} === ${errsCount || 0}`)
|
---|
| 252 | }
|
---|
| 253 | }
|
---|
| 254 |
|
---|
| 255 | function iterateKeywords(it: SchemaObjCxt, group: RuleGroup): void {
|
---|
| 256 | const {
|
---|
| 257 | gen,
|
---|
| 258 | schema,
|
---|
| 259 | opts: {useDefaults},
|
---|
| 260 | } = it
|
---|
| 261 | if (useDefaults) assignDefaults(it, group.type)
|
---|
| 262 | gen.block(() => {
|
---|
| 263 | for (const rule of group.rules) {
|
---|
| 264 | if (shouldUseRule(schema, rule)) {
|
---|
| 265 | keywordCode(it, rule.keyword, rule.definition, group.type)
|
---|
| 266 | }
|
---|
| 267 | }
|
---|
| 268 | })
|
---|
| 269 | }
|
---|
| 270 |
|
---|
| 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)
|
---|
| 276 | }
|
---|
| 277 |
|
---|
| 278 | function checkContextTypes(it: SchemaObjCxt, types: JSONType[]): void {
|
---|
| 279 | if (!types.length) return
|
---|
| 280 | if (!it.dataTypes.length) {
|
---|
| 281 | it.dataTypes = types
|
---|
| 282 | return
|
---|
| 283 | }
|
---|
| 284 | types.forEach((t) => {
|
---|
| 285 | if (!includesType(it.dataTypes, t)) {
|
---|
| 286 | strictTypesError(it, `type "${t}" not allowed by context "${it.dataTypes.join(",")}"`)
|
---|
| 287 | }
|
---|
| 288 | })
|
---|
| 289 | narrowSchemaTypes(it, types)
|
---|
| 290 | }
|
---|
| 291 |
|
---|
| 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")
|
---|
| 295 | }
|
---|
| 296 | }
|
---|
| 297 |
|
---|
| 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}"`)
|
---|
| 306 | }
|
---|
| 307 | }
|
---|
| 308 | }
|
---|
| 309 | }
|
---|
| 310 |
|
---|
| 311 | function hasApplicableType(schTs: JSONType[], kwdT: JSONType): boolean {
|
---|
| 312 | return schTs.includes(kwdT) || (kwdT === "number" && schTs.includes("integer"))
|
---|
| 313 | }
|
---|
| 314 |
|
---|
| 315 | function includesType(ts: JSONType[], t: JSONType): boolean {
|
---|
| 316 | return ts.includes(t) || (t === "integer" && ts.includes("number"))
|
---|
| 317 | }
|
---|
| 318 |
|
---|
| 319 | function narrowSchemaTypes(it: SchemaObjCxt, withTypes: JSONType[]): void {
|
---|
| 320 | const ts: JSONType[] = []
|
---|
| 321 | for (const t of it.dataTypes) {
|
---|
| 322 | if (includesType(withTypes, t)) ts.push(t)
|
---|
| 323 | else if (withTypes.includes("integer") && t === "number") ts.push("integer")
|
---|
| 324 | }
|
---|
| 325 | it.dataTypes = ts
|
---|
| 326 | }
|
---|
| 327 |
|
---|
| 328 | function strictTypesError(it: SchemaObjCxt, msg: string): void {
|
---|
| 329 | const schemaPath = it.schemaEnv.baseId + it.errSchemaPath
|
---|
| 330 | msg += ` at "${schemaPath}" (strictTypes)`
|
---|
| 331 | checkStrictMode(it, msg, it.opts.strictTypes)
|
---|
| 332 | }
|
---|
| 333 |
|
---|
| 334 | export class KeywordCxt implements KeywordErrorCxt {
|
---|
| 335 | readonly gen: CodeGen
|
---|
| 336 | readonly allErrors?: boolean
|
---|
| 337 | readonly keyword: string
|
---|
| 338 | readonly data: Name // Name referencing the current level of the data instance
|
---|
| 339 | readonly $data?: string | false
|
---|
| 340 | schema: any // keyword value in the schema
|
---|
| 341 | readonly schemaValue: Code | number | boolean // Code reference to keyword schema value or primitive value
|
---|
| 342 | readonly schemaCode: Code | number | boolean // Code reference to resolved schema value (different if schema is $data)
|
---|
| 343 | readonly schemaType: JSONType[] // allowed type(s) of keyword value in the schema
|
---|
| 344 | readonly parentSchema: AnySchemaObject
|
---|
| 345 | readonly errsCount?: Name // Name reference to the number of validation errors collected before this keyword,
|
---|
| 346 | // requires option trackErrors in keyword definition
|
---|
| 347 | params: KeywordCxtParams // object to pass parameters to error messages from keyword code
|
---|
| 348 | readonly it: SchemaObjCxt // schema compilation context (schema is guaranteed to be an object, not boolean)
|
---|
| 349 | readonly def: AddedKeywordDefinition
|
---|
| 350 |
|
---|
| 351 | constructor(it: SchemaObjCxt, def: AddedKeywordDefinition, keyword: string) {
|
---|
| 352 | validateKeywordUsage(it, def, keyword)
|
---|
| 353 | this.gen = it.gen
|
---|
| 354 | this.allErrors = it.allErrors
|
---|
| 355 | this.keyword = keyword
|
---|
| 356 | this.data = it.data
|
---|
| 357 | this.schema = it.schema[keyword]
|
---|
| 358 | this.$data = def.$data && it.opts.$data && this.schema && this.schema.$data
|
---|
| 359 | this.schemaValue = schemaRefOrVal(it, this.schema, keyword, this.$data)
|
---|
| 360 | this.schemaType = def.schemaType
|
---|
| 361 | this.parentSchema = it.schema
|
---|
| 362 | this.params = {}
|
---|
| 363 | this.it = it
|
---|
| 364 | this.def = def
|
---|
| 365 |
|
---|
| 366 | if (this.$data) {
|
---|
| 367 | this.schemaCode = it.gen.const("vSchema", getData(this.$data, it))
|
---|
| 368 | } else {
|
---|
| 369 | this.schemaCode = this.schemaValue
|
---|
| 370 | if (!validSchemaType(this.schema, def.schemaType, def.allowUndefined)) {
|
---|
| 371 | throw new Error(`${keyword} value must be ${JSON.stringify(def.schemaType)}`)
|
---|
| 372 | }
|
---|
| 373 | }
|
---|
| 374 |
|
---|
| 375 | if ("code" in def ? def.trackErrors : def.errors !== false) {
|
---|
| 376 | this.errsCount = it.gen.const("_errs", N.errors)
|
---|
| 377 | }
|
---|
| 378 | }
|
---|
| 379 |
|
---|
| 380 | result(condition: Code, successAction?: () => void, failAction?: () => void): void {
|
---|
| 381 | this.failResult(not(condition), successAction, failAction)
|
---|
| 382 | }
|
---|
| 383 |
|
---|
| 384 | failResult(condition: Code, successAction?: () => void, failAction?: () => void): void {
|
---|
| 385 | this.gen.if(condition)
|
---|
| 386 | if (failAction) failAction()
|
---|
| 387 | else this.error()
|
---|
| 388 | if (successAction) {
|
---|
| 389 | this.gen.else()
|
---|
| 390 | successAction()
|
---|
| 391 | if (this.allErrors) this.gen.endIf()
|
---|
| 392 | } else {
|
---|
| 393 | if (this.allErrors) this.gen.endIf()
|
---|
| 394 | else this.gen.else()
|
---|
| 395 | }
|
---|
| 396 | }
|
---|
| 397 |
|
---|
| 398 | pass(condition: Code, failAction?: () => void): void {
|
---|
| 399 | this.failResult(not(condition), undefined, failAction)
|
---|
| 400 | }
|
---|
| 401 |
|
---|
| 402 | fail(condition?: Code): void {
|
---|
| 403 | if (condition === undefined) {
|
---|
| 404 | this.error()
|
---|
| 405 | if (!this.allErrors) this.gen.if(false) // this branch will be removed by gen.optimize
|
---|
| 406 | return
|
---|
| 407 | }
|
---|
| 408 | this.gen.if(condition)
|
---|
| 409 | this.error()
|
---|
| 410 | if (this.allErrors) this.gen.endIf()
|
---|
| 411 | else this.gen.else()
|
---|
| 412 | }
|
---|
| 413 |
|
---|
| 414 | fail$data(condition: Code): void {
|
---|
| 415 | if (!this.$data) return this.fail(condition)
|
---|
| 416 | const {schemaCode} = this
|
---|
| 417 | this.fail(_`${schemaCode} !== undefined && (${or(this.invalid$data(), condition)})`)
|
---|
| 418 | }
|
---|
| 419 |
|
---|
| 420 | error(append?: boolean, errorParams?: KeywordCxtParams, errorPaths?: ErrorPaths): void {
|
---|
| 421 | if (errorParams) {
|
---|
| 422 | this.setParams(errorParams)
|
---|
| 423 | this._error(append, errorPaths)
|
---|
| 424 | this.setParams({})
|
---|
| 425 | return
|
---|
| 426 | }
|
---|
| 427 | this._error(append, errorPaths)
|
---|
| 428 | }
|
---|
| 429 |
|
---|
| 430 | private _error(append?: boolean, errorPaths?: ErrorPaths): void {
|
---|
| 431 | ;(append ? reportExtraError : reportError)(this, this.def.error, errorPaths)
|
---|
| 432 | }
|
---|
| 433 |
|
---|
| 434 | $dataError(): void {
|
---|
| 435 | reportError(this, this.def.$dataError || keyword$DataError)
|
---|
| 436 | }
|
---|
| 437 |
|
---|
| 438 | reset(): void {
|
---|
| 439 | if (this.errsCount === undefined) throw new Error('add "trackErrors" to keyword definition')
|
---|
| 440 | resetErrorsCount(this.gen, this.errsCount)
|
---|
| 441 | }
|
---|
| 442 |
|
---|
| 443 | ok(cond: Code | boolean): void {
|
---|
| 444 | if (!this.allErrors) this.gen.if(cond)
|
---|
| 445 | }
|
---|
| 446 |
|
---|
| 447 | setParams(obj: KeywordCxtParams, assign?: true): void {
|
---|
| 448 | if (assign) Object.assign(this.params, obj)
|
---|
| 449 | else this.params = obj
|
---|
| 450 | }
|
---|
| 451 |
|
---|
| 452 | block$data(valid: Name, codeBlock: () => void, $dataValid: Code = nil): void {
|
---|
| 453 | this.gen.block(() => {
|
---|
| 454 | this.check$data(valid, $dataValid)
|
---|
| 455 | codeBlock()
|
---|
| 456 | })
|
---|
| 457 | }
|
---|
| 458 |
|
---|
| 459 | check$data(valid: Name = nil, $dataValid: Code = nil): void {
|
---|
| 460 | if (!this.$data) return
|
---|
| 461 | const {gen, schemaCode, schemaType, def} = this
|
---|
| 462 | gen.if(or(_`${schemaCode} === undefined`, $dataValid))
|
---|
| 463 | if (valid !== nil) gen.assign(valid, true)
|
---|
| 464 | if (schemaType.length || def.validateSchema) {
|
---|
| 465 | gen.elseIf(this.invalid$data())
|
---|
| 466 | this.$dataError()
|
---|
| 467 | if (valid !== nil) gen.assign(valid, false)
|
---|
| 468 | }
|
---|
| 469 | gen.else()
|
---|
| 470 | }
|
---|
| 471 |
|
---|
| 472 | invalid$data(): Code {
|
---|
| 473 | const {gen, schemaCode, schemaType, def, it} = this
|
---|
| 474 | return or(wrong$DataType(), invalid$DataSchema())
|
---|
| 475 |
|
---|
| 476 | function wrong$DataType(): Code {
|
---|
| 477 | if (schemaType.length) {
|
---|
| 478 | /* istanbul ignore if */
|
---|
| 479 | if (!(schemaCode instanceof Name)) throw new Error("ajv implementation error")
|
---|
| 480 | const st = Array.isArray(schemaType) ? schemaType : [schemaType]
|
---|
| 481 | return _`${checkDataTypes(st, schemaCode, it.opts.strictNumbers, DataType.Wrong)}`
|
---|
| 482 | }
|
---|
| 483 | return nil
|
---|
| 484 | }
|
---|
| 485 |
|
---|
| 486 | function invalid$DataSchema(): Code {
|
---|
| 487 | if (def.validateSchema) {
|
---|
| 488 | const validateSchemaRef = gen.scopeValue("validate$data", {ref: def.validateSchema}) // TODO value.code for standalone
|
---|
| 489 | return _`!${validateSchemaRef}(${schemaCode})`
|
---|
| 490 | }
|
---|
| 491 | return nil
|
---|
| 492 | }
|
---|
| 493 | }
|
---|
| 494 |
|
---|
| 495 | subschema(appl: SubschemaArgs, valid: Name): SchemaCxt {
|
---|
| 496 | const subschema = getSubschema(this.it, appl)
|
---|
| 497 | extendSubschemaData(subschema, this.it, appl)
|
---|
| 498 | extendSubschemaMode(subschema, appl)
|
---|
| 499 | const nextContext = {...this.it, ...subschema, items: undefined, props: undefined}
|
---|
| 500 | subschemaCode(nextContext, valid)
|
---|
| 501 | return nextContext
|
---|
| 502 | }
|
---|
| 503 |
|
---|
| 504 | mergeEvaluated(schemaCxt: SchemaCxt, toName?: typeof Name): void {
|
---|
| 505 | const {it, gen} = this
|
---|
| 506 | if (!it.opts.unevaluated) return
|
---|
| 507 | if (it.props !== true && schemaCxt.props !== undefined) {
|
---|
| 508 | it.props = mergeEvaluated.props(gen, schemaCxt.props, it.props, toName)
|
---|
| 509 | }
|
---|
| 510 | if (it.items !== true && schemaCxt.items !== undefined) {
|
---|
| 511 | it.items = mergeEvaluated.items(gen, schemaCxt.items, it.items, toName)
|
---|
| 512 | }
|
---|
| 513 | }
|
---|
| 514 |
|
---|
| 515 | mergeValidEvaluated(schemaCxt: SchemaCxt, valid: Name): boolean | void {
|
---|
| 516 | const {it, gen} = this
|
---|
| 517 | if (it.opts.unevaluated && (it.props !== true || it.items !== true)) {
|
---|
| 518 | gen.if(valid, () => this.mergeEvaluated(schemaCxt, Name))
|
---|
| 519 | return true
|
---|
| 520 | }
|
---|
| 521 | }
|
---|
| 522 | }
|
---|
| 523 |
|
---|
| 524 | function keywordCode(
|
---|
| 525 | it: SchemaObjCxt,
|
---|
| 526 | keyword: string,
|
---|
| 527 | def: AddedKeywordDefinition,
|
---|
| 528 | ruleType?: JSONType
|
---|
| 529 | ): void {
|
---|
| 530 | const cxt = new KeywordCxt(it, def, keyword)
|
---|
| 531 | if ("code" in def) {
|
---|
| 532 | def.code(cxt, ruleType)
|
---|
| 533 | } else if (cxt.$data && def.validate) {
|
---|
| 534 | funcKeywordCode(cxt, def)
|
---|
| 535 | } else if ("macro" in def) {
|
---|
| 536 | macroKeywordCode(cxt, def)
|
---|
| 537 | } else if (def.compile || def.validate) {
|
---|
| 538 | funcKeywordCode(cxt, def)
|
---|
| 539 | }
|
---|
| 540 | }
|
---|
| 541 |
|
---|
| 542 | const JSON_POINTER = /^\/(?:[^~]|~0|~1)*$/
|
---|
| 543 | const RELATIVE_JSON_POINTER = /^([0-9]+)(#|\/(?:[^~]|~0|~1)*)?$/
|
---|
| 544 | export function getData(
|
---|
| 545 | $data: string,
|
---|
| 546 | {dataLevel, dataNames, dataPathArr}: SchemaCxt
|
---|
| 547 | ): Code | number {
|
---|
| 548 | let jsonPointer
|
---|
| 549 | let data: Code
|
---|
| 550 | if ($data === "") return N.rootData
|
---|
| 551 | if ($data[0] === "/") {
|
---|
| 552 | if (!JSON_POINTER.test($data)) throw new Error(`Invalid JSON-pointer: ${$data}`)
|
---|
| 553 | jsonPointer = $data
|
---|
| 554 | data = N.rootData
|
---|
| 555 | } else {
|
---|
| 556 | const matches = RELATIVE_JSON_POINTER.exec($data)
|
---|
| 557 | if (!matches) throw new Error(`Invalid JSON-pointer: ${$data}`)
|
---|
| 558 | const up: number = +matches[1]
|
---|
| 559 | jsonPointer = matches[2]
|
---|
| 560 | if (jsonPointer === "#") {
|
---|
| 561 | if (up >= dataLevel) throw new Error(errorMsg("property/index", up))
|
---|
| 562 | return dataPathArr[dataLevel - up]
|
---|
| 563 | }
|
---|
| 564 | if (up > dataLevel) throw new Error(errorMsg("data", up))
|
---|
| 565 | data = dataNames[dataLevel - up]
|
---|
| 566 | if (!jsonPointer) return data
|
---|
| 567 | }
|
---|
| 568 |
|
---|
| 569 | let expr = data
|
---|
| 570 | const segments = jsonPointer.split("/")
|
---|
| 571 | for (const segment of segments) {
|
---|
| 572 | if (segment) {
|
---|
| 573 | data = _`${data}${getProperty(unescapeJsonPointer(segment))}`
|
---|
| 574 | expr = _`${expr} && ${data}`
|
---|
| 575 | }
|
---|
| 576 | }
|
---|
| 577 | return expr
|
---|
| 578 |
|
---|
| 579 | function errorMsg(pointerType: string, up: number): string {
|
---|
| 580 | return `Cannot access ${pointerType} ${up} levels up, current level is ${dataLevel}`
|
---|
| 581 | }
|
---|
| 582 | }
|
---|