Brunobkr/llama.cpp_AlgMor24_github
ΩFFFΣLLIa • llama.cpp • AlgMor24 ██████╗ ███████╗███████╗███████╗██╗ ██╗ ██╗ █████╗ ██╔═══██╗██╔════╝██╔════╝██╔════╝██║ ██║ ██║██╔══██╗ ██║ ██║█████╗ █████╗ █████╗ ██║ ██║ ██║███████║ ██║ ██║██╔══╝ ██╔══╝ ██╔══╝ ██║ ██║ ██║██╔══██║ ╚██████╔╝██║ ██║ ███████╗███████╗███████╗██║██║ ██║ ╚═════╝ ╚═╝ ╚═╝ ╚══════╝╚══════╝╚══════╝╚═╝╚═╝ ╚═╝ High-Performance LLM / VLM Inference & Autonomous Agentic Ecosystem… See the full description on the dataset page: https://huggingface.co/datasets/Brunobkr/llama.cpp_AlgMor24_github.
03.1k
1<img align="right" alt="Ajv logo" width="160" src="https://ajv.js.org/images/ajv_logo.png">2 3# Ajv: Another JSON Schema Validator4 5The fastest JSON Schema validator for Node.js and browser. Supports draft-04/06/07.6 7[](https://travis-ci.org/ajv-validator/ajv)8[](https://www.npmjs.com/package/ajv)9[](https://www.npmjs.com/package/ajv/v/7.0.0-beta.4)10[](https://www.npmjs.com/package/ajv)11[](https://coveralls.io/github/ajv-validator/ajv?branch=master)12[](https://gitter.im/ajv-validator/ajv)13[](https://github.com/sponsors/epoberezkin)14 15 16## Ajv v7 beta is released17 18[Ajv version 7 (beta)](https://github.com/ajv-validator/ajv/tree/v7-beta) is released with these changes:19 20- support of JSON Schema draft-2019-09 features: [`unevaluatedProperties`](./json-schema.md#unevaluatedproperties) and [`unevaluatedItems`](./json-schema.md#unevaluateditems), [dynamic recursive references](./validation.md#extending-recursive-schemas) and other [additional keywords](./json-schema.md#json-schema-draft-2019-09).21- to reduce the mistakes in JSON schemas and unexpected validation results, [strict mode](./docs/strict-mode.md) is added - it prohibits ignored or ambiguous JSON Schema elements.22- to make code injection from untrusted schemas impossible, [code generation](./docs/codegen.md) is fully re-written to be safe and to allow code optimization (compiled schema code size is reduced by more than 10%).23- to simplify Ajv extensions, the new keyword API that is used by pre-defined keywords is available to user-defined keywords - it is much easier to define any keywords now, especially with subschemas. [ajv-keywords](https://github.com/ajv-validator/ajv-keywords) package was updated to use the new API (in [v4.0.0-beta.0](https://github.com/ajv-validator/ajv-keywords/releases/tag/v4.0.0-beta.0))24- schemas are compiled to ES6 code (ES5 code generation is also supported with an option).25- to improve reliability and maintainability the code is migrated to TypeScript.26 27**Please note**:28 29- the support for JSON-Schema draft-04 is removed - if you have schemas using "id" attributes you have to replace them with "\$id" (or continue using version 6 that will be supported until 02/28/2021).30- all formats are separated to ajv-formats package - they have to be explicitely added if you use them.31 32See [release notes](https://github.com/ajv-validator/ajv/releases/tag/v7.0.0-beta.0) for the details.33 34To install the new version:35 36```bash37npm install ajv@beta38```39 40See [Getting started with v7](https://github.com/ajv-validator/ajv/tree/v7-beta#usage) for code example.41 42 43## Mozilla MOSS grant and OpenJS Foundation44 45[<img src="https://www.poberezkin.com/images/mozilla.png" width="240" height="68">](https://www.mozilla.org/en-US/moss/) [<img src="https://www.poberezkin.com/images/openjs.png" width="220" height="68">](https://openjsf.org/blog/2020/08/14/ajv-joins-openjs-foundation-as-an-incubation-project/)46 47Ajv has been awarded a grant from Mozilla’s [Open Source Support (MOSS) program](https://www.mozilla.org/en-US/moss/) in the “Foundational Technology” track! It will sponsor the development of Ajv support of [JSON Schema version 2019-09](https://tools.ietf.org/html/draft-handrews-json-schema-02) and of [JSON Type Definition](https://tools.ietf.org/html/draft-ucarion-json-type-definition-04).48 49Ajv also joined [OpenJS Foundation](https://openjsf.org/) – having this support will help ensure the longevity and stability of Ajv for all its users.50 51This [blog post](https://www.poberezkin.com/posts/2020-08-14-ajv-json-validator-mozilla-open-source-grant-openjs-foundation.html) has more details.52 53I am looking for the long term maintainers of Ajv – working with [ReadySet](https://www.thereadyset.co/), also sponsored by Mozilla, to establish clear guidelines for the role of a "maintainer" and the contribution standards, and to encourage a wider, more inclusive, contribution from the community.54 55 56## Please [sponsor Ajv development](https://github.com/sponsors/epoberezkin)57 58Since I asked to support Ajv development 40 people and 6 organizations contributed via GitHub and OpenCollective - this support helped receiving the MOSS grant!59 60Your continuing support is very important - the funds will be used to develop and maintain Ajv once the next major version is released.61 62Please sponsor Ajv via:63- [GitHub sponsors page](https://github.com/sponsors/epoberezkin) (GitHub will match it)64- [Ajv Open Collective️](https://opencollective.com/ajv)65 66Thank you.67 68 69#### Open Collective sponsors70 71<a href="https://opencollective.com/ajv"><img src="https://opencollective.com/ajv/individuals.svg?width=890"></a>72 73<a href="https://opencollective.com/ajv/organization/0/website"><img src="https://opencollective.com/ajv/organization/0/avatar.svg"></a>74<a href="https://opencollective.com/ajv/organization/1/website"><img src="https://opencollective.com/ajv/organization/1/avatar.svg"></a>75<a href="https://opencollective.com/ajv/organization/2/website"><img src="https://opencollective.com/ajv/organization/2/avatar.svg"></a>76<a href="https://opencollective.com/ajv/organization/3/website"><img src="https://opencollective.com/ajv/organization/3/avatar.svg"></a>77<a href="https://opencollective.com/ajv/organization/4/website"><img src="https://opencollective.com/ajv/organization/4/avatar.svg"></a>78<a href="https://opencollective.com/ajv/organization/5/website"><img src="https://opencollective.com/ajv/organization/5/avatar.svg"></a>79<a href="https://opencollective.com/ajv/organization/6/website"><img src="https://opencollective.com/ajv/organization/6/avatar.svg"></a>80<a href="https://opencollective.com/ajv/organization/7/website"><img src="https://opencollective.com/ajv/organization/7/avatar.svg"></a>81<a href="https://opencollective.com/ajv/organization/8/website"><img src="https://opencollective.com/ajv/organization/8/avatar.svg"></a>82<a href="https://opencollective.com/ajv/organization/9/website"><img src="https://opencollective.com/ajv/organization/9/avatar.svg"></a>83 84 85## Using version 686 87[JSON Schema draft-07](http://json-schema.org/latest/json-schema-validation.html) is published.88 89[Ajv version 6.0.0](https://github.com/ajv-validator/ajv/releases/tag/v6.0.0) that supports draft-07 is released. It may require either migrating your schemas or updating your code (to continue using draft-04 and v5 schemas, draft-06 schemas will be supported without changes).90 91__Please note__: To use Ajv with draft-06 schemas you need to explicitly add the meta-schema to the validator instance:92 93```javascript94ajv.addMetaSchema(require('ajv/lib/refs/json-schema-draft-06.json'));95```96 97To use Ajv with draft-04 schemas in addition to explicitly adding meta-schema you also need to use option schemaId:98 99```javascript100var ajv = new Ajv({schemaId: 'id'});101// If you want to use both draft-04 and draft-06/07 schemas:102// var ajv = new Ajv({schemaId: 'auto'});103ajv.addMetaSchema(require('ajv/lib/refs/json-schema-draft-04.json'));104```105 106 107## Contents108 109- [Performance](#performance)110- [Features](#features)111- [Getting started](#getting-started)112- [Frequently Asked Questions](https://github.com/ajv-validator/ajv/blob/master/FAQ.md)113- [Using in browser](#using-in-browser)114 - [Ajv and Content Security Policies (CSP)](#ajv-and-content-security-policies-csp)115- [Command line interface](#command-line-interface)116- Validation117 - [Keywords](#validation-keywords)118 - [Annotation keywords](#annotation-keywords)119 - [Formats](#formats)120 - [Combining schemas with $ref](#ref)121 - [$data reference](#data-reference)122 - NEW: [$merge and $patch keywords](#merge-and-patch-keywords)123 - [Defining custom keywords](#defining-custom-keywords)124 - [Asynchronous schema compilation](#asynchronous-schema-compilation)125 - [Asynchronous validation](#asynchronous-validation)126- [Security considerations](#security-considerations)127 - [Security contact](#security-contact)128 - [Untrusted schemas](#untrusted-schemas)129 - [Circular references in objects](#circular-references-in-javascript-objects)130 - [Trusted schemas](#security-risks-of-trusted-schemas)131 - [ReDoS attack](#redos-attack)132- Modifying data during validation133 - [Filtering data](#filtering-data)134 - [Assigning defaults](#assigning-defaults)135 - [Coercing data types](#coercing-data-types)136- API137 - [Methods](#api)138 - [Options](#options)139 - [Validation errors](#validation-errors)140- [Plugins](#plugins)141- [Related packages](#related-packages)142- [Some packages using Ajv](#some-packages-using-ajv)143- [Tests, Contributing, Changes history](#tests)144- [Support, Code of conduct, License](#open-source-software-support)145 146 147## Performance148 149Ajv generates code using [doT templates](https://github.com/olado/doT) to turn JSON Schemas into super-fast validation functions that are efficient for v8 optimization.150 151Currently Ajv is the fastest and the most standard compliant validator according to these benchmarks:152 153- [json-schema-benchmark](https://github.com/ebdrup/json-schema-benchmark) - 50% faster than the second place154- [jsck benchmark](https://github.com/pandastrike/jsck#benchmarks) - 20-190% faster155- [z-schema benchmark](https://rawgit.com/zaggino/z-schema/master/benchmark/results.html)156- [themis benchmark](https://cdn.rawgit.com/playlyfe/themis/master/benchmark/results.html)157 158 159Performance of different validators by [json-schema-benchmark](https://github.com/ebdrup/json-schema-benchmark):160 161[](https://github.com/ebdrup/json-schema-benchmark/blob/master/README.md#performance)162 163 164## Features165 166- Ajv implements full JSON Schema [draft-06/07](http://json-schema.org/) and draft-04 standards:167 - all validation keywords (see [JSON Schema validation keywords](https://github.com/ajv-validator/ajv/blob/master/KEYWORDS.md))168 - full support of remote refs (remote schemas have to be added with `addSchema` or compiled to be available)169 - support of circular references between schemas170 - correct string lengths for strings with unicode pairs (can be turned off)171 - [formats](#formats) defined by JSON Schema draft-07 standard and custom formats (can be turned off)172 - [validates schemas against meta-schema](#api-validateschema)173- supports [browsers](#using-in-browser) and Node.js 0.10-14.x174- [asynchronous loading](#asynchronous-schema-compilation) of referenced schemas during compilation175- "All errors" validation mode with [option allErrors](#options)176- [error messages with parameters](#validation-errors) describing error reasons to allow creating custom error messages177- i18n error messages support with [ajv-i18n](https://github.com/ajv-validator/ajv-i18n) package178- [filtering data](#filtering-data) from additional properties179- [assigning defaults](#assigning-defaults) to missing properties and items180- [coercing data](#coercing-data-types) to the types specified in `type` keywords181- [custom keywords](#defining-custom-keywords)182- draft-06/07 keywords `const`, `contains`, `propertyNames` and `if/then/else`183- draft-06 boolean schemas (`true`/`false` as a schema to always pass/fail).184- keywords `switch`, `patternRequired`, `formatMaximum` / `formatMinimum` and `formatExclusiveMaximum` / `formatExclusiveMinimum` from [JSON Schema extension proposals](https://github.com/json-schema/json-schema/wiki/v5-Proposals) with [ajv-keywords](https://github.com/ajv-validator/ajv-keywords) package185- [$data reference](#data-reference) to use values from the validated data as values for the schema keywords186- [asynchronous validation](#asynchronous-validation) of custom formats and keywords187 188 189## Install190 191```192npm install ajv193```194 195 196## <a name="usage"></a>Getting started197 198Try it in the Node.js REPL: https://tonicdev.com/npm/ajv199 200 201The fastest validation call:202 203```javascript204// Node.js require:205var Ajv = require('ajv');206// or ESM/TypeScript import207import Ajv from 'ajv';208 209var ajv = new Ajv(); // options can be passed, e.g. {allErrors: true}210var validate = ajv.compile(schema);211var valid = validate(data);212if (!valid) console.log(validate.errors);213```214 215or with less code216 217```javascript218// ...219var valid = ajv.validate(schema, data);220if (!valid) console.log(ajv.errors);221// ...222```223 224or225 226```javascript227// ...228var valid = ajv.addSchema(schema, 'mySchema')229 .validate('mySchema', data);230if (!valid) console.log(ajv.errorsText());231// ...232```233 234See [API](#api) and [Options](#options) for more details.235 236Ajv compiles schemas to functions and caches them in all cases (using schema serialized with [fast-json-stable-stringify](https://github.com/epoberezkin/fast-json-stable-stringify) or a custom function as a key), so that the next time the same schema is used (not necessarily the same object instance) it won't be compiled again.237 238The best performance is achieved when using compiled functions returned by `compile` or `getSchema` methods (there is no additional function call).239 240__Please note__: every time a validation function or `ajv.validate` are called `errors` property is overwritten. You need to copy `errors` array reference to another variable if you want to use it later (e.g., in the callback). See [Validation errors](#validation-errors)241 242__Note for TypeScript users__: `ajv` provides its own TypeScript declarations243out of the box, so you don't need to install the deprecated `@types/ajv`244module.245 246 247## Using in browser248 249You can require Ajv directly from the code you browserify - in this case Ajv will be a part of your bundle.250 251If you need to use Ajv in several bundles you can create a separate UMD bundle using `npm run bundle` script (thanks to [siddo420](https://github.com/siddo420)).252 253Then you need to load Ajv in the browser:254```html255<script src="ajv.min.js"></script>256```257 258This bundle can be used with different module systems; it creates global `Ajv` if no module system is found.259 260The browser bundle is available on [cdnjs](https://cdnjs.com/libraries/ajv).261 262Ajv is tested with these browsers:263 264[](https://saucelabs.com/u/epoberezkin)265 266__Please note__: some frameworks, e.g. Dojo, may redefine global require in such way that is not compatible with CommonJS module format. In such case Ajv bundle has to be loaded before the framework and then you can use global Ajv (see issue [#234](https://github.com/ajv-validator/ajv/issues/234)).267 268 269### Ajv and Content Security Policies (CSP)270 271If you're using Ajv to compile a schema (the typical use) in a browser document that is loaded with a Content Security Policy (CSP), that policy will require a `script-src` directive that includes the value `'unsafe-eval'`.272:warning: NOTE, however, that `unsafe-eval` is NOT recommended in a secure CSP[[1]](https://developer.chrome.com/extensions/contentSecurityPolicy#relaxing-eval), as it has the potential to open the document to cross-site scripting (XSS) attacks.273 274In order to make use of Ajv without easing your CSP, you can [pre-compile a schema using the CLI](https://github.com/ajv-validator/ajv-cli#compile-schemas). This will transpile the schema JSON into a JavaScript file that exports a `validate` function that works simlarly to a schema compiled at runtime.275 276Note that pre-compilation of schemas is performed using [ajv-pack](https://github.com/ajv-validator/ajv-pack) and there are [some limitations to the schema features it can compile](https://github.com/ajv-validator/ajv-pack#limitations). A successfully pre-compiled schema is equivalent to the same schema compiled at runtime.277 278 279## Command line interface280 281CLI is available as a separate npm package [ajv-cli](https://github.com/ajv-validator/ajv-cli). It supports:282 283- compiling JSON Schemas to test their validity284- BETA: generating standalone module exporting a validation function to be used without Ajv (using [ajv-pack](https://github.com/ajv-validator/ajv-pack))285- migrate schemas to draft-07 (using [json-schema-migrate](https://github.com/epoberezkin/json-schema-migrate))286- validating data file(s) against JSON Schema287- testing expected validity of data against JSON Schema288- referenced schemas289- custom meta-schemas290- files in JSON, JSON5, YAML, and JavaScript format291- all Ajv options292- reporting changes in data after validation in [JSON-patch](https://tools.ietf.org/html/rfc6902) format293 294 295## Validation keywords296 297Ajv supports all validation keywords from draft-07 of JSON Schema standard:298 299- [type](https://github.com/ajv-validator/ajv/blob/master/KEYWORDS.md#type)300- [for numbers](https://github.com/ajv-validator/ajv/blob/master/KEYWORDS.md#keywords-for-numbers) - maximum, minimum, exclusiveMaximum, exclusiveMinimum, multipleOf301- [for strings](https://github.com/ajv-validator/ajv/blob/master/KEYWORDS.md#keywords-for-strings) - maxLength, minLength, pattern, format302- [for arrays](https://github.com/ajv-validator/ajv/blob/master/KEYWORDS.md#keywords-for-arrays) - maxItems, minItems, uniqueItems, items, additionalItems, [contains](https://github.com/ajv-validator/ajv/blob/master/KEYWORDS.md#contains)303- [for objects](https://github.com/ajv-validator/ajv/blob/master/KEYWORDS.md#keywords-for-objects) - maxProperties, minProperties, required, properties, patternProperties, additionalProperties, dependencies, [propertyNames](https://github.com/ajv-validator/ajv/blob/master/KEYWORDS.md#propertynames)304- [for all types](https://github.com/ajv-validator/ajv/blob/master/KEYWORDS.md#keywords-for-all-types) - enum, [const](https://github.com/ajv-validator/ajv/blob/master/KEYWORDS.md#const)305- [compound keywords](https://github.com/ajv-validator/ajv/blob/master/KEYWORDS.md#compound-keywords) - not, oneOf, anyOf, allOf, [if/then/else](https://github.com/ajv-validator/ajv/blob/master/KEYWORDS.md#ifthenelse)306 307With [ajv-keywords](https://github.com/ajv-validator/ajv-keywords) package Ajv also supports validation keywords from [JSON Schema extension proposals](https://github.com/json-schema/json-schema/wiki/v5-Proposals) for JSON Schema standard:308 309- [patternRequired](https://github.com/ajv-validator/ajv/blob/master/KEYWORDS.md#patternrequired-proposed) - like `required` but with patterns that some property should match.310- [formatMaximum, formatMinimum, formatExclusiveMaximum, formatExclusiveMinimum](https://github.com/ajv-validator/ajv/blob/master/KEYWORDS.md#formatmaximum--formatminimum-and-exclusiveformatmaximum--exclusiveformatminimum-proposed) - setting limits for date, time, etc.311 312See [JSON Schema validation keywords](https://github.com/ajv-validator/ajv/blob/master/KEYWORDS.md) for more details.313 314 315## Annotation keywords316 317JSON Schema specification defines several annotation keywords that describe schema itself but do not perform any validation.318 319- `title` and `description`: information about the data represented by that schema320- `$comment` (NEW in draft-07): information for developers. With option `$comment` Ajv logs or passes the comment string to the user-supplied function. See [Options](#options).321- `default`: a default value of the data instance, see [Assigning defaults](#assigning-defaults).322- `examples` (NEW in draft-06): an array of data instances. Ajv does not check the validity of these instances against the schema.323- `readOnly` and `writeOnly` (NEW in draft-07): marks data-instance as read-only or write-only in relation to the source of the data (database, api, etc.).324- `contentEncoding`: [RFC 2045](https://tools.ietf.org/html/rfc2045#section-6.1 ), e.g., "base64".325- `contentMediaType`: [RFC 2046](https://tools.ietf.org/html/rfc2046), e.g., "image/png".326 327__Please note__: Ajv does not implement validation of the keywords `examples`, `contentEncoding` and `contentMediaType` but it reserves them. If you want to create a plugin that implements some of them, it should remove these keywords from the instance.328 329 330## Formats331 332Ajv implements formats defined by JSON Schema specification and several other formats. It is recommended NOT to use "format" keyword implementations with untrusted data, as they use potentially unsafe regular expressions - see [ReDoS attack](#redos-attack).333 334__Please note__: if you need to use "format" keyword to validate untrusted data, you MUST assess their suitability and safety for your validation scenarios.335 336The following formats are implemented for string validation with "format" keyword:337 338- _date_: full-date according to [RFC3339](http://tools.ietf.org/html/rfc3339#section-5.6).339- _time_: time with optional time-zone.340- _date-time_: date-time from the same source (time-zone is mandatory). `date`, `time` and `date-time` validate ranges in `full` mode and only regexp in `fast` mode (see [options](#options)).341- _uri_: full URI.342- _uri-reference_: URI reference, including full and relative URIs.343- _uri-template_: URI template according to [RFC6570](https://tools.ietf.org/html/rfc6570)344- _url_ (deprecated): [URL record](https://url.spec.whatwg.org/#concept-url).345- _email_: email address.346- _hostname_: host name according to [RFC1034](http://tools.ietf.org/html/rfc1034#section-3.5).347- _ipv4_: IP address v4.348- _ipv6_: IP address v6.349- _regex_: tests whether a string is a valid regular expression by passing it to RegExp constructor.350- _uuid_: Universally Unique IDentifier according to [RFC4122](http://tools.ietf.org/html/rfc4122).351- _json-pointer_: JSON-pointer according to [RFC6901](https://tools.ietf.org/html/rfc6901).352- _relative-json-pointer_: relative JSON-pointer according to [this draft](http://tools.ietf.org/html/draft-luff-relative-json-pointer-00).353 354__Please note__: JSON Schema draft-07 also defines formats `iri`, `iri-reference`, `idn-hostname` and `idn-email` for URLs, hostnames and emails with international characters. Ajv does not implement these formats. If you create Ajv plugin that implements them please make a PR to mention this plugin here.355 356There are two modes of format validation: `fast` and `full`. This mode affects formats `date`, `time`, `date-time`, `uri`, `uri-reference`, and `email`. See [Options](#options) for details.357 358You can add additional formats and replace any of the formats above using [addFormat](#api-addformat) method.359 360The option `unknownFormats` allows changing the default behaviour when an unknown format is encountered. In this case Ajv can either fail schema compilation (default) or ignore it (default in versions before 5.0.0). You also can allow specific format(s) that will be ignored. See [Options](#options) for details.361 362You can find regular expressions used for format validation and the sources that were used in [formats.js](https://github.com/ajv-validator/ajv/blob/master/lib/compile/formats.js).363 364 365## <a name="ref"></a>Combining schemas with $ref366 367You can structure your validation logic across multiple schema files and have schemas reference each other using `$ref` keyword.368 369Example:370 371```javascript372var schema = {373 "$id": "http://example.com/schemas/schema.json",374 "type": "object",375 "properties": {376 "foo": { "$ref": "defs.json#/definitions/int" },377 "bar": { "$ref": "defs.json#/definitions/str" }378 }379};380 381var defsSchema = {382 "$id": "http://example.com/schemas/defs.json",383 "definitions": {384 "int": { "type": "integer" },385 "str": { "type": "string" }386 }387};388```389 390Now to compile your schema you can either pass all schemas to Ajv instance:391 392```javascript393var ajv = new Ajv({schemas: [schema, defsSchema]});394var validate = ajv.getSchema('http://example.com/schemas/schema.json');395```396 397or use `addSchema` method:398 399```javascript400var ajv = new Ajv;401var validate = ajv.addSchema(defsSchema)402 .compile(schema);403```404 405See [Options](#options) and [addSchema](#api) method.406 407__Please note__:408- `$ref` is resolved as the uri-reference using schema $id as the base URI (see the example).409- References can be recursive (and mutually recursive) to implement the schemas for different data structures (such as linked lists, trees, graphs, etc.).410- You don't have to host your schema files at the URIs that you use as schema $id. These URIs are only used to identify the schemas, and according to JSON Schema specification validators should not expect to be able to download the schemas from these URIs.411- The actual location of the schema file in the file system is not used.412- You can pass the identifier of the schema as the second parameter of `addSchema` method or as a property name in `schemas` option. This identifier can be used instead of (or in addition to) schema $id.413- You cannot have the same $id (or the schema identifier) used for more than one schema - the exception will be thrown.414- You can implement dynamic resolution of the referenced schemas using `compileAsync` method. In this way you can store schemas in any system (files, web, database, etc.) and reference them without explicitly adding to Ajv instance. See [Asynchronous schema compilation](#asynchronous-schema-compilation).415 416 417## $data reference418 419With `$data` option you can use values from the validated data as the values for the schema keywords. See [proposal](https://github.com/json-schema-org/json-schema-spec/issues/51) for more information about how it works.420 421`$data` reference is supported in the keywords: const, enum, format, maximum/minimum, exclusiveMaximum / exclusiveMinimum, maxLength / minLength, maxItems / minItems, maxProperties / minProperties, formatMaximum / formatMinimum, formatExclusiveMaximum / formatExclusiveMinimum, multipleOf, pattern, required, uniqueItems.422 423The value of "$data" should be a [JSON-pointer](https://tools.ietf.org/html/rfc6901) to the data (the root is always the top level data object, even if the $data reference is inside a referenced subschema) or a [relative JSON-pointer](http://tools.ietf.org/html/draft-luff-relative-json-pointer-00) (it is relative to the current point in data; if the $data reference is inside a referenced subschema it cannot point to the data outside of the root level for this subschema).424 425Examples.426 427This schema requires that the value in property `smaller` is less or equal than the value in the property larger:428 429```javascript430var ajv = new Ajv({$data: true});431 432var schema = {433 "properties": {434 "smaller": {435 "type": "number",436 "maximum": { "$data": "1/larger" }437 },438 "larger": { "type": "number" }439 }440};441 442var validData = {443 smaller: 5,444 larger: 7445};446 447ajv.validate(schema, validData); // true448```449 450This schema requires that the properties have the same format as their field names:451 452```javascript453var schema = {454 "additionalProperties": {455 "type": "string",456 "format": { "$data": "0#" }457 }458};459 460var validData = {461 'date-time': '1963-06-19T08:30:06.283185Z',462 email: 'joe.bloggs@example.com'463}464```465 466`$data` reference is resolved safely - it won't throw even if some property is undefined. If `$data` resolves to `undefined` the validation succeeds (with the exclusion of `const` keyword). If `$data` resolves to incorrect type (e.g. not "number" for maximum keyword) the validation fails.467 468 469## $merge and $patch keywords470 471With the package [ajv-merge-patch](https://github.com/ajv-validator/ajv-merge-patch) you can use the keywords `$merge` and `$patch` that allow extending JSON Schemas with patches using formats [JSON Merge Patch (RFC 7396)](https://tools.ietf.org/html/rfc7396) and [JSON Patch (RFC 6902)](https://tools.ietf.org/html/rfc6902).472 473To add keywords `$merge` and `$patch` to Ajv instance use this code:474 475```javascript476require('ajv-merge-patch')(ajv);477```478 479Examples.480 481Using `$merge`:482 483```json484{485 "$merge": {486 "source": {487 "type": "object",488 "properties": { "p": { "type": "string" } },489 "additionalProperties": false490 },491 "with": {492 "properties": { "q": { "type": "number" } }493 }494 }495}496```497 498Using `$patch`:499 500```json501{502 "$patch": {503 "source": {504 "type": "object",505 "properties": { "p": { "type": "string" } },506 "additionalProperties": false507 },508 "with": [509 { "op": "add", "path": "/properties/q", "value": { "type": "number" } }510 ]511 }512}513```514 515The schemas above are equivalent to this schema:516 517```json518{519 "type": "object",520 "properties": {521 "p": { "type": "string" },522 "q": { "type": "number" }523 },524 "additionalProperties": false525}526```527 528The properties `source` and `with` in the keywords `$merge` and `$patch` can use absolute or relative `$ref` to point to other schemas previously added to the Ajv instance or to the fragments of the current schema.529 530See the package [ajv-merge-patch](https://github.com/ajv-validator/ajv-merge-patch) for more information.531 532 533## Defining custom keywords534 535The advantages of using custom keywords are:536 537- allow creating validation scenarios that cannot be expressed using JSON Schema538- simplify your schemas539- help bringing a bigger part of the validation logic to your schemas540- make your schemas more expressive, less verbose and closer to your application domain541- implement custom data processors that modify your data (`modifying` option MUST be used in keyword definition) and/or create side effects while the data is being validated542 543If a keyword is used only for side-effects and its validation result is pre-defined, use option `valid: true/false` in keyword definition to simplify both generated code (no error handling in case of `valid: true`) and your keyword functions (no need to return any validation result).544 545The concerns you have to be aware of when extending JSON Schema standard with custom keywords are the portability and understanding of your schemas. You will have to support these custom keywords on other platforms and to properly document these keywords so that everybody can understand them in your schemas.546 547You can define custom keywords with [addKeyword](#api-addkeyword) method. Keywords are defined on the `ajv` instance level - new instances will not have previously defined keywords.548 549Ajv allows defining keywords with:550- validation function551- compilation function552- macro function553- inline compilation function that should return code (as string) that will be inlined in the currently compiled schema.554 555Example. `range` and `exclusiveRange` keywords using compiled schema:556 557```javascript558ajv.addKeyword('range', {559 type: 'number',560 compile: function (sch, parentSchema) {561 var min = sch[0];562 var max = sch[1];563 564 return parentSchema.exclusiveRange === true565 ? function (data) { return data > min && data < max; }566 : function (data) { return data >= min && data <= max; }567 }568});569 570var schema = { "range": [2, 4], "exclusiveRange": true };571var validate = ajv.compile(schema);572console.log(validate(2.01)); // true573console.log(validate(3.99)); // true574console.log(validate(2)); // false575console.log(validate(4)); // false576```577 578Several custom keywords (typeof, instanceof, range and propertyNames) are defined in [ajv-keywords](https://github.com/ajv-validator/ajv-keywords) package - they can be used for your schemas and as a starting point for your own custom keywords.579 580See [Defining custom keywords](https://github.com/ajv-validator/ajv/blob/master/CUSTOM.md) for more details.581 582 583## Asynchronous schema compilation584 585During asynchronous compilation remote references are loaded using supplied function. See `compileAsync` [method](#api-compileAsync) and `loadSchema` [option](#options).586 587Example:588 589```javascript590var ajv = new Ajv({ loadSchema: loadSchema });591 592ajv.compileAsync(schema).then(function (validate) {593 var valid = validate(data);594 // ...595});596 597function loadSchema(uri) {598 return request.json(uri).then(function (res) {599 if (res.statusCode >= 400)600 throw new Error('Loading error: ' + res.statusCode);601 return res.body;602 });603}604```605 606__Please note__: [Option](#options) `missingRefs` should NOT be set to `"ignore"` or `"fail"` for asynchronous compilation to work.607 608 609## Asynchronous validation610 611Example in Node.js REPL: https://tonicdev.com/esp/ajv-asynchronous-validation612 613You can define custom formats and keywords that perform validation asynchronously by accessing database or some other service. You should add `async: true` in the keyword or format definition (see [addFormat](#api-addformat), [addKeyword](#api-addkeyword) and [Defining custom keywords](#defining-custom-keywords)).614 615If your schema uses asynchronous formats/keywords or refers to some schema that contains them it should have `"$async": true` keyword so that Ajv can compile it correctly. If asynchronous format/keyword or reference to asynchronous schema is used in the schema without `$async` keyword Ajv will throw an exception during schema compilation.616 617__Please note__: all asynchronous subschemas that are referenced from the current or other schemas should have `"$async": true` keyword as well, otherwise the schema compilation will fail.618 619Validation function for an asynchronous custom format/keyword should return a promise that resolves with `true` or `false` (or rejects with `new Ajv.ValidationError(errors)` if you want to return custom errors from the keyword function).620 621Ajv compiles asynchronous schemas to [es7 async functions](http://tc39.github.io/ecmascript-asyncawait/) that can optionally be transpiled with [nodent](https://github.com/MatAtBread/nodent). Async functions are supported in Node.js 7+ and all modern browsers. You can also supply any other transpiler as a function via `processCode` option. See [Options](#options).622 623The compiled validation function has `$async: true` property (if the schema is asynchronous), so you can differentiate these functions if you are using both synchronous and asynchronous schemas.624 625Validation result will be a promise that resolves with validated data or rejects with an exception `Ajv.ValidationError` that contains the array of validation errors in `errors` property.626 627 628Example:629 630```javascript631var ajv = new Ajv;632// require('ajv-async')(ajv);633 634ajv.addKeyword('idExists', {635 async: true,636 type: 'number',637 validate: checkIdExists638});639 640 641function checkIdExists(schema, data) {642 return knex(schema.table)643 .select('id')644 .where('id', data)645 .then(function (rows) {646 return !!rows.length; // true if record is found647 });648}649 650var schema = {651 "$async": true,652 "properties": {653 "userId": {654 "type": "integer",655 "idExists": { "table": "users" }656 },657 "postId": {658 "type": "integer",659 "idExists": { "table": "posts" }660 }661 }662};663 664var validate = ajv.compile(schema);665 666validate({ userId: 1, postId: 19 })667.then(function (data) {668 console.log('Data is valid', data); // { userId: 1, postId: 19 }669})670.catch(function (err) {671 if (!(err instanceof Ajv.ValidationError)) throw err;672 // data is invalid673 console.log('Validation errors:', err.errors);674});675```676 677### Using transpilers with asynchronous validation functions.678 679[ajv-async](https://github.com/ajv-validator/ajv-async) uses [nodent](https://github.com/MatAtBread/nodent) to transpile async functions. To use another transpiler you should separately install it (or load its bundle in the browser).680 681 682#### Using nodent683 684```javascript685var ajv = new Ajv;686require('ajv-async')(ajv);687// in the browser if you want to load ajv-async bundle separately you can:688// window.ajvAsync(ajv);689var validate = ajv.compile(schema); // transpiled es7 async function690validate(data).then(successFunc).catch(errorFunc);691```692 693 694#### Using other transpilers695 696```javascript697var ajv = new Ajv({ processCode: transpileFunc });698var validate = ajv.compile(schema); // transpiled es7 async function699validate(data).then(successFunc).catch(errorFunc);700```701 702See [Options](#options).703 704 705## Security considerations706 707JSON Schema, if properly used, can replace data sanitisation. It doesn't replace other API security considerations. It also introduces additional security aspects to consider.708 709 710##### Security contact711 712To report a security vulnerability, please use the713[Tidelift security contact](https://tidelift.com/security).714Tidelift will coordinate the fix and disclosure. Please do NOT report security vulnerabilities via GitHub issues.715 716 717##### Untrusted schemas718 719Ajv treats JSON schemas as trusted as your application code. This security model is based on the most common use case, when the schemas are static and bundled together with the application.720 721If your schemas are received from untrusted sources (or generated from untrusted data) there are several scenarios you need to prevent:722- compiling schemas can cause stack overflow (if they are too deep)723- compiling schemas can be slow (e.g. [#557](https://github.com/ajv-validator/ajv/issues/557))724- validating certain data can be slow725 726It is difficult to predict all the scenarios, but at the very least it may help to limit the size of untrusted schemas (e.g. limit JSON string length) and also the maximum schema object depth (that can be high for relatively small JSON strings). You also may want to mitigate slow regular expressions in `pattern` and `patternProperties` keywords.727 728Regardless the measures you take, using untrusted schemas increases security risks.729 730 731##### Circular references in JavaScript objects732 733Ajv does not support schemas and validated data that have circular references in objects. See [issue #802](https://github.com/ajv-validator/ajv/issues/802).734 735An attempt to compile such schemas or validate such data would cause stack overflow (or will not complete in case of asynchronous validation). Depending on the parser you use, untrusted data can lead to circular references.736 737 738##### Security risks of trusted schemas739 740Some keywords in JSON Schemas can lead to very slow validation for certain data. These keywords include (but may be not limited to):741 742- `pattern` and `format` for large strings - in some cases using `maxLength` can help mitigate it, but certain regular expressions can lead to exponential validation time even with relatively short strings (see [ReDoS attack](#redos-attack)).743- `patternProperties` for large property names - use `propertyNames` to mitigate, but some regular expressions can have exponential evaluation time as well.744- `uniqueItems` for large non-scalar arrays - use `maxItems` to mitigate745 746__Please note__: The suggestions above to prevent slow validation would only work if you do NOT use `allErrors: true` in production code (using it would continue validation after validation errors).747 748You can validate your JSON schemas against [this meta-schema](https://github.com/ajv-validator/ajv/blob/master/lib/refs/json-schema-secure.json) to check that these recommendations are followed:749 750```javascript751const isSchemaSecure = ajv.compile(require('ajv/lib/refs/json-schema-secure.json'));752 753const schema1 = {format: 'email'};754isSchemaSecure(schema1); // false755 756const schema2 = {format: 'email', maxLength: MAX_LENGTH};757isSchemaSecure(schema2); // true758```759 760__Please note__: following all these recommendation is not a guarantee that validation of untrusted data is safe - it can still lead to some undesirable results.761 762 763##### Content Security Policies (CSP)764See [Ajv and Content Security Policies (CSP)](#ajv-and-content-security-policies-csp)765 766 767## ReDoS attack768 769Certain regular expressions can lead to the exponential evaluation time even with relatively short strings.770 771Please assess the regular expressions you use in the schemas on their vulnerability to this attack - see [safe-regex](https://github.com/substack/safe-regex), for example.772 773__Please note__: some formats that Ajv implements use [regular expressions](https://github.com/ajv-validator/ajv/blob/master/lib/compile/formats.js) that can be vulnerable to ReDoS attack, so if you use Ajv to validate data from untrusted sources __it is strongly recommended__ to consider the following:774 775- making assessment of "format" implementations in Ajv.776- using `format: 'fast'` option that simplifies some of the regular expressions (although it does not guarantee that they are safe).777- replacing format implementations provided by Ajv with your own implementations of "format" keyword that either uses different regular expressions or another approach to format validation. Please see [addFormat](#api-addformat) method.778- disabling format validation by ignoring "format" keyword with option `format: false`779 780Whatever mitigation you choose, please assume all formats provided by Ajv as potentially unsafe and make your own assessment of their suitability for your validation scenarios.781 782 783## Filtering data784 785With [option `removeAdditional`](#options) (added by [andyscott](https://github.com/andyscott)) you can filter data during the validation.786 787This option modifies original data.788 789Example:790 791```javascript792var ajv = new Ajv({ removeAdditional: true });793var schema = {794 "additionalProperties": false,795 "properties": {796 "foo": { "type": "number" },797 "bar": {798 "additionalProperties": { "type": "number" },799 "properties": {800 "baz": { "type": "string" }801 }802 }803 }804}805 806var data = {807 "foo": 0,808 "additional1": 1, // will be removed; `additionalProperties` == false809 "bar": {810 "baz": "abc",811 "additional2": 2 // will NOT be removed; `additionalProperties` != false812 },813}814 815var validate = ajv.compile(schema);816 817console.log(validate(data)); // true818console.log(data); // { "foo": 0, "bar": { "baz": "abc", "additional2": 2 }819```820 821If `removeAdditional` option in the example above were `"all"` then both `additional1` and `additional2` properties would have been removed.822 823If the option were `"failing"` then property `additional1` would have been removed regardless of its value and property `additional2` would have been removed only if its value were failing the schema in the inner `additionalProperties` (so in the example above it would have stayed because it passes the schema, but any non-number would have been removed).824 825__Please note__: If you use `removeAdditional` option with `additionalProperties` keyword inside `anyOf`/`oneOf` keywords your validation can fail with this schema, for example:826 827```json828{829 "type": "object",830 "oneOf": [831 {832 "properties": {833 "foo": { "type": "string" }834 },835 "required": [ "foo" ],836 "additionalProperties": false837 },838 {839 "properties": {840 "bar": { "type": "integer" }841 },842 "required": [ "bar" ],843 "additionalProperties": false844 }845 ]846}847```848 849The intention of the schema above is to allow objects with either the string property "foo" or the integer property "bar", but not with both and not with any other properties.850 851With the option `removeAdditional: true` the validation will pass for the object `{ "foo": "abc"}` but will fail for the object `{"bar": 1}`. It happens because while the first subschema in `oneOf` is validated, the property `bar` is removed because it is an additional property according to the standard (because it is not included in `properties` keyword in the same schema).852 853While this behaviour is unexpected (issues [#129](https://github.com/ajv-validator/ajv/issues/129), [#134](https://github.com/ajv-validator/ajv/issues/134)), it is correct. To have the expected behaviour (both objects are allowed and additional properties are removed) the schema has to be refactored in this way:854 855```json856{857 "type": "object",858 "properties": {859 "foo": { "type": "string" },860 "bar": { "type": "integer" }861 },862 "additionalProperties": false,863 "oneOf": [864 { "required": [ "foo" ] },865 { "required": [ "bar" ] }866 ]867}868```869 870The schema above is also more efficient - it will compile into a faster function.871 872 873## Assigning defaults874 875With [option `useDefaults`](#options) Ajv will assign values from `default` keyword in the schemas of `properties` and `items` (when it is the array of schemas) to the missing properties and items.876 877With the option value `"empty"` properties and items equal to `null` or `""` (empty string) will be considered missing and assigned defaults.878 879This option modifies original data.880 881__Please note__: the default value is inserted in the generated validation code as a literal, so the value inserted in the data will be the deep clone of the default in the schema.882 883 884Example 1 (`default` in `properties`):885 886```javascript887var ajv = new Ajv({ useDefaults: true });888var schema = {889 "type": "object",890 "properties": {891 "foo": { "type": "number" },892 "bar": { "type": "string", "default": "baz" }893 },894 "required": [ "foo", "bar" ]895};896 897var data = { "foo": 1 };898 899var validate = ajv.compile(schema);900 901console.log(validate(data)); // true902console.log(data); // { "foo": 1, "bar": "baz" }903```904 905Example 2 (`default` in `items`):906 907```javascript908var schema = {909 "type": "array",910 "items": [911 { "type": "number" },912 { "type": "string", "default": "foo" }913 ]914}915 916var data = [ 1 ];917 918var validate = ajv.compile(schema);919 920console.log(validate(data)); // true921console.log(data); // [ 1, "foo" ]922```923 924`default` keywords in other cases are ignored:925 926- not in `properties` or `items` subschemas927- in schemas inside `anyOf`, `oneOf` and `not` (see [#42](https://github.com/ajv-validator/ajv/issues/42))928- in `if` subschema of `switch` keyword929- in schemas generated by custom macro keywords930 931The [`strictDefaults` option](#options) customizes Ajv's behavior for the defaults that Ajv ignores (`true` raises an error, and `"log"` outputs a warning).932 933 934## Coercing data types935 936When you are validating user inputs all your data properties are usually strings. The option `coerceTypes` allows you to have your data types coerced to the types specified in your schema `type` keywords, both to pass the validation and to use the correctly typed data afterwards.937 938This option modifies original data.939 940__Please note__: if you pass a scalar value to the validating function its type will be coerced and it will pass the validation, but the value of the variable you pass won't be updated because scalars are passed by value.941 942 943Example 1:944 945```javascript946var ajv = new Ajv({ coerceTypes: true });947var schema = {948 "type": "object",949 "properties": {950 "foo": { "type": "number" },951 "bar": { "type": "boolean" }952 },953 "required": [ "foo", "bar" ]954};955 956var data = { "foo": "1", "bar": "false" };957 958var validate = ajv.compile(schema);959 960console.log(validate(data)); // true961console.log(data); // { "foo": 1, "bar": false }962```963 964Example 2 (array coercions):965 966```javascript967var ajv = new Ajv({ coerceTypes: 'array' });968var schema = {969 "properties": {970 "foo": { "type": "array", "items": { "type": "number" } },971 "bar": { "type": "boolean" }972 }973};974 975var data = { "foo": "1", "bar": ["false"] };976 977var validate = ajv.compile(schema);978 979console.log(validate(data)); // true980console.log(data); // { "foo": [1], "bar": false }981```982 983The coercion rules, as you can see from the example, are different from JavaScript both to validate user input as expected and to have the coercion reversible (to correctly validate cases where different types are defined in subschemas of "anyOf" and other compound keywords).984 985See [Coercion rules](https://github.com/ajv-validator/ajv/blob/master/COERCION.md) for details.986 987 988## API989 990##### new Ajv(Object options) -> Object991 992Create Ajv instance.993 994 995##### .compile(Object schema) -> Function<Object data>996 997Generate validating function and cache the compiled schema for future use.998 999Validating function returns a boolean value. This function has properties `errors` and `schema`. Errors encountered during the last validation are assigned to `errors` property (it is assigned `null` if there was no errors). `schema` property contains the reference to the original schema.1000 1001The schema passed to this method will be validated against meta-schema unless `validateSchema` option is false. If schema is invalid, an error will be thrown. See [options](#options).1002 1003 1004##### <a name="api-compileAsync"></a>.compileAsync(Object schema [, Boolean meta] [, Function callback]) -> Promise1005 1006Asynchronous version of `compile` method that loads missing remote schemas using asynchronous function in `options.loadSchema`. This function returns a Promise that resolves to a validation function. An optional callback passed to `compileAsync` will be called with 2 parameters: error (or null) and validating function. The returned promise will reject (and the callback will be called with an error) when:1007 1008- missing schema can't be loaded (`loadSchema` returns a Promise that rejects).1009- a schema containing a missing reference is loaded, but the reference cannot be resolved.1010- schema (or some loaded/referenced schema) is invalid.1011 1012The function compiles schema and loads the first missing schema (or meta-schema) until all missing schemas are loaded.1013 1014You can asynchronously compile meta-schema by passing `true` as the second parameter.1015 1016See example in [Asynchronous compilation](#asynchronous-schema-compilation).1017 1018 1019##### .validate(Object schema|String key|String ref, data) -> Boolean1020 1021Validate data using passed schema (it will be compiled and cached).1022 1023Instead of the schema you can use the key that was previously passed to `addSchema`, the schema id if it was present in the schema or any previously resolved reference.1024 1025Validation errors will be available in the `errors` property of Ajv instance (`null` if there were no errors).1026 1027__Please note__: every time this method is called the errors are overwritten so you need to copy them to another variable if you want to use them later.1028 1029If the schema is asynchronous (has `$async` keyword on the top level) this method returns a Promise. See [Asynchronous validation](#asynchronous-validation).1030 1031 1032##### .addSchema(Array<Object>|Object schema [, String key]) -> Ajv1033 1034Add schema(s) to validator instance. This method does not compile schemas (but it still validates them). Because of that dependencies can be added in any order and circular dependencies are supported. It also prevents unnecessary compilation of schemas that are containers for other schemas but not used as a whole.1035 1036Array of schemas can be passed (schemas should have ids), the second parameter will be ignored.1037 1038Key can be passed that can be used to reference the schema and will be used as the schema id if there is no id inside the schema. If the key is not passed, the schema id will be used as the key.1039 1040 1041Once the schema is added, it (and all the references inside it) can be referenced in other schemas and used to validate data.1042 1043Although `addSchema` does not compile schemas, explicit compilation is not required - the schema will be compiled when it is used first time.1044 1045By default the schema is validated against meta-schema before it is added, and if the schema does not pass validation the exception is thrown. This behaviour is controlled by `validateSchema` option.1046 1047__Please note__: Ajv uses the [method chaining syntax](https://en.wikipedia.org/wiki/Method_chaining) for all methods with the prefix `add*` and `remove*`.1048This allows you to do nice things like the following.1049 1050```javascript1051var validate = new Ajv().addSchema(schema).addFormat(name, regex).getSchema(uri);1052```1053 1054##### .addMetaSchema(Array<Object>|Object schema [, String key]) -> Ajv1055 1056Adds meta schema(s) that can be used to validate other schemas. That function should be used instead of `addSchema` because there may be instance options that would compile a meta schema incorrectly (at the moment it is `removeAdditional` option).1057 1058There is no need to explicitly add draft-07 meta schema (http://json-schema.org/draft-07/schema) - it is added by default, unless option `meta` is set to `false`. You only need to use it if you have a changed meta-schema that you want to use to validate your schemas. See `validateSchema`.1059 1060 1061##### <a name="api-validateschema"></a>.validateSchema(Object schema) -> Boolean1062 1063Validates schema. This method should be used to validate schemas rather than `validate` due to the inconsistency of `uri` format in JSON Schema standard.1064 1065By default this method is called automatically when the schema is added, so you rarely need to use it directly.1066 1067If schema doesn't have `$schema` property, it is validated against draft 6 meta-schema (option `meta` should not be false).1068 1069If schema has `$schema` property, then the schema with this id (that should be previously added) is used to validate passed schema.1070 1071Errors will be available at `ajv.errors`.1072 1073 1074##### .getSchema(String key) -> Function<Object data>1075 1076Retrieve compiled schema previously added with `addSchema` by the key passed to `addSchema` or by its full reference (id). The returned validating function has `schema` property with the reference to the original schema.1077 1078 1079##### .removeSchema([Object schema|String key|String ref|RegExp pattern]) -> Ajv1080 1081Remove added/cached schema. Even if schema is referenced by other schemas it can be safely removed as dependent schemas have local references.1082 1083Schema can be removed using:1084- key passed to `addSchema`1085- it's full reference (id)1086- RegExp that should match schema id or key (meta-schemas won't be removed)1087- actual schema object that will be stable-stringified to remove schema from cache1088 1089If no parameter is passed all schemas but meta-schemas will be removed and the cache will be cleared.1090 1091 1092##### <a name="api-addformat"></a>.addFormat(String name, String|RegExp|Function|Object format) -> Ajv1093 1094Add custom format to validate strings or numbers. It can also be used to replace pre-defined formats for Ajv instance.1095 1096Strings are converted to RegExp.1097 1098Function should return validation result as `true` or `false`.1099 1100If object is passed it should have properties `validate`, `compare` and `async`:1101 1102- _validate_: a string, RegExp or a function as described above.1103- _compare_: an optional comparison function that accepts two strings and compares them according to the format meaning. This function is used with keywords `formatMaximum`/`formatMinimum` (defined in [ajv-keywords](https://github.com/ajv-validator/ajv-keywords) package). It should return `1` if the first value is bigger than the second value, `-1` if it is smaller and `0` if it is equal.1104- _async_: an optional `true` value if `validate` is an asynchronous function; in this case it should return a promise that resolves with a value `true` or `false`.1105- _type_: an optional type of data that the format applies to. It can be `"string"` (default) or `"number"` (see https://github.com/ajv-validator/ajv/issues/291#issuecomment-259923858). If the type of data is different, the validation will pass.1106 1107Custom formats can be also added via `formats` option.1108 1109 1110##### <a name="api-addkeyword"></a>.addKeyword(String keyword, Object definition) -> Ajv1111 1112Add custom validation keyword to Ajv instance.1113 1114Keyword should be different from all standard JSON Schema keywords and different from previously defined keywords. There is no way to redefine keywords or to remove keyword definition from the instance.1115 1116Keyword must start with a letter, `_` or `$`, and may continue with letters, numbers, `_`, `$`, or `-`.1117It is recommended to use an application-specific prefix for keywords to avoid current and future name collisions.1118 1119Example Keywords:1120- `"xyz-example"`: valid, and uses prefix for the xyz project to avoid name collisions.1121- `"example"`: valid, but not recommended as it could collide with future versions of JSON Schema etc.1122- `"3-example"`: invalid as numbers are not allowed to be the first character in a keyword1123 1124Keyword definition is an object with the following properties:1125 1126- _type_: optional string or array of strings with data type(s) that the keyword applies to. If not present, the keyword will apply to all types.1127- _validate_: validating function1128- _compile_: compiling function1129- _macro_: macro function1130- _inline_: compiling function that returns code (as string)1131- _schema_: an optional `false` value used with "validate" keyword to not pass schema1132- _metaSchema_: an optional meta-schema for keyword schema1133- _dependencies_: an optional list of properties that must be present in the parent schema - it will be checked during schema compilation1134- _modifying_: `true` MUST be passed if keyword modifies data1135- _statements_: `true` can be passed in case inline keyword generates statements (as opposed to expression)1136- _valid_: pass `true`/`false` to pre-define validation result, the result returned from validation function will be ignored. This option cannot be used with macro keywords.1137- _$data_: an optional `true` value to support [$data reference](#data-reference) as the value of custom keyword. The reference will be resolved at validation time. If the keyword has meta-schema it would be extended to allow $data and it will be used to validate the resolved value. Supporting $data reference requires that keyword has validating function (as the only option or in addition to compile, macro or inline function).1138- _async_: an optional `true` value if the validation function is asynchronous (whether it is compiled or passed in _validate_ property); in this case it should return a promise that resolves with a value `true` or `false`. This option is ignored in case of "macro" and "inline" keywords.1139- _errors_: an optional boolean or string `"full"` indicating whether keyword returns errors. If this property is not set Ajv will determine if the errors were set in case of failed validation.1140 1141_compile_, _macro_ and _inline_ are mutually exclusive, only one should be used at a time. _validate_ can be used separately or in addition to them to support $data reference.1142 1143__Please note__: If the keyword is validating data type that is different from the type(s) in its definition, the validation function will not be called (and expanded macro will not be used), so there is no need to check for data type inside validation function or inside schema returned by macro function (unless you want to enforce a specific type and for some reason do not want to use a separate `type` keyword for that). In the same way as standard keywords work, if the keyword does not apply to the data type being validated, the validation of this keyword will succeed.1144 1145See [Defining custom keywords](#defining-custom-keywords) for more details.1146 1147 1148##### .getKeyword(String keyword) -> Object|Boolean1149 1150Returns custom keyword definition, `true` for pre-defined keywords and `false` if the keyword is unknown.1151 1152 1153##### .removeKeyword(String keyword) -> Ajv1154 1155Removes custom or pre-defined keyword so you can redefine them.1156 1157While this method can be used to extend pre-defined keywords, it can also be used to completely change their meaning - it may lead to unexpected results.1158 1159__Please note__: schemas compiled before the keyword is removed will continue to work without changes. To recompile schemas use `removeSchema` method and compile them again.1160 1161 1162##### .errorsText([Array<Object> errors [, Object options]]) -> String1163 1164Returns the text with all errors in a String.1165 1166Options can have properties `separator` (string used to separate errors, ", " by default) and `dataVar` (the variable name that dataPaths are prefixed with, "data" by default).1167 1168 1169## Options1170 1171Defaults:1172 1173```javascript1174{1175 // validation and reporting options:1176 $data: false,1177 allErrors: false,1178 verbose: false,1179 $comment: false, // NEW in Ajv version 6.01180 jsonPointers: false,1181 uniqueItems: true,1182 unicode: true,1183 nullable: false,1184 format: 'fast',1185 formats: {},1186 unknownFormats: true,1187 schemas: {},1188 logger: undefined,1189 // referenced schema options:1190 schemaId: '$id',1191 missingRefs: true,1192 extendRefs: 'ignore', // recommended 'fail'1193 loadSchema: undefined, // function(uri: string): Promise {}1194 // options to modify validated data:1195 removeAdditional: false,1196 useDefaults: false,1197 coerceTypes: false,1198 // strict mode options1199 strictDefaults: false,1200 strictKeywords: false,