{"id":14156622,"url":"https://github.com/azu/create-validator-ts","last_synced_at":"2025-04-12T23:42:26.612Z","repository":{"id":43369254,"uuid":"337449349","full_name":"azu/create-validator-ts","owner":"azu","description":"Create JSON Schema validator from TypeScript.","archived":false,"fork":false,"pushed_at":"2025-04-08T23:03:22.000Z","size":686,"stargazers_count":92,"open_issues_count":4,"forks_count":4,"subscribers_count":3,"default_branch":"main","last_synced_at":"2025-04-12T23:42:22.107Z","etag":null,"topics":["check","json-schema","runtime","typescript","validator"],"latest_commit_sha":null,"homepage":null,"language":"TypeScript","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"mit","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/azu.png","metadata":{"funding":{"github":"azu"},"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null}},"created_at":"2021-02-09T15:29:25.000Z","updated_at":"2025-04-08T23:03:25.000Z","dependencies_parsed_at":"2023-10-23T05:25:11.739Z","dependency_job_id":"3c954b7a-4456-41b5-aefa-b0076015c6d1","html_url":"https://github.com/azu/create-validator-ts","commit_stats":{"total_commits":370,"total_committers":5,"mean_commits":74.0,"dds":0.3648648648648649,"last_synced_commit":"d7dab478b8b119cf8864d60b40c210740a9627ba"},"previous_names":["azu/create-ts-validator"],"tags_count":23,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/azu%2Fcreate-validator-ts","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/azu%2Fcreate-validator-ts/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/azu%2Fcreate-validator-ts/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/azu%2Fcreate-validator-ts/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/azu","download_url":"https://codeload.github.com/azu/create-validator-ts/tar.gz/refs/heads/main","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":248647257,"owners_count":21139081,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["check","json-schema","runtime","typescript","validator"],"created_at":"2024-08-17T08:07:24.587Z","updated_at":"2025-04-12T23:42:26.584Z","avatar_url":"https://github.com/azu.png","language":"TypeScript","funding_links":["https://github.com/sponsors/azu"],"categories":["typescript"],"sub_categories":[],"readme":"# create-validator-ts\n\nCreate JSON Schema validator from TypeScript.\n\n## Motivation\n\n- Generate JSON Schema Validator functions from TypeScript code\n- Make TypeScript the [Single source of truth](https://en.wikipedia.org/wiki/Single_source_of_truth)\n\n### Structure\n\n```\n.\n└── src/\n    ├── hello/\n    │   ├── api-types.ts\n    │   ├── api-types.validator.ts \u003c- Generated\n    │   └── index.ts\n    └── status/\n        ├── api-types.ts\n        ├── api-types.validator.ts \u003c- Generated\n        └── index.ts\n```\n\n## Install\n\nInstall with [npm](https://www.npmjs.com/):\n\n    npm install create-validator-ts\n\n## Usage\n\n\n    Usage\n      $ create-validator-ts [file|glob*]\n \n    Options\n      --watch               [Boolean] If set the flag, start watch mode\n      --check               [Boolean] If set the flag, start test mode\n      --cwd                 [Path:String] current working directory\n      --tsconfigFilePath    [Path:String] path to tsconfig.json\n      --generatorScript     [Path:String] A JavaScript file path that customize validator code generator\n      --verbose             [Boolean] If set the flag, show progressing logs\n     \n      ts-json-schema-generator options\n      --sortProps               [Boolean] Enable sortProps\n      --no-sortProps            \n      --strictTuples            [Boolean] Enable strictTuples\n      --no-strictTuples         \n      --encodeRefs              [Boolean] Enable encodeRefs\n      --no-encodeRefs           \n      --skipTypeCheck           [Boolean] Enable skipTypeCheck. true by default\n      --no-skipTypeCheck\n      --additionalProperties    [Boolean] Enable additionalProperties. false by default\n      --no-additionalProperties \n    \n\n    Examples\n      $ create-validator-ts \"src/**/api-types.ts\"\n      # use cache\n      $ create-validator-ts --cache \"src/**/api-types.ts\"\n      # custom tsconfig.json\n      $ create-validator-ts \"src/**/api-types.ts\" --tsconfigFilePath ./tsconfig.app.json\n      # custom validator code\n      $ create-validator-ts \"src/**/api-types.ts\" --generatorScript ./custom.js\n\n## Example\n\nYou can generate validator code via following command\n\n    $ create-validator-ts \"src/**/api-types.ts\"\n\nDefault validator require [ajv](https://github.com/ajv-validator/ajv), and you need to install ajv into your project.\n\n    $ npm install ajv\n\nStructure:\n\n```\n.\n├ tsconfig.json\n└── src/\n    └─── api/\n        ├──  api-types.ts\n        └─── api-types.validator.ts \u003c- Generated\n```\n\n`api-types.ts`:\n\n```ts\n// Example api-types\n// GET /api\nexport type GetAPIRequestQuery = {\n    id: string;\n};\nexport type GetAPIResponseBody = {\n    ok: boolean;\n};\n```\n\n`api-types.validator.ts` (generated):\n\n```ts\n// @ts-nocheck\n// eslint-disable\n// This file is generated by create-validator-ts\nimport Ajv from 'ajv';\nimport * as apiTypes from './api-types';\n\nconst SCHEMA = {\n    \"$schema\": \"http://json-schema.org/draft-07/schema#\",\n    \"definitions\": {\n        \"GetAPIRequestQuery\": {\n            \"type\": \"object\",\n            \"properties\": {\n                \"id\": {\n                    \"type\": \"string\"\n                }\n            },\n            \"required\": [\n                \"id\"\n            ],\n            \"additionalProperties\": false\n        },\n        \"GetAPIResponseBody\": {\n            \"type\": \"object\",\n            \"properties\": {\n                \"ok\": {\n                    \"type\": \"boolean\"\n                }\n            },\n            \"required\": [\n                \"ok\"\n            ],\n            \"additionalProperties\": false\n        }\n    }\n};\nconst ajv = new Ajv({ removeAdditional: true }).addSchema(SCHEMA, \"SCHEMA\");\nexport function validateGetAPIRequestQuery(payload: unknown): apiTypes.GetAPIRequestQuery {\n  if (!isGetAPIRequestQuery(payload)) {\n    const error = new Error('invalid payload: GetAPIRequestQuery');\n    error.name = \"ValidatorError\";\n    throw error;\n  }\n  return payload;\n}\n\nexport function isGetAPIRequestQuery(payload: unknown): payload is apiTypes.GetAPIRequestQuery {\n  /** Schema is defined in {@link SCHEMA.definitions.GetAPIRequestQuery } **/\n  const ajvValidate = ajv.compile({ \"$ref\": \"SCHEMA#/definitions/GetAPIRequestQuery\" });\n  return ajvValidate(payload);\n}\n\nexport function validateGetAPIResponseBody(payload: unknown): apiTypes.GetAPIResponseBody {\n  if (!isGetAPIResponseBody(payload)) {\n    const error = new Error('invalid payload: GetAPIResponseBody');\n    error.name = \"ValidatorError\";\n    throw error;\n  }\n  return payload;\n}\n\nexport function isGetAPIResponseBody(payload: unknown): payload is apiTypes.GetAPIResponseBody {\n  /** Schema is defined in {@link SCHEMA.definitions.GetAPIResponseBody } **/\n  const ajvValidate = ajv.compile({ \"$ref\": \"SCHEMA#/definitions/GetAPIResponseBody\" });\n  return ajvValidate(payload);\n}\n```\n\n## Check generated code\n\nWhen You can check if your generated codes are match with `api-types.ts`, you can run it via `--check` flag.\n\n    $ create-validator-ts \"src/**/api-types.ts\"\n    # $? → 0 or 1\n\nIt is useful for testing on CI.\n\n## Custom Validator\n\nYou can create custom validator using `--generatorScript` flag.\n\n    $ create-validator-ts \"src/**/api-types.ts\" --generatorScript ./custom.js\n\n`custom.js`\n\n```js\n\"use strict\";\nconst path = require(\"path\");\nconst generator = ({ apiFilePath, apiFileCode, schema }) =\u003e {\n    const apiFileName = path.basename(apiFilePath, \".ts\");\n    const isExportedTypeInApiTypes = (apiName) =\u003e {\n        return (apiFileCode.includes(`export type ${apiName} =`) ||\n            apiFileCode.includes(`export interface ${apiName} {`));\n    };\n    const banner = `// @ts-nocheck\n// eslint-disable\n// This file is generated by create-validator-ts\nimport Ajv from 'ajv';\nimport logger from 'logger';\nimport * as apiTypes from './${apiFileName}';\n`;\n    // define SCHEMA to top, and we can refer it as \"SCHEMA\".\n    // Note: { \"$ref\": \"SCHEMA#/definitions/${apiName}\" }\n    const schemaDefinition = `const SCHEMA = ${JSON.stringify(schema, null, 4)};\nconst ajv = new Ajv({ removeAdditional: true }).addSchema(SCHEMA, \"SCHEMA\");`;\n    const code = Object.entries(schema.definitions || {})\n        .filter(([apiName]) =\u003e {\n        return isExportedTypeInApiTypes(apiName);\n    })\n        .map(([apiName, _schema]) =\u003e {\n        return `export function validate${apiName}(payload: unknown): apiTypes.${apiName} {\n  if (!is${apiName}(payload)) {\n    const error = new Error('invalid payload: ${apiName}');\n    error.name = \"ValidatorError\";\n    throw error;\n  }\n  return payload;\n}\n\nexport function is${apiName}(payload: unknown): payload is apiTypes.${apiName} {\n  /** Schema is defined in {@link SCHEMA.definitions.${apiName} } **/\n  const ajvValidate = ajv.compile({ \"$ref\": \"SCHEMA#/definitions/${apiName}\" });\n  return ajvValidate(payload);\n}`;\n    })\n        .join(\"\\n\\n\");\n    return `${banner}\n${schemaDefinition}\n${code}\n`;\n};\nexports.generator = generator;\nexports.generatorOptions = {\n  extraTags: [\"\u003cajv-plugin-extra-tag\u003e\"] // optional\n};\n```\n\n## Ignore generated Code\n\nIf you have used [Prettier](https://prettier.io/), you should add `*.validator.ts` to `.prettierignore`\n\n```\n*.validator.ts\n```\n\n- [Ignoring Code · Prettier](https://prettier.io/docs/en/ignore.html)\n\n## Compares\n\n- create-validator-ts\n  - It generate TypeScript validator from TypeScript types\n  - [ts-to-zod](https://github.com/fabien0102/ts-to-zod) uses same approach\n- OpenAPI\n  - It generate TypeScript validator from Schema file\n- TypeScript Validation library like [Zod](https://github.com/colinhacks/zod)\n  - Is allow to share TypeScript code and types, but it need to use builder function\n\n## FAQ\n\n### Can not parse new TypeScript syntax\n\nIt related to [vega/ts-json-schema-generator](https://github.com/vega/ts-json-schema-generator).\nPlease report the issue to [vega/ts-json-schema-generator](https://github.com/vega/ts-json-schema-generator).\n\n## Changelog\n\nSee [Releases page](https://github.com/azu/create-validator-ts/releases).\n\n## Running tests\n\nInstall devDependencies and Run `npm test`:\n\n    npm test\n\n## Contributing\n\nPull requests and stars are always welcome.\n\nFor bugs and feature requests, [please create an issue](https://github.com/azu/create-validator-ts/issues).\n\n1. Fork it!\n2. Create your feature branch: `git checkout -b my-new-feature`\n3. Commit your changes: `git commit -am 'Add some feature'`\n4. Push to the branch: `git push origin my-new-feature`\n5. Submit a pull request :D\n\n## Author\n\n- azu: [GitHub](https://github.com/azu), [Twitter](https://twitter.com/azu_re)\n\n## License\n\nMIT © azu\n\n## Prior art\n\n- [ForbesLindesay/typescript-json-validator](https://github.com/ForbesLindesay/typescript-json-validator)\n\nDifferences:\n\n- `create-validator-ts` support multiple types in a single file\n- `create-validator-ts` support more TypeScript that includes Utility types like `Pick\u003cT\u003e`\n    - `typescript-json-validator` uses [YousefED/typescript-json-schema](https://github.com/YousefED/typescript-json-schema)\n    - `create-validator-ts` uses [vega/ts-json-schema-generator](https://github.com/vega/ts-json-schema-generator)\n    - See also [Future of schema generators · Issue #101 · vega/ts-json-schema-generator](https://github.com/vega/ts-json-schema-generator/issues/101)\n- `create-validator-ts` is minimal and support customization of validation code using `--generatorScript`\n\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fazu%2Fcreate-validator-ts","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fazu%2Fcreate-validator-ts","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fazu%2Fcreate-validator-ts/lists"}