errors.js 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372
  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. const localizedKey = Hoek.reach(localized, 'key');
  85. if (typeof localizedKey === 'string') {
  86. format = localizedKey + format;
  87. }
  88. else {
  89. format = Hoek.reach(Language.errors, 'key') + format;
  90. }
  91. }
  92. const message = format.replace(/{{(!?)([^}]+)}}/g, ($0, isSecure, name) => {
  93. const value = Hoek.reach(this.context, name);
  94. const normalized = internals.stringify(value, wrapArrays);
  95. return (isSecure && this.options.escapeHtml ? Hoek.escapeHtml(normalized) : normalized);
  96. });
  97. this.toString = () => message; // Persist result of last toString call, it won't change
  98. return message;
  99. }
  100. };
  101. exports.create = function (type, context, state, options, flags, message, template) {
  102. return new exports.Err(type, context, state, options, flags, message, template);
  103. };
  104. exports.process = function (errors, object) {
  105. if (!errors) {
  106. return null;
  107. }
  108. // Construct error
  109. let message = '';
  110. const details = [];
  111. const processErrors = function (localErrors, parent, overrideMessage) {
  112. for (let i = 0; i < localErrors.length; ++i) {
  113. const item = localErrors[i];
  114. if (item instanceof Error) {
  115. return item;
  116. }
  117. if (item.flags.error && typeof item.flags.error !== 'function') {
  118. if (!item.flags.selfError || !item.context.reason) {
  119. return item.flags.error;
  120. }
  121. }
  122. let itemMessage;
  123. if (parent === undefined) {
  124. itemMessage = item.toString();
  125. message = message + (message ? '. ' : '') + itemMessage;
  126. }
  127. // Do not push intermediate errors, we're only interested in leafs
  128. if (item.context.reason) {
  129. const override = processErrors(item.context.reason, item.path, item.type === 'override' ? item.message : null);
  130. if (override) {
  131. return override;
  132. }
  133. }
  134. else {
  135. details.push({
  136. message: overrideMessage || itemMessage || item.toString(),
  137. path: item.path,
  138. type: item.type,
  139. context: item.context
  140. });
  141. }
  142. }
  143. };
  144. const override = processErrors(errors);
  145. if (override) {
  146. return override;
  147. }
  148. const error = new Error(message);
  149. error.isJoi = true;
  150. error.name = 'ValidationError';
  151. error.details = details;
  152. error._object = object;
  153. error.annotate = internals.annotate;
  154. return error;
  155. };
  156. // Inspired by json-stringify-safe
  157. internals.safeStringify = function (obj, spaces) {
  158. return JSON.stringify(obj, internals.serializer(), spaces);
  159. };
  160. internals.serializer = function () {
  161. const keys = [];
  162. const stack = [];
  163. const cycleReplacer = (key, value) => {
  164. if (stack[0] === value) {
  165. return '[Circular ~]';
  166. }
  167. return '[Circular ~.' + keys.slice(0, stack.indexOf(value)).join('.') + ']';
  168. };
  169. return function (key, value) {
  170. if (stack.length > 0) {
  171. const thisPos = stack.indexOf(this);
  172. if (~thisPos) {
  173. stack.length = thisPos + 1;
  174. keys.length = thisPos + 1;
  175. keys[thisPos] = key;
  176. }
  177. else {
  178. stack.push(this);
  179. keys.push(key);
  180. }
  181. if (~stack.indexOf(value)) {
  182. value = cycleReplacer.call(this, key, value);
  183. }
  184. }
  185. else {
  186. stack.push(value);
  187. }
  188. if (value) {
  189. const annotations = value[internals.annotations];
  190. if (annotations) {
  191. if (Array.isArray(value)) {
  192. const annotated = [];
  193. for (let i = 0; i < value.length; ++i) {
  194. if (annotations.errors[i]) {
  195. annotated.push(`_$idx$_${annotations.errors[i].sort().join(', ')}_$end$_`);
  196. }
  197. annotated.push(value[i]);
  198. }
  199. value = annotated;
  200. }
  201. else {
  202. const errorKeys = Object.keys(annotations.errors);
  203. for (let i = 0; i < errorKeys.length; ++i) {
  204. const errorKey = errorKeys[i];
  205. value[`${errorKey}_$key$_${annotations.errors[errorKey].sort().join(', ')}_$end$_`] = value[errorKey];
  206. value[errorKey] = undefined;
  207. }
  208. const missingKeys = Object.keys(annotations.missing);
  209. for (let i = 0; i < missingKeys.length; ++i) {
  210. const missingKey = missingKeys[i];
  211. value[`_$miss$_${missingKey}|${annotations.missing[missingKey]}_$end$_`] = '__missing__';
  212. }
  213. }
  214. return value;
  215. }
  216. }
  217. if (value === Infinity || value === -Infinity || Number.isNaN(value) ||
  218. typeof value === 'function' || typeof value === 'symbol') {
  219. return '[' + value.toString() + ']';
  220. }
  221. return value;
  222. };
  223. };
  224. internals.annotate = function (stripColorCodes) {
  225. const redFgEscape = stripColorCodes ? '' : '\u001b[31m';
  226. const redBgEscape = stripColorCodes ? '' : '\u001b[41m';
  227. const endColor = stripColorCodes ? '' : '\u001b[0m';
  228. if (typeof this._object !== 'object') {
  229. return this.details[0].message;
  230. }
  231. const obj = Hoek.clone(this._object || {});
  232. for (let i = this.details.length - 1; i >= 0; --i) { // Reverse order to process deepest child first
  233. const pos = i + 1;
  234. const error = this.details[i];
  235. const path = error.path;
  236. let ref = obj;
  237. for (let j = 0; ; ++j) {
  238. const seg = path[j];
  239. if (ref.isImmutable) {
  240. ref = ref.clone(); // joi schemas are not cloned by hoek, we have to take this extra step
  241. }
  242. if (j + 1 < path.length &&
  243. ref[seg] &&
  244. typeof ref[seg] !== 'string') {
  245. ref = ref[seg];
  246. }
  247. else {
  248. const refAnnotations = ref[internals.annotations] = ref[internals.annotations] || { errors: {}, missing: {} };
  249. const value = ref[seg];
  250. const cacheKey = seg || error.context.label;
  251. if (value !== undefined) {
  252. refAnnotations.errors[cacheKey] = refAnnotations.errors[cacheKey] || [];
  253. refAnnotations.errors[cacheKey].push(pos);
  254. }
  255. else {
  256. refAnnotations.missing[cacheKey] = pos;
  257. }
  258. break;
  259. }
  260. }
  261. }
  262. const replacers = {
  263. key: /_\$key\$_([, \d]+)_\$end\$_"/g,
  264. missing: /"_\$miss\$_([^|]+)\|(\d+)_\$end\$_": "__missing__"/g,
  265. arrayIndex: /\s*"_\$idx\$_([, \d]+)_\$end\$_",?\n(.*)/g,
  266. specials: /"\[(NaN|Symbol.*|-?Infinity|function.*|\(.*)]"/g
  267. };
  268. let message = internals.safeStringify(obj, 2)
  269. .replace(replacers.key, ($0, $1) => `" ${redFgEscape}[${$1}]${endColor}`)
  270. .replace(replacers.missing, ($0, $1, $2) => `${redBgEscape}"${$1}"${endColor}${redFgEscape} [${$2}]: -- missing --${endColor}`)
  271. .replace(replacers.arrayIndex, ($0, $1, $2) => `\n${$2} ${redFgEscape}[${$1}]${endColor}`)
  272. .replace(replacers.specials, ($0, $1) => $1);
  273. message = `${message}\n${redFgEscape}`;
  274. for (let i = 0; i < this.details.length; ++i) {
  275. const pos = i + 1;
  276. message = `${message}\n[${pos}] ${this.details[i].message}`;
  277. }
  278. message = message + endColor;
  279. return message;
  280. };