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

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
25 changes: 25 additions & 0 deletions site/src/docs/typescript/basic-usage.md
Original file line number Diff line number Diff line change
Expand Up @@ -308,6 +308,31 @@ const validator = createTypeScriptJsonValidator<SentimentResponse>(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:
Expand Down
38 changes: 36 additions & 2 deletions typescript/src/ts/validate.ts
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,29 @@ 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): 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> =
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[K]> } : T;`;

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Preserve class-instance constraints when recursively normalizing enum values.

keyof T excludes private/protected members, so rebuilding every object as a mapped type also strips class-instance constraints. This is another case where normalization accepts JSON that the original schema rejects, even when there are no enums.

From the TypeScript package directory, run npm run build, then save the following as repro-enum-wire.cjs in that directory and run node repro-enum-wire.cjs:

const { createTypeScriptJsonValidator } = require("typechat/ts");

const schema = `
export class Token {
    private brand!: string;
    value!: string;
}
export interface Response {
    token: Token;
}`;

const validator = createTypeScriptJsonValidator(schema, "Response");
const input = { token: { value: "unbranded" } };

try {
    console.log("PR generator:", validator.validate(input));

    // Restore the pre-PR assignment generator as a control.
    validator.createModuleTextFromJson = value => ({
        success: true,
        data: `import { Response } from './schema';
const json: Response = ${JSON.stringify(value)};`
    });
    console.log("Pre-PR assignment:", validator.validate(input));
} finally {
    validator.close();
}

On 05788e4, the first result has success: true. The control has success: false with:

Property 'brand' is missing in type '{ value: string; }' but required in type 'Token'.

The expected behavior is rejection in both cases: this JSON does not satisfy the original Token type. Please preserve that rejection while normalizing enums, and add negative regression coverage for class-instance constraints in an enum-free schema. Keep the existing serialized-enum cases passing.

}
Comment on lines +58 to +64

/**
* Represents an object that can validate JSON strings according to a given TypeScript schema.
*/
Expand Down Expand Up @@ -96,6 +119,7 @@ export function createTypeScriptJsonValidator<T extends object = object>(
throw new Error("The TypeScript virtual file system doesn't support writing files.");
}
const writeFile = fileSystem.writeFile;
const jsonWireTypeName = createUniqueJsonWireTypeName(schema);
let schemaValidationResult: Result<void> | undefined;
const validator: TypeScriptJsonValidatorWithSchemaValidation<T> = {
getSchemaText: () => schema,
Expand Down Expand Up @@ -241,7 +265,14 @@ export function createTypeScriptJsonValidator<T extends object = object>(
// 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;
Expand All @@ -263,6 +294,9 @@ export function createTypeScriptJsonValidator<T extends object = object>(
}

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`);
}
}
207 changes: 206 additions & 1 deletion typescript/test/validate.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -48,6 +48,92 @@ 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 callableSchema = `
export interface Response {
callback: () => string;
factory: new () => { ok: boolean };
}`;

const promiseSchema = `
export interface Response {
value: Promise<string>;
}`;

const genericWrapperSchema = `
export interface Metadata {
m1: string; m2: string; m3: string; m4: string;
m5: string; m6: string; m7: string;
}
export interface Wrapper<T> {
a: string; b: string; c: string; d: string;
e: string; f: string; g: string; payload: T;
}
export type Response = Wrapper<Metadata>;
`;

// ---------------------------------------------------------------------------
// Helper
// ---------------------------------------------------------------------------
Expand Down Expand Up @@ -280,6 +366,100 @@ 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/);
});
Comment on lines +376 to +385

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("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/);
Comment on lines +445 to +452
});

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/);
});
});

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");
Expand Down Expand Up @@ -388,7 +568,32 @@ 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> = T extends string"));

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Make this assertion independent of helper formatting.

The latest commit emits type __TypeChatJsonWire<T> = followed by a newline and indentation before T extends string. This exact single-line substring therefore no longer exists, and the validator suite fails.

From the TypeScript package directory, the focused reproduction is:

npm run build
npm exec --no -- tsc -p test
node --test --test-name-pattern="produces valid TypeScript module text for a simple object" .\out\validate.test.js

It fails at this assertion with ERR_ASSERTION. A standalone JavaScript reproduction, after building, is below; save it as repro-module-text.cjs in the same directory and run node repro-module-text.cjs:

const assert = require("node:assert/strict");
const { createTypeScriptJsonValidator } = require("typechat/ts");

const validator = createTypeScriptJsonValidator(
    "export interface Point { x: number; y: number; }",
    "Point"
);
try {
    const result = validator.createModuleTextFromJson({ x: 1, y: 2 });
    assert.ok(result.success);
    console.log(JSON.stringify(result.data));
    assert.ok(
        result.data.includes("type __TypeChatJsonWire<T> = T extends string")
    );
} finally {
    validator.close();
}

Please use a whitespace-independent assertion, for example:

assert.match(result.data, /type __TypeChatJsonWire<T>\s*=\s*T extends string/);

On Node 24.22.1 / TypeScript 7.0.2, the full focused validator file currently has 59 passes and this one failure. Please rerun it after the update and refresh the PR's validation results.

assert.ok(result.data.includes("const json: __TypeChatJsonWire<Point> ="));
});
});

describe("missing-property diagnostics with custom module text", () => {
it("keeps a custom generic annotation as the diagnostic target", () => {
const v = validatorFor<Record<string, unknown>>(genericWrapperSchema, "Response");
v.createModuleTextFromJson = value => ({
success: true,
data: `import { Wrapper, Metadata } from './schema';\n` +
`const json: Wrapper<Metadata> = ${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<Metadata>/);
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}`
);
});
});

Expand Down