index.ts 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302
  1. import type {
  2. AnySchema,
  3. AnySchemaObject,
  4. AnyValidateFunction,
  5. AsyncValidateFunction,
  6. EvaluatedProperties,
  7. EvaluatedItems,
  8. } from "../types"
  9. import type Ajv from "../core"
  10. import type {InstanceOptions} from "../core"
  11. import {CodeGen, _, nil, stringify, Name, Code, ValueScopeName} from "./codegen"
  12. import {ValidationError} from "./error_classes"
  13. import N from "./names"
  14. import {LocalRefs, getFullPath, _getFullPath, inlineRef, normalizeId, resolveUrl} from "./resolve"
  15. import {schemaHasRulesButRef, unescapeFragment} from "./util"
  16. import {validateFunctionCode} from "./validate"
  17. import URI = require("uri-js")
  18. import {JSONType} from "./rules"
  19. export type SchemaRefs = {
  20. [Ref in string]?: SchemaEnv | AnySchema
  21. }
  22. export interface SchemaCxt {
  23. readonly gen: CodeGen
  24. readonly allErrors?: boolean // validation mode - whether to collect all errors or break on error
  25. readonly data: Name // Name with reference to the current part of data instance
  26. readonly parentData: Name // should be used in keywords modifying data
  27. readonly parentDataProperty: Code | number // should be used in keywords modifying data
  28. readonly dataNames: Name[]
  29. readonly dataPathArr: (Code | number)[]
  30. readonly dataLevel: number // the level of the currently validated data,
  31. // it can be used to access both the property names and the data on all levels from the top.
  32. dataTypes: JSONType[] // data types applied to the current part of data instance
  33. readonly topSchemaRef: Code
  34. readonly validateName: Name
  35. evaluated?: Name
  36. readonly ValidationError?: Name
  37. readonly schema: AnySchema // current schema object - equal to parentSchema passed via KeywordCxt
  38. readonly schemaEnv: SchemaEnv
  39. readonly strictSchema?: boolean
  40. readonly rootId: string
  41. baseId: string // the current schema base URI that should be used as the base for resolving URIs in references (\$ref)
  42. readonly schemaPath: Code // the run-time expression that evaluates to the property name of the current schema
  43. readonly errSchemaPath: string // this is actual string, should not be changed to Code
  44. readonly errorPath: Code
  45. readonly propertyName?: Name
  46. readonly compositeRule?: boolean // true indicates that the current schema is inside the compound keyword,
  47. // where failing some rule doesn't mean validation failure (`anyOf`, `oneOf`, `not`, `if`).
  48. // This flag is used to determine whether you can return validation result immediately after any error in case the option `allErrors` is not `true.
  49. // You only need to use it if you have many steps in your keywords and potentially can define multiple errors.
  50. props?: EvaluatedProperties | Name // properties evaluated by this schema - used by parent schema or assigned to validation function
  51. items?: EvaluatedItems | Name // last item evaluated by this schema - used by parent schema or assigned to validation function
  52. readonly createErrors?: boolean
  53. readonly opts: InstanceOptions // Ajv instance option.
  54. readonly self: Ajv // current Ajv instance
  55. }
  56. export interface SchemaObjCxt extends SchemaCxt {
  57. readonly schema: AnySchemaObject
  58. }
  59. interface SchemaEnvArgs {
  60. readonly schema: AnySchema
  61. readonly root?: SchemaEnv
  62. readonly baseId?: string
  63. readonly localRefs?: LocalRefs
  64. readonly meta?: boolean
  65. }
  66. export class SchemaEnv implements SchemaEnvArgs {
  67. readonly schema: AnySchema
  68. readonly root: SchemaEnv
  69. baseId: string // TODO possibly, it should be readonly
  70. localRefs?: LocalRefs
  71. readonly meta?: boolean
  72. readonly $async?: boolean // true if the current schema is asynchronous.
  73. readonly refs: SchemaRefs = {}
  74. readonly dynamicAnchors: {[Ref in string]?: true} = {}
  75. validate?: AnyValidateFunction
  76. validateName?: ValueScopeName
  77. constructor(env: SchemaEnvArgs) {
  78. let schema: AnySchemaObject | undefined
  79. if (typeof env.schema == "object") schema = env.schema
  80. this.schema = env.schema
  81. this.root = env.root || this
  82. this.baseId = env.baseId ?? normalizeId(schema?.$id)
  83. this.localRefs = env.localRefs
  84. this.meta = env.meta
  85. this.$async = schema?.$async
  86. this.refs = {}
  87. }
  88. }
  89. // let codeSize = 0
  90. // let nodeCount = 0
  91. // Compiles schema in SchemaEnv
  92. export function compileSchema(this: Ajv, sch: SchemaEnv): SchemaEnv {
  93. // TODO refactor - remove compilations
  94. const _sch = getCompilingSchema.call(this, sch)
  95. if (_sch) return _sch
  96. const rootId = getFullPath(sch.root.baseId) // TODO if getFullPath removed 1 tests fails
  97. const {es5, lines} = this.opts.code
  98. const {ownProperties} = this.opts
  99. const gen = new CodeGen(this.scope, {es5, lines, ownProperties})
  100. let _ValidationError
  101. if (sch.$async) {
  102. _ValidationError = gen.scopeValue("Error", {
  103. ref: ValidationError,
  104. code: _`require("ajv/dist/compile/error_classes").ValidationError`,
  105. })
  106. }
  107. const validateName = gen.scopeName("validate")
  108. sch.validateName = validateName
  109. const schemaCxt: SchemaCxt = {
  110. gen,
  111. allErrors: this.opts.allErrors,
  112. data: N.data,
  113. parentData: N.parentData,
  114. parentDataProperty: N.parentDataProperty,
  115. dataNames: [N.data],
  116. dataPathArr: [nil], // TODO can its length be used as dataLevel if nil is removed?
  117. dataLevel: 0,
  118. dataTypes: [],
  119. topSchemaRef: gen.scopeValue(
  120. "schema",
  121. this.opts.code.source === true
  122. ? {ref: sch.schema, code: stringify(sch.schema)}
  123. : {ref: sch.schema}
  124. ),
  125. validateName,
  126. ValidationError: _ValidationError,
  127. schema: sch.schema,
  128. schemaEnv: sch,
  129. strictSchema: true,
  130. rootId,
  131. baseId: sch.baseId || rootId,
  132. schemaPath: nil,
  133. errSchemaPath: "#",
  134. errorPath: _`""`,
  135. opts: this.opts,
  136. self: this,
  137. }
  138. let sourceCode: string | undefined
  139. try {
  140. this._compilations.add(sch)
  141. validateFunctionCode(schemaCxt)
  142. gen.optimize(this.opts.code.optimize)
  143. // gen.optimize(1)
  144. const validateCode = gen.toString()
  145. sourceCode = `${gen.scopeRefs(N.scope)}return ${validateCode}`
  146. // console.log((codeSize += sourceCode.length), (nodeCount += gen.nodeCount))
  147. if (this.opts.code.process) sourceCode = this.opts.code.process(sourceCode, sch)
  148. // console.log("\n\n\n *** \n", sourceCode)
  149. const makeValidate = new Function(`${N.self}`, `${N.scope}`, sourceCode)
  150. const validate: AnyValidateFunction = makeValidate(this, this.scope.get())
  151. this.scope.value(validateName, {ref: validate})
  152. validate.errors = null
  153. validate.schema = sch.schema
  154. validate.schemaEnv = sch
  155. if (sch.$async) (validate as AsyncValidateFunction).$async = true
  156. if (this.opts.code.source === true) {
  157. validate.source = {validateName, validateCode, scopeValues: gen._values}
  158. }
  159. if (this.opts.unevaluated) {
  160. const {props, items} = schemaCxt
  161. validate.evaluated = {
  162. props: props instanceof Name ? undefined : props,
  163. items: items instanceof Name ? undefined : items,
  164. dynamicProps: props instanceof Name,
  165. dynamicItems: items instanceof Name,
  166. }
  167. if (validate.source) validate.source.evaluated = stringify(validate.evaluated)
  168. }
  169. sch.validate = validate
  170. return sch
  171. } catch (e) {
  172. delete sch.validate
  173. delete sch.validateName
  174. if (sourceCode) this.logger.error("Error compiling schema, function code:", sourceCode)
  175. // console.log("\n\n\n *** \n", sourceCode, this.opts)
  176. throw e
  177. } finally {
  178. this._compilations.delete(sch)
  179. }
  180. }
  181. export function resolveRef(
  182. this: Ajv,
  183. root: SchemaEnv,
  184. baseId: string,
  185. ref: string
  186. ): AnySchema | SchemaEnv | undefined {
  187. ref = resolveUrl(baseId, ref)
  188. const schOrFunc = root.refs[ref]
  189. if (schOrFunc) return schOrFunc
  190. let _sch = resolve.call(this, root, ref)
  191. if (_sch === undefined) {
  192. const schema = root.localRefs?.[ref] // TODO maybe localRefs should hold SchemaEnv
  193. if (schema) _sch = new SchemaEnv({schema, root, baseId})
  194. }
  195. if (_sch === undefined) return
  196. return (root.refs[ref] = inlineOrCompile.call(this, _sch))
  197. }
  198. function inlineOrCompile(this: Ajv, sch: SchemaEnv): AnySchema | SchemaEnv {
  199. if (inlineRef(sch.schema, this.opts.inlineRefs)) return sch.schema
  200. return sch.validate ? sch : compileSchema.call(this, sch)
  201. }
  202. // Index of schema compilation in the currently compiled list
  203. function getCompilingSchema(this: Ajv, schEnv: SchemaEnv): SchemaEnv | void {
  204. for (const sch of this._compilations) {
  205. if (sameSchemaEnv(sch, schEnv)) return sch
  206. }
  207. }
  208. function sameSchemaEnv(s1: SchemaEnv, s2: SchemaEnv): boolean {
  209. return s1.schema === s2.schema && s1.root === s2.root && s1.baseId === s2.baseId
  210. }
  211. // resolve and compile the references ($ref)
  212. // TODO returns AnySchemaObject (if the schema can be inlined) or validation function
  213. function resolve(
  214. this: Ajv,
  215. root: SchemaEnv, // information about the root schema for the current schema
  216. ref: string // reference to resolve
  217. ): SchemaEnv | undefined {
  218. let sch
  219. while (typeof (sch = this.refs[ref]) == "string") ref = sch
  220. return sch || this.schemas[ref] || resolveSchema.call(this, root, ref)
  221. }
  222. // Resolve schema, its root and baseId
  223. export function resolveSchema(
  224. this: Ajv,
  225. root: SchemaEnv, // root object with properties schema, refs TODO below SchemaEnv is assigned to it
  226. ref: string // reference to resolve
  227. ): SchemaEnv | undefined {
  228. const p = URI.parse(ref)
  229. const refPath = _getFullPath(p)
  230. const baseId = getFullPath(root.baseId)
  231. // TODO `Object.keys(root.schema).length > 0` should not be needed - but removing breaks 2 tests
  232. if (Object.keys(root.schema).length > 0 && refPath === baseId) {
  233. return getJsonPointer.call(this, p, root)
  234. }
  235. const id = normalizeId(refPath)
  236. const schOrRef = this.refs[id] || this.schemas[id]
  237. if (typeof schOrRef == "string") {
  238. const sch = resolveSchema.call(this, root, schOrRef)
  239. if (typeof sch?.schema !== "object") return
  240. return getJsonPointer.call(this, p, sch)
  241. }
  242. if (typeof schOrRef?.schema !== "object") return
  243. if (!schOrRef.validate) compileSchema.call(this, schOrRef)
  244. if (id === normalizeId(ref)) return new SchemaEnv({schema: schOrRef.schema, root, baseId})
  245. return getJsonPointer.call(this, p, schOrRef)
  246. }
  247. const PREVENT_SCOPE_CHANGE = new Set([
  248. "properties",
  249. "patternProperties",
  250. "enum",
  251. "dependencies",
  252. "definitions",
  253. ])
  254. function getJsonPointer(
  255. this: Ajv,
  256. parsedRef: URI.URIComponents,
  257. {baseId, schema, root}: SchemaEnv
  258. ): SchemaEnv | undefined {
  259. if (parsedRef.fragment?.[0] !== "/") return
  260. for (const part of parsedRef.fragment.slice(1).split("/")) {
  261. if (typeof schema == "boolean") return
  262. schema = schema[unescapeFragment(part)]
  263. if (schema === undefined) return
  264. // TODO PREVENT_SCOPE_CHANGE could be defined in keyword def?
  265. if (!PREVENT_SCOPE_CHANGE.has(part) && typeof schema == "object" && schema.$id) {
  266. baseId = resolveUrl(baseId, schema.$id)
  267. }
  268. }
  269. let env: SchemaEnv | undefined
  270. if (typeof schema != "boolean" && schema.$ref && !schemaHasRulesButRef(schema, this.RULES)) {
  271. const $ref = resolveUrl(baseId, schema.$ref)
  272. env = resolveSchema.call(this, root, $ref)
  273. }
  274. // even though resolution failed we need to return SchemaEnv to throw exception
  275. // so that compileAsync loads missing schema.
  276. env = env || new SchemaEnv({schema, root, baseId})
  277. if (env.schema !== env.root.schema) return env
  278. return undefined
  279. }