Skip to content

add support for importing typescript types and deduping imports #662

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 25 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
11 changes: 10 additions & 1 deletion src/cli.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
#!/usr/bin/env node

import minimist from 'minimist'
import {cloneDeep} from 'lodash'
import {readFileSync, writeFileSync, existsSync, lstatSync, readdirSync, mkdirSync} from 'fs'
import {glob, isDynamicPattern} from 'tinyglobby'
import {join, resolve, dirname} from 'path'
Expand All @@ -23,6 +24,7 @@ main(
'strictIndexSignatures',
'unknownAny',
'unreachableDefinitions',
'useTypeImports',
],
default: DEFAULT_OPTIONS,
string: ['bannerComment', 'cwd'],
Expand Down Expand Up @@ -101,7 +103,11 @@ async function processDir(argIn: string, argOut: string | undefined, argv: Parti
return [file, await processFile(file, argv)] as const
} else {
const outputPath = pathTransform(argOut, argIn, file)
return [file, await processFile(file, argv), outputPath] as const
// get argv with cwd corrected. We want to resolve relevant to dir.
const opts = cloneDeep(argv)
const dirPath = resolve(dirname(file))
opts.cwd = resolve(dirPath)
return [file, await processFile(file, opts), outputPath] as const
}
}),
)
Expand Down Expand Up @@ -179,6 +185,9 @@ Boolean values can be set to false using the 'no-' prefix.
Root directory for resolving $ref
--declareExternallyReferenced
Declare external schemas referenced via '$ref'?
--useTypeImports
Access external schemas referenced via '$ref' using 'import type'? This
requires --declareExternallyReferenced=false.
--enableConstEnums
Prepend enums with 'const'?
--inferStringEnumKeysFromValues
Expand Down
35 changes: 29 additions & 6 deletions src/generator.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@ import {
T_UNKNOWN,
} from './types/AST'
import {log, toSafeString} from './utils'
import {basename, dirname, extname, join} from 'path'

export function generate(ast: AST, options = DEFAULT_OPTIONS): string {
return (
Expand Down Expand Up @@ -349,14 +350,36 @@ function generateStandaloneEnum(ast: TEnum, options: Options): string {
}

function generateStandaloneInterface(ast: TNamedInterface, options: Options): string {
return (
(hasComment(ast) ? generateComment(ast.comment, ast.deprecated) + '\n' : '') +
const lines: string[] = []

hasComment(ast) ? lines.push(generateComment(ast.comment, ast.deprecated) + '\n') : lines.push('')

if (options.useTypeImports) {
for (const param of ast.params) {
if (param.ast.standaloneName && param.referencePath) {
const dir = dirname(param.referencePath)
const nameWithoutExt = basename(param.referencePath, extname(param.referencePath))
// If we needed to rename due to name clashes, import with the original
// name.
const importInBrackets =
param.ast.originalName && param.ast.originalName !== param.ast.standaloneName
? `${param.ast.originalName} as ${param.ast.standaloneName}`
: param.ast.standaloneName
const importPath = './' + join(dir, `${nameWithoutExt}.ts`)
lines.push(`import type { ${importInBrackets} } from '${importPath}';`)
}
}
}

lines.push(
`export interface ${toSafeString(ast.standaloneName)} ` +
(ast.superTypes.length > 0
? `extends ${ast.superTypes.map(superType => toSafeString(superType.standaloneName)).join(', ')} `
: '') +
generateInterface(ast, options)
(ast.superTypes.length > 0
? `extends ${ast.superTypes.map(superType => toSafeString(superType.standaloneName)).join(', ')} `
: '') +
generateInterface(ast, options),
)

return lines.join('')
}

function generateStandaloneType(ast: ASTWithStandaloneName, options: Options): string {
Expand Down
13 changes: 11 additions & 2 deletions src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -44,6 +44,10 @@ export interface Options {
* Declare external schemas referenced via `$ref`?
*/
declareExternallyReferenced: boolean
/**
* Use `import type` instead of redeclaring.
*/
useTypeImports: boolean
/**
* Prepend enums with [`const`](https://www.typescriptlang.org/docs/handbook/enums.html#computed-and-constant-members)?
*/
Expand Down Expand Up @@ -98,6 +102,7 @@ export const DEFAULT_OPTIONS: Options = {
*/`,
cwd: process.cwd(),
declareExternallyReferenced: true,
useTypeImports: false,
enableConstEnums: true,
inferStringEnumKeysFromValues: false,
format: true,
Expand Down Expand Up @@ -135,7 +140,10 @@ function parseAsJSONSchema(filename: string): JSONSchema4 {
export async function compile(schema: JSONSchema4, name: string, options: Partial<Options> = {}): Promise<string> {
validateOptions(options)

const _options = merge({}, DEFAULT_OPTIONS, options)
// useTypeImports implies declareExternallyReferenced = false
const optionOverrides = options.useTypeImports ? {declareExternallyReferenced: false} : {}

const _options = merge({}, DEFAULT_OPTIONS, options, optionOverrides)

const start = Date.now()
function time() {
Expand All @@ -151,6 +159,7 @@ export async function compile(schema: JSONSchema4, name: string, options: Partia
const _schema = cloneDeep(schema)

const {dereferencedPaths, dereferencedSchema} = await dereference(_schema, _options)

if (process.env.VERBOSE) {
if (isDeepStrictEqual(_schema, dereferencedSchema)) {
log('green', 'dereferencer', time(), '✅ No change')
Expand All @@ -176,7 +185,7 @@ export async function compile(schema: JSONSchema4, name: string, options: Partia
const normalized = normalize(linked, dereferencedPaths, name, _options)
log('yellow', 'normalizer', time(), '✅ Result:', normalized)

const parsed = parse(normalized, _options)
const parsed = parse(normalized, _options, dereferencedPaths)
log('blue', 'parser', time(), '✅ Result:', parsed)

const optimized = optimize(parsed, _options)
Expand Down
4 changes: 0 additions & 4 deletions src/normalizer.ts
Original file line number Diff line number Diff line change
Expand Up @@ -99,10 +99,6 @@ rules.set('Add an $id to anything that needs it', (schema, fileName, _options, _
if (!schema.$id && !schema.title && dereferencedName) {
schema.$id = toSafeString(justName(dereferencedName))
}

if (dereferencedName) {
dereferencedPaths.delete(schema)
}
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This seems less than ideal. I need this elsewhere, and I'm wondering if there's a more natural way to register the source path for this schema without needing to keep all references in this map.

})

rules.set('Escape closing JSDoc comment', schema => {
Expand Down
Loading