|
1 |
| -import { z, ZodTypeAny } from 'zod'; |
2 |
| - |
3 |
| -/** |
4 |
| - * Converts a JSON Schema object to a Zod schema |
5 |
| - * @param schema The JSON Schema object to convert |
6 |
| - * @returns A Zod schema equivalent to the input JSON Schema |
7 |
| - */ |
8 |
| -export function jsonSchemaToZod(schema: any): ZodTypeAny { |
9 |
| - switch (schema.type) { |
10 |
| - case 'object': |
11 |
| - if (schema.properties) { |
12 |
| - const shape: Record<string, ZodTypeAny> = {}; |
13 |
| - for (const key in schema.properties) { |
14 |
| - shape[key] = jsonSchemaToZod(schema.properties[key]); |
15 |
| - } |
16 |
| - let zodObject = z.object(shape); |
17 |
| - if (schema.required && Array.isArray(schema.required)) { |
18 |
| - zodObject = zodObject.partial().required(schema.required); |
19 |
| - } |
20 |
| - if (schema.description) { |
21 |
| - zodObject = zodObject.describe(schema.description); |
22 |
| - } |
23 |
| - return zodObject; |
24 |
| - } else { |
25 |
| - return z.object({}); |
26 |
| - } |
27 |
| - case 'array': |
28 |
| - if (schema.items) { |
29 |
| - let zodArray = z.array(jsonSchemaToZod(schema.items)); |
30 |
| - if (schema.description) { |
31 |
| - zodArray = zodArray.describe(schema.description); |
32 |
| - } |
33 |
| - return zodArray; |
34 |
| - } else { |
35 |
| - return z.array(z.any()); |
36 |
| - } |
37 |
| - case 'string': |
38 |
| - if (schema.enum) { |
39 |
| - return z.string().refine(val => schema.enum.includes(val)); |
40 |
| - } |
41 |
| - let zodString = z.string(); |
42 |
| - if (schema.description) { |
43 |
| - zodString = zodString.describe(schema.description); |
44 |
| - } |
45 |
| - return zodString; |
46 |
| - case 'number': |
47 |
| - let zodNumber = z.number(); |
48 |
| - if (schema.minimum !== undefined) { |
49 |
| - zodNumber = zodNumber.min(schema.minimum); |
50 |
| - } |
51 |
| - if (schema.maximum !== undefined) { |
52 |
| - zodNumber = zodNumber.max(schema.maximum); |
53 |
| - } |
54 |
| - if (schema.description) { |
55 |
| - zodNumber = zodNumber.describe(schema.description); |
56 |
| - } |
57 |
| - return zodNumber; |
58 |
| - case 'boolean': |
59 |
| - let zodBoolean = z.boolean(); |
60 |
| - if (schema.description) { |
61 |
| - zodBoolean = zodBoolean.describe(schema.description); |
62 |
| - } |
63 |
| - return zodBoolean; |
64 |
| - default: |
65 |
| - return z.any(); |
66 |
| - } |
67 |
| -} |
68 |
| - |
69 | 1 | /**
|
70 | 2 | * Sanitizes a message to ensure it's properly formatted JSON
|
71 | 3 | * @param message The message to sanitize
|
|
0 commit comments