Path: blob/master/node_modules/ajv/scripts/compile-dots.js
1126 views
//compile doT templates to js functions1'use strict';23var glob = require('glob')4, fs = require('fs')5, path = require('path')6, doT = require('dot')7, beautify = require('js-beautify').js_beautify;89var defsRootPath = process.argv[2] || path.join(__dirname, '../lib');1011var defs = {};12var defFiles = glob.sync('./dot/**/*.def', { cwd: defsRootPath });13defFiles.forEach(function (f) {14var name = path.basename(f, '.def');15defs[name] = fs.readFileSync(path.join(defsRootPath, f));16});1718var filesRootPath = process.argv[3] || path.join(__dirname, '../lib');19var files = glob.sync('./dot/**/*.jst', { cwd: filesRootPath });2021var dotjsPath = path.join(filesRootPath, './dotjs');22try { fs.mkdirSync(dotjsPath); } catch(e) {}2324console.log('\n\nCompiling:');2526var FUNCTION_NAME = /function\s+anonymous\s*\(it[^)]*\)\s*{/;27var OUT_EMPTY_STRING = /out\s*\+=\s*'\s*';/g;28var ISTANBUL = /'(istanbul[^']+)';/g;29var ERROR_KEYWORD = /\$errorKeyword/g;30var ERROR_KEYWORD_OR = /\$errorKeyword\s+\|\|/g;31var VARS = [32'$errs', '$valid', '$lvl', '$data', '$dataLvl',33'$errorKeyword', '$closingBraces', '$schemaPath',34'$validate'35];3637files.forEach(function (f) {38var keyword = path.basename(f, '.jst');39var targetPath = path.join(dotjsPath, keyword + '.js');40var template = fs.readFileSync(path.join(filesRootPath, f));41var code = doT.compile(template, defs);42code = code.toString()43.replace(OUT_EMPTY_STRING, '')44.replace(FUNCTION_NAME, 'function generate_' + keyword + '(it, $keyword, $ruleType) {')45.replace(ISTANBUL, '/* $1 */');46removeAlwaysFalsyInOr();47VARS.forEach(removeUnusedVar);48code = "'use strict';\nmodule.exports = " + code;49code = beautify(code, { indent_size: 2 }) + '\n';50fs.writeFileSync(targetPath, code);51console.log('compiled', keyword);5253function removeUnusedVar(v) {54v = v.replace(/\$/g, '\\$$');55var regexp = new RegExp(v + '[^A-Za-z0-9_$]', 'g');56var count = occurrences(regexp);57if (count == 1) {58regexp = new RegExp('var\\s+' + v + '\\s*=[^;]+;|var\\s+' + v + ';');59code = code.replace(regexp, '');60}61}6263function removeAlwaysFalsyInOr() {64var countUsed = occurrences(ERROR_KEYWORD);65var countOr = occurrences(ERROR_KEYWORD_OR);66if (countUsed == countOr + 1) code = code.replace(ERROR_KEYWORD_OR, '');67}6869function occurrences(regexp) {70return (code.match(regexp) || []).length;71}72});737475