errors.js 11 KB

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