Skip to content
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

feat: tsType, type and markdownType #22

Merged
merged 7 commits into from
Nov 5, 2021
Merged
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
1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -45,6 +45,7 @@
"marked": "latest",
"monaco-editor": "latest",
"prismjs": "latest",
"scule": "latest",
"siroc": "latest",
"standard-version": "latest",
"ts-jest": "latest",
Expand Down
12 changes: 10 additions & 2 deletions src/generator/dts.ts
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,8 @@ const SCHEMA_KEYS = [
'description',
'$schema',
'type',
'tsType',
'markdownType',
'tags',
'args',
'id',
Expand Down Expand Up @@ -67,7 +69,13 @@ function getTsType (type: TypeDescriptor | TypeDescriptor[]): string {
if (Array.isArray(type)) {
return [].concat(normalizeTypes(type.map(t => getTsType(t)))).join('|') || 'any'
}
if (!type || !type.type) {
if (!type) {
return 'any'
}
if (type.tsType) {
return type.tsType
}
if (!type.type) {
return 'any'
}
if (Array.isArray(type.type)) {
Expand All @@ -89,7 +97,7 @@ export function genFunctionArgs (args: Schema['args']) {
if (arg.optional || arg.default) {
argStr += '?'
}
if (arg.type) {
if (arg.type || arg.tsType) {
argStr += `: ${getTsType(arg)}`
}
return argStr
Expand Down
4 changes: 2 additions & 2 deletions src/generator/md.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ export function _generateMarkdown (schema: Schema, title: string, level: string)

lines.push(`${level} ${title}`)

if ('properties' in schema) {
if (schema.type === 'object') {
for (const key in schema.properties) {
const val = schema.properties[key] as Schema
lines.push('', ..._generateMarkdown(val, `\`${key}\``, level + '#'))
Expand All @@ -19,7 +19,7 @@ export function _generateMarkdown (schema: Schema, title: string, level: string)
}

// Type and default
lines.push(`- **Type**: \`${schema.type}\``)
lines.push(`- **Type**: \`${schema.markdownType || schema.tsType || schema.type}\``)
if ('default' in schema) {
lines.push(`- **Default**: \`${JSON.stringify(schema.default)}\``)
}
Expand Down
30 changes: 14 additions & 16 deletions src/loader/babel.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import type { ConfigAPI, PluginItem, PluginObj } from '@babel/core'
import * as t from '@babel/types'
import { Schema, JSType, TypeDescriptor, FunctionArg } from '../types'
import { normalizeTypes, mergedTypes, cachedFn } from '../utils'
import { normalizeTypes, mergedTypes, cachedFn, getTypeDescriptor } from '../utils'

import { version } from '../../package.json'

Expand Down Expand Up @@ -114,7 +114,7 @@ export default <PluginItem> function babelPluginUntyped (api: ConfigAPI) {
const { type } = tag.match(/^@returns\s+\{(?<type>[^}]+)\}/)?.groups || {}
if (type) {
schema.returns = schema.returns || {}
schema.returns.type = type
Object.assign(schema.returns, getTypeDescriptor(type))
return false
}
}
Expand All @@ -123,7 +123,7 @@ export default <PluginItem> function babelPluginUntyped (api: ConfigAPI) {
if (type && param) {
const arg = schema.args?.find(arg => arg.name === param)
if (arg) {
arg.type = type
Object.assign(arg, getTypeDescriptor(type))
return false
}
}
Expand Down Expand Up @@ -188,7 +188,13 @@ function parseJSDocs (input: string | string[]): Schema {
const tags = clumpLines(lines.slice(firstTag), ['@'], '\n')
for (const tag of tags) {
if (tag.startsWith('@type')) {
schema.type = tag.match(/@type\s+\{([^}]+)\}/)?.[1]
const type = tag.match(/@type\s+\{([^}]+)\}/)?.[1]
Object.assign(schema, getTypeDescriptor(type))
const typedef = tags.find(t => t.match(/@typedef\s+\{([^}]+)\} (.*)/)?.[2] === type)
if (typedef) {
schema.markdownType = type
schema.tsType = typedef.match(/@typedef\s+\{([^}]+)\}/)?.[1]
}
continue
}
schema.tags.push(tag.trim())
Expand Down Expand Up @@ -237,17 +243,13 @@ const AST_JSTYPE_MAP: Partial<Record<t.Expression['type'], JSType | 'RegExp'>> =

function inferArgType (e: t.Expression, getCode: GetCodeFn): TypeDescriptor {
if (AST_JSTYPE_MAP[e.type]) {
return {
type: AST_JSTYPE_MAP[e.type]
}
return getTypeDescriptor(AST_JSTYPE_MAP[e.type])
}
if (e.type === 'AssignmentExpression') {
return inferArgType(e.right, getCode)
}
if (e.type === 'NewExpression' && e.callee.type === 'Identifier') {
return {
type: e.callee.name
}
return getTypeDescriptor(e.callee.name)
}
if (e.type === 'ArrayExpression' || e.type === 'TupleExpression') {
const itemTypes = e.elements
Expand Down Expand Up @@ -279,9 +281,7 @@ function inferTSType (tsType: t.TSType, getCode: GetCodeFn): TypeDescriptor | nu
items: inferTSType(tsType.typeParameters.params[0], getCode)
}
}
return {
type: getCode(tsType.loc)
}
return getTypeDescriptor((getCode(tsType.loc)))
}
if (tsType.type === 'TSUnionType') {
return mergedTypes(...tsType.types.map(t => inferTSType(t, getCode)))
Expand All @@ -293,9 +293,7 @@ function inferTSType (tsType: t.TSType, getCode: GetCodeFn): TypeDescriptor | nu
}
}
// if (tsType.type.endsWith('Keyword')) {
return {
type: getCode(tsType.loc)
}
return getTypeDescriptor(getCode(tsType.loc))
// }
// return null
}
7 changes: 6 additions & 1 deletion src/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,12 @@ export type JSType =
export type ResolveFn = ((value: any, get: (key: string) => any) => JSValue)

export interface TypeDescriptor {
type?: JSType | JSType[] | string | string[]
/** Used internally to handle schema types */
type?: JSType | JSType[]
/** Fully resolved correct TypeScript type for generated TS declarations */
tsType?: string
/** Human-readable type description for use in generated documentation */
markdownType?: string
items?: TypeDescriptor | TypeDescriptor[]
}

Expand Down
35 changes: 33 additions & 2 deletions src/utils.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import { pascalCase } from 'scule'
import type { Schema, JSType, TypeDescriptor } from './types'

export function escapeKey (val: string): string {
Expand Down Expand Up @@ -87,15 +88,17 @@ export function mergedTypes (...types: TypeDescriptor[]): TypeDescriptor {
types = types.filter(Boolean)
if (types.length === 0) { return {} }
if (types.length === 1) { return types[0] }
const tsTypes = normalizeTypes(types.map(t => t.tsType).flat().filter(Boolean))
return {
type: normalizeTypes(types.map(t => t.type).flat().filter(Boolean)),
tsType: Array.isArray(tsTypes) ? tsTypes.join(' | ') : tsTypes,
items: mergedTypes(...types.map(t => t.items).flat().filter(Boolean))
}
}

export function normalizeTypes (val: string[]) {
export function normalizeTypes<T extends string> (val: T[]) {
const arr = unique(val.filter(str => str))
if (!arr.length || arr.includes('any')) { return undefined }
if (!arr.length || arr.includes('any' as any)) { return undefined }
return (arr.length > 1) ? arr : arr[0]
}

Expand All @@ -110,3 +113,31 @@ export function cachedFn (fn) {
return val
}
}

const jsTypes: JSType[] = ['string', 'number', 'bigint', 'boolean', 'symbol', 'function', 'object', 'any', 'array']

export function isJSType (val: unknown): val is JSType {
return jsTypes.includes(val as any)
}

const FRIENDLY_TYPE_RE = /typeof import\(['"](?<importName>[^'"]+)['"]\)(\[['"]|\.)(?<firstType>[^'"\s]+)(['"]\])?/g

export function getTypeDescriptor (type: string | JSType): TypeDescriptor {
if (!type) {
return {}
}

let markdownType = type
for (const match of type.matchAll(FRIENDLY_TYPE_RE) || []) {
const { importName, firstType } = match.groups || {}
if (importName && firstType) {
markdownType = markdownType.replace(match[0], pascalCase(importName) + pascalCase(firstType))
}
}

return {
...isJSType(type) ? { type } : {},
tsType: type,
...markdownType !== type ? { markdownType } : {}
}
}
48 changes: 42 additions & 6 deletions test/transform.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ describe('transform (functions)', () => {
type: 'string'
}, {
name: 'date',
type: 'Date'
tsType: 'Date'
}, {
name: 'append',
optional: true,
Expand All @@ -42,7 +42,7 @@ describe('transform (functions)', () => {
}
}, {
name: 'append',
type: 'false'
tsType: 'false'
}]
}
})
Expand All @@ -59,7 +59,7 @@ describe('transform (functions)', () => {
type: 'function',
args: [],
returns: {
type: 'void'
tsType: 'void'
}
}
})
Expand All @@ -84,7 +84,7 @@ describe('transform (functions)', () => {
{ name: 'b', type: 'number' }
],
returns: {
type: 'void'
tsType: 'void'
}
}
})
Expand Down Expand Up @@ -184,7 +184,42 @@ describe('transform (jsdoc)', () => {
/**
* @type {'src' | 'root'}
*/
srcDir: 'src'
srcDir: 'src',
/**
* @type {null | typeof import('path').posix | typeof import('net')['Socket']['PassThrough']}
*/
posix: null
}
`)
expectCodeToMatch(result, /export default ([\s\S]*)$/, {
srcDir: {
$default: 'src',
$schema: {
title: '',
description: '',
tsType: "'src' | 'root'"
}
},
posix: {
$default: null,
$schema: {
title: '',
description: '',
tsType: "null | typeof import('path').posix | typeof import('net')['Socket']['PassThrough']",
markdownType: 'null | PathPosix | NetSocket[\'PassThrough\']'
}
}
})
})

it('correctly parses @typedef tags', () => {
const result = transform(`
export default {
/**
* @typedef {'src' | 'root'} HumanReadable
* @type {HumanReadable}
*/
srcDir: 'src',
}
`)
expectCodeToMatch(result, /export default ([\s\S]*)$/, {
Expand All @@ -193,7 +228,8 @@ describe('transform (jsdoc)', () => {
$schema: {
title: '',
description: '',
type: "'src' | 'root'"
tsType: "'src' | 'root'",
markdownType: 'HumanReadable'
}
}
})
Expand Down
3 changes: 2 additions & 1 deletion test/types.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -66,6 +66,7 @@ interface Untyped {
}, {
name: 'append',
type: 'boolean',
tsType: 'false',
optional: true
}]
}
Expand All @@ -74,7 +75,7 @@ interface Untyped {

expect(types).toBe(`
interface Untyped {
add: (test?: Array<string | number>, append?: boolean) => any,
add: (test?: Array<string | number>, append?: false) => any,
}
`.trim())
})
Expand Down
5 changes: 5 additions & 0 deletions yarn.lock
Original file line number Diff line number Diff line change
Expand Up @@ -4482,6 +4482,11 @@ saxes@^5.0.1:
dependencies:
xmlchars "^2.2.0"

scule@latest:
version "0.2.1"
resolved "https://registry.yarnpkg.com/scule/-/scule-0.2.1.tgz#0c1dc847b18e07219ae9a3832f2f83224e2079dc"
integrity sha512-M9gnWtn3J0W+UhJOHmBxBTwv8mZCan5i1Himp60t6vvZcor0wr+IM0URKmIglsWJ7bRujNAVVN77fp+uZaWoKg==

"semver@2 || 3 || 4 || 5":
version "5.7.1"
resolved "https://registry.yarnpkg.com/semver/-/semver-5.7.1.tgz#a954f931aeba508d307bbf069eff0c01c96116f7"
Expand Down