2 Object.defineProperty(exports, "__esModule", { value: true });
3 exports.CodeGen = exports.Name = exports.nil = exports.stringify = exports.str = exports._ = exports.KeywordCxt = void 0;
4 var validate_1 = require("./compile/validate");
5 Object.defineProperty(exports, "KeywordCxt", { enumerable: true, get: function () { return validate_1.KeywordCxt; } });
6 var codegen_1 = require("./compile/codegen");
7 Object.defineProperty(exports, "_", { enumerable: true, get: function () { return codegen_1._; } });
8 Object.defineProperty(exports, "str", { enumerable: true, get: function () { return codegen_1.str; } });
9 Object.defineProperty(exports, "stringify", { enumerable: true, get: function () { return codegen_1.stringify; } });
10 Object.defineProperty(exports, "nil", { enumerable: true, get: function () { return codegen_1.nil; } });
11 Object.defineProperty(exports, "Name", { enumerable: true, get: function () { return codegen_1.Name; } });
12 Object.defineProperty(exports, "CodeGen", { enumerable: true, get: function () { return codegen_1.CodeGen; } });
13 const validation_error_1 = require("./runtime/validation_error");
14 const ref_error_1 = require("./compile/ref_error");
15 const rules_1 = require("./compile/rules");
16 const compile_1 = require("./compile");
17 const codegen_2 = require("./compile/codegen");
18 const resolve_1 = require("./compile/resolve");
19 const dataType_1 = require("./compile/validate/dataType");
20 const util_1 = require("./compile/util");
21 const $dataRefSchema = require("./refs/data.json");
22 const defaultRegExp = (str, flags) => new RegExp(str, flags);
23 defaultRegExp.code = "new RegExp";
24 const META_IGNORE_OPTIONS = ["removeAdditional", "useDefaults", "coerceTypes"];
25 const EXT_SCOPE_NAMES = new Set([
40 const removedOptions = {
42 format: "`validateFormats: false` can be used instead.",
43 nullable: '"nullable" keyword is supported by default.',
44 jsonPointers: "Deprecated jsPropertySyntax can be used instead.",
45 extendRefs: "Deprecated ignoreKeywordsWithRef can be used instead.",
46 missingRefs: "Pass empty schema with $id that should be ignored to ajv.addSchema.",
47 processCode: "Use option `code: {process: (code, schemaEnv: object) => string}`",
48 sourceCode: "Use option `code: {source: true}`",
49 strictDefaults: "It is default now, see option `strict`.",
50 strictKeywords: "It is default now, see option `strict`.",
51 uniqueItems: '"uniqueItems" keyword is always validated.',
52 unknownFormats: "Disable strict mode or pass `true` to `ajv.addFormat` (or `formats` option).",
53 cache: "Map is used as cache, schema object as key.",
54 serialize: "Map is used as cache, schema object as key.",
55 ajvErrors: "It is default now.",
57 const deprecatedOptions = {
58 ignoreKeywordsWithRef: "",
60 unicode: '"minLength"/"maxLength" account for unicode characters by default.',
62 const MAX_EXPRESSION = 200;
63 // eslint-disable-next-line complexity
64 function requiredOptions(o) {
65 var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k, _l, _m, _o, _p, _q, _r, _s, _t, _u, _v, _w, _x, _y, _z;
67 const _optz = (_a = o.code) === null || _a === void 0 ? void 0 : _a.optimize;
68 const optimize = _optz === true || _optz === undefined ? 1 : _optz || 0;
69 const regExp = (_c = (_b = o.code) === null || _b === void 0 ? void 0 : _b.regExp) !== null && _c !== void 0 ? _c : defaultRegExp;
71 strictSchema: (_e = (_d = o.strictSchema) !== null && _d !== void 0 ? _d : s) !== null && _e !== void 0 ? _e : true,
72 strictNumbers: (_g = (_f = o.strictNumbers) !== null && _f !== void 0 ? _f : s) !== null && _g !== void 0 ? _g : true,
73 strictTypes: (_j = (_h = o.strictTypes) !== null && _h !== void 0 ? _h : s) !== null && _j !== void 0 ? _j : "log",
74 strictTuples: (_l = (_k = o.strictTuples) !== null && _k !== void 0 ? _k : s) !== null && _l !== void 0 ? _l : "log",
75 strictRequired: (_o = (_m = o.strictRequired) !== null && _m !== void 0 ? _m : s) !== null && _o !== void 0 ? _o : false,
76 code: o.code ? { ...o.code, optimize, regExp } : { optimize, regExp },
77 loopRequired: (_p = o.loopRequired) !== null && _p !== void 0 ? _p : MAX_EXPRESSION,
78 loopEnum: (_q = o.loopEnum) !== null && _q !== void 0 ? _q : MAX_EXPRESSION,
79 meta: (_r = o.meta) !== null && _r !== void 0 ? _r : true,
80 messages: (_s = o.messages) !== null && _s !== void 0 ? _s : true,
81 inlineRefs: (_t = o.inlineRefs) !== null && _t !== void 0 ? _t : true,
82 schemaId: (_u = o.schemaId) !== null && _u !== void 0 ? _u : "$id",
83 addUsedSchema: (_v = o.addUsedSchema) !== null && _v !== void 0 ? _v : true,
84 validateSchema: (_w = o.validateSchema) !== null && _w !== void 0 ? _w : true,
85 validateFormats: (_x = o.validateFormats) !== null && _x !== void 0 ? _x : true,
86 unicodeRegExp: (_y = o.unicodeRegExp) !== null && _y !== void 0 ? _y : true,
87 int32range: (_z = o.int32range) !== null && _z !== void 0 ? _z : true,
91 constructor(opts = {}) {
95 this._compilations = new Set();
97 this._cache = new Map();
98 opts = this.opts = { ...opts, ...requiredOptions(opts) };
99 const { es5, lines } = this.opts.code;
100 this.scope = new codegen_2.ValueScope({ scope: {}, prefixes: EXT_SCOPE_NAMES, es5, lines });
101 this.logger = getLogger(opts.logger);
102 const formatOpt = opts.validateFormats;
103 opts.validateFormats = false;
104 this.RULES = (0, rules_1.getRules)();
105 checkOptions.call(this, removedOptions, opts, "NOT SUPPORTED");
106 checkOptions.call(this, deprecatedOptions, opts, "DEPRECATED", "warn");
107 this._metaOpts = getMetaSchemaOptions.call(this);
109 addInitialFormats.call(this);
110 this._addVocabularies();
111 this._addDefaultMetaSchema();
113 addInitialKeywords.call(this, opts.keywords);
114 if (typeof opts.meta == "object")
115 this.addMetaSchema(opts.meta);
116 addInitialSchemas.call(this);
117 opts.validateFormats = formatOpt;
120 this.addKeyword("$async");
122 _addDefaultMetaSchema() {
123 const { $data, meta, schemaId } = this.opts;
124 let _dataRefSchema = $dataRefSchema;
125 if (schemaId === "id") {
126 _dataRefSchema = { ...$dataRefSchema };
127 _dataRefSchema.id = _dataRefSchema.$id;
128 delete _dataRefSchema.$id;
131 this.addMetaSchema(_dataRefSchema, _dataRefSchema[schemaId], false);
134 const { meta, schemaId } = this.opts;
135 return (this.opts.defaultMeta = typeof meta == "object" ? meta[schemaId] || meta : undefined);
137 validate(schemaKeyRef, // key, ref or schema object
138 data // to be validated
141 if (typeof schemaKeyRef == "string") {
142 v = this.getSchema(schemaKeyRef);
144 throw new Error(`no schema with key or ref "${schemaKeyRef}"`);
147 v = this.compile(schemaKeyRef);
149 const valid = v(data);
150 if (!("$async" in v))
151 this.errors = v.errors;
154 compile(schema, _meta) {
155 const sch = this._addSchema(schema, _meta);
156 return (sch.validate || this._compileSchemaEnv(sch));
158 compileAsync(schema, meta) {
159 if (typeof this.opts.loadSchema != "function") {
160 throw new Error("options.loadSchema should be a function");
162 const { loadSchema } = this.opts;
163 return runCompileAsync.call(this, schema, meta);
164 async function runCompileAsync(_schema, _meta) {
165 await loadMetaSchema.call(this, _schema.$schema);
166 const sch = this._addSchema(_schema, _meta);
167 return sch.validate || _compileAsync.call(this, sch);
169 async function loadMetaSchema($ref) {
170 if ($ref && !this.getSchema($ref)) {
171 await runCompileAsync.call(this, { $ref }, true);
174 async function _compileAsync(sch) {
176 return this._compileSchemaEnv(sch);
179 if (!(e instanceof ref_error_1.default))
181 checkLoaded.call(this, e);
182 await loadMissingSchema.call(this, e.missingSchema);
183 return _compileAsync.call(this, sch);
186 function checkLoaded({ missingSchema: ref, missingRef }) {
187 if (this.refs[ref]) {
188 throw new Error(`AnySchema ${ref} is loaded but ${missingRef} cannot be resolved`);
191 async function loadMissingSchema(ref) {
192 const _schema = await _loadSchema.call(this, ref);
194 await loadMetaSchema.call(this, _schema.$schema);
196 this.addSchema(_schema, ref, meta);
198 async function _loadSchema(ref) {
199 const p = this._loading[ref];
203 return await (this._loading[ref] = loadSchema(ref));
206 delete this._loading[ref];
210 // Adds schema to the instance
211 addSchema(schema, // If array is passed, `key` will be ignored
212 key, // 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`.
213 _meta, // true if schema is a meta-schema. Used internally, addMetaSchema should be used instead.
214 _validateSchema = this.opts.validateSchema // false to skip schema validation. Used internally, option validateSchema should be used instead.
216 if (Array.isArray(schema)) {
217 for (const sch of schema)
218 this.addSchema(sch, undefined, _meta, _validateSchema);
222 if (typeof schema === "object") {
223 const { schemaId } = this.opts;
224 id = schema[schemaId];
225 if (id !== undefined && typeof id != "string") {
226 throw new Error(`schema ${schemaId} must be string`);
229 key = (0, resolve_1.normalizeId)(key || id);
230 this._checkUnique(key);
231 this.schemas[key] = this._addSchema(schema, _meta, key, _validateSchema, true);
234 // Add schema that will be used to validate other schemas
235 // options in META_IGNORE_OPTIONS are alway set to false
236 addMetaSchema(schema, key, // schema key
237 _validateSchema = this.opts.validateSchema // false to skip schema validation, can be used to override validateSchema option for meta-schema
239 this.addSchema(schema, key, true, _validateSchema);
242 // Validate schema against its meta-schema
243 validateSchema(schema, throwOrLogError) {
244 if (typeof schema == "boolean")
247 $schema = schema.$schema;
248 if ($schema !== undefined && typeof $schema != "string") {
249 throw new Error("$schema must be a string");
251 $schema = $schema || this.opts.defaultMeta || this.defaultMeta();
253 this.logger.warn("meta-schema not available");
257 const valid = this.validate($schema, schema);
258 if (!valid && throwOrLogError) {
259 const message = "schema is invalid: " + this.errorsText();
260 if (this.opts.validateSchema === "log")
261 this.logger.error(message);
263 throw new Error(message);
267 // Get compiled schema by `key` or `ref`.
268 // (`key` that was passed to `addSchema` or full schema reference - `schema.$id` or resolved id)
271 while (typeof (sch = getSchEnv.call(this, keyRef)) == "string")
273 if (sch === undefined) {
274 const { schemaId } = this.opts;
275 const root = new compile_1.SchemaEnv({ schema: {}, schemaId });
276 sch = compile_1.resolveSchema.call(this, root, keyRef);
279 this.refs[keyRef] = sch;
281 return (sch.validate || this._compileSchemaEnv(sch));
283 // Remove cached schema(s).
284 // If no parameter is passed all schemas but meta-schemas are removed.
285 // If RegExp is passed all schemas with key/id matching pattern but meta-schemas are removed.
286 // Even if schema is referenced by other schemas it still can be removed as other schemas have local references.
287 removeSchema(schemaKeyRef) {
288 if (schemaKeyRef instanceof RegExp) {
289 this._removeAllSchemas(this.schemas, schemaKeyRef);
290 this._removeAllSchemas(this.refs, schemaKeyRef);
293 switch (typeof schemaKeyRef) {
295 this._removeAllSchemas(this.schemas);
296 this._removeAllSchemas(this.refs);
300 const sch = getSchEnv.call(this, schemaKeyRef);
301 if (typeof sch == "object")
302 this._cache.delete(sch.schema);
303 delete this.schemas[schemaKeyRef];
304 delete this.refs[schemaKeyRef];
308 const cacheKey = schemaKeyRef;
309 this._cache.delete(cacheKey);
310 let id = schemaKeyRef[this.opts.schemaId];
312 id = (0, resolve_1.normalizeId)(id);
313 delete this.schemas[id];
314 delete this.refs[id];
319 throw new Error("ajv.removeSchema: invalid parameter");
322 // add "vocabulary" - a collection of keywords
323 addVocabulary(definitions) {
324 for (const def of definitions)
325 this.addKeyword(def);
328 addKeyword(kwdOrDef, def // deprecated
331 if (typeof kwdOrDef == "string") {
333 if (typeof def == "object") {
334 this.logger.warn("these parameters are deprecated, see docs for addKeyword");
335 def.keyword = keyword;
338 else if (typeof kwdOrDef == "object" && def === undefined) {
340 keyword = def.keyword;
341 if (Array.isArray(keyword) && !keyword.length) {
342 throw new Error("addKeywords: keyword must be string or non-empty array");
346 throw new Error("invalid addKeywords parameters");
348 checkKeyword.call(this, keyword, def);
350 (0, util_1.eachItem)(keyword, (kwd) => addRule.call(this, kwd));
353 keywordMetaschema.call(this, def);
356 type: (0, dataType_1.getJSONTypes)(def.type),
357 schemaType: (0, dataType_1.getJSONTypes)(def.schemaType),
359 (0, util_1.eachItem)(keyword, definition.type.length === 0
360 ? (k) => addRule.call(this, k, definition)
361 : (k) => definition.type.forEach((t) => addRule.call(this, k, definition, t)));
364 getKeyword(keyword) {
365 const rule = this.RULES.all[keyword];
366 return typeof rule == "object" ? rule.definition : !!rule;
369 removeKeyword(keyword) {
370 // TODO return type should be Ajv
371 const { RULES } = this;
372 delete RULES.keywords[keyword];
373 delete RULES.all[keyword];
374 for (const group of RULES.rules) {
375 const i = group.rules.findIndex((rule) => rule.keyword === keyword);
377 group.rules.splice(i, 1);
382 addFormat(name, format) {
383 if (typeof format == "string")
384 format = new RegExp(format);
385 this.formats[name] = format;
388 errorsText(errors = this.errors, // optional array of validation errors
389 { separator = ", ", dataVar = "data" } = {} // optional options with properties `separator` and `dataVar`
391 if (!errors || errors.length === 0)
394 .map((e) => `${dataVar}${e.instancePath} ${e.message}`)
395 .reduce((text, msg) => text + separator + msg);
397 $dataMetaSchema(metaSchema, keywordsJsonPointers) {
398 const rules = this.RULES.all;
399 metaSchema = JSON.parse(JSON.stringify(metaSchema));
400 for (const jsonPointer of keywordsJsonPointers) {
401 const segments = jsonPointer.split("/").slice(1); // first segment is an empty string
402 let keywords = metaSchema;
403 for (const seg of segments)
404 keywords = keywords[seg];
405 for (const key in rules) {
406 const rule = rules[key];
407 if (typeof rule != "object")
409 const { $data } = rule.definition;
410 const schema = keywords[key];
412 keywords[key] = schemaOrData(schema);
417 _removeAllSchemas(schemas, regex) {
418 for (const keyRef in schemas) {
419 const sch = schemas[keyRef];
420 if (!regex || regex.test(keyRef)) {
421 if (typeof sch == "string") {
422 delete schemas[keyRef];
424 else if (sch && !sch.meta) {
425 this._cache.delete(sch.schema);
426 delete schemas[keyRef];
431 _addSchema(schema, meta, baseId, validateSchema = this.opts.validateSchema, addSchema = this.opts.addUsedSchema) {
433 const { schemaId } = this.opts;
434 if (typeof schema == "object") {
435 id = schema[schemaId];
439 throw new Error("schema must be object");
440 else if (typeof schema != "boolean")
441 throw new Error("schema must be object or boolean");
443 let sch = this._cache.get(schema);
444 if (sch !== undefined)
446 baseId = (0, resolve_1.normalizeId)(id || baseId);
447 const localRefs = resolve_1.getSchemaRefs.call(this, schema, baseId);
448 sch = new compile_1.SchemaEnv({ schema, schemaId, meta, baseId, localRefs });
449 this._cache.set(sch.schema, sch);
450 if (addSchema && !baseId.startsWith("#")) {
451 // TODO atm it is allowed to overwrite schemas without id (instead of not adding them)
453 this._checkUnique(baseId);
454 this.refs[baseId] = sch;
457 this.validateSchema(schema, true);
461 if (this.schemas[id] || this.refs[id]) {
462 throw new Error(`schema with key or id "${id}" already exists`);
465 _compileSchemaEnv(sch) {
467 this._compileMetaSchema(sch);
469 compile_1.compileSchema.call(this, sch);
470 /* istanbul ignore if */
472 throw new Error("ajv implementation error");
475 _compileMetaSchema(sch) {
476 const currentOpts = this.opts;
477 this.opts = this._metaOpts;
479 compile_1.compileSchema.call(this, sch);
482 this.opts = currentOpts;
486 exports.default = Ajv;
487 Ajv.ValidationError = validation_error_1.default;
488 Ajv.MissingRefError = ref_error_1.default;
489 function checkOptions(checkOpts, options, msg, log = "error") {
490 for (const key in checkOpts) {
493 this.logger[log](`${msg}: option ${key}. ${checkOpts[opt]}`);
496 function getSchEnv(keyRef) {
497 keyRef = (0, resolve_1.normalizeId)(keyRef); // TODO tests fail without this line
498 return this.schemas[keyRef] || this.refs[keyRef];
500 function addInitialSchemas() {
501 const optsSchemas = this.opts.schemas;
504 if (Array.isArray(optsSchemas))
505 this.addSchema(optsSchemas);
507 for (const key in optsSchemas)
508 this.addSchema(optsSchemas[key], key);
510 function addInitialFormats() {
511 for (const name in this.opts.formats) {
512 const format = this.opts.formats[name];
514 this.addFormat(name, format);
517 function addInitialKeywords(defs) {
518 if (Array.isArray(defs)) {
519 this.addVocabulary(defs);
522 this.logger.warn("keywords option as map is deprecated, pass array");
523 for (const keyword in defs) {
524 const def = defs[keyword];
526 def.keyword = keyword;
527 this.addKeyword(def);
530 function getMetaSchemaOptions() {
531 const metaOpts = { ...this.opts };
532 for (const opt of META_IGNORE_OPTIONS)
533 delete metaOpts[opt];
536 const noLogs = { log() { }, warn() { }, error() { } };
537 function getLogger(logger) {
538 if (logger === false)
540 if (logger === undefined)
542 if (logger.log && logger.warn && logger.error)
544 throw new Error("logger must implement log, warn and error methods");
546 const KEYWORD_NAME = /^[a-z_$][a-z0-9_$:-]*$/i;
547 function checkKeyword(keyword, def) {
548 const { RULES } = this;
549 (0, util_1.eachItem)(keyword, (kwd) => {
550 if (RULES.keywords[kwd])
551 throw new Error(`Keyword ${kwd} is already defined`);
552 if (!KEYWORD_NAME.test(kwd))
553 throw new Error(`Keyword ${kwd} has invalid name`);
557 if (def.$data && !("code" in def || "validate" in def)) {
558 throw new Error('$data keyword must have "code" or "validate" function');
561 function addRule(keyword, definition, dataType) {
563 const post = definition === null || definition === void 0 ? void 0 : definition.post;
564 if (dataType && post)
565 throw new Error('keyword with "post" flag cannot have "type"');
566 const { RULES } = this;
567 let ruleGroup = post ? RULES.post : RULES.rules.find(({ type: t }) => t === dataType);
569 ruleGroup = { type: dataType, rules: [] };
570 RULES.rules.push(ruleGroup);
572 RULES.keywords[keyword] = true;
579 type: (0, dataType_1.getJSONTypes)(definition.type),
580 schemaType: (0, dataType_1.getJSONTypes)(definition.schemaType),
583 if (definition.before)
584 addBeforeRule.call(this, ruleGroup, rule, definition.before);
586 ruleGroup.rules.push(rule);
587 RULES.all[keyword] = rule;
588 (_a = definition.implements) === null || _a === void 0 ? void 0 : _a.forEach((kwd) => this.addKeyword(kwd));
590 function addBeforeRule(ruleGroup, rule, before) {
591 const i = ruleGroup.rules.findIndex((_rule) => _rule.keyword === before);
593 ruleGroup.rules.splice(i, 0, rule);
596 ruleGroup.rules.push(rule);
597 this.logger.warn(`rule ${before} is not defined`);
600 function keywordMetaschema(def) {
601 let { metaSchema } = def;
602 if (metaSchema === undefined)
604 if (def.$data && this.opts.$data)
605 metaSchema = schemaOrData(metaSchema);
606 def.validateSchema = this.compile(metaSchema, true);
609 $ref: "https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#",
611 function schemaOrData(schema) {
612 return { anyOf: [schema, $dataRef] };
614 //# sourceMappingURL=core.js.map