Skip to content

Commit

Permalink
fix: fix for #203
Browse files Browse the repository at this point in the history
* test: adding failing test-case

* test: fix test syntax

* refacto: reorganise file

* fix: unit test passes

* clean: prettying

* test: adding more test cases

* doc: adding comment
  • Loading branch information
tvillaren committed Feb 19, 2024
1 parent 4bd5972 commit 06f52a3
Show file tree
Hide file tree
Showing 2 changed files with 201 additions and 8 deletions.
174 changes: 173 additions & 1 deletion src/core/validateGeneratedTypes.test.ts
Expand Up @@ -97,6 +97,124 @@ describe("validateGeneratedTypes", () => {
expect(errors).toEqual([]);
});

it("should return no error if we reference a non-imported type", () => {
const sourceTypes = {
sourceText: `
export type Villain = {
name: string;
}
export type Citizen = {
villain: Villain | null;
};
`,
relativePath: "source.ts",
};

const zodSchemas = {
sourceText: `// Generated by ts-to-zod
import { z } from "zod";
export const villainSchema = z.object({
name: z.string()
});
export const citizenSchema = z.object({
villain: villainSchema.nullable()
});
`,
relativePath: "source.zod.ts",
};

const integrationTests = {
sourceText: `// Generated by ts-to-zod
import { z } from "zod";
import * as spec from "./${sourceTypes.relativePath.slice(0, -3)}";
import * as generated from "./${zodSchemas.relativePath.slice(0, -3)}";
// eslint-disable-next-line @typescript-eslint/no-unused-vars
function expectType<T>(_: T) {
/* noop */
}
export type CitizenInferredType = z.infer<typeof generated.citizenSchema>;
expectType<CitizenInferredType>({} as spec.Citizen);
expectType<spec.Citizen>({} as CitizenInferredType);
`,
relativePath: "source.integration.ts",
};

const errors = validateGeneratedTypes({
sourceTypes,
zodSchemas,
integrationTests,
skipParseJSDoc: false,
});

expect(errors).toEqual([]);
});

it("should return no error if we reference a non-imported type in an Array", () => {
const sourceTypes = {
sourceText: `
export type Villain = {
name: string;
}
export type Citizen = {
villains: Array<Villain>;
};
`,
relativePath: "source.ts",
};

const zodSchemas = {
sourceText: `// Generated by ts-to-zod
import { z } from "zod";
export const villainSchema = z.object({
name: z.string()
});
export const citizenSchema = z.object({
villains: z.array(villainSchema)
});
`,
relativePath: "source.zod.ts",
};

const integrationTests = {
sourceText: `// Generated by ts-to-zod
import { z } from "zod";
import * as spec from "./${sourceTypes.relativePath.slice(0, -3)}";
import * as generated from "./${zodSchemas.relativePath.slice(0, -3)}";
// eslint-disable-next-line @typescript-eslint/no-unused-vars
function expectType<T>(_: T) {
/* noop */
}
export type CitizenInferredType = z.infer<typeof generated.citizenSchema>;
expectType<CitizenInferredType>({} as spec.Citizen);
expectType<spec.Citizen>({} as CitizenInferredType);
`,
relativePath: "source.integration.ts",
};

const errors = validateGeneratedTypes({
sourceTypes,
zodSchemas,
integrationTests,
skipParseJSDoc: false,
});

expect(errors).toEqual([]);
});

