Generate JSON schema from your Typescript sources
Installations
npm install ts-json-schema-generator
Score
85.7
Supply Chain
98.9
Quality
92.4
Maintenance
100
Vulnerability
99.3
License
Developer
vega
Developer Guide
Module System
CommonJS
Min. Node Version
>=18.0.0
Typescript Support
Yes
Node Version
18.20.3
NPM Version
10.7.0
Statistics
1,466 Stars
2,122 Commits
195 Forks
13 Watching
12 Branches
106 Contributors
Updated on 28 Nov 2024
Bundle Size
3.43 MB
Minified
963.05 kB
Minified + Gzipped
Languages
TypeScript (99.11%)
JavaScript (0.89%)
Total Downloads
Cumulative downloads
Total Downloads
32,148,482
Last day
-13.1%
48,669
Compared to previous day
Last week
-1.9%
295,225
Compared to previous week
Last month
0.9%
1,278,044
Compared to previous month
Last year
59.5%
15,247,894
Compared to previous year
Daily Downloads
Weekly Downloads
Monthly Downloads
Yearly Downloads
Dev Dependencies
26
ts-json-schema-generator
Extended version of https://github.com/xiag-ag/typescript-to-json-schema.
Inspired by YousefED/typescript-json-schema
. Here's the differences list:
- this implementation avoids the use of
typeChecker.getTypeAtLocation()
(so probably it keeps correct type aliases) - processing AST and formatting JSON schema have been split into two independent steps
- not exported types, interfaces, enums are not exposed in the
definitions
section in the JSON schema
Contributors
This project is made possible by a community of contributors. We welcome contributions of any kind (issues, code, documentation, examples, tests,...). Please read our code of conduct.
CLI Usage
Run the schema generator with npx:
1npx ts-json-schema-generator --path 'my/project/**/*.ts' --type 'My.Type.Name'
Or install the package and then run it
1npm install --save ts-json-schema-generator 2./node_modules/.bin/ts-json-schema-generator --path 'my/project/**/*.ts' --type 'My.Type.Name'
Note that different platforms (e.g. Windows) may use different path separators so you may have to adjust the command above.
Also 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.
By 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.
Options
-p, --path <path> Source file path
-t, --type <name> Type name
-i, --id <name> $id for generated schema
-f, --tsconfig <path> Custom tsconfig.json path
-e, --expose <expose> Type exposing (choices: "all", "none", "export", default: "export")
-j, --jsDoc <extended> Read JsDoc annotations (choices: "none", "basic", "extended", default: "extended")
--markdown-description Generate `markdownDescription` in addition to `description`.
--functions <functions> How to handle functions. `fail` will throw an error. `comment` will add a comment. `hide` will treat the function like a NeverType or HiddenType.
(choices: "fail", "comment", "hide", default: "comment")
--minify Minify generated schema (default: false)
--unstable Do not sort properties
--strict-tuples Do not allow additional items on tuples
--no-top-ref Do not create a top-level $ref definition
--no-type-check Skip type checks to improve performance
--no-ref-encode Do not encode references
-o, --out <file> Set the output file (default: stdout)
--validation-keywords [value] Provide additional validation keywords to include (default: [])
--additional-properties Allow additional properties for objects with no index signature (default: false)
-V, --version output the version number
-h, --help display help for command
Programmatic Usage
1// main.js 2 3const tsj = require("ts-json-schema-generator"); 4const fs = require("fs"); 5 6/** @type {import('ts-json-schema-generator/dist/src/Config').Config} */ 7const config = { 8 path: "path/to/source/file", 9 tsconfig: "path/to/tsconfig.json", 10 type: "*", // Or <type-name> if you want to generate schema for that one type only 11}; 12 13const outputPath = "path/to/output/file"; 14 15const schema = tsj.createGenerator(config).createSchema(config.type); 16const schemaString = JSON.stringify(schema, null, 2); 17fs.writeFile(outputPath, schemaString, (err) => { 18 if (err) throw err; 19});
Run the schema generator via node main.js
.
Custom formatting
Extending the built-in formatting is possible by creating a custom formatter and adding it to the main formatter:
- First we create a formatter, in this case for formatting function types (note that there is a built in one):
1// my-function-formatter.ts 2import { BaseType, Definition, FunctionType, SubTypeFormatter } from "ts-json-schema-generator"; 3import ts from "typescript"; 4 5export class MyFunctionTypeFormatter implements SubTypeFormatter { 6 // You can skip this line if you don't need childTypeFormatter 7 public constructor(private childTypeFormatter: TypeFormatter) {} 8 9 public supportsType(type: BaseType): boolean { 10 return type instanceof FunctionType; 11 } 12 13 public getDefinition(type: FunctionType): Definition { 14 // Return a custom schema for the function property. 15 return { 16 type: "object", 17 properties: { 18 isFunction: { 19 type: "boolean", 20 const: true, 21 }, 22 }, 23 }; 24 } 25 26 // If this type does NOT HAVE children, generally all you need is: 27 public getChildren(type: FunctionType): BaseType[] { 28 return []; 29 } 30 31 // However, if children ARE supported, you'll need something similar to 32 // this (see src/TypeFormatter/{Array,Definition,etc}.ts for some examples): 33 public getChildren(type: FunctionType): BaseType[] { 34 return this.childTypeFormatter.getChildren(type.getType()); 35 } 36}
- Then we add the formatter as a child to the core formatter using the augmentation callback:
1import { createProgram, createParser, SchemaGenerator, createFormatter } from "ts-json-schema-generator";
2import { MyFunctionTypeFormatter } from "./my-function-formatter.ts";
3import fs from "fs";
4
5const config = {
6 path: "path/to/source/file",
7 tsconfig: "path/to/tsconfig.json",
8 type: "*", // Or <type-name> if you want to generate schema for that one type only
9};
10
11// We configure the formatter an add our custom formatter to it.
12const formatter = createFormatter(config, (fmt, circularReferenceTypeFormatter) => {
13 // If your formatter DOES NOT support children, e.g. getChildren() { return [] }:
14 fmt.addTypeFormatter(new MyFunctionTypeFormatter());
15 // If your formatter DOES support children, you'll need this reference too:
16 fmt.addTypeFormatter(new MyFunctionTypeFormatter(circularReferenceTypeFormatter));
17});
18
19const program = createProgram(config);
20const parser = createParser(program, config);
21const generator = new SchemaGenerator(program, parser, formatter, config);
22const schema = generator.createSchema(config.type);
23const outputPath = "path/to/output/file";
24
25const schemaString = JSON.stringify(schema, null, 2);
26fs.writeFile(outputPath, schemaString, (err) => {
27 if (err) throw err;
28});
Custom parsing
Similar to custom formatting, extending the built-in parsing works practically the same way:
- First we create a parser, in this case for parsing construct types:
1// my-constructor-parser.ts 2import { Context, StringType, ReferenceType, BaseType, SubNodeParser } from "ts-json-schema-generator"; 3// use typescript exported by TJS to avoid version conflict 4import ts from "ts-json-schema-generator"; 5 6export class MyConstructorParser implements SubNodeParser { 7 supportsNode(node: ts.Node): boolean { 8 return node.kind === ts.SyntaxKind.ConstructorType; 9 } 10 createType(node: ts.Node, context: Context, reference?: ReferenceType): BaseType | undefined { 11 return new StringType(); // Treat constructors as strings in this example 12 } 13}
- Then we add the parser as a child to the core parser using the augmentation callback:
1import { createProgram, createParser, SchemaGenerator, createFormatter } from "ts-json-schema-generator";
2import { MyConstructorParser } from "./my-constructor-parser.ts";
3import fs from "fs";
4
5const config = {
6 path: "path/to/source/file",
7 tsconfig: "path/to/tsconfig.json",
8 type: "*", // Or <type-name> if you want to generate schema for that one type only
9};
10
11const program = createProgram(config);
12
13// We configure the parser an add our custom parser to it.
14const parser = createParser(program, config, (prs) => {
15 prs.addNodeParser(new MyConstructorParser());
16});
17
18const formatter = createFormatter(config);
19const generator = new SchemaGenerator(program, parser, formatter, config);
20const schema = generator.createSchema(config.type);
21const outputPath = "path/to/output/file";
22
23const schemaString = JSON.stringify(schema, null, 2);
24fs.writeFile(outputPath, schemaString, (err) => {
25 if (err) throw err;
26});
Current state
interface
typesenum
typesunion
,tuple
,type[]
typesDate
,RegExp
,URL
typesstring
,boolean
,number
types"value"
,123
,true
,false
,null
,undefined
literals- type aliases
- generics
typeof
keyof
- conditional types
- functions
Promise<T>
unwraps toT
- Overrides (like
@format
)
Run locally
yarn --silent run run --path 'test/valid-data/type-mapped-array/*.ts' --type 'MyObject'
Debug
yarn --silent run debug --path 'test/valid-data/type-mapped-array/*.ts' --type 'MyObject'
And connect via the debugger protocol.
AST Explorer is amazing for developers of this tool!
Publish
Publishing is handled by a 2-branch pre-release process, configured in publish-auto.yml
. All changes should be based off the default next
branch, and are published automatically.
- PRs made into the default branch are auto-deployed to the
next
pre-release tag on NPM. The result can be installed withnpm install ts-json-schema-generator@next
- When merging into
next
, please use thesquash and merge
strategy.
- When merging into
- To release a new stable version, open a PR from
next
intostable
using this compare link.- When merging from
next
intostable
, please use thecreate a merge commit
strategy.
- When merging from
No vulnerabilities found.
Reason
30 commit(s) and 12 issue activity found in the last 90 days -- score normalized to 10
Reason
no dangerous workflow patterns detected
Reason
no binaries found in the repo
Reason
license file detected
Details
- Info: project has a license file: LICENSE:0
- Info: FSF or OSI recognized license: MIT License: LICENSE:0
Reason
0 existing vulnerabilities detected
Reason
Found 0/1 approved changesets -- score normalized to 0
Reason
detected GitHub workflow tokens with excessive permissions
Details
- Warn: no topLevel permission defined: .github/workflows/merge-dependabot.yml:1
- Warn: no topLevel permission defined: .github/workflows/publish-auto.yml:1
- Warn: no topLevel permission defined: .github/workflows/test.yml:1
- Info: no jobLevel write permissions found
Reason
dependency not pinned by hash detected -- score normalized to 0
Details
- Warn: third-party GitHubAction not pinned by hash: .github/workflows/merge-dependabot.yml:12: update your workflow using https://app.stepsecurity.io/secureworkflow/vega/ts-json-schema-generator/merge-dependabot.yml/next?enable=pin
- Warn: GitHub-owned GitHubAction not pinned by hash: .github/workflows/publish-auto.yml:16: update your workflow using https://app.stepsecurity.io/secureworkflow/vega/ts-json-schema-generator/publish-auto.yml/next?enable=pin
- Warn: GitHub-owned GitHubAction not pinned by hash: .github/workflows/publish-auto.yml:20: update your workflow using https://app.stepsecurity.io/secureworkflow/vega/ts-json-schema-generator/publish-auto.yml/next?enable=pin
- Warn: GitHub-owned GitHubAction not pinned by hash: .github/workflows/test.yml:23: update your workflow using https://app.stepsecurity.io/secureworkflow/vega/ts-json-schema-generator/test.yml/next?enable=pin
- Warn: GitHub-owned GitHubAction not pinned by hash: .github/workflows/test.yml:25: update your workflow using https://app.stepsecurity.io/secureworkflow/vega/ts-json-schema-generator/test.yml/next?enable=pin
- Warn: third-party GitHubAction not pinned by hash: .github/workflows/test.yml:43: update your workflow using https://app.stepsecurity.io/secureworkflow/vega/ts-json-schema-generator/test.yml/next?enable=pin
- Info: 0 out of 4 GitHub-owned GitHubAction dependencies pinned
- Info: 0 out of 2 third-party GitHubAction dependencies pinned
Reason
no effort to earn an OpenSSF best practices badge detected
Reason
project is not fuzzed
Details
- Warn: no fuzzer integrations found
Reason
security policy file not detected
Details
- Warn: no security policy file detected
- Warn: no security file to analyze
- Warn: no security file to analyze
- Warn: no security file to analyze
Reason
SAST tool is not run on all commits -- score normalized to 0
Details
- Warn: 0 commits out of 30 are checked with a SAST tool
Score
4.8
/10
Last Scanned on 2024-11-18
The Open Source Security Foundation is a cross-industry collaboration to improve the security of open source software (OSS). The Scorecard provides security health metrics for open source projects.
Learn MoreOther packages similar to ts-json-schema-generator
json-schema-traverse
Traverse JSON Schema passing each schema object to callback
@stoplight/json-schema-generator
JSON schema generator based on draft-v4.
json-schema-typed
JSON Schema TypeScript definitions with complete inline documentation.
json-schema
JSON Schema validation and specifications