code:
import type {
  KeywordErrorDefinition,
  KeywordErrorCxt,
  ErrorObject,
  AnySchemaObject,
} from "../../types"
import type {SchemaObjCxt} from ".."
import {isJSONType, JSONType} from "../rules"
import {schemaHasRulesForType} from "./applicability"
import {reportError} from "../errors"
import {_, nil, and, not, operators, Code, Name} from "../codegen"
import {toHash, schemaRefOrVal} from "../util"

export enum DataType {
  Correct,
  Wrong,
}

export function getSchemaTypes(schema: AnySchemaObject): JSONType[] {
  const types = getJSONTypes(schema.type)
  const hasNull = types.includes("null")
  if (hasNull) {
    if (schema.nullable === false) throw new Error("type: null contradicts nullable: false")
  } else {
    if (!types.length && schema.nullable !== undefined) {
      throw new Error('"nullable" cannot be used without "type"')
    }
    if (schema.nullable === true) types.push("null")
  }
  return types
}

// eslint-disable-next-line @typescript-eslint/no-redundant-type-constituents
export function getJSONTypes(ts: unknown | unknown[]): JSONType[] {
  const types: unknown[] = Array.isArray(ts) ? ts : ts ? [ts] : []
  if (types.every(isJSONType)) return types
  throw new Error("type must be JSONType or JSONType[]: " + types.join(","))
}

export function coerceAndCheckDataType(it: SchemaObjCxt, types: JSONType[]): boolean {
  const {gen, data, opts} = it
  const coerceTo = coerceToTypes(types, opts.coerceTypes)
  const checkTypes =
    types.length > 0 &&
    !(coerceTo.length === 0 && types.length === 1 && schemaHasRulesForType(it, types[0]))
  if (checkTypes) {
    const wrongType = checkDataTypes(types, data, opts.strictNumbers, DataType.Wrong)
    gen.if(wrongType, () => {
      if (coerceTo.length) coerceData(it, types, coerceTo)
      else reportTypeError(it)
    })
  }
  return checkTypes
}

const COERCIBLE: Set<JSONType> = new Set(["string", "number", "integer", "boolean", "null"])
function coerceToTypes(types: JSONType[], coerceTypes?: boolean | "array"): JSONType[] {
  return coerceTypes
    ? types.filter((t) => COERCIBLE.has(t) || (coerceTypes === "array" && t === "array"))
    : []
}

function coerceData(it: SchemaObjCxt, types: JSONType[], coerceTo: JSONType[]): void {
  const {gen, data, opts} = it
  const dataType = gen.let("dataType", _`typeof ${data}`)
  const coerced = gen.let("coerced", _`undefined`)
  if (opts.coerceTypes === "array") {
    gen.if(_`${dataType} == 'object' && Array.isArray(${data}) && ${data}.length == 1`, () =>
      gen
        .assign(data, _`${data}[0]`)
        .assign(dataType, _`typeof ${data}`)
        .if(checkDataTypes(types, data, opts.strictNumbers), () => gen.assign(coerced, data))
    )
  }
  gen.if(_`${coerced} !== undefined`)
  for (const t of coerceTo) {
    if (COERCIBLE.has(t) || (t === "array" && opts.coerceTypes === "array")) {
      coerceSpecificType(t)
    }
  }
  gen.else()
  reportTypeError(it)
  gen.endIf()

  gen.if(_`${coerced} !== undefined`, () => {
    gen.assign(data, coerced)
    assignParentData(it, coerced)
  })

  function coerceSpecificType(t: string): void {
    switch (t) {
      case "string":
        gen
          .elseIf(_`${dataType} == "number" || ${dataType} == "boolean"`)
          .assign(coerced, _`"" + ${data}`)
          .elseIf(_`${data} === null`)
          .assign(coerced, _`""`)
        return
      case "number":
        gen
          .elseIf(
            _`${dataType} == "boolean" || ${data} === null
              || (${dataType} == "string" && ${data} && ${data} == +${data})`
          )
          .assign(coerced, _`+${data}`)
        return
      case "integer":
        gen
          .elseIf(
            _`${dataType} === "boolean" || ${data} === null
              || (${dataType} === "string" && ${data} && ${data} == +${data} && !(${data} % 1))`
          )
          .assign(coerced, _`+${data}`)
        return
      case "boolean":
        gen
          .elseIf(_`${data} === "false" || ${data} === 0 || ${data} === null`)
          .assign(coerced, false)
          .elseIf(_`${data} === "true" || ${data} === 1`)
          .assign(coerced, true)
        return
      case "null":
        gen.elseIf(_`${data} === "" || ${data} === 0 || ${data} === false`)
        gen.assign(coerced, null)
        return

      case "array":
        gen
          .elseIf(
            _`${dataType} === "string" || ${dataType} === "number"
              || ${dataType} === "boolean" || ${data} === null`
          )
          .assign(coerced, _`[${data}]`)
    }
  }
}

function assignParentData({gen, parentData, parentDataProperty}: SchemaObjCxt, expr: Name): void {
  // TODO use gen.property
  gen.if(_`${parentData} !== undefined`, () =>
    gen.assign(_`${parentData}[${parentDataProperty}]`, expr)
  )
}

export function checkDataType(
  dataType: JSONType,
  data: Name,
  strictNums?: boolean | "log",
  correct = DataType.Correct
): Code {
  const EQ = correct === DataType.Correct ? operators.EQ : operators.NEQ
  let cond: Code
  switch (dataType) {
    case "null":
      return _`${data} ${EQ} null`
    case "array":
      cond = _`Array.isArray(${data})`
      break
    case "object":
      cond = _`${data} && typeof ${data} == "object" && !Array.isArray(${data})`
      break
    case "integer":
      cond = numCond(_`!(${data} % 1) && !isNaN(${data})`)
      break
    case "number":
      cond = numCond()
      break
    default:
      return _`typeof ${data} ${EQ} ${dataType}`
  }
  return correct === DataType.Correct ? cond : not(cond)

  function numCond(_cond: Code = nil): Code {
    return and(_`typeof ${data} == "number"`, _cond, strictNums ? _`isFinite(${data})` : nil)
  }
}

export function checkDataTypes(
  dataTypes: JSONType[],
  data: Name,
  strictNums?: boolean | "log",
  correct?: DataType
): Code {
  if (dataTypes.length === 1) {
    return checkDataType(dataTypes[0], data, strictNums, correct)
  }
  let cond: Code
  const types = toHash(dataTypes)
  if (types.array && types.object) {
    const notObj = _`typeof ${data} != "object"`
    cond = types.null ? notObj : _`!${data} || ${notObj}`
    delete types.null
    delete types.array
    delete types.object
  } else {
    cond = nil
  }
  if (types.number) delete types.integer
  for (const t in types) cond = and(cond, checkDataType(t as JSONType, data, strictNums, correct))
  return cond
}

export type TypeError = ErrorObject<"type", {type: string}>

const typeError: KeywordErrorDefinition = {
  message: ({schema}) => `must be ${schema}`,
  params: ({schema, schemaValue}) =>
    typeof schema == "string" ? _`{type: ${schema}}` : _`{type: ${schemaValue}}`,
}

export function reportTypeError(it: SchemaObjCxt): void {
  const cxt = getTypeErrorContext(it)
  reportError(cxt, typeError)
}

function getTypeErrorContext(it: SchemaObjCxt): KeywordErrorCxt {
  const {gen, data, schema} = it
  const schemaCode = schemaRefOrVal(it, schema, "type")
  return {
    gen,
    keyword: "type",
    data,
    schema: schema.type,
    schemaCode,
    schemaValue: schemaCode,
    parentSchema: schema,
    params: {},
    it,
  }
}


code:
import type {SchemaObjCxt} from ".."
import {_, getProperty, stringify} from "../codegen"
import {checkStrictMode} from "../util"

export function assignDefaults(it: SchemaObjCxt, ty?: string): void {
  const {properties, items} = it.schema
  if (ty === "object" && properties) {
    for (const key in properties) {
      assignDefault(it, key, properties[key].default)
    }
  } else if (ty === "array" && Array.isArray(items)) {
    items.forEach((sch, i: number) => assignDefault(it, i, sch.default))
  }
}

function assignDefault(it: SchemaObjCxt, prop: string | number, defaultValue: unknown): void {
  const {gen, compositeRule, data, opts} = it
  if (defaultValue === undefined) return
  const childData = _`${data}${getProperty(prop)}`
  if (compositeRule) {
    checkStrictMode(it, `default is ignored for: ${childData}`)
    return
  }

  let condition = _`${childData} === undefined`
  if (opts.useDefaults === "empty") {
    condition = _`${condition} || ${childData} === null || ${childData} === ""`
  }
  // `${childData} === undefined` +
  // (opts.useDefaults === "empty" ? ` || ${childData} === null || ${childData} === ""` : "")
  gen.if(condition, _`${childData} = ${stringify(defaultValue)}`)
}

license: mit


code:
import type {
  AddedKeywordDefinition,
  AnySchema,
  AnySchemaObject,
  KeywordErrorCxt,
  KeywordCxtParams,
} from "../../types"
import type {SchemaCxt, SchemaObjCxt} from ".."
import type {InstanceOptions} from "../../core"
import {boolOrEmptySchema, topBoolOrEmptySchema} from "./boolSchema"
import {coerceAndCheckDataType, getSchemaTypes} from "./dataType"
import {shouldUseGroup, shouldUseRule} from "./applicability"
import {checkDataType, checkDataTypes, reportTypeError, DataType} from "./dataType"
import {assignDefaults} from "./defaults"
import {funcKeywordCode, macroKeywordCode, validateKeywordUsage, validSchemaType} from "./keyword"
import {getSubschema, extendSubschemaData, SubschemaArgs, extendSubschemaMode} from "./subschema"
import {_, nil, str, or, not, getProperty, Block, Code, Name, CodeGen} from "../codegen"
import N from "../names"
import {resolveUrl} from "../resolve"
import {
  schemaRefOrVal,
  schemaHasRulesButRef,
  checkUnknownRules,
  checkStrictMode,
  unescapeJsonPointer,
  mergeEvaluated,
} from "../util"
import type {JSONType, Rule, RuleGroup} from "../rules"
import {
  ErrorPaths,
  reportError,
  reportExtraError,
  resetErrorsCount,
  keyword$DataError,
} from "../errors"

// schema compilation - generates validation function, subschemaCode (below) is used for subschemas
export function validateFunctionCode(it: SchemaCxt): void {
  if (isSchemaObj(it)) {
    checkKeywords(it)
    if (schemaCxtHasRules(it)) {
      topSchemaObjCode(it)
      return
    }
  }
  validateFunction(it, () => topBoolOrEmptySchema(it))
}

function validateFunction(
  {gen, validateName, schema, schemaEnv, opts}: SchemaCxt,
  body: Block
): void {
  if (opts.code.es5) {
    gen.func(validateName, _`${N.data}, ${N.valCxt}`, schemaEnv.$async, () => {
      gen.code(_`"use strict"; ${funcSourceUrl(schema, opts)}`)
      destructureValCxtES5(gen, opts)
      gen.code(body)
    })
  } else {
    gen.func(validateName, _`${N.data}, ${destructureValCxt(opts)}`, schemaEnv.$async, () =>
      gen.code(funcSourceUrl(schema, opts)).code(body)
    )
  }
}

function destructureValCxt(opts: InstanceOptions): Code {
  return _`{${N.instancePath}="", ${N.parentData}, ${N.parentDataProperty}, ${N.rootData}=${
    N.data
  }${opts.dynamicRef ? _`, ${N.dynamicAnchors}={}` : nil}}={}`
}

function destructureValCxtES5(gen: CodeGen, opts: InstanceOptions): void {
  gen.if(
    N.valCxt,
    () => {
      gen.var(N.instancePath, _`${N.valCxt}.${N.instancePath}`)
      gen.var(N.parentData, _`${N.valCxt}.${N.parentData}`)
      gen.var(N.parentDataProperty, _`${N.valCxt}.${N.parentDataProperty}`)
      gen.var(N.rootData, _`${N.valCxt}.${N.rootData}`)
      if (opts.dynamicRef) gen.var(N.dynamicAnchors, _`${N.valCxt}.${N.dynamicAnchors}`)
    },
    () => {
      gen.var(N.instancePath, _`""`)
      gen.var(N.parentData, _`undefined`)
      gen.var(N.parentDataProperty, _`undefined`)
      gen.var(N.rootData, N.data)
      if (opts.dynamicRef) gen.var(N.dynamicAnchors, _`{}`)
    }
  )
}

