(schema: Record<string, z.ZodType>)
| 78 | * @returns The TypeScript source code corresponding to the schema. |
| 79 | */ |
| 80 | export function getZodSchemaAsTypeScript(schema: Record<string, z.ZodType>): string { |
| 81 | let result = ""; |
| 82 | let startOfLine = true; |
| 83 | let indent = 0; |
| 84 | const entries = Array.from(Object.entries(schema)); |
| 85 | let namedTypes = new Map<object, string>(entries.map(([name, type]) => [getTypeIdentity(type), name])); |
| 86 | for (const [name, type] of entries) { |
| 87 | if (result) { |
| 88 | appendNewLine(); |
| 89 | } |
| 90 | const description = type.description; |
| 91 | if (description) { |
| 92 | for (const comment of description.split("\n")) { |
| 93 | append(`// ${comment}`); |
| 94 | appendNewLine(); |
| 95 | } |
| 96 | } |
| 97 | if (getTypeKind(type) === "object") { |
| 98 | append(`interface ${name} `); |
| 99 | appendObjectType(type as z.ZodObject); |
| 100 | } |
| 101 | else { |
| 102 | append(`type ${name} = `); |
| 103 | appendTypeDefinition(type); |
| 104 | append(";"); |
| 105 | } |
| 106 | appendNewLine(); |
| 107 | } |
| 108 | return result; |
| 109 | |
| 110 | function append(s: string) { |
| 111 | if (startOfLine) { |
| 112 | result += " ".repeat(indent); |
| 113 | startOfLine = false; |
| 114 | } |
| 115 | result += s; |
| 116 | } |
| 117 | |
| 118 | function appendNewLine() { |
| 119 | append("\n"); |
| 120 | startOfLine = true; |
| 121 | } |
| 122 | |
| 123 | function appendType(type: z.ZodType, minPrecedence = 0) { |
| 124 | const name = namedTypes.get(getTypeIdentity(type)); |
| 125 | if (name) { |
| 126 | append(name); |
| 127 | } |
| 128 | else { |
| 129 | const parenthesize = getTypePrecedence(type) < minPrecedence; |
| 130 | if (parenthesize) append("("); |
| 131 | appendTypeDefinition(type); |
| 132 | if (parenthesize) append(")"); |
| 133 | } |
| 134 | } |
| 135 | |
| 136 | function appendTypeDefinition(type: z.ZodType) { |
| 137 | switch (getTypeKind(type)) { |
searching dependent graphs…