Skip to content

Commit

Permalink
autoformat everything
Browse files Browse the repository at this point in the history
  • Loading branch information
bcherny committed Aug 27, 2023
1 parent a104878 commit aebe91e
Show file tree
Hide file tree
Showing 119 changed files with 27,635 additions and 27,684 deletions.
4 changes: 2 additions & 2 deletions example/index.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { writeFileSync } from 'fs'
import { compileFromFile } from 'json-schema-to-typescript'
import {writeFileSync} from 'fs'
import {compileFromFile} from 'json-schema-to-typescript'

async function generate() {
writeFileSync('person.d.ts', await compileFromFile('person.json'))
Expand Down
10 changes: 5 additions & 5 deletions example/person.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,12 +6,12 @@
*/

export interface Person {
firstName: string;
lastName: string;
firstName: string
lastName: string
/**
* Age in years
*/
age?: number;
hairColor?: "black" | "brown" | "blue";
[k: string]: unknown;
age?: number
hairColor?: 'black' | 'brown' | 'blue'
[k: string]: unknown
}
20 changes: 10 additions & 10 deletions src/cli.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ main(
alias: {
help: ['h'],
input: ['i'],
output: ['o']
output: ['o'],
},
boolean: [
'additionalProperties',
Expand All @@ -25,11 +25,11 @@ main(
'ignoreMinAndMaxItems',
'strictIndexSignatures',
'unknownAny',
'unreachableDefinitions'
'unreachableDefinitions',
],
default: DEFAULT_OPTIONS,
string: ['bannerComment', 'cwd']
})
string: ['bannerComment', 'cwd'],
}),
)

async function main(argv: minimist.ParsedArgs) {
Expand All @@ -46,7 +46,7 @@ async function main(argv: minimist.ParsedArgs) {

if ((ISGLOB || ISDIR) && argOut && argOut.includes('.d.ts')) {
throw new ReferenceError(
`You have specified a single file ${argOut} output for a multi file input ${argIn}. This feature is not yet supported, refer to issue #272 (https://github.com/bcherny/json-schema-to-typescript/issues/272)`
`You have specified a single file ${argOut} output for a multi file input ${argIn}. This feature is not yet supported, refer to issue #272 (https://github.com/bcherny/json-schema-to-typescript/issues/272)`,
)
}

Expand Down Expand Up @@ -76,15 +76,15 @@ async function processGlob(argIn: string, argOut: string | undefined, argv: Part

if (files.length === 0) {
throw ReferenceError(
`You passed a glob pattern "${argIn}", but there are no files that match that pattern in ${process.cwd()}`
`You passed a glob pattern "${argIn}", but there are no files that match that pattern in ${process.cwd()}`,
)
}

// we can do this concurrently for perf
const results = await Promise.all(
files.map(async file => {
return [file, await processFile(file, argv)] as const
})
}),
)

// careful to do this serially
Expand All @@ -106,12 +106,12 @@ async function processDir(argIn: string, argOut: string | undefined, argv: Parti
const outputPath = pathTransform(argOut, argIn, file)
return [file, await processFile(file, argv), outputPath] as const
}
})
}),
)

// careful to do this serially
results.forEach(([file, result, outputPath]) =>
outputResult(result, outputPath ? `${outputPath}/${basename(file, '.json')}.d.ts` : undefined)
outputResult(result, outputPath ? `${outputPath}/${basename(file, '.json')}.d.ts` : undefined),
)
}

Expand Down Expand Up @@ -184,6 +184,6 @@ Boolean values can be set to false using the 'no-' prefix.
Output unknown type instead of any type
--unreachableDefinitions
Generates code for definitions that aren't referenced by the schema
`
`,
)
}
18 changes: 9 additions & 9 deletions src/generator.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ import {
TIntersection,
TNamedInterface,
TUnion,
T_UNKNOWN
T_UNKNOWN,
} from './types/AST'
import {log, toSafeString} from './utils'

