UNPKG

30.2 kBPlain TextView Raw
1export {
2 Format,
3 FormatDefinition,
4 AsyncFormatDefinition,
5 KeywordDefinition,
6 KeywordErrorDefinition,
7 CodeKeywordDefinition,
8 MacroKeywordDefinition,
9 FuncKeywordDefinition,
10 Vocabulary,
11 Schema,
12 SchemaObject,
13 AnySchemaObject,
14 AsyncSchema,
15 AnySchema,
16 ValidateFunction,
17 AsyncValidateFunction,
18 AnyValidateFunction,
19 ErrorObject,
20 ErrorNoParams,
21} from "./types"
22
23export {SchemaCxt, SchemaObjCxt} from "./compile"
24export interface Plugin<Opts> {
25 (ajv: Ajv, options?: Opts): Ajv
26 [prop: string]: any
27}
28
29export {KeywordCxt} from "./compile/validate"
30export {DefinedError} from "./vocabularies/errors"
31export {JSONType} from "./compile/rules"
32export {JSONSchemaType} from "./types/json-schema"
33export {JTDSchemaType, SomeJTDSchemaType, JTDDataType} from "./types/jtd-schema"
34export {_, str, stringify, nil, Name, Code, CodeGen, CodeGenOptions} from "./compile/codegen"
35
36import type {
37 Schema,
38 AnySchema,
39 AnySchemaObject,
40 SchemaObject,
41 AsyncSchema,
42 Vocabulary,
43 KeywordDefinition,
44 AddedKeywordDefinition,
45 AnyValidateFunction,
46 ValidateFunction,
47 AsyncValidateFunction,
48 ErrorObject,
49 Format,
50 AddedFormat,
51 RegExpEngine,
52} from "./types"
53import type {JSONSchemaType} from "./types/json-schema"
54import type {JTDSchemaType, SomeJTDSchemaType, JTDDataType} from "./types/jtd-schema"
55import ValidationError from "./runtime/validation_error"
56import MissingRefError from "./compile/ref_error"
57import {getRules, ValidationRules, Rule, RuleGroup, JSONType} from "./compile/rules"
58import {SchemaEnv, compileSchema, resolveSchema} from "./compile"
59import {Code, ValueScope} from "./compile/codegen"
60import {normalizeId, getSchemaRefs} from "./compile/resolve"
61import {getJSONTypes} from "./compile/validate/dataType"
62import {eachItem} from "./compile/util"
63
64import * as $dataRefSchema from "./refs/data.json"
65
66const defaultRegExp: RegExpEngine = (str, flags) => new RegExp(str, flags)
67defaultRegExp.code = "new RegExp"
68
69const META_IGNORE_OPTIONS: (keyof Options)[] = ["removeAdditional", "useDefaults", "coerceTypes"]
70const EXT_SCOPE_NAMES = new Set([
71 "validate",
72 "serialize",
73 "parse",
74 "wrapper",
75 "root",
76 "schema",
77 "keyword",
78 "pattern",
79 "formats",
80 "validate$data",
81 "func",
82 "obj",
83 "Error",
84])
85
86export type Options = CurrentOptions & DeprecatedOptions
87
88export interface CurrentOptions {
89 // strict mode options (NEW)
90 strict?: boolean | "log"
91 strictSchema?: boolean | "log"
92 strictNumbers?: boolean | "log"
93 strictTypes?: boolean | "log"
94 strictTuples?: boolean | "log"
95 strictRequired?: boolean | "log"
96 allowMatchingProperties?: boolean // disables a strict mode restriction
97 allowUnionTypes?: boolean
98 validateFormats?: boolean
99 // validation and reporting options:
100 $data?: boolean
101 allErrors?: boolean
102 verbose?: boolean
103 discriminator?: boolean
104 unicodeRegExp?: boolean
105 timestamp?: "string" | "date" // JTD only
106 parseDate?: boolean // JTD only
107 allowDate?: boolean // JTD only
108 $comment?:
109 | true
110 | ((comment: string, schemaPath?: string, rootSchema?: AnySchemaObject) => unknown)
111 formats?: {[Name in string]?: Format}
112 keywords?: Vocabulary
113 schemas?: AnySchema[] | {[Key in string]?: AnySchema}
114 logger?: Logger | false
115 loadSchema?: (uri: string) => Promise<AnySchemaObject>
116 // options to modify validated data:
117 removeAdditional?: boolean | "all" | "failing"
118 useDefaults?: boolean | "empty"
119 coerceTypes?: boolean | "array"
120 // advanced options:
121 next?: boolean // NEW
122 unevaluated?: boolean // NEW
123 dynamicRef?: boolean // NEW
124 schemaId?: "id" | "$id"
125 jtd?: boolean // NEW
126 meta?: SchemaObject | boolean
127 defaultMeta?: string | AnySchemaObject
128 validateSchema?: boolean | "log"
129 addUsedSchema?: boolean
130 inlineRefs?: boolean | number
131 passContext?: boolean
132 loopRequired?: number
133 loopEnum?: number // NEW
134 ownProperties?: boolean
135 multipleOfPrecision?: number
136 int32range?: boolean // JTD only
137 messages?: boolean
138 code?: CodeOptions // NEW
139}
140
141export interface CodeOptions {
142 es5?: boolean
143 esm?: boolean
144 lines?: boolean
145 optimize?: boolean | number
146 formats?: Code // code to require (or construct) map of available formats - for standalone code
147 source?: boolean
148 process?: (code: string, schema?: SchemaEnv) => string
149 regExp?: RegExpEngine
150}
151
152interface InstanceCodeOptions extends CodeOptions {
153 regExp: RegExpEngine
154 optimize: number
155}
156
157interface DeprecatedOptions {
158 /** @deprecated */
159 ignoreKeywordsWithRef?: boolean
160 /** @deprecated */
161 jsPropertySyntax?: boolean // added instead of jsonPointers
162 /** @deprecated */
163 unicode?: boolean
164}
165
166interface RemovedOptions {
167 format?: boolean
168 errorDataPath?: "object" | "property"
169 nullable?: boolean // "nullable" keyword is supported by default
170 jsonPointers?: boolean
171 extendRefs?: true | "ignore" | "fail"
172 missingRefs?: true | "ignore" | "fail"
173 processCode?: (code: string, schema?: SchemaEnv) => string
174 sourceCode?: boolean
175 strictDefaults?: boolean
176 strictKeywords?: boolean
177 uniqueItems?: boolean
178 unknownFormats?: true | string[] | "ignore"
179 cache?: any
180 serialize?: (schema: AnySchema) => unknown
181 ajvErrors?: boolean
182}
183
184type OptionsInfo<T extends RemovedOptions | DeprecatedOptions> = {
185 [K in keyof T]-?: string | undefined
186}
187
188const removedOptions: OptionsInfo<RemovedOptions> = {
189 errorDataPath: "",
190 format: "`validateFormats: false` can be used instead.",
191 nullable: '"nullable" keyword is supported by default.',
192 jsonPointers: "Deprecated jsPropertySyntax can be used instead.",
193 extendRefs: "Deprecated ignoreKeywordsWithRef can be used instead.",
194 missingRefs: "Pass empty schema with $id that should be ignored to ajv.addSchema.",
195 processCode: "Use option `code: {process: (code, schemaEnv: object) => string}`",
196 sourceCode: "Use option `code: {source: true}`",
197 strictDefaults: "It is default now, see option `strict`.",
198 strictKeywords: "It is default now, see option `strict`.",
199 uniqueItems: '"uniqueItems" keyword is always validated.',
200 unknownFormats: "Disable strict mode or pass `true` to `ajv.addFormat` (or `formats` option).",
201 cache: "Map is used as cache, schema object as key.",
202 serialize: "Map is used as cache, schema object as key.",
203 ajvErrors: "It is default now.",
204}
205
206const deprecatedOptions: OptionsInfo<DeprecatedOptions> = {
207 ignoreKeywordsWithRef: "",
208 jsPropertySyntax: "",
209 unicode: '"minLength"/"maxLength" account for unicode characters by default.',
210}
211
212type RequiredInstanceOptions = {
213 [K in
214 | "strictSchema"
215 | "strictNumbers"
216 | "strictTypes"
217 | "strictTuples"
218 | "strictRequired"
219 | "inlineRefs"
220 | "loopRequired"
221 | "loopEnum"
222 | "meta"
223 | "messages"
224 | "schemaId"
225 | "addUsedSchema"
226 | "validateSchema"
227 | "validateFormats"
228 | "int32range"
229 | "unicodeRegExp"]: NonNullable<Options[K]>
230} & {code: InstanceCodeOptions}
231
232export type InstanceOptions = Options & RequiredInstanceOptions
233
234const MAX_EXPRESSION = 200
235
236// eslint-disable-next-line complexity
237function requiredOptions(o: Options): RequiredInstanceOptions {
238 const s = o.strict
239 const _optz = o.code?.optimize
240 const optimize = _optz === true || _optz === undefined ? 1 : _optz || 0
241 const regExp = o.code?.regExp ?? defaultRegExp
242 return {
243 strictSchema: o.strictSchema ?? s ?? true,
244 strictNumbers: o.strictNumbers ?? s ?? true,
245 strictTypes: o.strictTypes ?? s ?? "log",
246 strictTuples: o.strictTuples ?? s ?? "log",
247 strictRequired: o.strictRequired ?? s ?? false,
248 code: o.code ? {...o.code, optimize, regExp} : {optimize, regExp},
249 loopRequired: o.loopRequired ?? MAX_EXPRESSION,
250 loopEnum: o.loopEnum ?? MAX_EXPRESSION,
251 meta: o.meta ?? true,
252 messages: o.messages ?? true,
253 inlineRefs: o.inlineRefs ?? true,
254 schemaId: o.schemaId ?? "$id",
255 addUsedSchema: o.addUsedSchema ?? true,
256 validateSchema: o.validateSchema ?? true,
257 validateFormats: o.validateFormats ?? true,
258 unicodeRegExp: o.unicodeRegExp ?? true,
259 int32range: o.int32range ?? true,
260 }
261}
262
263export interface Logger {
264 log(...args: unknown[]): unknown
265 warn(...args: unknown[]): unknown
266 error(...args: unknown[]): unknown
267}
268
269export default class Ajv {
270 opts: InstanceOptions
271 errors?: ErrorObject[] | null // errors from the last validation
272 logger: Logger
273 // shared external scope values for compiled functions
274 readonly scope: ValueScope
275 readonly schemas: {[Key in string]?: SchemaEnv} = {}
276 readonly refs: {[Ref in string]?: SchemaEnv | string} = {}
277 readonly formats: {[Name in string]?: AddedFormat} = {}
278 readonly RULES: ValidationRules
279 readonly _compilations: Set<SchemaEnv> = new Set()
280 private readonly _loading: {[Ref in string]?: Promise<AnySchemaObject>} = {}
281 private readonly _cache: Map<AnySchema, SchemaEnv> = new Map()
282 private readonly _metaOpts: InstanceOptions
283
284 static ValidationError = ValidationError
285 static MissingRefError = MissingRefError
286
287 constructor(opts: Options = {}) {
288 opts = this.opts = {...opts, ...requiredOptions(opts)}
289 const {es5, lines} = this.opts.code
290
291 this.scope = new ValueScope({scope: {}, prefixes: EXT_SCOPE_NAMES, es5, lines})
292 this.logger = getLogger(opts.logger)
293 const formatOpt = opts.validateFormats
294 opts.validateFormats = false
295
296 this.RULES = getRules()
297 checkOptions.call(this, removedOptions, opts, "NOT SUPPORTED")
298 checkOptions.call(this, deprecatedOptions, opts, "DEPRECATED", "warn")
299 this._metaOpts = getMetaSchemaOptions.call(this)
300
301 if (opts.formats) addInitialFormats.call(this)
302 this._addVocabularies()
303 this._addDefaultMetaSchema()
304 if (opts.keywords) addInitialKeywords.call(this, opts.keywords)
305 if (typeof opts.meta == "object") this.addMetaSchema(opts.meta)
306 addInitialSchemas.call(this)
307 opts.validateFormats = formatOpt
308 }
309
310 _addVocabularies(): void {
311 this.addKeyword("$async")
312 }
313
314 _addDefaultMetaSchema(): void {
315 const {$data, meta, schemaId} = this.opts
316 let _dataRefSchema: SchemaObject = $dataRefSchema
317 if (schemaId === "id") {
318 _dataRefSchema = {...$dataRefSchema}
319 _dataRefSchema.id = _dataRefSchema.$id
320 delete _dataRefSchema.$id
321 }
322 if (meta && $data) this.addMetaSchema(_dataRefSchema, _dataRefSchema[schemaId], false)
323 }
324
325 defaultMeta(): string | AnySchemaObject | undefined {
326 const {meta, schemaId} = this.opts
327 return (this.opts.defaultMeta = typeof meta == "object" ? meta[schemaId] || meta : undefined)
328 }
329
330 // Validate data using schema
331 // AnySchema will be compiled and cached using schema itself as a key for Map
332 validate(schema: Schema | string, data: unknown): boolean
333 validate(schemaKeyRef: AnySchema | string, data: unknown): boolean | Promise<unknown>
334 validate<T>(schema: Schema | JSONSchemaType<T> | string, data: unknown): data is T
335 // Separated for type inference to work
336 // eslint-disable-next-line @typescript-eslint/unified-signatures
337 validate<T>(schema: JTDSchemaType<T>, data: unknown): data is T
338 // This overload is only intended for typescript inference, the first
339 // argument prevents manual type annotation from matching this overload
340 validate<N extends never, T extends SomeJTDSchemaType>(
341 schema: T,
342 data: unknown
343 ): data is JTDDataType<T>
344 validate<T>(schema: AsyncSchema, data: unknown | T): Promise<T>
345 validate<T>(schemaKeyRef: AnySchema | string, data: unknown): data is T | Promise<T>
346 validate<T>(
347 schemaKeyRef: AnySchema | string, // key, ref or schema object
348 data: unknown | T // to be validated
349 ): boolean | Promise<T> {
350 let v: AnyValidateFunction | undefined
351 if (typeof schemaKeyRef == "string") {
352 v = this.getSchema<T>(schemaKeyRef)
353 if (!v) throw new Error(`no schema with key or ref "${schemaKeyRef}"`)
354 } else {
355 v = this.compile<T>(schemaKeyRef)
356 }
357
358 const valid = v(data)
359 if (!("$async" in v)) this.errors = v.errors
360 return valid
361 }
362
363 // Create validation function for passed schema
364 // _meta: true if schema is a meta-schema. Used internally to compile meta schemas of user-defined keywords.
365 compile<T = unknown>(schema: Schema | JSONSchemaType<T>, _meta?: boolean): ValidateFunction<T>
366 // Separated for type inference to work
367 // eslint-disable-next-line @typescript-eslint/unified-signatures
368 compile<T = unknown>(schema: JTDSchemaType<T>, _meta?: boolean): ValidateFunction<T>
369 // This overload is only intended for typescript inference, the first
370 // argument prevents manual type annotation from matching this overload
371 compile<N extends never, T extends SomeJTDSchemaType>(
372 schema: T,
373 _meta?: boolean
374 ): ValidateFunction<JTDDataType<T>>
375 compile<T = unknown>(schema: AsyncSchema, _meta?: boolean): AsyncValidateFunction<T>
376 compile<T = unknown>(schema: AnySchema, _meta?: boolean): AnyValidateFunction<T>
377 compile<T = unknown>(schema: AnySchema, _meta?: boolean): AnyValidateFunction<T> {
378 const sch = this._addSchema(schema, _meta)
379 return (sch.validate || this._compileSchemaEnv(sch)) as AnyValidateFunction<T>
380 }
381
382 // Creates validating function for passed schema with asynchronous loading of missing schemas.
383 // `loadSchema` option should be a function that accepts schema uri and returns promise that resolves with the schema.
384 // TODO allow passing schema URI
385 // meta - optional true to compile meta-schema
386 compileAsync<T = unknown>(
387 schema: SchemaObject | JSONSchemaType<T>,
388 _meta?: boolean
389 ): Promise<ValidateFunction<T>>
390 // Separated for type inference to work
391 // eslint-disable-next-line @typescript-eslint/unified-signatures
392 compileAsync<T = unknown>(schema: JTDSchemaType<T>, _meta?: boolean): Promise<ValidateFunction<T>>
393 compileAsync<T = unknown>(schema: AsyncSchema, meta?: boolean): Promise<AsyncValidateFunction<T>>
394 // eslint-disable-next-line @typescript-eslint/unified-signatures
395 compileAsync<T = unknown>(
396 schema: AnySchemaObject,
397 meta?: boolean
398 ): Promise<AnyValidateFunction<T>>
399 compileAsync<T = unknown>(
400 schema: AnySchemaObject,
401 meta?: boolean
402 ): Promise<AnyValidateFunction<T>> {
403 if (typeof this.opts.loadSchema != "function") {
404 throw new Error("options.loadSchema should be a function")
405 }
406 const {loadSchema} = this.opts
407 return runCompileAsync.call(this, schema, meta)
408
409 async function runCompileAsync(
410 this: Ajv,
411 _schema: AnySchemaObject,
412 _meta?: boolean
413 ): Promise<AnyValidateFunction> {
414 await loadMetaSchema.call(this, _schema.$schema)
415 const sch = this._addSchema(_schema, _meta)
416 return sch.validate || _compileAsync.call(this, sch)
417 }
418
419 async function loadMetaSchema(this: Ajv, $ref?: string): Promise<void> {
420 if ($ref && !this.getSchema($ref)) {
421 await runCompileAsync.call(this, {$ref}, true)
422 }
423 }
424
425 async function _compileAsync(this: Ajv, sch: SchemaEnv): Promise<AnyValidateFunction> {
426 try {
427 return this._compileSchemaEnv(sch)
428 } catch (e) {
429 if (!(e instanceof MissingRefError)) throw e
430 checkLoaded.call(this, e)
431 await loadMissingSchema.call(this, e.missingSchema)
432 return _compileAsync.call(this, sch)
433 }
434 }
435
436 function checkLoaded(this: Ajv, {missingSchema: ref, missingRef}: MissingRefError): void {
437 if (this.refs[ref]) {
438 throw new Error(`AnySchema ${ref} is loaded but ${missingRef} cannot be resolved`)
439 }
440 }
441
442 async function loadMissingSchema(this: Ajv, ref: string): Promise<void> {
443 const _schema = await _loadSchema.call(this, ref)
444 if (!this.refs[ref]) await loadMetaSchema.call(this, _schema.$schema)
445 if (!this.refs[ref]) this.addSchema(_schema, ref, meta)
446 }
447
448 async function _loadSchema(this: Ajv, ref: string): Promise<AnySchemaObject> {
449 const p = this._loading[ref]
450 if (p) return p
451 try {
452 return await (this._loading[ref] = loadSchema(ref))
453 } finally {
454 delete this._loading[ref]
455 }
456 }
457 }
458
459 // Adds schema to the instance
460 addSchema(
461 schema: AnySchema | AnySchema[], // If array is passed, `key` will be ignored
462 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`.
463 _meta?: boolean, // true if schema is a meta-schema. Used internally, addMetaSchema should be used instead.
464 _validateSchema = this.opts.validateSchema // false to skip schema validation. Used internally, option validateSchema should be used instead.
465 ): Ajv {
466 if (Array.isArray(schema)) {
467 for (const sch of schema) this.addSchema(sch, undefined, _meta, _validateSchema)
468 return this
469 }
470 let id: string | undefined
471 if (typeof schema === "object") {
472 const {schemaId} = this.opts
473 id = schema[schemaId]
474 if (id !== undefined && typeof id != "string") {
475 throw new Error(`schema ${schemaId} must be string`)
476 }
477 }
478 key = normalizeId(key || id)
479 this._checkUnique(key)
480 this.schemas[key] = this._addSchema(schema, _meta, key, _validateSchema, true)
481 return this
482 }
483
484 // Add schema that will be used to validate other schemas
485 // options in META_IGNORE_OPTIONS are alway set to false
486 addMetaSchema(
487 schema: AnySchemaObject,
488 key?: string, // schema key
489 _validateSchema = this.opts.validateSchema // false to skip schema validation, can be used to override validateSchema option for meta-schema
490 ): Ajv {
491 this.addSchema(schema, key, true, _validateSchema)
492 return this
493 }
494
495 // Validate schema against its meta-schema
496 validateSchema(schema: AnySchema, throwOrLogError?: boolean): boolean | Promise<unknown> {
497 if (typeof schema == "boolean") return true
498 let $schema: string | AnySchemaObject | undefined
499 $schema = schema.$schema
500 if ($schema !== undefined && typeof $schema != "string") {
501 throw new Error("$schema must be a string")
502 }
503 $schema = $schema || this.opts.defaultMeta || this.defaultMeta()
504 if (!$schema) {
505 this.logger.warn("meta-schema not available")
506 this.errors = null
507 return true
508 }
509 const valid = this.validate($schema, schema)
510 if (!valid && throwOrLogError) {
511 const message = "schema is invalid: " + this.errorsText()
512 if (this.opts.validateSchema === "log") this.logger.error(message)
513 else throw new Error(message)
514 }
515 return valid
516 }
517
518 // Get compiled schema by `key` or `ref`.
519 // (`key` that was passed to `addSchema` or full schema reference - `schema.$id` or resolved id)
520 getSchema<T = unknown>(keyRef: string): AnyValidateFunction<T> | undefined {
521 let sch
522 while (typeof (sch = getSchEnv.call(this, keyRef)) == "string") keyRef = sch
523 if (sch === undefined) {
524 const {schemaId} = this.opts
525 const root = new SchemaEnv({schema: {}, schemaId})
526 sch = resolveSchema.call(this, root, keyRef)
527 if (!sch) return
528 this.refs[keyRef] = sch
529 }
530 return (sch.validate || this._compileSchemaEnv(sch)) as AnyValidateFunction<T> | undefined
531 }
532
533 // Remove cached schema(s).
534 // If no parameter is passed all schemas but meta-schemas are removed.
535 // If RegExp is passed all schemas with key/id matching pattern but meta-schemas are removed.
536 // Even if schema is referenced by other schemas it still can be removed as other schemas have local references.
537 removeSchema(schemaKeyRef?: AnySchema | string | RegExp): Ajv {
538 if (schemaKeyRef instanceof RegExp) {
539 this._removeAllSchemas(this.schemas, schemaKeyRef)
540 this._removeAllSchemas(this.refs, schemaKeyRef)
541 return this
542 }
543 switch (typeof schemaKeyRef) {
544 case "undefined":
545 this._removeAllSchemas(this.schemas)
546 this._removeAllSchemas(this.refs)
547 this._cache.clear()
548 return this
549 case "string": {
550 const sch = getSchEnv.call(this, schemaKeyRef)
551 if (typeof sch == "object") this._cache.delete(sch.schema)
552 delete this.schemas[schemaKeyRef]
553 delete this.refs[schemaKeyRef]
554 return this
555 }
556 case "object": {
557 const cacheKey = schemaKeyRef
558 this._cache.delete(cacheKey)
559 let id = schemaKeyRef[this.opts.schemaId]
560 if (id) {
561 id = normalizeId(id)
562 delete this.schemas[id]
563 delete this.refs[id]
564 }
565 return this
566 }
567 default:
568 throw new Error("ajv.removeSchema: invalid parameter")
569 }
570 }
571
572 // add "vocabulary" - a collection of keywords
573 addVocabulary(definitions: Vocabulary): Ajv {
574 for (const def of definitions) this.addKeyword(def)
575 return this
576 }
577
578 addKeyword(
579 kwdOrDef: string | KeywordDefinition,
580 def?: KeywordDefinition // deprecated
581 ): Ajv {
582 let keyword: string | string[]
583 if (typeof kwdOrDef == "string") {
584 keyword = kwdOrDef
585 if (typeof def == "object") {
586 this.logger.warn("these parameters are deprecated, see docs for addKeyword")
587 def.keyword = keyword
588 }
589 } else if (typeof kwdOrDef == "object" && def === undefined) {
590 def = kwdOrDef
591 keyword = def.keyword
592 if (Array.isArray(keyword) && !keyword.length) {
593 throw new Error("addKeywords: keyword must be string or non-empty array")
594 }
595 } else {
596 throw new Error("invalid addKeywords parameters")
597 }
598
599 checkKeyword.call(this, keyword, def)
600 if (!def) {
601 eachItem(keyword, (kwd) => addRule.call(this, kwd))
602 return this
603 }
604 keywordMetaschema.call(this, def)
605 const definition: AddedKeywordDefinition = {
606 ...def,
607 type: getJSONTypes(def.type),
608 schemaType: getJSONTypes(def.schemaType),
609 }
610 eachItem(
611 keyword,
612 definition.type.length === 0
613 ? (k) => addRule.call(this, k, definition)
614 : (k) => definition.type.forEach((t) => addRule.call(this, k, definition, t))
615 )
616 return this
617 }
618
619 getKeyword(keyword: string): AddedKeywordDefinition | boolean {
620 const rule = this.RULES.all[keyword]
621 return typeof rule == "object" ? rule.definition : !!rule
622 }
623
624 // Remove keyword
625 removeKeyword(keyword: string): Ajv {
626 // TODO return type should be Ajv
627 const {RULES} = this
628 delete RULES.keywords[keyword]
629 delete RULES.all[keyword]
630 for (const group of RULES.rules) {
631 const i = group.rules.findIndex((rule) => rule.keyword === keyword)
632 if (i >= 0) group.rules.splice(i, 1)
633 }
634 return this
635 }
636
637 // Add format
638 addFormat(name: string, format: Format): Ajv {
639 if (typeof format == "string") format = new RegExp(format)
640 this.formats[name] = format
641 return this
642 }
643
644 errorsText(
645 errors: ErrorObject[] | null | undefined = this.errors, // optional array of validation errors
646 {separator = ", ", dataVar = "data"}: ErrorsTextOptions = {} // optional options with properties `separator` and `dataVar`
647 ): string {
648 if (!errors || errors.length === 0) return "No errors"
649 return errors
650 .map((e) => `${dataVar}${e.instancePath} ${e.message}`)
651 .reduce((text, msg) => text + separator + msg)
652 }
653
654 $dataMetaSchema(metaSchema: AnySchemaObject, keywordsJsonPointers: string[]): AnySchemaObject {
655 const rules = this.RULES.all
656 metaSchema = JSON.parse(JSON.stringify(metaSchema))
657 for (const jsonPointer of keywordsJsonPointers) {
658 const segments = jsonPointer.split("/").slice(1) // first segment is an empty string
659 let keywords = metaSchema
660 for (const seg of segments) keywords = keywords[seg] as AnySchemaObject
661
662 for (const key in rules) {
663 const rule = rules[key]
664 if (typeof rule != "object") continue
665 const {$data} = rule.definition
666 const schema = keywords[key] as AnySchemaObject | undefined
667 if ($data && schema) keywords[key] = schemaOrData(schema)
668 }
669 }
670
671 return metaSchema
672 }
673
674 private _removeAllSchemas(schemas: {[Ref in string]?: SchemaEnv | string}, regex?: RegExp): void {
675 for (const keyRef in schemas) {
676 const sch = schemas[keyRef]
677 if (!regex || regex.test(keyRef)) {
678 if (typeof sch == "string") {
679 delete schemas[keyRef]
680 } else if (sch && !sch.meta) {
681 this._cache.delete(sch.schema)
682 delete schemas[keyRef]
683 }
684 }
685 }
686 }
687
688 _addSchema(
689 schema: AnySchema,
690 meta?: boolean,
691 baseId?: string,
692 validateSchema = this.opts.validateSchema,
693 addSchema = this.opts.addUsedSchema
694 ): SchemaEnv {
695 let id: string | undefined
696 const {schemaId} = this.opts
697 if (typeof schema == "object") {
698 id = schema[schemaId]
699 } else {
700 if (this.opts.jtd) throw new Error("schema must be object")
701 else if (typeof schema != "boolean") throw new Error("schema must be object or boolean")
702 }
703 let sch = this._cache.get(schema)
704 if (sch !== undefined) return sch
705
706 baseId = normalizeId(id || baseId)
707 const localRefs = getSchemaRefs.call(this, schema, baseId)
708 sch = new SchemaEnv({schema, schemaId, meta, baseId, localRefs})
709 this._cache.set(sch.schema, sch)
710 if (addSchema && !baseId.startsWith("#")) {
711 // TODO atm it is allowed to overwrite schemas without id (instead of not adding them)
712 if (baseId) this._checkUnique(baseId)
713 this.refs[baseId] = sch
714 }
715 if (validateSchema) this.validateSchema(schema, true)
716 return sch
717 }
718
719 private _checkUnique(id: string): void {
720 if (this.schemas[id] || this.refs[id]) {
721 throw new Error(`schema with key or id "${id}" already exists`)
722 }
723 }
724
725 private _compileSchemaEnv(sch: SchemaEnv): AnyValidateFunction {
726 if (sch.meta) this._compileMetaSchema(sch)
727 else compileSchema.call(this, sch)
728
729 /* istanbul ignore if */
730 if (!sch.validate) throw new Error("ajv implementation error")
731 return sch.validate
732 }
733
734 private _compileMetaSchema(sch: SchemaEnv): void {
735 const currentOpts = this.opts
736 this.opts = this._metaOpts
737 try {
738 compileSchema.call(this, sch)
739 } finally {
740 this.opts = currentOpts
741 }
742 }
743}
744
745export interface ErrorsTextOptions {
746 separator?: string
747 dataVar?: string
748}
749
750function checkOptions(
751 this: Ajv,
752 checkOpts: OptionsInfo<RemovedOptions | DeprecatedOptions>,
753 options: Options & RemovedOptions,
754 msg: string,
755 log: "warn" | "error" = "error"
756): void {
757 for (const key in checkOpts) {
758 const opt = key as keyof typeof checkOpts
759 if (opt in options) this.logger[log](`${msg}: option ${key}. ${checkOpts[opt]}`)
760 }
761}
762
763function getSchEnv(this: Ajv, keyRef: string): SchemaEnv | string | undefined {
764 keyRef = normalizeId(keyRef) // TODO tests fail without this line
765 return this.schemas[keyRef] || this.refs[keyRef]
766}
767
768function addInitialSchemas(this: Ajv): void {
769 const optsSchemas = this.opts.schemas
770 if (!optsSchemas) return
771 if (Array.isArray(optsSchemas)) this.addSchema(optsSchemas)
772 else for (const key in optsSchemas) this.addSchema(optsSchemas[key] as AnySchema, key)
773}
774
775function addInitialFormats(this: Ajv): void {
776 for (const name in this.opts.formats) {
777 const format = this.opts.formats[name]
778 if (format) this.addFormat(name, format)
779 }
780}
781
782function addInitialKeywords(
783 this: Ajv,
784 defs: Vocabulary | {[K in string]?: KeywordDefinition}
785): void {
786 if (Array.isArray(defs)) {
787 this.addVocabulary(defs)
788 return
789 }
790 this.logger.warn("keywords option as map is deprecated, pass array")
791 for (const keyword in defs) {
792 const def = defs[keyword] as KeywordDefinition
793 if (!def.keyword) def.keyword = keyword
794 this.addKeyword(def)
795 }
796}
797
798function getMetaSchemaOptions(this: Ajv): InstanceOptions {
799 const metaOpts = {...this.opts}
800 for (const opt of META_IGNORE_OPTIONS) delete metaOpts[opt]
801 return metaOpts
802}
803
804const noLogs = {log() {}, warn() {}, error() {}}
805
806function getLogger(logger?: Partial<Logger> | false): Logger {
807 if (logger === false) return noLogs
808 if (logger === undefined) return console
809 if (logger.log && logger.warn && logger.error) return logger as Logger
810 throw new Error("logger must implement log, warn and error methods")
811}
812
813const KEYWORD_NAME = /^[a-z_$][a-z0-9_$:-]*$/i
814
815function checkKeyword(this: Ajv, keyword: string | string[], def?: KeywordDefinition): void {
816 const {RULES} = this
817 eachItem(keyword, (kwd) => {
818 if (RULES.keywords[kwd]) throw new Error(`Keyword ${kwd} is already defined`)
819 if (!KEYWORD_NAME.test(kwd)) throw new Error(`Keyword ${kwd} has invalid name`)
820 })
821 if (!def) return
822 if (def.$data && !("code" in def || "validate" in def)) {
823 throw new Error('$data keyword must have "code" or "validate" function')
824 }
825}
826
827function addRule(
828 this: Ajv,
829 keyword: string,
830 definition?: AddedKeywordDefinition,
831 dataType?: JSONType
832): void {
833 const post = definition?.post
834 if (dataType && post) throw new Error('keyword with "post" flag cannot have "type"')
835 const {RULES} = this
836 let ruleGroup = post ? RULES.post : RULES.rules.find(({type: t}) => t === dataType)
837 if (!ruleGroup) {
838 ruleGroup = {type: dataType, rules: []}
839 RULES.rules.push(ruleGroup)
840 }
841 RULES.keywords[keyword] = true
842 if (!definition) return
843
844 const rule: Rule = {
845 keyword,
846 definition: {
847 ...definition,
848 type: getJSONTypes(definition.type),
849 schemaType: getJSONTypes(definition.schemaType),
850 },
851 }
852 if (definition.before) addBeforeRule.call(this, ruleGroup, rule, definition.before)
853 else ruleGroup.rules.push(rule)
854 RULES.all[keyword] = rule
855 definition.implements?.forEach((kwd) => this.addKeyword(kwd))
856}
857
858function addBeforeRule(this: Ajv, ruleGroup: RuleGroup, rule: Rule, before: string): void {
859 const i = ruleGroup.rules.findIndex((_rule) => _rule.keyword === before)
860 if (i >= 0) {
861 ruleGroup.rules.splice(i, 0, rule)
862 } else {
863 ruleGroup.rules.push(rule)
864 this.logger.warn(`rule ${before} is not defined`)
865 }
866}
867
868function keywordMetaschema(this: Ajv, def: KeywordDefinition): void {
869 let {metaSchema} = def
870 if (metaSchema === undefined) return
871 if (def.$data && this.opts.$data) metaSchema = schemaOrData(metaSchema)
872 def.validateSchema = this.compile(metaSchema, true)
873}
874
875const $dataRef = {
876 $ref: "https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#",
877}
878
879function schemaOrData(schema: AnySchema): AnySchemaObject {
880 return {anyOf: [schema, $dataRef]}
881}