From aa9599e3fbd2b069a935428c804df4bf4ab8d2de Mon Sep 17 00:00:00 2001 From: Utkarsh patwa Date: Thu, 19 Nov 2026 15:13:08 +0530 Subject: [PATCH 1/4] Emit typed wire schemas for Zod Set and Map (#451) Zod `z.set()` and `z.map()` previously fell through to `any` in `getZodSchemaAsTypeScript`. This change: - Emits `T[]` for `z.set()` as the JSON-compatible wire schema. - Emits `[K, V][]` for `z.map()` as the key-value tuple array wire schema. - Adds test coverage for `z.set()` and `z.map()` in `test/zod.test.ts`, including union elements. Closes #451 Signed-off-by: Utkarsh patwa --- typescript/src/zod/validate.ts | 18 ++++++++++++++++++ typescript/test/zod.test.ts | 28 ++++++++++++++++++++++++++++ 2 files changed, 46 insertions(+) diff --git a/typescript/src/zod/validate.ts b/typescript/src/zod/validate.ts index fff47237..21e57026 100644 --- a/typescript/src/zod/validate.ts +++ b/typescript/src/zod/validate.ts @@ -163,6 +163,10 @@ export function getZodSchemaAsTypeScript(schema: Record): str return append("unknown"); case "array": return appendArrayType(type); + case "set": + return appendSetType(type); + case "map": + return appendMapType(type); case "object": return appendObjectType(type); case "union": { // covers both z.union() and z.discriminatedUnion() — Zod v4 merged discriminated unions into the regular union type kind ("ZodDiscriminatedUnion" in v3); both have an `options` array @@ -198,6 +202,20 @@ export function getZodSchemaAsTypeScript(schema: Record): str append("[]"); } + function appendSetType(setType: z.ZodType) { + appendType((setType._zod.def as z.core.$ZodSetDef).valueType as z.ZodType, TypePrecedence.Object); + append("[]"); + } + + function appendMapType(mapType: z.ZodType) { + const mapDef = mapType._zod.def as z.core.$ZodMapDef; + append("["); + appendType(mapDef.keyType as z.ZodType); + append(", "); + appendType(mapDef.valueType as z.ZodType); + append("][]"); + } + function appendObjectType(objectType: z.ZodType) { append("{"); appendNewLine(); diff --git a/typescript/test/zod.test.ts b/typescript/test/zod.test.ts index 8db3e2ae..21bbf9f5 100644 --- a/typescript/test/zod.test.ts +++ b/typescript/test/zod.test.ts @@ -150,6 +150,34 @@ describe("getZodSchemaAsTypeScript", () => { }); + // ----------------------------------------------------------------------- + // Set & Map + // ----------------------------------------------------------------------- + + describe("z.set()", () => { + + it("produces an array wire representation for sets", () => { + assert.match(schemaOf("T", z.set(z.string())), /type T = string\[\];/); + }); + + it("parenthesizes a union element type in a set", () => { + assert.match(schemaOf("T", z.set(z.union([z.string(), z.number()]))), /type T = \(string \| number\)\[\];/); + }); + + }); + + describe("z.map()", () => { + + it("produces a key-value tuple array wire representation for maps", () => { + assert.match(schemaOf("T", z.map(z.string(), z.number())), /type T = \[string, number\]\[\];/); + }); + + it("supports union key and value types in maps", () => { + assert.match(schemaOf("T", z.map(z.union([z.string(), z.number()]), z.boolean())), /type T = \[string \| number, boolean\]\[\];/); + }); + + }); + // ----------------------------------------------------------------------- // Object — emitted as interface // ----------------------------------------------------------------------- From f2bc01e245d45d7ad9b840b78769dd7c62c5bd8c Mon Sep 17 00:00:00 2001 From: Utkarsh patwa Date: Thu, 19 Nov 2026 15:27:08 +0530 Subject: [PATCH 2/4] refactor(zod): preserve collection types for bare Set/Map and add transform regression tests Signed-off-by: Utkarsh patwa --- typescript/src/zod/validate.ts | 9 +++-- typescript/test/zod.test.ts | 68 ++++++++++++++++++++++++++++++---- 2 files changed, 66 insertions(+), 11 deletions(-) diff --git a/typescript/src/zod/validate.ts b/typescript/src/zod/validate.ts index 21e57026..42302286 100644 --- a/typescript/src/zod/validate.ts +++ b/typescript/src/zod/validate.ts @@ -203,17 +203,18 @@ export function getZodSchemaAsTypeScript(schema: Record): str } function appendSetType(setType: z.ZodType) { - appendType((setType._zod.def as z.core.$ZodSetDef).valueType as z.ZodType, TypePrecedence.Object); - append("[]"); + append("Set<"); + appendType((setType._zod.def as z.core.$ZodSetDef).valueType as z.ZodType); + append(">"); } function appendMapType(mapType: z.ZodType) { const mapDef = mapType._zod.def as z.core.$ZodMapDef; - append("["); + append("Map<"); appendType(mapDef.keyType as z.ZodType); append(", "); appendType(mapDef.valueType as z.ZodType); - append("][]"); + append(">"); } function appendObjectType(objectType: z.ZodType) { diff --git a/typescript/test/zod.test.ts b/typescript/test/zod.test.ts index 21bbf9f5..dfdab375 100644 --- a/typescript/test/zod.test.ts +++ b/typescript/test/zod.test.ts @@ -156,24 +156,24 @@ describe("getZodSchemaAsTypeScript", () => { describe("z.set()", () => { - it("produces an array wire representation for sets", () => { - assert.match(schemaOf("T", z.set(z.string())), /type T = string\[\];/); + it("produces Set representation for sets", () => { + assert.match(schemaOf("T", z.set(z.string())), /type T = Set;/); }); - it("parenthesizes a union element type in a set", () => { - assert.match(schemaOf("T", z.set(z.union([z.string(), z.number()]))), /type T = \(string \| number\)\[\];/); + it("supports union element type in a set", () => { + assert.match(schemaOf("T", z.set(z.union([z.string(), z.number()]))), /type T = Set;/); }); }); describe("z.map()", () => { - it("produces a key-value tuple array wire representation for maps", () => { - assert.match(schemaOf("T", z.map(z.string(), z.number())), /type T = \[string, number\]\[\];/); + it("produces Map representation for maps", () => { + assert.match(schemaOf("T", z.map(z.string(), z.number())), /type T = Map;/); }); it("supports union key and value types in maps", () => { - assert.match(schemaOf("T", z.map(z.union([z.string(), z.number()]), z.boolean())), /type T = \[string \| number, boolean\]\[\];/); + assert.match(schemaOf("T", z.map(z.union([z.string(), z.number()]), z.boolean())), /type T = Map;/); }); }); @@ -535,6 +535,60 @@ describe("getZodSchemaAsTypeScript", () => { assert.ok(!invalidResult.success, "expected invalid date-time validation to fail"); }); + it("preserves explicit array-to-Set and tuple-array-to-Map transforms during validation and translation", async () => { + const CollectionSchema = { + Collections: z.object({ + tags: z.array(z.string()).transform(items => new Set(items)), + entries: z.array(z.tuple([z.string(), z.number()])).transform(tuples => new Map(tuples)), + }), + }; + const validator = createZodJsonValidator(CollectionSchema, "Collections"); + const schemaText = validator.getSchemaText(); + assert.match(schemaText, /tags: string\[\];/); + assert.match(schemaText, /entries: \[string, number\]\[\];/); + + // Validation with JSON array inputs produces Set and Map instances + const valid = validator.validate({ + tags: ["apple", "banana", "apple"], + entries: [["first", 1], ["second", 2]], + }); + assert.ok(valid.success, "expected validation to succeed"); + assert.ok(valid.data.tags instanceof Set); + assert.equal(valid.data.tags.size, 2); + assert.ok(valid.data.tags.has("apple")); + assert.ok(valid.data.tags.has("banana")); + assert.ok(valid.data.entries instanceof Map); + assert.equal(valid.data.entries.get("first"), 1); + assert.equal(valid.data.entries.get("second"), 2); + + // Rejects invalid array elements + const invalid = validator.validate({ + tags: [123], + entries: [["first", 1]], + }); + assert.ok(!invalid.success, "expected invalid collection element to fail validation"); + + // Full translation path with stubbed language model + const mockModel = { + async complete() { + return { + success: true as const, + data: JSON.stringify({ + tags: ["alpha", "beta"], + entries: [["count", 42]], + }), + }; + }, + }; + const translator = createJsonTranslator(mockModel, validator); + const translationResult = await translator.translate("Provide sample collections"); + assert.ok(translationResult.success, "expected translation to succeed"); + assert.ok(translationResult.data.tags instanceof Set); + assert.ok(translationResult.data.tags.has("alpha")); + assert.ok(translationResult.data.entries instanceof Map); + assert.equal(translationResult.data.entries.get("count"), 42); + }); + }); // ----------------------------------------------------------------------- From f8f58f5abcb9eccd089a79c89b5efab87803a69e Mon Sep 17 00:00:00 2001 From: Utkarsh Patwa Date: Tue, 24 Nov 2026 12:40:25 +0530 Subject: [PATCH 3/4] feat(zod): qualify Set and Map with globalThis and add collision regression tests Signed-off-by: Utkarsh Patwa --- typescript/src/zod/validate.ts | 4 ++-- typescript/test/zod.test.ts | 22 ++++++++++++++++------ 2 files changed, 18 insertions(+), 8 deletions(-) diff --git a/typescript/src/zod/validate.ts b/typescript/src/zod/validate.ts index 42302286..21e8bd4a 100644 --- a/typescript/src/zod/validate.ts +++ b/typescript/src/zod/validate.ts @@ -203,14 +203,14 @@ export function getZodSchemaAsTypeScript(schema: Record): str } function appendSetType(setType: z.ZodType) { - append("Set<"); + append("globalThis.Set<"); appendType((setType._zod.def as z.core.$ZodSetDef).valueType as z.ZodType); append(">"); } function appendMapType(mapType: z.ZodType) { const mapDef = mapType._zod.def as z.core.$ZodMapDef; - append("Map<"); + append("globalThis.Map<"); appendType(mapDef.keyType as z.ZodType); append(", "); appendType(mapDef.valueType as z.ZodType); diff --git a/typescript/test/zod.test.ts b/typescript/test/zod.test.ts index dfdab375..d2e54548 100644 --- a/typescript/test/zod.test.ts +++ b/typescript/test/zod.test.ts @@ -156,24 +156,34 @@ describe("getZodSchemaAsTypeScript", () => { describe("z.set()", () => { - it("produces Set representation for sets", () => { - assert.match(schemaOf("T", z.set(z.string())), /type T = Set;/); + it("produces globalThis.Set representation for sets", () => { + assert.match(schemaOf("T", z.set(z.string())), /type T = globalThis\.Set;/); }); it("supports union element type in a set", () => { - assert.match(schemaOf("T", z.set(z.union([z.string(), z.number()]))), /type T = Set;/); + assert.match(schemaOf("T", z.set(z.union([z.string(), z.number()]))), /type T = globalThis\.Set;/); + }); + + it("qualifies Set to avoid collision when the schema itself is named Set", () => { + const out = schemaOf("Set", z.set(z.string())); + assert.match(out, /type Set = globalThis\.Set;/); }); }); describe("z.map()", () => { - it("produces Map representation for maps", () => { - assert.match(schemaOf("T", z.map(z.string(), z.number())), /type T = Map;/); + it("produces globalThis.Map representation for maps", () => { + assert.match(schemaOf("T", z.map(z.string(), z.number())), /type T = globalThis\.Map;/); }); it("supports union key and value types in maps", () => { - assert.match(schemaOf("T", z.map(z.union([z.string(), z.number()]), z.boolean())), /type T = Map;/); + assert.match(schemaOf("T", z.map(z.union([z.string(), z.number()]), z.boolean())), /type T = globalThis\.Map;/); + }); + + it("qualifies Map to avoid collision when the schema itself is named Map", () => { + const out = schemaOf("Map", z.map(z.string(), z.number())); + assert.match(out, /type Map = globalThis\.Map;/); }); }); From 56407db7655252ed81de40cecabe920708849015 Mon Sep 17 00:00:00 2001 From: Utkarsh Patwa Date: Wed, 25 Nov 2026 12:02:25 +0530 Subject: [PATCH 4/4] feat(zod): escape non-identifier property names and detect unnamed recursive collections (#451) - In appendObjectType, escape non-identifier property names with JSON.stringify in both required and optional branches. - In getZodSchemaAsTypeScript, track expanding type identities in expandingTypes to detect unnamed recursive types in collections or nested objects and throw an actionable error instructing callers to register the recursive type by name. - Add compiler-backed regression tests in typescript/test/zod.test.ts for non-identifier keys in Set, Map, and object types, as well as unnamed and registered recursive schemas for both Set and Map. Signed-off-by: Utkarsh Patwa --- typescript/src/zod/validate.ts | 23 +++++-- typescript/test/zod.test.ts | 112 +++++++++++++++++++++++++++++++++ 2 files changed, 131 insertions(+), 4 deletions(-) diff --git a/typescript/src/zod/validate.ts b/typescript/src/zod/validate.ts index 21e8bd4a..5ca18598 100644 --- a/typescript/src/zod/validate.ts +++ b/typescript/src/zod/validate.ts @@ -79,6 +79,10 @@ function getTypePrecedence(type: z.ZodType): TypePrecedence { return TypePrecedence.Object; } +function isValidPropertyName(name: string): boolean { + return /^[a-zA-Z_$][0-9a-zA-Z_$]*$/.test(name); +} + /** * Returns the TypeScript source code corresponding to a Zod schema. The schema is supplied as an object where each * property provides a name for an associated Zod type. The return value is a string containing the TypeScript source @@ -94,6 +98,7 @@ export function getZodSchemaAsTypeScript(schema: Record): str let indent = 0; const entries = Array.from(Object.entries(schema)); let namedTypes = new Map(entries.map(([name, type]) => [getTypeIdentity(type), name])); + const expandingTypes = new Set(); for (const [name, type] of entries) { if (result) { appendNewLine(); @@ -132,16 +137,25 @@ export function getZodSchemaAsTypeScript(schema: Record): str } function appendType(type: z.ZodType, minPrecedence = 0) { - const name = namedTypes.get(getTypeIdentity(type)); + const identity = getTypeIdentity(type); + const name = namedTypes.get(identity); if (name) { append(name); + return; } - else { + if (expandingTypes.has(identity)) { + throw new Error("Recursive type reference detected in schema. Register the recursive type by name in the schema object to allow named type reference emission."); + } + expandingTypes.add(identity); + try { const parenthesize = getTypePrecedence(type) < minPrecedence; if (parenthesize) append("("); appendTypeDefinition(type); if (parenthesize) append(")"); } + finally { + expandingTypes.delete(identity); + } } function appendTypeDefinition(type: z.ZodType) { @@ -222,6 +236,7 @@ export function getZodSchemaAsTypeScript(schema: Record): str appendNewLine(); indent++; for (let [name, type] of Object.entries((objectType._zod.def as z.core.$ZodObjectDef).shape) as [string, z.ZodType][]) { + const propertyName = isValidPropertyName(name) ? name : JSON.stringify(name); let inlineComment: string | undefined; if (getTypeKind(type) === "optional") { const wrapperDescription = type.description; @@ -231,12 +246,12 @@ export function getZodSchemaAsTypeScript(schema: Record): str appendNewLine(); } } - append(name); + append(propertyName); append("?"); type = (type._zod.def as z.core.$ZodOptionalDef).innerType as z.ZodType; } else { inlineComment = type.description; - append(name); + append(propertyName); } append(": "); appendType(type); diff --git a/typescript/test/zod.test.ts b/typescript/test/zod.test.ts index d2e54548..140ec109 100644 --- a/typescript/test/zod.test.ts +++ b/typescript/test/zod.test.ts @@ -169,6 +169,56 @@ describe("getZodSchemaAsTypeScript", () => { assert.match(out, /type Set = globalThis\.Set;/); }); + it("escapes non-identifier property names in object element types", () => { + const out = schemaOf("T", z.set(z.object({ + "part-number": z.string(), + "is-active": z.boolean().optional(), + valid_ident: z.number(), + }))); + assert.match(out, /"part-number": string;/); + assert.match(out, /"is-active"\?: boolean;/); + assert.match(out, /valid_ident: number;/); + assertSchemasCompile([out]); + }); + + it("throws when generating schema for an unnamed recursive object in a set", () => { + interface RecursiveNode { + name: string; + children?: Set; + } + const RecursiveNode: z.ZodType = z.object({ + name: z.string(), + get children() { + return z.set(RecursiveNode).optional(); + }, + }); + assert.throws( + () => getZodSchemaAsTypeScript({ Nodes: z.set(RecursiveNode) }), + /Recursive type reference detected in schema\. Register the recursive type by name in the schema object to allow named type reference emission\./ + ); + }); + + it("emits named recursive reference when the recursive object is registered by name", () => { + interface RecursiveNode { + name: string; + children?: Set; + } + const RecursiveNode: z.ZodType = z.object({ + name: z.string(), + get children() { + return z.set(RecursiveNode).optional(); + }, + }); + const out = schemasOf({ + RecursiveNode, + Nodes: z.set(RecursiveNode), + }); + assert.match(out, /interface RecursiveNode \{/); + assert.match(out, /children\?: globalThis\.Set;/); + assert.match(out, /type Nodes = globalThis\.Set;/); + assertSchemasCompile([out]); + }); + }); describe("z.map()", () => { @@ -186,6 +236,56 @@ describe("getZodSchemaAsTypeScript", () => { assert.match(out, /type Map = globalThis\.Map;/); }); + it("escapes non-identifier property names in map value object types", () => { + const out = schemaOf("T", z.map(z.string(), z.object({ + "part-number": z.string(), + "is-active": z.boolean().optional(), + valid_ident: z.number(), + }))); + assert.match(out, /"part-number": string;/); + assert.match(out, /"is-active"\?: boolean;/); + assert.match(out, /valid_ident: number;/); + assertSchemasCompile([out]); + }); + + it("throws when generating schema for an unnamed recursive object in a map", () => { + interface RecursiveMapNode { + name: string; + children?: Map; + } + const RecursiveMapNode: z.ZodType = z.object({ + name: z.string(), + get children() { + return z.map(z.string(), RecursiveMapNode).optional(); + }, + }); + assert.throws( + () => getZodSchemaAsTypeScript({ Nodes: z.map(z.string(), RecursiveMapNode) }), + /Recursive type reference detected in schema\. Register the recursive type by name in the schema object to allow named type reference emission\./ + ); + }); + + it("emits named recursive reference when the recursive object in a map is registered by name", () => { + interface RecursiveMapNode { + name: string; + children?: Map; + } + const RecursiveMapNode: z.ZodType = z.object({ + name: z.string(), + get children() { + return z.map(z.string(), RecursiveMapNode).optional(); + }, + }); + const out = schemasOf({ + RecursiveMapNode, + Nodes: z.map(z.string(), RecursiveMapNode), + }); + assert.match(out, /interface RecursiveMapNode \{/); + assert.match(out, /children\?: globalThis\.Map;/); + assert.match(out, /type Nodes = globalThis\.Map;/); + assertSchemasCompile([out]); + }); + }); // ----------------------------------------------------------------------- @@ -220,6 +320,18 @@ describe("getZodSchemaAsTypeScript", () => { assert.match(out, /x: number; \/\/ x coordinate/); }); + it("escapes non-identifier property names in interfaces", () => { + const out = schemaOf("InventoryItem", z.object({ + "part-number": z.string(), + "special-case?": z.boolean().optional(), + validName: z.number(), + })); + assert.match(out, /"part-number": string;/); + assert.match(out, /"special-case\?"\?: boolean;/); + assert.match(out, /validName: number;/); + assertSchemasCompile([out]); + }); + it("does NOT add comment to field comment if the optional wrapper has a description", () => { // The description on the optional wrapper should appear before the field, not inline on it const out = schemaOf("T", z.object({