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/8] 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/8] 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/8] 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;`; } /** From 8acc9d0dbd7411ffdac9fd06f29d0d05ae4e0168 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: Tue, 17 Nov 2026 16:52:55 +0800 Subject: [PATCH 4/8] fix(ts): preserve class constraints when normalizing enums --- typescript/src/ts/validate.ts | 18 +++++++++++------- typescript/test/validate.test.ts | 18 +++++++++++++++++- 2 files changed, 28 insertions(+), 8 deletions(-) diff --git a/typescript/src/ts/validate.ts b/typescript/src/ts/validate.ts index 59e887b3..ae16f93d 100644 --- a/typescript/src/ts/validate.ts +++ b/typescript/src/ts/validate.ts @@ -45,7 +45,7 @@ const schemaValidationFileName = "/schema-validation.ts"; */ function createUniqueJsonWireTypeName(schemaText: string): string { let name = "__TypeChatJsonWire"; - while (schemaText.includes(name)) { + while (schemaText.includes(name) || schemaText.includes(`${name}Object`) || schemaText.includes(`${name}Shape`)) { name += "_"; } return name; @@ -53,14 +53,18 @@ function createUniqueJsonWireTypeName(schemaText: string): string { /** * Maps serialized string-enum values back to their literal enum member types while preserving the - * rest of the schema's structure. + * rest of the schema's structure. Class instances with private or protected members are left + * unchanged because mapping their public keys would drop the nominal constraint that rejects + * plain JSON objects. */ 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}Object = { [K in keyof T]: ${typeName} }; +type ${typeName}Shape = { [K in keyof T]: T[K] }; +type ${typeName} = + T extends string ? \`\${T}\` : + T extends (...args: any[]) => any ? T : + T extends abstract new (...args: any[]) => any ? T : + T extends object ? (${typeName}Shape extends T ? ${typeName}Object : T) : T;`; } /** diff --git a/typescript/test/validate.test.ts b/typescript/test/validate.test.ts index df5c79ad..416efa81 100644 --- a/typescript/test/validate.test.ts +++ b/typescript/test/validate.test.ts @@ -122,6 +122,15 @@ export interface Response { value: Promise; }`; +const classInstanceSchema = ` +export class Token { + private brand!: string; + value!: string; +} +export interface Response { + token: Token; +}`; + const genericWrapperSchema = ` export interface Metadata { m1: string; m2: string; m3: string; m4: string; @@ -458,6 +467,13 @@ describe("createTypeScriptJsonValidator", () => { assert.ok(!result.success, "expected non-callable then/catch methods to fail"); assert.match(result.message, /not assignable/); }); + + it("preserves class-instance constraints in an enum-free schema", () => { + const v = validatorFor(classInstanceSchema, "Response"); + const result = v.validate({ token: { value: "unbranded" } }); + assert.ok(!result.success, "expected a plain object not to satisfy a class with private members"); + assert.match(result.message, /brand/); + }); }); describe("type mismatch errors (backward-compatible: unchanged code path)", () => { @@ -568,7 +584,7 @@ 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("type __TypeChatJsonWire = T extends string")); + assert.match(result.data, /type __TypeChatJsonWire\s*=\s*T extends string/); assert.ok(result.data.includes("const json: __TypeChatJsonWire =")); }); }); From dc9a39d0c3e354a7b3c5e18874f1daa1dfa949f8 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, 18 Nov 2026 09:04:06 +0800 Subject: [PATCH 5/8] fix(ts): preserve enum normalization constraints --- typescript/src/ts/validate.ts | 115 +++++++++++++++++++++++++---- typescript/test/validate.test.ts | 121 +++++++++++++++++++++++++++++-- 2 files changed, 215 insertions(+), 21 deletions(-) diff --git a/typescript/src/ts/validate.ts b/typescript/src/ts/validate.ts index ae16f93d..b77d9505 100644 --- a/typescript/src/ts/validate.ts +++ b/typescript/src/ts/validate.ts @@ -1,8 +1,8 @@ // TODO: Revisit these `typescript/unstable/*` imports once a stable API is available. import { API, NodeBuilderFlags, SymbolFlags, type Checker, type Diagnostic } from 'typescript/unstable/sync'; import { createVirtualFileSystem } from 'typescript/unstable/fs'; -import type { SourceFile } from 'typescript/unstable/ast'; -import { isTypeReferenceNode, isVariableStatement } from 'typescript/unstable/ast/is'; +import type { Node, SourceFile } from 'typescript/unstable/ast'; +import { isEnumDeclaration, isTypeReferenceNode, isVariableStatement } from 'typescript/unstable/ast/is'; import { Result, success, error } from '../result.js'; import { typeChatSchemaValidation, type TypeChatJsonValidator } from "../typechat.js"; @@ -45,26 +45,54 @@ const schemaValidationFileName = "/schema-validation.ts"; */ function createUniqueJsonWireTypeName(schemaText: string): string { let name = "__TypeChatJsonWire"; - while (schemaText.includes(name) || schemaText.includes(`${name}Object`) || schemaText.includes(`${name}Shape`)) { + while ( + schemaText.includes(name) || + schemaText.includes(`${name}Enum`) || + schemaText.includes(`${name}Object`) || + schemaText.includes(`${name}Shape`) + ) { name += "_"; } return name; } +/** + * Collects the string values declared by enums in the schema. Limiting the JSON wire mapping to + * these values leaves branded and opaque string types untouched. + */ +function getStringEnumValues(checker: Checker, sourceFile: SourceFile): string[] { + const values = new Set(); + sourceFile.forEachChild(function visit(node: Node) { + if (isEnumDeclaration(node)) { + for (const member of node.members) { + const value = checker.getConstantValue(member); + if (typeof value === "string") { + values.add(value); + } + } + } + node.forEachChild(visit); + }); + return [...values]; +} + /** * Maps serialized string-enum values back to their literal enum member types while preserving the * rest of the schema's structure. Class instances with private or protected members are left * unchanged because mapping their public keys would drop the nominal constraint that rejects * plain JSON objects. */ -function createJsonWireTypeDefinition(typeName: string): string { - return `type ${typeName}Object = { [K in keyof T]: ${typeName} }; +function createJsonWireTypeDefinition(typeName: string, stringEnumValues: readonly string[]): string { + const enumValues = stringEnumValues.map(value => JSON.stringify(value)).join(" | "); + return `type ${typeName}Enum = ${enumValues}; +type ${typeName}Object = { [K in keyof T]: ${typeName} }; type ${typeName}Shape = { [K in keyof T]: T[K] }; type ${typeName} = - T extends string ? \`\${T}\` : + T extends ${typeName}Enum ? \`\${T}\` : T extends (...args: any[]) => any ? T : T extends abstract new (...args: any[]) => any ? T : - T extends object ? (${typeName}Shape extends T ? ${typeName}Object : T) : T;`; + T extends object ? (${typeName}Shape extends T ? + (string extends T ? ${typeName}Object : ${typeName}Object & object) : T) : T;`; } /** @@ -118,12 +146,21 @@ export function createTypeScriptJsonValidator( [schemaValidationFileName]: "" }); const api = new API({ fs: fileSystem, cwd: "/" }); - api.updateSnapshot({ openProjects: [configFileName] }); if (!fileSystem.writeFile) { throw new Error("The TypeScript virtual file system doesn't support writing files."); } const writeFile = fileSystem.writeFile; const jsonWireTypeName = createUniqueJsonWireTypeName(schema); + const initialSnapshot = api.updateSnapshot({ openProjects: [configFileName] }); + const schemaProject = initialSnapshot.getProject(configFileName); + const schemaSourceFile = schemaProject?.program.getSourceFile(schemaFileName); + const stringEnumValues = schemaProject && schemaSourceFile + ? getStringEnumValues(schemaProject.checker, schemaSourceFile) + : []; + const jsonWireTypeDefinition = stringEnumValues.length + ? createJsonWireTypeDefinition(jsonWireTypeName, stringEnumValues) + : ""; + const jsonWireEnumValues = stringEnumValues.map(value => JSON.stringify(value)).join(" | "); let schemaValidationResult: Result | undefined; const validator: TypeScriptJsonValidatorWithSchemaValidation = { getSchemaText: () => schema, @@ -207,11 +244,13 @@ export function createTypeScriptJsonValidator( const checker = project.checker; const jsonFile = program.getSourceFile(jsonFileName); const diagnostics = programDiagnostics.map(d => { - const message = flattenDiagnosticMessageText(d, "\n"); + const message = normalizeJsonWireTypeNames(flattenDiagnosticMessageText(d, "\n")); // TS error 2740 truncates the missing-properties list to 4 items ("and N more"). // Use the type checker to reconstruct the full list of missing required properties. if (d.code === 2740 && jsonFile && d.fileName === jsonFileName) { - return expandMissingPropertiesMessage(checker, jsonFile, d.pos) ?? message; + return normalizeJsonWireTypeNames( + expandMissingPropertiesMessage(checker, jsonFile, d.pos) ?? message + ); } return message; }).join("\n"); @@ -220,6 +259,53 @@ export function createTypeScriptJsonValidator( return success(jsonObject as T); } + /** + * Removes internal helper names from diagnostics so callers and repair prompts see the schema + * type that they wrote. + */ + function normalizeJsonWireTypeNames(message: string): string { + let result = message; + let previous: string; + do { + previous = result; + for (const name of [`${jsonWireTypeName}Shape`, `${jsonWireTypeName}Object`, jsonWireTypeName]) { + result = stripTypeApplications(result, name); + } + if (jsonWireEnumValues) { + result = result.split(`${jsonWireTypeName}Enum`).join(jsonWireEnumValues); + } + } while (result !== previous); + return result; + } + + function stripTypeApplications(text: string, name: string): string { + const marker = `${name}<`; + let result = ""; + let index = 0; + while (true) { + const start = text.indexOf(marker, index); + if (start < 0) { + return result + text.slice(index); + } + result += text.slice(index, start); + let depth = 0; + let end = start + name.length; + for (; end < text.length; end++) { + if (text[end] === "<") { + depth++; + } + else if (text[end] === ">" && text[end - 1] !== "=" && --depth === 0) { + break; + } + } + if (end >= text.length) { + return result + text.slice(start); + } + result += text.slice(start + name.length + 1, end); + index = end + 1; + } + } + /** * Flattens a diagnostic and its chained messages into a single string, indenting each level of the chain. */ @@ -299,8 +385,11 @@ export function createTypeScriptJsonValidator( function createModuleTextFromJson(jsonObject: object) { // 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`); + // The JsonWire helper maps each enum value back to its string literal while recursively + // preserving object, array, tuple, optional-property, and union shapes. Numeric enums and + // enum-free schemas continue to validate against the original type. + const typeDefinition = jsonWireTypeDefinition ? `${jsonWireTypeDefinition}\n` : ""; + const jsonType = jsonWireTypeDefinition ? `${jsonWireTypeName}<${typeName}>` : typeName; + return success(`import { ${typeName} } from './schema';\n${typeDefinition}const json: ${jsonType} = ${JSON.stringify(jsonObject, undefined, 2)};\n`); } } diff --git a/typescript/test/validate.test.ts b/typescript/test/validate.test.ts index 416efa81..80478e44 100644 --- a/typescript/test/validate.test.ts +++ b/typescript/test/validate.test.ts @@ -111,9 +111,47 @@ export interface Order { currency: Currency; }`; -const callableSchema = ` +const recursiveEnumSchema = ` +export enum Phase { + Draft = "draft", + Done = "done" +} +export interface Task { + phase: Phase; + next?: Task; + history: [Phase, number]; +}`; + +const brandedStringSchema = ` +type UserId = string & { readonly __brand: "UserId" }; +export interface Response { + id: UserId; +}`; + +const objectConstraintSchema = ` +export interface Response { + value: object & { length: number }; +}`; + +const diagnosticSchema = ` +export enum State { + Active = "active" +} +export interface Item { + state: State; + count: number; +} +export interface Response { + item: Item; +}`; + +const callbackSchema = ` export interface Response { callback: () => string; +}`; + +const constructableSchema = ` +export interface Response { factory: new () => { ok: boolean }; }`; @@ -386,11 +424,17 @@ describe("createTypeScriptJsonValidator", () => { 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/); + assert.match(unknown.message, /not assignable to type/); + assert.ok(unknown.message.includes("enterprise"), "expected the rejected value in the diagnostic"); + assert.ok( + unknown.message.includes("basic") && unknown.message.includes("pro"), + "expected the accepted enum values in the diagnostic" + ); 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/); + assert.match(memberName.message, /not assignable to type/); + assert.ok(memberName.message.includes("Basic"), "expected the rejected member name in the diagnostic"); }); it("validates enums in nested objects, arrays, unions, and index signatures", () => { @@ -450,13 +494,49 @@ describe("createTypeScriptJsonValidator", () => { assert.match(invalid.message, /not assignable/); }); + it("validates enums in tuples, optional properties, and recursive schemas", () => { + const v = validatorFor(recursiveEnumSchema, "Task"); + const valid = v.validate({ + phase: "done", + next: { phase: "draft", history: ["done", 1] }, + history: ["draft", 2] + }); + assert.ok(valid.success, `expected recursive enum values to pass, got: ${valid.success ? "" : valid.message}`); + + const invalidTuple = v.validate({ phase: "draft", history: ["unknown", 1] }); + assert.ok(!invalidTuple.success, "expected an unknown tuple enum value to fail"); + + const invalidOptional = v.validate({ + phase: "draft", + next: { phase: "unknown", history: ["done", 1] }, + history: ["draft", 2] + }); + assert.ok(!invalidOptional.success, "expected an unknown optional-property enum value to fail"); + }); + + it("does not widen branded string types", () => { + const v = validatorFor(brandedStringSchema, "Response"); + const result = v.validate({ id: "plain-string" }); + assert.ok(!result.success, "expected a plain string not to satisfy a branded string type"); + assert.match(result.message, /not assignable/); + }); + + it("preserves non-primitive object constraints", () => { + const v = validatorFor(objectConstraintSchema, "Response"); + const valid = v.validate({ value: [1, 2] }); + assert.ok(valid.success, `expected an array to satisfy object with length, got: ${valid.success ? "" : valid.message}`); + + const invalid = v.validate({ value: "abc" }); + assert.ok(!invalid.success, "expected a primitive string not to satisfy object with length"); + 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 } }); + const callback = validatorFor(callbackSchema, "Response").validate({ callback: {} }); 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: {} }); + const factory = validatorFor(constructableSchema, "Response").validate({ factory: {} }); assert.ok(!factory.success, "expected an empty object not to satisfy a construct signature"); assert.match(factory.message, /not assignable/); }); @@ -474,6 +554,31 @@ describe("createTypeScriptJsonValidator", () => { assert.ok(!result.success, "expected a plain object not to satisfy a class with private members"); assert.match(result.message, /brand/); }); + + it("keeps internal helper names out of missing and excess property diagnostics", () => { + const v = validatorFor(diagnosticSchema, "Response"); + const missing = v.validate({}); + assert.ok(!missing.success, "expected a missing property to fail"); + assert.ok( + missing.message.includes("item"), + `expected the property name in the message, got: ${missing.message}` + ); + assert.ok( + !missing.message.includes("TypeChatJsonWire"), + `expected no internal type helper in the message, got: ${missing.message}` + ); + + const excess = v.validate({ item: { state: "active", count: 1, extra: true } }); + assert.ok(!excess.success, "expected an excess property to fail"); + assert.ok( + excess.message.includes("extra"), + `expected the property name in the message, got: ${excess.message}` + ); + assert.ok( + !excess.message.includes("TypeChatJsonWire"), + `expected no internal type helper in the message, got: ${excess.message}` + ); + }); }); describe("type mismatch errors (backward-compatible: unchanged code path)", () => { @@ -584,8 +689,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.match(result.data, /type __TypeChatJsonWire\s*=\s*T extends string/); - assert.ok(result.data.includes("const json: __TypeChatJsonWire =")); + assert.ok(result.data.includes("const json: Point =")); + assert.ok(!result.data.includes("TypeChatJsonWire")); }); }); From 3a144296934c08b6759bfbb4b87d985d652a1d64 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, 18 Nov 2026 09:05:12 +0800 Subject: [PATCH 6/8] fix(ts): tighten enum helper function guards --- typescript/src/ts/validate.ts | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/typescript/src/ts/validate.ts b/typescript/src/ts/validate.ts index b77d9505..feec9635 100644 --- a/typescript/src/ts/validate.ts +++ b/typescript/src/ts/validate.ts @@ -89,8 +89,8 @@ type ${typeName}Object = { [K in keyof T]: ${typeName} }; type ${typeName}Shape = { [K in keyof T]: T[K] }; type ${typeName} = T extends ${typeName}Enum ? \`\${T}\` : - T extends (...args: any[]) => any ? T : - T extends abstract new (...args: any[]) => any ? T : + T extends (...args: never[]) => unknown ? T : + T extends abstract new (...args: never[]) => unknown ? T : T extends object ? (${typeName}Shape extends T ? (string extends T ? ${typeName}Object : ${typeName}Object & object) : T) : T;`; } From f701783d64be29dc81fe01401fc0c9ee05ddad8b 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, 18 Nov 2026 10:26:15 +0800 Subject: [PATCH 7/8] fix(ts): preserve wrapper types and diagnostic values in enum mapping --- typescript/src/ts/validate.ts | 81 +++++++++++--- typescript/test/validate.test.ts | 185 +++++++++++++++++++++++++++++++ 2 files changed, 253 insertions(+), 13 deletions(-) diff --git a/typescript/src/ts/validate.ts b/typescript/src/ts/validate.ts index feec9635..bd5a69d8 100644 --- a/typescript/src/ts/validate.ts +++ b/typescript/src/ts/validate.ts @@ -43,13 +43,14 @@ const schemaValidationFileName = "/schema-validation.ts"; /** * Returns a type alias name that does not collide with identifiers in the schema. */ -function createUniqueJsonWireTypeName(schemaText: string): string { +function createUniqueJsonWireTypeName(schemaText: string, stringEnumValues: readonly string[]): string { let name = "__TypeChatJsonWire"; while ( schemaText.includes(name) || schemaText.includes(`${name}Enum`) || schemaText.includes(`${name}Object`) || - schemaText.includes(`${name}Shape`) + schemaText.includes(`${name}Shape`) || + stringEnumValues.some(value => value.includes(name)) ) { name += "_"; } @@ -92,7 +93,13 @@ type ${typeName} = T extends (...args: never[]) => unknown ? T : T extends abstract new (...args: never[]) => unknown ? T : T extends object ? (${typeName}Shape extends T ? - (string extends T ? ${typeName}Object : ${typeName}Object & object) : T) : T;`; + (string extends T + ? ${typeName}Object + : number extends T + ? ${typeName}Object + : boolean extends T + ? ${typeName}Object + : ${typeName}Object & object) : T) : T;`; } /** @@ -150,13 +157,13 @@ export function createTypeScriptJsonValidator( throw new Error("The TypeScript virtual file system doesn't support writing files."); } const writeFile = fileSystem.writeFile; - const jsonWireTypeName = createUniqueJsonWireTypeName(schema); const initialSnapshot = api.updateSnapshot({ openProjects: [configFileName] }); const schemaProject = initialSnapshot.getProject(configFileName); const schemaSourceFile = schemaProject?.program.getSourceFile(schemaFileName); const stringEnumValues = schemaProject && schemaSourceFile ? getStringEnumValues(schemaProject.checker, schemaSourceFile) : []; + const jsonWireTypeName = createUniqueJsonWireTypeName(schema, stringEnumValues); const jsonWireTypeDefinition = stringEnumValues.length ? createJsonWireTypeDefinition(jsonWireTypeName, stringEnumValues) : ""; @@ -247,7 +254,9 @@ export function createTypeScriptJsonValidator( const message = normalizeJsonWireTypeNames(flattenDiagnosticMessageText(d, "\n")); // TS error 2740 truncates the missing-properties list to 4 items ("and N more"). // Use the type checker to reconstruct the full list of missing required properties. - if (d.code === 2740 && jsonFile && d.fileName === jsonFileName) { + // The truncated message may also be a child of another diagnostic, for example an + // intersection target, so check the message as well as the error code. + if (jsonFile && d.fileName === jsonFileName && (d.code === 2740 || /and \d+ more/.test(message))) { return normalizeJsonWireTypeNames( expandMissingPropertiesMessage(checker, jsonFile, d.pos) ?? message ); @@ -264,17 +273,55 @@ export function createTypeScriptJsonValidator( * type that they wrote. */ function normalizeJsonWireTypeNames(message: string): string { - let result = message; - let previous: string; - do { - previous = result; - for (const name of [`${jsonWireTypeName}Shape`, `${jsonWireTypeName}Object`, jsonWireTypeName]) { - result = stripTypeApplications(result, name); - } + if (!jsonWireTypeDefinition) { + return message; + } + // Double-quoted spans are data values printed by TypeScript. Leave them untouched so a + // rejected value that happens to contain a helper name is reported verbatim. + return mapOutsideStringLiterals(message, segment => { + let result = segment; + let previous: string; + do { + previous = result; + for (const name of [`${jsonWireTypeName}Shape`, `${jsonWireTypeName}Object`, jsonWireTypeName]) { + result = stripTypeApplications(result, name); + } + } while (result !== previous); if (jsonWireEnumValues) { + // Replace the enum alias once. Doing this inside the loop could re-substitute a + // rejected value that spells the alias and never terminate. result = result.split(`${jsonWireTypeName}Enum`).join(jsonWireEnumValues); } - } while (result !== previous); + return result; + }); + } + + function mapOutsideStringLiterals(text: string, map: (segment: string) => string): string { + let result = ""; + let index = 0; + while (index < text.length) { + if (text[index] !== '"') { + const end = text.indexOf('"', index); + result += map(text.slice(index, end < 0 ? text.length : end)); + index = end < 0 ? text.length : end; + continue; + } + let end = index + 1; + while (end < text.length) { + if (text[end] === "\\") { + end += 2; + } + else if (text[end] === '"') { + end++; + break; + } + else { + end++; + } + } + result += text.slice(index, end); + index = end; + } return result; } @@ -303,6 +350,14 @@ export function createTypeScriptJsonValidator( } result += text.slice(start + name.length + 1, end); index = end + 1; + if (name.endsWith("Object")) { + // Drop the `& object` guard from the rendered helper so diagnostics mention the + // schema type alone. + const guard = /^\s*&\s*object\b/.exec(text.slice(index)); + if (guard) { + index += guard[0].length; + } + } } } diff --git a/typescript/test/validate.test.ts b/typescript/test/validate.test.ts index 80478e44..a8c1599a 100644 --- a/typescript/test/validate.test.ts +++ b/typescript/test/validate.test.ts @@ -169,6 +169,103 @@ export interface Response { token: Token; }`; +// Enum-bearing variants ensure the enum wire mapping does not change unrelated constraints. +const wrapperTypeSchema = ` +export enum Mode { + On = "on", + Off = "off" +} +export interface Response { + count: Number; + enabled: Boolean; + label: String; + mode: Mode; +}`; + +const objectConstraintEnumSchema = ` +export enum Mode { + On = "on" +} +export interface Response { + mode: Mode; + value: object & { length: number }; +}`; + +const brandedStringEnumSchema = ` +export enum Mode { + On = "on" +} +type UserId = string & { readonly __brand: "UserId" }; +export interface Response { + mode: Mode; + id: UserId; +}`; + +const callbackEnumSchema = ` +export enum Mode { + On = "on" +} +export interface Response { + mode: Mode; + callback: () => string; + factory: new () => { ok: boolean }; +}`; + +const classInstanceEnumSchema = ` +export enum Mode { + On = "on" +} +export class Token { + private brand!: string; + value!: string; +} +export interface Response { + mode: Mode; + token: Token; +}`; + +const numericAndStringEnumSchema = ` +export enum Priority { + Low, + High +} +export enum Mode { + On = "on" +} +export interface Config { + priority: Priority; + mode: Mode; + count: number; +}`; + +const wideEnumSchema = ` +export enum Mode { + On = "on", + Off = "off" +} +export interface Response { + mode: Mode; + m1: string; m2: string; m3: string; m4: string; + m5: string; m6: string; m7: string; +}`; + +const quotedValueSchema = ` +export enum Mode { + On = "on" +} +export interface Response { + mode: Mode; + note: "fixed"; +}`; + +const helperSpellingEnumSchema = ` +export enum Mode { + Wire = "__TypeChat" + "JsonWireEnum" +} +export interface Response { + mode: Mode; +}`; + const genericWrapperSchema = ` export interface Metadata { m1: string; m2: string; m3: string; m4: string; @@ -555,6 +652,94 @@ describe("createTypeScriptJsonValidator", () => { assert.match(result.message, /brand/); }); + it("preserves number, boolean, and string wrapper types when an enum is declared", () => { + const v = validatorFor(wrapperTypeSchema, "Response"); + const valid = v.validate({ count: 1, enabled: true, label: "x", mode: "on" }); + assert.ok(valid.success, `expected primitive wrappers to accept primitives, got: ${valid.success ? "" : valid.message}`); + + const invalid = v.validate({ count: "1", enabled: true, label: "x", mode: "on" }); + assert.ok(!invalid.success, "expected a string not to satisfy Number"); + assert.match(invalid.message, /not assignable/); + }); + + it("preserves object constraints when an enum is declared", () => { + const v = validatorFor(objectConstraintEnumSchema, "Response"); + const valid = v.validate({ mode: "on", value: [1, 2] }); + assert.ok(valid.success, `expected an array to satisfy object with length, got: ${valid.success ? "" : valid.message}`); + + const invalid = v.validate({ mode: "on", value: "abc" }); + assert.ok(!invalid.success, "expected a primitive string not to satisfy object with length"); + assert.match(invalid.message, /not assignable/); + }); + + it("does not widen branded strings when an enum is declared", () => { + const v = validatorFor(brandedStringEnumSchema, "Response"); + const result = v.validate({ mode: "on", id: "plain-string" }); + assert.ok(!result.success, "expected a plain string not to satisfy a branded string type"); + assert.match(result.message, /not assignable/); + }); + + it("preserves call and construct signatures when an enum is declared", () => { + const v = validatorFor(callbackEnumSchema, "Response"); + const callback = v.validate({ mode: "on", callback: {}, factory: {} }); + assert.ok(!callback.success, "expected an empty object not to satisfy a call signature"); + assert.match(callback.message, /not assignable/); + }); + + it("preserves class-instance constraints when an enum is declared", () => { + const v = validatorFor(classInstanceEnumSchema, "Response"); + const result = v.validate({ mode: "on", token: { value: "unbranded" } }); + assert.ok(!result.success, "expected a plain object not to satisfy a class with private members"); + assert.match(result.message, /brand/); + }); + + it("preserves numeric enums alongside string enums", () => { + const v = validatorFor(numericAndStringEnumSchema, "Config"); + const valid = v.validate({ priority: 0, mode: "on", count: 1 }); + assert.ok(valid.success, `expected valid enum values to pass, got: ${valid.success ? "" : valid.message}`); + + const invalid = v.validate({ priority: 5, mode: "on", count: 1 }); + 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 when a string enum is declared", () => { + const v = validatorFor(numericAndStringEnumSchema, "Config"); + const result = v.validate({ priority: 0, mode: "on", count: "two" }); + assert.ok(!result.success, "expected an unrelated type error to fail validation"); + assert.match(result.message, /not assignable/); + }); + + it("expands the full missing-property list for a normalized target", () => { + const v = validatorFor(wideEnumSchema, "Response"); + const result = v.validate({}); + assert.ok(!result.success, "expected missing properties to fail"); + for (const name of ["mode", "m1", "m2", "m3", "m4", "m5", "m6", "m7"]) { + assert.ok(result.message.includes(name), `expected '${name}' in the message, got: ${result.message}`); + } + assert.ok(result.message.includes("Response"), `expected the original target type, got: ${result.message}`); + assert.ok(!/and \d+ more/.test(result.message), `expected the complete list, got: ${result.message}`); + assert.ok(!result.message.includes("TypeChatJsonWire"), `expected no helper name, got: ${result.message}`); + }); + + it("preserves quoted values that resemble helper names", () => { + const v = validatorFor(quotedValueSchema, "Response"); + const result = v.validate({ mode: "on", note: "__TypeChatJsonWireObject" }); + assert.ok(!result.success, "expected a fixed literal to reject another value"); + assert.ok( + result.message.includes("__TypeChatJsonWireObject"), + `expected the rejected value verbatim, got: ${result.message}` + ); + }); + + it("terminates when an enum value spells the helper alias", () => { + const v = validatorFor(helperSpellingEnumSchema, "Response"); + const result = v.validate({ mode: "other" }); + assert.ok(!result.success, "expected an unknown enum value to fail"); + assert.ok(result.message.length < 2000, `expected a bounded diagnostic, got ${result.message.length} chars`); + assert.ok(!result.message.includes('""__TypeChat'), "expected no repeated quoting"); + }); + it("keeps internal helper names out of missing and excess property diagnostics", () => { const v = validatorFor(diagnosticSchema, "Response"); const missing = v.validate({}); From 117af85f729431ea0554df14b2eab31b3da3ff47 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, 18 Nov 2026 15:03:21 +0800 Subject: [PATCH 8/8] fix(ts): scope diagnostic expansion and preserve literal type arguments --- typescript/src/ts/validate.ts | 175 ++++++++++++++++++------------- typescript/test/validate.test.ts | 73 +++++++++++++ 2 files changed, 176 insertions(+), 72 deletions(-) diff --git a/typescript/src/ts/validate.ts b/typescript/src/ts/validate.ts index bd5a69d8..baf9c610 100644 --- a/typescript/src/ts/validate.ts +++ b/typescript/src/ts/validate.ts @@ -251,23 +251,37 @@ export function createTypeScriptJsonValidator( const checker = project.checker; const jsonFile = program.getSourceFile(jsonFileName); const diagnostics = programDiagnostics.map(d => { - const message = normalizeJsonWireTypeNames(flattenDiagnosticMessageText(d, "\n")); // TS error 2740 truncates the missing-properties list to 4 items ("and N more"). // Use the type checker to reconstruct the full list of missing required properties. - // The truncated message may also be a child of another diagnostic, for example an - // intersection target, so check the message as well as the error code. - if (jsonFile && d.fileName === jsonFileName && (d.code === 2740 || /and \d+ more/.test(message))) { - return normalizeJsonWireTypeNames( - expandMissingPropertiesMessage(checker, jsonFile, d.pos) ?? message - ); + // The truncated diagnostic may be a child of another one, for example an + // intersection target, so search the message chain rather than the rendered text. + const truncated = findDiagnosticWithCode(d, 2740); + if (jsonFile && truncated?.fileName === jsonFileName) { + const expanded = expandMissingPropertiesMessage(checker, jsonFile, truncated.pos, truncated.text); + if (expanded) { + return normalizeJsonWireTypeNames(expanded); + } } - return message; + return normalizeJsonWireTypeNames(flattenDiagnosticMessageText(d, "\n")); }).join("\n"); return error(diagnostics, { data: jsonObject }); } return success(jsonObject as T); } + function findDiagnosticWithCode(diagnostic: Diagnostic, code: number): Diagnostic | undefined { + if (diagnostic.code === code) { + return diagnostic; + } + for (const child of diagnostic.messageChain ?? []) { + const match = findDiagnosticWithCode(child, code); + if (match) { + return match; + } + } + return undefined; + } + /** * Removes internal helper names from diagnostics so callers and repair prompts see the schema * type that they wrote. @@ -276,89 +290,93 @@ export function createTypeScriptJsonValidator( if (!jsonWireTypeDefinition) { return message; } - // Double-quoted spans are data values printed by TypeScript. Leave them untouched so a - // rejected value that happens to contain a helper name is reported verbatim. - return mapOutsideStringLiterals(message, segment => { - let result = segment; - let previous: string; - do { - previous = result; - for (const name of [`${jsonWireTypeName}Shape`, `${jsonWireTypeName}Object`, jsonWireTypeName]) { - result = stripTypeApplications(result, name); - } - } while (result !== previous); - if (jsonWireEnumValues) { - // Replace the enum alias once. Doing this inside the loop could re-substitute a - // rejected value that spells the alias and never terminate. - result = result.split(`${jsonWireTypeName}Enum`).join(jsonWireEnumValues); - } - return result; - }); + return normalizeDiagnosticText(message); } - function mapOutsideStringLiterals(text: string, map: (segment: string) => string): string { + /** + * Unwraps helper type applications while leaving double-quoted values verbatim. Type arguments + * can themselves contain string literals, so a quoted span never terminates an enclosing + * application. + */ + function normalizeDiagnosticText(text: string): string { + const names = [`${jsonWireTypeName}Shape`, `${jsonWireTypeName}Object`, jsonWireTypeName]; let result = ""; let index = 0; while (index < text.length) { - if (text[index] !== '"') { - const end = text.indexOf('"', index); - result += map(text.slice(index, end < 0 ? text.length : end)); - index = end < 0 ? text.length : end; + if (text[index] === '"') { + const end = skipStringLiteral(text, index); + result += text.slice(index, end); + index = end; continue; } - let end = index + 1; - while (end < text.length) { - if (text[end] === "\\") { - end += 2; + let matched = false; + for (const name of names) { + if (!text.startsWith(name, index) || text[index + name.length] !== "<") { + continue; } - else if (text[end] === '"') { - end++; - break; + const end = findTypeArgumentEnd(text, index + name.length); + if (end < 0) { + continue; } - else { - end++; + result += normalizeDiagnosticText(text.slice(index + name.length + 1, end)); + index = end + 1; + if (name.endsWith("Object")) { + // Drop the `& object` guard from the rendered helper so diagnostics mention + // the schema type alone. + const guard = /^\s*&\s*object\b/.exec(text.slice(index)); + if (guard) { + index += guard[0].length; + } } + matched = true; + break; + } + if (matched) { + continue; + } + const enumName = `${jsonWireTypeName}Enum`; + if (jsonWireEnumValues && text.startsWith(enumName, index)) { + // Replace the alias once. Re-scanning the substituted text could turn a value + // that spells the alias into an unbounded expansion. + result += jsonWireEnumValues; + index += enumName.length; + continue; } - result += text.slice(index, end); - index = end; + result += text[index++]; } return result; } - function stripTypeApplications(text: string, name: string): string { - const marker = `${name}<`; - let result = ""; - let index = 0; - while (true) { - const start = text.indexOf(marker, index); - if (start < 0) { - return result + text.slice(index); + function skipStringLiteral(text: string, start: number): number { + let index = start + 1; + while (index < text.length) { + if (text[index] === "\\") { + index += 2; } - result += text.slice(index, start); - let depth = 0; - let end = start + name.length; - for (; end < text.length; end++) { - if (text[end] === "<") { - depth++; - } - else if (text[end] === ">" && text[end - 1] !== "=" && --depth === 0) { - break; - } + else if (text[index] === '"') { + return index + 1; } - if (end >= text.length) { - return result + text.slice(start); + else { + index++; } - result += text.slice(start + name.length + 1, end); - index = end + 1; - if (name.endsWith("Object")) { - // Drop the `& object` guard from the rendered helper so diagnostics mention the - // schema type alone. - const guard = /^\s*&\s*object\b/.exec(text.slice(index)); - if (guard) { - index += guard[0].length; - } + } + return text.length; + } + + function findTypeArgumentEnd(text: string, openBracket: number): number { + let depth = 0; + for (let index = openBracket; index < text.length; index++) { + if (text[index] === '"') { + index = skipStringLiteral(text, index) - 1; + } + else if (text[index] === "<") { + depth++; + } + else if (text[index] === ">" && text[index - 1] !== "=" && --depth === 0) { + return index; } } + return -1; } /** @@ -402,7 +420,13 @@ export function createTypeScriptJsonValidator( * variable declaration at `position` in `file`. Returns `undefined` if the declaration * cannot be located or yields no missing properties (fallback to the original message). */ - function expandMissingPropertiesMessage(checker: Checker, file: SourceFile, position: number): string | undefined { + function expandMissingPropertiesMessage( + checker: Checker, + file: SourceFile, + position: number, + diagnosticText: string + ): string | undefined { + const reportedTarget = / from type '(.+)': /.exec(diagnosticText)?.[1]; for (const stmt of file.statements) { if (isVariableStatement(stmt)) { for (const decl of stmt.declarationList.declarations) { @@ -429,6 +453,13 @@ export function createTypeScriptJsonValidator( if (missingProps.length > 0) { const srcStr = checker.typeToString(sourceType, undefined, NodeBuilderFlags.NoTruncation); const tgtStr = checker.typeToString(targetType, undefined, NodeBuilderFlags.NoTruncation); + // A nested diagnostic reports the nested type. Expanding it here + // would replace it with the outer declaration's missing properties. + if (reportedTarget !== undefined && + reportedTarget !== tgtStr && + reportedTarget !== `${jsonWireTypeName}Object<${tgtStr}>`) { + continue; + } return `Type '${srcStr}' is missing the following properties from type '${tgtStr}': ${missingProps.join(", ")}`; } } diff --git a/typescript/test/validate.test.ts b/typescript/test/validate.test.ts index a8c1599a..571d64d2 100644 --- a/typescript/test/validate.test.ts +++ b/typescript/test/validate.test.ts @@ -266,6 +266,43 @@ export interface Response { mode: Mode; }`; +const literalTypeSchema = ` +export enum Mode { + On = "on" +} +export interface Box { + value: T; +} +export interface Response { + mode: Mode; + box: Box<"fixed">; + item: { kind: "fixed"; count: number }; +}`; + +const andMoreValueSchema = ` +export enum Mode { + On = "on" +} +export interface Response { + mode: Mode; + note: "fixed"; + extra: string; +}`; + +const nestedMissingSchema = ` +export enum Mode { + On = "on" +} +export interface LargeItem { + m1: string; m2: string; m3: string; m4: string; + m5: string; m6: string; m7: string; +} +export interface Response { + mode: Mode; + item: LargeItem; + extra: string; +}`; + const genericWrapperSchema = ` export interface Metadata { m1: string; m2: string; m3: string; m4: string; @@ -740,6 +777,42 @@ describe("createTypeScriptJsonValidator", () => { assert.ok(!result.message.includes('""__TypeChat'), "expected no repeated quoting"); }); + it("unwraps literal-bearing type arguments without rewriting them", () => { + const v = validatorFor(literalTypeSchema, "Response"); + const result = v.validate({ + mode: "on", + box: "not-an-object", + item: { kind: "fixed", count: 1 } + }); + assert.ok(!result.success, "expected literal type errors to fail"); + assert.ok( + !result.message.includes("TypeChatJsonWire"), + `expected no helper name, got: ${result.message}` + ); + assert.ok( + result.message.includes('Box<"fixed">'), + `expected the literal type argument to be preserved, got: ${result.message}` + ); + }); + + it("does not treat a value containing 'and N more' as a truncated list", () => { + const v = validatorFor(andMoreValueSchema, "Response"); + const result = v.validate({ note: "and 5 more" }); + assert.ok(!result.success, "expected the literal value to fail"); + assert.ok( + result.message.includes("and 5 more"), + `expected the rejected value to survive, got: ${result.message}` + ); + }); + + it("keeps nested missing-property diagnostics scoped to the nested type", () => { + const v = validatorFor(nestedMissingSchema, "Response"); + const result = v.validate({ mode: "on", item: {} }); + assert.ok(!result.success, "expected missing nested properties to fail"); + assert.ok(result.message.includes("LargeItem"), `expected the nested type, got: ${result.message}`); + assert.ok(result.message.includes("m1"), `expected a nested property name, got: ${result.message}`); + }); + it("keeps internal helper names out of missing and excess property diagnostics", () => { const v = validatorFor(diagnosticSchema, "Response"); const missing = v.validate({});