diff --git a/CHANGELOG.md b/CHANGELOG.md new file mode 100644 index 0000000..312b638 --- /dev/null +++ b/CHANGELOG.md @@ -0,0 +1,49 @@ +## 0.0.8 (2023-02-27) + + +### Bug Fixes + +* 避免原有definitions被覆盖 ([64d2ff6](https://github.com/yunke-yunfly/fast-typescript-to-jsonschema/commit/64d2ff626dbb0b33593b6e0c890a8d1026c155a0)) +* 泛型默认值,进行深度克隆,避免被覆盖 ([ffb5d2d](https://github.com/yunke-yunfly/fast-typescript-to-jsonschema/commit/ffb5d2d2ebe606733fb8031c5b4018eccca67a71)) +* 完善重复引用逻辑 ([136e9b0](https://github.com/yunke-yunfly/fast-typescript-to-jsonschema/commit/136e9b037acb5c4cc3b47f080c3ee61c5e6880b8)) +* 完善重复引用逻辑 ([eed579e](https://github.com/yunke-yunfly/fast-typescript-to-jsonschema/commit/eed579e5f18977e35fc0ad8c5ab9f48bad7f4f16)) +* 重复引用以及 namespace 多层嵌套解析 ([a08d8d9](https://github.com/yunke-yunfly/fast-typescript-to-jsonschema/commit/a08d8d9e8aacef1a5995a23ebaa83dc86c66d415)) +* genJsonschema 方法 entry 增加默认值处理 ([cde668a](https://github.com/yunke-yunfly/fast-typescript-to-jsonschema/commit/cde668a66e53f69166943fbde95e1abe37176ffe)) +* namespace 多层嵌套解析问题 ([78b7b27](https://github.com/yunke-yunfly/fast-typescript-to-jsonschema/commit/78b7b277165ada3bef60af4417b563a169f374cc)) + + +### Features + +* 1. 新增对npm包类型的支持 2.修复非同类型枚举类型结果不准确问题 3.修复枚举类型中key为字符串时深度循环问题 ([1e9bbad](https://github.com/yunke-yunfly/fast-typescript-to-jsonschema/commit/1e9bbadb1635df39e41240978f80e8ccb2e01b06)) +* 1. 新增通过 code 生成 jsonschema ([96770e3](https://github.com/yunke-yunfly/fast-typescript-to-jsonschema/commit/96770e327ad65d8f6e9e0a79182eea946a6bdef5)) +* 更新文档,新增测试案例 ([84a5788](https://github.com/yunke-yunfly/fast-typescript-to-jsonschema/commit/84a5788d9b3593d3df6bd1a011f7590a8fec1794)) +* 更新文档,新增测试案例 ([c480e6c](https://github.com/yunke-yunfly/fast-typescript-to-jsonschema/commit/c480e6cf2e31b2a12bc9101f11cc0171a47f50c8)) +* 解析块级文档支持description参数 ([176adcb](https://github.com/yunke-yunfly/fast-typescript-to-jsonschema/commit/176adcb6fe3e23772f4228cf4a628c49e2489cca)) +* 枚举类型解析问题 ([6467bae](https://github.com/yunke-yunfly/fast-typescript-to-jsonschema/commit/6467bae084d9b237c1be516d12b8f6938eecaf83)) +* 默认文档切换为英文文档 ([df98316](https://github.com/yunke-yunfly/fast-typescript-to-jsonschema/commit/df98316506277468909d8c44b2f8473db3cab13c)) +* 删除额外属性,处理type为数组情况,完善逻辑 ([265ad1e](https://github.com/yunke-yunfly/fast-typescript-to-jsonschema/commit/265ad1e029d96c5ae16257e35e5f68bf54aca6d1)) +* 完善additionalProperties处理,补充测试用例 ([1e3fe87](https://github.com/yunke-yunfly/fast-typescript-to-jsonschema/commit/1e3fe873462b927eb500f6e74ae47dac8c32a67e)) +* 文档优化 ([3591789](https://github.com/yunke-yunfly/fast-typescript-to-jsonschema/commit/359178929e255e6f9bef2b9989acc3ecdc1275fb)) +* 新增测试覆盖率标识 ([c94dca2](https://github.com/yunke-yunfly/fast-typescript-to-jsonschema/commit/c94dca2ed57ed2692d714dfa4bc8d9b403e18e6c)) +* 新增测试覆盖率标识 ([56daa19](https://github.com/yunke-yunfly/fast-typescript-to-jsonschema/commit/56daa19e2deffb8c1f95d6097e104a6d6efbc971)) +* 新增测试覆盖率标识 ([96b1a17](https://github.com/yunke-yunfly/fast-typescript-to-jsonschema/commit/96b1a17682b5bfda68c88301ced8096a520b987c)) +* 新增测试覆盖率标识 ([1ad1c11](https://github.com/yunke-yunfly/fast-typescript-to-jsonschema/commit/1ad1c112d5391319828a553cbf82600526804958)) +* 新增测试覆盖率标识 ([4fb6beb](https://github.com/yunke-yunfly/fast-typescript-to-jsonschema/commit/4fb6bebe1f6af10c56bb6f4169ca3f900f11b7d9)) +* 新增测试覆盖率标识 ([cca0f42](https://github.com/yunke-yunfly/fast-typescript-to-jsonschema/commit/cca0f420d53507ff4e52302e2a8471401e3f88e4)) +* 修复包名 ([0813a33](https://github.com/yunke-yunfly/fast-typescript-to-jsonschema/commit/0813a33085589e0aeb547836fbde371785409aca)) +* 修复repository链接 ([24eea13](https://github.com/yunke-yunfly/fast-typescript-to-jsonschema/commit/24eea136c8b58ef9148b00cf0adf0b8507496ea5)) +* 增加本文件查找引用类型,删除枚举类型时的空definitions ([a7fc272](https://github.com/yunke-yunfly/fast-typescript-to-jsonschema/commit/a7fc2721988e50a653e2cfa12f09c10cde4cb59d)) +* 增加Partial、Required对联合类型的处理 ([a1c661b](https://github.com/yunke-yunfly/fast-typescript-to-jsonschema/commit/a1c661b62b0f5f78136abc5eb4a41ef035df3207)) +* 增加Pick/Omit对type的支持 ([46f2a9e](https://github.com/yunke-yunfly/fast-typescript-to-jsonschema/commit/46f2a9e220eff2fb2afdc2b6b65fd5371ec2205c)) +* 支持工具函数Partial ([fbe9c68](https://github.com/yunke-yunfly/fast-typescript-to-jsonschema/commit/fbe9c682d9fb8e24a4e2fd3f05f2420c1c898d43)) +* 支持工具函数Required ([486e1ea](https://github.com/yunke-yunfly/fast-typescript-to-jsonschema/commit/486e1eaaf0cd9c691eebbd2de1c72252af6203a4)) +* add codecov_token ([954b209](https://github.com/yunke-yunfly/fast-typescript-to-jsonschema/commit/954b209c3315e88aab95bd8b7678db445e1d5de0)) +* add codecov_token ([900ffda](https://github.com/yunke-yunfly/fast-typescript-to-jsonschema/commit/900ffda089a792691b6b6a5c9b544172117c0e8e)) +* add codecov_token ([22b7069](https://github.com/yunke-yunfly/fast-typescript-to-jsonschema/commit/22b7069acb674185bf0994ce8e680b3ad786d134)) +* add English docs ([0926ac6](https://github.com/yunke-yunfly/fast-typescript-to-jsonschema/commit/0926ac62a84ac035a1569efdfebc61d66c673ca8)) +* add license ([1f3fce9](https://github.com/yunke-yunfly/fast-typescript-to-jsonschema/commit/1f3fce925597fa8f93acf4b5f89a15b7139fe87f)) +* enable sourcemap ([882be37](https://github.com/yunke-yunfly/fast-typescript-to-jsonschema/commit/882be37152ff71296c007fe4a1ed6f65c4c3f0c6)) +* typescript-to-jsonschema first version ([15632cc](https://github.com/yunke-yunfly/fast-typescript-to-jsonschema/commit/15632cce735e96b037c9b01b64abce6056bcf4f2)) + + + diff --git a/README.md b/README.md index 10a6077..b1d40a5 100644 --- a/README.md +++ b/README.md @@ -1,6 +1,6 @@ # fast-typescript-to-jsonschema -[![npm version](https://img.shields.io/npm/v/fast-typescript-to-jsonschema.svg)](https://www.npmjs.com/package/fast-typescript-to-jsonschema) +[![npm version](https://img.shields.io/npm/v/fast-typescript-to-jsonschema.svg)](https://www.npmjs.com/package/fast-typescript-to-jsonschema) ![Test](https://github.com/yunke-yunfly/fast-typescript-to-jsonschema/workflows/Test/badge.svg) [![codecov](https://codecov.io/gh/yunke-yunfly/fast-typescript-to-jsonschema/branch/master/graph/badge.svg)](https://app.codecov.io/gh/yunke-yunfly/fast-typescript-to-jsonschema) @@ -33,6 +33,8 @@ interface ITest { 3. create `test.js` +3.1. gen jsonschema from file. + ```js const { default: genTypeSchema } = require('fast-typescript-to-jsonschema'); const path = require('path'); @@ -53,6 +55,31 @@ const jsonSchema = genTypeSchema.getJsonSchema(file, 'ITest'); console.log(jsonSchema); ``` +3.2. gen jsonschema from code. + +```js +const { default: genTypeSchema } = require('fast-typescript-to-jsonschema'); + +const code = ` +interface ITest { + attr1: string; + attr2: number; + attr3?: boolean; +} +` +// generate data +genTypeSchema.genJsonDataFromCode(code); + +// get all jsonschema data of current file +const json = genTypeSchema.genJsonData(); + +// get jsonschema of specific type +const jsonSchema = genTypeSchema.getJsonSchema('ITest'); + +// result +console.log(jsonSchema); +``` + 4. execute script ```js @@ -161,7 +188,7 @@ result: - [1.2 Named Export Modules](docs/module.en-US.md#12-named-export-modules) - [Extending Types](docs/extends.en-US.md#extending-types) - [1.1 Basic Extending Types](docs/extends.en-US.md#11-basic-extending-types) - - [1.2 Multiple Extending Types ](docs/extends.en-US.md#12-multiple-extending-types) + - [1.2 Multiple Extending Types](docs/extends.en-US.md#12-multiple-extending-types) - [Enums](docs/enum.en-US.md#enums) - [1.1 Numeric Enums](docs/enum.en-US.md#11-numeric-enums) - [1.2 String Enums](docs/enum.en-US.md#12-string-enums) diff --git a/README.zh-cn.md b/README.zh-cn.md index 8a89634..597d700 100644 --- a/README.zh-cn.md +++ b/README.zh-cn.md @@ -1,6 +1,6 @@ # fast-typescript-to-jsonschema -[![npm version](https://img.shields.io/npm/v/fast-typescript-to-jsonschema.svg)](https://www.npmjs.com/package/fast-typescript-to-jsonschema) +[![npm version](https://img.shields.io/npm/v/fast-typescript-to-jsonschema.svg)](https://www.npmjs.com/package/fast-typescript-to-jsonschema) ![Test](https://github.com/yunke-yunfly/fast-typescript-to-jsonschema/workflows/Test/badge.svg) [![codecov](https://codecov.io/gh/yunke-yunfly/fast-typescript-to-jsonschema/branch/master/graph/badge.svg)](https://app.codecov.io/gh/yunke-yunfly/fast-typescript-to-jsonschema) @@ -31,7 +31,9 @@ interface ITest { } ``` -3.创建`test.js`文件,内容如下: +3. 创建`test.js`文件,内容如下: + +3.1 通过文件生成 jsonschema ```js const { default: genTypeSchema } = require('fast-typescript-to-jsonschema'); @@ -53,6 +55,31 @@ const jsonSchema = genTypeSchema.getJsonSchema(file, 'ITest'); console.log(jsonSchema); ``` +3.2 通过 code 生成 jsonschema + +```js +const { default: genTypeSchema } = require('fast-typescript-to-jsonschema'); + +const code = ` +interface ITest { + attr1: string; + attr2: number; + attr3?: boolean; +} +` +// generate data +genTypeSchema.genJsonDataFromCode(code); + +// get all jsonschema data of current file +const json = genTypeSchema.genJsonData(); + +// get jsonschema of specific type +const jsonSchema = genTypeSchema.getJsonSchema('ITest'); + +// result +console.log(jsonSchema); +``` + 4.执行脚本 ```js @@ -84,7 +111,7 @@ node ./test.js ``` - example 案例地址: -https://github.com/yunke-yunfly/fast-typescript-to-jsonschema/tree/master/example + ## 注释 @@ -141,7 +168,6 @@ interface Interface_4 { } ``` - > 更多支持的类型解析[请看](docs/index.md),目录如下: - [接口](docs/interface.md) diff --git a/package.json b/package.json index 0c919d7..a344615 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "fast-typescript-to-jsonschema", - "version": "0.0.7", + "version": "0.0.8", "description": "fast-typescript-to-jsonschema generates JSON Schema files from your Typescript sources.", "main": "./dist/index.js", "typings": "dist/index.d.ts", diff --git a/src/__tests__/__snapshots__/code.test.ts.snap b/src/__tests__/__snapshots__/code.test.ts.snap new file mode 100644 index 0000000..59bf8d7 --- /dev/null +++ b/src/__tests__/__snapshots__/code.test.ts.snap @@ -0,0 +1,121 @@ +// Jest Snapshot v1, https://goo.gl/fbAQLP + +exports[`Type类型 1`] = ` +Object { + "anyOf": Array [ + Object { + "type": "string", + }, + Object { + "enum": Object { + "enum": Array [ + "home", + "about", + "contact", + ], + }, + "type": "string", + }, + ], +} +`; + +exports[`嵌套接口 1`] = ` +Object { + "additionalProperties": false, + "definitions": Object { + "BBB": Object { + "additionalProperties": false, + "properties": Object { + "some": Object { + "type": "string", + }, + }, + "required": Array [ + "some", + ], + "type": "object", + }, + }, + "properties": Object { + "some": Object { + "$ref": "#/definitions/BBB", + }, + "title": Object { + "type": "string", + }, + }, + "required": Array [ + "title", + "some", + ], + "type": "object", +} +`; + +exports[`嵌套泛型 1`] = ` +Object { + "additionalProperties": false, + "definitions": Object {}, + "properties": Object { + "value1": Object { + "type": "string", + }, + "value2": Object { + "type": "string", + }, + }, + "required": Array [ + "value1", + "value2", + ], + "type": "object", +} +`; + +exports[`枚举 1`] = ` +Object { + "enum": Array [ + "Maintainer", + "Developer", + ], + "type": "string", +} +`; + +exports[`泛型 1`] = ` +Object { + "additionalProperties": false, + "definitions": Object { + "T": Object {}, + }, + "properties": Object { + "value1": Object { + "type": "string", + }, + "value2": Object { + "$ref": "#/definitions/T", + }, + }, + "required": Array [ + "value1", + "value2", + ], + "type": "object", +} +`; + +exports[`简单接口 1`] = ` +Object { + "additionalProperties": false, + "properties": Object { + "some": Object { + "type": "string", + }, + }, + "required": Array [ + "some", + ], + "type": "object", +} +`; diff --git a/src/__tests__/__snapshots__/generic.test.ts.snap b/src/__tests__/__snapshots__/generic.test.ts.snap index 5df3711..25c61e7 100644 --- a/src/__tests__/__snapshots__/generic.test.ts.snap +++ b/src/__tests__/__snapshots__/generic.test.ts.snap @@ -34,6 +34,76 @@ Object { } `; +exports[`Generic多层对象_类型_2 1`] = ` +Object { + "additionalProperties": false, + "definitions": Object { + "Generic_8": Object { + "additionalProperties": false, + "properties": Object { + "value1": Object { + "additionalProperties": false, + "properties": Object { + "value2": Object { + "additionalProperties": false, + "properties": Object { + "value3": Object { + "type": "string", + }, + }, + "required": Array [ + "value3", + ], + "type": "object", + }, + }, + "required": Array [ + "value2", + ], + "type": "object", + }, + }, + "required": Array [ + "value1", + ], + "type": "object", + }, + }, + "properties": Object { + "value": Object { + "items": Object { + "$realRef": "Generic_8", + "$ref": "#/definitions/Generic_8", + }, + "type": "array", + }, + }, + "required": Array [ + "value", + ], + "type": "object", +} +`; + +exports[`Generic多层对象_类型_3 1`] = ` +Object { + "additionalProperties": false, + "definitions": Object {}, + "properties": Object { + "value": Object { + "items": Object { + "type": "string", + }, + "type": "array", + }, + }, + "required": Array [ + "value", + ], + "type": "object", +} +`; + exports[`Generic引用别的文件_类型_1 1`] = ` Object { "additionalProperties": false, @@ -186,6 +256,28 @@ Object { } `; +exports[`Generic类型_3 1`] = ` +Object { + "additionalProperties": false, + "definitions": Object { + "T": Object {}, + }, + "properties": Object { + "value1": Object { + "type": "string", + }, + "value2": Object { + "$ref": "#/definitions/T", + }, + }, + "required": Array [ + "value1", + "value2", + ], + "type": "object", +} +`; + exports[`Generic默认值_类型_1 1`] = ` Object { "additionalProperties": false, diff --git a/src/__tests__/code.test.ts b/src/__tests__/code.test.ts new file mode 100644 index 0000000..86bb305 --- /dev/null +++ b/src/__tests__/code.test.ts @@ -0,0 +1,53 @@ +import genTypeSchema from '../index'; + +const code = ` +import AAA from './aaa' +export type Generic_10 = Generic_type_1 +export interface Generic_type_1 { + value1: string; + value2: T; +} +interface BBB { + some: string; +} +export enum Role { + Maintainer = 'Maintainer', + Developer = 'Developer', +} +type Page = 'home' | 'about' | 'contact' | string; +interface PageInfo { + title: string; + some: BBB +} +` +genTypeSchema.genJsonDataFromCode(code); + +const getSchema = (type: string) => { + const schema = genTypeSchema.getJsonSchema(type); + return schema; +}; + +test('枚举', () => { + expect(getSchema('Role')).toMatchSnapshot(); +}); + +test('Type类型', () => { + expect(getSchema('Page')).toMatchSnapshot(); +}); + +test('简单接口', () => { + expect(getSchema('BBB')).toMatchSnapshot(); +}); + +test('嵌套接口', () => { + expect(getSchema('PageInfo')).toMatchSnapshot(); +}); + +test('泛型', () => { + expect(getSchema('Generic_type_1')).toMatchSnapshot(); +}); + +test('嵌套泛型', () => { + expect(getSchema('Generic_10')).toMatchSnapshot(); +}); + diff --git a/src/__tests__/generic.test.ts b/src/__tests__/generic.test.ts index 44797f5..4ba1b3e 100644 --- a/src/__tests__/generic.test.ts +++ b/src/__tests__/generic.test.ts @@ -22,6 +22,10 @@ test('Generic类型_2', () => { expect(getSchema('Generic_5')).toMatchSnapshot(); }); +test('Generic类型_3', () => { + expect(getSchema('Generic_type_1')).toMatchSnapshot(); +}); + test('Generic默认值_类型_1', () => { expect(getSchema('Generic_7')).toMatchSnapshot(); }); @@ -38,6 +42,15 @@ test('Generic多层对象_类型_1', () => { expect(getSchema('Generic_9')).toMatchSnapshot(); }); +test('Generic多层对象_类型_2', () => { + expect(getSchema('Generic_11')).toMatchSnapshot(); +}); + +test('Generic多层对象_类型_3', () => { + expect(getSchema('Generic_13')).toMatchSnapshot(); +}); + test('Generic引用别的文件_类型_1', () => { expect(getSchema('Generic_10')).toMatchSnapshot(); -}); \ No newline at end of file +}); + diff --git a/src/get-jsonschema-from-data.ts b/src/get-jsonschema-from-data.ts index d5b1cc4..bf85f31 100644 --- a/src/get-jsonschema-from-data.ts +++ b/src/get-jsonschema-from-data.ts @@ -32,12 +32,20 @@ export default class genTypeSchema extends typescriptToFileDatas { */ getJsonSchema( file: string, - type: string, + type?: string, entry?: { keySet: Set; refKeyTime: Record }, + isLast?: boolean ): AnyOption { if (!entry) { entry = { keySet: new Set(), refKeyTime: {} }; } + + // 支持输入的是 code 场景 + if (file && !type) { + type = file; + file = 'index.ts'; + } + if (!file || !type) return { type: 'object' }; // 处理 Param.C.D.E.F.GetBaseDetailResponse 这种外部导入路径 @@ -60,8 +68,13 @@ export default class genTypeSchema extends typescriptToFileDatas { refFile, typeJson.from ? type.replace(/.+?(?=\.)|.+/, typeJson.from) : type, entry, + true, ); + if (!isLast && typeJson.typeParams) { + delete typeJson.typeParams + } + return typeJson; } } @@ -85,6 +98,11 @@ export default class genTypeSchema extends typescriptToFileDatas { } typeJson.definitions[type] = cloneTypeJson; } + + if (!isLast && typeJson.typeParams) { + delete typeJson.typeParams + } + return typeJson; } @@ -200,7 +218,7 @@ export default class genTypeSchema extends typescriptToFileDatas { // 别的文件ref if (realRef.$ref && realRef.type !== ImportType.ImportNamespaceSpecifier) { const refFile = realRef.$ref.replace(/#\/definitions|#/, ''); - const realSchema = this.getJsonSchema(refFile, result.$realRef); + const realSchema = this.getJsonSchema(refFile, result.$realRef, undefined, true); delete realRef.$ref; delete realRef.from; Object.assign(realRef, realSchema); @@ -280,10 +298,10 @@ export default class genTypeSchema extends typescriptToFileDatas { // 处理继承 const handleExtends = (item: AnyOption) => { - const newTypeJson = this.getJsonSchema(file as string, item.extends, entry); + const newTypeJson = this.getJsonSchema(file as string, item.extends, entry, true); if (newTypeJson) { const result = newTypeJson.$ref - ? this.getJsonSchema(newTypeJson.$ref.replace(/#/g, ''), item.extends, entry) + ? this.getJsonSchema(newTypeJson.$ref.replace(/#/g, ''), item.extends, entry, true) : this.genJsonschema(fileJson, newTypeJson, entry); if (typeof result === 'object') { item = merge(result, item, { @@ -358,6 +376,7 @@ export default class genTypeSchema extends typescriptToFileDatas { $dependRefKey, $refJson.from ? $refKey.replace(/.+?(?=\.)|.+/, $refJson.from) : $refKey, entry, + true ); handle && handleCommonRef(result, $refKey); return result; @@ -650,6 +669,11 @@ export default class genTypeSchema extends typescriptToFileDatas { // anyOf|allOf allOfAnyOfHandle(typeJson); + // 处理泛型 + if (typeJson.typeParams && Object.keys(typeJson.typeParams).length) { + handleGenericDefaultType(typeJson.properties, typeJson.typeParams); + } + // 数组类型 if (typeJson.type === 'array') { commonArrayHandle(typeJson); @@ -660,7 +684,6 @@ export default class genTypeSchema extends typescriptToFileDatas { typeJson = handleExtends(typeJson); } - // 对象类型 if (typeJson.properties && Object.keys(typeJson.properties)) { // eslint-disable-next-line guard-for-in diff --git a/src/typescript-to-file-datas.ts b/src/typescript-to-file-datas.ts index d6338a1..4b523f7 100644 --- a/src/typescript-to-file-datas.ts +++ b/src/typescript-to-file-datas.ts @@ -7,7 +7,7 @@ import * as fs from 'fs'; // types import type { AnyOption, TSTypeAnnotationConfig, TypeAnnotationConfig } from './types'; // utils -import { genAst } from './utils'; +import { genAst, genAstFromCode } from './utils'; // require const chalk = require('chalk'); const doctrine = require('doctrine'); @@ -142,6 +142,13 @@ export default class typescriptToFileDatas { return { filePath: file, fileType: 'npm' }; } + /** + * 查找npm包types + * + * @param {{ sourceValue: string }} { sourceValue } + * @return {*} + * @memberof typescriptToFileDatas + */ getTypeFileFromNpm({ sourceValue }: { sourceValue: string }) { // 1. 优先查找 index.d.ts 其次查找 ${sourceValue}.d.ts const sourceValueArr = sourceValue.split('/'); @@ -191,6 +198,13 @@ export default class typescriptToFileDatas { return source } + /** + * 查找文件 import types + * + * @param {{ dir: string; sourceValue: string; ext: string }} { dir, sourceValue, ext } + * @return {*} + * @memberof typescriptToFileDatas + */ getTypeFileFromImport({ dir, sourceValue, ext }: { dir: string; sourceValue: string; ext: string }) { let source = ''; // 找依赖的文件,优先级 .ts >> .d.ts >> /index.ts >> /index.d.ts @@ -502,6 +516,19 @@ export default class typescriptToFileDatas { return { data: result, file }; } + /** + * 通过代码获得解析数据 + * + * @param {string} code + * @return {*} {AnyOption} + * @memberof typescriptToFileDatas + */ + genJsonDataFromCode(code: string): AnyOption { + // ast + const ast_ = genAstFromCode(code); + return this.genJsonDataFormFile('index.ts', ast_); + } + /** * 只获取代码前注释 支持行内注释与块注释 * diff --git a/src/utils.ts b/src/utils.ts index 62fadb5..797e872 100644 --- a/src/utils.ts +++ b/src/utils.ts @@ -8,6 +8,18 @@ import type { AnyOption } from './types'; type AstType = Node | Node[] | null | undefined; +const parseConfig: AnyOption = { + sourceType: 'unambiguous', + allowImportExportEverywhere: true, + allowAwaitOutsideFunction: true, + allowReturnOutsideFunction: true, + allowSuperOutsideMethod: true, + allowUndeclaredExports: true, + createParenthesizedExpressions: true, + errorRecovery: true, + plugins: ['typescript', 'decorators-legacy'], +}; + /** * 文件生成ast树 ast报错继续解析 * @@ -16,17 +28,6 @@ type AstType = Node | Node[] | null | undefined; */ export function genAst(file: string): AnyOption | null { try { - const parseConfig: AnyOption = { - sourceType: 'unambiguous', - allowImportExportEverywhere: true, - allowAwaitOutsideFunction: true, - allowReturnOutsideFunction: true, - allowSuperOutsideMethod: true, - allowUndeclaredExports: true, - createParenthesizedExpressions: true, - errorRecovery: true, - plugins: ['typescript', 'decorators-legacy'], - }; const fileContent = fs.readFileSync(file).toString(); const ast: AstType = parse(fileContent, parseConfig); return ast; @@ -35,6 +36,22 @@ export function genAst(file: string): AnyOption | null { } } +/** + * 代码生成ast树 ast报错继续解析 + * + * @export + * @param {string} code + * @return {*} {(AnyOption | null)} + */ +export function genAstFromCode(code: string): AnyOption | null { + try { + const ast: AstType = parse(code, parseConfig); + return ast; + } catch (err) { + return null; + } +} + /** * 生成随机字符串 *