util.js 7.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257
  1. 'use strict';
  2. module.exports = {
  3. copy: copy,
  4. checkDataType: checkDataType,
  5. checkDataTypes: checkDataTypes,
  6. coerceToTypes: coerceToTypes,
  7. toHash: toHash,
  8. getProperty: getProperty,
  9. escapeQuotes: escapeQuotes,
  10. ucs2length: require('./ucs2length'),
  11. varOccurences: varOccurences,
  12. varReplace: varReplace,
  13. cleanUpCode: cleanUpCode,
  14. cleanUpVarErrors: cleanUpVarErrors,
  15. schemaHasRules: schemaHasRules,
  16. schemaHasRulesExcept: schemaHasRulesExcept,
  17. stableStringify: require('json-stable-stringify'),
  18. toQuotedString: toQuotedString,
  19. getPathExpr: getPathExpr,
  20. getPath: getPath,
  21. getData: getData,
  22. unescapeFragment: unescapeFragment,
  23. escapeFragment: escapeFragment,
  24. escapeJsonPointer: escapeJsonPointer
  25. };
  26. function copy(o, to) {
  27. to = to || {};
  28. for (var key in o) to[key] = o[key];
  29. return to;
  30. }
  31. function checkDataType(dataType, data, negate) {
  32. var EQUAL = negate ? ' !== ' : ' === '
  33. , AND = negate ? ' || ' : ' && '
  34. , OK = negate ? '!' : ''
  35. , NOT = negate ? '' : '!';
  36. switch (dataType) {
  37. case 'null': return data + EQUAL + 'null';
  38. case 'array': return OK + 'Array.isArray(' + data + ')';
  39. case 'object': return '(' + OK + data + AND +
  40. 'typeof ' + data + EQUAL + '"object"' + AND +
  41. NOT + 'Array.isArray(' + data + '))';
  42. case 'integer': return '(typeof ' + data + EQUAL + '"number"' + AND +
  43. NOT + '(' + data + ' % 1)' +
  44. AND + data + EQUAL + data + ')';
  45. default: return 'typeof ' + data + EQUAL + '"' + dataType + '"';
  46. }
  47. }
  48. function checkDataTypes(dataTypes, data) {
  49. switch (dataTypes.length) {
  50. case 1: return checkDataType(dataTypes[0], data, true);
  51. default:
  52. var code = '';
  53. var types = toHash(dataTypes);
  54. if (types.array && types.object) {
  55. code = types.null ? '(': '(!' + data + ' || ';
  56. code += 'typeof ' + data + ' !== "object")';
  57. delete types.null;
  58. delete types.array;
  59. delete types.object;
  60. }
  61. if (types.number) delete types.integer;
  62. for (var t in types)
  63. code += (code ? ' && ' : '' ) + checkDataType(t, data, true);
  64. return code;
  65. }
  66. }
  67. var COERCE_TO_TYPES = toHash([ 'string', 'number', 'integer', 'boolean', 'null' ]);
  68. function coerceToTypes(optionCoerceTypes, dataTypes) {
  69. if (Array.isArray(dataTypes)) {
  70. var types = [];
  71. for (var i=0; i<dataTypes.length; i++) {
  72. var t = dataTypes[i];
  73. if (COERCE_TO_TYPES[t]) types[types.length] = t;
  74. else if (optionCoerceTypes === 'array' && t === 'array') types[types.length] = t;
  75. }
  76. if (types.length) return types;
  77. } else if (COERCE_TO_TYPES[dataTypes]) {
  78. return [dataTypes];
  79. } else if (optionCoerceTypes === 'array' && dataTypes === 'array') {
  80. return ['array'];
  81. }
  82. }
  83. function toHash(arr) {
  84. var hash = {};
  85. for (var i=0; i<arr.length; i++) hash[arr[i]] = true;
  86. return hash;
  87. }
  88. var IDENTIFIER = /^[a-z$_][a-z$_0-9]*$/i;
  89. var SINGLE_QUOTE = /'|\\/g;
  90. function getProperty(key) {
  91. return typeof key == 'number'
  92. ? '[' + key + ']'
  93. : IDENTIFIER.test(key)
  94. ? '.' + key
  95. : "['" + escapeQuotes(key) + "']";
  96. }
  97. function escapeQuotes(str) {
  98. return str.replace(SINGLE_QUOTE, '\\$&')
  99. .replace(/\n/g, '\\n')
  100. .replace(/\r/g, '\\r')
  101. .replace(/\f/g, '\\f')
  102. .replace(/\t/g, '\\t');
  103. }
  104. function varOccurences(str, dataVar) {
  105. dataVar += '[^0-9]';
  106. var matches = str.match(new RegExp(dataVar, 'g'));
  107. return matches ? matches.length : 0;
  108. }
  109. function varReplace(str, dataVar, expr) {
  110. dataVar += '([^0-9])';
  111. expr = expr.replace(/\$/g, '$$$$');
  112. return str.replace(new RegExp(dataVar, 'g'), expr + '$1');
  113. }
  114. var EMPTY_ELSE = /else\s*{\s*}/g
  115. , EMPTY_IF_NO_ELSE = /if\s*\([^)]+\)\s*\{\s*\}(?!\s*else)/g
  116. , EMPTY_IF_WITH_ELSE = /if\s*\(([^)]+)\)\s*\{\s*\}\s*else(?!\s*if)/g;
  117. function cleanUpCode(out) {
  118. return out.replace(EMPTY_ELSE, '')
  119. .replace(EMPTY_IF_NO_ELSE, '')
  120. .replace(EMPTY_IF_WITH_ELSE, 'if (!($1))');
  121. }
  122. var ERRORS_REGEXP = /[^v\.]errors/g
  123. , REMOVE_ERRORS = /var errors = 0;|var vErrors = null;|validate.errors = vErrors;/g
  124. , REMOVE_ERRORS_ASYNC = /var errors = 0;|var vErrors = null;/g
  125. , RETURN_VALID = 'return errors === 0;'
  126. , RETURN_TRUE = 'validate.errors = null; return true;'
  127. , RETURN_ASYNC = /if \(errors === 0\) return true;\s*else throw new ValidationError\(vErrors\);/
  128. , RETURN_TRUE_ASYNC = 'return true;';
  129. function cleanUpVarErrors(out, async) {
  130. var matches = out.match(ERRORS_REGEXP);
  131. if (!matches || matches.length !== 2) return out;
  132. return async
  133. ? out.replace(REMOVE_ERRORS_ASYNC, '')
  134. .replace(RETURN_ASYNC, RETURN_TRUE_ASYNC)
  135. : out.replace(REMOVE_ERRORS, '')
  136. .replace(RETURN_VALID, RETURN_TRUE);
  137. }
  138. function schemaHasRules(schema, rules) {
  139. for (var key in schema) if (rules[key]) return true;
  140. }
  141. function schemaHasRulesExcept(schema, rules, exceptKeyword) {
  142. for (var key in schema) if (key != exceptKeyword && rules[key]) return true;
  143. }
  144. function toQuotedString(str) {
  145. return '\'' + escapeQuotes(str) + '\'';
  146. }
  147. function getPathExpr(currentPath, expr, jsonPointers, isNumber) {
  148. var path = jsonPointers // false by default
  149. ? '\'/\' + ' + expr + (isNumber ? '' : '.replace(/~/g, \'~0\').replace(/\\//g, \'~1\')')
  150. : (isNumber ? '\'[\' + ' + expr + ' + \']\'' : '\'[\\\'\' + ' + expr + ' + \'\\\']\'');
  151. return joinPaths(currentPath, path);
  152. }
  153. function getPath(currentPath, prop, jsonPointers) {
  154. var path = jsonPointers // false by default
  155. ? toQuotedString('/' + escapeJsonPointer(prop))
  156. : toQuotedString(getProperty(prop));
  157. return joinPaths(currentPath, path);
  158. }
  159. var JSON_POINTER = /^\/(?:[^~]|~0|~1)*$/;
  160. var RELATIVE_JSON_POINTER = /^([0-9]+)(#|\/(?:[^~]|~0|~1)*)?$/;
  161. function getData($data, lvl, paths) {
  162. var up, jsonPointer, data, matches;
  163. if ($data === '') return 'rootData';
  164. if ($data[0] == '/') {
  165. if (!JSON_POINTER.test($data)) throw new Error('Invalid JSON-pointer: ' + $data);
  166. jsonPointer = $data;
  167. data = 'rootData';
  168. } else {
  169. matches = $data.match(RELATIVE_JSON_POINTER);
  170. if (!matches) throw new Error('Invalid JSON-pointer: ' + $data);
  171. up = +matches[1];
  172. jsonPointer = matches[2];
  173. if (jsonPointer == '#') {
  174. if (up >= lvl) throw new Error('Cannot access property/index ' + up + ' levels up, current level is ' + lvl);
  175. return paths[lvl - up];
  176. }
  177. if (up > lvl) throw new Error('Cannot access data ' + up + ' levels up, current level is ' + lvl);
  178. data = 'data' + ((lvl - up) || '');
  179. if (!jsonPointer) return data;
  180. }
  181. var expr = data;
  182. var segments = jsonPointer.split('/');
  183. for (var i=0; i<segments.length; i++) {
  184. var segment = segments[i];
  185. if (segment) {
  186. data += getProperty(unescapeJsonPointer(segment));
  187. expr += ' && ' + data;
  188. }
  189. }
  190. return expr;
  191. }
  192. function joinPaths (a, b) {
  193. if (a == '""') return b;
  194. return (a + ' + ' + b).replace(/' \+ '/g, '');
  195. }
  196. function unescapeFragment(str) {
  197. return unescapeJsonPointer(decodeURIComponent(str));
  198. }
  199. function escapeFragment(str) {
  200. return encodeURIComponent(escapeJsonPointer(str));
  201. }
  202. function escapeJsonPointer(str) {
  203. return str.replace(/~/g, '~0').replace(/\//g, '~1');
  204. }
  205. function unescapeJsonPointer(str) {
  206. return str.replace(/~1/g, '/').replace(/~0/g, '~');
  207. }