Вы не можете выбрать более 25 тем Темы должны начинаться с буквы или цифры, могут содержать дефисы(-) и должны содержать не более 35 символов.

3 лет назад
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357
  1. 'use strict';
  2. // Load modules
  3. const Hoek = require('hoek');
  4. const Language = require('./language');
  5. // Declare internals
  6. const internals = {
  7. annotations: Symbol('joi-annotations')
  8. };
  9. internals.stringify = function (value, wrapArrays) {
  10. const type = typeof value;
  11. if (value === null) {
  12. return 'null';
  13. }
  14. if (type === 'string') {
  15. return value;
  16. }
  17. if (value instanceof exports.Err || type === 'function' || type === 'symbol') {
  18. return value.toString();
  19. }
  20. if (type === 'object') {
  21. if (Array.isArray(value)) {
  22. let partial = '';
  23. for (let i = 0; i < value.length; ++i) {
  24. partial = partial + (partial.length ? ', ' : '') + internals.stringify(value[i], wrapArrays);
  25. }
  26. return wrapArrays ? '[' + partial + ']' : partial;
  27. }
  28. return value.toString();
  29. }
  30. return JSON.stringify(value);
  31. };
  32. exports.Err = class {
  33. constructor(type, context, state, options, flags, message, template) {
  34. this.isJoi = true;
  35. this.type = type;
  36. this.context = context || {};
  37. this.context.key = state.path[state.path.length - 1];
  38. this.context.label = state.key;
  39. this.path = state.path;
  40. this.options = options;
  41. this.flags = flags;
  42. this.message = message;
  43. this.template = template;
  44. const localized = this.options.language;
  45. if (this.flags.label) {
  46. this.context.label = this.flags.label;
  47. }
  48. else if (localized && // language can be null for arrays exclusion check
  49. (this.context.label === '' ||
  50. this.context.label === null)) {
  51. this.context.label = localized.root || Language.errors.root;
  52. }
  53. }
  54. toString() {
  55. if (this.message) {
  56. return this.message;
  57. }
  58. let format;
  59. if (this.template) {
  60. format = this.template;
  61. }
  62. const localized = this.options.language;
  63. format = format || Hoek.reach(localized, this.type) || Hoek.reach(Language.errors, this.type);
  64. if (format === undefined) {
  65. return `Error code "${this.type}" is not defined, your custom type is missing the correct language definition`;
  66. }
  67. let wrapArrays = Hoek.reach(localized, 'messages.wrapArrays');
  68. if (typeof wrapArrays !== 'boolean') {
  69. wrapArrays = Language.errors.messages.wrapArrays;
  70. }
  71. if (format === null) {
  72. const childrenString = internals.stringify(this.context.reason, wrapArrays);
  73. if (wrapArrays) {
  74. return childrenString.slice(1, -1);
  75. }
  76. return childrenString;
  77. }
  78. const hasKey = /\{\{\!?label\}\}/.test(format);
  79. const skipKey = format.length > 2 && format[0] === '!' && format[1] === '!';
  80. if (skipKey) {
  81. format = format.slice(2);
  82. }
  83. if (!hasKey && !skipKey) {
  84. format = (Hoek.reach(localized, 'key') || Hoek.reach(Language.errors, 'key')) + format;
  85. }
  86. return format.replace(/\{\{(\!?)([^}]+)\}\}/g, ($0, isSecure, name) => {
  87. const value = Hoek.reach(this.context, name);
  88. const normalized = internals.stringify(value, wrapArrays);
  89. return (isSecure ? Hoek.escapeHtml(normalized) : normalized);
  90. });
  91. }
  92. };
  93. exports.create = function (type, context, state, options, flags, message, template) {
  94. return new exports.Err(type, context, state, options, flags, message, template);
  95. };
  96. exports.process = function (errors, object) {
  97. if (!errors || !errors.length) {
  98. return null;
  99. }
  100. // Construct error
  101. let message = '';
  102. const details = [];
  103. const processErrors = function (localErrors, parent) {
  104. for (let i = 0; i < localErrors.length; ++i) {
  105. const item = localErrors[i];
  106. if (item instanceof Error) {
  107. return item;
  108. }
  109. if (item.flags.error && typeof item.flags.error !== 'function') {
  110. return item.flags.error;
  111. }
  112. let itemMessage;
  113. if (parent === undefined) {
  114. itemMessage = item.toString();
  115. message = message + (message ? '. ' : '') + itemMessage;
  116. }
  117. // Do not push intermediate errors, we're only interested in leafs
  118. if (item.context.reason && item.context.reason.length) {
  119. const override = processErrors(item.context.reason, item.path);
  120. if (override) {
  121. return override;
  122. }
  123. }
  124. else {
  125. details.push({
  126. message: itemMessage || item.toString(),
  127. path: item.path,
  128. type: item.type,
  129. context: item.context
  130. });
  131. }
  132. }
  133. };
  134. const override = processErrors(errors);
  135. if (override) {
  136. return override;
  137. }
  138. const error = new Error(message);
  139. error.isJoi = true;
  140. error.name = 'ValidationError';
  141. error.details = details;
  142. error._object = object;
  143. error.annotate = internals.annotate;
  144. return error;
  145. };
  146. // Inspired by json-stringify-safe
  147. internals.safeStringify = function (obj, spaces) {
  148. return JSON.stringify(obj, internals.serializer(), spaces);
  149. };
  150. internals.serializer = function () {
  151. const keys = [];
  152. const stack = [];
  153. const cycleReplacer = (key, value) => {
  154. if (stack[0] === value) {
  155. return '[Circular ~]';
  156. }
  157. return '[Circular ~.' + keys.slice(0, stack.indexOf(value)).join('.') + ']';
  158. };
  159. return function (key, value) {
  160. if (stack.length > 0) {
  161. const thisPos = stack.indexOf(this);
  162. if (~thisPos) {
  163. stack.length = thisPos + 1;
  164. keys.length = thisPos + 1;
  165. keys[thisPos] = key;
  166. }
  167. else {
  168. stack.push(this);
  169. keys.push(key);
  170. }
  171. if (~stack.indexOf(value)) {
  172. value = cycleReplacer.call(this, key, value);
  173. }
  174. }
  175. else {
  176. stack.push(value);
  177. }
  178. if (value) {
  179. const annotations = value[internals.annotations];
  180. if (annotations) {
  181. if (Array.isArray(value)) {
  182. const annotated = [];
  183. for (let i = 0; i < value.length; ++i) {
  184. if (annotations.errors[i]) {
  185. annotated.push(`_$idx$_${annotations.errors[i].sort().join(', ')}_$end$_`);
  186. }
  187. annotated.push(value[i]);
  188. }
  189. value = annotated;
  190. }
  191. else {
  192. const errorKeys = Object.keys(annotations.errors);
  193. for (let i = 0; i < errorKeys.length; ++i) {
  194. const errorKey = errorKeys[i];
  195. value[`${errorKey}_$key$_${annotations.errors[errorKey].sort().join(', ')}_$end$_`] = value[errorKey];
  196. value[errorKey] = undefined;
  197. }
  198. const missingKeys = Object.keys(annotations.missing);
  199. for (let i = 0; i < missingKeys.length; ++i) {
  200. const missingKey = missingKeys[i];
  201. value[`_$miss$_${missingKey}|${annotations.missing[missingKey]}_$end$_`] = '__missing__';
  202. }
  203. }
  204. return value;
  205. }
  206. }
  207. if (value === Infinity || value === -Infinity || Number.isNaN(value) ||
  208. typeof value === 'function' || typeof value === 'symbol') {
  209. return '[' + value.toString() + ']';
  210. }
  211. return value;
  212. };
  213. };
  214. internals.annotate = function (stripColorCodes) {
  215. const redFgEscape = stripColorCodes ? '' : '\u001b[31m';
  216. const redBgEscape = stripColorCodes ? '' : '\u001b[41m';
  217. const endColor = stripColorCodes ? '' : '\u001b[0m';
  218. if (typeof this._object !== 'object') {
  219. return this.details[0].message;
  220. }
  221. const obj = Hoek.clone(this._object || {});
  222. for (let i = this.details.length - 1; i >= 0; --i) { // Reverse order to process deepest child first
  223. const pos = i + 1;
  224. const error = this.details[i];
  225. const path = error.path;
  226. let ref = obj;
  227. for (let j = 0; ; ++j) {
  228. const seg = path[j];
  229. if (ref.isImmutable) {
  230. ref = ref.clone(); // joi schemas are not cloned by hoek, we have to take this extra step
  231. }
  232. if (j + 1 < path.length &&
  233. ref[seg] &&
  234. typeof ref[seg] !== 'string') {
  235. ref = ref[seg];
  236. }
  237. else {
  238. const refAnnotations = ref[internals.annotations] = ref[internals.annotations] || { errors: {}, missing: {} };
  239. const value = ref[seg];
  240. const cacheKey = seg || error.context.label;
  241. if (value !== undefined) {
  242. refAnnotations.errors[cacheKey] = refAnnotations.errors[cacheKey] || [];
  243. refAnnotations.errors[cacheKey].push(pos);
  244. }
  245. else {
  246. refAnnotations.missing[cacheKey] = pos;
  247. }
  248. break;
  249. }
  250. }
  251. }
  252. const replacers = {
  253. key: /_\$key\$_([, \d]+)_\$end\$_\"/g,
  254. missing: /\"_\$miss\$_([^\|]+)\|(\d+)_\$end\$_\"\: \"__missing__\"/g,
  255. arrayIndex: /\s*\"_\$idx\$_([, \d]+)_\$end\$_\",?\n(.*)/g,
  256. specials: /"\[(NaN|Symbol.*|-?Infinity|function.*|\(.*)\]"/g
  257. };
  258. let message = internals.safeStringify(obj, 2)
  259. .replace(replacers.key, ($0, $1) => `" ${redFgEscape}[${$1}]${endColor}`)
  260. .replace(replacers.missing, ($0, $1, $2) => `${redBgEscape}"${$1}"${endColor}${redFgEscape} [${$2}]: -- missing --${endColor}`)
  261. .replace(replacers.arrayIndex, ($0, $1, $2) => `\n${$2} ${redFgEscape}[${$1}]${endColor}`)
  262. .replace(replacers.specials, ($0, $1) => $1);
  263. message = `${message}\n${redFgEscape}`;
  264. for (let i = 0; i < this.details.length; ++i) {
  265. const pos = i + 1;
  266. message = `${message}\n[${pos}] ${this.details[i].message}`;
  267. }
  268. message = message + endColor;
  269. return message;
  270. };