{"id":13560792,"url":"https://github.com/vega/ts-json-schema-generator","last_synced_at":"2025-05-12T15:26:51.348Z","repository":{"id":37734421,"uuid":"93129134","full_name":"vega/ts-json-schema-generator","owner":"vega","description":"Generate JSON schema from your Typescript sources","archived":false,"fork":false,"pushed_at":"2025-05-04T11:02:15.000Z","size":10429,"stargazers_count":1556,"open_issues_count":113,"forks_count":209,"subscribers_count":13,"default_branch":"next","last_synced_at":"2025-05-04T12:18:53.795Z","etag":null,"topics":["compiler","generator","json-schema","typescript"],"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/vega.png","metadata":{"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,"zenodo":null},"funding":{"custom":"https://app.hubspot.com/payments/GyPC972GD9Rt?referrer=PAYMENT_LINK"}},"created_at":"2017-06-02T05:09:01.000Z","updated_at":"2025-05-04T11:02:16.000Z","dependencies_parsed_at":"2023-02-16T23:00:40.860Z","dependency_job_id":"8b433f43-7472-402b-8663-52246482ca6a","html_url":"https://github.com/vega/ts-json-schema-generator","commit_stats":{"total_commits":2125,"total_committers":97,"mean_commits":21.90721649484536,"dds":0.5505882352941176,"last_synced_commit":"4b0204c9a2d7ec27cc044c6df859ebe6057ee82e"},"previous_names":[],"tags_count":255,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/vega%2Fts-json-schema-generator","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/vega%2Fts-json-schema-generator/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/vega%2Fts-json-schema-generator/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/vega%2Fts-json-schema-generator/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/vega","download_url":"https://codeload.github.com/vega/ts-json-schema-generator/tar.gz/refs/heads/next","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":252466179,"owners_count":21752303,"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":["compiler","generator","json-schema","typescript"],"created_at":"2024-08-01T13:00:49.549Z","updated_at":"2025-05-12T15:26:51.085Z","avatar_url":"https://github.com/vega.png","language":"TypeScript","funding_links":["https://app.hubspot.com/payments/GyPC972GD9Rt?referrer=PAYMENT_LINK"],"categories":["TypeScript","typescript","compiler","Tools"],"sub_categories":["Optimization"],"readme":"# ts-json-schema-generator\n\n![Test](https://github.com/vega/ts-json-schema-generator/workflows/Test/badge.svg)\n[![codecov](https://codecov.io/gh/vega/ts-json-schema-generator/branch/master/graph/badge.svg)](https://codecov.io/gh/vega/ts-json-schema-generator)\n[![npm version](https://img.shields.io/npm/v/ts-json-schema-generator.svg)](https://www.npmjs.com/package/ts-json-schema-generator)\n\nExtended version of [https://github.com/xiag-ag/typescript-to-json-schema](https://github.com/xiag-ag/typescript-to-json-schema).\n\nInspired by [`YousefED/typescript-json-schema`](https://github.com/YousefED/typescript-json-schema). Here's the differences list:\n\n-   this implementation avoids the use of `typeChecker.getTypeAtLocation()` (so probably it keeps correct type aliases)\n-   processing AST and formatting JSON schema have been split into two independent steps\n-   not exported types, interfaces, enums are not exposed in the `definitions` section in the JSON schema\n\n## Contributors\n\nThis project is made possible by a [community of contributors](https://github.com/vega/ts-json-schema-generator/graphs/contributors). We welcome contributions of any kind (issues, code, documentation, examples, tests,...). Please read our [code of conduct](https://vega.github.io/vega/about/code-of-conduct).\n\n## CLI Usage\n\nRun the schema generator with npx:\n\n```bash\nnpx ts-json-schema-generator --path 'my/project/**/*.ts' --type 'My.Type.Name'\n```\n\nOr install the package and then run it\n\n```bash\nnpm install --save ts-json-schema-generator\n./node_modules/.bin/ts-json-schema-generator --path 'my/project/**/*.ts' --type 'My.Type.Name'\n```\n\nNote that different platforms (e.g. Windows) may use different path separators so you may have to adjust the command above.\n\nAlso note that you need to quote paths with `*` as otherwise the shell will expand the paths and therefore only pass the first path to the generator.\n\nBy default, the command-line generator will use the `tsconfig.json` file in the current working directory, or the first parent directory that contains a `tsconfig.json` file up to the root of the filesystem. If you want to use a different `tsconfig.json` file, you can use the `--tsconfig` option. In particular, if you need to use different compilation options for types, you may want to create a separate `tsconfig.json` file for the schema generation only.\n\n### Options\n\n```\n  -p, --path \u003cpath\u003e              Source file path\n  -t, --type \u003cname\u003e              Type name\n  -i, --id \u003cname\u003e                $id for generated schema\n  -f, --tsconfig \u003cpath\u003e          Custom tsconfig.json path\n  -e, --expose \u003cexpose\u003e          Type exposing (choices: \"all\", \"none\", \"export\", default: \"export\")\n  -j, --jsDoc \u003cextended\u003e         Read JsDoc annotations (choices: \"none\", \"basic\", \"extended\", default: \"extended\")\n  --markdown-description         Generate `markdownDescription` in addition to `description`.\n  --functions \u003cfunctions\u003e        How to handle functions. `fail` will throw an error. `comment` will add a comment. `hide` will treat the function like a NeverType or HiddenType.\n                                 (choices: \"fail\", \"comment\", \"hide\", default: \"comment\")\n  --minify                       Minify generated schema (default: false)\n  --unstable                     Do not sort properties\n  --strict-tuples                Do not allow additional items on tuples\n  --no-top-ref                   Do not create a top-level $ref definition\n  --no-type-check                Skip type checks to improve performance\n  --no-ref-encode                Do not encode references\n  -o, --out \u003cfile\u003e               Set the output file (default: stdout)\n  --validation-keywords [value]  Provide additional validation keywords to include (default: [])\n  --additional-properties        Allow additional properties for objects with no index signature (default: false)\n  -V, --version                  output the version number\n  -h, --help                     display help for command\n```\n\n## Programmatic Usage\n\n```js\n// main.js\n\nconst tsj = require(\"ts-json-schema-generator\");\nconst fs = require(\"fs\");\n\n/** @type {import('ts-json-schema-generator/dist/src/Config').Config} */\nconst config = {\n    path: \"path/to/source/file\",\n    tsconfig: \"path/to/tsconfig.json\",\n    type: \"*\", // Or \u003ctype-name\u003e if you want to generate schema for that one type only\n};\n\nconst outputPath = \"path/to/output/file\";\n\nconst schema = tsj.createGenerator(config).createSchema(config.type);\nconst schemaString = JSON.stringify(schema, null, 2);\nfs.writeFile(outputPath, schemaString, (err) =\u003e {\n    if (err) throw err;\n});\n```\n\nRun the schema generator via `node main.js`.\n\n### Custom formatting\n\nExtending the built-in formatting is possible by creating a custom formatter and adding it to the main formatter:\n\n1. First we create a formatter, in this case for formatting function types (note that there is a built in one):\n\n```ts\n// my-function-formatter.ts\nimport { BaseType, Definition, FunctionType, SubTypeFormatter } from \"ts-json-schema-generator\";\nimport ts from \"typescript\";\n\nexport class MyFunctionTypeFormatter implements SubTypeFormatter {\n    // You can skip this line if you don't need childTypeFormatter\n    public constructor(private childTypeFormatter: TypeFormatter) {}\n\n    public supportsType(type: BaseType): boolean {\n        return type instanceof FunctionType;\n    }\n\n    public getDefinition(type: FunctionType): Definition {\n        // Return a custom schema for the function property.\n        return {\n            type: \"object\",\n            properties: {\n                isFunction: {\n                    type: \"boolean\",\n                    const: true,\n                },\n            },\n        };\n    }\n\n    // If this type does NOT HAVE children, generally all you need is:\n    public getChildren(type: FunctionType): BaseType[] {\n        return [];\n    }\n\n    // However, if children ARE supported, you'll need something similar to\n    // this (see src/TypeFormatter/{Array,Definition,etc}.ts for some examples):\n    public getChildren(type: FunctionType): BaseType[] {\n        return this.childTypeFormatter.getChildren(type.getType());\n    }\n}\n```\n\n2. Then we add the formatter as a child to the core formatter using the augmentation callback:\n\n```ts\nimport { createProgram, createParser, SchemaGenerator, createFormatter } from \"ts-json-schema-generator\";\nimport { MyFunctionTypeFormatter } from \"./my-function-formatter.ts\";\nimport fs from \"fs\";\n\nconst config = {\n    path: \"path/to/source/file\",\n    tsconfig: \"path/to/tsconfig.json\",\n    type: \"*\", // Or \u003ctype-name\u003e if you want to generate schema for that one type only\n};\n\n// We configure the formatter an add our custom formatter to it.\nconst formatter = createFormatter(config, (fmt, circularReferenceTypeFormatter) =\u003e {\n    // If your formatter DOES NOT support children, e.g. getChildren() { return [] }:\n    fmt.addTypeFormatter(new MyFunctionTypeFormatter());\n    // If your formatter DOES support children, you'll need this reference too:\n    fmt.addTypeFormatter(new MyFunctionTypeFormatter(circularReferenceTypeFormatter));\n});\n\nconst program = createProgram(config);\nconst parser = createParser(program, config);\nconst generator = new SchemaGenerator(program, parser, formatter, config);\nconst schema = generator.createSchema(config.type);\nconst outputPath = \"path/to/output/file\";\n\nconst schemaString = JSON.stringify(schema, null, 2);\nfs.writeFile(outputPath, schemaString, (err) =\u003e {\n    if (err) throw err;\n});\n```\n\n### Custom parsing\n\nSimilar to custom formatting, extending the built-in parsing works practically the same way:\n\n1. First we create a parser, in this case for parsing construct types:\n\n```ts\n// my-constructor-parser.ts\nimport { Context, StringType, ReferenceType, BaseType, SubNodeParser } from \"ts-json-schema-generator\";\n// use typescript exported by TJS to avoid version conflict\nimport ts from \"ts-json-schema-generator\";\n\nexport class MyConstructorParser implements SubNodeParser {\n    supportsNode(node: ts.Node): boolean {\n        return node.kind === ts.SyntaxKind.ConstructorType;\n    }\n    createType(node: ts.Node, context: Context, reference?: ReferenceType): BaseType | undefined {\n        return new StringType(); // Treat constructors as strings in this example\n    }\n}\n```\n\n2. Then we add the parser as a child to the core parser using the augmentation callback:\n\n```ts\nimport { createProgram, createParser, SchemaGenerator, createFormatter } from \"ts-json-schema-generator\";\nimport { MyConstructorParser } from \"./my-constructor-parser.ts\";\nimport fs from \"fs\";\n\nconst config = {\n    path: \"path/to/source/file\",\n    tsconfig: \"path/to/tsconfig.json\",\n    type: \"*\", // Or \u003ctype-name\u003e if you want to generate schema for that one type only\n};\n\nconst program = createProgram(config);\n\n// We configure the parser an add our custom parser to it.\nconst parser = createParser(program, config, (prs) =\u003e {\n    prs.addNodeParser(new MyConstructorParser());\n});\n\nconst formatter = createFormatter(config);\nconst generator = new SchemaGenerator(program, parser, formatter, config);\nconst schema = generator.createSchema(config.type);\nconst outputPath = \"path/to/output/file\";\n\nconst schemaString = JSON.stringify(schema, null, 2);\nfs.writeFile(outputPath, schemaString, (err) =\u003e {\n    if (err) throw err;\n});\n```\n\n## Current state\n\n-   `interface` types\n-   `enum` types\n-   `union`, `tuple`, `type[]` types\n-   `Date`, `RegExp`, `URL` types\n-   `string`, `boolean`, `number` types\n-   `\"value\"`, `123`, `true`, `false`, `null`, `undefined` literals\n-   type aliases\n-   generics\n-   `typeof`\n-   `keyof`\n-   conditional types\n-   functions\n-   `Promise\u003cT\u003e` unwraps to `T`\n-   Overrides (like `@format`)\n\n## Run locally\n\n`npm run --silent run -- --path 'test/valid-data/type-mapped-array/*.ts' --type 'MyObject'`\n\n## Debug\n\n`npm run --silent debug -- --path 'test/valid-data/type-mapped-array/*.ts' --type 'MyObject'`\n\nAnd connect via the debugger protocol.\n\n[AST Explorer](https://astexplorer.net/) is amazing for developers of this tool!\n\n## Publish\n\nPublishing is handled by a 2-branch [pre-release process](https://intuit.github.io/auto/docs/generated/shipit#next-branch-default), configured in `publish-auto.yml`. All changes should be based off the default `next` branch, and are published automatically.\n\n-   PRs made into the default branch are auto-deployed to the `next` pre-release tag on NPM. The result can be installed with `npm install ts-json-schema-generator@next`\n    -   When merging into `next`, please use the `squash and merge` strategy.\n-   To release a new stable version, open a PR from `next` into `stable` using this [compare link](https://github.com/vega/ts-json-schema-generator/compare/stable...next).\n    -   When merging from `next` into `stable`, please use the `create a merge commit` strategy.\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fvega%2Fts-json-schema-generator","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fvega%2Fts-json-schema-generator","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fvega%2Fts-json-schema-generator/lists"}