propertyNames.ts 1.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051
  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} from "../../compile/codegen"
  9. import {alwaysValidSchema} from "../../compile/util"
  10. export type PropertyNamesError = ErrorObject<"propertyNames", {propertyName: string}, AnySchema>
  11. const error: KeywordErrorDefinition = {
  12. message: ({params}) => str`property name '${params.propertyName}' is invalid`, // TODO double quotes?
  13. params: ({params}) => _`{propertyName: ${params.propertyName}}`,
  14. }
  15. const def: CodeKeywordDefinition = {
  16. keyword: "propertyNames",
  17. type: "object",
  18. schemaType: ["object", "boolean"],
  19. error,
  20. code(cxt: KeywordCxt) {
  21. const {gen, schema, data, it} = cxt
  22. if (alwaysValidSchema(it, schema)) return
  23. const valid = gen.name("valid")
  24. gen.forIn("key", data, (key) => {
  25. cxt.setParams({propertyName: key})
  26. cxt.subschema(
  27. {
  28. keyword: "propertyNames",
  29. data: key,
  30. dataTypes: ["string"],
  31. propertyName: key,
  32. compositeRule: true,
  33. strictSchema: it.strictSchema,
  34. },
  35. valid
  36. )
  37. gen.if(not(valid), () => {
  38. cxt.error(true)
  39. if (!it.allErrors) gen.break()
  40. })
  41. })
  42. cxt.ok(valid)
  43. },
  44. }
  45. export default def