it("should return no error if we use a 'deep' non-optional any", () => {
const sourceTypes = {
sourceText: `
Expand Down Expand Up @@ -155,7 +273,7 @@ describe("validateGeneratedTypes", () => {
expect(errors).toEqual([]);
});

it("should return no error if we use an external import", () => {
it("should return no error if we reference an external import", () => {
const sourceTypes = {
sourceText: `
import { Hero } from "./hero-module.ts"
Expand Down Expand Up @@ -209,6 +327,60 @@ describe("validateGeneratedTypes", () => {
expect(errors).toEqual([]);
});

it("should return no error if we reference an array of external imports", () => {
const sourceTypes = {
sourceText: `
import { Hero } from "./hero-module.ts"
export interface Citizen {
heros: Array<Hero>
};
`,
relativePath: "source.ts",
};

const zodSchemas = {
sourceText: `// Generated by ts-to-zod
import { z } from "zod";
const heroSchema = z.any();
export const citizenSchema = z.object({
heros: z.array(heroSchema)
});
`,
relativePath: "source.zod.ts",
};

const integrationTests = {
sourceText: `// Generated by ts-to-zod
import { z } from "zod";
import * as spec from "./${sourceTypes.relativePath.slice(0, -3)}";
import * as generated from "./${zodSchemas.relativePath.slice(0, -3)}";
// eslint-disable-next-line @typescript-eslint/no-unused-vars
function expectType<T>(_: T) {
/* noop */
}
export type CitizenInferredType = z.infer<typeof generated.citizenSchema>;
expectType<CitizenInferredType>({} as spec.Citizen);
expectType<spec.Citizen>({} as CitizenInferredType);
`,
relativePath: "source.integration.ts",
};

const errors = validateGeneratedTypes({
sourceTypes,
zodSchemas,
integrationTests,
skipParseJSDoc: false,
});

expect(errors).toEqual([]);
});

it("should return no error if we use a deep external import", () => {
const sourceTypes = {
sourceText: `
Expand Down
35 changes: 28 additions & 7 deletions src/utils/fixOptionalAny.ts
@@ -1,17 +1,39 @@
import ts, { factory as f } from "typescript";
import { getImportIdentifiers } from "./importHandling";

/**
* Add optional property to `any` to workaround comparison issue.
* Add optional property to `any` or imported types to workaround comparison issue.
*
* ref:
* -> https://github.com/fabien0102/ts-to-zod/issues/140
* -> https://github.com/fabien0102/ts-to-zod/issues/203
*
* ref: https://github.com/fabien0102/ts-to-zod/issues/140
*/
export function fixOptionalAny(sourceText: string) {
const sourceFile = ts.createSourceFile(
"index.ts",
sourceText,
ts.ScriptTarget.Latest
);
const printer = ts.createPrinter({ newLine: ts.NewLineKind.LineFeed });

// Extracting imports
const importNamesAvailable = new Set<string>();
const extractImportIdentifiers = (node: ts.Node) => {
if (ts.isImportDeclaration(node) && node.importClause) {
const identifiers = getImportIdentifiers(node);
identifiers.forEach((i) => importNamesAvailable.add(i));
}
};
ts.forEachChild(sourceFile, extractImportIdentifiers);

function shouldAddQuestionToken(node: ts.TypeNode) {
return (
node.kind === ts.SyntaxKind.AnyKeyword ||
// Handling type referencing imported types
(ts.isTypeReferenceNode(node) &&
importNamesAvailable.has(node.typeName.getText(sourceFile)))
);
}

const markAnyAsOptional: ts.TransformerFactory<ts.SourceFile> = (context) => {
const visit: ts.Visitor = (node) => {
Expand Down Expand Up @@ -42,15 +64,14 @@ export function fixOptionalAny(sourceText: string) {
return (sourceFile) => ts.visitNode(sourceFile, visit) as ts.SourceFile;
};

// Apply transformation
const outputFile = ts.transform(sourceFile, [markAnyAsOptional]);

// Printing the transformed file
const printer = ts.createPrinter({ newLine: ts.NewLineKind.LineFeed });
return printer.printFile(outputFile.transformed[0]);
}

function shouldAddQuestionToken(node: ts.TypeNode) {
return node.kind === ts.SyntaxKind.AnyKeyword || ts.isTypeReferenceNode(node);
}

function createOptionalPropertyNode(node: ts.PropertySignature) {
return ts.factory.createPropertySignature(
node.modifiers,
Expand Down

0 comments on commit 06f52a3

Please sign in to comment.