function topSchemaObjCode(it: SchemaObjCxt): void {
  const {schema, opts, gen} = it
  validateFunction(it, () => {
    if (opts.$comment && schema.$comment) commentKeyword(it)
    checkNoDefault(it)
    gen.let(N.vErrors, null)
    gen.let(N.errors, 0)
    if (opts.unevaluated) resetEvaluated(it)
    typeAndKeywords(it)
    returnResults(it)
  })
  return
}

function resetEvaluated(it: SchemaObjCxt): void {
  // TODO maybe some hook to execute it in the end to check whether props/items are Name, as in assignEvaluated
  const {gen, validateName} = it
  it.evaluated = gen.const("evaluated", _`${validateName}.evaluated`)
  gen.if(_`${it.evaluated}.dynamicProps`, () => gen.assign(_`${it.evaluated}.props`, _`undefined`))
  gen.if(_`${it.evaluated}.dynamicItems`, () => gen.assign(_`${it.evaluated}.items`, _`undefined`))
}

function funcSourceUrl(schema: AnySchema, opts: InstanceOptions): Code {
  const schId = typeof schema == "object" && schema[opts.schemaId]
  return schId && (opts.code.source || opts.code.process) ? _`/*# sourceURL=${schId} */` : nil
}

// schema compilation - this function is used recursively to generate code for sub-schemas
function subschemaCode(it: SchemaCxt, valid: Name): void {
  if (isSchemaObj(it)) {
    checkKeywords(it)
    if (schemaCxtHasRules(it)) {
      subSchemaObjCode(it, valid)
      return
    }
  }
  boolOrEmptySchema(it, valid)
}

function schemaCxtHasRules({schema, self}: SchemaCxt): boolean {
  if (typeof schema == "boolean") return !schema
  for (const key in schema) if (self.RULES.all[key]) return true
  return false
}

function isSchemaObj(it: SchemaCxt): it is SchemaObjCxt {
  return typeof it.schema != "boolean"
}

function subSchemaObjCode(it: SchemaObjCxt, valid: Name): void {
  const {schema, gen, opts} = it
  if (opts.$comment && schema.$comment) commentKeyword(it)
  updateContext(it)
  checkAsyncSchema(it)
  const errsCount = gen.const("_errs", N.errors)
  typeAndKeywords(it, errsCount)
  // TODO var
  gen.var(valid, _`${errsCount} === ${N.errors}`)
}

function checkKeywords(it: SchemaObjCxt): void {
  checkUnknownRules(it)
  checkRefsAndKeywords(it)
}

function typeAndKeywords(it: SchemaObjCxt, errsCount?: Name): void {
  if (it.opts.jtd) return schemaKeywords(it, [], false, errsCount)
  const types = getSchemaTypes(it.schema)
  const checkedTypes = coerceAndCheckDataType(it, types)
  schemaKeywords(it, types, !checkedTypes, errsCount)
}

function checkRefsAndKeywords(it: SchemaObjCxt): void {
  const {schema, errSchemaPath, opts, self} = it
  if (schema.$ref && opts.ignoreKeywordsWithRef && schemaHasRulesButRef(schema, self.RULES)) {
    self.logger.warn(`$ref: keywords ignored in schema at path "${errSchemaPath}"`)
  }
}

function checkNoDefault(it: SchemaObjCxt): void {
  const {schema, opts} = it
  if (schema.default !== undefined && opts.useDefaults && opts.strictSchema) {
    checkStrictMode(it, "default is ignored in the schema root")
  }
}

function updateContext(it: SchemaObjCxt): void {
  const schId = it.schema[it.opts.schemaId]
  if (schId) it.baseId = resolveUrl(it.opts.uriResolver, it.baseId, schId)
}

function checkAsyncSchema(it: SchemaObjCxt): void {
  if (it.schema.$async && !it.schemaEnv.$async) throw new Error("async schema in sync schema")
}

function commentKeyword({gen, schemaEnv, schema, errSchemaPath, opts}: SchemaObjCxt): void {
  const msg = schema.$comment
  if (opts.$comment === true) {
    gen.code(_`${N.self}.logger.log(${msg})`)
  } else if (typeof opts.$comment == "function") {
    const schemaPath = str`${errSchemaPath}/$comment`
    const rootName = gen.scopeValue("root", {ref: schemaEnv.root})
    gen.code(_`${N.self}.opts.$comment(${msg}, ${schemaPath}, ${rootName}.schema)`)
  }
}

function returnResults(it: SchemaCxt): void {
  const {gen, schemaEnv, validateName, ValidationError, opts} = it
  if (schemaEnv.$async) {
    // TODO assign unevaluated
    gen.if(
      _`${N.errors} === 0`,
      () => gen.return(N.data),
      () => gen.throw(_`new ${ValidationError as Name}(${N.vErrors})`)
    )
  } else {
    gen.assign(_`${validateName}.errors`, N.vErrors)
    if (opts.unevaluated) assignEvaluated(it)
    gen.return(_`${N.errors} === 0`)
  }
}

function assignEvaluated({gen, evaluated, props, items}: SchemaCxt): void {
  if (props instanceof Name) gen.assign(_`${evaluated}.props`, props)
  if (items instanceof Name) gen.assign(_`${evaluated}.items`, items)
}

function schemaKeywords(
  it: SchemaObjCxt,
  types: JSONType[],
  typeErrors: boolean,
  errsCount?: Name
): void {
  const {gen, schema, data, allErrors, opts, self} = it
  const {RULES} = self
  if (schema.$ref && (opts.ignoreKeywordsWithRef || !schemaHasRulesButRef(schema, RULES))) {
    gen.block(() => keywordCode(it, "$ref", (RULES.all.$ref as Rule).definition)) // TODO typecast
    return
  }
  if (!opts.jtd) checkStrictTypes(it, types)
  gen.block(() => {
    for (const group of RULES.rules) groupKeywords(group)
    groupKeywords(RULES.post)
  })

  function groupKeywords(group: RuleGroup): void {
    if (!shouldUseGroup(schema, group)) return
    if (group.type) {
      gen.if(checkDataType(group.type, data, opts.strictNumbers))
      iterateKeywords(it, group)
      if (types.length === 1 && types[0] === group.type && typeErrors) {
        gen.else()
        reportTypeError(it)
      }
      gen.endIf()
    } else {
      iterateKeywords(it, group)
    }
    // TODO make it "ok" call?
    if (!allErrors) gen.if(_`${N.errors} === ${errsCount || 0}`)
  }
}

function iterateKeywords(it: SchemaObjCxt, group: RuleGroup): void {
  const {
    gen,
    schema,
    opts: {useDefaults},
  } = it
  if (useDefaults) assignDefaults(it, group.type)
  gen.block(() => {
    for (const rule of group.rules) {
      if (shouldUseRule(schema, rule)) {
        keywordCode(it, rule.keyword, rule.definition, group.type)
      }
    }
  })
}

function checkStrictTypes(it: SchemaObjCxt, types: JSONType[]): void {
  if (it.schemaEnv.meta || !it.opts.strictTypes) return
  checkContextTypes(it, types)
  if (!it.opts.allowUnionTypes) checkMultipleTypes(it, types)
  checkKeywordTypes(it, it.dataTypes)
}

function checkContextTypes(it: SchemaObjCxt, types: JSONType[]): void {
  if (!types.length) return
  if (!it.dataTypes.length) {
    it.dataTypes = types
    return
  }
  types.forEach((t) => {
    if (!includesType(it.dataTypes, t)) {
      strictTypesError(it, `type "${t}" not allowed by context "${it.dataTypes.join(",")}"`)
    }
  })
  narrowSchemaTypes(it, types)
}

function checkMultipleTypes(it: SchemaObjCxt, ts: JSONType[]): void {
  if (ts.length > 1 && !(ts.length === 2 && ts.includes("null"))) {
    strictTypesError(it, "use allowUnionTypes to allow union type keyword")
  }
}

function checkKeywordTypes(it: SchemaObjCxt, ts: JSONType[]): void {
  const rules = it.self.RULES.all
  for (const keyword in rules) {
    const rule = rules[keyword]
    if (typeof rule == "object" && shouldUseRule(it.schema, rule)) {
      const {type} = rule.definition
      if (type.length && !type.some((t) => hasApplicableType(ts, t))) {
        strictTypesError(it, `missing type "${type.join(",")}" for keyword "${keyword}"`)
      }
    }
  }
}

function hasApplicableType(schTs: JSONType[], kwdT: JSONType): boolean {
  return schTs.includes(kwdT) || (kwdT === "number" && schTs.includes("integer"))
}

function includesType(ts: JSONType[], t: JSONType): boolean {
  return ts.includes(t) || (t === "integer" && ts.includes("number"))
}

function narrowSchemaTypes(it: SchemaObjCxt, withTypes: JSONType[]): void {
  const ts: JSONType[] = []
  for (const t of it.dataTypes) {
    if (includesType(withTypes, t)) ts.push(t)
    else if (withTypes.includes("integer") && t === "number") ts.push("integer")
  }
  it.dataTypes = ts
}

function strictTypesError(it: SchemaObjCxt, msg: string): void {
  const schemaPath = it.schemaEnv.baseId + it.errSchemaPath
  msg += ` at "${schemaPath}" (strictTypes)`
  checkStrictMode(it, msg, it.opts.strictTypes)
}

export class KeywordCxt implements KeywordErrorCxt {
  readonly gen: CodeGen
  readonly allErrors?: boolean
  readonly keyword: string
  readonly data: Name // Name referencing the current level of the data instance
  readonly $data?: string | false
  schema: any // keyword value in the schema
  readonly schemaValue: Code | number | boolean // Code reference to keyword schema value or primitive value
  readonly schemaCode: Code | number | boolean // Code reference to resolved schema value (different if schema is $data)
  readonly schemaType: JSONType[] // allowed type(s) of keyword value in the schema
  readonly parentSchema: AnySchemaObject
  readonly errsCount?: Name // Name reference to the number of validation errors collected before this keyword,
  // requires option trackErrors in keyword definition
  params: KeywordCxtParams // object to pass parameters to error messages from keyword code
  readonly it: SchemaObjCxt // schema compilation context (schema is guaranteed to be an object, not boolean)
  readonly def: AddedKeywordDefinition

  constructor(it: SchemaObjCxt, def: AddedKeywordDefinition, keyword: string) {
    validateKeywordUsage(it, def, keyword)
    this.gen = it.gen
    this.allErrors = it.allErrors
    this.keyword = keyword
    this.data = it.data
    this.schema = it.schema[keyword]
    this.$data = def.$data && it.opts.$data && this.schema && this.schema.$data
    this.schemaValue = schemaRefOrVal(it, this.schema, keyword, this.$data)
    this.schemaType = def.schemaType
    this.parentSchema = it.schema
    this.params = {}
    this.it = it
    this.def = def

    if (this.$data) {
      this.schemaCode = it.gen.const("vSchema", getData(this.$data, it))
    } else {
      this.schemaCode = this.schemaValue
      if (!validSchemaType(this.schema, def.schemaType, def.allowUndefined)) {
        throw new Error(`${keyword} value must be ${JSON.stringify(def.schemaType)}`)
      }
    }

    if ("code" in def ? def.trackErrors : def.errors !== false) {
      this.errsCount = it.gen.const("_errs", N.errors)
    }
  }

  result(condition: Code, successAction?: () => void, failAction?: () => void): void {
    this.failResult(not(condition), successAction, failAction)
  }

  failResult(condition: Code, successAction?: () => void, failAction?: () => void): void {
    this.gen.if(condition)
    if (failAction) failAction()
    else this.error()
    if (successAction) {
      this.gen.else()
      successAction()
      if (this.allErrors) this.gen.endIf()
    } else {
      if (this.allErrors) this.gen.endIf()
      else this.gen.else()
    }
  }

  pass(condition: Code, failAction?: () => void): void {
    this.failResult(not(condition), undefined, failAction)
  }

  fail(condition?: Code): void {
    if (condition === undefined) {
      this.error()
      if (!this.allErrors) this.gen.if(false) // this branch will be removed by gen.optimize
      return
    }
    this.gen.if(condition)
    this.error()
    if (this.allErrors) this.gen.endIf()
    else this.gen.else()
  }

  fail$data(condition: Code): void {
    if (!this.$data) return this.fail(condition)
    const {schemaCode} = this
    this.fail(_`${schemaCode} !== undefined && (${or(this.invalid$data(), condition)})`)
  }

  error(append?: boolean, errorParams?: KeywordCxtParams, errorPaths?: ErrorPaths): void {
    if (errorParams) {
      this.setParams(errorParams)
      this._error(append, errorPaths)
      this.setParams({})
      return
    }
    this._error(append, errorPaths)
  }

  private _error(append?: boolean, errorPaths?: ErrorPaths): void {
    ;(append ? reportExtraError : reportError)(this, this.def.error, errorPaths)
  }

