unevaluatedItems.ts 1.5 KB

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