Socket
Socket
Sign inDemoInstall

json-schema-to-typescript

Package Overview
Dependencies
Maintainers
0
Versions
114
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

json-schema-to-typescript - npm Package Compare versions

Comparing version 14.0.5 to 14.1.0

6

CHANGELOG.md

@@ -5,5 +5,9 @@ # Changelog

## 14.1.0
- 3e2e1e9 Added `inferStringEnumKeysFromValues` option (#578)
## 14.0.5
- b7fee29 Added .taml support for CLI (#598)
- b7fee29 Added .yaml support for CLI (#598)

@@ -10,0 +14,0 @@ ## 14.0.2

24

dist/src/cli.js

@@ -47,3 +47,3 @@ #!/usr/bin/env node

const minimist_1 = __importDefault(require("minimist"));
const fs_1 = require("mz/fs");
const fs_1 = require("fs");
const mkdirp = __importStar(require("mkdirp"));

@@ -145,13 +145,11 @@ const glob_1 = require("glob");

function outputResult(result, outputPath) {
return __awaiter(this, void 0, void 0, function* () {
if (!outputPath) {
process.stdout.write(result);
if (!outputPath) {
process.stdout.write(result);
}
else {
if (!isDir((0, path_1.dirname)(outputPath))) {
mkdirp.sync((0, path_1.dirname)(outputPath));
}
else {
if (!isDir((0, path_1.dirname)(outputPath))) {
mkdirp.sync((0, path_1.dirname)(outputPath));
}
return yield (0, fs_1.writeFile)(outputPath, result);
}
});
return (0, fs_1.writeFileSync)(outputPath, result);
}
}

@@ -184,3 +182,3 @@ function processFile(argIn, argv) {

filename: argIn,
contents: yield (0, fs_1.readFile)((0, path_1.resolve)(process.cwd(), argIn), 'utf-8'),
contents: (0, fs_1.readFileSync)((0, path_1.resolve)(process.cwd(), argIn), 'utf-8'),
};

@@ -233,2 +231,4 @@ });

Prepend enums with 'const'?
--inferStringEnumKeysFromValues
Create enums from JSON enums instead of union types
--format

@@ -235,0 +235,0 @@ Format code? Set this to false to improve performance.

@@ -36,2 +36,6 @@ import { JSONSchema4 } from 'json-schema';

/**
* Create enums from JSON enums with eponymous keys
*/
inferStringEnumKeysFromValues: boolean;
/**
* Format code? Set this to `false` to improve performance.

@@ -38,0 +42,0 @@ */

@@ -39,2 +39,3 @@ "use strict";

enableConstEnums: true,
inferStringEnumKeysFromValues: false,
format: true,

@@ -41,0 +42,0 @@ ignoreMinAndMaxItems: false,

@@ -17,2 +17,5 @@ "use strict";

}
function isEnumTypeWithoutTsEnumNames(schema) {
return schema.type === 'string' && schema.enum !== undefined && schema.tsEnumNames === undefined;
}
rules.set('Remove `type=["null"]` if `enum=[null]`', schema => {

@@ -187,2 +190,8 @@ if (Array.isArray(schema.enum) &&

});
rules.set('Add tsEnumNames to enum types', (schema, _, options) => {
var _a;
if (isEnumTypeWithoutTsEnumNames(schema) && options.inferStringEnumKeysFromValues) {
schema.tsEnumNames = (_a = schema.enum) === null || _a === void 0 ? void 0 : _a.map(String);
}
});
function normalize(rootSchema, dereferencedPaths, filename, options) {

@@ -189,0 +198,0 @@ rules.forEach(rule => (0, utils_1.traverse)(rootSchema, (schema, key) => rule(schema, filename, options, key, dereferencedPaths)));

import { JSONSchema4Type } from 'json-schema';
import { Options } from './';
import { AST } from './types/AST';
import { JSONSchema as LinkedJSONSchema, SchemaType } from './types/JSONSchema';
export type Processed = Map<LinkedJSONSchema, Map<SchemaType, AST>>;
import { NormalizedJSONSchema, SchemaType } from './types/JSONSchema';
export type Processed = Map<NormalizedJSONSchema, Map<SchemaType, AST>>;
export type UsedNames = Set<string>;
export declare function parse(schema: LinkedJSONSchema | JSONSchema4Type, options: Options, keyName?: string, processed?: Processed, usedNames?: Set<string>): AST;
export declare function parse(schema: NormalizedJSONSchema | JSONSchema4Type, options: Options, keyName?: string, processed?: Processed, usedNames?: Set<string>): AST;

@@ -26,5 +26,8 @@ "use strict";

const ast = parseAsTypeWithCache({
[JSONSchema_1.Parent]: schema[JSONSchema_1.Parent],
$id: schema.$id,
additionalProperties: schema.additionalProperties,
allOf: [],
description: schema.description,
required: schema.required,
title: schema.title,

@@ -225,3 +228,3 @@ }, 'ALL_OF', options, keyName, processed, usedNames);

params: schema.type.map(type => {
const member = Object.assign(Object.assign({}, (0, lodash_1.omit)(schema, '$id', 'description', 'title')), { type });
const member = Object.assign(Object.assign({}, (0, lodash_1.omit)(schema, '$id', 'description', 'title')), { type, additionalProperties: schema.additionalProperties, required: schema.required });
return parse((0, utils_1.maybeStripDefault)(member), options, undefined, processed, usedNames);

@@ -228,0 +231,0 @@ }),

@@ -47,3 +47,9 @@ /// <reference types="lodash" />

}
export interface NormalizedJSONSchema extends LinkedJSONSchema {
/**
* Normalized JSON schema.
*
* Note: `definitions` and `id` are removed by the normalizer. Use `$defs` and `$id` instead.
*/
export interface NormalizedJSONSchema extends Omit<LinkedJSONSchema, 'definitions' | 'id'> {
[Parent]: NormalizedJSONSchema | null;
additionalItems?: boolean | NormalizedJSONSchema;

@@ -70,7 +76,5 @@ additionalProperties: boolean | NormalizedJSONSchema;

required: string[];
definitions: never;
id: never;
}
export interface EnumJSONSchema extends NormalizedJSONSchema {
enum: any[];
enum: JSONSchema4Type[];
}

@@ -94,5 +98,5 @@ export interface NamedEnumJSONSchema extends NormalizedJSONSchema {

}
export declare const getRootSchema: ((schema: LinkedJSONSchema) => LinkedJSONSchema) & import("lodash").MemoizedFunction;
export declare const getRootSchema: ((schema: NormalizedJSONSchema) => NormalizedJSONSchema) & import("lodash").MemoizedFunction;
export declare function isBoolean(schema: LinkedJSONSchema | JSONSchemaType): schema is boolean;
export declare function isPrimitive(schema: LinkedJSONSchema | JSONSchemaType): schema is JSONSchemaType;
export declare function isCompound(schema: JSONSchema): boolean;

@@ -1,2 +0,2 @@

import { JSONSchema, LinkedJSONSchema } from './types/JSONSchema';
import { JSONSchema, LinkedJSONSchema, NormalizedJSONSchema } from './types/JSONSchema';
import { JSONSchema4 } from 'json-schema';

@@ -41,3 +41,3 @@ export declare function Try<T>(fn: () => T, err: (e: Error) => any): T;

*/
export declare function maybeStripNameHints(schema: JSONSchema): JSONSchema;
export declare function maybeStripNameHints(schema: NormalizedJSONSchema): NormalizedJSONSchema;
export declare function appendToDescription(existingDescription: string | undefined, ...values: string[]): string;

@@ -44,0 +44,0 @@ export declare function isSchemaLike(schema: LinkedJSONSchema): boolean;

{
"name": "json-schema-to-typescript",
"version": "14.0.5",
"version": "14.1.0",
"description": "compile json schema to typescript typings",

@@ -61,3 +61,2 @@ "main": "dist/src/index.js",

"mkdirp": "^3.0.1",
"mz": "^2.7.0",
"node-fetch": "^3.3.2",

@@ -72,3 +71,2 @@ "prettier": "^3.2.5"

"@types/mkdirp": "^2.0.0",
"@types/mz": "^2.7.8",
"@types/node": "^20.12.7",

@@ -75,0 +73,0 @@ "@types/rimraf": "^4.0.5",

@@ -141,2 +141,3 @@ # json-schema-to-typescript [![Build Status][build]](https://github.com/bcherny/json-schema-to-typescript/actions?query=branch%3Amaster+workflow%3ACI) [![npm]](https://www.npmjs.com/package/json-schema-to-typescript) [![mit]](https://opensource.org/licenses/MIT) ![node]

| enableConstEnums | boolean | `true` | Prepend enums with [`const`](https://www.typescriptlang.org/docs/handbook/enums.html#computed-and-constant-members)? |
| inferStringEnumKeysFromValues | boolean | `false` | Create enums from JSON enums with eponymous keys |
| format | boolean | `true` | Format code? Set this to `false` to improve performance. |

@@ -143,0 +144,0 @@ | ignoreMinAndMaxItems | boolean | `false` | Ignore maxItems and minItems for `array` types, preventing tuples being generated. |

#!/usr/bin/env node
import minimist from 'minimist'
import {readFile, writeFile, existsSync, lstatSync, readdirSync} from 'mz/fs'
import {readFileSync, writeFileSync, existsSync, lstatSync, readdirSync} from 'fs'
import * as mkdirp from 'mkdirp'

@@ -117,3 +117,3 @@ import {glob} from 'glob'

async function outputResult(result: string, outputPath: string | undefined): Promise<void> {
function outputResult(result: string, outputPath: string | undefined): void {
if (!outputPath) {

@@ -125,3 +125,3 @@ process.stdout.write(result)

}
return await writeFile(outputPath, result)
return writeFileSync(outputPath, result)
}

@@ -155,3 +155,3 @@ }

filename: argIn,
contents: await readFile(resolve(process.cwd(), argIn), 'utf-8'),
contents: readFileSync(resolve(process.cwd(), argIn), 'utf-8'),
}

@@ -161,3 +161,3 @@ }

async function readStream(stream: NodeJS.ReadStream): Promise<string> {
const chunks = []
const chunks: Uint8Array[] = []
for await (const chunk of stream) chunks.push(chunk)

@@ -190,2 +190,4 @@ return Buffer.concat(chunks).toString('utf8')

Prepend enums with 'const'?
--inferStringEnumKeysFromValues
Create enums from JSON enums instead of union types
--format

@@ -192,0 +194,0 @@ Format code? Set this to false to improve performance.

@@ -52,2 +52,6 @@ import {readFileSync} from 'fs'

/**
* Create enums from JSON enums with eponymous keys
*/
inferStringEnumKeysFromValues: boolean
/**
* Format code? Set this to `false` to improve performance.

@@ -99,2 +103,3 @@ */

enableConstEnums: true,
inferStringEnumKeysFromValues: false,
format: true,

@@ -101,0 +106,0 @@ ignoreMinAndMaxItems: false,

@@ -25,2 +25,5 @@ import {JSONSchemaTypeName, LinkedJSONSchema, NormalizedJSONSchema, Parent} from './types/JSONSchema'

}
function isEnumTypeWithoutTsEnumNames(schema: LinkedJSONSchema) {
return schema.type === 'string' && schema.enum !== undefined && schema.tsEnumNames === undefined
}

@@ -226,2 +229,8 @@ rules.set('Remove `type=["null"]` if `enum=[null]`', schema => {

rules.set('Add tsEnumNames to enum types', (schema, _, options) => {
if (isEnumTypeWithoutTsEnumNames(schema) && options.inferStringEnumKeysFromValues) {
schema.tsEnumNames = schema.enum?.map(String)
}
})
export function normalize(

@@ -228,0 +237,0 @@ rootSchema: LinkedJSONSchema,

@@ -19,7 +19,9 @@ import {JSONSchema4Type, JSONSchema4TypeName} from 'json-schema'

import {
EnumJSONSchema,
getRootSchema,
isBoolean,
isPrimitive,
JSONSchema as LinkedJSONSchema,
JSONSchemaWithDefinitions,
NormalizedJSONSchema,
Parent,
SchemaSchema,

@@ -30,3 +32,3 @@ SchemaType,

export type Processed = Map<LinkedJSONSchema, Map<SchemaType, AST>>
export type Processed = Map<NormalizedJSONSchema, Map<SchemaType, AST>>

@@ -36,3 +38,3 @@ export type UsedNames = Set<string>

export function parse(
schema: LinkedJSONSchema | JSONSchema4Type,
schema: NormalizedJSONSchema | JSONSchema4Type,
options: Options,

@@ -62,5 +64,8 @@ keyName?: string,

{
[Parent]: schema[Parent],
$id: schema.$id,
additionalProperties: schema.additionalProperties,
allOf: [],
description: schema.description,
required: schema.required,
title: schema.title,

@@ -86,3 +91,3 @@ },

function parseAsTypeWithCache(
schema: LinkedJSONSchema,
schema: NormalizedJSONSchema,
type: SchemaType,

@@ -139,3 +144,3 @@ options: Options,

function parseNonLiteral(
schema: LinkedJSONSchema,
schema: NormalizedJSONSchema,
type: SchemaType,

@@ -200,3 +205,3 @@ options: Options,

standaloneName: standaloneName(schema, keyNameFromDefinition ?? keyName, usedNames, options)!,
params: schema.enum!.map((_, n) => ({
params: (schema as EnumJSONSchema).enum!.map((_, n) => ({
ast: parseLiteral(_, undefined),

@@ -298,3 +303,8 @@ keyName: schema.tsEnumNames![n],

params: (schema.type as JSONSchema4TypeName[]).map(type => {
const member: LinkedJSONSchema = {...omit(schema, '$id', 'description', 'title'), type}
const member: NormalizedJSONSchema = {
...omit(schema, '$id', 'description', 'title'),
type,
additionalProperties: schema.additionalProperties,
required: schema.required,
}
return parse(maybeStripDefault(member as any), options, undefined, processed, usedNames)

@@ -310,3 +320,3 @@ }),

standaloneName: standaloneName(schema, keyNameFromDefinition, usedNames, options),
params: schema.enum!.map(_ => parseLiteral(_, undefined)),
params: (schema as EnumJSONSchema).enum!.map(_ => parseLiteral(_, undefined)),
type: 'UNION',

@@ -352,3 +362,3 @@ }

function standaloneName(
schema: LinkedJSONSchema,
schema: NormalizedJSONSchema,
keyNameFromDefinition: string | undefined,

@@ -491,8 +501,8 @@ usedNames: UsedNames,

type Definitions = {[k: string]: LinkedJSONSchema}
type Definitions = {[k: string]: NormalizedJSONSchema}
function getDefinitions(
schema: LinkedJSONSchema,
schema: NormalizedJSONSchema,
isSchema = true,
processed = new Set<LinkedJSONSchema>(),
processed = new Set<NormalizedJSONSchema>(),
): Definitions {

@@ -532,4 +542,4 @@ if (processed.has(schema)) {

*/
function hasDefinitions(schema: LinkedJSONSchema): schema is JSONSchemaWithDefinitions {
function hasDefinitions(schema: NormalizedJSONSchema): schema is JSONSchemaWithDefinitions {
return '$defs' in schema
}

@@ -73,3 +73,10 @@ import {JSONSchema4, JSONSchema4Type, JSONSchema4TypeName} from 'json-schema'

export interface NormalizedJSONSchema extends LinkedJSONSchema {
/**
* Normalized JSON schema.
*
* Note: `definitions` and `id` are removed by the normalizer. Use `$defs` and `$id` instead.
*/
export interface NormalizedJSONSchema extends Omit<LinkedJSONSchema, 'definitions' | 'id'> {
[Parent]: NormalizedJSONSchema | null
additionalItems?: boolean | NormalizedJSONSchema

@@ -96,10 +103,6 @@ additionalProperties: boolean | NormalizedJSONSchema

required: string[]
// Removed by normalizer
definitions: never
id: never
}
export interface EnumJSONSchema extends NormalizedJSONSchema {
enum: any[]
enum: JSONSchema4Type[]
}

@@ -128,3 +131,3 @@

export const getRootSchema = memoize((schema: LinkedJSONSchema): LinkedJSONSchema => {
export const getRootSchema = memoize((schema: NormalizedJSONSchema): NormalizedJSONSchema => {
const parent = schema[Parent]

@@ -131,0 +134,0 @@ if (!parent) {

import {deburr, isPlainObject, trim, upperFirst} from 'lodash'
import {basename, dirname, extname, normalize, sep, posix} from 'path'
import {JSONSchema, LinkedJSONSchema, Parent} from './types/JSONSchema'
import {JSONSchema, LinkedJSONSchema, NormalizedJSONSchema, Parent} from './types/JSONSchema'
import {JSONSchema4} from 'json-schema'

@@ -341,3 +341,3 @@ import yaml from 'js-yaml'

*/
export function maybeStripNameHints(schema: JSONSchema): JSONSchema {
export function maybeStripNameHints(schema: NormalizedJSONSchema): NormalizedJSONSchema {
if ('$id' in schema) {

@@ -344,0 +344,0 @@ delete schema.$id

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap
  • Changelog

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc