( error: ZodError, filePath: string, )
| 95 | } |
| 96 | |
| 97 | export function formatZodError( |
| 98 | error: ZodError, |
| 99 | filePath: string, |
| 100 | ): ValidationError[] { |
| 101 | return error.issues.map((issue): ValidationError => { |
| 102 | const path = issue.path.map(String).join('.') |
| 103 | let message = issue.message |
| 104 | let expected: string | undefined |
| 105 | |
| 106 | let enumValues: string[] | undefined |
| 107 | let expectedValue: string | undefined |
| 108 | let receivedValue: unknown |
| 109 | let invalidValue: unknown |
| 110 | |
| 111 | if (isInvalidValueIssue(issue)) { |
| 112 | enumValues = issue.values.map(v => String(v)) |
| 113 | expectedValue = enumValues.join(' | ') |
| 114 | receivedValue = undefined |
| 115 | invalidValue = undefined |
| 116 | } else if (isInvalidTypeIssue(issue)) { |
| 117 | expectedValue = issue.expected |
| 118 | const receivedType = extractReceivedFromMessage(issue.message) |
| 119 | receivedValue = receivedType ?? getReceivedType(issue.input) |
| 120 | invalidValue = receivedType ?? getReceivedType(issue.input) |
| 121 | } else if (isTooSmallIssue(issue)) { |
| 122 | expectedValue = String(issue.minimum) |
| 123 | } else if (issue.code === 'custom' && 'params' in issue) { |
| 124 | const params = issue.params as { received?: unknown } |
| 125 | receivedValue = params.received |
| 126 | invalidValue = receivedValue |
| 127 | } |
| 128 | |
| 129 | const tip = getValidationTip({ |
| 130 | path, |
| 131 | code: issue.code, |
| 132 | expected: expectedValue, |
| 133 | received: receivedValue, |
| 134 | enumValues, |
| 135 | message: issue.message, |
| 136 | value: receivedValue, |
| 137 | }) |
| 138 | |
| 139 | if (isInvalidValueIssue(issue)) { |
| 140 | expected = enumValues?.map(v => `"${v}"`).join(', ') |
| 141 | message = `Invalid value. Expected one of: ${expected}` |
| 142 | } else if (isInvalidTypeIssue(issue)) { |
| 143 | const receivedType = |
| 144 | extractReceivedFromMessage(issue.message) ?? |
| 145 | getReceivedType(issue.input) |
| 146 | if ( |
| 147 | issue.expected === 'object' && |
| 148 | receivedType === 'null' && |
| 149 | path === '' |
| 150 | ) { |
| 151 | message = 'Invalid or malformed JSON' |
| 152 | } else { |
| 153 | message = `Expected ${issue.expected}, but received ${receivedType}` |
| 154 | } |
no test coverage detected