  $dataError(): void {
    reportError(this, this.def.$dataError || keyword$DataError)
  }

  reset(): void {
    if (this.errsCount === undefined) throw new Error('add "trackErrors" to keyword definition')
    resetErrorsCount(this.gen, this.errsCount)
  }

  ok(cond: Code | boolean): void {
    if (!this.allErrors) this.gen.if(cond)
  }

  setParams(obj: KeywordCxtParams, assign?: true): void {
    if (assign) Object.assign(this.params, obj)
    else this.params = obj
  }

  block$data(valid: Name, codeBlock: () => void, $dataValid: Code = nil): void {
    this.gen.block(() => {
      this.check$data(valid, $dataValid)
      codeBlock()
    })
  }

  check$data(valid: Name = nil, $dataValid: Code = nil): void {
    if (!this.$data) return
    const {gen, schemaCode, schemaType, def} = this
    gen.if(or(_`${schemaCode} === undefined`, $dataValid))
    if (valid !== nil) gen.assign(valid, true)
    if (schemaType.length || def.validateSchema) {
      gen.elseIf(this.invalid$data())
      this.$dataError()
      if (valid !== nil) gen.assign(valid, false)
    }
    gen.else()
  }

  invalid$data(): Code {
    const {gen, schemaCode, schemaType, def, it} = this
    return or(wrong$DataType(), invalid$DataSchema())

    function wrong$DataType(): Code {
      if (schemaType.length) {
        /* istanbul ignore if */
        if (!(schemaCode instanceof Name)) throw new Error("ajv implementation error")
        const st = Array.isArray(schemaType) ? schemaType : [schemaType]
        return _`${checkDataTypes(st, schemaCode, it.opts.strictNumbers, DataType.Wrong)}`
      }
      return nil
    }

    function invalid$DataSchema(): Code {
      if (def.validateSchema) {
        const validateSchemaRef = gen.scopeValue("validate$data", {ref: def.validateSchema}) // TODO value.code for standalone
        return _`!${validateSchemaRef}(${schemaCode})`
      }
      return nil
    }
  }

  subschema(appl: SubschemaArgs, valid: Name): SchemaCxt {
    const subschema = getSubschema(this.it, appl)
    extendSubschemaData(subschema, this.it, appl)
    extendSubschemaMode(subschema, appl)
    const nextContext = {...this.it, ...subschema, items: undefined, props: undefined}
    subschemaCode(nextContext, valid)
    return nextContext
  }

  mergeEvaluated(schemaCxt: SchemaCxt, toName?: typeof Name): void {
    const {it, gen} = this
    if (!it.opts.unevaluated) return
    if (it.props !== true && schemaCxt.props !== undefined) {
      it.props = mergeEvaluated.props(gen, schemaCxt.props, it.props, toName)
    }
    if (it.items !== true && schemaCxt.items !== undefined) {
      it.items = mergeEvaluated.items(gen, schemaCxt.items, it.items, toName)
    }
  }

  mergeValidEvaluated(schemaCxt: SchemaCxt, valid: Name): boolean | void {
    const {it, gen} = this
    if (it.opts.unevaluated && (it.props !== true || it.items !== true)) {
      gen.if(valid, () => this.mergeEvaluated(schemaCxt, Name))
      return true
    }
  }
}

function keywordCode(
  it: SchemaObjCxt,
  keyword: string,
  def: AddedKeywordDefinition,
  ruleType?: JSONType
): void {
  const cxt = new KeywordCxt(it, def, keyword)
  if ("code" in def) {
    def.code(cxt, ruleType)
  } else if (cxt.$data && def.validate) {
    funcKeywordCode(cxt, def)
  } else if ("macro" in def) {
    macroKeywordCode(cxt, def)
  } else if (def.compile || def.validate) {
    funcKeywordCode(cxt, def)
  }
}

