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
13 changes: 12 additions & 1 deletion package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

3 changes: 2 additions & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -90,7 +90,8 @@
"typescript": "~7.0.2",
"vitest": "^4.1.10",
"watch": "^1.0.2",
"web-tree-sitter": "^0.26.9"
"web-tree-sitter": "^0.26.9",
"zod": "3.20.2"
},
"files": [
"dist"
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -168,7 +168,7 @@ export class TypeScriptZodRenderer extends ConvenienceRenderer {
},
(_classType) => panic("Should already be handled."),
(_mapType) => [
"z.record(z.string(), ",
"mapSchema(",
this.typeMapTypeFor(_mapType.values, false),
")",
],
Expand Down Expand Up @@ -630,6 +630,14 @@ export class TypeScriptZodRenderer extends ConvenienceRenderer {
}

this.emitImports();
if (this.haveMaps) {
this.emitMultiline(`
const mapSchema = <T extends z.ZodTypeAny>(value: T) =>
z.custom<Record<string, unknown>>(input => z.getParsedType(input) === z.ZodParsedType.object)
.transform(Object.entries)
.pipe(z.array(z.tuple([z.string(), value])))
.transform((entries): Record<string, z.output<T>> => Object.fromEntries(entries));`);
}
this.emitSchemas();
}
}
86 changes: 86 additions & 0 deletions test/unit/typescript-zod-map-helper.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,86 @@
import { execFileSync } from "node:child_process";
import * as fs from "node:fs";
import * as path from "node:path";
import { describe, expect, test } from "vitest";

import { InputData, JSONSchemaInput, quicktype } from "quicktype-core";

async function render(schema: object): Promise<string> {
const schemaInput = new JSONSchemaInput(undefined);
await schemaInput.addSource({
name: "TopLevel",
schema: JSON.stringify(schema),
});
const inputData = new InputData();
inputData.addInput(schemaInput);
const result = await quicktype({ inputData, lang: "typescript-zod" });
return result.lines.join("\n");
}

function evaluate(output: string): Record<string, unknown> {
const directory = fs.mkdtempSync(path.join(process.cwd(), ".tmp-zod-map-"));
try {
fs.writeFileSync(path.join(directory, "TopLevel.ts"), output);
fs.writeFileSync(
path.join(directory, "main.ts"),
`import { TopLevelSchema } from "./TopLevel";
const input = Object.create(null);
Object.defineProperty(input, "__proto__", { value: 1, enumerable: true, writable: true, configurable: true });
const parsed = TopLevelSchema.parse(input);
const typed: Record<string, number> = parsed;
// @ts-expect-error Map values are numbers.
const invalid: string = parsed.value;
console.log(JSON.stringify({
prototype: Object.getPrototypeOf(parsed) === Object.prototype,
descriptor: Object.getOwnPropertyDescriptor(parsed, "__proto__"),
rejects: [new Date(), new Map(), new Set()].map(value => !TopLevelSchema.safeParse(value).success),
}));`,
);
execFileSync(
path.join(process.cwd(), "node_modules/.bin/tsc"),
[
"--ignoreConfig",
"--noEmit",
"--skipLibCheck",
"--moduleResolution",
"bundler",
"--target",
"ES2020",
"--module",
"preserve",
path.join(directory, "main.ts"),
],
{ timeout: 60_000 },
);
return JSON.parse(
execFileSync(
path.join(process.cwd(), "node_modules/.bin/tsx"),
[path.join(directory, "main.ts")],
{ encoding: "utf8", timeout: 60_000 },
),
);
} finally {
fs.rmSync(directory, { recursive: true, force: true });
}
}

describe("TypeScript Zod map helper", () => {
test("preserves record behavior and prototype-named keys", async () => {
const output = await render({
type: "object",
additionalProperties: { type: "integer" },
});
const result = evaluate(output);

expect(result).toEqual({
prototype: true,
descriptor: {
value: 1,
writable: true,
enumerable: true,
configurable: true,
},
rejects: [true, true, true],
});
}, 60_000);
});
Loading