unevaluatedProperties.ts 2.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  1. import type {
  2. CodeKeywordDefinition,
  3. KeywordErrorDefinition,
  4. ErrorObject,
  5. AnySchema,
  6. } from "../../types"
  7. import {_, not, and, Name, Code} from "../../compile/codegen"
  8. import {alwaysValidSchema, Type} from "../../compile/util"
  9. import N from "../../compile/names"
  10. export type UnevaluatedPropertiesError = ErrorObject<
  11. "unevaluatedProperties",
  12. {unevaluatedProperty: string},
  13. AnySchema
  14. >
  15. const error: KeywordErrorDefinition = {
  16. message: "must NOT have unevaluated properties",
  17. params: ({params}) => _`{unevaluatedProperty: ${params.unevaluatedProperty}}`,
  18. }
  19. const def: CodeKeywordDefinition = {
  20. keyword: "unevaluatedProperties",
  21. type: "object",
  22. schemaType: ["boolean", "object"],
  23. trackErrors: true,
  24. error,
  25. code(cxt) {
  26. const {gen, schema, data, errsCount, it} = cxt
  27. /* istanbul ignore if */
  28. if (!errsCount) throw new Error("ajv implementation error")
  29. const {allErrors, props} = it
  30. if (props instanceof Name) {
  31. gen.if(_`${props} !== true`, () =>
  32. gen.forIn("key", data, (key: Name) =>
  33. gen.if(unevaluatedDynamic(props, key), () => unevaluatedPropCode(key))
  34. )
  35. )
  36. } else if (props !== true) {
  37. gen.forIn("key", data, (key: Name) =>
  38. props === undefined
  39. ? unevaluatedPropCode(key)
  40. : gen.if(unevaluatedStatic(props, key), () => unevaluatedPropCode(key))
  41. )
  42. }
  43. it.props = true
  44. cxt.ok(_`${errsCount} === ${N.errors}`)
  45. function unevaluatedPropCode(key: Name): void {
  46. if (schema === false) {
  47. cxt.setParams({unevaluatedProperty: key})
  48. cxt.error()
  49. if (!allErrors) gen.break()
  50. return
  51. }
  52. if (!alwaysValidSchema(it, schema)) {
  53. const valid = gen.name("valid")
  54. cxt.subschema(
  55. {
  56. keyword: "unevaluatedProperties",
  57. dataProp: key,
  58. dataPropType: Type.Str,
  59. },
  60. valid
  61. )
  62. if (!allErrors) gen.if(not(valid), () => gen.break())
  63. }
  64. }
  65. function unevaluatedDynamic(evaluatedProps: Name, key: Name): Code {
  66. return _`!${evaluatedProps} || !${evaluatedProps}[${key}]`
  67. }
  68. function unevaluatedStatic(evaluatedProps: {[K in string]?: true}, key: Name): Code {
  69. const ps: Code[] = []
  70. for (const p in evaluatedProps) {
  71. if (evaluatedProps[p] === true) ps.push(_`${key} !== ${p}`)
  72. }
  73. return and(...ps)
  74. }
  75. },
  76. }
  77. export default def