errors.js 9.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319
  1. 'use strict';
  2. // Load modules
  3. const Hoek = require('hoek');
  4. const Language = require('./language');
  5. // Declare internals
  6. const internals = {};
  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') {
  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) {
  32. this.isJoi = true;
  33. this.type = type;
  34. this.context = context || {};
  35. this.context.key = state.key;
  36. this.path = state.path;
  37. this.options = options;
  38. this.flags = flags;
  39. }
  40. toString() {
  41. const localized = this.options.language;
  42. if (this.flags.label) {
  43. this.context.key = this.flags.label;
  44. }
  45. else if (this.context.key === '' || this.context.key === null) {
  46. this.context.key = localized.root || Language.errors.root;
  47. }
  48. let format = Hoek.reach(localized, this.type) || Hoek.reach(Language.errors, this.type);
  49. const hasKey = /\{\{\!?key\}\}/.test(format);
  50. const skipKey = format.length > 2 && format[0] === '!' && format[1] === '!';
  51. if (skipKey) {
  52. format = format.slice(2);
  53. }
  54. if (!hasKey && !skipKey) {
  55. format = (Hoek.reach(localized, 'key') || Hoek.reach(Language.errors, 'key')) + format;
  56. }
  57. let wrapArrays = Hoek.reach(localized, 'messages.wrapArrays');
  58. if (typeof wrapArrays !== 'boolean') {
  59. wrapArrays = Language.errors.messages.wrapArrays;
  60. }
  61. return format.replace(/\{\{(\!?)([^}]+)\}\}/g, ($0, isSecure, name) => {
  62. const value = Hoek.reach(this.context, name);
  63. const normalized = internals.stringify(value, wrapArrays);
  64. return (isSecure ? Hoek.escapeHtml(normalized) : normalized);
  65. });
  66. }
  67. };
  68. exports.create = function (type, context, state, options, flags) {
  69. return new exports.Err(type, context, state, options, flags);
  70. };
  71. exports.process = function (errors, object) {
  72. if (!errors || !errors.length) {
  73. return null;
  74. }
  75. // Construct error
  76. let message = '';
  77. const details = [];
  78. const processErrors = function (localErrors, parent) {
  79. for (let i = 0; i < localErrors.length; ++i) {
  80. const item = localErrors[i];
  81. if (item.flags.error) {
  82. return item.flags.error;
  83. }
  84. let itemMessage;
  85. if (parent === undefined) {
  86. itemMessage = item.toString();
  87. message = message + (message ? '. ' : '') + itemMessage;
  88. }
  89. // Do not push intermediate errors, we're only interested in leafs
  90. if (item.context.reason && item.context.reason.length) {
  91. const override = processErrors(item.context.reason, item.path);
  92. if (override) {
  93. return override;
  94. }
  95. }
  96. else {
  97. details.push({
  98. message: itemMessage || item.toString(),
  99. path: internals.getPath(item),
  100. type: item.type,
  101. context: item.context
  102. });
  103. }
  104. }
  105. };
  106. const override = processErrors(errors);
  107. if (override) {
  108. return override;
  109. }
  110. const error = new Error(message);
  111. error.isJoi = true;
  112. error.name = 'ValidationError';
  113. error.details = details;
  114. error._object = object;
  115. error.annotate = internals.annotate;
  116. return error;
  117. };
  118. internals.getPath = function (item) {
  119. return item.path || item.context.key;
  120. };
  121. // Inspired by json-stringify-safe
  122. internals.safeStringify = function (obj, spaces) {
  123. return JSON.stringify(obj, internals.serializer(), spaces);
  124. };
  125. internals.serializer = function () {
  126. const keys = [];
  127. const stack = [];
  128. const cycleReplacer = (key, value) => {
  129. if (stack[0] === value) {
  130. return '[Circular ~]';
  131. }
  132. return '[Circular ~.' + keys.slice(0, stack.indexOf(value)).join('.') + ']';
  133. };
  134. return function (key, value) {
  135. if (stack.length > 0) {
  136. const thisPos = stack.indexOf(this);
  137. if (~thisPos) {
  138. stack.length = thisPos + 1;
  139. keys.length = thisPos + 1;
  140. keys[thisPos] = key;
  141. }
  142. else {
  143. stack.push(this);
  144. keys.push(key);
  145. }
  146. if (~stack.indexOf(value)) {
  147. value = cycleReplacer.call(this, key, value);
  148. }
  149. }
  150. else {
  151. stack.push(value);
  152. }
  153. if (Array.isArray(value) && value.placeholders) {
  154. const placeholders = value.placeholders;
  155. const arrWithPlaceholders = [];
  156. for (let i = 0; i < value.length; ++i) {
  157. if (placeholders[i]) {
  158. arrWithPlaceholders.push(placeholders[i]);
  159. }
  160. arrWithPlaceholders.push(value[i]);
  161. }
  162. value = arrWithPlaceholders;
  163. }
  164. if (value === Infinity || value === -Infinity || Number.isNaN(value) ||
  165. typeof value === 'function' || typeof value === 'symbol') {
  166. return '[' + value.toString() + ']';
  167. }
  168. return value;
  169. };
  170. };
  171. internals.annotate = function (stripColorCodes) {
  172. const redFgEscape = stripColorCodes ? '' : '\u001b[31m';
  173. const redBgEscape = stripColorCodes ? '' : '\u001b[41m';
  174. const endColor = stripColorCodes ? '' : '\u001b[0m';
  175. if (typeof this._object !== 'object') {
  176. return this.details[0].message;
  177. }
  178. const obj = Hoek.clone(this._object || {});
  179. const lookup = {};
  180. for (let i = this.details.length - 1; i >= 0; --i) { // Reverse order to process deepest child first
  181. const pos = i + 1;
  182. const error = this.details[i];
  183. const path = error.path.split('.');
  184. let ref = obj;
  185. for (let j = 0; j < path.length && ref; ++j) {
  186. const seg = path[j];
  187. if (j + 1 < path.length) {
  188. ref = ref[seg];
  189. }
  190. else {
  191. const value = ref[seg];
  192. if (Array.isArray(ref)) {
  193. const arrayLabel = `_$idx$_${pos}_$end$_`;
  194. if (!ref.placeholders) {
  195. ref.placeholders = {};
  196. }
  197. if (ref.placeholders[seg]) {
  198. ref.placeholders[seg] = ref.placeholders[seg].replace('_$end$_', `, ${pos}_$end$_`);
  199. }
  200. else {
  201. ref.placeholders[seg] = arrayLabel;
  202. }
  203. }
  204. else {
  205. if (value !== undefined) {
  206. delete ref[seg];
  207. const objectLabel = `${seg}_$key$_${pos}_$end$_`;
  208. ref[objectLabel] = value;
  209. lookup[error.path] = objectLabel;
  210. }
  211. else if (lookup[error.path]) {
  212. const replacement = lookup[error.path];
  213. const appended = replacement.replace('_$end$_', `, ${pos}_$end$_`);
  214. ref[appended] = ref[replacement];
  215. lookup[error.path] = appended;
  216. delete ref[replacement];
  217. }
  218. else {
  219. ref[`_$miss$_${seg}|${pos}_$end$_`] = '__missing__';
  220. }
  221. }
  222. }
  223. }
  224. }
  225. const replacers = {
  226. key: /_\$key\$_([, \d]+)_\$end\$_\"/g,
  227. missing: /\"_\$miss\$_([^\|]+)\|(\d+)_\$end\$_\"\: \"__missing__\"/g,
  228. arrayIndex: /\s*\"_\$idx\$_([, \d]+)_\$end\$_\",?\n(.*)/g,
  229. specials: /"\[(NaN|Symbol.*|-?Infinity|function.*|\(.*)\]"/g
  230. };
  231. let message = internals.safeStringify(obj, 2)
  232. .replace(replacers.key, ($0, $1) => `" ${redFgEscape}[${$1}]${endColor}`)
  233. .replace(replacers.missing, ($0, $1, $2) => `${redBgEscape}"${$1}"${endColor}${redFgEscape} [${$2}]: -- missing --${endColor}`)
  234. .replace(replacers.arrayIndex, ($0, $1, $2) => `\n${$2} ${redFgEscape}[${$1}]${endColor}`)
  235. .replace(replacers.specials, ($0, $1) => $1);
  236. message = `${message}\n${redFgEscape}`;
  237. for (let i = 0; i < this.details.length; ++i) {
  238. const pos = i + 1;
  239. message = `${message}\n[${pos}] ${this.details[i].message}`;
  240. }
  241. message = message + endColor;
  242. return message;
  243. };