1 | "use strict";
|
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 uri_1 = require("./runtime/uri");
|
23 | const defaultRegExp = (str, flags) => new RegExp(str, flags);
|
24 | defaultRegExp.code = "new RegExp";
|
25 | const META_IGNORE_OPTIONS = ["removeAdditional", "useDefaults", "coerceTypes"];
|
26 | const EXT_SCOPE_NAMES = new Set([
|
27 | "validate",
|
28 | "serialize",
|
29 | "parse",
|
30 | "wrapper",
|
31 | "root",
|
32 | "schema",
|
33 | "keyword",
|
34 | "pattern",
|
35 | "formats",
|
36 | "validate$data",
|
37 | "func",
|
38 | "obj",
|
39 | "Error",
|
40 | ]);
|
41 | const removedOptions = {
|
42 | errorDataPath: "",
|
43 | format: "`validateFormats: false` can be used instead.",
|
44 | nullable: '"nullable" keyword is supported by default.',
|
45 | jsonPointers: "Deprecated jsPropertySyntax can be used instead.",
|
46 | extendRefs: "Deprecated ignoreKeywordsWithRef can be used instead.",
|
47 | missingRefs: "Pass empty schema with $id that should be ignored to ajv.addSchema.",
|
48 | processCode: "Use option `code: {process: (code, schemaEnv: object) => string}`",
|
49 | sourceCode: "Use option `code: {source: true}`",
|
50 | strictDefaults: "It is default now, see option `strict`.",
|
51 | strictKeywords: "It is default now, see option `strict`.",
|
52 | uniqueItems: '"uniqueItems" keyword is always validated.',
|
53 | unknownFormats: "Disable strict mode or pass `true` to `ajv.addFormat` (or `formats` option).",
|
54 | cache: "Map is used as cache, schema object as key.",
|
55 | serialize: "Map is used as cache, schema object as key.",
|
56 | ajvErrors: "It is default now.",
|
57 | };
|
58 | const deprecatedOptions = {
|
59 | ignoreKeywordsWithRef: "",
|
60 | jsPropertySyntax: "",
|
61 | unicode: '"minLength"/"maxLength" account for unicode characters by default.',
|
62 | };
|
63 | const MAX_EXPRESSION = 200;
|
64 |
|
65 | function requiredOptions(o) {
|
66 | 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, _0;
|
67 | const s = o.strict;
|
68 | const _optz = (_a = o.code) === null || _a === void 0 ? void 0 : _a.optimize;
|
69 | const optimize = _optz === true || _optz === undefined ? 1 : _optz || 0;
|
70 | const regExp = (_c = (_b = o.code) === null || _b === void 0 ? void 0 : _b.regExp) !== null && _c !== void 0 ? _c : defaultRegExp;
|
71 | const uriResolver = (_d = o.uriResolver) !== null && _d !== void 0 ? _d : uri_1.default;
|
72 | return {
|
73 | strictSchema: (_f = (_e = o.strictSchema) !== null && _e !== void 0 ? _e : s) !== null && _f !== void 0 ? _f : true,
|
74 | strictNumbers: (_h = (_g = o.strictNumbers) !== null && _g !== void 0 ? _g : s) !== null && _h !== void 0 ? _h : true,
|
75 | strictTypes: (_k = (_j = o.strictTypes) !== null && _j !== void 0 ? _j : s) !== null && _k !== void 0 ? _k : "log",
|
76 | strictTuples: (_m = (_l = o.strictTuples) !== null && _l !== void 0 ? _l : s) !== null && _m !== void 0 ? _m : "log",
|
77 | strictRequired: (_p = (_o = o.strictRequired) !== null && _o !== void 0 ? _o : s) !== null && _p !== void 0 ? _p : false,
|
78 | code: o.code ? { ...o.code, optimize, regExp } : { optimize, regExp },
|
79 | loopRequired: (_q = o.loopRequired) !== null && _q !== void 0 ? _q : MAX_EXPRESSION,
|
80 | loopEnum: (_r = o.loopEnum) !== null && _r !== void 0 ? _r : MAX_EXPRESSION,
|
81 | meta: (_s = o.meta) !== null && _s !== void 0 ? _s : true,
|
82 | messages: (_t = o.messages) !== null && _t !== void 0 ? _t : true,
|
83 | inlineRefs: (_u = o.inlineRefs) !== null && _u !== void 0 ? _u : true,
|
84 | schemaId: (_v = o.schemaId) !== null && _v !== void 0 ? _v : "$id",
|
85 | addUsedSchema: (_w = o.addUsedSchema) !== null && _w !== void 0 ? _w : true,
|
86 | validateSchema: (_x = o.validateSchema) !== null && _x !== void 0 ? _x : true,
|
87 | validateFormats: (_y = o.validateFormats) !== null && _y !== void 0 ? _y : true,
|
88 | unicodeRegExp: (_z = o.unicodeRegExp) !== null && _z !== void 0 ? _z : true,
|
89 | int32range: (_0 = o.int32range) !== null && _0 !== void 0 ? _0 : true,
|
90 | uriResolver: uriResolver,
|
91 | };
|
92 | }
|
93 | class Ajv {
|
94 | constructor(opts = {}) {
|
95 | this.schemas = {};
|
96 | this.refs = {};
|
97 | this.formats = {};
|
98 | this._compilations = new Set();
|
99 | this._loading = {};
|
100 | this._cache = new Map();
|
101 | opts = this.opts = { ...opts, ...requiredOptions(opts) };
|
102 | const { es5, lines } = this.opts.code;
|
103 | this.scope = new codegen_2.ValueScope({ scope: {}, prefixes: EXT_SCOPE_NAMES, es5, lines });
|
104 | this.logger = getLogger(opts.logger);
|
105 | const formatOpt = opts.validateFormats;
|
106 | opts.validateFormats = false;
|
107 | this.RULES = (0, rules_1.getRules)();
|
108 | checkOptions.call(this, removedOptions, opts, "NOT SUPPORTED");
|
109 | checkOptions.call(this, deprecatedOptions, opts, "DEPRECATED", "warn");
|
110 | this._metaOpts = getMetaSchemaOptions.call(this);
|
111 | if (opts.formats)
|
112 | addInitialFormats.call(this);
|
113 | this._addVocabularies();
|
114 | this._addDefaultMetaSchema();
|
115 | if (opts.keywords)
|
116 | addInitialKeywords.call(this, opts.keywords);
|
117 | if (typeof opts.meta == "object")
|
118 | this.addMetaSchema(opts.meta);
|
119 | addInitialSchemas.call(this);
|
120 | opts.validateFormats = formatOpt;
|
121 | }
|
122 | _addVocabularies() {
|
123 | this.addKeyword("$async");
|
124 | }
|
125 | _addDefaultMetaSchema() {
|
126 | const { $data, meta, schemaId } = this.opts;
|
127 | let _dataRefSchema = $dataRefSchema;
|
128 | if (schemaId === "id") {
|
129 | _dataRefSchema = { ...$dataRefSchema };
|
130 | _dataRefSchema.id = _dataRefSchema.$id;
|
131 | delete _dataRefSchema.$id;
|
132 | }
|
133 | if (meta && $data)
|
134 | this.addMetaSchema(_dataRefSchema, _dataRefSchema[schemaId], false);
|
135 | }
|
136 | defaultMeta() {
|
137 | const { meta, schemaId } = this.opts;
|
138 | return (this.opts.defaultMeta = typeof meta == "object" ? meta[schemaId] || meta : undefined);
|
139 | }
|
140 | validate(schemaKeyRef,
|
141 | data
|
142 | ) {
|
143 | let v;
|
144 | if (typeof schemaKeyRef == "string") {
|
145 | v = this.getSchema(schemaKeyRef);
|
146 | if (!v)
|
147 | throw new Error(`no schema with key or ref "${schemaKeyRef}"`);
|
148 | }
|
149 | else {
|
150 | v = this.compile(schemaKeyRef);
|
151 | }
|
152 | const valid = v(data);
|
153 | if (!("$async" in v))
|
154 | this.errors = v.errors;
|
155 | return valid;
|
156 | }
|
157 | compile(schema, _meta) {
|
158 | const sch = this._addSchema(schema, _meta);
|
159 | return (sch.validate || this._compileSchemaEnv(sch));
|
160 | }
|
161 | compileAsync(schema, meta) {
|
162 | if (typeof this.opts.loadSchema != "function") {
|
163 | throw new Error("options.loadSchema should be a function");
|
164 | }
|
165 | const { loadSchema } = this.opts;
|
166 | return runCompileAsync.call(this, schema, meta);
|
167 | async function runCompileAsync(_schema, _meta) {
|
168 | await loadMetaSchema.call(this, _schema.$schema);
|
169 | const sch = this._addSchema(_schema, _meta);
|
170 | return sch.validate || _compileAsync.call(this, sch);
|
171 | }
|
172 | async function loadMetaSchema($ref) {
|
173 | if ($ref && !this.getSchema($ref)) {
|
174 | await runCompileAsync.call(this, { $ref }, true);
|
175 | }
|
176 | }
|
177 | async function _compileAsync(sch) {
|
178 | try {
|
179 | return this._compileSchemaEnv(sch);
|
180 | }
|
181 | catch (e) {
|
182 | if (!(e instanceof ref_error_1.default))
|
183 | throw e;
|
184 | checkLoaded.call(this, e);
|
185 | await loadMissingSchema.call(this, e.missingSchema);
|
186 | return _compileAsync.call(this, sch);
|
187 | }
|
188 | }
|
189 | function checkLoaded({ missingSchema: ref, missingRef }) {
|
190 | if (this.refs[ref]) {
|
191 | throw new Error(`AnySchema ${ref} is loaded but ${missingRef} cannot be resolved`);
|
192 | }
|
193 | }
|
194 | async function loadMissingSchema(ref) {
|
195 | const _schema = await _loadSchema.call(this, ref);
|
196 | if (!this.refs[ref])
|
197 | await loadMetaSchema.call(this, _schema.$schema);
|
198 | if (!this.refs[ref])
|
199 | this.addSchema(_schema, ref, meta);
|
200 | }
|
201 | async function _loadSchema(ref) {
|
202 | const p = this._loading[ref];
|
203 | if (p)
|
204 | return p;
|
205 | try {
|
206 | return await (this._loading[ref] = loadSchema(ref));
|
207 | }
|
208 | finally {
|
209 | delete this._loading[ref];
|
210 | }
|
211 | }
|
212 | }
|
213 |
|
214 | addSchema(schema,
|
215 | key,
|
216 | _meta,
|
217 | _validateSchema = this.opts.validateSchema
|
218 | ) {
|
219 | if (Array.isArray(schema)) {
|
220 | for (const sch of schema)
|
221 | this.addSchema(sch, undefined, _meta, _validateSchema);
|
222 | return this;
|
223 | }
|
224 | let id;
|
225 | if (typeof schema === "object") {
|
226 | const { schemaId } = this.opts;
|
227 | id = schema[schemaId];
|
228 | if (id !== undefined && typeof id != "string") {
|
229 | throw new Error(`schema ${schemaId} must be string`);
|
230 | }
|
231 | }
|
232 | key = (0, resolve_1.normalizeId)(key || id);
|
233 | this._checkUnique(key);
|
234 | this.schemas[key] = this._addSchema(schema, _meta, key, _validateSchema, true);
|
235 | return this;
|
236 | }
|
237 |
|
238 |
|
239 | addMetaSchema(schema, key,
|
240 | _validateSchema = this.opts.validateSchema
|
241 | ) {
|
242 | this.addSchema(schema, key, true, _validateSchema);
|
243 | return this;
|
244 | }
|
245 |
|
246 | validateSchema(schema, throwOrLogError) {
|
247 | if (typeof schema == "boolean")
|
248 | return true;
|
249 | let $schema;
|
250 | $schema = schema.$schema;
|
251 | if ($schema !== undefined && typeof $schema != "string") {
|
252 | throw new Error("$schema must be a string");
|
253 | }
|
254 | $schema = $schema || this.opts.defaultMeta || this.defaultMeta();
|
255 | if (!$schema) {
|
256 | this.logger.warn("meta-schema not available");
|
257 | this.errors = null;
|
258 | return true;
|
259 | }
|
260 | const valid = this.validate($schema, schema);
|
261 | if (!valid && throwOrLogError) {
|
262 | const message = "schema is invalid: " + this.errorsText();
|
263 | if (this.opts.validateSchema === "log")
|
264 | this.logger.error(message);
|
265 | else
|
266 | throw new Error(message);
|
267 | }
|
268 | return valid;
|
269 | }
|
270 |
|
271 |
|
272 | getSchema(keyRef) {
|
273 | let sch;
|
274 | while (typeof (sch = getSchEnv.call(this, keyRef)) == "string")
|
275 | keyRef = sch;
|
276 | if (sch === undefined) {
|
277 | const { schemaId } = this.opts;
|
278 | const root = new compile_1.SchemaEnv({ schema: {}, schemaId });
|
279 | sch = compile_1.resolveSchema.call(this, root, keyRef);
|
280 | if (!sch)
|
281 | return;
|
282 | this.refs[keyRef] = sch;
|
283 | }
|
284 | return (sch.validate || this._compileSchemaEnv(sch));
|
285 | }
|
286 |
|
287 |
|
288 |
|
289 |
|
290 | removeSchema(schemaKeyRef) {
|
291 | if (schemaKeyRef instanceof RegExp) {
|
292 | this._removeAllSchemas(this.schemas, schemaKeyRef);
|
293 | this._removeAllSchemas(this.refs, schemaKeyRef);
|
294 | return this;
|
295 | }
|
296 | switch (typeof schemaKeyRef) {
|
297 | case "undefined":
|
298 | this._removeAllSchemas(this.schemas);
|
299 | this._removeAllSchemas(this.refs);
|
300 | this._cache.clear();
|
301 | return this;
|
302 | case "string": {
|
303 | const sch = getSchEnv.call(this, schemaKeyRef);
|
304 | if (typeof sch == "object")
|
305 | this._cache.delete(sch.schema);
|
306 | delete this.schemas[schemaKeyRef];
|
307 | delete this.refs[schemaKeyRef];
|
308 | return this;
|
309 | }
|
310 | case "object": {
|
311 | const cacheKey = schemaKeyRef;
|
312 | this._cache.delete(cacheKey);
|
313 | let id = schemaKeyRef[this.opts.schemaId];
|
314 | if (id) {
|
315 | id = (0, resolve_1.normalizeId)(id);
|
316 | delete this.schemas[id];
|
317 | delete this.refs[id];
|
318 | }
|
319 | return this;
|
320 | }
|
321 | default:
|
322 | throw new Error("ajv.removeSchema: invalid parameter");
|
323 | }
|
324 | }
|
325 |
|
326 | addVocabulary(definitions) {
|
327 | for (const def of definitions)
|
328 | this.addKeyword(def);
|
329 | return this;
|
330 | }
|
331 | addKeyword(kwdOrDef, def
|
332 | ) {
|
333 | let keyword;
|
334 | if (typeof kwdOrDef == "string") {
|
335 | keyword = kwdOrDef;
|
336 | if (typeof def == "object") {
|
337 | this.logger.warn("these parameters are deprecated, see docs for addKeyword");
|
338 | def.keyword = keyword;
|
339 | }
|
340 | }
|
341 | else if (typeof kwdOrDef == "object" && def === undefined) {
|
342 | def = kwdOrDef;
|
343 | keyword = def.keyword;
|
344 | if (Array.isArray(keyword) && !keyword.length) {
|
345 | throw new Error("addKeywords: keyword must be string or non-empty array");
|
346 | }
|
347 | }
|
348 | else {
|
349 | throw new Error("invalid addKeywords parameters");
|
350 | }
|
351 | checkKeyword.call(this, keyword, def);
|
352 | if (!def) {
|
353 | (0, util_1.eachItem)(keyword, (kwd) => addRule.call(this, kwd));
|
354 | return this;
|
355 | }
|
356 | keywordMetaschema.call(this, def);
|
357 | const definition = {
|
358 | ...def,
|
359 | type: (0, dataType_1.getJSONTypes)(def.type),
|
360 | schemaType: (0, dataType_1.getJSONTypes)(def.schemaType),
|
361 | };
|
362 | (0, util_1.eachItem)(keyword, definition.type.length === 0
|
363 | ? (k) => addRule.call(this, k, definition)
|
364 | : (k) => definition.type.forEach((t) => addRule.call(this, k, definition, t)));
|
365 | return this;
|
366 | }
|
367 | getKeyword(keyword) {
|
368 | const rule = this.RULES.all[keyword];
|
369 | return typeof rule == "object" ? rule.definition : !!rule;
|
370 | }
|
371 |
|
372 | removeKeyword(keyword) {
|
373 |
|
374 | const { RULES } = this;
|
375 | delete RULES.keywords[keyword];
|
376 | delete RULES.all[keyword];
|
377 | for (const group of RULES.rules) {
|
378 | const i = group.rules.findIndex((rule) => rule.keyword === keyword);
|
379 | if (i >= 0)
|
380 | group.rules.splice(i, 1);
|
381 | }
|
382 | return this;
|
383 | }
|
384 |
|
385 | addFormat(name, format) {
|
386 | if (typeof format == "string")
|
387 | format = new RegExp(format);
|
388 | this.formats[name] = format;
|
389 | return this;
|
390 | }
|
391 | errorsText(errors = this.errors,
|
392 | { separator = ", ", dataVar = "data" } = {}
|
393 | ) {
|
394 | if (!errors || errors.length === 0)
|
395 | return "No errors";
|
396 | return errors
|
397 | .map((e) => `${dataVar}${e.instancePath} ${e.message}`)
|
398 | .reduce((text, msg) => text + separator + msg);
|
399 | }
|
400 | $dataMetaSchema(metaSchema, keywordsJsonPointers) {
|
401 | const rules = this.RULES.all;
|
402 | metaSchema = JSON.parse(JSON.stringify(metaSchema));
|
403 | for (const jsonPointer of keywordsJsonPointers) {
|
404 | const segments = jsonPointer.split("/").slice(1);
|
405 | let keywords = metaSchema;
|
406 | for (const seg of segments)
|
407 | keywords = keywords[seg];
|
408 | for (const key in rules) {
|
409 | const rule = rules[key];
|
410 | if (typeof rule != "object")
|
411 | continue;
|
412 | const { $data } = rule.definition;
|
413 | const schema = keywords[key];
|
414 | if ($data && schema)
|
415 | keywords[key] = schemaOrData(schema);
|
416 | }
|
417 | }
|
418 | return metaSchema;
|
419 | }
|
420 | _removeAllSchemas(schemas, regex) {
|
421 | for (const keyRef in schemas) {
|
422 | const sch = schemas[keyRef];
|
423 | if (!regex || regex.test(keyRef)) {
|
424 | if (typeof sch == "string") {
|
425 | delete schemas[keyRef];
|
426 | }
|
427 | else if (sch && !sch.meta) {
|
428 | this._cache.delete(sch.schema);
|
429 | delete schemas[keyRef];
|
430 | }
|
431 | }
|
432 | }
|
433 | }
|
434 | _addSchema(schema, meta, baseId, validateSchema = this.opts.validateSchema, addSchema = this.opts.addUsedSchema) {
|
435 | let id;
|
436 | const { schemaId } = this.opts;
|
437 | if (typeof schema == "object") {
|
438 | id = schema[schemaId];
|
439 | }
|
440 | else {
|
441 | if (this.opts.jtd)
|
442 | throw new Error("schema must be object");
|
443 | else if (typeof schema != "boolean")
|
444 | throw new Error("schema must be object or boolean");
|
445 | }
|
446 | let sch = this._cache.get(schema);
|
447 | if (sch !== undefined)
|
448 | return sch;
|
449 | baseId = (0, resolve_1.normalizeId)(id || baseId);
|
450 | const localRefs = resolve_1.getSchemaRefs.call(this, schema, baseId);
|
451 | sch = new compile_1.SchemaEnv({ schema, schemaId, meta, baseId, localRefs });
|
452 | this._cache.set(sch.schema, sch);
|
453 | if (addSchema && !baseId.startsWith("#")) {
|
454 |
|
455 | if (baseId)
|
456 | this._checkUnique(baseId);
|
457 | this.refs[baseId] = sch;
|
458 | }
|
459 | if (validateSchema)
|
460 | this.validateSchema(schema, true);
|
461 | return sch;
|
462 | }
|
463 | _checkUnique(id) {
|
464 | if (this.schemas[id] || this.refs[id]) {
|
465 | throw new Error(`schema with key or id "${id}" already exists`);
|
466 | }
|
467 | }
|
468 | _compileSchemaEnv(sch) {
|
469 | if (sch.meta)
|
470 | this._compileMetaSchema(sch);
|
471 | else
|
472 | compile_1.compileSchema.call(this, sch);
|
473 |
|
474 | if (!sch.validate)
|
475 | throw new Error("ajv implementation error");
|
476 | return sch.validate;
|
477 | }
|
478 | _compileMetaSchema(sch) {
|
479 | const currentOpts = this.opts;
|
480 | this.opts = this._metaOpts;
|
481 | try {
|
482 | compile_1.compileSchema.call(this, sch);
|
483 | }
|
484 | finally {
|
485 | this.opts = currentOpts;
|
486 | }
|
487 | }
|
488 | }
|
489 | exports.default = Ajv;
|
490 | Ajv.ValidationError = validation_error_1.default;
|
491 | Ajv.MissingRefError = ref_error_1.default;
|
492 | function checkOptions(checkOpts, options, msg, log = "error") {
|
493 | for (const key in checkOpts) {
|
494 | const opt = key;
|
495 | if (opt in options)
|
496 | this.logger[log](`${msg}: option ${key}. ${checkOpts[opt]}`);
|
497 | }
|
498 | }
|
499 | function getSchEnv(keyRef) {
|
500 | keyRef = (0, resolve_1.normalizeId)(keyRef);
|
501 | return this.schemas[keyRef] || this.refs[keyRef];
|
502 | }
|
503 | function addInitialSchemas() {
|
504 | const optsSchemas = this.opts.schemas;
|
505 | if (!optsSchemas)
|
506 | return;
|
507 | if (Array.isArray(optsSchemas))
|
508 | this.addSchema(optsSchemas);
|
509 | else
|
510 | for (const key in optsSchemas)
|
511 | this.addSchema(optsSchemas[key], key);
|
512 | }
|
513 | function addInitialFormats() {
|
514 | for (const name in this.opts.formats) {
|
515 | const format = this.opts.formats[name];
|
516 | if (format)
|
517 | this.addFormat(name, format);
|
518 | }
|
519 | }
|
520 | function addInitialKeywords(defs) {
|
521 | if (Array.isArray(defs)) {
|
522 | this.addVocabulary(defs);
|
523 | return;
|
524 | }
|
525 | this.logger.warn("keywords option as map is deprecated, pass array");
|
526 | for (const keyword in defs) {
|
527 | const def = defs[keyword];
|
528 | if (!def.keyword)
|
529 | def.keyword = keyword;
|
530 | this.addKeyword(def);
|
531 | }
|
532 | }
|
533 | function getMetaSchemaOptions() {
|
534 | const metaOpts = { ...this.opts };
|
535 | for (const opt of META_IGNORE_OPTIONS)
|
536 | delete metaOpts[opt];
|
537 | return metaOpts;
|
538 | }
|
539 | const noLogs = { log() { }, warn() { }, error() { } };
|
540 | function getLogger(logger) {
|
541 | if (logger === false)
|
542 | return noLogs;
|
543 | if (logger === undefined)
|
544 | return console;
|
545 | if (logger.log && logger.warn && logger.error)
|
546 | return logger;
|
547 | throw new Error("logger must implement log, warn and error methods");
|
548 | }
|
549 | const KEYWORD_NAME = /^[a-z_$][a-z0-9_$:-]*$/i;
|
550 | function checkKeyword(keyword, def) {
|
551 | const { RULES } = this;
|
552 | (0, util_1.eachItem)(keyword, (kwd) => {
|
553 | if (RULES.keywords[kwd])
|
554 | throw new Error(`Keyword ${kwd} is already defined`);
|
555 | if (!KEYWORD_NAME.test(kwd))
|
556 | throw new Error(`Keyword ${kwd} has invalid name`);
|
557 | });
|
558 | if (!def)
|
559 | return;
|
560 | if (def.$data && !("code" in def || "validate" in def)) {
|
561 | throw new Error('$data keyword must have "code" or "validate" function');
|
562 | }
|
563 | }
|
564 | function addRule(keyword, definition, dataType) {
|
565 | var _a;
|
566 | const post = definition === null || definition === void 0 ? void 0 : definition.post;
|
567 | if (dataType && post)
|
568 | throw new Error('keyword with "post" flag cannot have "type"');
|
569 | const { RULES } = this;
|
570 | let ruleGroup = post ? RULES.post : RULES.rules.find(({ type: t }) => t === dataType);
|
571 | if (!ruleGroup) {
|
572 | ruleGroup = { type: dataType, rules: [] };
|
573 | RULES.rules.push(ruleGroup);
|
574 | }
|
575 | RULES.keywords[keyword] = true;
|
576 | if (!definition)
|
577 | return;
|
578 | const rule = {
|
579 | keyword,
|
580 | definition: {
|
581 | ...definition,
|
582 | type: (0, dataType_1.getJSONTypes)(definition.type),
|
583 | schemaType: (0, dataType_1.getJSONTypes)(definition.schemaType),
|
584 | },
|
585 | };
|
586 | if (definition.before)
|
587 | addBeforeRule.call(this, ruleGroup, rule, definition.before);
|
588 | else
|
589 | ruleGroup.rules.push(rule);
|
590 | RULES.all[keyword] = rule;
|
591 | (_a = definition.implements) === null || _a === void 0 ? void 0 : _a.forEach((kwd) => this.addKeyword(kwd));
|
592 | }
|
593 | function addBeforeRule(ruleGroup, rule, before) {
|
594 | const i = ruleGroup.rules.findIndex((_rule) => _rule.keyword === before);
|
595 | if (i >= 0) {
|
596 | ruleGroup.rules.splice(i, 0, rule);
|
597 | }
|
598 | else {
|
599 | ruleGroup.rules.push(rule);
|
600 | this.logger.warn(`rule ${before} is not defined`);
|
601 | }
|
602 | }
|
603 | function keywordMetaschema(def) {
|
604 | let { metaSchema } = def;
|
605 | if (metaSchema === undefined)
|
606 | return;
|
607 | if (def.$data && this.opts.$data)
|
608 | metaSchema = schemaOrData(metaSchema);
|
609 | def.validateSchema = this.compile(metaSchema, true);
|
610 | }
|
611 | const $dataRef = {
|
612 | $ref: "https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#",
|
613 | };
|
614 | function schemaOrData(schema) {
|
615 | return { anyOf: [schema, $dataRef] };
|
616 | }
|
617 |
|
\ | No newline at end of file |