(schema: PrimitiveSchemaDefinition)
| 133 | } |
| 134 | |
| 135 | function getZodSchema(schema: PrimitiveSchemaDefinition): z.ZodTypeAny { |
| 136 | if (isEnumSchema(schema)) { |
| 137 | const [first, ...rest] = getEnumValues(schema) |
| 138 | if (!first) { |
| 139 | return z.never() |
| 140 | } |
| 141 | return z.enum([first, ...rest]) |
| 142 | } |
| 143 | if (schema.type === 'string') { |
| 144 | let stringSchema = z.string() |
| 145 | if (schema.minLength !== undefined) { |
| 146 | stringSchema = stringSchema.min(schema.minLength, { |
| 147 | message: `Must be at least ${schema.minLength} ${plural(schema.minLength, 'character')}`, |
| 148 | }) |
| 149 | } |
| 150 | if (schema.maxLength !== undefined) { |
| 151 | stringSchema = stringSchema.max(schema.maxLength, { |
| 152 | message: `Must be at most ${schema.maxLength} ${plural(schema.maxLength, 'character')}`, |
| 153 | }) |
| 154 | } |
| 155 | switch (schema.format) { |
| 156 | case 'email': |
| 157 | stringSchema = stringSchema.email({ |
| 158 | message: 'Must be a valid email address, e.g. user@example.com', |
| 159 | }) |
| 160 | break |
| 161 | case 'uri': |
| 162 | stringSchema = stringSchema.url({ |
| 163 | message: 'Must be a valid URI, e.g. https://example.com', |
| 164 | }) |
| 165 | break |
| 166 | case 'date': |
| 167 | stringSchema = stringSchema.date( |
| 168 | 'Must be a valid date, e.g. 2024-03-15, today, next Monday', |
| 169 | ) |
| 170 | break |
| 171 | case 'date-time': |
| 172 | stringSchema = stringSchema.datetime({ |
| 173 | offset: true, |
| 174 | message: |
| 175 | 'Must be a valid date-time, e.g. 2024-03-15T14:30:00Z, tomorrow at 3pm', |
| 176 | }) |
| 177 | break |
| 178 | default: |
| 179 | // No specific format validation |
| 180 | break |
| 181 | } |
| 182 | return stringSchema |
| 183 | } |
| 184 | if (schema.type === 'number' || schema.type === 'integer') { |
| 185 | const typeLabel = schema.type === 'integer' ? 'an integer' : 'a number' |
| 186 | const isInteger = schema.type === 'integer' |
| 187 | const formatNum = (n: number) => |
| 188 | Number.isInteger(n) && !isInteger ? `${n}.0` : String(n) |
| 189 | |
| 190 | // Build a single descriptive error message for range violations |
| 191 | const rangeMsg = |
| 192 | schema.minimum !== undefined && schema.maximum !== undefined |
no test coverage detected