From 188eadf806662fe8b30bdf305707e3bf26b76e5d Mon Sep 17 00:00:00 2001 From: Evgeny Poberezkin <2769109+epoberezkin@users.noreply.github.com> Date: Tue, 25 Aug 2020 09:30:11 -0400 Subject: [PATCH] refactor: remove doT --- .codeclimate.yml | 2 - .gitignore | 3 - .prettierignore | 1 - CONTRIBUTING.md | 6 +- CUSTOM.md | 8 +- README.md | 8 +- lib/compile/rules.ts | 2 +- lib/compile/validate/index.ts | 8 +- lib/compile/validate/iterate.ts | 2 +- lib/compile/validate/keyword.ts | 2 +- lib/dot/custom.jst | 213 ------------------------ lib/dot/definitions.def | 194 --------------------- lib/dot/errors.def | 122 -------------- lib/dotjs/README.md | 3 - lib/keyword.ts | 3 +- lib/types.ts | 2 +- package.json | 9 +- scripts/compile-dots.js | 85 ---------- spec/custom.spec.js | 73 ++++---- spec/custom_rules/index.js | 14 -- spec/custom_rules/range.jst | 8 - spec/custom_rules/range_with_errors.jst | 42 ----- 22 files changed, 51 insertions(+), 759 deletions(-) delete mode 100644 .codeclimate.yml delete mode 100644 lib/dot/custom.jst delete mode 100644 lib/dot/definitions.def delete mode 100644 lib/dot/errors.def delete mode 100644 lib/dotjs/README.md delete mode 100644 scripts/compile-dots.js delete mode 100644 spec/custom_rules/index.js delete mode 100644 spec/custom_rules/range.jst delete mode 100644 spec/custom_rules/range_with_errors.jst diff --git a/.codeclimate.yml b/.codeclimate.yml deleted file mode 100644 index 84849f008..000000000 --- a/.codeclimate.yml +++ /dev/null @@ -1,2 +0,0 @@ -exclude_paths: -- lib/dotjs/** diff --git a/.gitignore b/.gitignore index b7f774a0d..9951605f1 100644 --- a/.gitignore +++ b/.gitignore @@ -29,9 +29,6 @@ node_modules .DS_Store -# Compiled templates -lib/dotjs/*.js - # Browserified tests .browser diff --git a/.prettierignore b/.prettierignore index e2fcb3647..8d0387cf3 100644 --- a/.prettierignore +++ b/.prettierignore @@ -3,4 +3,3 @@ spec/JSON-Schema-Test-Suite coverage dist .nyc_output -lib/dotjs diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 00a6afcd1..e83384d00 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -133,11 +133,9 @@ npm run test-fast git commit -nm 'type: message' ``` -All validation functions are generated using doT templates in [dot](https://github.com/ajv-validator/ajv/tree/master/lib/dot) folder. Templates are precompiled so doT is not a run-time dependency. +`npm run build` - compiles typescript to dist folder. -`npm run build` - compiles templates to [dotjs](https://github.com/ajv-validator/ajv/tree/master/lib/dotjs) folder. - -`npm run watch` - automatically compiles templates when files in dot folder change +`npm run watch` - automatically compiles typescript when files in lib folder change #### Pull requests diff --git a/CUSTOM.md b/CUSTOM.md index 49d5b7a90..41fa6f2ea 100644 --- a/CUSTOM.md +++ b/CUSTOM.md @@ -43,9 +43,7 @@ Example. `constant` keyword (a synonym for draft-06 keyword `const`, it is equiv ```javascript ajv.addKeyword("constant", { validate: function (schema, data) { - return typeof schema == "object" && schema !== null - ? deepEqual(schema, data) - : schema === data + return typeof schema == "object" && schema !== null ? deepEqual(schema, data) : schema === data }, errors: false, }) @@ -388,7 +386,9 @@ All custom keywords but macro keywords can optionally create custom error messag Synchronous validating and compiled keywords should define errors by assigning them to `.errors` property of the validation function. Asynchronous keywords can return promise that rejects with `new Ajv.ValidationError(errors)`, where `errors` is an array of custom validation errors (if you don't want to define custom errors in asynchronous keyword, its validation function can return the promise that resolves with `false`). -Inline custom keyword should increase error counter `errors` and add error to `vErrors` array (it can be null). This can be done for both synchronous and asynchronous keywords. See [example range keyword](https://github.com/ajv-validator/ajv/blob/master/spec/custom_rules/range_with_errors.jst). +TODO replace "inline" keywords with "code" keywords + +Inline custom keyword should increase error counter `errors` and add error to `vErrors` array (it can be null). This can be done for both synchronous and asynchronous keywords. When inline keyword performs validation Ajv checks whether it created errors by comparing errors count before and after validation. To skip this check add option `errors` (can be `"full"`, `true` or `false`) to keyword definition: diff --git a/README.md b/README.md index e6acbdb57..5526d4c63 100644 --- a/README.md +++ b/README.md @@ -106,7 +106,7 @@ ajv.addMetaSchema(require("ajv/lib/refs/json-schema-draft-06.json")) ## Performance -Ajv 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. +Ajv generates code to turn JSON Schemas into super-fast validation functions that are efficient for v8 optimization. Currently Ajv is the fastest and the most standard compliant validator according to these benchmarks: @@ -1370,11 +1370,9 @@ npm test ## Contributing -All validation functions are generated using doT templates in [dot](https://github.com/ajv-validator/ajv/tree/master/lib/dot) folder. Templates are precompiled so doT is not a run-time dependency. +`npm run build` - compiles typescript to dist folder. -`npm run build` - compiles templates to [dotjs](https://github.com/ajv-validator/ajv/tree/master/lib/dotjs) folder. - -`npm run watch` - automatically compiles templates when files in dot folder change +`npm run watch` - automatically compiles typescript when files in lib folder change Please see [Contributing guidelines](https://github.com/ajv-validator/ajv/blob/master/CONTRIBUTING.md) diff --git a/lib/compile/rules.ts b/lib/compile/rules.ts index 2d2a578b3..169f8db3f 100644 --- a/lib/compile/rules.ts +++ b/lib/compile/rules.ts @@ -16,7 +16,7 @@ export interface RuleGroup { export interface Rule { keyword: string - code: (it: CompilationContext, keyword?: string, ruleType?: string) => void + code: (it: CompilationContext, keyword: string, ruleType?: string) => void implements?: string[] definition?: KeywordDefinition custom?: true diff --git a/lib/compile/validate/index.ts b/lib/compile/validate/index.ts index ac6ac3f28..76f444b3b 100644 --- a/lib/compile/validate/index.ts +++ b/lib/compile/validate/index.ts @@ -47,7 +47,7 @@ export default function validateCode( if ($comment && schema.$comment) commentKeyword(it) if (isTop) { - updateTopContext(it) + delete it.isTop checkNoDefault(it) initializeTop(it) typeAndKeywords() @@ -136,12 +136,6 @@ function startFunction({ ) } -function updateTopContext(it: CompilationContext): void { - // it.rootId = resolve.fullPath(it.root.schema.$id) - // it.baseId = it.baseId || it.rootId - delete it.isTop -} - function checkNoDefault({ schema, opts: {useDefaults, strictDefaults}, diff --git a/lib/compile/validate/iterate.ts b/lib/compile/validate/iterate.ts index bb070a562..d56c74574 100644 --- a/lib/compile/validate/iterate.ts +++ b/lib/compile/validate/iterate.ts @@ -9,7 +9,7 @@ export function schemaKeywords( it: CompilationContext, types: string[], typeErrors: boolean, - top: boolean + top?: boolean ): void { const { gen, diff --git a/lib/compile/validate/keyword.ts b/lib/compile/validate/keyword.ts index 32d6f43da..0d7d76d69 100644 --- a/lib/compile/validate/keyword.ts +++ b/lib/compile/validate/keyword.ts @@ -9,7 +9,7 @@ import { } from "../../types" import {applySubschema} from "../subschema" import {reportError, reportExtraError, extendErrors} from "../errors" -import {getParentData, dataNotType} from "../../vocabularies/util" +import {getParentData} from "../../vocabularies/util" export const keywordError: KeywordErrorDefinition = { message: ({keyword}) => `'should pass "${keyword}" keyword validation'`, diff --git a/lib/dot/custom.jst b/lib/dot/custom.jst deleted file mode 100644 index d33eaa02c..000000000 --- a/lib/dot/custom.jst +++ /dev/null @@ -1,213 +0,0 @@ -{{# def.definitions }} -{{# def.errors }} -{{# def.setupKeyword }} -{{# def.$data }} - -{{ - var $rule = this - , $definition = 'definition' + $lvl - , $rDef = $rule.definition - , $closingBraces = ''; - var $validate = $rDef.validate; - var $compile, $macro, $ruleValidate, $validateCode; -}} - -{{? $isData && $rDef.$data }} - {{ - $validateCode = 'keywordValidate' + $lvl; - var $validateSchema = $rDef.validateSchema; - }} - var {{=$definition}} = RULES.custom['{{=$keyword}}'].definition; - var {{=$validateCode}} = {{=$definition}}.validate; -{{??}} - {{ - $ruleValidate = useCustomRule.call(it.self, $rule, $schema, it.schema, it); - if (!$ruleValidate) return; - $schemaValue = it.topSchemaRef + $schemaPath; - $validateCode = $ruleValidate.code; - $compile = $rDef.compile; - $macro = $rDef.macro; - }} -{{?}} - -{{ - var $ruleErrs = $validateCode + '.errors' - , $i = 'i' + $lvl - , $ruleErr = 'ruleErr' + $lvl - , $asyncKeyword = $rDef.async; - - if ($asyncKeyword && !it.async) - throw new Error('async keyword in sync schema'); -}} - - -{{? !$macro }}{{=$ruleErrs}} = null;{{?}} -var {{=$errs}} = errors; -var {{=$valid}}; - -{{## def.callRuleValidate: - {{=$validateCode}}.call( - {{? it.opts.passContext }}this{{??}}self{{?}} - {{? $compile || $rDef.schema === false }} - , {{=$data}} - {{??}} - , {{=$schemaValue}} - , {{=$data}} - , {{=it.topSchemaRef}}{{=it.schemaPath}} - {{?}} - , {{# def.dataPath }} - {{# def.passParentData }} - , rootData - ) -#}} - -{{## def.extendErrors:_inline: - for (var {{=$i}}={{=$errs}}; {{=$i}} 0) - || _schema === false - : it.util.schemaHasRules(_schema, it.RULES.all)) -#}} - - -{{## def.willOptimize: - it.util.varOccurrences($code, $nextData) < 2 -#}} - - -{{## def.generateSubschemaCode: - {{ - var $code = it.validateCode($it); - $it.baseId = $currentBaseId; - }} -#}} - - -{{## def.insertSubschemaCode: - {{= it.validateCode($it) }} - {{ $it.baseId = $currentBaseId; }} -#}} - - -{{## def._optimizeValidate: - it.util.varReplace($code, $nextData, $passData) -#}} - - -{{## def.optimizeValidate: - {{? {{# def.willOptimize}} }} - {{= {{# def._optimizeValidate }} }} - {{??}} - var {{=$nextData}} = {{=$passData}}; - {{= $code }} - {{?}} -#}} - - -{{## def.$data: - {{ - var $isData = it.opts.$data && $schema && $schema.$data - , $schemaValue; - }} - {{? $isData }} - var schema{{=$lvl}} = {{= it.util.getData($schema.$data, $dataLvl, it.dataPathArr) }}; - {{ $schemaValue = 'schema' + $lvl; }} - {{??}} - {{ $schemaValue = $schema; }} - {{?}} -#}} - - -{{## def.$dataNotType:_type: - {{?$isData}} ({{=$schemaValue}} !== undefined && typeof {{=$schemaValue}} != _type) || {{?}} -#}} - - -{{## def.check$dataIsArray: - if (schema{{=$lvl}} === undefined) {{=$valid}} = true; - else if (!Array.isArray(schema{{=$lvl}})) {{=$valid}} = false; - else { -#}} - - -{{## def.numberKeyword: - {{? !($isData || typeof $schema == 'number') }} - {{ throw new Error($keyword + ' must be number'); }} - {{?}} -#}} - - -{{## def.beginDefOut: - {{ - var $$outStack = $$outStack || []; - $$outStack.push(out); - out = ''; - }} -#}} - - -{{## def.storeDefOut:_variable: - {{ - var _variable = out; - out = $$outStack.pop(); - }} -#}} - - -{{## def.dataPath:(dataPath || ''){{? it.errorPath != '""'}} + {{= it.errorPath }}{{?}}#}} - -{{## def.setParentData: - {{ - var $parentData = $dataLvl ? 'data' + (($dataLvl-1)||'') : 'parentData' - , $parentDataProperty = $dataLvl ? it.dataPathArr[$dataLvl] : 'parentDataProperty'; - }} -#}} - -{{## def.passParentData: - {{# def.setParentData }} - , {{= $parentData }} - , {{= $parentDataProperty }} -#}} - - -{{## def.iterateProperties: - {{? $ownProperties }} - {{=$dataProperties}} = {{=$dataProperties}} || Object.keys({{=$data}}); - for (var {{=$idx}}=0; {{=$idx}}<{{=$dataProperties}}.length; {{=$idx}}++) { - var {{=$key}} = {{=$dataProperties}}[{{=$idx}}]; - {{??}} - for (var {{=$key}} in {{=$data}}) { - {{?}} -#}} - - -{{## def.noPropertyInData: - {{=$useData}} === undefined - {{? $ownProperties }} - || !{{# def.isOwnProperty }} - {{?}} -#}} - - -{{## def.isOwnProperty: - Object.prototype.hasOwnProperty.call({{=$data}}, '{{=it.util.escapeQuotes($propertyKey)}}') -#}} diff --git a/lib/dot/errors.def b/lib/dot/errors.def deleted file mode 100644 index b65e02521..000000000 --- a/lib/dot/errors.def +++ /dev/null @@ -1,122 +0,0 @@ -{{# def.definitions }} - -{{## def._error:_rule: - {{ 'istanbul ignore else'; }} - {{? it.createErrors !== false }} - { - keyword: '{{= $errorKeyword || _rule }}' - , dataPath: (dataPath || '') + {{= it.errorPath }} - , schemaPath: {{=it.util.toQuotedString($errSchemaPath)}} - , params: {{# def._errorParams[_rule] }} - {{? it.opts.messages !== false }} - , message: {{# def._errorMessages[_rule] }} - {{?}} - {{? it.opts.verbose }} - , schema: {{# def._errorSchemas[_rule] }} - , parentSchema: {{=it.topSchemaRef}}{{=it.schemaPath}} - , data: {{=$data}} - {{?}} - } - {{??}} - {} - {{?}} -#}} - - -{{## def._addError:_rule: - if (vErrors === null) vErrors = [err]; - else vErrors.push(err); - errors++; -#}} - - -{{## def.addError:_rule: - var err = {{# def._error:_rule }}; - {{# def._addError:_rule }} -#}} - - -{{## def.error:_rule: - {{# def.beginDefOut}} - {{# def._error:_rule }} - {{# def.storeDefOut:__err }} - - {{? !it.compositeRule && $breakOnError }} - {{ 'istanbul ignore if'; }} - {{? it.async }} - throw new ValidationError([{{=__err}}]); - {{??}} - validate.errors = [{{=__err}}]; - return false; - {{?}} - {{??}} - var err = {{=__err}}; - {{# def._addError:_rule }} - {{?}} -#}} - - -{{## def.extraError:_rule: - {{# def.addError:_rule}} - {{? !it.compositeRule && $breakOnError }} - {{ 'istanbul ignore if'; }} - {{? it.async }} - throw new ValidationError(vErrors); - {{??}} - validate.errors = vErrors; - return false; - {{?}} - {{?}} -#}} - - -{{## def.checkError:_rule: - if (!{{=$valid}}) { - {{# def.error:_rule }} - } -#}} - - -{{## def.resetErrors: - errors = {{=$errs}}; - if (vErrors !== null) { - if ({{=$errs}}) vErrors.length = {{=$errs}}; - else vErrors = null; - } -#}} - - -{{## def.concatSchemaEQ:{{?$isData}}' + {{=$schemaValue}} + '{{??}}{{=it.util.escapeQuotes($schema)}}{{?}}#}} - -{{## def._errorMessages = { - $ref: "'can\\\'t resolve reference {{=it.util.escapeQuotes($schema)}}'", - custom: "'should pass \"{{=$rule.keyword}}\" keyword validation'", - patternRequired: "'should have property matching pattern \\'{{=$missingPattern}}\\''", - switch: "'should pass \"switch\" keyword validation'", - _formatLimit: "'should be {{=$opStr}} \"{{#def.concatSchemaEQ}}\"'", - _formatExclusiveLimit: "'{{=$exclusiveKeyword}} should be boolean'" -} #}} - - -{{## def.schemaRefOrQS: {{?$isData}}{{=it.topSchemaRef}}{{=$schemaPath}}{{??}}{{=it.util.toQuotedString($schema)}}{{?}} #}} - -{{## def._errorSchemas = { - $ref: "{{=it.util.toQuotedString($schema)}}", - custom: "{{=it.topSchemaRef}}{{=$schemaPath}}", - patternRequired: "{{=it.topSchemaRef}}{{=$schemaPath}}", - switch: "{{=it.topSchemaRef}}{{=$schemaPath}}", - _formatLimit: "{{#def.schemaRefOrQS}}", - _formatExclusiveLimit: "{{=it.topSchemaRef}}{{=$schemaPath}}" -} #}} - - -{{## def.schemaValueQS: {{?$isData}}{{=$schemaValue}}{{??}}{{=it.util.toQuotedString($schema)}}{{?}} #}} - -{{## def._errorParams = { - $ref: "{ ref: '{{=it.util.escapeQuotes($schema)}}' }", - custom: "{ keyword: '{{=$rule.keyword}}' }", - patternRequired: "{ missingPattern: '{{=$missingPattern}}' }", - switch: "{ caseIndex: {{=$caseIndex}} }", - _formatLimit: "{ comparison: {{=$opExpr}}, limit: {{#def.schemaValueQS}}, exclusive: {{=$exclusive}} }", - _formatExclusiveLimit: "{}" -} #}} diff --git a/lib/dotjs/README.md b/lib/dotjs/README.md deleted file mode 100644 index 4d994846c..000000000 --- a/lib/dotjs/README.md +++ /dev/null @@ -1,3 +0,0 @@ -These files are compiled dot templates from dot folder. - -Do NOT edit them directly, edit the templates and run `npm run build` from main ajv folder. diff --git a/lib/keyword.ts b/lib/keyword.ts index dd5d73f54..a52247286 100644 --- a/lib/keyword.ts +++ b/lib/keyword.ts @@ -18,7 +18,6 @@ import {definitionSchema} from "./definition_schema" import keywordCode, {validateKeywordSchema, keywordError} from "./compile/validate/keyword" const IDENTIFIER = /^[a-z_$][a-z0-9_$-]*$/i -const customRuleCode = require("./dotjs/custom") /** * Define vocabulary @@ -112,7 +111,7 @@ export function addKeyword( keyword, definition, custom: true, - code: ruleCode, // "code" in definition || !definition.$data ? ruleCode : customRuleCode, + code: ruleCode, implements: definition.implements, } diff --git a/lib/types.ts b/lib/types.ts index 51b5e4552..c0332c469 100644 --- a/lib/types.ts +++ b/lib/types.ts @@ -136,7 +136,7 @@ export interface CompilationContext { self: any // TODO RULES: ValidationRules logger: Logger // TODO ? - isTop: boolean // TODO ? + isTop?: boolean // TODO ? root: SchemaRoot // TODO ? rootId: string // TODO ? topSchemaRef: string diff --git a/package.json b/package.json index 7a3d4113c..6c97ca039 100644 --- a/package.json +++ b/package.json @@ -23,15 +23,13 @@ "test-ts": "tsc --target ES5 --noImplicitAny --noEmit spec/typescript/index.ts", "bundle": "del-cli dist && node ./scripts/bundle.js . Ajv pure_getters", "bundle-beautify": "node ./scripts/bundle.js js-beautify", - "dot": "del-cli lib/dotjs/*.js \"!lib/dotjs/index.js\" && node scripts/compile-dots.js", - "tsc": "tsc || true && cp -r lib/refs dist/refs", - "build": "npm run dot && npm run tsc", + "build": "del-cli dist && tsc || true && cp -r lib/refs dist/refs", "test-karma": "karma start", "test-browser": "del-cli .browser && npm run bundle && scripts/prepare-tests && npm run test-karma", "test-all": "npm run test-cov && if-node-version 12 npm run test-browser", "test": "npm run lint && npm run build && npm run test-cov", "prepublish": "npm run build", - "watch": "watch \"npm run build\" ./lib/dot" + "watch": "watch \"npm run build\" ./lib" }, "nyc": { "exclude": [ @@ -83,7 +81,6 @@ "chai": "^4.0.1", "coveralls": "^3.0.1", "del-cli": "^3.0.0", - "dot": "^1.0.3", "eslint": "^7.3.1", "eslint-config-prettier": "^6.11.0", "gh-pages-generator": "^0.2.3", @@ -91,7 +88,6 @@ "husky": "^4.2.5", "if-node-version": "^1.0.0", "js-beautify": "^1.7.3", - "jshint": "^2.10.2", "json-schema-test": "^2.0.0", "karma": "^5.0.0", "karma-chrome-launcher": "^3.0.0", @@ -100,7 +96,6 @@ "lint-staged": "^10.2.11", "mocha": "^8.0.1", "nyc": "^15.0.0", - "pre-commit": "^1.1.1", "prettier": "^2.0.5", "require-globify": "^1.3.0", "typescript": "^4.0.0", diff --git a/scripts/compile-dots.js b/scripts/compile-dots.js deleted file mode 100644 index a72e7ecb2..000000000 --- a/scripts/compile-dots.js +++ /dev/null @@ -1,85 +0,0 @@ -//compile doT templates to js functions -"use strict" - -var glob = require("glob"), - fs = require("fs"), - path = require("path"), - doT = require("dot"), - beautify = require("js-beautify").js_beautify - -var defsRootPath = process.argv[2] || path.join(__dirname, "../lib") - -var defs = {} -var defFiles = glob.sync("./dot/**/*.def", {cwd: defsRootPath}) -defFiles.forEach((f) => { - var name = path.basename(f, ".def") - defs[name] = fs.readFileSync(path.join(defsRootPath, f)) -}) - -var filesRootPath = process.argv[3] || path.join(__dirname, "../lib") -var files = glob.sync("./dot/**/*.jst", {cwd: filesRootPath}) - -var dotjsPath = path.join(filesRootPath, "./dotjs") -try { - fs.mkdirSync(dotjsPath) -} catch (e) {} - -console.log("\n\nCompiling:") - -var FUNCTION_NAME = /function\s+anonymous\s*\(it[^)]*\)\s*{/ -var OUT_EMPTY_STRING = /out\s*\+=\s*'\s*';/g -var ISTANBUL = /'(istanbul[^']+)';/g -var ERROR_KEYWORD = /\$errorKeyword/g -var ERROR_KEYWORD_OR = /\$errorKeyword\s+\|\|/g -var VARS = [ - "$errs", - "$valid", - "$lvl", - "$data", - "$dataLvl", - "$errorKeyword", - "$closingBraces", - "$schemaPath", - "$validate", -] - -files.forEach((f) => { - var keyword = path.basename(f, ".jst") - var targetPath = path.join(dotjsPath, keyword + ".js") - var template = fs.readFileSync(path.join(filesRootPath, f)) - var code = doT.compile(template, defs) - code = code - .toString() - .replace(OUT_EMPTY_STRING, "") - .replace( - FUNCTION_NAME, - "function generate_" + keyword + "(it, $keyword, $ruleType) {" - ) - .replace(ISTANBUL, "/* $1 */") - removeAlwaysFalsyInOr() - VARS.forEach(removeUnusedVar) - code = "'use strict';\nmodule.exports = " + code - code = beautify(code, {indent_size: 2}) + "\n" - fs.writeFileSync(targetPath, code) - console.log("compiled", keyword) - - function removeUnusedVar(v) { - v = v.replace(/\$/g, "\\$$") - var regexp = new RegExp(v + "[^A-Za-z0-9_$]", "g") - var count = occurrences(regexp) - if (count === 1) { - regexp = new RegExp("var\\s+" + v + "\\s*=[^;]+;|var\\s+" + v + ";") - code = code.replace(regexp, "") - } - } - - function removeAlwaysFalsyInOr() { - var countUsed = occurrences(ERROR_KEYWORD) - var countOr = occurrences(ERROR_KEYWORD_OR) - if (countUsed === countOr + 1) code = code.replace(ERROR_KEYWORD_OR, "") - } - - function occurrences(regexp) { - return (code.match(regexp) || []).length - } -}) diff --git a/spec/custom.spec.js b/spec/custom.spec.js index 85926109a..18bf89e40 100644 --- a/spec/custom.spec.js +++ b/spec/custom.spec.js @@ -2,8 +2,7 @@ var getAjvInstances = require("./ajv_instances"), should = require("./chai").should(), - equal = require("../dist/compile/equal"), - customRules = require("./custom_rules") + equal = require("../dist/compile/equal") describe("Custom keywords", () => { var ajv, instances @@ -498,7 +497,7 @@ describe("Custom keywords", () => { } }) - // TODO replace with custom "code" keyword + // TODO replace with custom "code" keywords describe.skip("inline rules", () => { it('should add and validate rule with "inline" code keyword', () => { testEvenKeyword({type: "number", inline: inlineEven}) @@ -509,51 +508,47 @@ describe("Custom keywords", () => { }) it('should define "inline" keyword as template', () => { - var inlineRangeTemplate = customRules.range - - testRangeKeyword({ - type: "number", - inline: inlineRangeTemplate, - statements: true, - }) + // var inlineRangeTemplate = customRules.range + // testRangeKeyword({ + // type: "number", + // inline: inlineRangeTemplate, + // statements: true, + // }) }) it('should define "inline" keyword without errors', () => { - var inlineRangeTemplate = customRules.range - - testRangeKeyword({ - type: "number", - inline: inlineRangeTemplate, - statements: true, - errors: false, - }) + // var inlineRangeTemplate = customRules.range + // testRangeKeyword({ + // type: "number", + // inline: inlineRangeTemplate, + // statements: true, + // errors: false, + // }) }) it("should allow defining optional errors", () => { - var inlineRangeTemplate = customRules.rangeWithErrors - - testRangeKeyword( - { - type: "number", - inline: inlineRangeTemplate, - statements: true, - }, - true - ) + // var inlineRangeTemplate = customRules.rangeWithErrors + // testRangeKeyword( + // { + // type: "number", + // inline: inlineRangeTemplate, + // statements: true, + // }, + // true + // ) }) it("should allow defining required errors", () => { - var inlineRangeTemplate = customRules.rangeWithErrors - - testRangeKeyword( - { - type: "number", - inline: inlineRangeTemplate, - statements: true, - errors: true, - }, - true - ) + // var inlineRangeTemplate = customRules.rangeWithErrors + // testRangeKeyword( + // { + // type: "number", + // inline: inlineRangeTemplate, + // statements: true, + // errors: true, + // }, + // true + // ) }) function inlineEven(it, keyword, schema) { diff --git a/spec/custom_rules/index.js b/spec/custom_rules/index.js deleted file mode 100644 index 9dedfbdff..000000000 --- a/spec/custom_rules/index.js +++ /dev/null @@ -1,14 +0,0 @@ -"use strict" - -var fs = require("fs"), - path = require("path"), - doT = require("dot") - -module.exports = { - range: doT.compile( - fs.readFileSync(path.join(__dirname, "range.jst"), "utf8") - ), - rangeWithErrors: doT.compile( - fs.readFileSync(path.join(__dirname, "range_with_errors.jst"), "utf8") - ), -} diff --git a/spec/custom_rules/range.jst b/spec/custom_rules/range.jst deleted file mode 100644 index adb481e01..000000000 --- a/spec/custom_rules/range.jst +++ /dev/null @@ -1,8 +0,0 @@ -{{ - var $data = 'data' + (it.dataLevel || '') - , $min = it.schema['x-range'][0] - , $max = it.schema['x-range'][1] - , $gt = it.schema.exclusiveRange ? '>' : '>=' - , $lt = it.schema.exclusiveRange ? '<' : '<='; -}} -var valid{{=it.level}} = {{=$data}} {{=$gt}} {{=$min}} && {{=$data}} {{=$lt}} {{=$max}}; diff --git a/spec/custom_rules/range_with_errors.jst b/spec/custom_rules/range_with_errors.jst deleted file mode 100644 index 6bfb6e571..000000000 --- a/spec/custom_rules/range_with_errors.jst +++ /dev/null @@ -1,42 +0,0 @@ -{{ - var $data = 'data' + (it.dataLevel || '') - , $min = it.schema['x-range'][0] - , $max = it.schema['x-range'][1] - , $exclusive = !!it.schema.exclusiveRange - , $gt = $exclusive ? '>' : '>=' - , $lt = $exclusive ? '<' : '<=' - , $lvl = it.level - , $err = 'err' + $lvl; -}} - -var minOk{{=$lvl}} = {{=$data}} {{=$gt}} {{=$min}}; -var valid{{=$lvl}} = minOk{{=$lvl}} && {{=$data}} {{=$lt}} {{=$max}}; - -if (!valid{{=$lvl}}) { - var {{=$err}}; - if (minOk{{=$lvl}}) { - {{=$err}} = { - keyword: 'x-range', - message: 'should be {{=$lt}} {{=$max}}', - params: { - comparison: '{{=$lt}}', - limit: {{=$max}}, - exclusive: {{=$exclusive}} - } - }; - } else { - {{=$err}} = { - keyword: 'x-range', - message: 'should be {{=$gt}} {{=$min}}', - params: { - comparison: '{{=$gt}}', - limit: {{=$min}}, - exclusive: {{=$exclusive}} - } - }; - } - - errors++; - if (vErrors) vErrors[vErrors.length] = {{=$err}}; - else vErrors = [{{=$err}}]; -}