Gathering detailed insights and metrics for ts-json-schema-generator
Gathering detailed insights and metrics for ts-json-schema-generator
Gathering detailed insights and metrics for ts-json-schema-generator
Gathering detailed insights and metrics for 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
Generate JSON schema from your Typescript sources
npm install ts-json-schema-generator
85.7
Supply Chain
98.9
Quality
92.4
Maintenance
100
Vulnerability
99.3
License
Module System
Min. Node Version
Typescript Support
Node Version
NPM Version
1,466 Stars
2,122 Commits
195 Forks
13 Watching
12 Branches
106 Contributors
Updated on 28 Nov 2024
Minified
Minified + Gzipped
TypeScript (99.11%)
JavaScript (0.89%)
Cumulative downloads
Total Downloads
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
26
Extended version of https://github.com/xiag-ag/typescript-to-json-schema.
Inspired by YousefED/typescript-json-schema
. Here's the differences list:
typeChecker.getTypeAtLocation()
(so probably it keeps correct type aliases)definitions
section in the JSON schemaThis 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.
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.
-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
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
.
Extending the built-in formatting is possible by creating a custom formatter and adding it to the main formatter:
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}
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});
Similar to custom formatting, extending the built-in parsing works practically the same way:
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}
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});
interface
typesenum
typesunion
, tuple
, type[]
typesDate
, RegExp
, URL
typesstring
, boolean
, number
types"value"
, 123
, true
, false
, null
, undefined
literalstypeof
keyof
Promise<T>
unwraps to T
@format
)yarn --silent run run --path 'test/valid-data/type-mapped-array/*.ts' --type 'MyObject'
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!
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.
next
pre-release tag on NPM. The result can be installed with npm install ts-json-schema-generator@next
next
, please use the squash and merge
strategy.next
into stable
using this compare link.
next
into stable
, please use the create a merge commit
strategy.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
Reason
0 existing vulnerabilities detected
Reason
Found 0/1 approved changesets -- score normalized to 0
Reason
detected GitHub workflow tokens with excessive permissions
Details
Reason
dependency not pinned by hash detected -- score normalized to 0
Details
Reason
no effort to earn an OpenSSF best practices badge detected
Reason
project is not fuzzed
Details
Reason
security policy file not detected
Details
Reason
SAST tool is not run on all commits -- score normalized to 0
Details
Score
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 More