unevaluatedItems.ts 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748
  1. import type {
  2. CodeKeywordDefinition,
  3. ErrorObject,
  4. KeywordErrorDefinition,
  5. AnySchema,
  6. } from "../../types"
  7. import type KeywordCxt from "../../compile/context"
  8. import {_, str, not, Name} from "../../compile/codegen"
  9. import {Type} from "../../compile/subschema"
  10. import {alwaysValidSchema} from "../../compile/util"
  11. export type UnevaluatedItemsError = ErrorObject<"unevaluatedItems", {limit: number}, AnySchema>
  12. const error: KeywordErrorDefinition = {
  13. message: ({params: {len}}) => str`should NOT have more than ${len} items`,
  14. params: ({params: {len}}) => _`{limit: ${len}}`,
  15. }
  16. const def: CodeKeywordDefinition = {
  17. keyword: "unevaluatedItems",
  18. type: "array",
  19. schemaType: ["boolean", "object"],
  20. error,
  21. code(cxt: KeywordCxt) {
  22. const {gen, schema, data, it} = cxt
  23. const items = it.items || 0
  24. if (items === true) return
  25. const len = gen.const("len", _`${data}.length`)
  26. if (schema === false) {
  27. cxt.setParams({len: items})
  28. cxt.fail(_`${len} > ${items}`)
  29. } else if (typeof schema == "object" && !alwaysValidSchema(it, schema)) {
  30. const valid = gen.var("valid", _`${len} <= ${items}`)
  31. gen.if(not(valid), () => validateItems(valid, items))
  32. cxt.ok(valid)
  33. }
  34. it.items = true
  35. function validateItems(valid: Name, from: Name | number): void {
  36. gen.forRange("i", from, len, (i) => {
  37. cxt.subschema({keyword: "unevaluatedItems", dataProp: i, dataPropType: Type.Num}, valid)
  38. if (!it.allErrors) gen.if(not(valid), () => gen.break())
  39. })
  40. }
  41. },
  42. }
  43. export default def