Skip to content

Commit ae28653

Browse files
committed
feat: reduce type lenght
1 parent f9c0d18 commit ae28653

1 file changed

Lines changed: 27 additions & 3 deletions

File tree

ts/src/internal/zod-schema.ts

Lines changed: 27 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
import {toJSONSchema, type ZodTypeAny} from "zod";
2-
import {zodToTs, printNode, createAuxiliaryTypeStore} from "zod-to-ts";
2+
import {zodToTs, printNode, createAuxiliaryTypeStore, type TypeOverrideMap} from "zod-to-ts";
33
import type {DefinitionDataTypeRule} from "@code0-tech/tucana/shared";
44

55
type JsonSchema = {
@@ -8,9 +8,33 @@ type JsonSchema = {
88
maximum?: number;
99
};
1010

11+
const schemaRegistry = new Map<ZodTypeAny, string>();
12+
13+
export function registerSchema(schema: ZodTypeAny, identifier: string): void {
14+
schemaRegistry.set(schema, identifier);
15+
}
16+
17+
export function getRegisteredIdentifier(schema: ZodTypeAny): string | undefined {
18+
return schemaRegistry.get(schema);
19+
}
20+
21+
function buildOverrides(skip: ZodTypeAny): TypeOverrideMap {
22+
const overrides: TypeOverrideMap = new Map();
23+
for (const [schema, identifier] of schemaRegistry) {
24+
if (schema === skip) continue;
25+
overrides.set(schema as never, (typescript) =>
26+
typescript.factory.createTypeReferenceNode(typescript.factory.createIdentifier(identifier))
27+
);
28+
}
29+
return overrides;
30+
}
31+
1132
export function zodToTypeString(schema: ZodTypeAny): string {
12-
const {node} = zodToTs(schema, {auxiliaryTypeStore: createAuxiliaryTypeStore()});
13-
return printNode(node);
33+
const {node} = zodToTs(schema, {
34+
auxiliaryTypeStore: createAuxiliaryTypeStore(),
35+
overrides: buildOverrides(schema),
36+
});
37+
return printNode(node, {removeComments: true, omitTrailingSemicolon: true}).replace(/\s+/g, " ").trim();
1438
}
1539

1640
export function zodToRules(schema: ZodTypeAny): DefinitionDataTypeRule[] {

0 commit comments

Comments
 (0)