Skip to content
Merged
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
5 changes: 5 additions & 0 deletions nx.json
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,11 @@
},
"@nx/eslint:lint": {
"inputs": ["default", "{workspaceRoot}/.eslintrc.json"]
},
"@nx/js:tsc": {
"cache": true,
"dependsOn": ["^build"],
"inputs": ["production", "^production"]
}
},
"namedInputs": {
Expand Down
2,632 changes: 1,343 additions & 1,289 deletions package-lock.json

Large diffs are not rendered by default.

6 changes: 5 additions & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,8 @@
"object-hash": "3.0.0",
"tslib": "^2.3.0",
"yaml": "2.8.0",
"yargs": "18.0.0"
"yargs": "18.0.0",
"zod": ">=3.22.0"
},
"devDependencies": {
"@commitlint/cli": "^19.8.1",
Expand All @@ -25,6 +26,9 @@
"@nx/js": "21.6.4",
"@nx/node": "21.6.4",
"@nx/workspace": "21.6.4",
"@swc-node/register": "~1.9.1",
"@swc/core": "~1.5.7",
"@swc/helpers": "~0.5.11",
"@types/jest": "30.0.0",
"@types/lodash": "4.17.17",
"@types/node": "^24.0.3",
Expand Down
215 changes: 215 additions & 0 deletions plugins/zod/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,215 @@
# @leancodepl/contractsgenerator-typescript-plugin-zod

Plugin for generating Zod schemas for DTOs (Data Transfer Objects), Commands, Queries, Operations, Topics, and Enums.

## Config

- `input` - configuration passed to [Contracts Generator Server](https://github.com/leancodepl/contractsgenerator). All
paths are relative to directory from your current CWD. Unless you are using JavaScript files - in that case you can
use `__dirname` and `path.join`/`path.resolve` for paths relative to configuration file.
- `base` - base path for your backend code source. If you provide that then all the other properties are relative to
this directory.

Then you can provide one of:
- `file`
or
- `include` and `exclude` - single globs or arrays of globs to match specific .cs files
or
- `project` - can be multiple

For details on these options please refer to
[Contracts Generator Server](https://github.com/leancodepl/contractsgenerator).

- `customTypes` - dictionary of custom types configuration where keys are the name of Known Type and value is custom
type name. Valid custom types include: String, Guid, Uri, Boolean, UInt8, Int8, Int16, UInt16, Int32, UInt32, Int64,
UInt64, Float32, Float64, DateOnly, TimeOnly, DateTimeOffset, TimeSpan.

- `nameTransform` - function `(fullName: string) => string | undefined` which allows you to transform full name of the
DTO (like `LeanCode.Core.Contracts.User.UserDetailsDTO`). This is especially useful when you want to map namespaces,
for e.g. when you have conflicts, want to remove parts of the namespace (`LeanCode.Core.User.UserDetailsDTO` instead
of `LeanCode.Core.`**`Contracts`**`.User.UserDetailsDTO`). If the function returns `undefined`, the DTO is not
included in the output.

- `fieldValidation` - function `(fieldPath: string, property: FieldValidationContext) => string | undefined` which
allows you to provide custom validation logic for specific fields. The function receives:
- `fieldPath`: Full path to the field (e.g., `"ExampleApp.Examples.Contracts.Booking.LocationDTO.Latitude"`)
- `property`: An object containing:
- `name`: Name of the property (e.g., `"Latitude"`)
- `isNullable`: Boolean indicating if the property is nullable
- `type`: The property type (`"string" | "number" | "boolean" | "array" | "object" | "enum" | "unknown"`)
- Returns: A string containing additional Zod validation code (e.g., `".min(1)"`, `".positive().max(90)"`), or
`undefined` to use the default schema. The string will be appended to the default schema code.

## Features

- Generates Zod schemas for DTOs, Commands, Queries, Operations, Topics, and Enums
- Uses PascalCase naming convention for schema names (e.g., `LocationDTO` → `LocationDTOSchema`)
- Maintains namespace structure based on nameTransform
- Handles nullable properties with `.nullable()`
- Supports interface inheritance with `.extend()`
- Handles generic types and arrays
- Generates enum schemas as `z.enum()` with metadata (values mapping and comments)
- Adds comments and attributes to `.meta()` for interfaces and enums
- Validates duplicate names in namespaces (same as contracts plugin)

## Example

### Config

```js
module.exports = {
generates: {
"schemas.ts": {
plugins: ["zod"],
},
},
config: {
input: {
base: "../../../backend/src",
project: ["Core/Project.Core.Contracts/Project.Core.Contracts.csproj"],
},
},
}
```

### Output

```typescript
import { z } from "zod"

export namespace ExampleApp {
export namespace Examples {
export namespace Contracts {
export namespace Booking {
export const LocationDTOSchema = z.object({
Latitude: z.number(),
Longitude: z.number(),
})

export const MoneyDTOSchema = z.object({
Value: z.number(),
Currency: z.string(),
})

export const ServiceProviderTypeDTOSchema = z.enum({ Hairdresser: 0, BarberShop: 1, Groomer: 2 }).meta({
"meta:enum": { Hairdresser: 0, BarberShop: 1, Groomer: 2 },
})

export const MyReservationDTOSchema = z.object({
Id: z.string(),
Location: ExampleApp.Examples.Contracts.Booking.LocationDTOSchema,
Price: ExampleApp.Examples.Contracts.Booking.MoneyDTOSchema,
Type: ExampleApp.Examples.Contracts.Booking.ServiceProviderTypeDTOSchema,
})
}
}
}
}
```

### With nameTransform

```js
module.exports = {
generates: {
"schemas.ts": {
plugins: ["zod"],
},
},
config: {
input: {
base: "../../../backend/src",
project: ["Core/Project.Core.Contracts/Project.Core.Contracts.csproj"],
},
nameTransform: nameWithNamespace => nameWithNamespace.split(".").at(-1),
},
}
```

Output:

```typescript
import { z } from "zod"

export const LocationDTOSchema = z.object({
Latitude: z.number(),
Longitude: z.number(),
})

export const MoneyDTOSchema = z.object({
Value: z.number(),
Currency: z.string(),
})

export const ServiceProviderTypeDTOSchema = z.enum({ Hairdresser: 0, BarberShop: 1, Groomer: 2 }).meta({
"meta:enum": { Hairdresser: 0, BarberShop: 1, Groomer: 2 },
})

export const MyReservationDTOSchema = z.object({
Id: z.string(),
Location: LocationDTOSchema,
Price: MoneyDTOSchema,
Type: ServiceProviderTypeDTOSchema,
})
```

### With fieldValidation

```js
module.exports = {
generates: {
"schemas.ts": {
plugins: ["zod"],
},
},
config: {
input: {
base: "../../../backend/src",
project: ["Core/Project.Core.Contracts/Project.Core.Contracts.csproj"],
},
fieldValidation: (fieldPath, property) => {
// Add min length validation for string fields named "Name"
if (property.name === "Name" && property.type === "string") {
return ".min(1)"
}
// Add positive number validation for coordinates
if (
(property.name === "Latitude" || property.name === "Longitude") &&
property.type === "number" &&
fieldPath.includes("LocationDTO")
) {
return ".positive().max(90)"
}
// Add custom refine validation with options
if (property.name === "Value" && property.type === "number") {
return '.refine(val => val > 0, { message: "Must be positive" })'
}
return undefined
},
},
}
```

Output:

```typescript
import { z } from "zod"

export namespace ExampleApp {
export namespace Examples {
export namespace Contracts {
export namespace Booking {
export const LocationDTOSchema = z.object({
Latitude: z.number().positive().max(90),
Longitude: z.number().positive().max(90),
})

export const ServiceProviderDetailsDTOSchema = z.object({
Name: z.string().min(1),
// ... other properties
})
}
}
}
}
```
3 changes: 3 additions & 0 deletions plugins/zod/eslint.config.cjs
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
const baseConfig = require("../../eslint.base.config.cjs")

module.exports = [...baseConfig]
17 changes: 17 additions & 0 deletions plugins/zod/jest.config.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
/* eslint-disable */
export default {
displayName: "zod",
preset: "../../jest.preset.js",
globals: {},
testEnvironment: "node",
transform: {
"^.+\\.[tj]sx?$": [
"ts-jest",
{
tsconfig: "<rootDir>/tsconfig.spec.json",
},
],
},
moduleFileExtensions: ["ts", "tsx", "js", "jsx"],
coverageDirectory: "../../coverage/plugins/zod",
}
18 changes: 18 additions & 0 deletions plugins/zod/package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
{
"name": "@leancodepl/contractsgenerator-typescript-plugin-zod",
"version": "1.0.0",
"license": "Apache-2.0",
"repository": "https://github.com/leancodepl/contractsgenerator-typescript",
"dependencies": {
"@leancodepl/contractsgenerator-typescript-plugin": "1.1.3",
"@leancodepl/contractsgenerator-typescript-schema": "1.1.3",
"@leancodepl/contractsgenerator-typescript-types": "1.1.3",
"@leancodepl/contractsgenerator-typescript-values": "1.1.3",
"lodash": "^4.0.0",
"topological-sort": "0.3.0",
"zod": ">=4.0.0"
},
"peerDependencies": {
"typescript": ">=5.0.0"
}
}
34 changes: 34 additions & 0 deletions plugins/zod/project.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
{
"name": "zod",
"$schema": "../../node_modules/nx/schemas/project-schema.json",
"sourceRoot": "plugins/zod/src",
"projectType": "library",
"tags": ["plugin"],
"targets": {
"build": {
"executor": "@nx/js:tsc",
"outputs": ["{options.outputPath}"],
"options": {
"outputPath": "dist/plugins/zod",
"tsConfig": "plugins/zod/tsconfig.lib.json",
"packageJson": "plugins/zod/package.json",
"main": "plugins/zod/src/index.ts",
"assets": ["plugins/zod/*.md"]
}
},
"lint": {
"executor": "@nx/eslint:lint"
},
"test": {
"options": {
"passWithNoTests": true
},
"configurations": {
"ci": {
"ci": true,
"coverage": true
}
}
}
}
}
62 changes: 62 additions & 0 deletions plugins/zod/src/configuration.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,62 @@
import z from "zod/v4"
import { PropertyTypeCategory } from "./utils/getPropertyTypeCategory"

export type ZodGeneratorPluginConfiguration = z.infer<typeof zodGeneratorPluginConfigurationSchema>

export type FieldValidationContext = {
name: string
isNullable: boolean
type: PropertyTypeCategory
}

export type FieldValidationFunction = (fieldPath: string, property: FieldValidationContext) => string | undefined

export const fieldValidationReturnSchema = z.string().optional()

export type GeneratorInput = z.infer<typeof generatorInputSchema>

export type CustomTypesMap = z.infer<typeof customTypesMapSchema>

export const generatorInputSchema = z.strictObject({
raw: z.string().optional(),
base: z.string().optional(),
file: z.string().optional(),
include: z.union([z.string(), z.array(z.string())]).optional(),
exclude: z.union([z.string(), z.array(z.string())]).optional(),
project: z.union([z.string(), z.array(z.string())]).optional(),
options: z.array(z.string()).optional(),
})

export const customTypesMapSchema = z.strictObject({
String: z.string().optional(),
Guid: z.string().optional(),
Uri: z.string().optional(),
Boolean: z.string().optional(),
UInt8: z.string().optional(),
Int8: z.string().optional(),
Int16: z.string().optional(),
UInt16: z.string().optional(),
Int32: z.string().optional(),
UInt32: z.string().optional(),
Int64: z.string().optional(),
UInt64: z.string().optional(),
Float32: z.string().optional(),
Float64: z.string().optional(),
DateOnly: z.string().optional(),
TimeOnly: z.string().optional(),
DateTimeOffset: z.string().optional(),
TimeSpan: z.string().optional(),
DateTime: z.string().optional(),
})

export const zodGeneratorPluginConfigurationSchema = z.object({
input: generatorInputSchema,
customTypes: customTypesMapSchema.optional(),
nameTransform: z
.function({
input: [z.string()],
output: z.string().optional(),
})
.optional(),
fieldValidation: z.custom<FieldValidationFunction>().optional(),
})
Loading