diff --git a/site/src/docs/typescript/basic-usage.md b/site/src/docs/typescript/basic-usage.md index 1da0adb3..5e0df32b 100644 --- a/site/src/docs/typescript/basic-usage.md +++ b/site/src/docs/typescript/basic-usage.md @@ -308,6 +308,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 550d6158..baf9c610 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"; @@ -40,6 +40,68 @@ const schemaFileName = "/schema.ts"; const jsonFileName = "/json.ts"; const schemaValidationFileName = "/schema-validation.ts"; +/** + * Returns a type alias name that does not collide with identifiers in the schema. + */ +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`) || + stringEnumValues.some(value => value.includes(name)) + ) { + 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, 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 ${typeName}Enum ? \`\${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 + : number extends T + ? ${typeName}Object + : boolean extends T + ? ${typeName}Object + : ${typeName}Object & object) : T) : T;`; +} + /** * Represents an object that can validate JSON strings according to a given TypeScript schema. */ @@ -91,11 +153,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 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) + : ""; + const jsonWireEnumValues = stringEnumValues.map(value => JSON.stringify(value)).join(" | "); let schemaValidationResult: Result | undefined; const validator: TypeScriptJsonValidatorWithSchemaValidation = { getSchemaText: () => schema, @@ -179,19 +251,134 @@ export function createTypeScriptJsonValidator( const checker = project.checker; const jsonFile = program.getSourceFile(jsonFileName); const diagnostics = programDiagnostics.map(d => { - const message = 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; + // 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. + */ + function normalizeJsonWireTypeNames(message: string): string { + if (!jsonWireTypeDefinition) { + return message; + } + return normalizeDiagnosticText(message); + } + + /** + * 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 = skipStringLiteral(text, index); + result += text.slice(index, end); + index = end; + continue; + } + let matched = false; + for (const name of names) { + if (!text.startsWith(name, index) || text[index + name.length] !== "<") { + continue; + } + const end = findTypeArgumentEnd(text, index + name.length); + if (end < 0) { + continue; + } + 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[index++]; + } + return result; + } + + function skipStringLiteral(text: string, start: number): number { + let index = start + 1; + while (index < text.length) { + if (text[index] === "\\") { + index += 2; + } + else if (text[index] === '"') { + return index + 1; + } + else { + index++; + } + } + 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; + } + /** * Flattens a diagnostic and its chained messages into a single string, indenting each level of the chain. */ @@ -233,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) { @@ -241,7 +434,14 @@ export function createTypeScriptJsonValidator( // 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); + // 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) { continue; @@ -253,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(", ")}`; } } @@ -263,6 +470,12 @@ export function createTypeScriptJsonValidator( } 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 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 cfdece22..571d64d2 100644 --- a/typescript/test/validate.test.ts +++ b/typescript/test/validate.test.ts @@ -48,6 +48,273 @@ 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; +}`; + +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 }; +}`; + +const promiseSchema = ` +export interface Response { + value: Promise; +}`; + +const classInstanceSchema = ` +export class Token { + private brand!: string; + value!: string; +} +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 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; + 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 // --------------------------------------------------------------------------- @@ -280,6 +547,298 @@ 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 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 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", () => { + 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/); + }); + + 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 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 = 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/); + }); + + it("preserves rejection of Promise-shaped objects with non-callable methods", () => { + const v = validatorFor(promiseSchema, "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/); + }); + + 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/); + }); + + 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("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({}); + 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)", () => { it("reports a type error when a property has the wrong type", () => { const v = validatorFor(smallSchema, "Point"); @@ -389,6 +948,31 @@ describe("createTypeScriptJsonValidator", () => { 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("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}` + ); }); });