Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
19 changes: 19 additions & 0 deletions typescript/src/zod/validate.ts
Original file line number Diff line number Diff line change
Expand Up @@ -163,6 +163,10 @@ export function getZodSchemaAsTypeScript(schema: Record<string, z.ZodType>): str
return append("unknown");
case "array":
return appendArrayType(type);
case "set":
return appendSetType(type);
case "map":
return appendMapType(type);
Comment on lines +166 to +169

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Addressed in commit f2bc01e:

  • Bare collection schemas z.set() and z.map() now emit their true TypeScript types (Set<T> and Map<K, V>) rather than advertising raw array wire schemas that bare Zod collection instances reject.
  • Added comprehensive regression tests for explicit JSON-to-collection transforms (z.array(...).transform(v => new Set(v)) and z.array(z.tuple(...)).transform(v => new Map(v))), verifying wire schema generation (string[], [string, number][]), JSON validation into Set/Map instances, and full translation execution with createJsonTranslator.

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
Expand Down Expand Up @@ -198,6 +202,21 @@ export function getZodSchemaAsTypeScript(schema: Record<string, z.ZodType>): str
append("[]");
}

function appendSetType(setType: z.ZodType) {
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("Map<");
appendType(mapDef.keyType as z.ZodType);
append(", ");
appendType(mapDef.valueType as z.ZodType);
append(">");
}

function appendObjectType(objectType: z.ZodType) {
append("{");
appendNewLine();
Expand Down
82 changes: 82 additions & 0 deletions typescript/test/zod.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -150,6 +150,34 @@ describe("getZodSchemaAsTypeScript", () => {

});

// -----------------------------------------------------------------------
// Set & Map
// -----------------------------------------------------------------------

describe("z.set()", () => {

it("produces Set<T> representation for sets", () => {
assert.match(schemaOf("T", z.set(z.string())), /type T = Set<string>;/);
});

it("supports union element type in a set", () => {
assert.match(schemaOf("T", z.set(z.union([z.string(), z.number()]))), /type T = Set<string \| number>;/);
});

});

describe("z.map()", () => {

it("produces Map<K, V> representation for maps", () => {
assert.match(schemaOf("T", z.map(z.string(), z.number())), /type T = Map<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 = Map<string \| number, boolean>;/);
});

});

// -----------------------------------------------------------------------
// Object — emitted as interface
// -----------------------------------------------------------------------
Expand Down Expand Up @@ -507,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);
});

});

// -----------------------------------------------------------------------
Expand Down