id
int64 0
3.78k
| code
stringlengths 13
37.9k
| declarations
stringlengths 16
64.6k
|
---|---|---|
2,100 | function invalidSchema(schema: SchemaObject, error: any): void {
ajvs.forEach((ajv) => assert.throws(() => ajv.compile(schema), error))
} | interface SchemaObject extends _SchemaObject {
id?: string
$id?: string
$schema?: string
$async?: false
[x: string]: any // TODO
} |
2,101 | function runTest({instances, draft, tests, skip = [], remotes = {}}: SchemaTest) {
for (const ajv of instances) {
ajv.opts.code.source = true
if (draft === 6) {
ajv.addMetaSchema(draft6MetaSchema)
ajv.opts.defaultMeta = "http://json-schema.org/draft-06/schema#"
}
for (const id in remoteRefs) ajv.addSchema(remoteRefs[id], id)
for (const id in remotes) ajv.addSchema(remotes[id], id)
ajvFormats(ajv)
}
jsonSchemaTest(withStandalone(instances), {
description: `JSON-Schema Test Suite draft-${draft}: ${instances.length} ajv instances with different options`,
suites: {tests},
only: [],
skip,
assert: chai.assert,
afterError,
afterEach,
cwd: __dirname,
hideFolder: `draft${draft}/`,
timeout: 30000,
})
} | interface SchemaTest {
instances: Ajv[]
draft: number
tests: TestSuite[]
skip?: string[]
remotes?: Record<string, any>
} |
2,102 | function testTimestamp(
opts: JTDOptions,
valid: {Date: boolean; datetime: boolean; date: boolean}
) {
const ajv = new _AjvJTD(opts)
const schema = {type: "timestamp"}
const validate = ajv.compile(schema)
assert.strictEqual(validate(new Date()), valid.Date)
assert.strictEqual(validate("2021-05-03T05:24:43.906Z"), valid.datetime)
assert.strictEqual(validate("2021-05-03"), valid.date)
assert.strictEqual(validate("foo"), false)
} | 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
} |
2,103 | function badEvenCode(cxt: KeywordCxt) {
const op = cxt.schema ? _`===` : _`!===` // invalid on purpose
cxt.pass(_`${cxt.data} % 2 ${op} 0`)
} | 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
}
}
} |
2,104 | function passValidationThrowCompile(schema: SchemaObject) {
ajv.validateSchema(schema).should.equal(true)
should.throw(() => {
ajv.compile(schema)
}, /value must be/)
} | interface SchemaObject extends _SchemaObject {
id?: string
$id?: string
$schema?: string
$async?: false
[x: string]: any // TODO
} |
2,105 | function afterError(res: TestResult): void {
console.log("ajv options:", res.validator.opts)
} | interface TestResult {
validator: Ajv
schema: AnySchema
data: unknown
valid: boolean
expected: boolean
errors: ErrorObject[] | null
passed: boolean // true if valid == expected
} |
2,106 | function afterEach(res: TestResult): void {
// console.log(res.errors);
res.valid.should.be.a("boolean")
if (res.valid === true) {
should.equal(res.errors, null)
} else {
const errs = res.errors as ErrorObject[]
errs.should.be.an("array")
for (const err of errs) {
err.should.be.an("object")
}
}
} | interface TestResult {
validator: Ajv
schema: AnySchema
data: unknown
valid: boolean
expected: boolean
errors: ErrorObject[] | null
passed: boolean // true if valid == expected
} |
2,107 | function getAjvAllInstances(options: Options, extraOpts: Options = {}): AjvCore[] {
return [...getAjvs(_Ajv), ...getAjvs(_Ajv2019)]
function getAjvs(Ajv: typeof AjvCore): AjvCore[] {
return getAjvInstances(Ajv, options, extraOpts)
}
} | type Options = CurrentOptions & DeprecatedOptions |
2,108 | (i: Name) => gen.code(_`console.log(${xs}[${i}])`) | class Name extends _CodeOrName {
readonly str: string
constructor(s: string) {
super()
if (!IDENTIFIER.test(s)) throw new Error("CodeGen: name must be a valid identifier")
this.str = s
}
toString(): string {
return this.str
}
emptyStr(): boolean {
return false
}
get names(): UsedNames {
return {[this.str]: 1}
}
} |
2,109 | (x: Name) => gen.code(_`console.log(${x})`) | class Name extends _CodeOrName {
readonly str: string
constructor(s: string) {
super()
if (!IDENTIFIER.test(s)) throw new Error("CodeGen: name must be a valid identifier")
this.str = s
}
toString(): string {
return this.str
}
emptyStr(): boolean {
return false
}
get names(): UsedNames {
return {[this.str]: 1}
}
} |
2,110 | (x: Name) => _gen.code(_`console.log(${x})`) | class Name extends _CodeOrName {
readonly str: string
constructor(s: string) {
super()
if (!IDENTIFIER.test(s)) throw new Error("CodeGen: name must be a valid identifier")
this.str = s
}
toString(): string {
return this.str
}
emptyStr(): boolean {
return false
}
get names(): UsedNames {
return {[this.str]: 1}
}
} |
2,111 | function getGen(opts?: CodeGenOptions): CodeGen {
return new CodeGen(new ValueScope({scope: {}}), opts)
} | interface CodeGenOptions {
es5?: boolean
lines?: boolean
ownProperties?: boolean
} |
2,112 | function test(_ajv: Ajv) {
const schema = {
type: "object",
required: {$data: "0/req"},
properties: {
req: {},
foo: {},
bar: {},
},
}
const validate = _ajv.compile(schema)
shouldBeValid(validate, {req: ["foo", "bar"], foo: 1, bar: 2})
shouldBeInvalid(validate, {req: ["foo", "bar"], foo: 1})
shouldBeError(
validate.errors?.[0],
"required",
"#/required",
"",
"must have required property 'bar'",
{missingProperty: "bar"}
)
shouldBeInvalid(validate, {req: "invalid"})
shouldBeError(
validate.errors?.[0],
"required",
"#/required",
"",
'"required" keyword must be array ($data)',
{}
)
} | 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
validate<N extends never, T extends SomeJTDSchemaType>(
schema: T,
data: unknown
): data is JTDDataType<T>
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
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
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
}
}
} |
2,113 | function test(_ajv: Ajv) {
const schema = {
type: "object",
required: {$data: "0/req"},
properties: {
req: {},
foo: {},
bar: {},
},
}
const validate = _ajv.compile(schema)
shouldBeValid(validate, {req: ["foo", "bar"], foo: 1, bar: 2})
shouldBeInvalid(validate, {req: ["foo", "bar"], foo: 1})
shouldBeError(
validate.errors?.[0],
"required",
"#/required",
"",
"must have required property 'bar'",
{missingProperty: "bar"}
)
shouldBeInvalid(validate, {req: "invalid"})
shouldBeError(
validate.errors?.[0],
"required",
"#/required",
"",
'"required" keyword must be array ($data)',
{}
)
} | 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
}
} |
2,114 | function test(_ajv: Ajv) {
const schema = {
type: "object",
required: {$data: "0/req"},
properties: {
req: {},
foo: {},
bar: {},
},
}
const validate = _ajv.compile(schema)
shouldBeValid(validate, {req: ["foo", "bar"], foo: 1, bar: 2})
shouldBeInvalid(validate, {req: ["foo", "bar"], foo: 1})
shouldBeError(
validate.errors?.[0],
"required",
"#/required",
"",
"must have required property 'bar'",
{missingProperty: "bar"}
)
shouldBeInvalid(validate, {req: "invalid"})
shouldBeError(
validate.errors?.[0],
"required",
"#/required",
"",
'"required" keyword must be array ($data)',
{}
)
} | class Ajv extends AjvCore {
_addVocabularies(): void {
super._addVocabularies()
draft7Vocabularies.forEach((v) => this.addVocabulary(v))
if (this.opts.discriminator) this.addKeyword(discriminator)
}
_addDefaultMetaSchema(): void {
super._addDefaultMetaSchema()
if (!this.opts.meta) return
const metaSchema = this.opts.$data
? this.$dataMetaSchema(draft7MetaSchema, META_SUPPORT_DATA)
: draft7MetaSchema
this.addMetaSchema(metaSchema, META_SCHEMA_ID, false)
this.refs["http://json-schema.org/schema"] = META_SCHEMA_ID
}
defaultMeta(): string | AnySchemaObject | undefined {
return (this.opts.defaultMeta =
super.defaultMeta() || (this.getSchema(META_SCHEMA_ID) ? META_SCHEMA_ID : undefined))
}
} |
2,115 | function test(_ajv: Ajv): void {
const schema = {
type: "object",
required: ["a"],
properties: {
a: {type: "string"},
},
}
const validate = _ajv.compile(schema)
shouldBeValid(validate, {a: "abc"})
shouldBeInvalid(validate, {})
shouldBeError(
validate.errors?.[0],
"required",
"#/required",
"",
"must have required property 'a'",
{missingProperty: "a"}
)
} | 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
validate<N extends never, T extends SomeJTDSchemaType>(
schema: T,
data: unknown
): data is JTDDataType<T>
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
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
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
}
}
} |
2,116 | function test(_ajv: Ajv): void {
const schema = {
type: "object",
required: ["a"],
properties: {
a: {type: "string"},
},
}
const validate = _ajv.compile(schema)
shouldBeValid(validate, {a: "abc"})
shouldBeInvalid(validate, {})
shouldBeError(
validate.errors?.[0],
"required",
"#/required",
"",
"must have required property 'a'",
{missingProperty: "a"}
)
} | 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
}
} |
2,117 | function test(_ajv: Ajv): void {
const schema = {
type: "object",
required: ["a"],
properties: {
a: {type: "string"},
},
}
const validate = _ajv.compile(schema)
shouldBeValid(validate, {a: "abc"})
shouldBeInvalid(validate, {})
shouldBeError(
validate.errors?.[0],
"required",
"#/required",
"",
"must have required property 'a'",
{missingProperty: "a"}
)
} | class Ajv extends AjvCore {
_addVocabularies(): void {
super._addVocabularies()
draft7Vocabularies.forEach((v) => this.addVocabulary(v))
if (this.opts.discriminator) this.addKeyword(discriminator)
}
_addDefaultMetaSchema(): void {
super._addDefaultMetaSchema()
if (!this.opts.meta) return
const metaSchema = this.opts.$data
? this.$dataMetaSchema(draft7MetaSchema, META_SUPPORT_DATA)
: draft7MetaSchema
this.addMetaSchema(metaSchema, META_SCHEMA_ID, false)
this.refs["http://json-schema.org/schema"] = META_SCHEMA_ID
}
defaultMeta(): string | AnySchemaObject | undefined {
return (this.opts.defaultMeta =
super.defaultMeta() || (this.getSchema(META_SCHEMA_ID) ? META_SCHEMA_ID : undefined))
}
} |
2,118 | function test(_ajv: Ajv, numErrors: number) {
const validate = _ajv.compile(schema)
shouldBeValid(validate, data)
shouldBeInvalid(validate, invalidData, numErrors)
shouldBeError(
validate.errors?.[0],
"pattern",
"#/propertyNames/pattern",
"",
'must match pattern "bar"'
)
shouldBeError(
validate.errors?.[1],
"propertyNames",
"#/propertyNames",
"",
"property name must be valid"
)
if (numErrors === 4) {
shouldBeError(
validate.errors?.[2],
"pattern",
"#/propertyNames/pattern",
"",
'must match pattern "bar"'
)
shouldBeError(
validate.errors?.[3],
"propertyNames",
"#/propertyNames",
"",
"property name must be valid"
)
}
} | 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
validate<N extends never, T extends SomeJTDSchemaType>(
schema: T,
data: unknown
): data is JTDDataType<T>
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
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
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
}
}
} |
2,119 | function test(_ajv: Ajv, numErrors: number) {
const validate = _ajv.compile(schema)
shouldBeValid(validate, data)
shouldBeInvalid(validate, invalidData, numErrors)
shouldBeError(
validate.errors?.[0],
"pattern",
"#/propertyNames/pattern",
"",
'must match pattern "bar"'
)
shouldBeError(
validate.errors?.[1],
"propertyNames",
"#/propertyNames",
"",
"property name must be valid"
)
if (numErrors === 4) {
shouldBeError(
validate.errors?.[2],
"pattern",
"#/propertyNames/pattern",
"",
'must match pattern "bar"'
)
shouldBeError(
validate.errors?.[3],
"propertyNames",
"#/propertyNames",
"",
"property name must be valid"
)
}
} | 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
}
} |
2,120 | function test(_ajv: Ajv, numErrors: number) {
const validate = _ajv.compile(schema)
shouldBeValid(validate, data)
shouldBeInvalid(validate, invalidData, numErrors)
shouldBeError(
validate.errors?.[0],
"pattern",
"#/propertyNames/pattern",
"",
'must match pattern "bar"'
)
shouldBeError(
validate.errors?.[1],
"propertyNames",
"#/propertyNames",
"",
"property name must be valid"
)
if (numErrors === 4) {
shouldBeError(
validate.errors?.[2],
"pattern",
"#/propertyNames/pattern",
"",
'must match pattern "bar"'
)
shouldBeError(
validate.errors?.[3],
"propertyNames",
"#/propertyNames",
"",
"property name must be valid"
)
}
} | class Ajv extends AjvCore {
_addVocabularies(): void {
super._addVocabularies()
draft7Vocabularies.forEach((v) => this.addVocabulary(v))
if (this.opts.discriminator) this.addKeyword(discriminator)
}
_addDefaultMetaSchema(): void {
super._addDefaultMetaSchema()
if (!this.opts.meta) return
const metaSchema = this.opts.$data
? this.$dataMetaSchema(draft7MetaSchema, META_SUPPORT_DATA)
: draft7MetaSchema
this.addMetaSchema(metaSchema, META_SCHEMA_ID, false)
this.refs["http://json-schema.org/schema"] = META_SCHEMA_ID
}
defaultMeta(): string | AnySchemaObject | undefined {
return (this.opts.defaultMeta =
super.defaultMeta() || (this.getSchema(META_SCHEMA_ID) ? META_SCHEMA_ID : undefined))
}
} |
2,121 | function test(_ajv: Ajv, numErrors?: number) {
const schema = {
type: ["array", "object"],
minItems: 2,
minProperties: 2,
minimum: 5, // this keyword would log/throw in strictTypes mode
}
const validate = _ajv.compile(schema)
shouldBeValid(validate, [1, 2])
shouldBeValid(validate, {foo: 1, bar: 2})
shouldBeInvalid(validate, [1])
shouldBeInvalid(validate, {foo: 1})
shouldBeInvalid(validate, 5) // fails because number not allowed
shouldBeInvalid(validate, 4, numErrors)
} | 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
validate<N extends never, T extends SomeJTDSchemaType>(
schema: T,
data: unknown
): data is JTDDataType<T>
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
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
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
}
}
} |
2,122 | function test(_ajv: Ajv, numErrors?: number) {
const schema = {
type: ["array", "object"],
minItems: 2,
minProperties: 2,
minimum: 5, // this keyword would log/throw in strictTypes mode
}
const validate = _ajv.compile(schema)
shouldBeValid(validate, [1, 2])
shouldBeValid(validate, {foo: 1, bar: 2})
shouldBeInvalid(validate, [1])
shouldBeInvalid(validate, {foo: 1})
shouldBeInvalid(validate, 5) // fails because number not allowed
shouldBeInvalid(validate, 4, numErrors)
} | 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
}
} |
2,123 | function test(_ajv: Ajv, numErrors?: number) {
const schema = {
type: ["array", "object"],
minItems: 2,
minProperties: 2,
minimum: 5, // this keyword would log/throw in strictTypes mode
}
const validate = _ajv.compile(schema)
shouldBeValid(validate, [1, 2])
shouldBeValid(validate, {foo: 1, bar: 2})
shouldBeInvalid(validate, [1])
shouldBeInvalid(validate, {foo: 1})
shouldBeInvalid(validate, 5) // fails because number not allowed
shouldBeInvalid(validate, 4, numErrors)
} | class Ajv extends AjvCore {
_addVocabularies(): void {
super._addVocabularies()
draft7Vocabularies.forEach((v) => this.addVocabulary(v))
if (this.opts.discriminator) this.addKeyword(discriminator)
}
_addDefaultMetaSchema(): void {
super._addDefaultMetaSchema()
if (!this.opts.meta) return
const metaSchema = this.opts.$data
? this.$dataMetaSchema(draft7MetaSchema, META_SUPPORT_DATA)
: draft7MetaSchema
this.addMetaSchema(metaSchema, META_SCHEMA_ID, false)
this.refs["http://json-schema.org/schema"] = META_SCHEMA_ID
}
defaultMeta(): string | AnySchemaObject | undefined {
return (this.opts.defaultMeta =
super.defaultMeta() || (this.getSchema(META_SCHEMA_ID) ? META_SCHEMA_ID : undefined))
}
} |
2,124 | function prepareTest(_ajv: Ajv, schema) {
validate = _ajv.compile(schema)
numErrors = _ajv.opts.allErrors ? 2 : 1
} | 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
validate<N extends never, T extends SomeJTDSchemaType>(
schema: T,
data: unknown
): data is JTDDataType<T>
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
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
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
}
}
} |
2,125 | function prepareTest(_ajv: Ajv, schema) {
validate = _ajv.compile(schema)
numErrors = _ajv.opts.allErrors ? 2 : 1
} | 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
}
} |
2,126 | function prepareTest(_ajv: Ajv, schema) {
validate = _ajv.compile(schema)
numErrors = _ajv.opts.allErrors ? 2 : 1
} | class Ajv extends AjvCore {
_addVocabularies(): void {
super._addVocabularies()
draft7Vocabularies.forEach((v) => this.addVocabulary(v))
if (this.opts.discriminator) this.addKeyword(discriminator)
}
_addDefaultMetaSchema(): void {
super._addDefaultMetaSchema()
if (!this.opts.meta) return
const metaSchema = this.opts.$data
? this.$dataMetaSchema(draft7MetaSchema, META_SUPPORT_DATA)
: draft7MetaSchema
this.addMetaSchema(metaSchema, META_SCHEMA_ID, false)
this.refs["http://json-schema.org/schema"] = META_SCHEMA_ID
}
defaultMeta(): string | AnySchemaObject | undefined {
return (this.opts.defaultMeta =
super.defaultMeta() || (this.getSchema(META_SCHEMA_ID) ? META_SCHEMA_ID : undefined))
}
} |
2,127 | function _getAjvInstances(opts: Options, useOpts: Options): AjvCore[] {
const optNames = Object.keys(opts)
if (optNames.length) {
opts = Object.assign({}, opts)
const useOpts1 = Object.assign({}, useOpts)
const optName = optNames[0]
useOpts1[optName] = opts[optName]
delete opts[optName]
return [..._getAjvInstances(opts, useOpts), ..._getAjvInstances(opts, useOpts1)]
}
return [new _Ajv(useOpts)]
} | type Options = CurrentOptions & DeprecatedOptions |
2,128 | (e1: JTDError, e2: JTDError) =>
e1.schemaPath.localeCompare(e2.schemaPath) ||
e1.instancePath.localeCompare(e2.instancePath) | interface JTDError {
instancePath: string
schemaPath: string
} |
2,129 | function _it({only, skip}: JSONParseTest): TestFunc {
return skip ? it.skip : only ? it.only : it
} | interface JSONParseTest {
name: string
valid: boolean | null
json: string
data?: unknown
only?: boolean
skip?: boolean
} |
2,130 | function shouldParse(parse: JTDParser, str: string, res: unknown): void {
assert.deepStrictEqual(parse(str), res)
assert.strictEqual(parse.message, undefined)
assert.strictEqual(parse.position, undefined)
} | interface JTDParser<T = unknown> {
(json: string): T | undefined
message?: string
position?: number
} |
2,131 | function shouldFail(parse: JTDParser, str: string): void {
assert.strictEqual(parse(str), undefined)
assert.strictEqual(typeof parse.message, "string")
assert.strictEqual(typeof parse.position, "number")
} | interface JTDParser<T = unknown> {
(json: string): T | undefined
message?: string
position?: number
} |
2,132 | function addAsyncFormatsAndKeywords(ajv: Ajv) {
ajv.addFormat("date", /^\d\d\d\d-[0-1]\d-[0-3]\d$/)
ajv.addFormat("english_word", {
async: true,
validate: checkWordOnServer,
})
ajv.addKeyword({
keyword: "idExists",
async: true,
type: "number",
validate: checkIdExists,
errors: false,
})
ajv.addKeyword({
keyword: "idExistsWithError",
async: true,
type: "number",
validate: checkIdExistsWithError,
errors: true,
})
ajv.addKeyword({
keyword: "idExistsCompiled",
async: true,
type: "number",
compile: compileCheckIdExists,
})
} | 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
validate<N extends never, T extends SomeJTDSchemaType>(
schema: T,
data: unknown
): data is JTDDataType<T>
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
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
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
}
}
} |
2,133 | function addAsyncFormatsAndKeywords(ajv: Ajv) {
ajv.addFormat("date", /^\d\d\d\d-[0-1]\d-[0-3]\d$/)
ajv.addFormat("english_word", {
async: true,
validate: checkWordOnServer,
})
ajv.addKeyword({
keyword: "idExists",
async: true,
type: "number",
validate: checkIdExists,
errors: false,
})
ajv.addKeyword({
keyword: "idExistsWithError",
async: true,
type: "number",
validate: checkIdExistsWithError,
errors: true,
})
ajv.addKeyword({
keyword: "idExistsCompiled",
async: true,
type: "number",
compile: compileCheckIdExists,
})
} | 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
}
} |
2,134 | function addAsyncFormatsAndKeywords(ajv: Ajv) {
ajv.addFormat("date", /^\d\d\d\d-[0-1]\d-[0-3]\d$/)
ajv.addFormat("english_word", {
async: true,
validate: checkWordOnServer,
})
ajv.addKeyword({
keyword: "idExists",
async: true,
type: "number",
validate: checkIdExists,
errors: false,
})
ajv.addKeyword({
keyword: "idExistsWithError",
async: true,
type: "number",
validate: checkIdExistsWithError,
errors: true,
})
ajv.addKeyword({
keyword: "idExistsCompiled",
async: true,
type: "number",
compile: compileCheckIdExists,
})
} | class Ajv extends AjvCore {
_addVocabularies(): void {
super._addVocabularies()
draft7Vocabularies.forEach((v) => this.addVocabulary(v))
if (this.opts.discriminator) this.addKeyword(discriminator)
}
_addDefaultMetaSchema(): void {
super._addDefaultMetaSchema()
if (!this.opts.meta) return
const metaSchema = this.opts.$data
? this.$dataMetaSchema(draft7MetaSchema, META_SUPPORT_DATA)
: draft7MetaSchema
this.addMetaSchema(metaSchema, META_SCHEMA_ID, false)
this.refs["http://json-schema.org/schema"] = META_SCHEMA_ID
}
defaultMeta(): string | AnySchemaObject | undefined {
return (this.opts.defaultMeta =
super.defaultMeta() || (this.getSchema(META_SCHEMA_ID) ? META_SCHEMA_ID : undefined))
}
} |
2,135 | function testKeywordErrors(def: KeywordDefinition): void {
const ajv = new _Ajv({allErrors: true})
ajv.addKeyword(def)
const schema = {
type: "object",
required: ["foo"],
alwaysFails: true,
}
const validate: any = ajv.compile(schema)
validate({foo: 1}).should.equal(false)
validate.errors.should.have.length(1)
validate.errors[0].keyword.should.equal("alwaysFails")
validate({}).should.equal(false)
validate.errors.should.have.length(2)
validate.errors[0].keyword.should.equal("required")
validate.errors[1].keyword.should.equal("alwaysFails")
} | type KeywordDefinition =
| CodeKeywordDefinition
| FuncKeywordDefinition
| MacroKeywordDefinition |
2,136 | function test(ajv: Ajv) {
const validate = ajv.compile({type: "number"})
should.not.exist(validate.source)
} | 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
validate<N extends never, T extends SomeJTDSchemaType>(
schema: T,
data: unknown
): data is JTDDataType<T>
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
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
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
}
}
} |
2,137 | function test(ajv: Ajv) {
const validate = ajv.compile({type: "number"})
should.not.exist(validate.source)
} | 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
}
} |
2,138 | function test(ajv: Ajv) {
const validate = ajv.compile({type: "number"})
should.not.exist(validate.source)
} | class Ajv extends AjvCore {
_addVocabularies(): void {
super._addVocabularies()
draft7Vocabularies.forEach((v) => this.addVocabulary(v))
if (this.opts.discriminator) this.addKeyword(discriminator)
}
_addDefaultMetaSchema(): void {
super._addDefaultMetaSchema()
if (!this.opts.meta) return
const metaSchema = this.opts.$data
? this.$dataMetaSchema(draft7MetaSchema, META_SUPPORT_DATA)
: draft7MetaSchema
this.addMetaSchema(metaSchema, META_SCHEMA_ID, false)
this.refs["http://json-schema.org/schema"] = META_SCHEMA_ID
}
defaultMeta(): string | AnySchemaObject | undefined {
return (this.opts.defaultMeta =
super.defaultMeta() || (this.getSchema(META_SCHEMA_ID) ? META_SCHEMA_ID : undefined))
}
} |
2,139 | function test(ajv: Ajv) {
ajv.addSchema({$id: "mySchema1", type: "string"})
const validate = ajv.getSchema("mySchema1")
assert(typeof validate == "function")
validate("foo").should.equal(true)
validate(1).should.equal(false)
should.throw(
() => ajv.compile({id: "mySchema2", type: "string"}),
/NOT SUPPORTED: keyword "id"/
)
should.not.exist(ajv.getSchema("mySchema2"))
} | 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
validate<N extends never, T extends SomeJTDSchemaType>(
schema: T,
data: unknown
): data is JTDDataType<T>
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
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
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
}
}
} |
2,140 | function test(ajv: Ajv) {
ajv.addSchema({$id: "mySchema1", type: "string"})
const validate = ajv.getSchema("mySchema1")
assert(typeof validate == "function")
validate("foo").should.equal(true)
validate(1).should.equal(false)
should.throw(
() => ajv.compile({id: "mySchema2", type: "string"}),
/NOT SUPPORTED: keyword "id"/
)
should.not.exist(ajv.getSchema("mySchema2"))
} | 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
}
} |
2,141 | function test(ajv: Ajv) {
ajv.addSchema({$id: "mySchema1", type: "string"})
const validate = ajv.getSchema("mySchema1")
assert(typeof validate == "function")
validate("foo").should.equal(true)
validate(1).should.equal(false)
should.throw(
() => ajv.compile({id: "mySchema2", type: "string"}),
/NOT SUPPORTED: keyword "id"/
)
should.not.exist(ajv.getSchema("mySchema2"))
} | class Ajv extends AjvCore {
_addVocabularies(): void {
super._addVocabularies()
draft7Vocabularies.forEach((v) => this.addVocabulary(v))
if (this.opts.discriminator) this.addKeyword(discriminator)
}
_addDefaultMetaSchema(): void {
super._addDefaultMetaSchema()
if (!this.opts.meta) return
const metaSchema = this.opts.$data
? this.$dataMetaSchema(draft7MetaSchema, META_SUPPORT_DATA)
: draft7MetaSchema
this.addMetaSchema(metaSchema, META_SCHEMA_ID, false)
this.refs["http://json-schema.org/schema"] = META_SCHEMA_ID
}
defaultMeta(): string | AnySchemaObject | undefined {
return (this.opts.defaultMeta =
super.defaultMeta() || (this.getSchema(META_SCHEMA_ID) ? META_SCHEMA_ID : undefined))
}
} |
2,142 | function testKeyword(ajv: Ajv) {
const validate = ajv.compile({
type: ["string", "number"],
identifier: true,
})
validate("Abc1").should.equal(true)
validate("foo bar").should.equal(false)
validate("123").should.equal(false)
validate(123).should.equal(true)
} | 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
validate<N extends never, T extends SomeJTDSchemaType>(
schema: T,
data: unknown
): data is JTDDataType<T>
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
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
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
}
}
} |
2,143 | function testKeyword(ajv: Ajv) {
const validate = ajv.compile({
type: ["string", "number"],
identifier: true,
})
validate("Abc1").should.equal(true)
validate("foo bar").should.equal(false)
validate("123").should.equal(false)
validate(123).should.equal(true)
} | 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
}
} |
2,144 | function testKeyword(ajv: Ajv) {
const validate = ajv.compile({
type: ["string", "number"],
identifier: true,
})
validate("Abc1").should.equal(true)
validate("foo bar").should.equal(false)
validate("123").should.equal(false)
validate(123).should.equal(true)
} | class Ajv extends AjvCore {
_addVocabularies(): void {
super._addVocabularies()
draft7Vocabularies.forEach((v) => this.addVocabulary(v))
if (this.opts.discriminator) this.addKeyword(discriminator)
}
_addDefaultMetaSchema(): void {
super._addDefaultMetaSchema()
if (!this.opts.meta) return
const metaSchema = this.opts.$data
? this.$dataMetaSchema(draft7MetaSchema, META_SUPPORT_DATA)
: draft7MetaSchema
this.addMetaSchema(metaSchema, META_SCHEMA_ID, false)
this.refs["http://json-schema.org/schema"] = META_SCHEMA_ID
}
defaultMeta(): string | AnySchemaObject | undefined {
return (this.opts.defaultMeta =
super.defaultMeta() || (this.getSchema(META_SCHEMA_ID) ? META_SCHEMA_ID : undefined))
}
} |
2,145 | function testUnicode(ajv: Ajv) {
let validateWithUnicode = ajvUnicode.compile({type: "string", minLength: 2})
let validate = ajv.compile({type: "string", minLength: 2})
validateWithUnicode("😀").should.equal(false)
validate("😀").should.equal(true)
validateWithUnicode = ajvUnicode.compile({type: "string", maxLength: 1})
validate = ajv.compile({type: "string", maxLength: 1})
validateWithUnicode("😀").should.equal(true)
validate("😀").should.equal(false)
} | 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
validate<N extends never, T extends SomeJTDSchemaType>(
schema: T,
data: unknown
): data is JTDDataType<T>
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
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
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
}
}
} |
2,146 | function testUnicode(ajv: Ajv) {
let validateWithUnicode = ajvUnicode.compile({type: "string", minLength: 2})
let validate = ajv.compile({type: "string", minLength: 2})
validateWithUnicode("😀").should.equal(false)
validate("😀").should.equal(true)
validateWithUnicode = ajvUnicode.compile({type: "string", maxLength: 1})
validate = ajv.compile({type: "string", maxLength: 1})
validateWithUnicode("😀").should.equal(true)
validate("😀").should.equal(false)
} | 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
}
} |
2,147 | function testUnicode(ajv: Ajv) {
let validateWithUnicode = ajvUnicode.compile({type: "string", minLength: 2})
let validate = ajv.compile({type: "string", minLength: 2})
validateWithUnicode("😀").should.equal(false)
validate("😀").should.equal(true)
validateWithUnicode = ajvUnicode.compile({type: "string", maxLength: 1})
validate = ajv.compile({type: "string", maxLength: 1})
validateWithUnicode("😀").should.equal(true)
validate("😀").should.equal(false)
} | class Ajv extends AjvCore {
_addVocabularies(): void {
super._addVocabularies()
draft7Vocabularies.forEach((v) => this.addVocabulary(v))
if (this.opts.discriminator) this.addKeyword(discriminator)
}
_addDefaultMetaSchema(): void {
super._addDefaultMetaSchema()
if (!this.opts.meta) return
const metaSchema = this.opts.$data
? this.$dataMetaSchema(draft7MetaSchema, META_SUPPORT_DATA)
: draft7MetaSchema
this.addMetaSchema(metaSchema, META_SCHEMA_ID, false)
this.refs["http://json-schema.org/schema"] = META_SCHEMA_ID
}
defaultMeta(): string | AnySchemaObject | undefined {
return (this.opts.defaultMeta =
super.defaultMeta() || (this.getSchema(META_SCHEMA_ID) ? META_SCHEMA_ID : undefined))
}
} |
2,148 | function test(opts: Options, shouldExtendRef: boolean) {
const ajv = new _Ajv(opts)
const schema = {
definitions: {
int: {type: "integer"},
},
type: "number",
$ref: "#/definitions/int",
minimum: 10,
}
let validate = ajv.compile(schema)
validate(10).should.equal(true)
validate(1).should.equal(!shouldExtendRef)
const schema1 = {
definitions: {
int: {type: "integer"},
},
type: "object",
properties: {
foo: {
$ref: "#/definitions/int",
type: "number",
minimum: 10,
},
bar: {
type: "number",
allOf: [{$ref: "#/definitions/int"}, {minimum: 10}],
},
},
}
validate = ajv.compile(schema1)
validate({foo: 10, bar: 10}).should.equal(true)
validate({foo: 1, bar: 10}).should.equal(!shouldExtendRef)
validate({foo: 10, bar: 1}).should.equal(false)
} | type Options = CurrentOptions & DeprecatedOptions |
2,149 | function testWarning(opts: Options = {}, msgPattern?: RegExp) {
let oldConsole
try {
oldConsole = console.warn
let consoleMsg
console.warn = function (...args: any[]) {
consoleMsg = Array.prototype.join.call(args, " ")
}
const ajv = new _Ajv(opts)
const schema = {
definitions: {
int: {type: "integer"},
},
type: "number",
$ref: "#/definitions/int",
minimum: 10,
}
ajv.compile(schema)
if (msgPattern) consoleMsg.should.match(msgPattern)
else should.not.exist(consoleMsg)
} finally {
console.warn = oldConsole
}
} | type Options = CurrentOptions & DeprecatedOptions |
2,150 | constructor(opts: Options = {}) {
super({
...opts,
dynamicRef: true,
next: true,
unevaluated: true,
})
} | type Options = CurrentOptions & DeprecatedOptions |
2,151 | (ajv: Ajv, options?: Opts): Ajv | 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
validate<N extends never, T extends SomeJTDSchemaType>(
schema: T,
data: unknown
): data is JTDDataType<T>
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
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
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
}
}
} |
2,152 | (ajv: Ajv, options?: Opts): Ajv | 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
}
} |
2,153 | (ajv: Ajv, options?: Opts): Ajv | class Ajv extends AjvCore {
_addVocabularies(): void {
super._addVocabularies()
draft7Vocabularies.forEach((v) => this.addVocabulary(v))
if (this.opts.discriminator) this.addKeyword(discriminator)
}
_addDefaultMetaSchema(): void {
super._addDefaultMetaSchema()
if (!this.opts.meta) return
const metaSchema = this.opts.$data
? this.$dataMetaSchema(draft7MetaSchema, META_SUPPORT_DATA)
: draft7MetaSchema
this.addMetaSchema(metaSchema, META_SCHEMA_ID, false)
this.refs["http://json-schema.org/schema"] = META_SCHEMA_ID
}
defaultMeta(): string | AnySchemaObject | undefined {
return (this.opts.defaultMeta =
super.defaultMeta() || (this.getSchema(META_SCHEMA_ID) ? META_SCHEMA_ID : undefined))
}
} |
2,154 | (schema: AnySchema) => unknown | type AnySchema = Schema | AsyncSchema |
2,155 | 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,
}
} | type Options = CurrentOptions & DeprecatedOptions |
2,156 | 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
} | type Options = CurrentOptions & DeprecatedOptions |
2,157 | validate<T>(schema: AsyncSchema, data: unknown | T): Promise<T> | interface AsyncSchema extends _SchemaObject {
$async: true
} |
2,158 | compile<T = unknown>(schema: AsyncSchema, _meta?: boolean): AsyncValidateFunction<T> | interface AsyncSchema extends _SchemaObject {
$async: true
} |
2,159 | compile<T = unknown>(schema: AnySchema, _meta?: boolean): AnyValidateFunction<T> | type AnySchema = Schema | AsyncSchema |
2,160 | compile<T = unknown>(schema: AnySchema, _meta?: boolean): AnyValidateFunction<T> {
const sch = this._addSchema(schema, _meta)
return (sch.validate || this._compileSchemaEnv(sch)) as AnyValidateFunction<T>
} | type AnySchema = Schema | AsyncSchema |
2,161 | compileAsync<T = unknown>(schema: AsyncSchema, meta?: boolean): Promise<AsyncValidateFunction<T>> | interface AsyncSchema extends _SchemaObject {
$async: true
} |
2,162 | compileAsync<T = unknown>(
schema: AnySchemaObject,
meta?: boolean
): Promise<AnyValidateFunction<T>> | type AnySchemaObject = SchemaObject | AsyncSchema |
2,163 | 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]
}
}
} | type AnySchemaObject = SchemaObject | AsyncSchema |
2,164 | 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)
} | type AnySchemaObject = SchemaObject | AsyncSchema |
2,165 | 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)
} | 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
validate<N extends never, T extends SomeJTDSchemaType>(
schema: T,
data: unknown
): data is JTDDataType<T>
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
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
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
}
}
} |
2,166 | 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)
} | 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
}
} |
2,167 | 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)
} | class Ajv extends AjvCore {
_addVocabularies(): void {
super._addVocabularies()
draft7Vocabularies.forEach((v) => this.addVocabulary(v))
if (this.opts.discriminator) this.addKeyword(discriminator)
}
_addDefaultMetaSchema(): void {
super._addDefaultMetaSchema()
if (!this.opts.meta) return
const metaSchema = this.opts.$data
? this.$dataMetaSchema(draft7MetaSchema, META_SUPPORT_DATA)
: draft7MetaSchema
this.addMetaSchema(metaSchema, META_SCHEMA_ID, false)
this.refs["http://json-schema.org/schema"] = META_SCHEMA_ID
}
defaultMeta(): string | AnySchemaObject | undefined {
return (this.opts.defaultMeta =
super.defaultMeta() || (this.getSchema(META_SCHEMA_ID) ? META_SCHEMA_ID : undefined))
}
} |
2,168 | async function loadMetaSchema(this: Ajv, $ref?: string): Promise<void> {
if ($ref && !this.getSchema($ref)) {
await runCompileAsync.call(this, {$ref}, true)
}
} | 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
validate<N extends never, T extends SomeJTDSchemaType>(
schema: T,
data: unknown
): data is JTDDataType<T>
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
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
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
}
}
} |
2,169 | async function loadMetaSchema(this: Ajv, $ref?: string): Promise<void> {
if ($ref && !this.getSchema($ref)) {
await runCompileAsync.call(this, {$ref}, true)
}
} | 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
}
} |
2,170 | async function loadMetaSchema(this: Ajv, $ref?: string): Promise<void> {
if ($ref && !this.getSchema($ref)) {
await runCompileAsync.call(this, {$ref}, true)
}
} | class Ajv extends AjvCore {
_addVocabularies(): void {
super._addVocabularies()
draft7Vocabularies.forEach((v) => this.addVocabulary(v))
if (this.opts.discriminator) this.addKeyword(discriminator)
}
_addDefaultMetaSchema(): void {
super._addDefaultMetaSchema()
if (!this.opts.meta) return
const metaSchema = this.opts.$data
? this.$dataMetaSchema(draft7MetaSchema, META_SUPPORT_DATA)
: draft7MetaSchema
this.addMetaSchema(metaSchema, META_SCHEMA_ID, false)
this.refs["http://json-schema.org/schema"] = META_SCHEMA_ID
}
defaultMeta(): string | AnySchemaObject | undefined {
return (this.opts.defaultMeta =
super.defaultMeta() || (this.getSchema(META_SCHEMA_ID) ? META_SCHEMA_ID : undefined))
}
} |
2,171 | 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)
}
} | class SchemaEnv implements SchemaEnvArgs {
readonly schema: AnySchema
readonly schemaId?: "$id" | "id"
readonly root: SchemaEnv
baseId: string // TODO possibly, it should be readonly
schemaPath?: string
localRefs?: LocalRefs
readonly meta?: boolean
readonly $async?: boolean // true if the current schema is asynchronous.
readonly refs: SchemaRefs = {}
readonly dynamicAnchors: {[Ref in string]?: true} = {}
validate?: AnyValidateFunction
validateName?: ValueScopeName
serialize?: (data: unknown) => string
serializeName?: ValueScopeName
parse?: (data: string) => unknown
parseName?: ValueScopeName
constructor(env: SchemaEnvArgs) {
let schema: AnySchemaObject | undefined
if (typeof env.schema == "object") schema = env.schema
this.schema = env.schema
this.schemaId = env.schemaId
this.root = env.root || this
this.baseId = env.baseId ?? normalizeId(schema?.[env.schemaId || "$id"])
this.schemaPath = env.schemaPath
this.localRefs = env.localRefs
this.meta = env.meta
this.$async = schema?.$async
this.refs = {}
}
} |
2,172 | 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)
}
} | 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
validate<N extends never, T extends SomeJTDSchemaType>(
schema: T,
data: unknown
): data is JTDDataType<T>
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
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
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
}
}
} |
2,173 | 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)
}
} | 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
}
} |
2,174 | 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)
}
} | class Ajv extends AjvCore {
_addVocabularies(): void {
super._addVocabularies()
draft7Vocabularies.forEach((v) => this.addVocabulary(v))
if (this.opts.discriminator) this.addKeyword(discriminator)
}
_addDefaultMetaSchema(): void {
super._addDefaultMetaSchema()
if (!this.opts.meta) return
const metaSchema = this.opts.$data
? this.$dataMetaSchema(draft7MetaSchema, META_SUPPORT_DATA)
: draft7MetaSchema
this.addMetaSchema(metaSchema, META_SCHEMA_ID, false)
this.refs["http://json-schema.org/schema"] = META_SCHEMA_ID
}
defaultMeta(): string | AnySchemaObject | undefined {
return (this.opts.defaultMeta =
super.defaultMeta() || (this.getSchema(META_SCHEMA_ID) ? META_SCHEMA_ID : undefined))
}
} |
2,175 | 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`)
}
} | 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
validate<N extends never, T extends SomeJTDSchemaType>(
schema: T,
data: unknown
): data is JTDDataType<T>
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
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
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
}
}
} |
2,176 | 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`)
}
} | 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
}
} |
2,177 | 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`)
}
} | class Ajv extends AjvCore {
_addVocabularies(): void {
super._addVocabularies()
draft7Vocabularies.forEach((v) => this.addVocabulary(v))
if (this.opts.discriminator) this.addKeyword(discriminator)
}
_addDefaultMetaSchema(): void {
super._addDefaultMetaSchema()
if (!this.opts.meta) return
const metaSchema = this.opts.$data
? this.$dataMetaSchema(draft7MetaSchema, META_SUPPORT_DATA)
: draft7MetaSchema
this.addMetaSchema(metaSchema, META_SCHEMA_ID, false)
this.refs["http://json-schema.org/schema"] = META_SCHEMA_ID
}
defaultMeta(): string | AnySchemaObject | undefined {
return (this.opts.defaultMeta =
super.defaultMeta() || (this.getSchema(META_SCHEMA_ID) ? META_SCHEMA_ID : undefined))
}
} |
2,178 | 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`)
}
} | class MissingRefError extends Error {
readonly missingRef: string
readonly missingSchema: string
constructor(resolver: UriResolver, baseId: string, ref: string, msg?: string) {
super(msg || `can't resolve reference ${ref} from id ${baseId}`)
this.missingRef = resolveUrl(resolver, baseId, ref)
this.missingSchema = normalizeId(getFullPath(resolver, this.missingRef))
}
} |
2,179 | 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)
} | 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
validate<N extends never, T extends SomeJTDSchemaType>(
schema: T,
data: unknown
): data is JTDDataType<T>
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
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
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
}
}
} |
2,180 | 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)
} | 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
}
} |
2,181 | 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)
} | class Ajv extends AjvCore {
_addVocabularies(): void {
super._addVocabularies()
draft7Vocabularies.forEach((v) => this.addVocabulary(v))
if (this.opts.discriminator) this.addKeyword(discriminator)
}
_addDefaultMetaSchema(): void {
super._addDefaultMetaSchema()
if (!this.opts.meta) return
const metaSchema = this.opts.$data
? this.$dataMetaSchema(draft7MetaSchema, META_SUPPORT_DATA)
: draft7MetaSchema
this.addMetaSchema(metaSchema, META_SCHEMA_ID, false)
this.refs["http://json-schema.org/schema"] = META_SCHEMA_ID
}
defaultMeta(): string | AnySchemaObject | undefined {
return (this.opts.defaultMeta =
super.defaultMeta() || (this.getSchema(META_SCHEMA_ID) ? META_SCHEMA_ID : undefined))
}
} |
2,182 | 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]
}
} | 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
validate<N extends never, T extends SomeJTDSchemaType>(
schema: T,
data: unknown
): data is JTDDataType<T>
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
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
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
}
}
} |
2,183 | 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]
}
} | 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
}
} |
2,184 | 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]
}
} | class Ajv extends AjvCore {
_addVocabularies(): void {
super._addVocabularies()
draft7Vocabularies.forEach((v) => this.addVocabulary(v))
if (this.opts.discriminator) this.addKeyword(discriminator)
}
_addDefaultMetaSchema(): void {
super._addDefaultMetaSchema()
if (!this.opts.meta) return
const metaSchema = this.opts.$data
? this.$dataMetaSchema(draft7MetaSchema, META_SUPPORT_DATA)
: draft7MetaSchema
this.addMetaSchema(metaSchema, META_SCHEMA_ID, false)
this.refs["http://json-schema.org/schema"] = META_SCHEMA_ID
}
defaultMeta(): string | AnySchemaObject | undefined {
return (this.opts.defaultMeta =
super.defaultMeta() || (this.getSchema(META_SCHEMA_ID) ? META_SCHEMA_ID : undefined))
}
} |
2,185 | 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
} | type AnySchemaObject = SchemaObject | AsyncSchema |
2,186 | 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
} | type AnySchema = Schema | AsyncSchema |
2,187 | addVocabulary(definitions: Vocabulary): Ajv {
for (const def of definitions) this.addKeyword(def)
return this
} | type Vocabulary = (KeywordDefinition | string)[] |
2,188 | $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
} | type AnySchemaObject = SchemaObject | AsyncSchema |
2,189 | _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
} | type AnySchema = Schema | AsyncSchema |
2,190 | 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
} | class SchemaEnv implements SchemaEnvArgs {
readonly schema: AnySchema
readonly schemaId?: "$id" | "id"
readonly root: SchemaEnv
baseId: string // TODO possibly, it should be readonly
schemaPath?: string
localRefs?: LocalRefs
readonly meta?: boolean
readonly $async?: boolean // true if the current schema is asynchronous.
readonly refs: SchemaRefs = {}
readonly dynamicAnchors: {[Ref in string]?: true} = {}
validate?: AnyValidateFunction
validateName?: ValueScopeName
serialize?: (data: unknown) => string
serializeName?: ValueScopeName
parse?: (data: string) => unknown
parseName?: ValueScopeName
constructor(env: SchemaEnvArgs) {
let schema: AnySchemaObject | undefined
if (typeof env.schema == "object") schema = env.schema
this.schema = env.schema
this.schemaId = env.schemaId
this.root = env.root || this
this.baseId = env.baseId ?? normalizeId(schema?.[env.schemaId || "$id"])
this.schemaPath = env.schemaPath
this.localRefs = env.localRefs
this.meta = env.meta
this.$async = schema?.$async
this.refs = {}
}
} |
2,191 | private _compileMetaSchema(sch: SchemaEnv): void {
const currentOpts = this.opts
this.opts = this._metaOpts
try {
compileSchema.call(this, sch)
} finally {
this.opts = currentOpts
}
} | class SchemaEnv implements SchemaEnvArgs {
readonly schema: AnySchema
readonly schemaId?: "$id" | "id"
readonly root: SchemaEnv
baseId: string // TODO possibly, it should be readonly
schemaPath?: string
localRefs?: LocalRefs
readonly meta?: boolean
readonly $async?: boolean // true if the current schema is asynchronous.
readonly refs: SchemaRefs = {}
readonly dynamicAnchors: {[Ref in string]?: true} = {}
validate?: AnyValidateFunction
validateName?: ValueScopeName
serialize?: (data: unknown) => string
serializeName?: ValueScopeName
parse?: (data: string) => unknown
parseName?: ValueScopeName
constructor(env: SchemaEnvArgs) {
let schema: AnySchemaObject | undefined
if (typeof env.schema == "object") schema = env.schema
this.schema = env.schema
this.schemaId = env.schemaId
this.root = env.root || this
this.baseId = env.baseId ?? normalizeId(schema?.[env.schemaId || "$id"])
this.schemaPath = env.schemaPath
this.localRefs = env.localRefs
this.meta = env.meta
this.$async = schema?.$async
this.refs = {}
}
} |
2,192 | 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]}`)
}
} | 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
validate<N extends never, T extends SomeJTDSchemaType>(
schema: T,
data: unknown
): data is JTDDataType<T>
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
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
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
}
}
} |
2,193 | 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]}`)
}
} | 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
}
} |
2,194 | 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]}`)
}
} | class Ajv extends AjvCore {
_addVocabularies(): void {
super._addVocabularies()
draft7Vocabularies.forEach((v) => this.addVocabulary(v))
if (this.opts.discriminator) this.addKeyword(discriminator)
}
_addDefaultMetaSchema(): void {
super._addDefaultMetaSchema()
if (!this.opts.meta) return
const metaSchema = this.opts.$data
? this.$dataMetaSchema(draft7MetaSchema, META_SUPPORT_DATA)
: draft7MetaSchema
this.addMetaSchema(metaSchema, META_SCHEMA_ID, false)
this.refs["http://json-schema.org/schema"] = META_SCHEMA_ID
}
defaultMeta(): string | AnySchemaObject | undefined {
return (this.opts.defaultMeta =
super.defaultMeta() || (this.getSchema(META_SCHEMA_ID) ? META_SCHEMA_ID : undefined))
}
} |
2,195 | 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]
} | 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
validate<N extends never, T extends SomeJTDSchemaType>(
schema: T,
data: unknown
): data is JTDDataType<T>
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
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
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
}
}
} |
2,196 | 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]
} | 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
}
} |
2,197 | 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]
} | class Ajv extends AjvCore {
_addVocabularies(): void {
super._addVocabularies()
draft7Vocabularies.forEach((v) => this.addVocabulary(v))
if (this.opts.discriminator) this.addKeyword(discriminator)
}
_addDefaultMetaSchema(): void {
super._addDefaultMetaSchema()
if (!this.opts.meta) return
const metaSchema = this.opts.$data
? this.$dataMetaSchema(draft7MetaSchema, META_SUPPORT_DATA)
: draft7MetaSchema
this.addMetaSchema(metaSchema, META_SCHEMA_ID, false)
this.refs["http://json-schema.org/schema"] = META_SCHEMA_ID
}
defaultMeta(): string | AnySchemaObject | undefined {
return (this.opts.defaultMeta =
super.defaultMeta() || (this.getSchema(META_SCHEMA_ID) ? META_SCHEMA_ID : undefined))
}
} |
2,198 | 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)
} | 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
validate<N extends never, T extends SomeJTDSchemaType>(
schema: T,
data: unknown
): data is JTDDataType<T>
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
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
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
}
}
} |
2,199 | 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)
} | 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
}
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.