Expand All @@ -22,7 +22,7 @@ export function generate(ast: AST, options = DEFAULT_OPTIONS): string {
options.bannerComment,
declareNamedTypes(ast, options, ast.standaloneName!),
declareNamedInterfaces(ast, options, ast.standaloneName!),
declareEnums(ast, options)
declareEnums(ast, options),
]
.filter(Boolean)
.join('\n\n') + '\n'
Expand Down Expand Up @@ -78,7 +78,7 @@ function declareNamedInterfaces(ast: AST, options: Options, rootASTName: string,
getSuperTypesAndParams(ast)
.map(ast => declareNamedInterfaces(ast, options, rootASTName, processed))
.filter(Boolean)
.join('\n')
.join('\n'),
]
.filter(Boolean)
.join('\n')
Expand Down Expand Up @@ -112,7 +112,7 @@ function declareNamedTypes(ast: AST, options: Options, rootASTName: string, proc
case 'ARRAY':
return [
declareNamedTypes(ast.params, options, rootASTName, processed),
hasStandaloneName(ast) ? generateStandaloneType(ast, options) : undefined
hasStandaloneName(ast) ? generateStandaloneType(ast, options) : undefined,
]
.filter(Boolean)
.join('\n')
Expand All @@ -123,7 +123,7 @@ function declareNamedTypes(ast: AST, options: Options, rootASTName: string, proc
.map(
ast =>
(ast.standaloneName === rootASTName || options.declareExternallyReferenced) &&
declareNamedTypes(ast, options, rootASTName, processed)
declareNamedTypes(ast, options, rootASTName, processed),
)
.filter(Boolean)
.join('\n')
Expand All @@ -138,7 +138,7 @@ function declareNamedTypes(ast: AST, options: Options, rootASTName: string, proc
.join('\n'),
'spreadParam' in ast && ast.spreadParam
? declareNamedTypes(ast.spreadParam, options, rootASTName, processed)
: undefined
: undefined,
]
.filter(Boolean)
.join('\n')
Expand Down Expand Up @@ -300,15 +300,15 @@ function generateInterface(ast: TInterface, options: Options): string {
.filter(_ => !_.isPatternProperty && !_.isUnreachableDefinition)
.map(
({isRequired, keyName, ast}) =>
[isRequired, keyName, ast, generateType(ast, options)] as [boolean, string, AST, string]
[isRequired, keyName, ast, generateType(ast, options)] as [boolean, string, AST, string],
)
.map(
([isRequired, keyName, ast, type]) =>
(hasComment(ast) && !ast.standaloneName ? generateComment(ast.comment, ast.deprecated) + '\n' : '') +
escapeKeyName(keyName) +
(isRequired ? '' : '?') +
': ' +
type
type,
)
.join('\n') +
'\n' +
Expand Down Expand Up @@ -355,7 +355,7 @@ function generateStandaloneType(ast: ASTWithStandaloneName, options: Options): s
(hasComment(ast) ? generateComment(ast.comment) + '\n' : '') +
`export type ${toSafeString(ast.standaloneName)} = ${generateType(
omit<AST>(ast, 'standaloneName') as AST /* TODO */,
options
options,
)}`
)
}
Expand Down
8 changes: 4 additions & 4 deletions src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -101,24 +101,24 @@ export const DEFAULT_OPTIONS: Options = {
singleQuote: false,
tabWidth: 2,
trailingComma: 'none',
useTabs: false
useTabs: false,
},
unreachableDefinitions: false,
unknownAny: true
unknownAny: true,
}