const JSON_POINTER = /^\/(?:[^~]|~0|~1)*$/
const RELATIVE_JSON_POINTER = /^([0-9]+)(#|\/(?:[^~]|~0|~1)*)?$/
export function getData(
  $data: string,
  {dataLevel, dataNames, dataPathArr}: SchemaCxt
): Code | number {
  let jsonPointer
  let data: Code
  if ($data === "") return N.rootData
  if ($data[0] === "/") {
    if (!JSON_POINTER.test($data)) throw new Error(`Invalid JSON-pointer: ${$data}`)
    jsonPointer = $data
    data = N.rootData
  } else {
    const matches = RELATIVE_JSON_POINTER.exec($data)
    if (!matches) throw new Error(`Invalid JSON-pointer: ${$data}`)
    const up: number = +matches[1]
    jsonPointer = matches[2]
    if (jsonPointer === "#") {
      if (up >= dataLevel) throw new Error(errorMsg("property/index", up))
      return dataPathArr[dataLevel - up]
    }
    if (up > dataLevel) throw new Error(errorMsg("data", up))
    data = dataNames[dataLevel - up]
    if (!jsonPointer) return data
  }

  let expr = data
  const segments = jsonPointer.split("/")
  for (const segment of segments) {
    if (segment) {
      data = _`${data}${getProperty(unescapeJsonPointer(segment))}`
      expr = _`${expr} && ${data}`
    }
  }
  return expr

  function errorMsg(pointerType: string, up: number): string {
    return `Cannot access ${pointerType} ${up} levels up, current level is ${dataLevel}`
  }
}


code:
import type {KeywordCxt} from "."
import type {
  AnySchema,
  SchemaValidateFunction,
  AnyValidateFunction,
  AddedKeywordDefinition,
  MacroKeywordDefinition,
  FuncKeywordDefinition,
} from "../../types"
import type {SchemaObjCxt} from ".."
import {_, nil, not, stringify, Code, Name, CodeGen} from "../codegen"
import N from "../names"
import type {JSONType} from "../rules"
import {callValidateCode} from "../../vocabularies/code"
import {extendErrors} from "../errors"

type KeywordCompilationResult = AnySchema | SchemaValidateFunction | AnyValidateFunction

export function macroKeywordCode(cxt: KeywordCxt, def: MacroKeywordDefinition): void {
  const {gen, keyword, schema, parentSchema, it} = cxt
  const macroSchema = def.macro.call(it.self, schema, parentSchema, it)
  const schemaRef = useKeyword(gen, keyword, macroSchema)
  if (it.opts.validateSchema !== false) it.self.validateSchema(macroSchema, true)

  const valid = gen.name("valid")
  cxt.subschema(
    {
      schema: macroSchema,
      schemaPath: nil,
      errSchemaPath: `${it.errSchemaPath}/${keyword}`,
      topSchemaRef: schemaRef,
      compositeRule: true,
    },
    valid
  )
  cxt.pass(valid, () => cxt.error(true))
}

export function funcKeywordCode(cxt: KeywordCxt, def: FuncKeywordDefinition): void {
  const {gen, keyword, schema, parentSchema, $data, it} = cxt
  checkAsyncKeyword(it, def)
  const validate =
    !$data && def.compile ? def.compile.call(it.self, schema, parentSchema, it) : def.validate
  const validateRef = useKeyword(gen, keyword, validate)
  const valid = gen.let("valid")
  cxt.block$data(valid, validateKeyword)
  cxt.ok(def.valid ?? valid)

  function validateKeyword(): void {
    if (def.errors === false) {
      assignValid()
      if (def.modifying) modifyData(cxt)
      reportErrs(() => cxt.error())
    } else {
      const ruleErrs = def.async ? validateAsync() : validateSync()
      if (def.modifying) modifyData(cxt)
      reportErrs(() => addErrs(cxt, ruleErrs))
    }
  }

  function validateAsync(): Name {
    const ruleErrs = gen.let("ruleErrs", null)
    gen.try(
      () => assignValid(_`await `),
      (e) =>
        gen.assign(valid, false).if(
          _`${e} instanceof ${it.ValidationError as Name}`,
          () => gen.assign(ruleErrs, _`${e}.errors`),
          () => gen.throw(e)
        )
    )
    return ruleErrs
  }

  function validateSync(): Code {
    const validateErrs = _`${validateRef}.errors`
    gen.assign(validateErrs, null)
    assignValid(nil)
    return validateErrs
  }

  function assignValid(_await: Code = def.async ? _`await ` : nil): void {
    const passCxt = it.opts.passContext ? N.this : N.self
    const passSchema = !(("compile" in def && !$data) || def.schema === false)
    gen.assign(
      valid,
      _`${_await}${callValidateCode(cxt, validateRef, passCxt, passSchema)}`,
      def.modifying
    )
  }

  function reportErrs(errors: () => void): void {
    gen.if(not(def.valid ?? valid), errors)
  }
}

function modifyData(cxt: KeywordCxt): void {
  const {gen, data, it} = cxt
  gen.if(it.parentData, () => gen.assign(data, _`${it.parentData}[${it.parentDataProperty}]`))
}

function addErrs(cxt: KeywordCxt, errs: Code): void {
  const {gen} = cxt
  gen.if(
    _`Array.isArray(${errs})`,
    () => {
      gen
        .assign(N.vErrors, _`${N.vErrors} === null ? ${errs} : ${N.vErrors}.concat(${errs})`)
        .assign(N.errors, _`${N.vErrors}.length`)
      extendErrors(cxt)
    },
    () => cxt.error()
  )
}

function checkAsyncKeyword({schemaEnv}: SchemaObjCxt, def: FuncKeywordDefinition): void {
  if (def.async && !schemaEnv.$async) throw new Error("async keyword in sync schema")
}

function useKeyword(gen: CodeGen, keyword: string, result?: KeywordCompilationResult): Name {
  if (result === undefined) throw new Error(`keyword "${keyword}" failed to compile`)
  return gen.scopeValue(
    "keyword",
    typeof result == "function" ? {ref: result} : {ref: result, code: stringify(result)}
  )
}

export function validSchemaType(
  schema: unknown,
  schemaType: JSONType[],
  allowUndefined = false
): boolean {
  // TODO add tests
  return (
    !schemaType.length ||
    schemaType.some((st) =>
      st === "array"
        ? Array.isArray(schema)
        : st === "object"
        ? schema && typeof schema == "object" && !Array.isArray(schema)
        : typeof schema == st || (allowUndefined && typeof schema == "undefined")
    )
  )
}

export function validateKeywordUsage(
  {schema, opts, self, errSchemaPath}: SchemaObjCxt,
  def: AddedKeywordDefinition,
  keyword: string
): void {
  /* istanbul ignore if */
  if (Array.isArray(def.keyword) ? !def.keyword.includes(keyword) : def.keyword !== keyword) {
    throw new Error("ajv implementation error")
  }

  const deps = def.dependencies
  if (deps?.some((kwd) => !Object.prototype.hasOwnProperty.call(schema, kwd))) {
    throw new Error(`parent schema must have dependencies of ${keyword}: ${deps.join(",")}`)
  }

  if (def.validateSchema) {
    const valid = def.validateSchema(schema[keyword])
    if (!valid) {
      const msg =
        `keyword "${keyword}" value is invalid at path "${errSchemaPath}": ` +
        self.errorsText(def.validateSchema.errors)
      if (opts.validateSchema === "log") self.logger.error(msg)
      else throw new Error(msg)
    }
  }
}


code:
import type {AnySchema} from "../../types"
import type {SchemaObjCxt} from ".."
import {_, str, getProperty, Code, Name} from "../codegen"
import {escapeFragment, getErrorPath, Type} from "../util"
import type {JSONType} from "../rules"

export interface SubschemaContext {
  // TODO use Optional? align with SchemCxt property types
  schema: AnySchema
  schemaPath: Code
  errSchemaPath: string
  topSchemaRef?: Code
  errorPath?: Code
  dataLevel?: number
  dataTypes?: JSONType[]
  data?: Name
  parentData?: Name
  parentDataProperty?: Code | number
  dataNames?: Name[]
  dataPathArr?: (Code | number)[]
  propertyName?: Name
  jtdDiscriminator?: string
  jtdMetadata?: boolean
  compositeRule?: true
  createErrors?: boolean
  allErrors?: boolean
}

export type SubschemaArgs = Partial<{
  keyword: string
  schemaProp: string | number
  schema: AnySchema
  schemaPath: Code
  errSchemaPath: string
  topSchemaRef: Code
  data: Name | Code
  dataProp: Code | string | number
  dataTypes: JSONType[]
  definedProperties: Set<string>
  propertyName: Name
  dataPropType: Type
  jtdDiscriminator: string
  jtdMetadata: boolean
  compositeRule: true
  createErrors: boolean
  allErrors: boolean
}>

export function getSubschema(
  it: SchemaObjCxt,
  {keyword, schemaProp, schema, schemaPath, errSchemaPath, topSchemaRef}: SubschemaArgs
): SubschemaContext {
  if (keyword !== undefined && schema !== undefined) {
    throw new Error('both "keyword" and "schema" passed, only one allowed')
  }

  if (keyword !== undefined) {
    const sch = it.schema[keyword]
    return schemaProp === undefined
      ? {
          schema: sch,
          schemaPath: _`${it.schemaPath}${getProperty(keyword)}`,
          errSchemaPath: `${it.errSchemaPath}/${keyword}`,
        }
      : {
          schema: sch[schemaProp],
          schemaPath: _`${it.schemaPath}${getProperty(keyword)}${getProperty(schemaProp)}`,
          errSchemaPath: `${it.errSchemaPath}/${keyword}/${escapeFragment(schemaProp)}`,
        }
  }

  if (schema !== undefined) {
    if (schemaPath === undefined || errSchemaPath === undefined || topSchemaRef === undefined) {
      throw new Error('"schemaPath", "errSchemaPath" and "topSchemaRef" are required with "schema"')
    }
    return {
      schema,
      schemaPath,
      topSchemaRef,
      errSchemaPath,
    }
  }

  throw new Error('either "keyword" or "schema" must be passed')
}

export function extendSubschemaData(
  subschema: SubschemaContext,
  it: SchemaObjCxt,
  {dataProp, dataPropType: dpType, data, dataTypes, propertyName}: SubschemaArgs
): void {
  if (data !== undefined && dataProp !== undefined) {
    throw new Error('both "data" and "dataProp" passed, only one allowed')
  }

  const {gen} = it

  if (dataProp !== undefined) {
    const {errorPath, dataPathArr, opts} = it
    const nextData = gen.let("data", _`${it.data}${getProperty(dataProp)}`, true)
    dataContextProps(nextData)
    subschema.errorPath = str`${errorPath}${getErrorPath(dataProp, dpType, opts.jsPropertySyntax)}`
    subschema.parentDataProperty = _`${dataProp}`
    subschema.dataPathArr = [...dataPathArr, subschema.parentDataProperty]
  }

  if (data !== undefined) {
    const nextData = data instanceof Name ? data : gen.let("data", data, true) // replaceable if used once?
    dataContextProps(nextData)
    if (propertyName !== undefined) subschema.propertyName = propertyName
    // TODO something is possibly wrong here with not changing parentDataProperty and not appending dataPathArr
  }

  if (dataTypes) subschema.dataTypes = dataTypes

  function dataContextProps(_nextData: Name): void {
    subschema.data = _nextData
    subschema.dataLevel = it.dataLevel + 1
    subschema.dataTypes = []
    it.definedProperties = new Set<string>()
    subschema.parentData = it.data
    subschema.dataNames = [...it.dataNames, _nextData]
  }
}

export function extendSubschemaMode(
  subschema: SubschemaContext,
  {jtdDiscriminator, jtdMetadata, compositeRule, createErrors, allErrors}: SubschemaArgs
): void {
  if (compositeRule !== undefined) subschema.compositeRule = compositeRule
  if (createErrors !== undefined) subschema.createErrors = createErrors
  if (allErrors !== undefined) subschema.allErrors = allErrors
  subschema.jtdDiscriminator = jtdDiscriminator // not inherited
  subschema.jtdMetadata = jtdMetadata // not inherited
}


code:
export {
  Format,
  FormatDefinition,
  AsyncFormatDefinition,
  KeywordDefinition,
  KeywordErrorDefinition,
  CodeKeywordDefinition,
  MacroKeywordDefinition,
  FuncKeywordDefinition,
  Vocabulary,
  Schema,
  SchemaObject,
  AnySchemaObject,
  AsyncSchema,
  AnySchema,
  ValidateFunction,
  AsyncValidateFunction,
  AnyValidateFunction,
  ErrorObject,
  ErrorNoParams,
} from "./types"

export {SchemaCxt, SchemaObjCxt} from "./compile"
export interface Plugin<Opts> {
  (ajv: Ajv, options?: Opts): Ajv
  [prop: string]: any
}

export {KeywordCxt} from "./compile/validate"
export {DefinedError} from "./vocabularies/errors"
export {JSONType} from "./compile/rules"
export {JSONSchemaType} from "./types/json-schema"
export {JTDSchemaType, SomeJTDSchemaType, JTDDataType} from "./types/jtd-schema"
export {_, str, stringify, nil, Name, Code, CodeGen, CodeGenOptions} from "./compile/codegen"

import type {
  Schema,
  AnySchema,
  AnySchemaObject,
  SchemaObject,
  AsyncSchema,
  Vocabulary,
  KeywordDefinition,
  AddedKeywordDefinition,
  AnyValidateFunction,
  ValidateFunction,
  AsyncValidateFunction,
  ErrorObject,
  Format,
  AddedFormat,
  RegExpEngine,
  UriResolver,
} from "./types"
import type {JSONSchemaType} from "./types/json-schema"
import type {JTDSchemaType, SomeJTDSchemaType, JTDDataType} from "./types/jtd-schema"
import ValidationError from "./runtime/validation_error"
import MissingRefError from "./compile/ref_error"
import {getRules, ValidationRules, Rule, RuleGroup, JSONType} from "./compile/rules"
import {SchemaEnv, compileSchema, resolveSchema} from "./compile"
import {Code, ValueScope} from "./compile/codegen"
import {normalizeId, getSchemaRefs} from "./compile/resolve"
import {getJSONTypes} from "./compile/validate/dataType"
import {eachItem} from "./compile/util"
import * as $dataRefSchema from "./refs/data.json"

import DefaultUriResolver from "./runtime/uri"

const defaultRegExp: RegExpEngine = (str, flags) => new RegExp(str, flags)
defaultRegExp.code = "new RegExp"

const META_IGNORE_OPTIONS: (keyof Options)[] = ["removeAdditional", "useDefaults", "coerceTypes"]
const EXT_SCOPE_NAMES = new Set([
  "validate",
  "serialize",
  "parse",
  "wrapper",
  "root",
  "schema",
  "keyword",
  "pattern",
  "formats",
  "validate$data",
  "func",
  "obj",
  "Error",
])

export type Options = CurrentOptions & DeprecatedOptions

export interface CurrentOptions {
  // strict mode options (NEW)
  strict?: boolean | "log"
  strictSchema?: boolean | "log"
  strictNumbers?: boolean | "log"
  strictTypes?: boolean | "log"
  strictTuples?: boolean | "log"
  strictRequired?: boolean | "log"
  allowMatchingProperties?: boolean // disables a strict mode restriction
  allowUnionTypes?: boolean
  validateFormats?: boolean
  // validation and reporting options:
  $data?: boolean
  allErrors?: boolean
  verbose?: boolean
  discriminator?: boolean
  unicodeRegExp?: boolean
  timestamp?: "string" | "date" // JTD only
  parseDate?: boolean // JTD only
  allowDate?: boolean // JTD only
  $comment?:
    | true
    | ((comment: string, schemaPath?: string, rootSchema?: AnySchemaObject) => unknown)
  formats?: {[Name in string]?: Format}
  keywords?: Vocabulary
  schemas?: AnySchema[] | {[Key in string]?: AnySchema}
  logger?: Logger | false
  loadSchema?: (uri: string) => Promise<AnySchemaObject>
  // options to modify validated data:
  removeAdditional?: boolean | "all" | "failing"
  useDefaults?: boolean | "empty"
  coerceTypes?: boolean | "array"
  // advanced options:
  next?: boolean // NEW
  unevaluated?: boolean // NEW
  dynamicRef?: boolean // NEW
  schemaId?: "id" | "$id"
  jtd?: boolean // NEW
  meta?: SchemaObject | boolean
  defaultMeta?: string | AnySchemaObject
  validateSchema?: boolean | "log"
  addUsedSchema?: boolean
  inlineRefs?: boolean | number
  passContext?: boolean
  loopRequired?: number
  loopEnum?: number // NEW
  ownProperties?: boolean
  multipleOfPrecision?: number
  int32range?: boolean // JTD only
  messages?: boolean
  code?: CodeOptions // NEW
  uriResolver?: UriResolver
}

export interface CodeOptions {
  es5?: boolean
  esm?: boolean
  lines?: boolean
  optimize?: boolean | number
  formats?: Code // code to require (or construct) map of available formats - for standalone code
  source?: boolean
  process?: (code: string, schema?: SchemaEnv) => string
  regExp?: RegExpEngine
}

interface InstanceCodeOptions extends CodeOptions {
  regExp: RegExpEngine
  optimize: number
}

interface DeprecatedOptions {
  /** @deprecated */
  ignoreKeywordsWithRef?: boolean
  /** @deprecated */
  jsPropertySyntax?: boolean // added instead of jsonPointers
  /** @deprecated */
  unicode?: boolean
}

interface RemovedOptions {
  format?: boolean
  errorDataPath?: "object" | "property"
  nullable?: boolean // "nullable" keyword is supported by default
  jsonPointers?: boolean
  extendRefs?: true | "ignore" | "fail"
  missingRefs?: true | "ignore" | "fail"
  processCode?: (code: string, schema?: SchemaEnv) => string
  sourceCode?: boolean
  strictDefaults?: boolean
  strictKeywords?: boolean
  uniqueItems?: boolean
  unknownFormats?: true | string[] | "ignore"
  cache?: any
  serialize?: (schema: AnySchema) => unknown
  ajvErrors?: boolean
}

type OptionsInfo<T extends RemovedOptions | DeprecatedOptions> = {
  [K in keyof T]-?: string | undefined
}

const removedOptions: OptionsInfo<RemovedOptions> = {
  errorDataPath: "",
  format: "`validateFormats: false` can be used instead.",
  nullable: '"nullable" keyword is supported by default.',
  jsonPointers: "Deprecated jsPropertySyntax can be used instead.",
  extendRefs: "Deprecated ignoreKeywordsWithRef can be used instead.",
  missingRefs: "Pass empty schema with $id that should be ignored to ajv.addSchema.",
  processCode: "Use option `code: {process: (code, schemaEnv: object) => string}`",
  sourceCode: "Use option `code: {source: true}`",
  strictDefaults: "It is default now, see option `strict`.",
  strictKeywords: "It is default now, see option `strict`.",
  uniqueItems: '"uniqueItems" keyword is always validated.',
  unknownFormats: "Disable strict mode or pass `true` to `ajv.addFormat` (or `formats` option).",
  cache: "Map is used as cache, schema object as key.",
  serialize: "Map is used as cache, schema object as key.",
  ajvErrors: "It is default now.",
}

const deprecatedOptions: OptionsInfo<DeprecatedOptions> = {
  ignoreKeywordsWithRef: "",
  jsPropertySyntax: "",
  unicode: '"minLength"/"maxLength" account for unicode characters by default.',
}

type RequiredInstanceOptions = {
  [K in
    | "strictSchema"
    | "strictNumbers"
    | "strictTypes"
    | "strictTuples"
    | "strictRequired"
    | "inlineRefs"
    | "loopRequired"
    | "loopEnum"
    | "meta"
    | "messages"
    | "schemaId"
    | "addUsedSchema"
    | "validateSchema"
    | "validateFormats"
    | "int32range"
    | "unicodeRegExp"
    | "uriResolver"]: NonNullable<Options[K]>
} & {code: InstanceCodeOptions}

export type InstanceOptions = Options & RequiredInstanceOptions

const MAX_EXPRESSION = 200

// eslint-disable-next-line complexity
function requiredOptions(o: Options): RequiredInstanceOptions {
  const s = o.strict
  const _optz = o.code?.optimize
  const optimize = _optz === true || _optz === undefined ? 1 : _optz || 0
  const regExp = o.code?.regExp ?? defaultRegExp
  const uriResolver = o.uriResolver ?? DefaultUriResolver
  return {
    strictSchema: o.strictSchema ?? s ?? true,
    strictNumbers: o.strictNumbers ?? s ?? true,
    strictTypes: o.strictTypes ?? s ?? "log",
    strictTuples: o.strictTuples ?? s ?? "log",
    strictRequired: o.strictRequired ?? s ?? false,
    code: o.code ? {...o.code, optimize, regExp} : {optimize, regExp},
    loopRequired: o.loopRequired ?? MAX_EXPRESSION,
    loopEnum: o.loopEnum ?? MAX_EXPRESSION,
    meta: o.meta ?? true,
    messages: o.messages ?? true,
    inlineRefs: o.inlineRefs ?? true,
    schemaId: o.schemaId ?? "$id",
    addUsedSchema: o.addUsedSchema ?? true,
    validateSchema: o.validateSchema ?? true,
    validateFormats: o.validateFormats ?? true,
    unicodeRegExp: o.unicodeRegExp ?? true,
    int32range: o.int32range ?? true,
    uriResolver: uriResolver,
  }
}

export interface Logger {
  log(...args: unknown[]): unknown
  warn(...args: unknown[]): unknown
  error(...args: unknown[]): unknown
}

export default class Ajv {
  opts: InstanceOptions
  errors?: ErrorObject[] | null // errors from the last validation
  logger: Logger
  // shared external scope values for compiled functions
  readonly scope: ValueScope
  readonly schemas: {[Key in string]?: SchemaEnv} = {}
  readonly refs: {[Ref in string]?: SchemaEnv | string} = {}
  readonly formats: {[Name in string]?: AddedFormat} = {}
  readonly RULES: ValidationRules
  readonly _compilations: Set<SchemaEnv> = new Set()
  private readonly _loading: {[Ref in string]?: Promise<AnySchemaObject>} = {}
  private readonly _cache: Map<AnySchema, SchemaEnv> = new Map()
  private readonly _metaOpts: InstanceOptions

  static ValidationError = ValidationError
  static MissingRefError = MissingRefError

  constructor(opts: Options = {}) {
    opts = this.opts = {...opts, ...requiredOptions(opts)}
    const {es5, lines} = this.opts.code

    this.scope = new ValueScope({scope: {}, prefixes: EXT_SCOPE_NAMES, es5, lines})
    this.logger = getLogger(opts.logger)
    const formatOpt = opts.validateFormats
    opts.validateFormats = false

    this.RULES = getRules()
    checkOptions.call(this, removedOptions, opts, "NOT SUPPORTED")
    checkOptions.call(this, deprecatedOptions, opts, "DEPRECATED", "warn")
    this._metaOpts = getMetaSchemaOptions.call(this)

    if (opts.formats) addInitialFormats.call(this)
    this._addVocabularies()
    this._addDefaultMetaSchema()
    if (opts.keywords) addInitialKeywords.call(this, opts.keywords)
    if (typeof opts.meta == "object") this.addMetaSchema(opts.meta)
    addInitialSchemas.call(this)
    opts.validateFormats = formatOpt
  }

  _addVocabularies(): void {
    this.addKeyword("$async")
  }

  _addDefaultMetaSchema(): void {
    const {$data, meta, schemaId} = this.opts
    let _dataRefSchema: SchemaObject = $dataRefSchema
    if (schemaId === "id") {
      _dataRefSchema = {...$dataRefSchema}
      _dataRefSchema.id = _dataRefSchema.$id
      delete _dataRefSchema.$id
    }
    if (meta && $data) this.addMetaSchema(_dataRefSchema, _dataRefSchema[schemaId], false)
  }

  defaultMeta(): string | AnySchemaObject | undefined {
    const {meta, schemaId} = this.opts
    return (this.opts.defaultMeta = typeof meta == "object" ? meta[schemaId] || meta : undefined)
  }

  // Validate data using schema
  // AnySchema will be compiled and cached using schema itself as a key for Map
  validate(schema: Schema | string, data: unknown): boolean
  validate(schemaKeyRef: AnySchema | string, data: unknown): boolean | Promise<unknown>
  validate<T>(schema: Schema | JSONSchemaType<T> | string, data: unknown): data is T
  // Separated for type inference to work
  // eslint-disable-next-line @typescript-eslint/unified-signatures
  validate<T>(schema: JTDSchemaType<T>, data: unknown): data is T
  // This overload is only intended for typescript inference, the first
  // argument prevents manual type annotation from matching this overload
  // eslint-disable-next-line @typescript-eslint/no-unused-vars
  validate<N extends never, T extends SomeJTDSchemaType>(
    schema: T,
    data: unknown
  ): data is JTDDataType<T>
  // eslint-disable-next-line @typescript-eslint/no-redundant-type-constituents
  validate<T>(schema: AsyncSchema, data: unknown | T): Promise<T>
  validate<T>(schemaKeyRef: AnySchema | string, data: unknown): data is T | Promise<T>
  validate<T>(
    schemaKeyRef: AnySchema | string, // key, ref or schema object
    // eslint-disable-next-line @typescript-eslint/no-redundant-type-constituents
    data: unknown | T // to be validated
  ): boolean | Promise<T> {
    let v: AnyValidateFunction | undefined
    if (typeof schemaKeyRef == "string") {
      v = this.getSchema<T>(schemaKeyRef)
      if (!v) throw new Error(`no schema with key or ref "${schemaKeyRef}"`)
    } else {
      v = this.compile<T>(schemaKeyRef)
    }

    const valid = v(data)
    if (!("$async" in v)) this.errors = v.errors
    return valid
  }

  // Create validation function for passed schema
  // _meta: true if schema is a meta-schema. Used internally to compile meta schemas of user-defined keywords.
  compile<T = unknown>(schema: Schema | JSONSchemaType<T>, _meta?: boolean): ValidateFunction<T>
  // Separated for type inference to work
  // eslint-disable-next-line @typescript-eslint/unified-signatures
  compile<T = unknown>(schema: JTDSchemaType<T>, _meta?: boolean): ValidateFunction<T>
  // This overload is only intended for typescript inference, the first
  // argument prevents manual type annotation from matching this overload
  // eslint-disable-next-line @typescript-eslint/no-unused-vars
  compile<N extends never, T extends SomeJTDSchemaType>(
    schema: T,
    _meta?: boolean
  ): ValidateFunction<JTDDataType<T>>
  compile<T = unknown>(schema: AsyncSchema, _meta?: boolean): AsyncValidateFunction<T>
  compile<T = unknown>(schema: AnySchema, _meta?: boolean): AnyValidateFunction<T>
  compile<T = unknown>(schema: AnySchema, _meta?: boolean): AnyValidateFunction<T> {
    const sch = this._addSchema(schema, _meta)
    return (sch.validate || this._compileSchemaEnv(sch)) as AnyValidateFunction<T>
  }

  // Creates validating function for passed schema with asynchronous loading of missing schemas.
  // `loadSchema` option should be a function that accepts schema uri and returns promise that resolves with the schema.
  // TODO allow passing schema URI
  // meta - optional true to compile meta-schema
  compileAsync<T = unknown>(
    schema: SchemaObject | JSONSchemaType<T>,
    _meta?: boolean
  ): Promise<ValidateFunction<T>>
  // Separated for type inference to work
  // eslint-disable-next-line @typescript-eslint/unified-signatures
  compileAsync<T = unknown>(schema: JTDSchemaType<T>, _meta?: boolean): Promise<ValidateFunction<T>>
  compileAsync<T = unknown>(schema: AsyncSchema, meta?: boolean): Promise<AsyncValidateFunction<T>>
  // eslint-disable-next-line @typescript-eslint/unified-signatures
  compileAsync<T = unknown>(
    schema: AnySchemaObject,
    meta?: boolean
  ): Promise<AnyValidateFunction<T>>
  compileAsync<T = unknown>(
    schema: AnySchemaObject,
    meta?: boolean
  ): Promise<AnyValidateFunction<T>> {
    if (typeof this.opts.loadSchema != "function") {
      throw new Error("options.loadSchema should be a function")
    }
    const {loadSchema} = this.opts
    return runCompileAsync.call(this, schema, meta)

    async function runCompileAsync(
      this: Ajv,
      _schema: AnySchemaObject,
      _meta?: boolean
    ): Promise<AnyValidateFunction> {
      await loadMetaSchema.call(this, _schema.$schema)
      const sch = this._addSchema(_schema, _meta)
      return sch.validate || _compileAsync.call(this, sch)
    }

    async function loadMetaSchema(this: Ajv, $ref?: string): Promise<void> {
      if ($ref && !this.getSchema($ref)) {
        await runCompileAsync.call(this, {$ref}, true)
      }
    }

    async function _compileAsync(this: Ajv, sch: SchemaEnv): Promise<AnyValidateFunction> {
      try {
        return this._compileSchemaEnv(sch)
      } catch (e) {
        if (!(e instanceof MissingRefError)) throw e
        checkLoaded.call(this, e)
        await loadMissingSchema.call(this, e.missingSchema)
        return _compileAsync.call(this, sch)
      }
    }

    function checkLoaded(this: Ajv, {missingSchema: ref, missingRef}: MissingRefError): void {
      if (this.refs[ref]) {
        throw new Error(`AnySchema ${ref} is loaded but ${missingRef} cannot be resolved`)
      }
    }

    async function loadMissingSchema(this: Ajv, ref: string): Promise<void> {
      const _schema = await _loadSchema.call(this, ref)
      if (!this.refs[ref]) await loadMetaSchema.call(this, _schema.$schema)
      if (!this.refs[ref]) this.addSchema(_schema, ref, meta)
    }

    async function _loadSchema(this: Ajv, ref: string): Promise<AnySchemaObject> {
      const p = this._loading[ref]
      if (p) return p
      try {
        return await (this._loading[ref] = loadSchema(ref))
      } finally {
        delete this._loading[ref]
      }
    }
  }

  // Adds schema to the instance
  addSchema(
    schema: AnySchema | AnySchema[], // If array is passed, `key` will be ignored
    key?: string, // Optional schema key. Can be passed to `validate` method instead of schema object or id/ref. One schema per instance can have empty `id` and `key`.
    _meta?: boolean, // true if schema is a meta-schema. Used internally, addMetaSchema should be used instead.
    _validateSchema = this.opts.validateSchema // false to skip schema validation. Used internally, option validateSchema should be used instead.
  ): Ajv {
    if (Array.isArray(schema)) {
      for (const sch of schema) this.addSchema(sch, undefined, _meta, _validateSchema)
      return this
    }
    let id: string | undefined
    if (typeof schema === "object") {
      const {schemaId} = this.opts
      id = schema[schemaId]
      if (id !== undefined && typeof id != "string") {
        throw new Error(`schema ${schemaId} must be string`)
      }
    }
    key = normalizeId(key || id)
    this._checkUnique(key)
    this.schemas[key] = this._addSchema(schema, _meta, key, _validateSchema, true)
    return this
  }

  // Add schema that will be used to validate other schemas
  // options in META_IGNORE_OPTIONS are alway set to false
  addMetaSchema(
    schema: AnySchemaObject,
    key?: string, // schema key
    _validateSchema = this.opts.validateSchema // false to skip schema validation, can be used to override validateSchema option for meta-schema
  ): Ajv {
    this.addSchema(schema, key, true, _validateSchema)
    return this
  }

  //  Validate schema against its meta-schema
  validateSchema(schema: AnySchema, throwOrLogError?: boolean): boolean | Promise<unknown> {
    if (typeof schema == "boolean") return true
    let $schema: string | AnySchemaObject | undefined
    $schema = schema.$schema
    if ($schema !== undefined && typeof $schema != "string") {
      throw new Error("$schema must be a string")
    }
    $schema = $schema || this.opts.defaultMeta || this.defaultMeta()
    if (!$schema) {
      this.logger.warn("meta-schema not available")
      this.errors = null
      return true
    }
    const valid = this.validate($schema, schema)
    if (!valid && throwOrLogError) {
      const message = "schema is invalid: " + this.errorsText()
      if (this.opts.validateSchema === "log") this.logger.error(message)
      else throw new Error(message)
    }
    return valid
  }

  // Get compiled schema by `key` or `ref`.
  // (`key` that was passed to `addSchema` or full schema reference - `schema.$id` or resolved id)
  getSchema<T = unknown>(keyRef: string): AnyValidateFunction<T> | undefined {
    let sch
    while (typeof (sch = getSchEnv.call(this, keyRef)) == "string") keyRef = sch
    if (sch === undefined) {
      const {schemaId} = this.opts
      const root = new SchemaEnv({schema: {}, schemaId})
      sch = resolveSchema.call(this, root, keyRef)
      if (!sch) return
      this.refs[keyRef] = sch
    }
    return (sch.validate || this._compileSchemaEnv(sch)) as AnyValidateFunction<T> | undefined
  }

  // Remove cached schema(s).
  // If no parameter is passed all schemas but meta-schemas are removed.
  // If RegExp is passed all schemas with key/id matching pattern but meta-schemas are removed.
  // Even if schema is referenced by other schemas it still can be removed as other schemas have local references.
  removeSchema(schemaKeyRef?: AnySchema | string | RegExp): Ajv {
    if (schemaKeyRef instanceof RegExp) {
      this._removeAllSchemas(this.schemas, schemaKeyRef)
      this._removeAllSchemas(this.refs, schemaKeyRef)
      return this
    }
    switch (typeof schemaKeyRef) {
      case "undefined":
        this._removeAllSchemas(this.schemas)
        this._removeAllSchemas(this.refs)
        this._cache.clear()
        return this
      case "string": {
        const sch = getSchEnv.call(this, schemaKeyRef)
        if (typeof sch == "object") this._cache.delete(sch.schema)
        delete this.schemas[schemaKeyRef]
        delete this.refs[schemaKeyRef]
        return this
      }
      case "object": {
        const cacheKey = schemaKeyRef
        this._cache.delete(cacheKey)
        let id = schemaKeyRef[this.opts.schemaId]
        if (id) {
          id = normalizeId(id)
          delete this.schemas[id]
          delete this.refs[id]
        }
        return this
      }
      default:
        throw new Error("ajv.removeSchema: invalid parameter")
    }
  }

  // add "vocabulary" - a collection of keywords
  addVocabulary(definitions: Vocabulary): Ajv {
    for (const def of definitions) this.addKeyword(def)
    return this
  }

  addKeyword(
    kwdOrDef: string | KeywordDefinition,
    def?: KeywordDefinition // deprecated
  ): Ajv {
    let keyword: string | string[]
    if (typeof kwdOrDef == "string") {
      keyword = kwdOrDef
      if (typeof def == "object") {
        this.logger.warn("these parameters are deprecated, see docs for addKeyword")
        def.keyword = keyword
      }
    } else if (typeof kwdOrDef == "object" && def === undefined) {
      def = kwdOrDef
      keyword = def.keyword
      if (Array.isArray(keyword) && !keyword.length) {
        throw new Error("addKeywords: keyword must be string or non-empty array")
      }
    } else {
      throw new Error("invalid addKeywords parameters")
    }

    checkKeyword.call(this, keyword, def)
    if (!def) {
      eachItem(keyword, (kwd) => addRule.call(this, kwd))
      return this
    }
    keywordMetaschema.call(this, def)
    const definition: AddedKeywordDefinition = {
      ...def,
      type: getJSONTypes(def.type),
      schemaType: getJSONTypes(def.schemaType),
    }
    eachItem(
      keyword,
      definition.type.length === 0
        ? (k) => addRule.call(this, k, definition)
        : (k) => definition.type.forEach((t) => addRule.call(this, k, definition, t))
    )
    return this
  }

  getKeyword(keyword: string): AddedKeywordDefinition | boolean {
    const rule = this.RULES.all[keyword]
    return typeof rule == "object" ? rule.definition : !!rule
  }

  // Remove keyword
  removeKeyword(keyword: string): Ajv {
    // TODO return type should be Ajv
    const {RULES} = this
    delete RULES.keywords[keyword]
    delete RULES.all[keyword]
    for (const group of RULES.rules) {
      const i = group.rules.findIndex((rule) => rule.keyword === keyword)
      if (i >= 0) group.rules.splice(i, 1)
    }
    return this
  }

  // Add format
  addFormat(name: string, format: Format): Ajv {
    if (typeof format == "string") format = new RegExp(format)
    this.formats[name] = format
    return this
  }

  errorsText(
    errors: ErrorObject[] | null | undefined = this.errors, // optional array of validation errors
    {separator = ", ", dataVar = "data"}: ErrorsTextOptions = {} // optional options with properties `separator` and `dataVar`
  ): string {
    if (!errors || errors.length === 0) return "No errors"
    return errors
      .map((e) => `${dataVar}${e.instancePath} ${e.message}`)
      .reduce((text, msg) => text + separator + msg)
  }

  $dataMetaSchema(metaSchema: AnySchemaObject, keywordsJsonPointers: string[]): AnySchemaObject {
    const rules = this.RULES.all
    metaSchema = JSON.parse(JSON.stringify(metaSchema))
    for (const jsonPointer of keywordsJsonPointers) {
      const segments = jsonPointer.split("/").slice(1) // first segment is an empty string
      let keywords = metaSchema
      for (const seg of segments) keywords = keywords[seg] as AnySchemaObject

      for (const key in rules) {
        const rule = rules[key]
        if (typeof rule != "object") continue
        const {$data} = rule.definition
        const schema = keywords[key] as AnySchemaObject | undefined
        if ($data && schema) keywords[key] = schemaOrData(schema)
      }
    }

    return metaSchema
  }

  private _removeAllSchemas(schemas: {[Ref in string]?: SchemaEnv | string}, regex?: RegExp): void {
    for (const keyRef in schemas) {
      const sch = schemas[keyRef]
      if (!regex || regex.test(keyRef)) {
        if (typeof sch == "string") {
          delete schemas[keyRef]
        } else if (sch && !sch.meta) {
          this._cache.delete(sch.schema)
          delete schemas[keyRef]
        }
      }
    }
  }

  _addSchema(
    schema: AnySchema,
    meta?: boolean,
    baseId?: string,
    validateSchema = this.opts.validateSchema,
    addSchema = this.opts.addUsedSchema
  ): SchemaEnv {
    let id: string | undefined
    const {schemaId} = this.opts
    if (typeof schema == "object") {
      id = schema[schemaId]
    } else {
      if (this.opts.jtd) throw new Error("schema must be object")
      else if (typeof schema != "boolean") throw new Error("schema must be object or boolean")
    }
    let sch = this._cache.get(schema)
    if (sch !== undefined) return sch

    baseId = normalizeId(id || baseId)
    const localRefs = getSchemaRefs.call(this, schema, baseId)
    sch = new SchemaEnv({schema, schemaId, meta, baseId, localRefs})
    this._cache.set(sch.schema, sch)
    if (addSchema && !baseId.startsWith("#")) {
      // TODO atm it is allowed to overwrite schemas without id (instead of not adding them)
      if (baseId) this._checkUnique(baseId)
      this.refs[baseId] = sch
    }
    if (validateSchema) this.validateSchema(schema, true)
    return sch
  }

  private _checkUnique(id: string): void {
    if (this.schemas[id] || this.refs[id]) {
      throw new Error(`schema with key or id "${id}" already exists`)
    }
  }

  private _compileSchemaEnv(sch: SchemaEnv): AnyValidateFunction {
    if (sch.meta) this._compileMetaSchema(sch)
    else compileSchema.call(this, sch)

    /* istanbul ignore if */
    if (!sch.validate) throw new Error("ajv implementation error")
    return sch.validate
  }

  private _compileMetaSchema(sch: SchemaEnv): void {
    const currentOpts = this.opts
    this.opts = this._metaOpts
    try {
      compileSchema.call(this, sch)
    } finally {
      this.opts = currentOpts
    }
  }
}

export interface ErrorsTextOptions {
  separator?: string
  dataVar?: string
}

function checkOptions(
  this: Ajv,
  checkOpts: OptionsInfo<RemovedOptions | DeprecatedOptions>,
  options: Options & RemovedOptions,
  msg: string,
  log: "warn" | "error" = "error"
): void {
  for (const key in checkOpts) {
    const opt = key as keyof typeof checkOpts
    if (opt in options) this.logger[log](`${msg}: option ${key}. ${checkOpts[opt]}`)
  }
}

function getSchEnv(this: Ajv, keyRef: string): SchemaEnv | string | undefined {
  keyRef = normalizeId(keyRef) // TODO tests fail without this line
  return this.schemas[keyRef] || this.refs[keyRef]
}

function addInitialSchemas(this: Ajv): void {
  const optsSchemas = this.opts.schemas
  if (!optsSchemas) return
  if (Array.isArray(optsSchemas)) this.addSchema(optsSchemas)
  else for (const key in optsSchemas) this.addSchema(optsSchemas[key] as AnySchema, key)
}

function addInitialFormats(this: Ajv): void {
  for (const name in this.opts.formats) {
    const format = this.opts.formats[name]
    if (format) this.addFormat(name, format)
  }
}

function addInitialKeywords(
  this: Ajv,
  defs: Vocabulary | {[K in string]?: KeywordDefinition}
): void {
  if (Array.isArray(defs)) {
    this.addVocabulary(defs)
    return
  }
  this.logger.warn("keywords option as map is deprecated, pass array")
  for (const keyword in defs) {
    const def = defs[keyword] as KeywordDefinition
    if (!def.keyword) def.keyword = keyword
    this.addKeyword(def)
  }
}

function getMetaSchemaOptions(this: Ajv): InstanceOptions {
  const metaOpts = {...this.opts}
  for (const opt of META_IGNORE_OPTIONS) delete metaOpts[opt]
  return metaOpts
}

const noLogs = {log() {}, warn() {}, error() {}}

function getLogger(logger?: Partial<Logger> | false): Logger {
  if (logger === false) return noLogs
  if (logger === undefined) return console
  if (logger.log && logger.warn && logger.error) return logger as Logger
  throw new Error("logger must implement log, warn and error methods")
}

const KEYWORD_NAME = /^[a-z_$][a-z0-9_$:-]*$/i

function checkKeyword(this: Ajv, keyword: string | string[], def?: KeywordDefinition): void {
  const {RULES} = this
  eachItem(keyword, (kwd) => {
    if (RULES.keywords[kwd]) throw new Error(`Keyword ${kwd} is already defined`)
    if (!KEYWORD_NAME.test(kwd)) throw new Error(`Keyword ${kwd} has invalid name`)
  })
  if (!def) return
  if (def.$data && !("code" in def || "validate" in def)) {
    throw new Error('$data keyword must have "code" or "validate" function')
  }
}

function addRule(
  this: Ajv,
  keyword: string,
  definition?: AddedKeywordDefinition,
  dataType?: JSONType
): void {
  const post = definition?.post
  if (dataType && post) throw new Error('keyword with "post" flag cannot have "type"')
  const {RULES} = this
  let ruleGroup = post ? RULES.post : RULES.rules.find(({type: t}) => t === dataType)
  if (!ruleGroup) {
    ruleGroup = {type: dataType, rules: []}
    RULES.rules.push(ruleGroup)
  }
  RULES.keywords[keyword] = true
  if (!definition) return

  const rule: Rule = {
    keyword,
    definition: {
      ...definition,
      type: getJSONTypes(definition.type),
      schemaType: getJSONTypes(definition.schemaType),
    },
  }
  if (definition.before) addBeforeRule.call(this, ruleGroup, rule, definition.before)
  else ruleGroup.rules.push(rule)
  RULES.all[keyword] = rule
  definition.implements?.forEach((kwd) => this.addKeyword(kwd))
}

function addBeforeRule(this: Ajv, ruleGroup: RuleGroup, rule: Rule, before: string): void {
  const i = ruleGroup.rules.findIndex((_rule) => _rule.keyword === before)
  if (i >= 0) {
    ruleGroup.rules.splice(i, 0, rule)
  } else {
    ruleGroup.rules.push(rule)
    this.logger.warn(`rule ${before} is not defined`)
  }
}

function keywordMetaschema(this: Ajv, def: KeywordDefinition): void {
  let {metaSchema} = def
  if (metaSchema === undefined) return
  if (def.$data && this.opts.$data) metaSchema = schemaOrData(metaSchema)
  def.validateSchema = this.compile(metaSchema, true)
}

const $dataRef = {
  $ref: "https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#",
}

function schemaOrData(schema: AnySchema): AnySchemaObject {
  return {anyOf: [schema, $dataRef]}
}


code:
import type {AnySchemaObject, SchemaObject, JTDParser} from "./types"
import type {JTDSchemaType, SomeJTDSchemaType, JTDDataType} from "./types/jtd-schema"
import AjvCore, {CurrentOptions} from "./core"
import jtdVocabulary from "./vocabularies/jtd"
import jtdMetaSchema from "./refs/jtd-schema"
import compileSerializer from "./compile/jtd/serialize"
import compileParser from "./compile/jtd/parse"
import {SchemaEnv} from "./compile"

const META_SCHEMA_ID = "JTD-meta-schema"

type JTDOptions = CurrentOptions & {
  // strict mode options not supported with JTD:
  strict?: never
  allowMatchingProperties?: never
  allowUnionTypes?: never
  validateFormats?: never
  // validation and reporting options not supported with JTD:
  $data?: never
  verbose?: boolean
  $comment?: never
  formats?: never
  loadSchema?: never
  // options to modify validated data:
  useDefaults?: never
  coerceTypes?: never
  // advanced options:
  next?: never
  unevaluated?: never
  dynamicRef?: never
  meta?: boolean
  defaultMeta?: never
  inlineRefs?: boolean
  loopRequired?: never
  multipleOfPrecision?: never
}

export class Ajv extends AjvCore {
  constructor(opts: JTDOptions = {}) {
    super({
      ...opts,
      jtd: true,
    })
  }

  _addVocabularies(): void {
    super._addVocabularies()
    this.addVocabulary(jtdVocabulary)
  }

  _addDefaultMetaSchema(): void {
    super._addDefaultMetaSchema()
    if (!this.opts.meta) return
    this.addMetaSchema(jtdMetaSchema, META_SCHEMA_ID, false)
  }

  defaultMeta(): string | AnySchemaObject | undefined {
    return (this.opts.defaultMeta =
      super.defaultMeta() || (this.getSchema(META_SCHEMA_ID) ? META_SCHEMA_ID : undefined))
  }

  compileSerializer<T = unknown>(schema: SchemaObject): (data: T) => string
  // Separated for type inference to work
  // eslint-disable-next-line @typescript-eslint/unified-signatures
  compileSerializer<T = unknown>(schema: JTDSchemaType<T>): (data: T) => string
  compileSerializer<T = unknown>(schema: SchemaObject): (data: T) => string {
    const sch = this._addSchema(schema)
    return sch.serialize || this._compileSerializer(sch)
  }

  compileParser<T = unknown>(schema: SchemaObject): JTDParser<T>
  // Separated for type inference to work
  // eslint-disable-next-line @typescript-eslint/unified-signatures
  compileParser<T = unknown>(schema: JTDSchemaType<T>): JTDParser<T>
  compileParser<T = unknown>(schema: SchemaObject): JTDParser<T> {
    const sch = this._addSchema(schema)
    return (sch.parse || this._compileParser(sch)) as JTDParser<T>
  }

  private _compileSerializer<T>(sch: SchemaEnv): (data: T) => string {
    compileSerializer.call(this, sch, (sch.schema as AnySchemaObject).definitions || {})
    /* istanbul ignore if */
    if (!sch.serialize) throw new Error("ajv implementation error")
    return sch.serialize
  }

  private _compileParser(sch: SchemaEnv): JTDParser {
    compileParser.call(this, sch, (sch.schema as AnySchemaObject).definitions || {})
    /* istanbul ignore if */
    if (!sch.parse) throw new Error("ajv implementation error")
    return sch.parse
  }
}

module.exports = exports = Ajv
module.exports.Ajv = Ajv
Object.defineProperty(exports, "__esModule", {value: true})

export default Ajv

export {
  Format,
  FormatDefinition,
  AsyncFormatDefinition,
  KeywordDefinition,
  KeywordErrorDefinition,
  CodeKeywordDefinition,
  MacroKeywordDefinition,
  FuncKeywordDefinition,
  Vocabulary,
  Schema,
  SchemaObject,
  AnySchemaObject,
  AsyncSchema,
  AnySchema,
  ValidateFunction,
  AsyncValidateFunction,
  ErrorObject,
  ErrorNoParams,
  JTDParser,
} from "./types"

export {Plugin, Options, CodeOptions, InstanceOptions, Logger, ErrorsTextOptions} from "./core"
export {SchemaCxt, SchemaObjCxt} from "./compile"
export {KeywordCxt} from "./compile/validate"
export {JTDErrorObject} from "./vocabularies/jtd"
export {_, str, stringify, nil, Name, Code, CodeGen, CodeGenOptions} from "./compile/codegen"

export {JTDSchemaType, SomeJTDSchemaType, JTDDataType}
export {JTDOptions}
export {default as ValidationError} from "./runtime/validation_error"
export {default as MissingRefError} from "./compile/ref_error"


description: Meta-schema for $data reference (JSON AnySchema extension proposal)

type: object

type: string

format: relative-json-pointer

format: json-pointer


code:
import type Ajv from "../../core"
import type {AnySchemaObject} from "../../types"
import * as metaSchema from "./schema.json"
import * as applicator from "./meta/applicator.json"
import * as content from "./meta/content.json"
import * as core from "./meta/core.json"
import * as format from "./meta/format.json"
import * as metadata from "./meta/meta-data.json"
import * as validation from "./meta/validation.json"

const META_SUPPORT_DATA = ["/properties"]

export default function addMetaSchema2019(this: Ajv, $data?: boolean): Ajv {
  ;[
    metaSchema,
    applicator,
    content,
    core,
    with$data(this, format),
    metadata,
    with$data(this, validation),
  ].forEach((sch) => this.addMetaSchema(sch, undefined, false))
  return this

  function with$data(ajv: Ajv, sch: AnySchemaObject): AnySchemaObject {
    return $data ? ajv.$dataMetaSchema(sch, META_SUPPORT_DATA) : sch
  }
}


title: Applicator vocabulary meta-schema

type: object boolean

$ref: #/$defs/schemaArray

format: regex

type: array


title: Content vocabulary meta-schema


title: Core vocabulary meta-schema

format: uri-reference

$comment: Non-empty fragments not allowed.

format: uri

type: boolean


title: Format vocabulary meta-schema


title: Meta-data vocabulary meta-schema


title: Validation vocabulary meta-schema

type: number

$ref: #/$defs/nonNegativeInteger

$ref: #/$defs/stringArray

$ref: #/$defs/simpleTypes

type: integer

enum: array boolean integer null number object string


title: Core and Validation specifications meta-schema

$ref: meta/core

$ref: meta/applicator

$ref: meta/validation

$ref: meta/meta-data

$ref: meta/format

$ref: meta/content

$comment: While no longer an official keyword as it is replaced by $defs, this keyword is retained in the meta-schema to prevent incompatible extensions as it remains in common use.

$comment: "dependencies" is no longer a keyword, but schema authors should avoid redefining it to facilitate a smooth transition to "dependentSchemas" and "dependentRequired"

$ref: meta/validation#/$defs/stringArray


code:
import type Ajv from "../../core"
import type {AnySchemaObject} from "../../types"
import * as metaSchema from "./schema.json"
import * as applicator from "./meta/applicator.json"
import * as unevaluated from "./meta/unevaluated.json"
import * as content from "./meta/content.json"
import * as core from "./meta/core.json"
import * as format from "./meta/format-annotation.json"
import * as metadata from "./meta/meta-data.json"
import * as validation from "./meta/validation.json"

const META_SUPPORT_DATA = ["/properties"]

export default function addMetaSchema2020(this: Ajv, $data?: boolean): Ajv {
  ;[
    metaSchema,
    applicator,
    unevaluated,
    content,
    core,
    with$data(this, format),
    metadata,
    with$data(this, validation),
  ].forEach((sch) => this.addMetaSchema(sch, undefined, false))
  return this

  function with$data(ajv: Ajv, sch: AnySchemaObject): AnySchemaObject {
    return $data ? ajv.$dataMetaSchema(sch, META_SUPPORT_DATA) : sch
  }
}


$dynamicAnchor: meta

title: Applicator vocabulary meta-schema

$dynamicRef: #meta


title: Content vocabulary meta-schema


title: Core vocabulary meta-schema

$ref: #/$defs/uriReferenceString

$ref: #/$defs/uriString

$ref: #/$defs/anchorString


title: Format vocabulary meta-schema for annotation results


title: Meta-data vocabulary meta-schema


title: Unevaluated applicator vocabulary meta-schema


title: Validation vocabulary meta-schema


$ref: meta/unevaluated

$ref: meta/format-annotation

$comment: This meta-schema also defines keywords that have appeared in previous drafts in order to prevent incompatible extensions as they remain in common use.

$comment: "definitions" has been replaced by "$defs".

$comment: "dependencies" has been split and replaced by "dependentSchemas" and "dependentRequired" in order to serve their differing semantics.

$comment: "$recursiveAnchor" has been replaced by "$dynamicAnchor".

$ref: meta/core#/$defs/anchorString

$comment: "$recursiveRef" has been replaced by "$dynamicRef".

$ref: meta/core#/$defs/uriReferenceString


title: Core schema meta-schema

$ref: #/definitions/nonNegativeInteger

$ref: #/definitions/schemaArray

$ref: #/definitions/stringArray

$ref: #/definitions/simpleTypes


title: Core schema meta-schema


title: Meta-schema for the security assessment of JSON Schemas

description: If a JSON AnySchema fails validation against this meta-schema, it may be unsafe to validate untrusted data

description: prevent slow validation of large property names

description: prevent slow validation of large non-scalar arrays

enum: object array

description: prevent slow pattern matching of large strings

description: prevent slow format validation of large strings


code:
import {SchemaObject} from "../types"

type MetaSchema = (root: boolean) => SchemaObject

const shared: MetaSchema = (root) => {
  const sch: SchemaObject = {
    nullable: {type: "boolean"},
    metadata: {
      optionalProperties: {
        union: {elements: {ref: "schema"}},
      },
      additionalProperties: true,
    },
  }
  if (root) sch.definitions = {values: {ref: "schema"}}
  return sch
}

const emptyForm: MetaSchema = (root) => ({
  optionalProperties: shared(root),
})

const refForm: MetaSchema = (root) => ({
  properties: {
    ref: {type: "string"},
  },
  optionalProperties: shared(root),
})

const typeForm: MetaSchema = (root) => ({
  properties: {
    type: {
      enum: [
        "boolean",
        "timestamp",
        "string",
        "float32",
        "float64",
        "int8",
        "uint8",
        "int16",
        "uint16",
        "int32",
        "uint32",
      ],
    },
  },
  optionalProperties: shared(root),
})

const enumForm: MetaSchema = (root) => ({
  properties: {
    enum: {elements: {type: "string"}},
  },
  optionalProperties: shared(root),
})

const elementsForm: MetaSchema = (root) => ({
  properties: {
    elements: {ref: "schema"},
  },
  optionalProperties: shared(root),
})

const propertiesForm: MetaSchema = (root) => ({
  properties: {
    properties: {values: {ref: "schema"}},
  },
  optionalProperties: {
    optionalProperties: {values: {ref: "schema"}},
    additionalProperties: {type: "boolean"},
    ...shared(root),
  },
})

const optionalPropertiesForm: MetaSchema = (root) => ({
  properties: {
    optionalProperties: {values: {ref: "schema"}},
  },
  optionalProperties: {
    additionalProperties: {type: "boolean"},
    ...shared(root),
  },
})

const discriminatorForm: MetaSchema = (root) => ({
  properties: {
    discriminator: {type: "string"},
    mapping: {
      values: {
        metadata: {
          union: [propertiesForm(false), optionalPropertiesForm(false)],
        },
      },
    },
  },
  optionalProperties: shared(root),
})

const valuesForm: MetaSchema = (root) => ({
  properties: {
    values: {ref: "schema"},
  },
  optionalProperties: shared(root),
})

const schema: MetaSchema = (root) => ({
  metadata: {
    union: [
      emptyForm,
      refForm,
      typeForm,
      enumForm,
      elementsForm,
      propertiesForm,
      optionalPropertiesForm,
      discriminatorForm,
      valuesForm,
    ].map((s) => s(root)),
  },
})

const jtdMetaSchema: SchemaObject = {
  definitions: {
    schema: schema(false),
  },
  ...schema(true),
}

export default jtdMetaSchema


code:
// https://github.com/ajv-validator/ajv/issues/889
import * as equal from "fast-deep-equal"

type Equal = typeof equal & {code: string}
;(equal as Equal).code = 'require("ajv/dist/runtime/equal").default'

export default equal as Equal


code:
const rxParseJson = /position\s(\d+)(?: \(line \d+ column \d+\))?$/

export function parseJson(s: string, pos: number): unknown {
  let endPos: number | undefined
  parseJson.message = undefined
  let matches: RegExpExecArray | null
  if (pos) s = s.slice(pos)
  try {
    parseJson.position = pos + s.length
    return JSON.parse(s)
  } catch (e) {
    matches = rxParseJson.exec((e as Error).message)
    if (!matches) {
      parseJson.message = "unexpected end"
      return undefined
    }
    endPos = +matches[1]
    const c = s[endPos]
    s = s.slice(0, endPos)
    parseJson.position = pos + endPos
    try {
      return JSON.parse(s)
    } catch (e1) {
      parseJson.message = `unexpected token ${c}`
      return undefined
    }
  }
}

parseJson.message = undefined as string | undefined
parseJson.position = 0 as number
parseJson.code = 'require("ajv/dist/runtime/parseJson").parseJson'

export function parseJsonNumber(s: string, pos: number, maxDigits?: number): number | undefined {
  let numStr = ""
  let c: string
  parseJsonNumber.message = undefined
  if (s[pos] === "-") {
    numStr += "-"
    pos++
  }
  if (s[pos] === "0") {
    numStr += "0"
    pos++
  } else {
    if (!parseDigits(maxDigits)) {
      errorMessage()
      return undefined
    }
  }
  if (maxDigits) {
    parseJsonNumber.position = pos
    return +numStr
  }
  if (s[pos] === ".") {
    numStr += "."
    pos++
    if (!parseDigits()) {
      errorMessage()
      return undefined
    }
  }
  if (((c = s[pos]), c === "e" || c === "E")) {
    numStr += "e"
    pos++
    if (((c = s[pos]), c === "+" || c === "-")) {
      numStr += c
      pos++
    }
    if (!parseDigits()) {
      errorMessage()
      return undefined
    }
  }
  parseJsonNumber.position = pos
  return +numStr

  function parseDigits(maxLen?: number): boolean {
    let digit = false
    while (((c = s[pos]), c >= "0" && c <= "9" && (maxLen === undefined || maxLen-- > 0))) {
      digit = true
      numStr += c
      pos++
    }
    return digit
  }

  function errorMessage(): void {
    parseJsonNumber.position = pos
    parseJsonNumber.message = pos < s.length ? `unexpected token ${s[pos]}` : "unexpected end"
  }
}

parseJsonNumber.message = undefined as string | undefined
parseJsonNumber.position = 0 as number
parseJsonNumber.code = 'require("ajv/dist/runtime/parseJson").parseJsonNumber'

const escapedChars: {[X in string]?: string} = {
  b: "\b",
  f: "\f",
  n: "\n",
  r: "\r",
  t: "\t",
  '"': '"',
  "/": "/",
  "\\": "\\",
}

const CODE_A: number = "a".charCodeAt(0)
const CODE_0: number = "0".charCodeAt(0)

export function parseJsonString(s: string, pos: number): string | undefined {
  let str = ""
  let c: string | undefined
  parseJsonString.message = undefined
  // eslint-disable-next-line no-constant-condition, @typescript-eslint/no-unnecessary-condition
  while (true) {
    c = s[pos++]
    if (c === '"') break
    if (c === "\\") {
      c = s[pos]
      if (c in escapedChars) {
        str += escapedChars[c]
        pos++
      } else if (c === "u") {
        pos++
        let count = 4
        let code = 0
        while (count--) {
          code <<= 4
          c = s[pos]
          // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition
          if (c === undefined) {
            errorMessage("unexpected end")
            return undefined
          }
          c = c.toLowerCase()
          if (c >= "a" && c <= "f") {
            code += c.charCodeAt(0) - CODE_A + 10
          } else if (c >= "0" && c <= "9") {
            code += c.charCodeAt(0) - CODE_0
          } else {
            errorMessage(`unexpected token ${c}`)
            return undefined
          }
          pos++
        }
        str += String.fromCharCode(code)
      } else {
        errorMessage(`unexpected token ${c}`)
        return undefined
      }
      // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition
    } else if (c === undefined) {
      errorMessage("unexpected end")
      return undefined
    } else {
      if (c.charCodeAt(0) >= 0x20) {
        str += c
      } else {
        errorMessage(`unexpected token ${c}`)
        return undefined
      }
    }
  }
  parseJsonString.position = pos
  return str

  function errorMessage(msg: string): void {
    parseJsonString.position = pos
    parseJsonString.message = msg
  }
}

parseJsonString.message = undefined as string | undefined
parseJsonString.position = 0 as number
parseJsonString.code = 'require("ajv/dist/runtime/parseJson").parseJsonString'


code:
const rxEscapable =
  // eslint-disable-next-line no-control-regex, no-misleading-character-class
  /[\\"\u0000-\u001f\u007f-\u009f\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g

const escaped: {[K in string]?: string} = {
  "\b": "\\b",
  "\t": "\\t",
  "\n": "\\n",
  "\f": "\\f",
  "\r": "\\r",
  '"': '\\"',
  "\\": "\\\\",
}

export default function quote(s: string): string {
  rxEscapable.lastIndex = 0
  return (
    '"' +
    (rxEscapable.test(s)
      ? s.replace(rxEscapable, (a) => {
          const c = escaped[a]
          return typeof c === "string"
            ? c
            : "\\u" + ("0000" + a.charCodeAt(0).toString(16)).slice(-4)
        })
      : s) +
    '"'
  )
}

quote.code = 'require("ajv/dist/runtime/quote").default'


code:
import * as re2 from "re2"

type Re2 = typeof re2 & {code: string}
;(re2 as Re2).code = 'require("ajv/dist/runtime/re2").default'

export default re2 as Re2


code:
const DT_SEPARATOR = /t|\s/i
const DATE = /^(\d\d\d\d)-(\d\d)-(\d\d)$/
const TIME = /^(\d\d):(\d\d):(\d\d)(?:\.\d+)?(?:z|([+-]\d\d)(?::?(\d\d))?)$/i
const DAYS = [0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]

export default function validTimestamp(str: string, allowDate: boolean): boolean {
  // http://tools.ietf.org/html/rfc3339#section-5.6
  const dt: string[] = str.split(DT_SEPARATOR)
  return (
    (dt.length === 2 && validDate(dt[0]) && validTime(dt[1])) ||
    (allowDate && dt.length === 1 && validDate(dt[0]))
  )
}

function validDate(str: string): boolean {
  const matches: string[] | null = DATE.exec(str)
  if (!matches) return false
  const y: number = +matches[1]
  const m: number = +matches[2]
  const d: number = +matches[3]
  return (
    m >= 1 &&
    m <= 12 &&
    d >= 1 &&
    (d <= DAYS[m] ||
      // leap year: https://tools.ietf.org/html/rfc3339#appendix-C
      (m === 2 && d === 29 && (y % 100 === 0 ? y % 400 === 0 : y % 4 === 0)))
  )
}

function validTime(str: string): boolean {
  const matches: string[] | null = TIME.exec(str)
  if (!matches) return false
  const hr: number = +matches[1]
  const min: number = +matches[2]
  const sec: number = +matches[3]
  const tzH: number = +(matches[4] || 0)
  const tzM: number = +(matches[5] || 0)
  return (
    (hr <= 23 && min <= 59 && sec <= 59) ||
    // leap second
    (hr - tzH === 23 && min - tzM === 59 && sec === 60)
  )
}

validTimestamp.code = 'require("ajv/dist/runtime/timestamp").default'


code:
// https://mathiasbynens.be/notes/javascript-encoding
// https://github.com/bestiejs/punycode.js - punycode.ucs2.decode
export default function ucs2length(str: string): number {
  const len = str.length
  let length = 0
  let pos = 0
  let value: number
  while (pos < len) {
    length++
    value = str.charCodeAt(pos++)
    if (value >= 0xd800 && value <= 0xdbff && pos < len) {
      // high surrogate, and there is a next character
      value = str.charCodeAt(pos)
      if ((value & 0xfc00) === 0xdc00) pos++ // low surrogate
    }
  }
  return length
}

ucs2length.code = 'require("ajv/dist/runtime/ucs2length").default'


code:
import * as uri from "uri-js"

type URI = typeof uri & {code: string}
;(uri as URI).code = 'require("ajv/dist/runtime/uri").default'

export default uri as URI


code:
import type {ErrorObject} from "../types"

export default class ValidationError extends Error {
  readonly errors: Partial<ErrorObject>[]
  readonly ajv: true
  readonly validation: true

  constructor(errors: Partial<ErrorObject>[]) {
    super("validation failed")
    this.errors = errors
    this.ajv = this.validation = true
  }
}


code:
import type AjvCore from "../core"
import type {AnyValidateFunction, SourceCode} from "../types"
import type {SchemaEnv} from "../compile"
import {UsedScopeValues, UsedValueState, ValueScopeName, varKinds} from "../compile/codegen/scope"
import {_, nil, _Code, Code, getProperty, getEsmExportName} from "../compile/codegen/code"

function standaloneCode(
  ajv: AjvCore,
  refsOrFunc?: {[K in string]?: string} | AnyValidateFunction
): string {
  if (!ajv.opts.code.source) {
    throw new Error("moduleCode: ajv instance must have code.source option")
  }
  const {_n} = ajv.scope.opts
  return typeof refsOrFunc == "function"
    ? funcExportCode(refsOrFunc.source)
    : refsOrFunc !== undefined
    ? multiExportsCode<string>(refsOrFunc, getValidate)
    : multiExportsCode<SchemaEnv>(ajv.schemas, (sch) =>
        sch.meta ? undefined : ajv.compile(sch.schema)
      )

  function getValidate(id: string): AnyValidateFunction {
    const v = ajv.getSchema(id)
    if (!v) throw new Error(`moduleCode: no schema with id ${id}`)
    return v
  }

  function funcExportCode(source?: SourceCode): string {
    const usedValues: UsedScopeValues = {}
    const n = source?.validateName
    const vCode = validateCode(usedValues, source)
    if (ajv.opts.code.esm) {
      // Always do named export as `validate` rather than the variable `n` which is `validateXX` for known export value
      return `"use strict";${_n}export const validate = ${n};${_n}export default ${n};${_n}${vCode}`
    }
    return `"use strict";${_n}module.exports = ${n};${_n}module.exports.default = ${n};${_n}${vCode}`
  }

  function multiExportsCode<T extends SchemaEnv | string>(
    schemas: {[K in string]?: T},
    getValidateFunc: (schOrId: T) => AnyValidateFunction | undefined
  ): string {
    const usedValues: UsedScopeValues = {}
    let code = _`"use strict";`
    for (const name in schemas) {
      const v = getValidateFunc(schemas[name] as T)
      if (v) {
        const vCode = validateCode(usedValues, v.source)
        const exportSyntax = ajv.opts.code.esm
          ? _`export const ${getEsmExportName(name)}`
          : _`exports${getProperty(name)}`
        code = _`${code}${_n}${exportSyntax} = ${v.source?.validateName};${_n}${vCode}`
      }
    }
    return `${code}`
  }

  function validateCode(usedValues: UsedScopeValues, s?: SourceCode): Code {
    if (!s) throw new Error('moduleCode: function does not have "source" property')
    if (usedState(s.validateName) === UsedValueState.Completed) return nil
    setUsedState(s.validateName, UsedValueState.Started)

    const scopeCode = ajv.scope.scopeCode(s.scopeValues, usedValues, refValidateCode)
    const code = new _Code(`${scopeCode}${_n}${s.validateCode}`)
    return s.evaluated ? _`${code}${s.validateName}.evaluated = ${s.evaluated};${_n}` : code

    function refValidateCode(n: ValueScopeName): Code | undefined {
      const vRef = n.value?.ref
      if (n.prefix === "validate" && typeof vRef == "function") {
        const v = vRef as AnyValidateFunction
        return validateCode(usedValues, v.source)
      } else if ((n.prefix === "root" || n.prefix === "wrapper") && typeof vRef == "object") {
        const {validate, validateName} = vRef as SchemaEnv
        if (!validateName) throw new Error("ajv internal error")
        const def = ajv.opts.code.es5 ? varKinds.var : varKinds.const
        const wrapper = _`${def} ${n} = {validate: ${validateName}};`
        if (usedState(validateName) === UsedValueState.Started) return wrapper
        const vCode = validateCode(usedValues, validate?.source)
        return _`${wrapper}${_n}${vCode}`
      }
      return undefined
    }

    function usedState(name: ValueScopeName): UsedValueState | undefined {
      return usedValues[name.prefix]?.get(name)
    }

    function setUsedState(name: ValueScopeName, state: UsedValueState): void {
      const {prefix} = name
      const names = (usedValues[prefix] = usedValues[prefix] || new Map())
      names.set(name, state)
    }
  }
}

module.exports = exports = standaloneCode
Object.defineProperty(exports, "__esModule", {value: true})

export default standaloneCode


code:
import Ajv, {AnySchema, AnyValidateFunction, ErrorObject} from "../core"
import standaloneCode from "."
import * as requireFromString from "require-from-string"

export default class AjvPack {
  errors?: ErrorObject[] | null // errors from the last validation
  constructor(readonly ajv: Ajv) {}

  validate(schemaKeyRef: AnySchema | string, data: unknown): boolean | Promise<unknown> {
    return Ajv.prototype.validate.call(this, schemaKeyRef, data)
  }

  compile<T = unknown>(schema: AnySchema, meta?: boolean): AnyValidateFunction<T> {
    return this.getStandalone(this.ajv.compile<T>(schema, meta))
  }

  getSchema<T = unknown>(keyRef: string): AnyValidateFunction<T> | undefined {
    const v = this.ajv.getSchema<T>(keyRef)
    if (!v) return undefined
    return this.getStandalone(v)
  }

  private getStandalone<T = unknown>(v: AnyValidateFunction<T>): AnyValidateFunction<T> {
    return requireFromString(standaloneCode(this.ajv, v)) as AnyValidateFunction<T>
  }

  addSchema(...args: Parameters<typeof Ajv.prototype.addSchema>): AjvPack {
    this.ajv.addSchema.call(this.ajv, ...args)
    return this
  }

  addKeyword(...args: Parameters<typeof Ajv.prototype.addKeyword>): AjvPack {
    this.ajv.addKeyword.call(this.ajv, ...args)
    return this
  }
}