rules.ts 1.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950
  1. import type {AddedKeywordDefinition} from "../types"
  2. const _jsonTypes = ["string", "number", "integer", "boolean", "null", "object", "array"] as const
  3. export type JSONType = (typeof _jsonTypes)[number]
  4. const jsonTypes: Set<string> = new Set(_jsonTypes)
  5. export function isJSONType(x: unknown): x is JSONType {
  6. return typeof x == "string" && jsonTypes.has(x)
  7. }
  8. type ValidationTypes = {
  9. [K in JSONType]: boolean | RuleGroup | undefined
  10. }
  11. export interface ValidationRules {
  12. rules: RuleGroup[]
  13. post: RuleGroup
  14. all: {[Key in string]?: boolean | Rule} // rules that have to be validated
  15. keywords: {[Key in string]?: boolean} // all known keywords (superset of "all")
  16. types: ValidationTypes
  17. }
  18. export interface RuleGroup {
  19. type?: JSONType
  20. rules: Rule[]
  21. }
  22. // This interface wraps KeywordDefinition because definition can have multiple keywords
  23. export interface Rule {
  24. keyword: string
  25. definition: AddedKeywordDefinition
  26. }
  27. export function getRules(): ValidationRules {
  28. const groups: Record<"number" | "string" | "array" | "object", RuleGroup> = {
  29. number: {type: "number", rules: []},
  30. string: {type: "string", rules: []},
  31. array: {type: "array", rules: []},
  32. object: {type: "object", rules: []},
  33. }
  34. return {
  35. types: {...groups, integer: true, boolean: true, null: true},
  36. rules: [{rules: []}, groups.number, groups.string, groups.array, groups.object],
  37. post: {rules: []},
  38. all: {},
  39. keywords: {},
  40. }
  41. }