export function compileFromFile(filename: string, options: Partial<Options> = DEFAULT_OPTIONS): Promise<string> {
const contents = Try(
() => readFileSync(filename),
() => {
throw new ReferenceError(`Unable to read file "${filename}"`)
}
},
)
const schema = Try<JSONSchema4>(
() => JSON.parse(contents.toString()),
() => {
throw new TypeError(`Error parsing JSON in file "${filename}"`)
}
},
)
return compile(schema, stripExtension(filename), {cwd: dirname(filename), ...options})
}
Expand Down
2 changes: 1 addition & 1 deletion src/linker.ts
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@ export function link(schema: JSONSchema4Type | JSONSchema, parent: JSONSchema4Ty
Object.defineProperty(schema, Parent, {
enumerable: false,
value: parent,
writable: false
writable: false,
})

// Arrays
Expand Down
10 changes: 5 additions & 5 deletions src/normalizer.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ type Rule = (
fileName: string,
options: Options,
key: string | null,
dereferencedPaths: DereferencedPaths
dereferencedPaths: DereferencedPaths,
) => void
const rules = new Map<string, Rule>()

Expand Down Expand Up @@ -64,7 +64,7 @@ rules.set('Transform id to $id', (schema, fileName) => {
}
if (schema.id && schema.$id && schema.id !== schema.$id) {
throw ReferenceError(
`Schema must define either id or $id, not both. Given id=${schema.id}, $id=${schema.$id} in ${fileName}`
`Schema must define either id or $id, not both. Given id=${schema.id}, $id=${schema.$id} in ${fileName}`,
)
}
if (schema.id) {
Expand Down Expand Up @@ -111,7 +111,7 @@ rules.set('Add JSDoc comments for minItems and maxItems', schema => {
}
const commentsToAppend = [
'minItems' in schema ? `@minItems ${schema.minItems}` : '',
'maxItems' in schema ? `@maxItems ${schema.maxItems}` : ''
'maxItems' in schema ? `@maxItems ${schema.maxItems}` : '',
].filter(Boolean)
if (commentsToAppend.length) {
schema.description = appendToDescription(schema.description, ...commentsToAppend)
Expand Down Expand Up @@ -206,7 +206,7 @@ rules.set('Make extends always an array, if it is defined', schema => {
rules.set('Transform definitions to $defs', (schema, fileName) => {
if (schema.definitions && schema.$defs && !isDeepStrictEqual(schema.definitions, schema.$defs)) {
throw ReferenceError(
`Schema must define either definitions or $defs, not both. Given id=${schema.id} in ${fileName}`
`Schema must define either definitions or $defs, not both. Given id=${schema.id} in ${fileName}`,
)
}
if (schema.definitions) {
Expand All @@ -226,7 +226,7 @@ export function normalize(
rootSchema: LinkedJSONSchema,
dereferencedPaths: DereferencedPaths,
filename: string,
options: Options
options: Options,
): NormalizedJSONSchema {
rules.forEach(rule => traverse(rootSchema, (schema, key) => rule(schema, filename, options, key, dereferencedPaths)))
return rootSchema as NormalizedJSONSchema
Expand Down
6 changes: 3 additions & 3 deletions src/optimizer.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,13 +14,13 @@ export function optimize(ast: AST, options: Options, processed = new Set<AST>())
switch (ast.type) {
case 'INTERFACE':
return Object.assign(ast, {
params: ast.params.map(_ => Object.assign(_, {ast: optimize(_.ast, options, processed)}))
params: ast.params.map(_ => Object.assign(_, {ast: optimize(_.ast, options, processed)})),
})
case 'INTERSECTION':
case 'UNION':
// Start with the leaves...
const optimizedAST = Object.assign(ast, {
params: ast.params.map(_ => optimize(_, options, processed))
params: ast.params.map(_ => optimize(_, options, processed)),
})

// [A, B, C, Any] -> Any
Expand Down Expand Up @@ -56,7 +56,7 @@ export function optimize(ast: AST, options: Options, processed = new Set<AST>())
}

return Object.assign(optimizedAST, {
params: optimizedAST.params.map(_ => optimize(_, options, processed))
params: optimizedAST.params.map(_ => optimize(_, options, processed)),
})
default:
return ast
Expand Down
6 changes: 3 additions & 3 deletions src/resolver.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ export type DereferencedPaths = WeakMap<$RefParser.JSONSchemaObject, string>

export async function dereference(
schema: JSONSchema,
{cwd, $refOptions}: {cwd: string; $refOptions: $RefParser.Options}
{cwd, $refOptions}: {cwd: string; $refOptions: $RefParser.Options},
): Promise<{dereferencedPaths: DereferencedPaths; dereferencedSchema: JSONSchema}> {
log('green', 'dereferencer', 'Dereferencing input schema:', cwd, schema)
const parser = new $RefParser()
Expand All @@ -17,8 +17,8 @@ export async function dereference(
...$refOptions.dereference,
onDereference($ref, schema) {
dereferencedPaths.set(schema, $ref)
}
}
},
},
})) as any // TODO: fix types
return {dereferencedPaths, dereferencedSchema}
}
8 changes: 4 additions & 4 deletions src/types/AST.ts
Original file line number Diff line number Diff line change
Expand Up @@ -153,19 +153,19 @@ export interface TCustomType extends AbstractAST {
//////////////////////////////////////////// literals

export const T_ANY: TAny = {
type: 'ANY'
type: 'ANY',
}

export const T_ANY_ADDITIONAL_PROPERTIES: TAny & ASTWithName = {
keyName: '[k: string]',
type: 'ANY'
type: 'ANY',
}

export const T_UNKNOWN: TUnknown = {
type: 'UNKNOWN'
type: 'UNKNOWN',
}

export const T_UNKNOWN_ADDITIONAL_PROPERTIES: TUnknown & ASTWithName = {
keyName: '[k: string]',
type: 'UNKNOWN'
type: 'UNKNOWN',
}
2 changes: 1 addition & 1 deletion src/typesOfSchema.ts
Original file line number Diff line number Diff line change
Expand Up @@ -145,5 +145,5 @@ const matchers: Record<SchemaType, (schema: JSONSchema) => boolean> = {
},
UNTYPED_ARRAY(schema) {
return schema.type === 'array' && !('items' in schema)
}
},
}
12 changes: 6 additions & 6 deletions src/utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -46,13 +46,13 @@ const BLACKLISTED_KEYS = new Set([
'allOf',
'anyOf',
'oneOf',
'not'
'not',
])

function traverseObjectKeys(
obj: Record<string, LinkedJSONSchema>,
callback: (schema: LinkedJSONSchema, key: string | null) => void,
processed: Set<LinkedJSONSchema>
processed: Set<LinkedJSONSchema>,
) {
Object.keys(obj).forEach(k => {
if (obj[k] && typeof obj[k] === 'object' && !Array.isArray(obj[k])) {
Expand All @@ -64,7 +64,7 @@ function traverseObjectKeys(
function traverseArray(
arr: LinkedJSONSchema[],
callback: (schema: LinkedJSONSchema, key: string | null) => void,
processed: Set<LinkedJSONSchema>
processed: Set<LinkedJSONSchema>,
) {
arr.forEach((s, k) => traverse(s, callback, processed, k.toString()))
}
Expand All @@ -73,7 +73,7 @@ export function traverse(
schema: LinkedJSONSchema,
callback: (schema: LinkedJSONSchema, key: string | null) => void,
processed = new Set<LinkedJSONSchema>(),
key?: string
key?: string,
): void {
// Handle recursive schemas
if (processed.has(schema)) {
Expand Down Expand Up @@ -177,7 +177,7 @@ export function toSafeString(string: string) {
// uppercase first letter after whitespace
.replace(/\s+([a-zA-Z])/g, match => trim(match.toUpperCase()))
// remove remaining whitespace
.replace(/\s/g, '')
.replace(/\s/g, ''),
)
}

Expand Down Expand Up @@ -376,7 +376,7 @@ export function isSchemaLike(schema: LinkedJSONSchema) {
'oneOf',
'patternProperties',
'properties',
'required'
'required',
]
if (JSON_SCHEMA_KEYWORDS.some(_ => parent[_] === schema)) {
return false
Expand Down
Loading

0 comments on commit aebe91e

Please sign in to comment.