From e2f3f7bc7ce60083b5a20d2eff5eabf45ad689de Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E4=B8=8E=E4=B8=96=E6=97=A0=E4=BA=89=E5=89=91=E5=AE=87?= =?UTF-8?q?=E5=AD=90?= <1530683628@qq.com> Date: Wed, 21 Oct 2026 11:16:21 +0800 Subject: [PATCH 1/3] fix(ts): accept serialized string enum values --- site/src/docs/typescript/basic-usage.md | 25 +++++ typescript/src/ts/validate.ts | 30 ++++- typescript/test/validate.test.ts | 142 +++++++++++++++++++++++- 3 files changed, 194 insertions(+), 3 deletions(-) diff --git a/site/src/docs/typescript/basic-usage.md b/site/src/docs/typescript/basic-usage.md index 085a5c9c..4757e1e2 100644 --- a/site/src/docs/typescript/basic-usage.md +++ b/site/src/docs/typescript/basic-usage.md @@ -202,6 +202,31 @@ const validator = createTypeScriptJsonValidator(schema, "Sent We provided the text of the schema and the name of the type we want returned data to satisfy. We also have to provide the type argument `SentimentResponse` to explain what data shape we expect (though note that this is a bit like a type cast and isn't guaranteed). +#### String enums + +JSON represents a TypeScript string enum using the member's value, not its name. The TypeScript validator +normalizes string-enum types to their literal values before validating, including when they appear in nested +objects, arrays, unions, and index signatures. + +```ts +export enum Currency { + USD = "USD", + EUR = "EUR" +} + +export interface Order { + currency: Currency; +} +``` + +The JSON `{ "currency": "EUR" }` is valid, while `{ "currency": "GBP" }` is not. If a member's name and value +differ, such as `Basic = "basic"`, JSON must use `"basic"`; `"Basic"` is rejected. Numeric enums keep their +existing numeric validation behavior. + +Members initialized with compile-time string expressions, such as `Euro = "E" + "UR"`, are supported when +TypeScript resolves the value to a string literal. Computed members without a compile-time literal type should be +modeled with a string literal union instead. + ### Zod Validators If you chose to define your schema with Zod, you can use the `createZodJsonValidator` function: diff --git a/typescript/src/ts/validate.ts b/typescript/src/ts/validate.ts index be202b74..5cb58415 100644 --- a/typescript/src/ts/validate.ts +++ b/typescript/src/ts/validate.ts @@ -34,6 +34,25 @@ const libFileName = "/lib.d.ts"; const schemaFileName = "/schema.ts"; const jsonFileName = "/json.ts"; +/** + * Returns a type alias name that does not collide with identifiers in the schema. + */ +function createUniqueJsonWireTypeName(schemaText: string): string { + let name = "__TypeChatJsonWire"; + while (schemaText.includes(name)) { + name += "_"; + } + return name; +} + +/** + * Maps serialized string-enum values back to their literal enum member types while preserving the + * rest of the schema's structure. + */ +function createJsonWireTypeDefinition(typeName: string): string { + return `type ${typeName} = T extends string ? \`\${T}\` : T extends object ? { [K in keyof T]: ${typeName} } : T;`; +} + /** * Represents an object that can validate JSON strings according to a given TypeScript schema. */ @@ -80,6 +99,7 @@ export function createTypeScriptJsonValidator(schema: throw new Error("The TypeScript virtual file system doesn't support writing files."); } const writeJsonFile = fileSystem.writeFile; + const jsonWireTypeName = createUniqueJsonWireTypeName(schema); const validator: TypeScriptJsonValidator = { getSchemaText: () => schema, getTypeName: () => typeName, @@ -155,7 +175,10 @@ export function createTypeScriptJsonValidator(schema: // Use getStart() to exclude leading trivia from the range check. if (decl.getStart(file) <= position && position <= decl.end && decl.type && isTypeReferenceNode(decl.type) && decl.initializer) { - const targetType = checker.getTypeAtLocation(decl.type); + // The generated JSON declaration wraps the schema type in the JsonWire helper. + // Use the wrapped schema type for user-facing diagnostics. + const targetTypeNode = decl.type.typeArguments?.[0] ?? decl.type; + const targetType = checker.getTypeAtLocation(targetTypeNode); const sourceType = checker.getTypeAtLocation(decl.initializer); if (!targetType || !sourceType) { continue; @@ -177,6 +200,9 @@ export function createTypeScriptJsonValidator(schema: } function createModuleTextFromJson(jsonObject: object) { - return success(`import { ${typeName} } from './schema';\nconst json: ${typeName} = ${JSON.stringify(jsonObject, undefined, 2)};\n`); + // String enums do not accept their serialized values in a normal enum-typed assignment. + // The JsonWire helper maps each string literal back to itself while recursively preserving + // object, array, tuple, optional-property, and union shapes. Numeric enums remain unchanged. + return success(`import { ${typeName} } from './schema';\n${createJsonWireTypeDefinition(jsonWireTypeName)}\nconst json: ${jsonWireTypeName}<${typeName}> = ${JSON.stringify(jsonObject, undefined, 2)};\n`); } } diff --git a/typescript/test/validate.test.ts b/typescript/test/validate.test.ts index 31ef89fa..15c7dfc9 100644 --- a/typescript/test/validate.test.ts +++ b/typescript/test/validate.test.ts @@ -40,6 +40,69 @@ export interface Point { y: number; }`; +// Schemas for serialized string-enum validation. +const stringEnumSchema = ` +export enum Currency { + USD = "USD", + EUR = "EUR" +} +export interface Order { + currency: Currency; +}`; + +const differingEnumValueSchema = ` +export enum Plan { + Basic = "basic", + Pro = "pro" +} +export interface Subscription { + plan: Plan; +}`; + +const nestedEnumSchema = ` +export enum Status { + Active = "active", + Paused = "paused" +} +export interface Item { + status: Status; +} +export interface Batch { + primary: Item; + items: Item[]; + lookup: { [id: string]: Status }; + result: { ok: true; value: Status } | { ok: false; error: string }; +}`; + +const enumMemberTypeSchema = ` +export enum Currency { + USD = "USD", + EUR = "EUR" +} +export type EuropeanCurrency = Currency.EUR; +export interface Payment { + currency: EuropeanCurrency; +}`; + +const numericEnumSchema = ` +export enum Priority { + Low, + Medium, + High +} +export interface Config { + priority: Priority; + count: number; +}`; + +const computedStringEnumSchema = ` +export enum Currency { + Euro = "E" + "UR" +} +export interface Order { + currency: Currency; +}`; + // --------------------------------------------------------------------------- // Helper // --------------------------------------------------------------------------- @@ -82,6 +145,82 @@ describe("createTypeScriptJsonValidator", () => { }); }); + describe("serialized string enum values", () => { + it("accepts a valid serialized string-enum value", () => { + const v = validatorFor(stringEnumSchema, "Order"); + const result = v.validate({ currency: "EUR" }); + assert.ok(result.success, `expected validation to succeed, got: ${result.success ? "" : result.message}`); + }); + + it("rejects unknown values and member names that differ from their values", () => { + const v = validatorFor(differingEnumValueSchema, "Subscription"); + const unknown = v.validate({ plan: "enterprise" }); + assert.ok(!unknown.success, "expected an unknown enum value to fail"); + assert.match(unknown.message, /not assignable/); + + const memberName = v.validate({ plan: "Basic" }); + assert.ok(!memberName.success, "expected an enum member name to fail when it differs from the value"); + assert.match(memberName.message, /not assignable/); + }); + + it("validates enums in nested objects, arrays, unions, and index signatures", () => { + const v = validatorFor(nestedEnumSchema, "Batch"); + const valid = v.validate({ + primary: { status: "active" }, + items: [{ status: "paused" }, { status: "active" }], + lookup: { first: "active", second: "paused" }, + result: { ok: true, value: "active" } + }); + assert.ok(valid.success, `expected nested enum values to pass, got: ${valid.success ? "" : valid.message}`); + + const invalid = v.validate({ + primary: { status: "active" }, + items: [{ status: "unknown" }], + lookup: { first: "active" }, + result: { ok: false, error: "failed" } + }); + assert.ok(!invalid.success, "expected an unknown nested enum value to fail"); + assert.match(invalid.message, /not assignable/); + }); + + it("accepts serialized values for an individual enum-member type", () => { + const v = validatorFor(enumMemberTypeSchema, "Payment"); + const valid = v.validate({ currency: "EUR" }); + assert.ok(valid.success, `expected enum-member value to pass, got: ${valid.success ? "" : valid.message}`); + + const invalid = v.validate({ currency: "USD" }); + assert.ok(!invalid.success, "expected a different enum member to fail"); + assert.match(invalid.message, /not assignable/); + }); + + it("preserves numeric enum validation", () => { + const v = validatorFor(numericEnumSchema, "Config"); + const valid = v.validate({ priority: 1, count: 2 }); + assert.ok(valid.success, `expected numeric enum value to pass, got: ${valid.success ? "" : valid.message}`); + + const invalid = v.validate({ priority: 3, count: 2 }); + assert.ok(!invalid.success, "expected a value outside the numeric enum to fail"); + assert.match(invalid.message, /not assignable/); + }); + + it("does not hide unrelated type errors", () => { + const v = validatorFor(numericEnumSchema, "Config"); + const result = v.validate({ priority: 1, count: "two" }); + assert.ok(!result.success, "expected an unrelated type error to fail validation"); + assert.match(result.message, /not assignable/); + }); + + it("supports constant-folded string enum values", () => { + const v = validatorFor(computedStringEnumSchema, "Order"); + const valid = v.validate({ currency: "EUR" }); + assert.ok(valid.success, `expected constant-folded enum value to pass, got: ${valid.success ? "" : valid.message}`); + + const invalid = v.validate({ currency: "USD" }); + assert.ok(!invalid.success, "expected a value not produced by the computed member to fail"); + assert.match(invalid.message, /not assignable/); + }); + }); + describe("type mismatch errors (backward-compatible: unchanged code path)", () => { it("reports a type error when a property has the wrong type", () => { const v = validatorFor(smallSchema, "Point"); @@ -190,7 +329,8 @@ describe("createTypeScriptJsonValidator", () => { const result = v.createModuleTextFromJson({ x: 1, y: 2 }); assert.ok(result.success, "expected module text creation to succeed"); assert.ok(result.data.includes("import { Point } from './schema'")); - assert.ok(result.data.includes("const json: Point =")); + assert.ok(result.data.includes("type __TypeChatJsonWire = T extends string")); + assert.ok(result.data.includes("const json: __TypeChatJsonWire =")); }); }); }); From 26343163f8a5c78305004cd0ff0c85c6e81f75f4 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E4=B8=8E=E4=B8=96=E6=97=A0=E4=BA=89=E5=89=91=E5=AE=87?= =?UTF-8?q?=E5=AD=90?= <1530683628@qq.com> Date: Mon, 9 Nov 2026 15:22:18 +0800 Subject: [PATCH 2/3] fix(ts): preserve callable types and generic diagnostics --- typescript/src/ts/validate.ts | 15 +++++-- typescript/test/validate.test.ts | 69 ++++++++++++++++++++++++++++++++ 2 files changed, 80 insertions(+), 4 deletions(-) diff --git a/typescript/src/ts/validate.ts b/typescript/src/ts/validate.ts index 5cb58415..12466e69 100644 --- a/typescript/src/ts/validate.ts +++ b/typescript/src/ts/validate.ts @@ -50,7 +50,10 @@ function createUniqueJsonWireTypeName(schemaText: string): string { * rest of the schema's structure. */ function createJsonWireTypeDefinition(typeName: string): string { - return `type ${typeName} = T extends string ? \`\${T}\` : T extends object ? { [K in keyof T]: ${typeName} } : T;`; + return `type ${typeName} = T extends string ? \`\${T}\` : ` + + `T extends (...args: any[]) => any ? T : ` + + `T extends abstract new (...args: any[]) => any ? T : ` + + `T extends object ? { [K in keyof T]: ${typeName} } : T;`; } /** @@ -175,9 +178,13 @@ export function createTypeScriptJsonValidator(schema: // Use getStart() to exclude leading trivia from the range check. if (decl.getStart(file) <= position && position <= decl.end && decl.type && isTypeReferenceNode(decl.type) && decl.initializer) { - // The generated JSON declaration wraps the schema type in the JsonWire helper. - // Use the wrapped schema type for user-facing diagnostics. - const targetTypeNode = decl.type.typeArguments?.[0] ?? decl.type; + // Only the declaration generated by this validator wraps the schema type in + // the JsonWire helper. A custom createModuleTextFromJson may use any generic + // annotation, so unwrap only our own helper and keep other targets intact. + const isJsonWireReference = decl.type.typeName.getText(file) === jsonWireTypeName; + const targetTypeNode = isJsonWireReference + ? decl.type.typeArguments?.[0] ?? decl.type + : decl.type; const targetType = checker.getTypeAtLocation(targetTypeNode); const sourceType = checker.getTypeAtLocation(decl.initializer); if (!targetType || !sourceType) { diff --git a/typescript/test/validate.test.ts b/typescript/test/validate.test.ts index 15c7dfc9..61b8efae 100644 --- a/typescript/test/validate.test.ts +++ b/typescript/test/validate.test.ts @@ -103,6 +103,33 @@ export interface Order { currency: Currency; }`; +const callableSchema = ` +export interface Response { + callback: () => string; + factory: new () => { ok: boolean }; +}`; + +const promiseLikeSchema = ` +interface PromiseLike { + then(onFulfilled: (value: T) => unknown): unknown; + catch(onRejected: (reason: unknown) => unknown): unknown; +} +export interface Response { + value: PromiseLike; +}`; + +const genericWrapperSchema = ` +export interface Metadata { + m1: string; m2: string; m3: string; m4: string; + m5: string; m6: string; m7: string; +} +export interface Wrapper { + a: string; b: string; c: string; d: string; + e: string; f: string; g: string; payload: T; +} +export type Response = Wrapper; +`; + // --------------------------------------------------------------------------- // Helper // --------------------------------------------------------------------------- @@ -219,6 +246,24 @@ describe("createTypeScriptJsonValidator", () => { assert.ok(!invalid.success, "expected a value not produced by the computed member to fail"); assert.match(invalid.message, /not assignable/); }); + + it("preserves rejection of call and construct signatures", () => { + const v = validatorFor(callableSchema, "Response"); + const callback = v.validate({ callback: {}, factory: { ok: true } }); + assert.ok(!callback.success, "expected an empty object not to satisfy a call signature"); + assert.match(callback.message, /not assignable/); + + const factory = v.validate({ callback: () => "ok", factory: {} }); + assert.ok(!factory.success, "expected an empty object not to satisfy a construct signature"); + assert.match(factory.message, /not assignable/); + }); + + it("preserves rejection of Promise-shaped objects with non-callable methods", () => { + const v = validatorFor(promiseLikeSchema, "Response"); + const result = v.validate({ value: { then: {}, catch: {} } }); + assert.ok(!result.success, "expected non-callable then/catch methods to fail"); + assert.match(result.message, /not assignable/); + }); }); describe("type mismatch errors (backward-compatible: unchanged code path)", () => { @@ -333,4 +378,28 @@ describe("createTypeScriptJsonValidator", () => { assert.ok(result.data.includes("const json: __TypeChatJsonWire =")); }); }); + + describe("missing-property diagnostics with custom module text", () => { + it("keeps a custom generic annotation as the diagnostic target", () => { + const v = validatorFor>(genericWrapperSchema, "Response"); + v.createModuleTextFromJson = value => ({ + success: true, + data: `import { Wrapper, Metadata } from './schema';\n` + + `const json: Wrapper = ${JSON.stringify(value)};` + }); + const result = v.validate({ + payload: { m1: "", m2: "", m3: "", m4: "", m5: "", m6: "", m7: "" } + }); + assert.ok(!result.success, "expected the missing wrapper fields to fail validation"); + assert.match(result.message, /Wrapper/); + assert.ok( + result.message.includes(": a, b, c, d, e, f, g"), + `expected all missing wrapper properties, got: ${result.message}` + ); + assert.ok( + !result.message.includes("from type 'Metadata'"), + `diagnostic must not target the unwrapped Metadata type, got: ${result.message}` + ); + }); + }); }); From 05788e4823d6369f626c079c19c656de63a8dd66 Mon Sep 17 00:00:00 2001 From: robgruen Date: Tue, 10 Nov 2026 12:52:12 -0800 Subject: [PATCH 3/3] Refactor createJsonWireTypeDefinition function Co-authored-by: Copilot Autofix powered by AI <175728472+Copilot@users.noreply.github.com> --- typescript/src/ts/validate.ts | 9 +++++---- 1 file changed, 5 insertions(+), 4 deletions(-) diff --git a/typescript/src/ts/validate.ts b/typescript/src/ts/validate.ts index 8a7ee39e..59e887b3 100644 --- a/typescript/src/ts/validate.ts +++ b/typescript/src/ts/validate.ts @@ -56,10 +56,11 @@ function createUniqueJsonWireTypeName(schemaText: string): string { * rest of the schema's structure. */ function createJsonWireTypeDefinition(typeName: string): string { - return `type ${typeName} = T extends string ? \`\${T}\` : ` + - `T extends (...args: any[]) => any ? T : ` + - `T extends abstract new (...args: any[]) => any ? T : ` + - `T extends object ? { [K in keyof T]: ${typeName} } : T;`; + return `type ${typeName} = + T extends string ? \`\${T}\` : + T extends (...args: any[]) => any ? T : + T extends abstract new (...args: any[]) => any ? T : + T extends object ? { [K in keyof T]: ${typeName} } : T;`; } /**