errors.cjs 7.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213
  1. "use strict";
  2. var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
  3. if (k2 === undefined) k2 = k;
  4. var desc = Object.getOwnPropertyDescriptor(m, k);
  5. if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
  6. desc = { enumerable: true, get: function() { return m[k]; } };
  7. }
  8. Object.defineProperty(o, k2, desc);
  9. }) : (function(o, m, k, k2) {
  10. if (k2 === undefined) k2 = k;
  11. o[k2] = m[k];
  12. }));
  13. var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
  14. Object.defineProperty(o, "default", { enumerable: true, value: v });
  15. }) : function(o, v) {
  16. o["default"] = v;
  17. });
  18. var __importStar = (this && this.__importStar) || function (mod) {
  19. if (mod && mod.__esModule) return mod;
  20. var result = {};
  21. if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
  22. __setModuleDefault(result, mod);
  23. return result;
  24. };
  25. Object.defineProperty(exports, "__esModule", { value: true });
  26. exports.$ZodRealError = exports.$ZodError = void 0;
  27. exports.flattenError = flattenError;
  28. exports.formatError = formatError;
  29. exports.treeifyError = treeifyError;
  30. exports.toDotPath = toDotPath;
  31. exports.prettifyError = prettifyError;
  32. const core_js_1 = require("./core.cjs");
  33. const util = __importStar(require("./util.cjs"));
  34. const initializer = (inst, def) => {
  35. inst.name = "$ZodError";
  36. Object.defineProperty(inst, "_zod", {
  37. value: inst._zod,
  38. enumerable: false,
  39. });
  40. Object.defineProperty(inst, "issues", {
  41. value: def,
  42. enumerable: false,
  43. });
  44. inst.message = JSON.stringify(def, util.jsonStringifyReplacer, 2);
  45. Object.defineProperty(inst, "toString", {
  46. value: () => inst.message,
  47. enumerable: false,
  48. });
  49. };
  50. exports.$ZodError = (0, core_js_1.$constructor)("$ZodError", initializer);
  51. exports.$ZodRealError = (0, core_js_1.$constructor)("$ZodError", initializer, { Parent: Error });
  52. function flattenError(error, mapper = (issue) => issue.message) {
  53. const fieldErrors = {};
  54. const formErrors = [];
  55. for (const sub of error.issues) {
  56. if (sub.path.length > 0) {
  57. fieldErrors[sub.path[0]] = fieldErrors[sub.path[0]] || [];
  58. fieldErrors[sub.path[0]].push(mapper(sub));
  59. }
  60. else {
  61. formErrors.push(mapper(sub));
  62. }
  63. }
  64. return { formErrors, fieldErrors };
  65. }
  66. function formatError(error, mapper = (issue) => issue.message) {
  67. const fieldErrors = { _errors: [] };
  68. const processError = (error) => {
  69. for (const issue of error.issues) {
  70. if (issue.code === "invalid_union" && issue.errors.length) {
  71. issue.errors.map((issues) => processError({ issues }));
  72. }
  73. else if (issue.code === "invalid_key") {
  74. processError({ issues: issue.issues });
  75. }
  76. else if (issue.code === "invalid_element") {
  77. processError({ issues: issue.issues });
  78. }
  79. else if (issue.path.length === 0) {
  80. fieldErrors._errors.push(mapper(issue));
  81. }
  82. else {
  83. let curr = fieldErrors;
  84. let i = 0;
  85. while (i < issue.path.length) {
  86. const el = issue.path[i];
  87. const terminal = i === issue.path.length - 1;
  88. if (!terminal) {
  89. curr[el] = curr[el] || { _errors: [] };
  90. }
  91. else {
  92. curr[el] = curr[el] || { _errors: [] };
  93. curr[el]._errors.push(mapper(issue));
  94. }
  95. curr = curr[el];
  96. i++;
  97. }
  98. }
  99. }
  100. };
  101. processError(error);
  102. return fieldErrors;
  103. }
  104. function treeifyError(error, mapper = (issue) => issue.message) {
  105. const result = { errors: [] };
  106. const processError = (error, path = []) => {
  107. var _a, _b;
  108. for (const issue of error.issues) {
  109. if (issue.code === "invalid_union" && issue.errors.length) {
  110. // regular union error
  111. issue.errors.map((issues) => processError({ issues }, issue.path));
  112. }
  113. else if (issue.code === "invalid_key") {
  114. processError({ issues: issue.issues }, issue.path);
  115. }
  116. else if (issue.code === "invalid_element") {
  117. processError({ issues: issue.issues }, issue.path);
  118. }
  119. else {
  120. const fullpath = [...path, ...issue.path];
  121. if (fullpath.length === 0) {
  122. result.errors.push(mapper(issue));
  123. continue;
  124. }
  125. let curr = result;
  126. let i = 0;
  127. while (i < fullpath.length) {
  128. const el = fullpath[i];
  129. const terminal = i === fullpath.length - 1;
  130. if (typeof el === "string") {
  131. curr.properties ?? (curr.properties = {});
  132. (_a = curr.properties)[el] ?? (_a[el] = { errors: [] });
  133. curr = curr.properties[el];
  134. }
  135. else {
  136. curr.items ?? (curr.items = []);
  137. (_b = curr.items)[el] ?? (_b[el] = { errors: [] });
  138. curr = curr.items[el];
  139. }
  140. if (terminal) {
  141. curr.errors.push(mapper(issue));
  142. }
  143. i++;
  144. }
  145. }
  146. }
  147. };
  148. processError(error);
  149. return result;
  150. }
  151. /** Format a ZodError as a human-readable string in the following form.
  152. *
  153. * From
  154. *
  155. * ```ts
  156. * ZodError {
  157. * issues: [
  158. * {
  159. * expected: 'string',
  160. * code: 'invalid_type',
  161. * path: [ 'username' ],
  162. * message: 'Invalid input: expected string'
  163. * },
  164. * {
  165. * expected: 'number',
  166. * code: 'invalid_type',
  167. * path: [ 'favoriteNumbers', 1 ],
  168. * message: 'Invalid input: expected number'
  169. * }
  170. * ];
  171. * }
  172. * ```
  173. *
  174. * to
  175. *
  176. * ```
  177. * username
  178. * ✖ Expected number, received string at "username
  179. * favoriteNumbers[0]
  180. * ✖ Invalid input: expected number
  181. * ```
  182. */
  183. function toDotPath(_path) {
  184. const segs = [];
  185. const path = _path.map((seg) => (typeof seg === "object" ? seg.key : seg));
  186. for (const seg of path) {
  187. if (typeof seg === "number")
  188. segs.push(`[${seg}]`);
  189. else if (typeof seg === "symbol")
  190. segs.push(`[${JSON.stringify(String(seg))}]`);
  191. else if (/[^\w$]/.test(seg))
  192. segs.push(`[${JSON.stringify(seg)}]`);
  193. else {
  194. if (segs.length)
  195. segs.push(".");
  196. segs.push(seg);
  197. }
  198. }
  199. return segs.join("");
  200. }
  201. function prettifyError(error) {
  202. const lines = [];
  203. // sort by path length
  204. const issues = [...error.issues].sort((a, b) => (a.path ?? []).length - (b.path ?? []).length);
  205. // Process each issue
  206. for (const issue of issues) {
  207. lines.push(`✖ ${issue.message}`);
  208. if (issue.path?.length)
  209. lines.push(` → at ${toDotPath(issue.path)}`);
  210. }
  211. // Convert Map to formatted string
  212. return lines.join("\n");
  213. }